From 8bf490cbbcd2790422f8c489b6c855cb43db17ad Mon Sep 17 00:00:00 2001 From: LiJianying Date: Thu, 19 Nov 2026 19:11:44 +0800 Subject: [PATCH] Coalesce Windows move/resize events and add fast paths for zero listeners and message dispatch --- src/foundation/event_emitter.h | 18 + .../windows/window_manager_windows.cpp | 220 ++++++++++- .../windows/window_message_dispatcher.cpp | 343 ++++++++++++------ .../windows/window_message_dispatcher.h | 59 ++- src/platform/windows/window_windows.cpp | 6 +- tests/CMakeLists.txt | 4 + .../window_geometry_coalesce_windows_test.cpp | 213 +++++++++++ 7 files changed, 734 insertions(+), 129 deletions(-) create mode 100644 tests/window_geometry_coalesce_windows_test.cpp diff --git a/src/foundation/event_emitter.h b/src/foundation/event_emitter.h index 1dab7267..ee57e83e 100644 --- a/src/foundation/event_emitter.h +++ b/src/foundation/event_emitter.h @@ -221,6 +221,7 @@ class EventEmitter { // deliver any further events to this listener. (*it)->MarkRemoved(); listeners_.erase(it); + listener_count_.store(listeners_.size(), std::memory_order_relaxed); dispatch_cache_.clear(); removed = true; became_empty = listeners_.empty(); @@ -259,6 +260,7 @@ class EventEmitter { entry->MarkRemoved(); } listeners_.clear(); + listener_count_.store(0, std::memory_order_relaxed); dispatch_cache_.clear(); } @@ -294,6 +296,13 @@ class EventEmitter { return GetListenerCount() > 0; } + /** + * Lock-free check for whether any listener is currently registered. + */ + bool HasAnyListeners() const { + return listener_count_.load(std::memory_order_relaxed) > 0; + } + /** * Emit an event synchronously to all registered listeners. * This is a public method for internal use by platform implementations. @@ -304,6 +313,10 @@ class EventEmitter { * @param event The event to emit */ void Emit(const BaseEventType& event) { + if (!HasAnyListeners()) { + return; + } + std::vector snapshot; { @@ -489,6 +502,7 @@ class EventEmitter { std::lock_guard lock(listeners_mutex_); was_empty = listeners_.empty(); listeners_.push_back(std::move(entry)); + listener_count_.store(listeners_.size(), std::memory_order_relaxed); dispatch_cache_.clear(); } @@ -516,6 +530,7 @@ class EventEmitter { return false; }); listeners_.erase(new_end, listeners_.end()); + listener_count_.store(listeners_.size(), std::memory_order_relaxed); removed_any = listeners_.size() != before; if (removed_any) { @@ -619,6 +634,9 @@ class EventEmitter { // Listener ID generation std::atomic next_listener_id_; + + // Lock-free mirror of listeners_.size() for zero-listener fast paths. + std::atomic listener_count_{0}; }; } // namespace nativeapi diff --git a/src/platform/windows/window_manager_windows.cpp b/src/platform/windows/window_manager_windows.cpp index 23d4ae5d..78722754 100644 --- a/src/platform/windows/window_manager_windows.cpp +++ b/src/platform/windows/window_manager_windows.cpp @@ -152,8 +152,38 @@ struct WindowSnapshot { RECT rect; double scale_factor = 1.0; }; + +// Coalescing state for WindowMovedEvent / WindowResizedEvent per window. +// During interactive edge-drag (WM_ENTERSIZEMOVE..WM_EXITSIZEMOVE) or rapid +// programmatic SetWindowPos bursts, geometry events are coalesced on a low- +// priority WM_TIMER (50 ms) and flushed immediately on WM_EXITSIZEMOVE. +// Single isolated moves/resizes outside a burst emit immediately (0 ms delay). +static constexpr UINT kGeometryCoalesceMs = 50; +static UINT_PTR GeometryTimerId() { + static int tag = 0; + return reinterpret_cast(&tag); +} + +struct PendingGeometry { + bool moved = false; + bool resized = false; + bool timer_armed = false; + bool in_size_move = false; + ULONGLONG last_emit_tick = 0; + WindowSnapshot snapshot = {}; +}; + +// Lock-free mirror of whether any listener exists on WindowManager or any Window. +// When false, WindowGeometryProc short-circuits straight to DefSubclassProc. +static std::atomic g_has_window_listeners{false}; + +static constexpr DWORD kEventGeometryEnterSizeMove = 0xFFFFFF01u; +static constexpr DWORD kEventGeometryExitSizeMove = 0xFFFFFF02u; +static constexpr DWORD kEventGeometryFlushTimer = 0xFFFFFF03u; + static HWINEVENTHOOK g_lifetime_hook = nullptr; static std::unordered_map g_window_snapshots; +static std::unordered_map g_pending_geometry; // Windows seen on screen, which is what WindowCreatedEvent and WindowClosedEvent // are about. The ID is kept because the destroy event is delivered after the // HWND, and the property holding its ID, are gone. @@ -204,8 +234,43 @@ static bool IsReportableWindow(HWND hwnd) { static LRESULT CALLBACK WindowGeometryProc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp, UINT_PTR subclass_id, DWORD_PTR) { if (message == WM_NCDESTROY) { + KillTimer(hwnd, GeometryTimerId()); + WithObserver([&] { g_pending_geometry.erase(hwnd); }); RemoveWindowSubclass(hwnd, WindowGeometryProc, subclass_id); - } else if (message == WM_WINDOWPOSCHANGED || message == WM_DPICHANGED) { + return DefSubclassProc(hwnd, message, wp, lp); + } + if (message == WM_TIMER && wp == GeometryTimerId()) { + KillTimer(hwnd, GeometryTimerId()); + if (g_has_window_listeners.load(std::memory_order_relaxed)) { + WithObserver([&] { + if (g_window_changed_fn && g_window_changed_context) { + g_window_changed_fn(g_window_changed_context, kEventGeometryFlushTimer, hwnd); + } + }); + } + return 0; + } + if (!g_has_window_listeners.load(std::memory_order_relaxed)) { + return DefSubclassProc(hwnd, message, wp, lp); + } + if (message == WM_ENTERSIZEMOVE) { + WithObserver([&] { + if (g_window_changed_fn && g_window_changed_context) { + g_window_changed_fn(g_window_changed_context, kEventGeometryEnterSizeMove, hwnd); + } + }); + return DefSubclassProc(hwnd, message, wp, lp); + } + if (message == WM_EXITSIZEMOVE) { + const LRESULT result = DefSubclassProc(hwnd, message, wp, lp); + WithObserver([&] { + if (g_window_changed_fn && g_window_changed_context) { + g_window_changed_fn(g_window_changed_context, kEventGeometryExitSizeMove, hwnd); + } + }); + return result; + } + if (message == WM_WINDOWPOSCHANGED || message == WM_DPICHANGED) { const LRESULT result = DefSubclassProc(hwnd, message, wp, lp); WithObserver([&] { if (g_window_changed_fn && g_window_changed_context) { @@ -827,12 +892,35 @@ class WindowManager::Impl { g_lifetime_hook = nullptr; } for (const auto& [hwnd, snapshot] : g_window_snapshots) { + KillTimer(hwnd, GeometryTimerId()); UnwatchWindowGeometry(hwnd); } g_window_snapshots.clear(); + g_pending_geometry.clear(); g_shown_windows.clear(); } + static void RefreshTrackedSnapshots() { + WithObserver([] { + for (auto& [hwnd, snapshot] : g_window_snapshots) { + if (IsWindow(hwnd)) { + snapshot = TakeSnapshot(hwnd); + } + } + }); + } + + static void ClearPendingGeometryTimers() { + WithObserver([] { + for (auto& [hwnd, pending] : g_pending_geometry) { + if (pending.timer_armed && IsWindow(hwnd)) { + KillTimer(hwnd, GeometryTimerId()); + } + } + g_pending_geometry.clear(); + }); + } + public: static WindowSnapshot TakeSnapshot(HWND hwnd) { WindowSnapshot snapshot = {}; @@ -843,9 +931,91 @@ class WindowManager::Impl { return snapshot; } + static Size LogicalSizeFromSnapshot(const WindowSnapshot& snapshot) { + const double scale = snapshot.scale_factor > 0.0 ? snapshot.scale_factor : 1.0; + return { + static_cast(snapshot.rect.right - snapshot.rect.left) / scale, + static_cast(snapshot.rect.bottom - snapshot.rect.top) / scale, + }; + } + + static Point LogicalPositionFromSnapshot(const WindowSnapshot& snapshot) { + return PhysicalToLogicalPoint({snapshot.rect.left, snapshot.rect.top}); + } + + void EmitGeometryFromSnapshot(HWND hwnd, + const WindowSnapshot& snapshot, + bool moved, + bool resized) { + if (!moved && !resized) { + return; + } + const WindowId window_id = GetWindowIdFromHwnd(hwnd); + if (window_id == IdAllocator::kInvalidId) { + return; + } + if (moved) { + WindowMovedEvent event(window_id, LogicalPositionFromSnapshot(snapshot)); + manager_->DispatchWindowEvent(event); + } + if (resized) { + WindowResizedEvent event(window_id, LogicalSizeFromSnapshot(snapshot)); + manager_->DispatchWindowEvent(event); + } + } + + void FlushPendingGeometry(HWND hwnd) { + auto pit = g_pending_geometry.find(hwnd); + if (pit == g_pending_geometry.end()) { + return; + } + PendingGeometry& pending = pit->second; + if (pending.timer_armed) { + KillTimer(hwnd, GeometryTimerId()); + pending.timer_armed = false; + } + const bool moved = pending.moved; + const bool resized = pending.resized; + const WindowSnapshot snapshot = pending.snapshot; + pending.moved = false; + pending.resized = false; + if (moved || resized) { + pending.last_emit_tick = GetTickCount64(); + EmitGeometryFromSnapshot(hwnd, snapshot, moved, resized); + } + } + // Compare a window with its last snapshot and emit what changed. void OnWindowChanged(DWORD event, HWND hwnd) { + if (event == kEventGeometryEnterSizeMove) { + g_pending_geometry[hwnd].in_size_move = true; + return; + } + if (event == kEventGeometryExitSizeMove) { + auto pit = g_pending_geometry.find(hwnd); + if (pit != g_pending_geometry.end()) { + pit->second.in_size_move = false; + } + FlushPendingGeometry(hwnd); + ScheduleOcclusionRefresh(); + return; + } + if (event == kEventGeometryFlushTimer) { + auto pit = g_pending_geometry.find(hwnd); + if (pit != g_pending_geometry.end()) { + pit->second.timer_armed = false; + } + FlushPendingGeometry(hwnd); + return; + } if (event == EVENT_OBJECT_DESTROY) { + auto pit = g_pending_geometry.find(hwnd); + if (pit != g_pending_geometry.end()) { + if (pit->second.timer_armed && IsWindow(hwnd)) { + KillTimer(hwnd, GeometryTimerId()); + } + g_pending_geometry.erase(pit); + } g_window_snapshots.erase(hwnd); auto shown = g_shown_windows.find(hwnd); if (shown != g_shown_windows.end()) { @@ -886,6 +1056,15 @@ class WindowManager::Impl { // A minimized window is parked off screen (-32000) and no longer reports // as maximized. Keep the rest of the snapshot, so that restoring it to // where it was is neither a move, a resize nor a second "maximized". + auto pit = g_pending_geometry.find(hwnd); + if (pit != g_pending_geometry.end()) { + if (pit->second.timer_armed) { + KillTimer(hwnd, GeometryTimerId()); + pit->second.timer_armed = false; + } + pit->second.moved = false; + pit->second.resized = false; + } it->second.minimized = true; if (!previous.minimized) { OnWindowEvent(hwnd, "minimized"); @@ -908,15 +1087,37 @@ class WindowManager::Impl { const bool resized = current.rect.right - current.rect.left != previous.rect.right - previous.rect.left || current.rect.bottom - current.rect.top != previous.rect.bottom - previous.rect.top; - if (moved) { - OnWindowEvent(hwnd, "moved"); - } - if (resized) { - OnWindowEvent(hwnd, "resized"); + if (!moved && !resized) { + return; } - if (moved || resized) { + + PendingGeometry& pending = g_pending_geometry[hwnd]; + if (!pending.in_size_move) { ScheduleOcclusionRefresh(); } + const ULONGLONG now = GetTickCount64(); + const ULONGLONG elapsed = now - pending.last_emit_tick; + if (!pending.in_size_move && !pending.timer_armed && elapsed >= kGeometryCoalesceMs) { + pending.last_emit_tick = now; + EmitGeometryFromSnapshot(hwnd, current, moved, resized); + return; + } + + pending.moved |= moved; + pending.resized |= resized; + pending.snapshot = current; + if (!pending.timer_armed) { + const UINT delay = + pending.in_size_move + ? kGeometryCoalesceMs + : (elapsed >= kGeometryCoalesceMs ? kGeometryCoalesceMs + : static_cast(kGeometryCoalesceMs - elapsed)); + if (SetTimer(hwnd, GeometryTimerId(), delay > 0 ? delay : 1, nullptr) != 0) { + pending.timer_armed = true; + } else { + FlushPendingGeometry(hwnd); + } + } } // Translate a foreground change into blurred/focused events. Only windows of @@ -1015,6 +1216,7 @@ WindowManager::WindowManager() : pimpl_(std::make_unique(this)) { WindowManager::~WindowManager() { ShutdownEmitter(); + g_has_window_listeners.store(false, std::memory_order_relaxed); pimpl_->StopEventListening(); } @@ -1327,9 +1529,13 @@ bool WindowManager::CallOriginalHide(WindowId id) { void WindowManager::StartEventListening() { pimpl_->StartEventListening(); pimpl_->SetOcclusionTrackingEnabled(true); + Impl::RefreshTrackedSnapshots(); + g_has_window_listeners.store(true, std::memory_order_relaxed); } void WindowManager::StopEventListening() { + g_has_window_listeners.store(false, std::memory_order_relaxed); + Impl::ClearPendingGeometryTimers(); pimpl_->SetOcclusionTrackingEnabled(false); } diff --git a/src/platform/windows/window_message_dispatcher.cpp b/src/platform/windows/window_message_dispatcher.cpp index 07e355f4..49aa660c 100644 --- a/src/platform/windows/window_message_dispatcher.cpp +++ b/src/platform/windows/window_message_dispatcher.cpp @@ -1,11 +1,30 @@ #include "window_message_dispatcher.h" +#include #include #include +#include #include #include "dpi_utils_windows.h" +#include "ui_thread_windows.h" namespace nativeapi { +namespace { + +UINT_PTR DispatcherSubclassId() { + static int tag = 0; + return reinterpret_cast(&tag); +} + +bool MatchesMessageFilter(const std::vector& messages, UINT msg) { + if (messages.empty()) { + return true; + } + return std::find(messages.begin(), messages.end(), msg) != messages.end(); +} + +} // namespace + WindowMessageDispatcher& WindowMessageDispatcher::GetInstance() { // Use heap allocation to avoid static destruction order issues // The instance is never destroyed to ensure it remains valid during @@ -15,55 +34,109 @@ WindowMessageDispatcher& WindowMessageDispatcher::GetInstance() { } WindowMessageDispatcher::~WindowMessageDispatcher() { - std::lock_guard lock(mutex_); - - // Destroy host window if it exists - if (host_window_) { - DestroyWindow(host_window_); + std::unordered_map> states; + HWND host = nullptr; + { + std::lock_guard lock(mutex_); + host = host_window_; host_window_ = nullptr; + states.swap(window_states_); + handlers_.clear(); + global_handler_ids_.clear(); + global_handler_count_.store(0, std::memory_order_relaxed); } - // Uninstall all hooks before destruction. Over a copy: UninstallHook() erases - // from original_procs_. - const auto hooked = original_procs_; - for (const auto& [hwnd, _] : hooked) { - UninstallHook(hwnd); + for (const auto& [hwnd, state] : states) { + if (hwnd && IsWindow(hwnd)) { + RemoveWindowSubclass(hwnd, SubclassWindowProc, DispatcherSubclassId()); + } + } + if (host && IsWindow(host)) { + DestroyWindow(host); + } +} + +void WindowMessageDispatcher::RebuildWindowMaskLocked(WindowState& state) { + std::array mask{}; + uint32_t wildcards = 0; + for (const int id : state.handler_ids) { + auto it = handlers_.find(id); + if (it == handlers_.end()) { + continue; + } + const auto& msgs = it->second.messages; + if (msgs.empty()) { + ++wildcards; + continue; + } + bool all_in_mask = true; + for (const UINT m : msgs) { + if (m < WindowState::kMaskWords * 64) { + mask[m >> 6] |= (uint64_t{1} << (m & 63)); + } else { + all_in_mask = false; + } + } + if (!all_in_mask) { + ++wildcards; + } + } + for (size_t i = 0; i < WindowState::kMaskWords; ++i) { + state.msg_mask[i].store(mask[i], std::memory_order_relaxed); } - original_procs_.clear(); + state.wildcard_count.store(wildcards, std::memory_order_relaxed); } int WindowMessageDispatcher::RegisterHandler(WindowMessageHandler handler) { std::lock_guard lock(mutex_); int id = next_id_++; - handlers_[id] = {std::move(handler), HWND(0)}; // HWND(0) for global handler + handlers_[id] = {std::move(handler), HWND(0), {}}; // HWND(0) for global handler + global_handler_ids_.insert(global_handler_ids_.begin(), id); + global_handler_count_.store(static_cast(global_handler_ids_.size()), + std::memory_order_relaxed); return id; } int WindowMessageDispatcher::RegisterHandler(HWND hwnd, WindowMessageHandler handler) { - // Check if hook needs to be installed (outside of lock to avoid deadlock) + return RegisterHandler(hwnd, {}, std::move(handler)); +} + +int WindowMessageDispatcher::RegisterHandler(HWND hwnd, + std::initializer_list messages, + WindowMessageHandler handler) { + std::shared_ptr state; bool needs_hook = false; + int id = 0; + { std::lock_guard lock(mutex_); - needs_hook = (original_procs_.find(hwnd) == original_procs_.end()); + id = next_id_++; + handlers_[id] = {std::move(handler), hwnd, std::vector(messages)}; + + auto it = window_states_.find(hwnd); + if (it == window_states_.end()) { + state = std::make_shared(); + window_states_[hwnd] = state; + needs_hook = true; + } else { + state = it->second; + } + // Keep handler_ids sorted descending by ID (most recently registered first). + state->handler_ids.insert(state->handler_ids.begin(), id); + RebuildWindowMaskLocked(*state); } - // Install hook if needed (outside of lock) if (needs_hook) { - InstallHook(hwnd); + EnsureHookInstalled(hwnd, state); } - // Register the handler (inside lock) - std::lock_guard lock(mutex_); - int id = next_id_++; - handlers_[id] = {std::move(handler), hwnd}; - return id; } bool WindowMessageDispatcher::UnregisterHandler(int id) { HWND target_hwnd = HWND(0); - bool should_uninstall = false; + std::shared_ptr state_to_uninstall; { std::lock_guard lock(mutex_); @@ -76,67 +149,80 @@ bool WindowMessageDispatcher::UnregisterHandler(int id) { target_hwnd = it->second.target_hwnd; handlers_.erase(it); - // Check if this was the last handler for this window - if (target_hwnd != HWND(0)) { - bool has_other_handlers = std::any_of( - handlers_.begin(), handlers_.end(), - [target_hwnd](const auto& pair) { return pair.second.target_hwnd == target_hwnd; }); - - should_uninstall = !has_other_handlers; + if (target_hwnd == HWND(0)) { + auto git = std::find(global_handler_ids_.begin(), global_handler_ids_.end(), id); + if (git != global_handler_ids_.end()) { + global_handler_ids_.erase(git); + } + global_handler_count_.store(static_cast(global_handler_ids_.size()), + std::memory_order_relaxed); + } else { + auto sit = window_states_.find(target_hwnd); + if (sit != window_states_.end()) { + auto& ids = sit->second->handler_ids; + auto id_it = std::find(ids.begin(), ids.end(), id); + if (id_it != ids.end()) { + ids.erase(id_it); + } + RebuildWindowMaskLocked(*sit->second); + if (ids.empty()) { + state_to_uninstall = sit->second; + } + } } } - // Uninstall hook if needed (outside of lock to avoid deadlock) - if (should_uninstall) { - UninstallHook(target_hwnd); + if (state_to_uninstall) { + ScheduleHookUninstall(target_hwnd, state_to_uninstall); } return true; } -LRESULT CALLBACK WindowMessageDispatcher::DispatchWindowProc(HWND hwnd, +LRESULT CALLBACK WindowMessageDispatcher::SubclassWindowProc(HWND hwnd, UINT msg, WPARAM wparam, - LPARAM lparam) { + LPARAM lparam, + UINT_PTR subclass_id, + DWORD_PTR ref_data) { auto& dispatcher = GetInstance(); + auto* state = reinterpret_cast(ref_data); + + const bool has_global = dispatcher.global_handler_count_.load(std::memory_order_relaxed) > 0; + const bool has_window_match = + state != nullptr && + (state->wildcard_count.load(std::memory_order_relaxed) > 0 || + (msg < WindowState::kMaskWords * 64 && + (state->msg_mask[msg >> 6].load(std::memory_order_relaxed) & + (uint64_t{1} << (msg & 63))) != 0)); + + // Fast path: no global handler and no per-window handler cares about `msg`. + if (msg != WM_NCDESTROY && !has_global && !has_window_match) { + return DefSubclassProc(hwnd, msg, wparam, lparam); + } - // Take the original window procedure and the handler IDs while holding the - // lock. Only the IDs: a handler may destroy the object another handler - // belongs to -- a Menu freed from a MenuOpenedEvent listener, say, while this - // very message is being dispatched -- so each handler is read back under the - // lock immediately before it is called. Calling a copy taken up front would - // reach into freed memory from inside a window procedure, which Windows turns - // into an immediate process kill (STATUS_FATAL_USER_CALLBACK_EXCEPTION). - WNDPROC original_proc = nullptr; + // Slow path: snapshot candidate handler IDs (already sorted descending by ID). + // Only the IDs are snapshotted: a handler may destroy the object another + // handler belongs to while this message is being dispatched, so each handler + // is read back under the lock immediately before it is invoked. std::vector ids; - - { + if (has_global || has_window_match) { std::lock_guard lock(dispatcher.mutex_); - - // Get original window procedure - auto proc_it = dispatcher.original_procs_.find(hwnd); - if (proc_it == dispatcher.original_procs_.end()) { - return DefWindowProc(hwnd, msg, wparam, lparam); - } - - original_proc = proc_it->second; - - ids.reserve(dispatcher.handlers_.size()); - for (const auto& [id, entry] : dispatcher.handlers_) { - if (entry.target_hwnd == HWND(0) || entry.target_hwnd == hwnd) { - ids.push_back(id); + if (!has_global) { + if (state) { + ids = state->handler_ids; } + } else if (!state || state->handler_ids.empty()) { + ids = dispatcher.global_handler_ids_; + } else { + ids.reserve(state->handler_ids.size() + dispatcher.global_handler_ids_.size()); + std::merge(state->handler_ids.begin(), state->handler_ids.end(), + dispatcher.global_handler_ids_.begin(), dispatcher.global_handler_ids_.end(), + std::back_inserter(ids), std::greater()); } } - // Most recently registered first: IDs grow with each registration, and - // handlers_ is unordered. - std::sort(ids.begin(), ids.end(), std::greater()); - - // Call the handlers without holding the mutex, so they may register, remove - // or emit freely. A handler unregistered since the snapshot is skipped. - // (A handler removed from another thread between the lookup and the call can - // still be reached; handlers are expected to live on the UI thread.) + std::optional handled_result; for (const int id : ids) { WindowMessageHandler handler; { @@ -148,64 +234,111 @@ LRESULT CALLBACK WindowMessageDispatcher::DispatchWindowProc(HWND hwnd, if (entry->second.target_hwnd != HWND(0) && entry->second.target_hwnd != hwnd) { continue; } + if (!MatchesMessageFilter(entry->second.messages, msg)) { + continue; + } handler = entry->second.handler; } auto result = handler(hwnd, msg, wparam, lparam); if (result.has_value()) { - return result.value(); + handled_result = result; + break; } } - // No handler consumed the message, call original procedure - return CallWindowProc(original_proc, hwnd, msg, wparam, lparam); -} - -bool WindowMessageDispatcher::InstallHook(HWND hwnd) { - if (!hwnd || !IsWindow(hwnd)) { - return false; - } - - // Get current window procedure - WNDPROC current_proc = reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_WNDPROC)); - if (!current_proc) { - return false; + if (msg == WM_NCDESTROY) { + RemoveWindowSubclass(hwnd, SubclassWindowProc, subclass_id); + std::lock_guard lock(dispatcher.mutex_); + auto sit = dispatcher.window_states_.find(hwnd); + if (sit != dispatcher.window_states_.end() && sit->second.get() == state) { + dispatcher.window_states_.erase(sit); + } } - // If the window already has DispatchWindowProc, don't install it again - if (current_proc == DispatchWindowProc) { - return true; // Already installed + if (handled_result.has_value()) { + return handled_result.value(); } + return DefSubclassProc(hwnd, msg, wparam, lparam); +} - // Store original procedure - original_procs_[hwnd] = current_proc; - - // Install our dispatcher as the new window procedure - SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast(DispatchWindowProc)); - - return true; +LRESULT CALLBACK WindowMessageDispatcher::DispatchWindowProc(HWND hwnd, + UINT msg, + WPARAM wparam, + LPARAM lparam) { + return DefWindowProcW(hwnd, msg, wparam, lparam); } -void WindowMessageDispatcher::UninstallHook(HWND hwnd) { - auto it = original_procs_.find(hwnd); - if (it == original_procs_.end()) { +void WindowMessageDispatcher::EnsureHookInstalled(HWND hwnd, + const std::shared_ptr& state) { + if (!hwnd || !IsWindow(hwnd)) { return; } - - // The host window keeps DispatchWindowProc for its whole life, so it also - // keeps its entry here. Dropping it would make the window deaf for good: - // DispatchWindowProc bails out early on a window it cannot find, and - // InstallHook() would not add it back, since the procedure it sees installed - // is already ours. That is what happened once every menu had been destroyed. - if (hwnd == host_window_) { + const DWORD thread = GetWindowThreadProcessId(hwnd, nullptr); + if (!thread) { return; } + auto install = [this, hwnd, state]() { + if (!IsWindow(hwnd)) { + return; + } + { + std::lock_guard lock(mutex_); + auto sit = window_states_.find(hwnd); + if (sit == window_states_.end() || sit->second != state) { + return; + } + } + SetWindowSubclass(hwnd, SubclassWindowProc, DispatcherSubclassId(), + reinterpret_cast(state.get())); + }; + if (thread == GetCurrentThreadId()) { + install(); + } else { + detail::PostToThread(thread, std::move(install)); + } +} - // Restore original window procedure - SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast(it->second)); +void WindowMessageDispatcher::ScheduleHookUninstall(HWND hwnd, + const std::shared_ptr& state) { + if (!hwnd) { + return; + } + auto uninstall = [this, hwnd, state]() { + bool should_remove = false; + { + std::lock_guard lock(mutex_); + auto sit = window_states_.find(hwnd); + if (sit != window_states_.end() && sit->second == state && state->handler_ids.empty()) { + should_remove = true; + } + } + if (!should_remove) { + return; + } + if (IsWindow(hwnd)) { + RemoveWindowSubclass(hwnd, SubclassWindowProc, DispatcherSubclassId()); + } + // Re-check under the lock before erasing, in case a handler was added + // while RemoveWindowSubclass was running, and keep `state` alive until + // after RemoveWindowSubclass has returned on the window's thread. + std::lock_guard lock(mutex_); + auto sit = window_states_.find(hwnd); + if (sit != window_states_.end() && sit->second == state && state->handler_ids.empty()) { + window_states_.erase(sit); + } + }; - // Remove from our tracking - original_procs_.erase(it); + const DWORD thread = IsWindow(hwnd) ? GetWindowThreadProcessId(hwnd, nullptr) : 0; + if (thread == 0 || thread == GetCurrentThreadId()) { + uninstall(); + } else if (!detail::PostToThread(thread, uninstall)) { + std::lock_guard lock(mutex_); + auto sit = window_states_.find(hwnd); + if (sit != window_states_.end() && sit->second == state && state->handler_ids.empty()) { + window_states_.erase(sit); + } + } } HWND WindowMessageDispatcher::GetHostWindow() { @@ -220,7 +353,7 @@ HWND WindowMessageDispatcher::GetHostWindow() { static const wchar_t* class_name = L"NativeApiHostWindow"; WNDCLASSW wc = {}; - wc.lpfnWndProc = DispatchWindowProc; // Use dispatcher for host window + wc.lpfnWndProc = DefWindowProcW; wc.hInstance = GetModuleHandle(nullptr); wc.lpszClassName = class_name; @@ -261,9 +394,7 @@ HWND WindowMessageDispatcher::GetHostWindow() { return host_window_; } - // Register the host window in original_procs_ with DefWindowProc as fallback host_window_ = new_host_window; - original_procs_[host_window_] = DefWindowProcW; } return host_window_; diff --git a/src/platform/windows/window_message_dispatcher.h b/src/platform/windows/window_message_dispatcher.h index 58b1eb56..4c67edcc 100644 --- a/src/platform/windows/window_message_dispatcher.h +++ b/src/platform/windows/window_message_dispatcher.h @@ -1,10 +1,16 @@ #pragma once #include +#include +#include +#include #include +#include +#include #include #include #include +#include namespace nativeapi { @@ -90,6 +96,21 @@ class WindowMessageDispatcher { */ int RegisterHandler(HWND hwnd, WindowMessageHandler handler); + /** + * @brief Register a message handler for a specific window and subset of messages. + * + * Messages not listed in @p messages bypass mutex locking, handler lookup, + * and allocation in the subclass procedure via a lock-free bitmask. + * + * @param hwnd Target window handle + * @param messages Win32 message IDs this handler cares about (empty = all) + * @param handler Function to call for matching Windows messages + * @return int Handler ID for unregistration + */ + int RegisterHandler(HWND hwnd, + std::initializer_list messages, + WindowMessageHandler handler); + /** * @brief Unregister a message handler by ID. * @@ -134,29 +155,41 @@ class WindowMessageDispatcher { struct HandlerEntry { WindowMessageHandler handler; ///< The handler function HWND target_hwnd; ///< Target window (HWND(0) for global handlers) + std::vector messages; ///< Empty = all messages; otherwise filter list }; /** - * @brief Install message hook for a window. - * - * @param hwnd Window handle to hook - * @return bool true if hook was installed successfully + * @brief Per-window dispatch state passed directly as SetWindowSubclass dwRefData. */ - bool InstallHook(HWND hwnd); + struct WindowState { + static constexpr size_t kMaskWords = 16; // Covers standard messages 0..1023. + std::array, kMaskWords> msg_mask{}; + std::atomic wildcard_count{0}; + // Protected by WindowMessageDispatcher::mutex_, kept sorted descending by ID. + std::vector handler_ids; + }; - /** - * @brief Uninstall message hook for a window. - * - * @param hwnd Window handle to unhook - */ - void UninstallHook(HWND hwnd); + static LRESULT CALLBACK SubclassWindowProc(HWND hwnd, + UINT msg, + WPARAM wparam, + LPARAM lparam, + UINT_PTR subclass_id, + DWORD_PTR ref_data); + + void RebuildWindowMaskLocked(WindowState& state); + void EnsureHookInstalled(HWND hwnd, const std::shared_ptr& state); + void ScheduleHookUninstall(HWND hwnd, const std::shared_ptr& state); ///< Mutex for thread safety mutable std::mutex mutex_; ///< Registered handlers by ID std::unordered_map handlers_; - ///< Original window procedures - std::unordered_map original_procs_; + ///< Global handler IDs (sorted descending) + std::vector global_handler_ids_; + ///< Lock-free count of global handlers for the fast path + std::atomic global_handler_count_{0}; + ///< Per-window subclass state + std::unordered_map> window_states_; ///< Next available handler ID int next_id_ = 1; ///< Host window for tray icons and menus diff --git a/src/platform/windows/window_windows.cpp b/src/platform/windows/window_windows.cpp index 9edc3c49..2741e71d 100644 --- a/src/platform/windows/window_windows.cpp +++ b/src/platform/windows/window_windows.cpp @@ -1590,7 +1590,7 @@ static int RegisterAspectRatioHandler(HWND hwnd, return 0; } return WindowMessageDispatcher::GetInstance().RegisterHandler( - hwnd, + hwnd, {WM_SIZING}, [aspect_ratio, minimum, maximum](HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) -> std::optional { const double ratio = *aspect_ratio; @@ -1689,7 +1689,7 @@ static int RegisterAlwaysOnBottomHandler(HWND hwnd, int existing_handler_id) { } auto& dispatcher = WindowMessageDispatcher::GetInstance(); return dispatcher.RegisterHandler( - hwnd, + hwnd, {WM_WINDOWPOSCHANGING}, [](HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) -> std::optional { if (msg != WM_WINDOWPOSCHANGING) { return std::nullopt; @@ -1722,7 +1722,7 @@ static int RegisterMinMaxInfoHandler(HWND hwnd, // wrapper that installed this handler. Its destructor unregisters the handler // before destroying the Impl that owns these sizes. return WindowMessageDispatcher::GetInstance().RegisterHandler( - hwnd, + hwnd, {WM_GETMINMAXINFO}, [minimum, maximum](HWND hwnd, UINT msg, WPARAM, LPARAM lparam) -> std::optional { if (msg != WM_GETMINMAXINFO || !lparam) { return std::nullopt; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3a3f2129..5ae2b60f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -78,6 +78,10 @@ if(WIN32) target_link_libraries(window_startup_maximize_windows_test PRIVATE nativeapi comctl32) add_test(NAME window_startup_maximize_windows_test COMMAND window_startup_maximize_windows_test) set_tests_properties(window_startup_maximize_windows_test PROPERTIES TIMEOUT 20) + add_executable(window_geometry_coalesce_windows_test window_geometry_coalesce_windows_test.cpp) + target_link_libraries(window_geometry_coalesce_windows_test PRIVATE nativeapi comctl32) + add_test(NAME window_geometry_coalesce_windows_test COMMAND window_geometry_coalesce_windows_test) + set_tests_properties(window_geometry_coalesce_windows_test PROPERTIES TIMEOUT 20) endif() # window_manager#569 (#77): WS_POPUP windows and their caption. diff --git a/tests/window_geometry_coalesce_windows_test.cpp b/tests/window_geometry_coalesce_windows_test.cpp new file mode 100644 index 00000000..f51745fa --- /dev/null +++ b/tests/window_geometry_coalesce_windows_test.cpp @@ -0,0 +1,213 @@ +// Verifies Issue #30 fixes on Windows: +// 1. Rapid SetWindowPos left-edge bursts coalesce WindowMovedEvent / +// WindowResizedEvent instead of emitting synchronously on every step, and +// deliver the exact final geometry once the burst settles. +// 2. Inside WM_ENTERSIZEMOVE..WM_EXITSIZEMOVE, per-step WM_WINDOWPOSCHANGED +// does not emit synchronously, and WM_EXITSIZEMOVE flushes the final +// geometry immediately. +// 3. With zero listeners, WindowManager::HasAnyListeners() is false and +// re-adding a listener delivers isolated changes immediately without stale +// events. +// 4. WindowMessageDispatcher's message-filtered RegisterHandler only invokes +// the handler for subscribed messages. + +#include + +#include +#include +#include +#include + +#include "../src/platform/windows/window_message_dispatcher.h" +#include "../src/window.h" +#include "../src/window_manager.h" + +namespace { + +int g_failures = 0; + +void Check(bool condition, const char* what) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++g_failures; + } +} + +void PumpFor(DWORD ms) { + const ULONGLONG deadline = GetTickCount64() + ms; + MSG msg = {}; + while (true) { + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + if (GetTickCount64() >= deadline) { + break; + } + Sleep(5); + } +} + +void PumpPending() { + MSG msg = {}; + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } +} + +LRESULT CALLBACK TestWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { + return DefWindowProcW(hwnd, msg, wp, lp); +} + +} // namespace + +int main() { + WNDCLASSW wc = {}; + wc.lpfnWndProc = TestWndProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"NativeAPIIssue30TestWindow"; + RegisterClassW(&wc); + + HWND hwnd = CreateWindowExW(0, wc.lpszClassName, L"Issue30 Test", WS_OVERLAPPEDWINDOW, 100, 100, + 400, 300, nullptr, nullptr, wc.hInstance, nullptr); + Check(hwnd != nullptr, "create test window"); + if (!hwnd) { + return 1; + } + + ShowWindow(hwnd, SW_SHOW); + UpdateWindow(hwnd); + PumpFor(30); + + auto& manager = nativeapi::WindowManager::GetInstance(); + nativeapi::Window window(hwnd); + const auto id = window.GetId(); + Check(id != nativeapi::IdAllocator::kInvalidId, "window has valid id"); + Check(!manager.HasAnyListeners(), "zero listeners initially"); + + // 1. Message-filtered WindowMessageDispatcher test. + { + auto& dispatcher = nativeapi::WindowMessageDispatcher::GetInstance(); + std::atomic minmax_calls{0}; + std::atomic other_calls{0}; + const int hid = dispatcher.RegisterHandler( + hwnd, {WM_GETMINMAXINFO}, + [&](HWND, UINT msg, WPARAM, LPARAM) -> std::optional { + if (msg == WM_GETMINMAXINFO) { + ++minmax_calls; + } else { + ++other_calls; + } + return std::nullopt; + }); + Check(hid > 0, "register filtered handler"); + + for (int i = 0; i < 50; ++i) { + SendMessageW(hwnd, WM_MOUSEMOVE, 0, 0); + SendMessageW(hwnd, WM_USER + 7, 0, 0); + } + Check(other_calls.load() == 0, "filtered handler never called for unrelated messages"); + Check(minmax_calls.load() == 0, "filtered handler not called before WM_GETMINMAXINFO"); + + MINMAXINFO mmi = {}; + SendMessageW(hwnd, WM_GETMINMAXINFO, 0, reinterpret_cast(&mmi)); + Check(minmax_calls.load() == 1, "filtered handler called for WM_GETMINMAXINFO"); + Check(other_calls.load() == 0, "filtered handler still 0 for unrelated messages"); + + Check(dispatcher.UnregisterHandler(hid), "unregister filtered handler"); + SendMessageW(hwnd, WM_GETMINMAXINFO, 0, reinterpret_cast(&mmi)); + Check(minmax_calls.load() == 1, "unregistered handler no longer called"); + } + + // 2. Zero-listener fast path: moves while unsubscribed should not emit stale + // events when a listener is later attached. + SetWindowPos(hwnd, nullptr, 140, 120, 420, 320, SWP_NOZORDER | SWP_NOACTIVATE); + PumpFor(20); + Check(!manager.HasAnyListeners(), "still zero listeners after unsubscribed move/resize"); + + int moved_count = 0; + int resized_count = 0; + nativeapi::Point last_pos = {}; + nativeapi::Size last_size = {}; + + const size_t moved_lid = manager.AddListener([&](const auto& e) { + if (e.GetWindowId() == id) { + ++moved_count; + last_pos = e.GetNewPosition(); + } + }); + const size_t resized_lid = + manager.AddListener([&](const auto& e) { + if (e.GetWindowId() == id) { + ++resized_count; + last_size = e.GetNewSize(); + } + }); + Check(manager.HasAnyListeners(), "HasAnyListeners true after AddListener"); + + // 3. Isolated single resize (without moving) emits immediately with no stale move. + SetWindowPos(hwnd, nullptr, 0, 0, 460, 320, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); + PumpPending(); + Check(resized_count == 1, "isolated resize emits immediately"); + Check(moved_count == 0, "isolated resize does not emit stale move from pre-listener change"); + + // 4. Rapid left-edge SetWindowPos burst (60 steps) must coalesce. + moved_count = 0; + resized_count = 0; + for (int i = 0; i < 60; ++i) { + const int delta = (i % 2 == 0) ? 1 : 0; + SetWindowPos(hwnd, nullptr, 140 + delta, 120, 460 - delta, 320, + SWP_NOZORDER | SWP_NOACTIVATE); + } + const int sync_moved = moved_count; + const int sync_resized = resized_count; + Check(sync_moved < 10, "rapid burst coalesces synchronous WindowMovedEvent"); + Check(sync_resized < 10, "rapid burst coalesces synchronous WindowResizedEvent"); + + // Wait for coalesce timer to flush final geometry. + PumpFor(120); + Check(moved_count >= 1 && moved_count < 15, "burst delivers coalesced WindowMovedEvent"); + Check(resized_count >= 1 && resized_count < 15, "burst delivers coalesced WindowResizedEvent"); + const nativeapi::Size expected_burst_size = window.GetSize(); + Check(std::abs(last_size.width - expected_burst_size.width) < 1.0 && + std::abs(last_size.height - expected_burst_size.height) < 1.0, + "coalesced final size matches actual window size"); + + // 5. Interactive WM_ENTERSIZEMOVE..WM_EXITSIZEMOVE: zero synchronous events + // during rapid steps, immediate flush of final geometry on WM_EXITSIZEMOVE. + PumpFor(80); + moved_count = 0; + resized_count = 0; + SendMessageW(hwnd, WM_ENTERSIZEMOVE, 0, 0); + for (int i = 1; i <= 20; ++i) { + SetWindowPos(hwnd, nullptr, 140 + i, 120, 460 + i * 2, 320, SWP_NOZORDER | SWP_NOACTIVATE); + } + Check(moved_count == 0, "no synchronous WindowMovedEvent inside WM_ENTERSIZEMOVE"); + Check(resized_count == 0, "no synchronous WindowResizedEvent inside WM_ENTERSIZEMOVE"); + + SendMessageW(hwnd, WM_EXITSIZEMOVE, 0, 0); + Check(moved_count == 1, "WM_EXITSIZEMOVE flushes final WindowMovedEvent immediately"); + Check(resized_count == 1, "WM_EXITSIZEMOVE flushes final WindowResizedEvent immediately"); + const nativeapi::Point expected_exit_pos = window.GetPosition(); + const nativeapi::Size expected_exit_size = window.GetSize(); + Check(std::abs(last_pos.x - expected_exit_pos.x) < 1.0 && + std::abs(last_pos.y - expected_exit_pos.y) < 1.0, + "WM_EXITSIZEMOVE position matches final window position"); + Check(std::abs(last_size.width - expected_exit_size.width) < 1.0 && + std::abs(last_size.height - expected_exit_size.height) < 1.0, + "WM_EXITSIZEMOVE size matches final window size"); + + manager.RemoveListener(moved_lid); + manager.RemoveListener(resized_lid); + Check(!manager.HasAnyListeners(), "HasAnyListeners false after removing listeners"); + + DestroyWindow(hwnd); + PumpFor(20); + UnregisterClassW(wc.lpszClassName, wc.hInstance); + + if (g_failures == 0) { + std::printf("PASS: window_geometry_coalesce_windows_test\n"); + } + return g_failures == 0 ? 0 : 1; +}