Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

On Windows, Add HitTest event (rebased) #3207

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Unreleased` header.
# Unreleased

- On Windows, fix so `drag_window` and `drag_resize_window` can be called from another thread.
- On Windows, add `HitTest` event.

# 0.29.3

Expand Down
58 changes: 58 additions & 0 deletions examples/hit_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#![allow(clippy::single_match)]

use simple_logger::SimpleLogger;
use winit::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{WindowArea, WindowBuilder},
};

fn main() {
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new().unwrap();

let window = WindowBuilder::new()
.with_title("A fantastic window!")
.with_inner_size(winit::dpi::LogicalSize::new(400.0, 400.0))
.with_decorations(false)
.build(&event_loop)
.unwrap();

let _ = event_loop.run(move |event, elwt| {
elwt.set_control_flow(ControlFlow::Wait);

match event {
Event::NewEvents(StartCause::Init) => {
eprintln!("Click on window edges to start resizing. Click anywhere in the top 30px to start dragging the window.")
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
window_id,
} if window_id == window.id() => elwt.exit(),
Event::WindowEvent {
event: WindowEvent::HitTest{ x, y, new_area_writer},
..
} => {
let size = window.inner_size();
let h = size.height;
let w = size.width;

const MARGIN: u32 = 30;

let _ = new_area_writer.request_area(match (x, y) {
_ if x <= MARGIN && y <= MARGIN => WindowArea::TOPLEFT,
_ if x >= w - MARGIN && y <= MARGIN => WindowArea::TOPRIGHT,
_ if x >= w - MARGIN && y >= h - MARGIN => WindowArea::BOTTOMRIGHT,
_ if x <= MARGIN && y >= h - MARGIN => WindowArea::BOTTOMLEFT,
_ if x <= MARGIN => WindowArea::LEFT,
_ if y <= MARGIN => WindowArea::TOP,
_ if x >= w - MARGIN => WindowArea::RIGHT,
_ if y >= h - MARGIN => WindowArea::BOTTOM,
(_, 30..=100) => WindowArea::CAPTION,
_ => WindowArea::CLIENT,
});
}
_ => (),
}
});
}
43 changes: 42 additions & 1 deletion src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ use crate::{
event_loop::AsyncRequestSerial,
keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState},
platform_impl,
window::{ActivationToken, Theme, WindowId},
window::{ActivationToken, Theme, WindowArea, WindowId},
};

/// Describes a generic event.
Expand Down Expand Up @@ -591,6 +591,25 @@ pub enum WindowEvent {
/// Winit will aggregate duplicate redraw requests into a single event, to
/// help avoid duplicating rendering work.
RedrawRequested,

/// Sent to a window in order to determine what part of the window corresponds to a particular screen coordinate.
/// This can happen, for example, when the cursor moves, when a mouse button is pressed or released.
///
/// - `x` and `y` are relatvie to the window top-left corner.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// - `x` and `y` are relatvie to the window top-left corner.
/// - `x` and `y` are relative to the window top-left corner.

///
/// After this event callback has been processed, the response will be whatever value
/// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested
/// by the OS, but it can be changed to any value.
///
/// ## Platform-specific
///
/// - **X11 / Wayland / macOS:** Not implemented.
/// - **iOS / Android :** Unsupported.
HitTest {
x: u32,
y: u32,
new_area_writer: NewAreaWriter,
},
}

/// Identifier of an input device.
Expand Down Expand Up @@ -1140,6 +1159,28 @@ impl PartialEq for InnerSizeWriter {
}
}

#[derive(Debug, Clone)]
pub struct NewAreaWriter {
pub(crate) new_area: Weak<Mutex<WindowArea>>,
}

impl NewAreaWriter {
pub fn request_area(&self, new_area: WindowArea) -> Result<(), ExternalError> {
if let Some(inner) = self.new_area.upgrade() {
*inner.lock().unwrap() = new_area;
Ok(())
} else {
Err(ExternalError::Ignored)
}
}
}

impl PartialEq for NewAreaWriter {
fn eq(&self, other: &Self) -> bool {
self.new_area.as_ptr() == other.new_area.as_ptr()
}
}

#[cfg(test)]
mod tests {
use crate::event;
Expand Down
114 changes: 105 additions & 9 deletions src/platform_impl/windows/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,18 @@ use windows_sys::Win32::{
GetCursorPos, GetMenu, GetMessageW, KillTimer, LoadCursorW, PeekMessageW, PostMessageW,
RegisterClassExW, RegisterWindowMessageA, SetCursor, SetTimer, SetWindowPos,
TranslateMessage, CREATESTRUCTW, GIDC_ARRIVAL, GIDC_REMOVAL, GWL_STYLE, GWL_USERDATA,
HTCAPTION, HTCLIENT, MINMAXINFO, MNC_CLOSE, MSG, NCCALCSIZE_PARAMS, PM_REMOVE, PT_PEN,
PT_TOUCH, RI_KEY_E0, RI_KEY_E1, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE,
SC_RESTORE, SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER,
WHEEL_DELTA, WINDOWPOS, WM_CAPTURECHANGED, WM_CLOSE, WM_CREATE, WM_DESTROY,
WM_DPICHANGED, WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION,
HTBORDER, HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTCLIENT, HTCLOSE, HTERROR,
HTHELP, HTHSCROLL, HTLEFT, HTMAXBUTTON, HTMENU, HTMINBUTTON, HTNOWHERE, HTREDUCE,
HTRIGHT, HTSIZE, HTSYSMENU, HTTOP, HTTOPLEFT, HTTOPRIGHT, HTTRANSPARENT, HTVSCROLL,
HTZOOM, MINMAXINFO, MNC_CLOSE, MSG, NCCALCSIZE_PARAMS, PM_REMOVE, PT_PEN, PT_TOUCH,
RI_KEY_E0, RI_KEY_E1, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE,
SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA,
WINDOWPOS, WM_CAPTURECHANGED, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED,
WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION,
WM_IME_ENDCOMPOSITION, WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT,
WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN,
WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MENUCHAR, WM_MOUSEHWHEEL, WM_MOUSEMOVE,
WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, WM_NCCREATE, WM_NCDESTROY,
WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, WM_NCCREATE, WM_NCDESTROY, WM_NCHITTEST,
WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN, WM_POINTERUP, WM_POINTERUPDATE,
WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS, WM_SETTINGCHANGE, WM_SIZE,
WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH, WM_WINDOWPOSCHANGED,
Expand All @@ -76,8 +79,8 @@ use crate::{
dpi::{PhysicalPosition, PhysicalSize},
error::EventLoopError,
event::{
DeviceEvent, Event, Force, Ime, InnerSizeWriter, RawKeyEvent, Touch, TouchPhase,
WindowEvent,
DeviceEvent, Event, Force, Ime, InnerSizeWriter, NewAreaWriter, RawKeyEvent, Touch,
TouchPhase, WindowEvent,
},
event_loop::{ControlFlow, DeviceEvents, EventLoopClosed, EventLoopWindowTarget as RootELW},
keyboard::{KeyCode, ModifiersState, PhysicalKey},
Expand All @@ -95,7 +98,7 @@ use crate::{
window_state::{CursorFlags, ImeState, WindowFlags, WindowState},
wrap_device_id, Fullscreen, WindowId, DEVICE_ID,
},
window::WindowId as RootWindowId,
window::{WindowArea, WindowId as RootWindowId},
};
use runner::{EventLoopRunner, EventLoopRunnerShared};

Expand Down Expand Up @@ -2296,6 +2299,35 @@ unsafe fn public_window_callback_inner<T: 'static>(
result = ProcResult::DefWindowProc(wparam);
}

WM_NCHITTEST => {
use crate::event::WindowEvent::HitTest;

let x = super::get_x_lparam(lparam as u32) as i32;
let y = super::get_y_lparam(lparam as u32) as i32;

let mut pt = POINT { x, y };
unsafe { ScreenToClient(window, &mut pt) };

let default = unsafe { DefWindowProcW(window, msg, wparam, lparam) };
let area = Arc::new(Mutex::new(WindowArea::from_wm_nchittesst(default)));

userdata.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window)),
event: HitTest {
x: pt.x as u32,
y: pt.y as u32,
new_area_writer: NewAreaWriter {
new_area: Arc::downgrade(&area),
},
},
});

let area_received = *area.lock().unwrap();
drop(area);

result = ProcResult::Value(area_received.to_wm_nchittest())
}

_ => {
if msg == DESTROY_MSG_ID.get() {
unsafe { DestroyWindow(window) };
Expand Down Expand Up @@ -2630,3 +2662,67 @@ fn get_pointer_move_kind(
PointerMoveKind::None
}
}

impl WindowArea {
fn from_wm_nchittesst(m: isize) -> Self {
match m {
m if m == HTCAPTION as isize => Self::CAPTION,
m if m == HTBORDER as isize => Self::BORDER,
m if m == HTBOTTOM as isize => Self::BOTTOM,
m if m == HTBOTTOMLEFT as isize => Self::BOTTOMLEFT,
m if m == HTBOTTOMRIGHT as isize => Self::BOTTOMRIGHT,
m if m == HTCAPTION as isize => Self::CAPTION,
m if m == HTCLIENT as isize => Self::CLIENT,
m if m == HTCLOSE as isize => Self::CLOSE,
m if m == HTERROR as isize => Self::ERROR,
m if m == HTHELP as isize => Self::HELP,
m if m == HTHSCROLL as isize => Self::HSCROLL,
m if m == HTLEFT as isize => Self::LEFT,
m if m == HTMENU as isize => Self::MENU,
m if m == HTMAXBUTTON as isize => Self::MAXBUTTON,
m if m == HTMINBUTTON as isize => Self::MINBUTTON,
m if m == HTNOWHERE as isize => Self::NOWHERE,
m if m == HTREDUCE as isize => Self::REDUCE,
m if m == HTRIGHT as isize => Self::RIGHT,
m if m == HTSIZE as isize => Self::SIZE,
m if m == HTSYSMENU as isize => Self::SYSMENU,
m if m == HTTOP as isize => Self::TOP,
m if m == HTTOPLEFT as isize => Self::TOPLEFT,
m if m == HTTOPRIGHT as isize => Self::TOPRIGHT,
m if m == HTTRANSPARENT as isize => Self::TRANSPARENT,
m if m == HTVSCROLL as isize => Self::VSCROLL,
m if m == HTZOOM as isize => Self::ZOOM,
_ => Self::CLIENT,
}
}

fn to_wm_nchittest(self) -> isize {
match self {
Self::BORDER => HTBORDER as isize,
Self::BOTTOM => HTBOTTOM as isize,
Self::BOTTOMLEFT => HTBOTTOMLEFT as isize,
Self::BOTTOMRIGHT => HTBOTTOMRIGHT as isize,
Self::CAPTION => HTCAPTION as isize,
Self::CLIENT => HTCLIENT as isize,
Self::CLOSE => HTCLOSE as isize,
Self::ERROR => HTERROR as isize,
Self::HELP => HTHELP as isize,
Self::HSCROLL => HTHSCROLL as isize,
Self::LEFT => HTLEFT as isize,
Self::MENU => HTMENU as isize,
Self::MAXBUTTON => HTMAXBUTTON as isize,
Self::MINBUTTON => HTMINBUTTON as isize,
Self::NOWHERE => HTNOWHERE as isize,
Self::REDUCE => HTREDUCE as isize,
Self::RIGHT => HTRIGHT as isize,
Self::SIZE => HTSIZE as isize,
Self::SYSMENU => HTSYSMENU as isize,
Self::TOP => HTTOP as isize,
Self::TOPLEFT => HTTOPLEFT as isize,
Self::TOPRIGHT => HTTOPRIGHT as isize,
Self::TRANSPARENT => HTTRANSPARENT as isize,
Self::VSCROLL => HTVSCROLL as isize,
Self::ZOOM => HTZOOM as isize,
}
}
}
54 changes: 54 additions & 0 deletions src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1754,3 +1754,57 @@ impl ActivationToken {
Self { _token }
}
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum WindowArea {
/// In the border of a window that does not have a sizing border.
BORDER,
/// In the lower-horizontal border of a resizable window (the user can click the mouse to resize the window vertically).
BOTTOM,
/// In the lower-left corner of a border of a resizable window (the user can click the mouse to resize the window diagonally).
BOTTOMLEFT,
/// In the lower-right corner of a border of a resizable window (the user can click the mouse to resize the window diagonally).
BOTTOMRIGHT,
/// In a title bar.
CAPTION,
/// In a client area.
CLIENT,
/// In a Close button.
CLOSE,
/// On the screen background or on a dividing line between windows (same as HTNOWHERE, except that it produces a system beep to indicate an error).
ERROR,
/// In a Help button.
HELP,
/// In a horizontal scroll bar.
HSCROLL,
/// In the left border of a resizable window (the user can click the mouse to resize the window horizontally).
LEFT,
/// In a menu.
MENU,
/// In a Maximize button.
MAXBUTTON,
/// In a Minimize button.
MINBUTTON,
/// On the screen background or on a dividing line between windows.
NOWHERE,
/// In a Minimize button.
REDUCE,
/// In the right border of a resizable window (the user can click the mouse to resize the window horizontally).
RIGHT,
/// In a size box.
SIZE,
/// In a window menu or in a Close button in a child window.
SYSMENU,
/// In the upper-horizontal border of a window.
TOP,
/// In the upper-left corner of a window border.
TOPLEFT,
/// In the upper-right corner of a window border.
TOPRIGHT,
/// In a window currently covered by another window in the same thread.
TRANSPARENT,
/// In the vertical scroll bar.
VSCROLL,
/// In a Maximize button.
ZOOM,
}