-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add API for storing drag-and-drop payload
- Loading branch information
Showing
4 changed files
with
77 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
use std::{any::Any, sync::Arc}; | ||
|
||
use crate::{Context, Id}; | ||
|
||
/// Helpers for drag-and-drop in egui. | ||
#[derive(Clone, Default)] | ||
pub struct DragAndDrop { | ||
/// If set, something is currently being dragged | ||
payload: Option<Arc<dyn Any + Send + Sync>>, | ||
} | ||
|
||
impl DragAndDrop { | ||
pub(crate) fn register(ctx: &Context) { | ||
ctx.on_end_frame("debug_text", std::sync::Arc::new(Self::end_frame)); | ||
} | ||
|
||
fn end_frame(ctx: &Context) { | ||
let pointer_released = ctx.input(|i| i.pointer.any_released()); | ||
if pointer_released { | ||
ctx.data_mut(|data| { | ||
let state = data.get_temp_mut_or_default::<Self>(Id::NULL); | ||
state.payload = None; | ||
}); | ||
} | ||
} | ||
|
||
/// Set a drag-and-drop payload. | ||
/// | ||
/// This can be read by [`Self::payload`] until the pointer is released. | ||
pub fn set_payload<T>(ctx: &Context, payload: T) | ||
where | ||
T: Any + Send + Sync, | ||
{ | ||
ctx.data_mut(|data| { | ||
let state = data.get_temp_mut_or_default::<Self>(Id::NULL); | ||
state.payload = Some(Arc::new(payload)); | ||
}); | ||
} | ||
|
||
/// Retreive the payload, if any. | ||
/// | ||
/// Returns `None` if there is no payload, or if it is not of the requested type. | ||
pub fn payload<T>(ctx: &Context) -> Option<Arc<T>> | ||
where | ||
T: Any + Send + Sync, | ||
{ | ||
ctx.data(|data| { | ||
let state = data.get_temp::<Self>(Id::NULL)?; | ||
let payload = state.payload?; | ||
payload.downcast().ok() | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters