Merge pull request #1298 from zed-industries/mouse-region-refactor

Mouse Event Refactor
This commit is contained in:
Nathan Sobo 2022-07-07 16:43:36 -06:00 committed by GitHub
commit 805c06ee76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 306 additions and 278 deletions

View File

@ -23,8 +23,9 @@ use gpui::{
json::{self, ToJson}, json::{self, ToJson},
platform::CursorStyle, platform::CursorStyle,
text_layout::{self, Line, RunStyle, TextLayoutCache}, text_layout::{self, Line, RunStyle, TextLayoutCache},
AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext, AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext, KeyDownEvent,
LayoutContext, MutableAppContext, PaintContext, Quad, Scene, SizeConstraint, ViewContext, LayoutContext, ModifiersChangedEvent, MouseButton, MouseEvent, MouseMovedEvent,
MutableAppContext, PaintContext, Quad, Scene, ScrollWheelEvent, SizeConstraint, ViewContext,
WeakViewHandle, WeakViewHandle,
}; };
use json::json; use json::json;
@ -1463,14 +1464,15 @@ impl Element for EditorElement {
} }
match event { match event {
Event::LeftMouseDown { Event::MouseDown(MouseEvent {
button: MouseButton::Left,
position, position,
cmd, cmd,
alt, alt,
shift, shift,
click_count, click_count,
.. ..
} => self.mouse_down( }) => self.mouse_down(
*position, *position,
*cmd, *cmd,
*alt, *alt,
@ -1480,18 +1482,26 @@ impl Element for EditorElement {
paint, paint,
cx, cx,
), ),
Event::LeftMouseUp { position, .. } => self.mouse_up(*position, cx), Event::MouseUp(MouseEvent {
Event::LeftMouseDragged { position, .. } => { button: MouseButton::Left,
self.mouse_dragged(*position, layout, paint, cx) position,
} ..
Event::ScrollWheel { }) => self.mouse_up(*position, cx),
Event::MouseMoved(MouseMovedEvent {
pressed_button: Some(MouseButton::Left),
position,
..
}) => self.mouse_dragged(*position, layout, paint, cx),
Event::ScrollWheel(ScrollWheelEvent {
position, position,
delta, delta,
precise, precise,
} => self.scroll(*position, *delta, *precise, layout, paint, cx), }) => self.scroll(*position, *delta, *precise, layout, paint, cx),
Event::KeyDown { input, .. } => self.key_down(input.as_deref(), cx), Event::KeyDown(KeyDownEvent { input, .. }) => self.key_down(input.as_deref(), cx),
Event::ModifiersChanged { cmd, .. } => self.modifiers_changed(*cmd, cx), Event::ModifiersChanged(ModifiersChangedEvent { cmd, .. }) => {
Event::MouseMoved { position, cmd, .. } => { self.modifiers_changed(*cmd, cx)
}
Event::MouseMoved(MouseMovedEvent { position, cmd, .. }) => {
self.mouse_moved(*position, *cmd, layout, paint, cx) self.mouse_moved(*position, *cmd, layout, paint, cx)
} }

View File

@ -4,7 +4,7 @@ use crate::{
elements::ElementBox, elements::ElementBox,
executor::{self, Task}, executor::{self, Task},
keymap::{self, Binding, Keystroke}, keymap::{self, Binding, Keystroke},
platform::{self, Platform, PromptLevel, WindowOptions}, platform::{self, KeyDownEvent, Platform, PromptLevel, WindowOptions},
presenter::Presenter, presenter::Presenter,
util::post_inc, util::post_inc,
AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId, PathPromptOptions, AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId, PathPromptOptions,
@ -379,11 +379,11 @@ impl TestAppContext {
if !cx.dispatch_keystroke(window_id, dispatch_path, &keystroke) { if !cx.dispatch_keystroke(window_id, dispatch_path, &keystroke) {
presenter.borrow_mut().dispatch_event( presenter.borrow_mut().dispatch_event(
Event::KeyDown { Event::KeyDown(KeyDownEvent {
keystroke, keystroke,
input, input,
is_held, is_held,
}, }),
cx, cx,
); );
} }
@ -1835,7 +1835,7 @@ impl MutableAppContext {
window.on_event(Box::new(move |event| { window.on_event(Box::new(move |event| {
app.update(|cx| { app.update(|cx| {
if let Some(presenter) = presenter.upgrade() { if let Some(presenter) = presenter.upgrade() {
if let Event::KeyDown { keystroke, .. } = &event { if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
if cx.dispatch_keystroke( if cx.dispatch_keystroke(
window_id, window_id,
presenter.borrow().dispatch_path(cx.as_ref()), presenter.borrow().dispatch_path(cx.as_ref()),
@ -5392,7 +5392,7 @@ impl RefCounts {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::{actions, elements::*, impl_actions}; use crate::{actions, elements::*, impl_actions, MouseButton, MouseEvent};
use serde::Deserialize; use serde::Deserialize;
use smol::future::poll_once; use smol::future::poll_once;
use std::{ use std::{
@ -5745,14 +5745,15 @@ mod tests {
let presenter = cx.presenters_and_platform_windows[&window_id].0.clone(); let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
// Ensure window's root element is in a valid lifecycle state. // Ensure window's root element is in a valid lifecycle state.
presenter.borrow_mut().dispatch_event( presenter.borrow_mut().dispatch_event(
Event::LeftMouseDown { Event::MouseDown(MouseEvent {
position: Default::default(), position: Default::default(),
button: MouseButton::Left,
ctrl: false, ctrl: false,
alt: false, alt: false,
shift: false, shift: false,
cmd: false, cmd: false,
click_count: 1, click_count: 1,
}, }),
cx, cx,
); );
assert_eq!(mouse_down_count.load(SeqCst), 1); assert_eq!(mouse_down_count.load(SeqCst), 1);

View File

@ -1,6 +1,7 @@
use crate::{ use crate::{
geometry::vector::Vector2F, CursorRegion, DebugContext, Element, ElementBox, Event, geometry::vector::Vector2F, CursorRegion, DebugContext, Element, ElementBox, Event,
EventContext, LayoutContext, MouseRegion, NavigationDirection, PaintContext, SizeConstraint, EventContext, LayoutContext, MouseButton, MouseEvent, MouseRegion, NavigationDirection,
PaintContext, SizeConstraint,
}; };
use pathfinder_geometry::rect::RectF; use pathfinder_geometry::rect::RectF;
use serde_json::json; use serde_json::json;
@ -116,7 +117,11 @@ impl Element for EventHandler {
true true
} else { } else {
match event { match event {
Event::LeftMouseDown { position, .. } => { Event::MouseDown(MouseEvent {
button: MouseButton::Left,
position,
..
}) => {
if let Some(callback) = self.mouse_down.as_mut() { if let Some(callback) = self.mouse_down.as_mut() {
if visible_bounds.contains_point(*position) { if visible_bounds.contains_point(*position) {
return callback(cx); return callback(cx);
@ -124,7 +129,11 @@ impl Element for EventHandler {
} }
false false
} }
Event::RightMouseDown { position, .. } => { Event::MouseDown(MouseEvent {
button: MouseButton::Right,
position,
..
}) => {
if let Some(callback) = self.right_mouse_down.as_mut() { if let Some(callback) = self.right_mouse_down.as_mut() {
if visible_bounds.contains_point(*position) { if visible_bounds.contains_point(*position) {
return callback(cx); return callback(cx);
@ -132,11 +141,11 @@ impl Element for EventHandler {
} }
false false
} }
Event::NavigateMouseDown { Event::MouseDown(MouseEvent {
button: MouseButton::Navigate(direction),
position, position,
direction,
.. ..
} => { }) => {
if let Some(callback) = self.navigate_mouse_down.as_mut() { if let Some(callback) = self.navigate_mouse_down.as_mut() {
if visible_bounds.contains_point(*position) { if visible_bounds.contains_point(*position) {
return callback(*direction, cx); return callback(*direction, cx);

View File

@ -3,7 +3,8 @@ use std::{any::Any, f32::INFINITY};
use crate::{ use crate::{
json::{self, ToJson, Value}, json::{self, ToJson, Value},
Axis, DebugContext, Element, ElementBox, ElementStateHandle, Event, EventContext, Axis, DebugContext, Element, ElementBox, ElementStateHandle, Event, EventContext,
LayoutContext, PaintContext, RenderContext, SizeConstraint, Vector2FExt, View, LayoutContext, MouseMovedEvent, PaintContext, RenderContext, ScrollWheelEvent, SizeConstraint,
Vector2FExt, View,
}; };
use pathfinder_geometry::{ use pathfinder_geometry::{
rect::RectF, rect::RectF,
@ -287,11 +288,11 @@ impl Element for Flex {
handled = child.dispatch_event(event, cx) || handled; handled = child.dispatch_event(event, cx) || handled;
} }
if !handled { if !handled {
if let &Event::ScrollWheel { if let &Event::ScrollWheel(ScrollWheelEvent {
position, position,
delta, delta,
precise, precise,
} = event }) = event
{ {
if *remaining_space < 0. && bounds.contains_point(position) { if *remaining_space < 0. && bounds.contains_point(position) {
if let Some(scroll_state) = self.scroll_state.as_ref() { if let Some(scroll_state) = self.scroll_state.as_ref() {
@ -321,7 +322,7 @@ impl Element for Flex {
} }
if !handled { if !handled {
if let &Event::MouseMoved { position, .. } = event { if let &Event::MouseMoved(MouseMovedEvent { position, .. }) = event {
// If this is a scrollable flex, and the mouse is over it, eat the scroll event to prevent // If this is a scrollable flex, and the mouse is over it, eat the scroll event to prevent
// propogating it to the element below. // propogating it to the element below.
if self.scroll_state.is_some() && bounds.contains_point(position) { if self.scroll_state.is_some() && bounds.contains_point(position) {

View File

@ -5,7 +5,7 @@ use crate::{
}, },
json::json, json::json,
DebugContext, Element, ElementBox, ElementRc, Event, EventContext, LayoutContext, PaintContext, DebugContext, Element, ElementBox, ElementRc, Event, EventContext, LayoutContext, PaintContext,
RenderContext, SizeConstraint, View, ViewContext, RenderContext, ScrollWheelEvent, SizeConstraint, View, ViewContext,
}; };
use std::{cell::RefCell, collections::VecDeque, ops::Range, rc::Rc}; use std::{cell::RefCell, collections::VecDeque, ops::Range, rc::Rc};
use sum_tree::{Bias, SumTree}; use sum_tree::{Bias, SumTree};
@ -311,11 +311,11 @@ impl Element for List {
state.items = new_items; state.items = new_items;
match event { match event {
Event::ScrollWheel { Event::ScrollWheel(ScrollWheelEvent {
position, position,
delta, delta,
precise, precise,
} => { }) => {
if bounds.contains_point(*position) { if bounds.contains_point(*position) {
if state.scroll(scroll_top, bounds.height(), *delta, *precise, cx) { if state.scroll(scroll_top, bounds.height(), *delta, *precise, cx) {
handled = true; handled = true;

View File

@ -5,7 +5,7 @@ use crate::{
vector::{vec2f, Vector2F}, vector::{vec2f, Vector2F},
}, },
json::{self, json}, json::{self, json},
ElementBox, RenderContext, View, ElementBox, RenderContext, ScrollWheelEvent, View,
}; };
use json::ToJson; use json::ToJson;
use std::{cell::RefCell, cmp, ops::Range, rc::Rc}; use std::{cell::RefCell, cmp, ops::Range, rc::Rc};
@ -310,11 +310,11 @@ impl Element for UniformList {
} }
match event { match event {
Event::ScrollWheel { Event::ScrollWheel(ScrollWheelEvent {
position, position,
delta, delta,
precise, precise,
} => { }) => {
if bounds.contains_point(*position) { if bounds.contains_point(*position) {
if self.scroll(*position, *delta, *precise, layout.scroll_max, cx) { if self.scroll(*position, *delta, *precise, layout.scroll_max, cx) {
handled = true; handled = true;

View File

@ -28,8 +28,7 @@ pub mod json;
pub mod keymap; pub mod keymap;
pub mod platform; pub mod platform;
pub use gpui_macros::test; pub use gpui_macros::test;
pub use platform::FontSystem; pub use platform::*;
pub use platform::{Event, NavigationDirection, PathPromptOptions, Platform, PromptLevel};
pub use presenter::{ pub use presenter::{
Axis, DebugContext, EventContext, LayoutContext, PaintContext, SizeConstraint, Vector2FExt, Axis, DebugContext, EventContext, LayoutContext, PaintContext, SizeConstraint, Vector2FExt,
}; };

View File

@ -20,7 +20,7 @@ use crate::{
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use async_task::Runnable; use async_task::Runnable;
pub use event::{Event, NavigationDirection}; pub use event::*;
use postage::oneshot; use postage::oneshot;
use serde::Deserialize; use serde::Deserialize;
use std::{ use std::{

View File

@ -1,85 +1,77 @@
use crate::{geometry::vector::Vector2F, keymap::Keystroke}; use crate::{geometry::vector::Vector2F, keymap::Keystroke};
#[derive(Clone, Debug)]
pub struct KeyDownEvent {
pub keystroke: Keystroke,
pub input: Option<String>,
pub is_held: bool,
}
#[derive(Clone, Debug)]
pub struct KeyUpEvent {
pub keystroke: Keystroke,
pub input: Option<String>,
}
#[derive(Clone, Debug)]
pub struct ModifiersChangedEvent {
pub ctrl: bool,
pub alt: bool,
pub shift: bool,
pub cmd: bool,
}
#[derive(Clone, Debug)]
pub struct ScrollWheelEvent {
pub position: Vector2F,
pub delta: Vector2F,
pub precise: bool,
}
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum NavigationDirection { pub enum NavigationDirection {
Back, Back,
Forward, Forward,
} }
#[derive(Copy, Clone, Debug)]
pub enum MouseButton {
Left,
Right,
Middle,
Navigate(NavigationDirection),
}
#[derive(Clone, Debug)]
pub struct MouseEvent {
pub button: MouseButton,
pub position: Vector2F,
pub ctrl: bool,
pub alt: bool,
pub shift: bool,
pub cmd: bool,
pub click_count: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct MouseMovedEvent {
pub position: Vector2F,
pub pressed_button: Option<MouseButton>,
pub ctrl: bool,
pub cmd: bool,
pub alt: bool,
pub shift: bool,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Event { pub enum Event {
KeyDown { KeyDown(KeyDownEvent),
keystroke: Keystroke, KeyUp(KeyUpEvent),
input: Option<String>, ModifiersChanged(ModifiersChangedEvent),
is_held: bool, MouseDown(MouseEvent),
}, MouseUp(MouseEvent),
KeyUp { MouseMoved(MouseMovedEvent),
keystroke: Keystroke, ScrollWheel(ScrollWheelEvent),
input: Option<String>,
},
ModifiersChanged {
ctrl: bool,
alt: bool,
shift: bool,
cmd: bool,
},
ScrollWheel {
position: Vector2F,
delta: Vector2F,
precise: bool,
},
LeftMouseDown {
position: Vector2F,
ctrl: bool,
alt: bool,
shift: bool,
cmd: bool,
click_count: usize,
},
LeftMouseUp {
position: Vector2F,
click_count: usize,
},
LeftMouseDragged {
position: Vector2F,
ctrl: bool,
alt: bool,
shift: bool,
cmd: bool,
},
RightMouseDown {
position: Vector2F,
ctrl: bool,
alt: bool,
shift: bool,
cmd: bool,
click_count: usize,
},
RightMouseUp {
position: Vector2F,
click_count: usize,
},
NavigateMouseDown {
position: Vector2F,
direction: NavigationDirection,
ctrl: bool,
alt: bool,
shift: bool,
cmd: bool,
click_count: usize,
},
NavigateMouseUp {
position: Vector2F,
direction: NavigationDirection,
},
MouseMoved {
position: Vector2F,
left_mouse_down: bool,
ctrl: bool,
cmd: bool,
alt: bool,
shift: bool,
},
} }
impl Event { impl Event {
@ -88,15 +80,9 @@ impl Event {
Event::KeyDown { .. } => None, Event::KeyDown { .. } => None,
Event::KeyUp { .. } => None, Event::KeyUp { .. } => None,
Event::ModifiersChanged { .. } => None, Event::ModifiersChanged { .. } => None,
Event::ScrollWheel { position, .. } Event::MouseDown(event) | Event::MouseUp(event) => Some(event.position),
| Event::LeftMouseDown { position, .. } Event::MouseMoved(event) => Some(event.position),
| Event::LeftMouseUp { position, .. } Event::ScrollWheel(event) => Some(event.position),
| Event::LeftMouseDragged { position, .. }
| Event::RightMouseDown { position, .. }
| Event::RightMouseUp { position, .. }
| Event::NavigateMouseDown { position, .. }
| Event::NavigateMouseUp { position, .. }
| Event::MouseMoved { position, .. } => Some(*position),
} }
} }
} }

View File

@ -2,10 +2,12 @@ use crate::{
geometry::vector::vec2f, geometry::vector::vec2f,
keymap::Keystroke, keymap::Keystroke,
platform::{Event, NavigationDirection}, platform::{Event, NavigationDirection},
KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, MouseButton, MouseEvent, MouseMovedEvent,
ScrollWheelEvent,
}; };
use cocoa::{ use cocoa::{
appkit::{NSEvent, NSEventModifierFlags, NSEventType}, appkit::{NSEvent, NSEventModifierFlags, NSEventType},
base::{id, nil, YES}, base::{id, YES},
foundation::NSString as _, foundation::NSString as _,
}; };
use std::{borrow::Cow, ffi::CStr, os::raw::c_char}; use std::{borrow::Cow, ffi::CStr, os::raw::c_char};
@ -59,12 +61,12 @@ impl Event {
let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask); let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask); let cmd = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
Some(Self::ModifiersChanged { Some(Self::ModifiersChanged(ModifiersChangedEvent {
ctrl, ctrl,
alt, alt,
shift, shift,
cmd, cmd,
}) }))
} }
NSEventType::NSKeyDown => { NSEventType::NSKeyDown => {
let modifiers = native_event.modifierFlags(); let modifiers = native_event.modifierFlags();
@ -76,7 +78,7 @@ impl Event {
let (unmodified_chars, input) = get_key_text(native_event, cmd, ctrl, function)?; let (unmodified_chars, input) = get_key_text(native_event, cmd, ctrl, function)?;
Some(Self::KeyDown { Some(Self::KeyDown(KeyDownEvent {
keystroke: Keystroke { keystroke: Keystroke {
ctrl, ctrl,
alt, alt,
@ -86,7 +88,7 @@ impl Event {
}, },
input, input,
is_held: native_event.isARepeat() == YES, is_held: native_event.isARepeat() == YES,
}) }))
} }
NSEventType::NSKeyUp => { NSEventType::NSKeyUp => {
let modifiers = native_event.modifierFlags(); let modifiers = native_event.modifierFlags();
@ -98,7 +100,7 @@ impl Event {
let (unmodified_chars, input) = get_key_text(native_event, cmd, ctrl, function)?; let (unmodified_chars, input) = get_key_text(native_event, cmd, ctrl, function)?;
Some(Self::KeyUp { Some(Self::KeyUp(KeyUpEvent {
keystroke: Keystroke { keystroke: Keystroke {
ctrl, ctrl,
alt, alt,
@ -107,11 +109,25 @@ impl Event {
key: unmodified_chars.into(), key: unmodified_chars.into(),
}, },
input, input,
}) }))
} }
NSEventType::NSLeftMouseDown => { NSEventType::NSLeftMouseDown
| NSEventType::NSRightMouseDown
| NSEventType::NSOtherMouseDown => {
let button = match native_event.buttonNumber() {
0 => MouseButton::Left,
1 => MouseButton::Right,
2 => MouseButton::Middle,
3 => MouseButton::Navigate(NavigationDirection::Back),
4 => MouseButton::Navigate(NavigationDirection::Forward),
// Other mouse buttons aren't tracked currently
_ => return None,
};
let modifiers = native_event.modifierFlags(); let modifiers = native_event.modifierFlags();
window_height.map(|window_height| Self::LeftMouseDown {
window_height.map(|window_height| {
Self::MouseDown(MouseEvent {
button,
position: vec2f( position: vec2f(
native_event.locationInWindow().x as f32, native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32, window_height - native_event.locationInWindow().y as f32,
@ -122,76 +138,25 @@ impl Event {
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask), cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
click_count: native_event.clickCount() as usize, click_count: native_event.clickCount() as usize,
}) })
}
NSEventType::NSLeftMouseUp => window_height.map(|window_height| Self::LeftMouseUp {
position: vec2f(
native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32,
),
click_count: native_event.clickCount() as usize,
}),
NSEventType::NSRightMouseDown => {
let modifiers = native_event.modifierFlags();
window_height.map(|window_height| Self::RightMouseDown {
position: vec2f(
native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32,
),
ctrl: modifiers.contains(NSEventModifierFlags::NSControlKeyMask),
alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask),
shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask),
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
click_count: native_event.clickCount() as usize,
}) })
} }
NSEventType::NSRightMouseUp => window_height.map(|window_height| Self::RightMouseUp { NSEventType::NSLeftMouseUp
position: vec2f( | NSEventType::NSRightMouseUp
native_event.locationInWindow().x as f32, | NSEventType::NSOtherMouseUp => {
window_height - native_event.locationInWindow().y as f32, let button = match native_event.buttonNumber() {
), 0 => MouseButton::Left,
click_count: native_event.clickCount() as usize, 1 => MouseButton::Right,
}), 2 => MouseButton::Middle,
NSEventType::NSOtherMouseDown => { 3 => MouseButton::Navigate(NavigationDirection::Back),
let direction = match native_event.buttonNumber() { 4 => MouseButton::Navigate(NavigationDirection::Forward),
3 => NavigationDirection::Back,
4 => NavigationDirection::Forward,
// Other mouse buttons aren't tracked currently // Other mouse buttons aren't tracked currently
_ => return None, _ => return None,
}; };
window_height.map(|window_height| {
let modifiers = native_event.modifierFlags(); let modifiers = native_event.modifierFlags();
window_height.map(|window_height| Self::NavigateMouseDown { Self::MouseUp(MouseEvent {
position: vec2f( button,
native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32,
),
direction,
ctrl: modifiers.contains(NSEventModifierFlags::NSControlKeyMask),
alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask),
shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask),
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
click_count: native_event.clickCount() as usize,
})
}
NSEventType::NSOtherMouseUp => {
let direction = match native_event.buttonNumber() {
3 => NavigationDirection::Back,
4 => NavigationDirection::Forward,
// Other mouse buttons aren't tracked currently
_ => return None,
};
window_height.map(|window_height| Self::NavigateMouseUp {
position: vec2f(
native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32,
),
direction,
})
}
NSEventType::NSLeftMouseDragged => window_height.map(|window_height| {
let modifiers = native_event.modifierFlags();
Self::LeftMouseDragged {
position: vec2f( position: vec2f(
native_event.locationInWindow().x as f32, native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32, window_height - native_event.locationInWindow().y as f32,
@ -200,9 +165,12 @@ impl Event {
alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask), alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask),
shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask), shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask),
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask), cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
click_count: native_event.clickCount() as usize,
})
})
} }
}), NSEventType::NSScrollWheel => window_height.map(|window_height| {
NSEventType::NSScrollWheel => window_height.map(|window_height| Self::ScrollWheel { Self::ScrollWheel(ScrollWheelEvent {
position: vec2f( position: vec2f(
native_event.locationInWindow().x as f32, native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32, window_height - native_event.locationInWindow().y as f32,
@ -212,20 +180,49 @@ impl Event {
native_event.scrollingDeltaY() as f32, native_event.scrollingDeltaY() as f32,
), ),
precise: native_event.hasPreciseScrollingDeltas() == YES, precise: native_event.hasPreciseScrollingDeltas() == YES,
})
}), }),
NSEventType::NSMouseMoved => window_height.map(|window_height| { NSEventType::NSLeftMouseDragged
| NSEventType::NSRightMouseDragged
| NSEventType::NSOtherMouseDragged => {
let pressed_button = match native_event.buttonNumber() {
0 => MouseButton::Left,
1 => MouseButton::Right,
2 => MouseButton::Middle,
3 => MouseButton::Navigate(NavigationDirection::Back),
4 => MouseButton::Navigate(NavigationDirection::Forward),
// Other mouse buttons aren't tracked currently
_ => return None,
};
window_height.map(|window_height| {
let modifiers = native_event.modifierFlags(); let modifiers = native_event.modifierFlags();
Self::MouseMoved { Self::MouseMoved(MouseMovedEvent {
pressed_button: Some(pressed_button),
position: vec2f( position: vec2f(
native_event.locationInWindow().x as f32, native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32, window_height - native_event.locationInWindow().y as f32,
), ),
left_mouse_down: NSEvent::pressedMouseButtons(nil) & 1 != 0,
ctrl: modifiers.contains(NSEventModifierFlags::NSControlKeyMask), ctrl: modifiers.contains(NSEventModifierFlags::NSControlKeyMask),
alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask), alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask),
shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask), shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask),
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask), cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
})
})
} }
NSEventType::NSMouseMoved => window_height.map(|window_height| {
let modifiers = native_event.modifierFlags();
Self::MouseMoved(MouseMovedEvent {
position: vec2f(
native_event.locationInWindow().x as f32,
window_height - native_event.locationInWindow().y as f32,
),
pressed_button: None,
ctrl: modifiers.contains(NSEventModifierFlags::NSControlKeyMask),
alt: modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask),
shift: modifiers.contains(NSEventModifierFlags::NSShiftKeyMask),
cmd: modifiers.contains(NSEventModifierFlags::NSCommandKeyMask),
})
}), }),
_ => None, _ => None,
} }

View File

@ -6,7 +6,7 @@ use crate::{
}, },
keymap::Keystroke, keymap::Keystroke,
platform::{self, Event, WindowBounds, WindowContext}, platform::{self, Event, WindowBounds, WindowContext},
Scene, KeyDownEvent, ModifiersChangedEvent, MouseButton, MouseEvent, MouseMovedEvent, Scene,
}; };
use block::ConcreteBlock; use block::ConcreteBlock;
use cocoa::{ use cocoa::{
@ -562,11 +562,11 @@ extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) ->
let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) }; let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
if let Some(event) = event { if let Some(event) = event {
match &event { match &event {
Event::KeyDown { Event::KeyDown(KeyDownEvent {
keystroke, keystroke,
input, input,
is_held, is_held,
} => { }) => {
let keydown = (keystroke.clone(), input.clone()); let keydown = (keystroke.clone(), input.clone());
// Ignore events from held-down keys after some of the initially-pressed keys // Ignore events from held-down keys after some of the initially-pressed keys
// were released. // were released.
@ -603,33 +603,41 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
if let Some(event) = event { if let Some(event) = event {
match &event { match &event {
Event::LeftMouseDragged { position, .. } => { Event::MouseMoved(
event @ MouseMovedEvent {
pressed_button: Some(_),
..
},
) => {
window_state_borrow.synthetic_drag_counter += 1; window_state_borrow.synthetic_drag_counter += 1;
window_state_borrow window_state_borrow
.executor .executor
.spawn(synthetic_drag( .spawn(synthetic_drag(
weak_window_state, weak_window_state,
window_state_borrow.synthetic_drag_counter, window_state_borrow.synthetic_drag_counter,
*position, *event,
)) ))
.detach(); .detach();
} }
Event::LeftMouseUp { .. } => { Event::MouseUp(MouseEvent {
button: MouseButton::Left,
..
}) => {
window_state_borrow.synthetic_drag_counter += 1; window_state_borrow.synthetic_drag_counter += 1;
} }
Event::ModifiersChanged { Event::ModifiersChanged(ModifiersChangedEvent {
ctrl, ctrl,
alt, alt,
shift, shift,
cmd, cmd,
} => { }) => {
// Only raise modifiers changed event when they have actually changed // Only raise modifiers changed event when they have actually changed
if let Some(Event::ModifiersChanged { if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
ctrl: prev_ctrl, ctrl: prev_ctrl,
alt: prev_alt, alt: prev_alt,
shift: prev_shift, shift: prev_shift,
cmd: prev_cmd, cmd: prev_cmd,
}) = &window_state_borrow.previous_modifiers_changed_event })) = &window_state_borrow.previous_modifiers_changed_event
{ {
if prev_ctrl == ctrl if prev_ctrl == ctrl
&& prev_alt == alt && prev_alt == alt
@ -667,11 +675,11 @@ extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
shift: false, shift: false,
key: chars.clone(), key: chars.clone(),
}; };
let event = Event::KeyDown { let event = Event::KeyDown(KeyDownEvent {
keystroke: keystroke.clone(), keystroke: keystroke.clone(),
input: Some(chars.clone()), input: Some(chars.clone()),
is_held: false, is_held: false,
}; });
window_state_borrow.last_fresh_keydown = Some((keystroke, Some(chars))); window_state_borrow.last_fresh_keydown = Some((keystroke, Some(chars)));
if let Some(mut callback) = window_state_borrow.event_callback.take() { if let Some(mut callback) = window_state_borrow.event_callback.take() {
@ -835,7 +843,7 @@ extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
async fn synthetic_drag( async fn synthetic_drag(
window_state: Weak<RefCell<WindowState>>, window_state: Weak<RefCell<WindowState>>,
drag_id: usize, drag_id: usize,
position: Vector2F, event: MouseMovedEvent,
) { ) {
loop { loop {
Timer::after(Duration::from_millis(16)).await; Timer::after(Duration::from_millis(16)).await;
@ -844,14 +852,7 @@ async fn synthetic_drag(
if window_state_borrow.synthetic_drag_counter == drag_id { if window_state_borrow.synthetic_drag_counter == drag_id {
if let Some(mut callback) = window_state_borrow.event_callback.take() { if let Some(mut callback) = window_state_borrow.event_callback.take() {
drop(window_state_borrow); drop(window_state_borrow);
callback(Event::LeftMouseDragged { callback(Event::MouseMoved(event));
// TODO: Make sure empty modifiers is correct for this
position,
shift: false,
ctrl: false,
alt: false,
cmd: false,
});
window_state.borrow_mut().event_callback = Some(callback); window_state.borrow_mut().event_callback = Some(callback);
} }
} else { } else {

View File

@ -9,9 +9,9 @@ use crate::{
scene::CursorRegion, scene::CursorRegion,
text_layout::TextLayoutCache, text_layout::TextLayoutCache,
Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity, Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
FontSystem, ModelHandle, MouseRegion, MouseRegionId, ReadModel, ReadView, RenderContext, FontSystem, ModelHandle, MouseButton, MouseEvent, MouseMovedEvent, MouseRegion, MouseRegionId,
RenderParams, Scene, UpgradeModelHandle, UpgradeViewHandle, View, ViewHandle, WeakModelHandle, ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle, UpgradeViewHandle,
WeakViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
}; };
use pathfinder_geometry::vector::{vec2f, Vector2F}; use pathfinder_geometry::vector::{vec2f, Vector2F};
use serde_json::json; use serde_json::json;
@ -235,7 +235,11 @@ impl Presenter {
let mut dragged_region = None; let mut dragged_region = None;
match event { match event {
Event::LeftMouseDown { position, .. } => { Event::MouseDown(MouseEvent {
position,
button: MouseButton::Left,
..
}) => {
let mut hit = false; let mut hit = false;
for (region, _) in self.mouse_regions.iter().rev() { for (region, _) in self.mouse_regions.iter().rev() {
if region.bounds.contains_point(position) { if region.bounds.contains_point(position) {
@ -251,11 +255,12 @@ impl Presenter {
} }
} }
} }
Event::LeftMouseUp { Event::MouseUp(MouseEvent {
position, position,
click_count, click_count,
button: MouseButton::Left,
.. ..
} => { }) => {
self.prev_drag_position.take(); self.prev_drag_position.take();
if let Some(region) = self.clicked_region.take() { if let Some(region) = self.clicked_region.take() {
invalidated_views.push(region.view_id); invalidated_views.push(region.view_id);
@ -264,7 +269,11 @@ impl Presenter {
} }
} }
} }
Event::RightMouseDown { position, .. } => { Event::MouseDown(MouseEvent {
position,
button: MouseButton::Right,
..
}) => {
let mut hit = false; let mut hit = false;
for (region, _) in self.mouse_regions.iter().rev() { for (region, _) in self.mouse_regions.iter().rev() {
if region.bounds.contains_point(position) { if region.bounds.contains_point(position) {
@ -279,11 +288,12 @@ impl Presenter {
} }
} }
} }
Event::RightMouseUp { Event::MouseUp(MouseEvent {
position, position,
click_count, click_count,
button: MouseButton::Right,
.. ..
} => { }) => {
if let Some(region) = self.right_clicked_region.take() { if let Some(region) = self.right_clicked_region.take() {
invalidated_views.push(region.view_id); invalidated_views.push(region.view_id);
if region.bounds.contains_point(position) { if region.bounds.contains_point(position) {
@ -291,16 +301,16 @@ impl Presenter {
} }
} }
} }
Event::MouseMoved { .. } => { Event::MouseMoved(MouseMovedEvent {
self.last_mouse_moved_event = Some(event.clone()); pressed_button,
}
Event::LeftMouseDragged {
position, position,
shift, shift,
ctrl, ctrl,
alt, alt,
cmd, cmd,
} => { ..
}) => {
if let Some(MouseButton::Left) = pressed_button {
if let Some((clicked_region, prev_drag_position)) = self if let Some((clicked_region, prev_drag_position)) = self
.clicked_region .clicked_region
.as_ref() .as_ref()
@ -311,14 +321,17 @@ impl Presenter {
*prev_drag_position = position; *prev_drag_position = position;
} }
self.last_mouse_moved_event = Some(Event::MouseMoved { self.last_mouse_moved_event = Some(Event::MouseMoved(MouseMovedEvent {
position, position,
left_mouse_down: true, pressed_button: Some(MouseButton::Left),
shift, shift,
ctrl, ctrl,
alt, alt,
cmd, cmd,
}); }));
}
self.last_mouse_moved_event = Some(event.clone());
} }
_ => {} _ => {}
} }
@ -410,13 +423,13 @@ impl Presenter {
let mut unhovered_regions = Vec::new(); let mut unhovered_regions = Vec::new();
let mut hovered_regions = Vec::new(); let mut hovered_regions = Vec::new();
if let Event::MouseMoved { if let Event::MouseMoved(MouseMovedEvent {
position, position,
left_mouse_down, pressed_button,
.. ..
} = event }) = event
{ {
if !left_mouse_down { if let None = pressed_button {
let mut style_to_assign = CursorStyle::Arrow; let mut style_to_assign = CursorStyle::Arrow;
for region in self.cursor_regions.iter().rev() { for region in self.cursor_regions.iter().rev() {
if region.bounds.contains_point(*position) { if region.bounds.contains_point(*position) {

View File

@ -8,7 +8,7 @@ use crate::{
geometry::{rect::RectF, vector::Vector2F}, geometry::{rect::RectF, vector::Vector2F},
json::ToJson, json::ToJson,
platform::CursorStyle, platform::CursorStyle,
EventContext, ImageData, EventContext, ImageData, MouseEvent, MouseMovedEvent, ScrollWheelEvent,
}; };
pub struct Scene { pub struct Scene {
@ -44,11 +44,22 @@ pub struct CursorRegion {
pub style: CursorStyle, pub style: CursorStyle,
} }
pub enum MouseRegionEvent {
Moved(MouseMovedEvent),
Hover(MouseEvent),
Down(MouseEvent),
Up(MouseEvent),
Click(MouseEvent),
DownOut(MouseEvent),
ScrollWheel(ScrollWheelEvent),
}
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct MouseRegion { pub struct MouseRegion {
pub view_id: usize, pub view_id: usize,
pub discriminant: Option<(TypeId, usize)>, pub discriminant: Option<(TypeId, usize)>,
pub bounds: RectF, pub bounds: RectF,
pub hover: Option<Rc<dyn Fn(Vector2F, bool, &mut EventContext)>>, pub hover: Option<Rc<dyn Fn(Vector2F, bool, &mut EventContext)>>,
pub mouse_down: Option<Rc<dyn Fn(Vector2F, &mut EventContext)>>, pub mouse_down: Option<Rc<dyn Fn(Vector2F, &mut EventContext)>>,
pub click: Option<Rc<dyn Fn(Vector2F, usize, &mut EventContext)>>, pub click: Option<Rc<dyn Fn(Vector2F, usize, &mut EventContext)>>,

View File

@ -18,8 +18,8 @@ use gpui::{
}, },
json::json, json::json,
text_layout::{Line, RunStyle}, text_layout::{Line, RunStyle},
Event, FontCache, MouseRegion, PaintContext, Quad, SizeConstraint, TextLayoutCache, Event, FontCache, KeyDownEvent, MouseRegion, PaintContext, Quad, ScrollWheelEvent,
WeakViewHandle, SizeConstraint, TextLayoutCache, WeakViewHandle,
}; };
use itertools::Itertools; use itertools::Itertools;
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
@ -276,9 +276,9 @@ impl Element for TerminalEl {
cx: &mut gpui::EventContext, cx: &mut gpui::EventContext,
) -> bool { ) -> bool {
match event { match event {
Event::ScrollWheel { Event::ScrollWheel(ScrollWheelEvent {
delta, position, .. delta, position, ..
} => visible_bounds }) => visible_bounds
.contains_point(*position) .contains_point(*position)
.then(|| { .then(|| {
let vertical_scroll = let vertical_scroll =
@ -286,9 +286,9 @@ impl Element for TerminalEl {
cx.dispatch_action(ScrollTerminal(vertical_scroll.round() as i32)); cx.dispatch_action(ScrollTerminal(vertical_scroll.round() as i32));
}) })
.is_some(), .is_some(),
Event::KeyDown { Event::KeyDown(KeyDownEvent {
input: Some(input), .. input: Some(input), ..
} => cx }) => cx
.is_parent_view_focused() .is_parent_view_focused()
.then(|| { .then(|| {
cx.dispatch_action(Input(input.to_string())); cx.dispatch_action(Input(input.to_string()));