use crate::color::Color;
use crate::event::Cursor;
use crate::geom::{pt, rect};
use crate::id::Id;
use crate::ui::{Anchor, Response, Ui};
use std::cell::Cell;
use std::path::PathBuf;
const SLACK: f32 = 4.0;
const CARRIED: Id = 0xca22_1ed0_ca22_1ed0;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum DragData<'a> {
Files(&'a [PathBuf]),
Text(&'a str),
Picture(usize, &'a [u32]),
Link(&'a str),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DropEffect {
Copied,
Moved,
}
#[derive(Debug, PartialEq)]
pub(crate) enum OwnedDragData {
Files(Vec<PathBuf>),
Text(String),
Picture(usize, Vec<u32>),
Link(String),
}
impl OwnedDragData {
pub(crate) fn of(what: DragData) -> OwnedDragData {
match what {
DragData::Files(files) => OwnedDragData::Files(files.to_vec()),
DragData::Text(text) => OwnedDragData::Text(text.into()),
DragData::Picture(width, pixels) => OwnedDragData::Picture(width, pixels.to_vec()),
DragData::Link(address) => OwnedDragData::Link(address.into()),
}
}
fn as_drag_data(&self) -> DragData<'_> {
match self {
OwnedDragData::Files(files) => DragData::Files(files),
OwnedDragData::Text(text) => DragData::Text(text),
OwnedDragData::Picture(width, pixels) => DragData::Picture(*width, pixels),
OwnedDragData::Link(address) => DragData::Link(address),
}
}
}
#[derive(Default)]
pub(crate) struct Crossing {
held: Id,
out: Option<(Id, OwnedDragData)>,
news: bool,
taken: Option<(Id, DropEffect)>,
pub(crate) text_over: bool,
pub(crate) text: Option<String>,
pub(crate) takes_text: Cell<bool>,
took: bool,
}
impl Crossing {
pub(crate) fn settle(&mut self, down: bool) {
(self.text, self.taken) = (None, None);
if !down {
self.held = 0;
if std::mem::take(&mut self.news) {
self.out = None;
}
}
}
}
impl Ui {
#[cfg_attr(debug_assertions, track_caller)]
pub fn drag_source(&mut self, from: &Response, what: u64) -> bool {
let Some((gone, _)) = self.drag_delta(from, [0.0; 4]) else { return false };
if self.dragging.is_none() && gone.x.abs().max(gone.y.abs()) > SLACK {
self.dragging = Some((from.id, what));
}
let out = self.crossing.out.as_ref().is_some_and(|(id, _)| *id == from.id);
let inside = |at: &crate::geom::Point| !out || rect(0.0, 0.0, self.size().w, self.size().h).contains(*at);
let Some(at) = self.pointer().filter(|at| inside(at) && self.dragging.is_some_and(|(source, _)| source == from.id)) else { return false };
let t = self.theme;
self.set_cursor(Cursor::Move);
self.layer(from.id ^ CARRIED, Anchor::At(pt(at.x + 12.0, at.y + 14.0)), false, Color::NONE);
self.row().pad((8.0, 4.0)).fill(t.raised).border(t.line_strong, 1.0).radius(6.0).shadow(10.0).open();
true
}
pub fn drag_out(&mut self, from: &Response, what: DragData) -> Option<DropEffect> {
crate::platform::hands_out();
if let Some((_, taken)) = self.crossing.taken.take_if(|(id, _)| *id == from.id) {
self.again = true;
return Some(taken);
}
if !from.pressed {
return None;
}
let gone = self.drag_delta(from, [0.0; 4]).is_some_and(|(gone, _)| gone.x.abs().max(gone.y.abs()) > SLACK);
if gone && self.crossing.held == 0 {
self.crossing.held = from.id;
}
let off = self.pointer().is_none_or(|at| !rect(0.0, 0.0, self.size().w, self.size().h).contains(at));
if self.crossing.held == from.id && self.crossing.out.is_none() && off {
(self.crossing.out, self.crossing.news) = (Some((from.id, OwnedDragData::of(what))), true);
}
None
}
pub fn drag_leaves_window(&self) -> bool {
self.crossing.held != 0 && self.crossing.out.is_none()
}
pub fn take_drag_out(&mut self) -> Option<DragData<'_>> {
let news = std::mem::take(&mut self.crossing.news);
self.crossing.out.as_ref().filter(|_| news).map(|(_, kept)| kept.as_drag_data())
}
pub fn set_drop_effect(&mut self, taken: Option<DropEffect>) {
let from = self.crossing.out.take().map(|(id, _)| id);
self.crossing.taken = from.zip(taken);
}
pub fn files_hovered(&self) -> bool {
crate::platform::hand_drops();
self.takes_files.set(true);
self.files_over
}
pub fn files_dropped(&mut self, on: &Response) -> Option<Vec<PathBuf>> {
crate::platform::hand_drops();
self.takes_files.set(true);
let here = !self.files.is_empty() && self.pointer().is_some_and(|at| on.rect.contains(at));
(self.again, self.crossing.took) = (self.again || here, self.crossing.took || here);
here.then(|| std::mem::take(&mut self.files))
}
pub fn text_hovered(&self) -> bool {
crate::platform::hand_drops();
self.crossing.takes_text.set(true);
self.crossing.text_over
}
pub fn text_dropped(&mut self, on: &Response) -> Option<String> {
crate::platform::hand_drops();
self.crossing.takes_text.set(true);
let here = self.crossing.text.is_some() && self.pointer().is_some_and(|at| on.rect.contains(at));
(self.again, self.crossing.took) = (self.again || here, self.crossing.took || here);
self.crossing.text.take_if(|_| here)
}
pub fn take_drop_accepted(&mut self) -> bool {
std::mem::take(&mut self.crossing.took)
}
pub fn drag_payload(&self) -> Option<u64> {
self.dragging.map(|(_, what)| what)
}
pub fn dropped(&mut self, on: &Response) -> Option<u64> {
let (_, what) = self.dragging?;
let over = self.pointer().is_some_and(|at| on.rect.contains(at));
if !over || !self.input.released[0] {
return None;
}
(self.dragging, self.again) = (None, true);
Some(what)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::{Button, Event, Mods};
use crate::geom::{Point, Size};
use crate::platform::LocalClipboard;
use crate::text::BuiltInFont;
#[derive(Default)]
struct Seen {
from: crate::geom::Rect,
on: crate::geom::Rect,
carried: bool,
dropped: Option<u64>,
taken: Vec<DropEffect>,
files: Option<Vec<PathBuf>>,
text: Option<String>,
over: (bool, bool),
}
struct App {
ui: Ui,
seen: Seen,
what: Option<DragData<'static>>,
}
impl App {
fn new(what: Option<DragData<'static>>) -> App {
let mut ui = Ui::new(Box::new(BuiltInFont), Box::new(LocalClipboard::default()));
ui.resize(Size { w: 300.0, h: 200.0 }, 1.0);
let mut app = App { ui, seen: Seen::default(), what };
app.run();
app.run();
app
}
fn run(&mut self) {
let (seen, what) = (&mut self.seen, self.what);
self.ui.run(&mut |ui| {
ui.column().pad(20.0).gap(20.0).open();
let from = ui.button("Carry me");
if ui.drag_source(&from, 7) {
ui.label("seven");
ui.close();
}
seen.carried |= ui.drag_payload().is_some();
seen.taken.extend(what.and_then(|what| ui.drag_out(&from, what)));
let on = ui.button("Let go here");
seen.dropped = seen.dropped.or(ui.dropped(&on));
seen.files = seen.files.take().or(ui.files_dropped(&on));
seen.text = seen.text.take().or(ui.text_dropped(&on));
seen.over = (ui.files_hovered(), ui.text_hovered());
(seen.from, seen.on) = (from.rect, on.rect);
ui.close();
});
}
fn does(&mut self, events: &[Event]) {
events.iter().for_each(|event| _ = self.ui.event(event.clone()));
self.run();
}
fn middle(of: crate::geom::Rect) -> Point {
pt(of.x + of.w / 2.0, of.y + of.h / 2.0)
}
fn take(&mut self) {
let at = App::middle(self.seen.from);
self.does(&[Event::Move(at), Event::Press(Button::Left, Mods::NONE)]);
self.does(&[Event::Move(pt(at.x + 10.0, at.y))]);
}
}
#[test]
fn what_is_carried_past_the_windows_edge_goes_out_as_what_the_app_says_it_is() {
let paths = [PathBuf::from("/a/one.txt"), PathBuf::from("/b/two.png")];
let paths: &'static [PathBuf] = Box::leak(Box::new(paths));
let mut app = App::new(Some(DragData::Files(paths)));
app.take();
assert!(app.seen.carried && app.ui.drag_leaves_window());
assert_eq!(app.ui.take_drag_out(), None);
app.does(&[Event::Move(pt(290.0, 100.0))]);
assert_eq!(app.ui.take_drag_out(), None, "still inside");
app.does(&[Event::Move(pt(310.0, 100.0))]);
assert!(!app.ui.drag_leaves_window());
assert_eq!(app.ui.take_drag_out(), Some(DragData::Files(paths)));
assert_eq!(app.ui.take_drag_out(), None, "once");
app.does(&[Event::Move(pt(330.0, 120.0))]);
assert_eq!(app.ui.take_drag_out(), None, "it is out already");
app.does(&[Event::Leave, Event::Release(Button::Left)]);
app.ui.set_drop_effect(Some(DropEffect::Moved));
app.run();
app.run();
assert_eq!((app.seen.taken.as_slice(), app.seen.dropped), (&[DropEffect::Moved][..], None));
}
#[test]
fn what_comes_back_into_its_window_is_the_number_again() {
let mut app = App::new(Some(DragData::Text("words")));
app.take();
app.does(&[Event::Leave]);
assert_eq!(app.ui.take_drag_out(), Some(DragData::Text("words")));
app.does(&[Event::Move(App::middle(app.seen.on))]);
assert!(app.ui.drag_payload() == Some(7) && app.ui.wants_pointer());
app.does(&[Event::Release(Button::Left)]);
app.ui.set_drop_effect(None);
app.run();
assert_eq!((app.seen.dropped, app.seen.taken.as_slice()), (Some(7), &[][..]));
assert!(!app.ui.drag_leaves_window() && app.ui.drag_payload().is_none());
}
#[test]
fn nothing_goes_out_of_a_window_whose_app_does_not_hand_anything_out() {
let mut app = App::new(None);
app.take();
assert!(!app.ui.drag_leaves_window());
app.does(&[Event::Move(pt(400.0, 100.0))]);
assert_eq!(app.ui.take_drag_out(), None);
app.does(&[Event::Move(App::middle(app.seen.on)), Event::Release(Button::Left)]);
assert_eq!(app.seen.dropped, Some(7));
}
#[test]
fn what_goes_out_where_nobody_hands_it_on_is_forgotten_when_the_button_comes_up() {
let mut app = App::new(Some(DragData::Link("https://example.org/")));
app.take();
app.does(&[Event::Move(pt(-20.0, 50.0))]);
app.does(&[Event::Release(Button::Left)]);
assert_eq!(app.ui.take_drag_out(), None, "an interface run by a program that hands nothing on");
app.take();
app.does(&[Event::Move(pt(-20.0, 50.0))]);
assert_eq!(app.ui.take_drag_out(), Some(DragData::Link("https://example.org/")));
app.does(&[Event::Release(Button::Left)]);
app.ui.set_drop_effect(Some(DropEffect::Copied));
app.run();
let at = App::middle(app.seen.from);
app.does(&[Event::Move(at), Event::Press(Button::Left, Mods::NONE)]);
app.does(&[Event::Move(pt(at.x + 2.0, at.y)), Event::Leave]);
assert!(!app.ui.drag_leaves_window() && app.ui.take_drag_out().is_none());
assert_eq!(app.seen.taken, [DropEffect::Copied]);
}
#[test]
fn a_picture_goes_out_as_its_own_copy() {
let pixels: &'static [u32] = Box::leak(Box::new([0xff10_2030u32, 0x8040_5060]));
let mut app = App::new(Some(DragData::Picture(2, pixels)));
app.take();
app.does(&[Event::Move(pt(100.0, 250.0))]);
assert_eq!(app.ui.take_drag_out(), Some(DragData::Picture(2, &[0xff10_2030, 0x8040_5060])));
let Some((_, OwnedDragData::Picture(_, kept))) = &app.ui.crossing.out else { panic!("no picture") };
assert!(!std::ptr::eq(kept.as_ptr(), pixels.as_ptr()), "the app may change its own meanwhile");
}
#[test]
fn text_from_another_program_is_taken_by_the_box_it_is_let_go_on() {
let mut app = App::new(None);
assert!(app.ui.crossing.takes_text.get() && app.ui.takes_files.get(), "the app asked about both");
app.does(&[Event::TextHovered(true), Event::Move(pt(250.0, 190.0))]);
assert_eq!(app.seen.over, (false, true));
app.does(&[Event::TextDropped("beside".into())]);
assert_eq!((app.seen.text.take(), app.seen.over, app.ui.take_drop_accepted()), (None, (false, false), false));
app.does(&[Event::TextHovered(true), Event::Move(App::middle(app.seen.on)), Event::TextDropped("on it".into())]);
assert_eq!((app.seen.text.take().as_deref(), app.ui.take_drop_accepted(), app.ui.take_drop_accepted()), (Some("on it"), true, false));
app.does(&[Event::FilesHovered(true), Event::Move(App::middle(app.seen.on))]);
assert_eq!(app.seen.over, (true, false));
app.does(&[Event::FilesDropped(vec![PathBuf::from("/x")])]);
assert_eq!((app.seen.files.take(), app.ui.take_drop_accepted()), (Some(vec![PathBuf::from("/x")]), true));
}
}