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

add drag n drop support to x11 #187

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ raw-window-handle = "0.5"
x11rb = { version = "0.13.0", features = ["cursor", "resource_manager", "allow-unsafe-code"] }
x11 = { version = "2.21", features = ["xlib", "xlib_xcb"] }
nix = "0.22.0"
percent-encoding = "2.3.1"
bytemuck = "1.15.0"

[target.'cfg(target_os="windows")'.dependencies]
winapi = { version = "0.3.8", features = ["libloaderapi", "winuser", "windef", "minwindef", "guiddef", "combaseapi", "wingdi", "errhandlingapi", "ole2", "oleidl", "shellapi", "winerror"] }
Expand Down
7 changes: 6 additions & 1 deletion examples/render_femtovg/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ impl WindowHandler for FemtovgExample {
self.canvas.set_size(phy_size.width, phy_size.height, size.scale() as f32);
self.damaged = true;
}
Event::Mouse(MouseEvent::CursorMoved { position, .. }) => {
Event::Mouse(
MouseEvent::CursorMoved { position, .. }
| MouseEvent::DragEntered { position, .. }
| MouseEvent::DragMoved { position, .. }
| MouseEvent::DragDropped { position, .. },
) => {
self.current_mouse_position = position.to_physical(&self.current_size);
self.damaged = true;
}
Expand Down
615 changes: 615 additions & 0 deletions src/x11/drag_n_drop.rs

Large diffs are not rendered by default.

58 changes: 54 additions & 4 deletions src/x11/event_loop.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::x11::drag_n_drop::DragNDropState;
use crate::x11::keyboard::{convert_key_press_event, convert_key_release_event, key_mods};
use crate::x11::{ParentHandle, Window, WindowInner};
use crate::{
Expand All @@ -18,6 +19,8 @@ pub(super) struct EventLoop {
new_physical_size: Option<PhySize>,
frame_interval: Duration,
event_loop_running: bool,

drag_n_drop: DragNDropState,
}

impl EventLoop {
Expand All @@ -32,6 +35,7 @@ impl EventLoop {
frame_interval: Duration::from_millis(15),
event_loop_running: false,
new_physical_size: None,
drag_n_drop: DragNDropState::NoCurrentSession,
}
}

Expand Down Expand Up @@ -155,14 +159,60 @@ impl EventLoop {
// window
////
XEvent::ClientMessage(event) => {
if event.format == 32
&& event.data.as_data32()[0]
== self.window.xcb_connection.atoms.WM_DELETE_WINDOW
{
if event.format != 32 {
return;
}

if event.data.as_data32()[0] == self.window.xcb_connection.atoms.WM_DELETE_WINDOW {
self.handle_close_requested();
return;
}

////
// drag n drop
////
if event.type_ == self.window.xcb_connection.atoms.XdndEnter {
if let Err(_e) = self.drag_n_drop.handle_enter_event(
&self.window,
&mut *self.handler,
&event,
) {
// TODO: log warning
}
} else if event.type_ == self.window.xcb_connection.atoms.XdndPosition {
if let Err(_e) = self.drag_n_drop.handle_position_event(
&self.window,
&mut *self.handler,
&event,
) {
// TODO: log warning
}
} else if event.type_ == self.window.xcb_connection.atoms.XdndDrop {
if let Err(_e) =
self.drag_n_drop.handle_drop_event(&self.window, &mut *self.handler, &event)
{
// TODO: log warning
}
} else if event.type_ == self.window.xcb_connection.atoms.XdndLeave {
self.drag_n_drop.handle_leave_event(&self.window, &mut *self.handler, &event);
}
}

XEvent::SelectionNotify(event) => {
if event.property == self.window.xcb_connection.atoms.XdndSelection {
if let Err(_e) = self.drag_n_drop.handle_selection_notify_event(
&self.window,
&mut *self.handler,
&event,
) {
// TODO: Log warning
}
}
}

////
// window resize
////
XEvent::ConfigureNotify(event) => {
let new_physical_size = PhySize::new(event.width as u32, event.height as u32);

Expand Down
1 change: 1 addition & 0 deletions src/x11/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod window;
pub use window::*;

mod cursor;
mod drag_n_drop;
mod event_loop;
mod keyboard;
mod visual_info;
13 changes: 11 additions & 2 deletions src/x11/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use raw_window_handle::{

use x11rb::connection::Connection;
use x11rb::protocol::xproto::{
AtomEnum, ChangeWindowAttributesAux, ConfigureWindowAux, ConnectionExt as _, CreateGCAux,
AtomEnum, ChangeWindowAttributesAux, ConfigureWindowAux, ConnectionExt, CreateGCAux,
CreateWindowAux, EventMask, PropMode, Visualid, Window as XWindow, WindowClass,
};
use x11rb::wrapper::ConnectionExt as _;
Expand Down Expand Up @@ -95,7 +95,7 @@ impl Drop for ParentHandle {

pub(crate) struct WindowInner {
pub(crate) xcb_connection: XcbConnection,
window_id: XWindow,
pub(crate) window_id: XWindow,
pub(crate) window_info: WindowInfo,
visual_id: Visualid,
mouse_cursor: Cell<MouseCursor>,
Expand Down Expand Up @@ -253,6 +253,15 @@ impl<'a> Window<'a> {
&[xcb_connection.atoms.WM_DELETE_WINDOW],
)?;

// Enable drag and drop (TODO: Make this toggleable?)
xcb_connection.conn.change_property32(
PropMode::REPLACE,
window_id,
xcb_connection.atoms.XdndAware,
AtomEnum::ATOM,
&[5u32], // Latest version; hasn't changed since 2002
)?;

xcb_connection.conn.flush()?;

// TODO: These APIs could use a couple tweaks now that everything is internal and there is
Expand Down
25 changes: 24 additions & 1 deletion src/x11/xcb_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,35 @@ use x11::{xlib, xlib::Display, xlib_xcb};

use x11rb::connection::Connection;
use x11rb::cursor::Handle as CursorHandle;
use x11rb::protocol::xproto::{Cursor, Screen};
use x11rb::protocol::xproto::{self, Cursor, Screen};
use x11rb::resource_manager;
use x11rb::xcb_ffi::XCBConnection;

use crate::MouseCursor;

use super::cursor;

mod get_property;
pub use get_property::GetPropertyError;

x11rb::atom_manager! {
pub Atoms: AtomsCookie {
WM_PROTOCOLS,
WM_DELETE_WINDOW,

// Drag-N-Drop Atoms
XdndAware,
XdndEnter,
XdndLeave,
XdndDrop,
XdndPosition,
XdndStatus,
XdndActionPrivate,
XdndSelection,
XdndFinished,
XdndTypeList,
TextUriList: b"text/uri-list",
None: b"None",
}
}

Expand Down Expand Up @@ -121,6 +138,12 @@ impl XcbConnection {
pub fn screen(&self) -> &Screen {
&self.conn.setup().roots[self.screen]
}

pub fn get_property<T: bytemuck::Pod>(
&self, window: xproto::Window, property: xproto::Atom, property_type: xproto::Atom,
) -> Result<Vec<T>, GetPropertyError> {
self::get_property::get_property(window, property, property_type, &self.conn)
}
}

impl Drop for XcbConnection {
Expand Down
188 changes: 188 additions & 0 deletions src/x11/xcb_connection/get_property.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
The code in this file was derived from the Winit project (https://github.com/rust-windowing/winit).
The original, unmodified code file this work is derived from can be found here:

https://github.com/rust-windowing/winit/blob/44aabdddcc9f720aec860c1f83c1041082c28560/src/platform_impl/linux/x11/util/window_property.rs

The original code this is based on is licensed under the following terms:
*/

/*
Copyright 2024 "The Winit contributors".

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
The full licensing terms of the original source code, at the time of writing, can also be found at:
https://github.com/rust-windowing/winit/blob/44aabdddcc9f720aec860c1f83c1041082c28560/LICENSE .

The Derived Work present in this file contains modifications made to the original source code, is
Copyright (c) 2024 "The Baseview contributors",
and is licensed under either the Apache License, Version 2.0; or The MIT license, at your option.

Copies of those licenses can be respectively found at:
* https://github.com/RustAudio/baseview/blob/master/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0 ;
* https://github.com/RustAudio/baseview/blob/master/LICENSE-MIT.

*/

use std::error::Error;
use std::ffi::c_int;
use std::fmt;
use std::mem;
use std::sync::Arc;

use bytemuck::Pod;

use x11rb::errors::ReplyError;
use x11rb::protocol::xproto::{self, ConnectionExt};
use x11rb::xcb_ffi::XCBConnection;

#[derive(Debug, Clone)]
pub enum GetPropertyError {
X11rbError(Arc<ReplyError>),
TypeMismatch(xproto::Atom),
FormatMismatch(c_int),
}

impl<T: Into<ReplyError>> From<T> for GetPropertyError {
fn from(e: T) -> Self {
Self::X11rbError(Arc::new(e.into()))
}
}

impl fmt::Display for GetPropertyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GetPropertyError::X11rbError(err) => err.fmt(f),
GetPropertyError::TypeMismatch(err) => write!(f, "type mismatch: {err}"),
GetPropertyError::FormatMismatch(err) => write!(f, "format mismatch: {err}"),
}
}
}

impl Error for GetPropertyError {}

// Number of 32-bit chunks to retrieve per iteration of get_property's inner loop.
// To test if `get_property` works correctly, set this to 1.
const PROPERTY_BUFFER_SIZE: u32 = 1024; // 4k of RAM ought to be enough for anyone!

pub(super) fn get_property<T: Pod>(
window: xproto::Window, property: xproto::Atom, property_type: xproto::Atom,
conn: &XCBConnection,
) -> Result<Vec<T>, GetPropertyError> {
let mut iter = PropIterator::new(conn, window, property, property_type);
let mut data = vec![];

loop {
if !iter.next_window(&mut data)? {
break;
}
}

Ok(data)
}

/// An iterator over the "windows" of the property that we are fetching.
struct PropIterator<'a, T> {
/// Handle to the connection.
conn: &'a XCBConnection,

/// The window that we're fetching the property from.
window: xproto::Window,

/// The property that we're fetching.
property: xproto::Atom,

/// The type of the property that we're fetching.
property_type: xproto::Atom,

/// The offset of the next window, in 32-bit chunks.
offset: u32,

/// The format of the type.
format: u8,

/// Keep a reference to `T`.
_phantom: std::marker::PhantomData<T>,
}

impl<'a, T: Pod> PropIterator<'a, T> {
/// Create a new property iterator.
fn new(
conn: &'a XCBConnection, window: xproto::Window, property: xproto::Atom,
property_type: xproto::Atom,
) -> Self {
let format = match mem::size_of::<T>() {
1 => 8,
2 => 16,
4 => 32,
_ => unreachable!(),
};

Self {
conn,
window,
property,
property_type,
offset: 0,
format,
_phantom: Default::default(),
}
}

/// Get the next window and append it to `data`.
///
/// Returns whether there are more windows to fetch.
fn next_window(&mut self, data: &mut Vec<T>) -> Result<bool, GetPropertyError> {
// Send the request and wait for the reply.
let reply = self
.conn
.get_property(
false,
self.window,
self.property,
self.property_type,
self.offset,
PROPERTY_BUFFER_SIZE,
)?
.reply()?;

// Make sure that the reply is of the correct type.
if reply.type_ != self.property_type {
return Err(GetPropertyError::TypeMismatch(reply.type_));
}

// Make sure that the reply is of the correct format.
if reply.format != self.format {
return Err(GetPropertyError::FormatMismatch(reply.format.into()));
}

// Append the data to the output.
if mem::size_of::<T>() == 1 && mem::align_of::<T>() == 1 {
// We can just do a bytewise append.
data.extend_from_slice(bytemuck::cast_slice(&reply.value));
} else {
let old_len = data.len();
let added_len = reply.value.len() / mem::size_of::<T>();

data.resize(old_len + added_len, T::zeroed());
bytemuck::cast_slice_mut::<T, u8>(&mut data[old_len..]).copy_from_slice(&reply.value);
}

// Check `bytes_after` to see if there are more windows to fetch.
self.offset += PROPERTY_BUFFER_SIZE;
Ok(reply.bytes_after != 0)
}
}