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

Rework DnD #2615

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 10 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ And please only add new entries to the top of this list, right below the `# Unre

# Unreleased

- **Breaking:** Add cursor position to `WindowEvent::DroppedFile` and `WindowEvent::HoveredFile` events.
- On X11, fix errors handled during `register_xlib_error_hook` invocation bleeding into winit.
- Add `Window::has_focus`.
- On Windows, fix `Window::set_minimized(false)` not working for windows minimized by `Win + D` hotkey.
Expand Down
6 changes: 5 additions & 1 deletion examples/window_icon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ fn main() {
use winit::event::WindowEvent::*;
match event {
CloseRequested => control_flow.set_exit(),
DroppedFile(path) => {
HoveredFile { position, .. } => {
dbg!("Hovered", position);
}
DroppedFile { path, position } => {
dbg!("Dropped", position);
window.set_window_icon(Some(load_icon(&path)));
}
_ => (),
Expand Down
26 changes: 20 additions & 6 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,13 +337,21 @@ pub enum WindowEvent<'a> {
///
/// When the user drops multiple files at once, this event will be emitted for each file
/// separately.
DroppedFile(PathBuf),
DroppedFile {
path: PathBuf,
/// The position of the mouse cursor, similar to [`WindowEvent::CursorMoved`].
position: PhysicalPosition<f64>,
},

/// A file is being hovered over the window.
///
/// When the user hovers multiple files at once, this event will be emitted for each file
/// separately.
HoveredFile(PathBuf),
HoveredFile {
path: PathBuf,
/// The position of the mouse cursor, similar to [`WindowEvent::CursorMoved`].
position: PhysicalPosition<f64>,
},

/// A file was hovered, but has exited the window.
///
Expand Down Expand Up @@ -529,8 +537,14 @@ impl Clone for WindowEvent<'static> {
Moved(pos) => Moved(*pos),
CloseRequested => CloseRequested,
Destroyed => Destroyed,
DroppedFile(file) => DroppedFile(file.clone()),
HoveredFile(file) => HoveredFile(file.clone()),
DroppedFile { path, position } => DroppedFile {
path: path.clone(),
position: *position,
},
HoveredFile { path, position } => HoveredFile {
path: path.clone(),
position: *position,
},
HoveredFileCancelled => HoveredFileCancelled,
ReceivedCharacter(c) => ReceivedCharacter(*c),
Focused(f) => Focused(*f),
Expand Down Expand Up @@ -639,8 +653,8 @@ impl<'a> WindowEvent<'a> {
Moved(position) => Some(Moved(position)),
CloseRequested => Some(CloseRequested),
Destroyed => Some(Destroyed),
DroppedFile(file) => Some(DroppedFile(file)),
HoveredFile(file) => Some(HoveredFile(file)),
DroppedFile { path, position } => Some(DroppedFile { path, position }),
HoveredFile { path, position } => Some(HoveredFile { path, position }),
HoveredFileCancelled => Some(HoveredFileCancelled),
ReceivedCharacter(c) => Some(ReceivedCharacter(c)),
Focused(focused) => Some(Focused(focused)),
Expand Down
3 changes: 3 additions & 0 deletions src/platform_impl/linux/x11/dnd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ pub(crate) struct Dnd {
pub type_list: Option<Vec<c_ulong>>,
// Populated by XdndPosition event handler
pub source_window: Option<c_ulong>,
// Populated by XdndPosition event handler
pub position: (c_long, c_long),
// Populated by SelectionNotify event handler (triggered by XdndPosition event handler)
pub result: Option<Result<Vec<PathBuf>, DndDataParseError>>,
}
Expand All @@ -105,6 +107,7 @@ impl Dnd {
version: None,
type_list: None,
source_window: None,
position: (0, 0),
result: None,
})
}
Expand Down
47 changes: 41 additions & 6 deletions src/platform_impl/linux/x11/event_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,11 @@ impl<T: 'static> EventProcessor<T> {
// where `shift = mem::size_of::<c_short>() * 8`
// Note that coordinates are in "desktop space", not "window space"
// (in X11 parlance, they're root window coordinates)
//let packed_coordinates = client_msg.data.get_long(2);
//let shift = mem::size_of::<libc::c_short>() * 8;
//let x = packed_coordinates >> shift;
//let y = packed_coordinates & !(x << shift);
let packed_coordinates = client_msg.data.get_long(2);
let shift = std::mem::size_of::<libc::c_short>() * 8;
let x = packed_coordinates >> shift;
let y = packed_coordinates & !(x << shift);
self.dnd.position = (x, y);

// By our own state flow, `version` should never be `None` at this point.
let version = self.dnd.version.unwrap_or(5);
Expand Down Expand Up @@ -274,10 +275,26 @@ impl<T: 'static> EventProcessor<T> {
let (source_window, state) = if let Some(source_window) = self.dnd.source_window
{
if let Some(Ok(ref path_list)) = self.dnd.result {
let coords = wt
.xconn
.translate_coords(
source_window,
window,
self.dnd.position.0 as _,
self.dnd.position.1 as _,
)
.expect("Failed to translate window coordinates");

let position =
PhysicalPosition::new(coords.x_rel as f64, coords.y_rel as f64);

for path in path_list {
callback(Event::WindowEvent {
window_id,
event: WindowEvent::DroppedFile(path.clone()),
event: WindowEvent::DroppedFile {
path: path.clone(),
position,
},
});
}
}
Expand Down Expand Up @@ -316,10 +333,28 @@ impl<T: 'static> EventProcessor<T> {
if let Ok(mut data) = unsafe { self.dnd.read_data(window) } {
let parse_result = self.dnd.parse_data(&mut data);
if let Ok(ref path_list) = parse_result {
let source_window = self.dnd.source_window.unwrap_or(wt.root);

let coords = wt
.xconn
.translate_coords(
source_window,
window,
self.dnd.position.0 as _,
self.dnd.position.1 as _,
)
.expect("Failed to translate window coordinates");

let position =
PhysicalPosition::new(coords.x_rel as f64, coords.y_rel as f64);

for path in path_list {
callback(Event::WindowEvent {
window_id,
event: WindowEvent::HoveredFile(path.clone()),
event: WindowEvent::HoveredFile {
path: path.clone(),
position,
},
});
}
}
Expand Down
46 changes: 36 additions & 10 deletions src/platform_impl/linux/x11/util/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ impl AaRect {

#[derive(Debug, Default)]
pub struct TranslatedCoords {
pub x_rel_root: c_int,
pub y_rel_root: c_int,
pub x_rel: c_int,
pub y_rel: c_int,
pub child: ffi::Window,
}

Expand Down Expand Up @@ -142,7 +142,7 @@ impl FrameExtentsHeuristic {

impl XConnection {
// This is adequate for inner_position
pub fn translate_coords(
pub fn translate_coords_root(
&self,
window: ffi::Window,
root: ffi::Window,
Expand All @@ -156,8 +156,34 @@ impl XConnection {
root,
0,
0,
&mut coords.x_rel_root,
&mut coords.y_rel_root,
&mut coords.x_rel,
&mut coords.y_rel,
&mut coords.child,
);
}

self.check_errors()?;
Ok(coords)
}

pub fn translate_coords(
&self,
src_w: ffi::Window,
dest_w: ffi::Window,
src_x: i32,
src_y: i32,
) -> Result<TranslatedCoords, XError> {
let mut coords = TranslatedCoords::default();

unsafe {
(self.xlib.XTranslateCoordinates)(
self.display,
src_w,
dest_w,
src_x,
src_y,
&mut coords.x_rel,
&mut coords.y_rel,
&mut coords.child,
amrbashir marked this conversation as resolved.
Show resolved Hide resolved
);
}
Expand Down Expand Up @@ -284,11 +310,11 @@ impl XConnection {
// With rare exceptions, this is the position of a nested window. Cases where the window
// isn't nested are outlined in the comments throghout this function, but in addition to
// that, fullscreen windows often aren't nested.
let (inner_y_rel_root, child) = {
let (inner_y_rel, child) = {
let coords = self
.translate_coords(window, root)
.translate_coords_root(window, root)
.expect("Failed to translate window coordinates");
(coords.y_rel_root, coords.child)
(coords.y_rel, coords.child)
};

let (width, height, border) = {
Expand Down Expand Up @@ -331,7 +357,7 @@ impl XConnection {
// having a position (-10, -8).
// * Compiz has a drop shadow margin just like Mutter/Muffin/Budgie, though it's 10px
// on all sides, and there's no additional border.
// * Enlightenment otherwise gets a y position equivalent to inner_y_rel_root.
// * Enlightenment otherwise gets a y position equivalent to inner_y_rel.
// Without decorations, there's no difference. This is presumably related to
// Enlightenment's fairly unique concept of window position; it interprets
// positions given to XMoveWindow as a client area position rather than a position
Expand Down Expand Up @@ -363,7 +389,7 @@ impl XConnection {
// area, we can figure out what's in between.
let diff_x = outer_width.saturating_sub(width);
let diff_y = outer_height.saturating_sub(height);
let offset_y = inner_y_rel_root.saturating_sub(outer_y) as c_uint;
let offset_y = inner_y_rel.saturating_sub(outer_y) as c_uint;

let left = diff_x / 2;
let right = left;
Expand Down
4 changes: 2 additions & 2 deletions src/platform_impl/linux/x11/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1066,8 +1066,8 @@ impl UnownedWindow {
// This should be okay to unwrap since the only error XTranslateCoordinates can return
// is BadWindow, and if the window handle is bad we have bigger problems.
self.xconn
.translate_coords(self.xwindow, self.root)
.map(|coords| (coords.x_rel_root, coords.y_rel_root))
.translate_coords_root(self.xwindow, self.root)
.map(|coords| (coords.x_rel, coords.y_rel))
.unwrap()
}

Expand Down
24 changes: 21 additions & 3 deletions src/platform_impl/macos/window_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::ptr;

use objc2::declare::{Ivar, IvarDrop};
use objc2::foundation::{NSArray, NSObject, NSString};
use objc2::foundation::{NSArray, NSObject, NSPoint, NSRect, NSString};
use objc2::rc::{autoreleasepool, Id, Shared};
use objc2::runtime::Object;
use objc2::{class, declare_class, msg_send, msg_send_id, sel, ClassType};
Expand Down Expand Up @@ -172,9 +172,18 @@ declare_class!(
let filenames = pb.propertyListForType(unsafe { NSFilenamesPboardType });
let filenames: Id<NSArray<NSString>, Shared> = unsafe { Id::cast(filenames) };

let dl: NSPoint = unsafe { msg_send![sender, draggingLocation] };
let rect = NSRect {
origin: dl,
..Default::default()
};
let y = util::bottom_left_to_top_left(rect);
let scale_factor = self.window.scale_factor();
let position = LogicalPosition::<f64>::from((dl.x, y)).to_physical(scale_factor);
amrbashir marked this conversation as resolved.
Show resolved Hide resolved

filenames.into_iter().for_each(|file| {
let path = PathBuf::from(file.to_string());
self.emit_event(WindowEvent::HoveredFile(path));
self.emit_event(WindowEvent::HoveredFile { path, position });
});

true
Expand All @@ -198,9 +207,18 @@ declare_class!(
let filenames = pb.propertyListForType(unsafe { NSFilenamesPboardType });
let filenames: Id<NSArray<NSString>, Shared> = unsafe { Id::cast(filenames) };

let dl: NSPoint = unsafe { msg_send![sender, draggingLocation] };
let rect = NSRect {
origin: dl,
..Default::default()
};
let y = util::bottom_left_to_top_left(rect);
let scale_factor = self.window.scale_factor();
let position = LogicalPosition::<f64>::from((dl.x, y)).to_physical(scale_factor);

filenames.into_iter().for_each(|file| {
let path = PathBuf::from(file.to_string());
self.emit_event(WindowEvent::DroppedFile(path));
self.emit_event(WindowEvent::DroppedFile { path, position });
});

true
Expand Down
6 changes: 3 additions & 3 deletions src/platform_impl/windows/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,21 @@ pub struct IDropTargetVtbl {
This: *mut IDropTarget,
pDataObj: *const IDataObject,
grfKeyState: u32,
pt: *const POINTL,
pt: POINTL,
pdwEffect: *mut u32,
) -> HRESULT,
pub DragOver: unsafe extern "system" fn(
This: *mut IDropTarget,
grfKeyState: u32,
pt: *const POINTL,
pt: POINTL,
pdwEffect: *mut u32,
) -> HRESULT,
pub DragLeave: unsafe extern "system" fn(This: *mut IDropTarget) -> HRESULT,
pub Drop: unsafe extern "system" fn(
This: *mut IDropTarget,
pDataObj: *const IDataObject,
grfKeyState: u32,
pt: *const POINTL,
pt: POINTL,
pdwEffect: *mut u32,
) -> HRESULT,
}
Expand Down
Loading