Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 33 additions & 20 deletions src/platform/macos/macos_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -487,23 +487,19 @@ namespace lvh::detail {
*
* Local-event suppression on `source` is set to zero so cursor warps do not
* discard the following click or mouse-moved events. CoreGraphics copies
* that configuration into each event at creation time, so `mouse_event` is
* refreshed from `source` after the interval is configured.
* that configuration into each event at creation time, so mouse events are
* created after the interval is configured.
*/
class MacosInputState {
public:
MacosInputState():
source {CGEventSourceCreate(kCGEventSourceStateHIDSystemState)},
keyboard_source {CGEventSourceCreate(kCGEventSourceStatePrivate)},
mouse_event {source ? CGEventCreate(source) : nullptr},
scroll_lines_per_detent_value {read_scroll_lines_per_detent(scrollwheel_scaling)} {
// Each move warps the cursor. The default 250ms suppression then drops the
// following click and mouse-moved events. The cursor image still moves.
if (source) {
CGEventSourceSetLocalEventsSuppressionInterval(source, 0);
if (mouse_event) {
CGEventSetSource(mouse_event, source);
}
}
}

Expand All @@ -513,9 +509,6 @@ namespace lvh::detail {
MacosInputState &operator=(MacosInputState &&) noexcept = delete;

~MacosInputState() {
if (mouse_event) {
CFRelease(mouse_event);
}
if (keyboard_source) {
CFRelease(keyboard_source);
}
Expand All @@ -526,7 +519,6 @@ namespace lvh::detail {

CGEventSourceRef source {}; ///< Mouse/scroll source with local-event suppression disabled.
CGEventSourceRef keyboard_source {}; ///< CoreGraphics event source for keyboard events.
CGEventRef mouse_event {}; ///< Reusable mouse event refreshed from `source` after suppression is disabled.
double scrollwheel_scaling = default_scrollwheel_scaling; ///< Raw macOS scroll-wheel scaling preference.
int scroll_lines_per_detent_value = default_scroll_lines_per_detent; ///< Logical lines per wheel detent.
CGEventFlags keyboard_flags {}; ///< Active modifier flags applied to mouse events.
Expand Down Expand Up @@ -734,7 +726,7 @@ namespace lvh::detail {
}

/**
* @brief Backend mouse backed by CoreGraphics mouse and scroll events.
* @brief Backend mouse that creates a fresh CoreGraphics event for each submission.
*/
class MacosMouse final: public BackendMouse {
public:
Expand All @@ -753,7 +745,7 @@ namespace lvh::detail {
if (!open_) {
return OperationStatus::failure(ErrorCode::device_closed, "macOS mouse is closed");
}
if (!state_->source || !state_->mouse_event) {
if (!state_->source) {
return OperationStatus::failure(ErrorCode::backend_failure, "macOS mouse event source is unavailable");
}

Expand Down Expand Up @@ -798,6 +790,16 @@ namespace lvh::detail {
return current;
}

/**
* @brief Create and post a fresh native mouse event with the requested metadata.
*
* @param button CoreGraphics mouse button.
* @param type Mouse movement, drag, or button event type.
* @param raw_location Requested cursor location before display clamping.
* @param previous_location Cursor location used to calculate movement deltas.
* @param click_count Number of clicks in the current button sequence.
* @return Submission status, including an event allocation failure when applicable.
*/
OperationStatus post_mouse(
CGMouseButton button,
CGEventType type,
Expand All @@ -810,10 +812,11 @@ namespace lvh::detail {
std::clamp(raw_location.y, viewport_bounds_.origin.y, viewport_bounds_.origin.y + viewport_bounds_.size.height - 1)
};

const auto event = state_->mouse_event;
CGEventSetType(event, type);
CGEventSetLocation(event, location);
CGEventSetIntegerValueField(event, kCGMouseEventButtonNumber, button);
const auto event = CGEventCreateMouseEvent(state_->source, type, location, button);
if (!event) {
return OperationStatus::failure(ErrorCode::backend_failure, "create macOS mouse event");
}
Comment thread
ReenigneArcher marked this conversation as resolved.
Resolved

CGEventSetIntegerValueField(event, kCGMouseEventClickState, click_count);
CGEventSetDoubleValueField(event, kCGMouseEventDeltaX, raw_location.x - previous_location.x);
CGEventSetDoubleValueField(event, kCGMouseEventDeltaY, raw_location.y - previous_location.y);
Expand All @@ -824,6 +827,7 @@ namespace lvh::detail {
}

CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
CGWarpMouseCursorPosition(location);
return OperationStatus::success();
}
Expand All @@ -841,6 +845,12 @@ namespace lvh::detail {
return post_mouse(motion.button, motion.event_type, location, current_location(), 0);
}

/**
* @brief Post a button transition and update the drag and click state on success.
*
* @param event Requested mouse button transition.
* @return Submission status. A failed allocation leaves button and click state unchanged.
*/
OperationStatus submit_button(const MouseEvent &event) {
using enum ErrorCode;

Expand All @@ -849,14 +859,17 @@ namespace lvh::detail {
return OperationStatus::failure(unsupported_profile, "macOS mouse backend supports only left, middle, and right buttons");
}

mouse_down_[button->index] = event.pressed;
const auto now = std::chrono::steady_clock::now();
const auto release_index = event.pressed ? 0U : 1U;
const auto mouse_position = current_location();
const auto click_count = now < last_mouse_event_[button->index][release_index] + multi_click_delay ? 2 : 1;

last_mouse_event_[button->index][release_index] = now;
return post_mouse(button->button, event.pressed ? button->down_event : button->up_event, mouse_position, mouse_position, click_count);
const auto status = post_mouse(button->button, event.pressed ? button->down_event : button->up_event, mouse_position, mouse_position, click_count);
if (status.ok()) {
mouse_down_[button->index] = event.pressed;
last_mouse_event_[button->index][release_index] = now;
}
return status;
}

OperationStatus submit_scroll(std::int32_t high_resolution_vertical, std::int32_t high_resolution_horizontal) const {
Expand Down Expand Up @@ -927,7 +940,7 @@ namespace lvh::detail {
return {OperationStatus::failure(ErrorCode::unsupported_profile, "device profile is not a mouse"), nullptr};
}
auto state = input_state();
if (!state->source || !state->mouse_event) {
if (!state->source) {
return {OperationStatus::failure(ErrorCode::backend_failure, "macOS mouse event source is unavailable"), nullptr};
}

Expand Down
45 changes: 44 additions & 1 deletion tests/fixtures/include/fixtures/macos_backend_test_hooks.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#pragma once

// standard includes
#include <cstddef>
#include <cstdint>
#include <optional>
#include <utility>
Expand Down Expand Up @@ -59,6 +60,31 @@ namespace lvh::detail::test {
std::uint32_t event_type {}; ///< CoreGraphics mouse event type value.
};

/**
* @brief Metadata captured from a CoreGraphics mouse event at submission time.
*/
struct MacosMouseEventResult {
std::uint32_t tap_location {}; ///< CoreGraphics event tap used for posting.
std::uint32_t event_type {}; ///< CoreGraphics event type.
std::int64_t button {}; ///< CoreGraphics mouse button number.
std::int64_t click_count {}; ///< Number of clicks in the button sequence.
std::uint64_t timestamp {}; ///< Native event timestamp, which may be unset before posting.
std::uint64_t flags {}; ///< Keyboard modifier flags applied to the event.
std::optional<double> suppression_interval; ///< Local-event suppression copied into the event source.
MacosPoint location; ///< Clamped cursor position.
MacosPoint delta; ///< Requested movement delta before clamping.
};

/**
* @brief Results of mouse submissions with posting and cursor warping intercepted.
*/
struct MacosMouseEventsResult {
std::vector<OperationStatus> statuses; ///< Status of each requested submission.
std::vector<MacosMouseEventResult> events; ///< Events captured before posting.
std::size_t creation_attempts {}; ///< Calls to create a new CoreGraphics mouse event.
std::size_t cursor_warps {}; ///< Calls to update the cursor after posting.
};

/**
* @brief Portable view of one CoreGraphics keyboard event the macOS backend built.
*/
Expand Down Expand Up @@ -192,6 +218,23 @@ namespace lvh::detail::test {
*/
MacosMouseMotionResult macos_backend_mouse_motion(bool left_down, bool right_down, bool middle_down);

/**
* @brief Submit mouse events using aged cursor snapshots without changing the desktop.
*
* Cursor snapshots have timestamp 1 and location (40, 60) on a display with
* bounds (10, 20, 400, 200). Shift and Control modifiers are held throughout.
*
* @param events Mouse events to submit through the production backend.
* @param fail_first_creation Whether the first mouse event allocation should fail.
* @param source_available Whether the mouse event source remains available.
* @return Submission statuses, posted event metadata, and allocation and warp counts.
*/
MacosMouseEventsResult macos_backend_mouse_events(
const std::vector<MouseEvent> &events,
bool fail_first_creation = false,
bool source_available = true
);

/**
* @brief Exercise macOS backend creation and unsupported-device paths.
*
Expand All @@ -200,7 +243,7 @@ namespace lvh::detail::test {
MacosBackendUtilityResult macos_backend_utilities();

/**
* @brief Read the suppression interval stored on the backend's reusable mouse event.
* @brief Read the suppression interval stored on a freshly submitted backend mouse event.
*
* @return Suppression interval in seconds, or no value if event-source creation fails.
*/
Expand Down
106 changes: 95 additions & 11 deletions tests/fixtures/macos_backend_test_hooks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,60 @@ namespace {
lvh::detail::test::MacosPoint cursor_location;
std::optional<lvh::detail::test::MacosPoint> posted_location;
std::optional<lvh::detail::test::MacosPoint> warped_location;
lvh::detail::test::MacosMouseEventsResult *events = nullptr; ///< Optional capture of native event metadata.
bool fail_first_creation = false; ///< Whether to fail the next mouse event allocation.
};

/**
* @brief Age cursor snapshots while capturing fresh mouse event submissions.
*
* @param source CoreGraphics event source.
* @return Native cursor snapshot, or null when allocation fails.
*/
CGEventRef mouse_create_event(CGEventSourceRef source) {
const auto event = CGEventCreate(source);
if (event && mouse_environment() && mouse_environment()->events) {
CGEventSetTimestamp(event, 1);
}
return event;
}

/**
* @brief Count native mouse event allocations and optionally fail the first allocation.
*
* @param source CoreGraphics event source.
* @param type Requested event type.
* @param location Cursor location.
* @param button CoreGraphics button number.
* @return New native mouse event, or null for the injected failure.
*/
CGEventRef mouse_create_mouse_event(CGEventSourceRef source, CGEventType type, CGPoint location, CGMouseButton button) {
if (mouse_environment() && mouse_environment()->events) {
++mouse_environment()->events->creation_attempts;
if (mouse_environment()->fail_first_creation) {
mouse_environment()->fail_first_creation = false;
return nullptr;
}
}
return CGEventCreateMouseEvent(source, type, location, button);
}

/**
* @brief Read the local-event suppression copied into a native event source.
*
* @param event Mouse event whose source is inspected.
* @return Suppression interval in seconds, or no value when source creation fails.
*/
std::optional<double> mouse_event_suppression_interval(CGEventRef event) {
const auto source = CGEventCreateSourceFromEvent(event);
if (!source) {
return std::nullopt;
}
const auto interval = CGEventSourceGetLocalEventsSuppressionInterval(source);
CFRelease(source);
return interval;
}

CGDirectDisplayID mouse_main_display_id() {
return mouse_environment() ? 42 : CGMainDisplayID();
}
Expand All @@ -89,13 +141,29 @@ namespace {
}
const auto point = CGEventGetLocation(event);
mouse_environment()->posted_location = {.x = point.x, .y = point.y};
if (mouse_environment()->events) {
mouse_environment()->events->events.push_back({
.tap_location = static_cast<std::uint32_t>(tap),
.event_type = static_cast<std::uint32_t>(CGEventGetType(event)),
.button = CGEventGetIntegerValueField(event, kCGMouseEventButtonNumber),
.click_count = CGEventGetIntegerValueField(event, kCGMouseEventClickState),
.timestamp = CGEventGetTimestamp(event),
.flags = static_cast<std::uint64_t>(CGEventGetFlags(event)),
.suppression_interval = mouse_event_suppression_interval(event),
.location = {point.x, point.y},
.delta = {CGEventGetDoubleValueField(event, kCGMouseEventDeltaX), CGEventGetDoubleValueField(event, kCGMouseEventDeltaY)},
});
}
}

CGError mouse_warp_cursor_position(CGPoint point) {
if (!mouse_environment()) {
return CGWarpMouseCursorPosition(point);
}
mouse_environment()->warped_location = {.x = point.x, .y = point.y};
if (mouse_environment()->events) {
++mouse_environment()->events->cursor_warps;
}
return kCGErrorSuccess;
}

Expand All @@ -105,6 +173,8 @@ namespace {
// separate namespace so instrumented inline symbols remain isolated.
#define macos macos_backend_test
#define CGMainDisplayID mouse_main_display_id
#define CGEventCreate mouse_create_event
#define CGEventCreateMouseEvent mouse_create_mouse_event
#define CGDisplayBounds mouse_display_bounds
#define CGEventGetLocation mouse_event_location
#define CGEventPost mouse_event_post
Expand All @@ -116,6 +186,8 @@ namespace {
#undef CGEventPost
#undef CGEventGetLocation
#undef CGDisplayBounds
#undef CGEventCreateMouseEvent
#undef CGEventCreate
#undef CGMainDisplayID
#undef macos

Expand All @@ -124,17 +196,8 @@ namespace lvh::detail::test {
namespace macos = lvh::detail::macos_backend_test;

std::optional<double> macos_backend_mouse_event_suppression_interval() {
macos::MacosInputState state;
if (!state.mouse_event) {
return std::nullopt;
}
const auto source = CGEventCreateSourceFromEvent(state.mouse_event);
if (!source) {
return std::nullopt;
}
const auto interval = CGEventSourceGetLocalEventsSuppressionInterval(source);
CFRelease(source);
return interval;
const auto result = macos_backend_mouse_events({{.kind = MouseEventKind::relative_motion, .x = 1, .y = 1}});
return result.events.empty() ? std::nullopt : result.events.front().suppression_interval;
}

std::optional<std::uint16_t> macos_backend_key_code(KeyboardKeyCode key_code) {
Expand Down Expand Up @@ -263,6 +326,27 @@ namespace lvh::detail::test {
};
}

MacosMouseEventsResult macos_backend_mouse_events(const std::vector<MouseEvent> &events, bool fail_first_creation, bool source_available) {
MacosMouseEventsResult result;
MouseEnvironment environment {{.origin_x = 10, .origin_y = 20, .width = 400, .height = 200}};
environment.cursor_location = {40, 60};
environment.events = &result;
environment.fail_first_creation = fail_first_creation;

auto state = std::make_shared<macos::MacosInputState>();
state->keyboard_flags = kCGEventFlagMaskShift | kCGEventFlagMaskControl;
if (!source_available && state->source) {
CFRelease(state->source);
state->source = nullptr;
}

macos::MacosMouse mouse {std::move(state), {}};
for (const auto &event : events) {
result.statuses.push_back(mouse.submit(event));
}
return result;
}

MacosBackendUtilityResult macos_backend_utilities() {
auto backend = create_platform_backend_for_macos_backend_test_hooks();
MacosBackendUtilityResult result;
Expand Down
Loading
Loading