use super::*;
pub const MAX_TARGETED_ACTIONS_PER_EVENT: usize = 256;
pub const MAX_PENDING_TARGETED_ACTIONS: usize = 1_024;
pub const MAX_NATIVE_POPUP_MENUS_PER_EVENT: usize = 4;
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
CloseRequested,
PointerMoved(Point),
PointerLeft,
MouseButton {
button: MouseButton,
pressed: bool,
},
Click(crate::ElementId),
ContextMenu(ContextMenuEvent),
Dismiss(crate::ElementId),
Scroll(Vector),
MousePressure(MousePressureEvent),
Pinch(PinchEvent),
Rotation(RotationEvent),
SmartMagnify(SmartMagnifyEvent),
Touch(TouchEvent),
KeyDown {
key: Key,
key_char: Option<Key>,
modifiers: Modifiers,
repeat: bool,
},
KeyUp {
key: Key,
key_char: Option<Key>,
modifiers: Modifiers,
},
TextInput(String),
ModifiersChanged(Modifiers),
FocusChanged(Option<ElementId>),
Focused(bool),
AppearanceChanged(WindowAppearance),
Moved {
logical_position: Point,
scale_factor: f32,
},
FilesHovered(DroppedFiles),
FilesHoverCancelled,
FilesDropped(DroppedFiles),
ExternalDragEnded(ExternalDragEndEvent),
Resized {
logical_size: Size,
scale_factor: f32,
},
}
pub const MAX_FORM_FIELDS: usize = 256;
pub const MAX_VALIDATION_ISSUES: usize = 256;
pub const MAX_VALIDATION_MESSAGE_BYTES: usize = 4 * 1024;
pub const MAX_FORM_SUBMISSIONS_PER_EVENT: usize = 64;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FormField {
id: ElementId,
value: Arc<str>,
}
impl FormField {
pub(crate) fn new(id: ElementId, value: Arc<str>) -> Self {
Self { id, value }
}
pub const fn id(&self) -> ElementId {
self.id
}
pub fn value(&self) -> &str {
&self.value
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FormSubmitEvent {
form: ElementId,
trigger: Option<ElementId>,
fields: Arc<[FormField]>,
truncated: bool,
}
impl FormSubmitEvent {
pub(crate) fn new(
form: ElementId,
trigger: Option<ElementId>,
fields: Vec<FormField>,
truncated: bool,
) -> Self {
debug_assert!(fields.len() <= MAX_FORM_FIELDS);
Self {
form,
trigger,
fields: Arc::from(fields),
truncated,
}
}
pub const fn form(&self) -> ElementId {
self.form
}
pub const fn trigger(&self) -> Option<ElementId> {
self.trigger
}
pub fn fields(&self) -> &[FormField] {
&self.fields
}
pub fn value(&self, id: impl Into<ElementId>) -> Option<&str> {
let id = id.into();
self.fields
.iter()
.find(|field| field.id == id)
.map(FormField::value)
}
pub const fn is_truncated(&self) -> bool {
self.truncated
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ValidationIssue {
id: ElementId,
message: Option<Arc<str>>,
message_truncated: bool,
}
impl ValidationIssue {
pub(crate) fn new(id: ElementId, message: Option<Arc<str>>, message_truncated: bool) -> Self {
Self {
id,
message,
message_truncated,
}
}
pub const fn id(&self) -> ElementId {
self.id
}
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
pub const fn is_message_truncated(&self) -> bool {
self.message_truncated
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ValidationReport {
form: ElementId,
trigger: Option<ElementId>,
issues: Arc<[ValidationIssue]>,
truncated: bool,
}
impl ValidationReport {
pub(crate) fn new(
form: ElementId,
trigger: Option<ElementId>,
issues: Vec<ValidationIssue>,
truncated: bool,
) -> Self {
debug_assert!(issues.len() <= MAX_VALIDATION_ISSUES);
Self {
form,
trigger,
issues: Arc::from(issues),
truncated,
}
}
pub const fn form(&self) -> ElementId {
self.form
}
pub const fn trigger(&self) -> Option<ElementId> {
self.trigger
}
pub fn issues(&self) -> &[ValidationIssue] {
&self.issues
}
pub fn first(&self) -> Option<&ValidationIssue> {
self.issues.first()
}
pub const fn is_truncated(&self) -> bool {
self.truncated
}
}
pub const MAX_DROPPED_FILES: usize = 4_096;
pub const MAX_EXTERNAL_DRAG_FILES: usize = 4_096;
pub const MAX_EXTERNAL_DRAG_PATH_BYTES: usize = 16 * 1024;
pub const MAX_EXTERNAL_DRAG_TOTAL_PATH_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_EXTERNAL_DRAG_TEXT_BYTES: usize = 1024 * 1024;
pub const MAX_EXTERNAL_DRAG_URL_BYTES: usize = 16 * 1024;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DroppedFiles {
paths: Arc<[PathBuf]>,
truncated: bool,
}
impl DroppedFiles {
pub fn new(paths: impl IntoIterator<Item = PathBuf>) -> Self {
let mut paths = paths.into_iter();
let retained = paths.by_ref().take(MAX_DROPPED_FILES).collect::<Vec<_>>();
Self {
paths: Arc::from(retained),
truncated: paths.next().is_some(),
}
}
pub fn paths(&self) -> &[PathBuf] {
&self.paths
}
pub fn is_empty(&self) -> bool {
self.paths.is_empty()
}
pub fn is_truncated(&self) -> bool {
self.truncated
}
pub(crate) fn from_retained(paths: Vec<PathBuf>, truncated: bool) -> Self {
debug_assert!(paths.len() <= MAX_DROPPED_FILES);
Self {
paths: Arc::from(paths),
truncated,
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FileDragPaths {
entries: Arc<[(PathBuf, bool)]>,
truncated: bool,
}
impl FileDragPaths {
pub fn new(entries: impl IntoIterator<Item = (PathBuf, bool)>) -> Self {
let mut entries = entries.into_iter();
let mut retained = Vec::with_capacity(entries.size_hint().0.min(MAX_EXTERNAL_DRAG_FILES));
let mut retained_bytes = 0_usize;
let mut truncated = false;
for (path, is_directory) in entries.by_ref().take(MAX_EXTERNAL_DRAG_FILES) {
let path_bytes = path.as_os_str().as_encoded_bytes().len();
let next_bytes = retained_bytes.saturating_add(path_bytes);
if path_bytes == 0
|| path_bytes > MAX_EXTERNAL_DRAG_PATH_BYTES
|| next_bytes > MAX_EXTERNAL_DRAG_TOTAL_PATH_BYTES
{
truncated = true;
continue;
}
retained_bytes = next_bytes;
retained.push((path, is_directory));
}
truncated |= entries.next().is_some();
Self {
entries: Arc::from(retained),
truncated,
}
}
pub fn files(paths: impl IntoIterator<Item = PathBuf>) -> Self {
Self::new(paths.into_iter().map(|path| (path, false)))
}
pub fn directories(paths: impl IntoIterator<Item = PathBuf>) -> Self {
Self::new(paths.into_iter().map(|path| (path, true)))
}
pub fn entries(&self) -> &[(PathBuf, bool)] {
&self.entries
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn is_truncated(&self) -> bool {
self.truncated
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ExternalDragText {
pub(super) text: Arc<str>,
truncated: bool,
}
impl ExternalDragText {
pub fn new(text: impl Into<Arc<str>>) -> Self {
let text = text.into();
if text.len() <= MAX_EXTERNAL_DRAG_TEXT_BYTES {
return Self {
text,
truncated: false,
};
}
let mut end = MAX_EXTERNAL_DRAG_TEXT_BYTES;
while !text.is_char_boundary(end) {
end -= 1;
}
Self {
text: Arc::from(&text[..end]),
truncated: true,
}
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn is_truncated(&self) -> bool {
self.truncated
}
pub(crate) fn from_bounded(text: String, truncated: bool) -> Self {
debug_assert!(text.len() <= MAX_EXTERNAL_DRAG_TEXT_BYTES);
Self {
text: Arc::from(text),
truncated,
}
}
}
impl From<&str> for ExternalDragText {
fn from(text: &str) -> Self {
Self::new(text)
}
}
impl From<String> for ExternalDragText {
fn from(text: String) -> Self {
Self::new(text)
}
}
impl From<Arc<str>> for ExternalDragText {
fn from(text: Arc<str>) -> Self {
Self::new(text)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExternalDragUrl(pub(super) Arc<str>);
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ExternalDragUrlError {
#[error("external drag URL is empty")]
Empty,
#[error(
"external drag URL is {bytes} bytes; the maximum is {MAX_EXTERNAL_DRAG_URL_BYTES} bytes"
)]
TooLarge { bytes: usize },
#[error("external drag URL must have an absolute RFC 3986 scheme")]
InvalidScheme,
#[error("external drag URL contains whitespace or control characters")]
InvalidCharacter,
}
impl ExternalDragUrl {
pub fn new(url: impl Into<Arc<str>>) -> Result<Self, ExternalDragUrlError> {
let url = url.into();
if url.is_empty() {
return Err(ExternalDragUrlError::Empty);
}
if url.len() > MAX_EXTERNAL_DRAG_URL_BYTES {
return Err(ExternalDragUrlError::TooLarge { bytes: url.len() });
}
if url
.chars()
.any(|character| character.is_whitespace() || character.is_control())
{
return Err(ExternalDragUrlError::InvalidCharacter);
}
let Some((scheme, remainder)) = url.split_once(':') else {
return Err(ExternalDragUrlError::InvalidScheme);
};
let mut characters = scheme.chars();
if remainder.is_empty()
|| !characters
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
|| !characters.all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '+' | '-' | '.')
})
{
return Err(ExternalDragUrlError::InvalidScheme);
}
Ok(Self(url))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
pub type DroppedText = ExternalDragText;
pub type DroppedUrl = ExternalDragUrl;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExternalDragPayload {
Files(FileDragPaths),
Text(ExternalDragText),
Url(ExternalDragUrl),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExternalDragOperation {
Cancelled,
Copied,
Moved,
Linked,
Deleted,
Other,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ExternalDragEndEvent {
pub source: ElementId,
pub operation: ExternalDragOperation,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DragStartEvent {
pub origin: Point,
pub position: Point,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DragOrigin {
Internal(ElementId),
CrossWindow {
window: WindowHandle,
source: ElementId,
},
External,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DropEvent {
pub position: Point,
pub modifiers: Modifiers,
pub origin: DragOrigin,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum MouseButton {
#[default]
Left,
Right,
Middle,
Back,
Forward,
Other(u16),
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum DispatchPhase {
#[default]
Bubble,
Capture,
}
impl DispatchPhase {
pub const fn bubble(self) -> bool {
matches!(self, Self::Bubble)
}
pub const fn capture(self) -> bool {
matches!(self, Self::Capture)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MouseDownEvent {
pub button: MouseButton,
pub position: Point,
pub modifiers: Modifiers,
pub click_count: usize,
pub first_mouse: bool,
}
impl MouseDownEvent {
pub const fn is_focusing(self) -> bool {
matches!(self.button, MouseButton::Left)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MouseUpEvent {
pub button: MouseButton,
pub position: Point,
pub modifiers: Modifiers,
pub click_count: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MouseMoveEvent {
pub position: Point,
pub pressed_button: Option<MouseButton>,
pub modifiers: Modifiers,
}
impl MouseMoveEvent {
pub const fn dragging(self) -> bool {
self.pressed_button.is_some()
}
pub fn dragging_button(self, button: MouseButton) -> bool {
matches!(self.pressed_button, Some(pressed) if pressed == button)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MouseExitEvent {
pub position: Point,
pub pressed_button: Option<MouseButton>,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PointerPhase {
Down,
Move,
Up,
Cancel,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PointerEvent {
pub phase: PointerPhase,
pub position: Point,
pub origin: Point,
pub local_position: Point,
pub local_origin: Point,
pub delta: Vector,
pub button: MouseButton,
pub modifiers: Modifiers,
}
impl PointerEvent {
pub(crate) fn localize(mut self, bounds: Rect) -> Self {
self.local_position = Point::new(self.position.x - bounds.x, self.position.y - bounds.y);
self.local_origin = Point::new(self.origin.x - bounds.x, self.origin.y - bounds.y);
self
}
}
pub const MAX_SCROLL_PIXELS_PER_EVENT: f32 = 1_048_576.0;
pub const MAX_SCROLL_LINES_PER_EVENT: f32 = 4_096.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScrollDelta {
Pixels(Vector),
Lines(Vector),
}
impl Default for ScrollDelta {
fn default() -> Self {
Self::Lines(Vector::ZERO)
}
}
impl ScrollDelta {
pub fn precise(&self) -> bool {
matches!(self, Self::Pixels(_))
}
pub fn pixel_delta(&self, line_height: f32) -> Vector {
match *self {
Self::Pixels(delta) => bounded_scroll_vector(delta, MAX_SCROLL_PIXELS_PER_EVENT),
Self::Lines(delta) => {
let line_height = if line_height.is_finite() {
line_height.clamp(0.0, MAX_SCROLL_PIXELS_PER_EVENT)
} else {
0.0
};
bounded_scroll_vector(
Vector::new(delta.x * line_height, delta.y * line_height),
MAX_SCROLL_PIXELS_PER_EVENT,
)
}
}
}
pub(crate) fn bounded(self) -> Self {
match self {
Self::Pixels(delta) => {
Self::Pixels(bounded_scroll_vector(delta, MAX_SCROLL_PIXELS_PER_EVENT))
}
Self::Lines(delta) => {
Self::Lines(bounded_scroll_vector(delta, MAX_SCROLL_LINES_PER_EVENT))
}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScrollWheelEvent {
pub position: Point,
pub delta: ScrollDelta,
pub phase: GesturePhase,
pub modifiers: Modifiers,
}
impl ScrollWheelEvent {
pub(crate) fn bounded(mut self) -> Self {
self.delta = self.delta.bounded();
self
}
}
fn bounded_scroll_vector(delta: Vector, limit: f32) -> Vector {
let component = |value: f32| {
if value.is_finite() {
value.clamp(-limit, limit)
} else {
0.0
}
};
Vector::new(component(delta.x), component(delta.y))
}
pub const MAX_PINCH_DELTA_PER_EVENT: f32 = 8.0;
pub const MAX_ROTATION_DEGREES_PER_EVENT: f32 = 360.0;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum GesturePhase {
Started,
#[default]
Moved,
Ended,
Cancelled,
}
pub const MAX_ACTIVE_TOUCHES_PER_WINDOW: usize = 32;
pub const MAX_TOUCH_COORDINATE: f32 = 16_777_216.0;
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TouchId(pub u64);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum TouchPhase {
Started,
#[default]
Moved,
Ended,
Cancelled,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TouchEvent {
pub id: TouchId,
pub phase: TouchPhase,
pub position: Point,
pub force: Option<f32>,
}
impl TouchEvent {
pub(crate) fn bounded(mut self) -> Self {
let coordinate = |value: f32| {
if value.is_finite() {
value.clamp(-MAX_TOUCH_COORDINATE, MAX_TOUCH_COORDINATE)
} else {
0.0
}
};
self.position = Point::new(coordinate(self.position.x), coordinate(self.position.y));
self.force = self.force.map(|force| {
if force.is_finite() {
force.clamp(0.0, 1.0)
} else {
0.0
}
});
self
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum PressureStage {
#[default]
Zero,
Normal,
Force,
Other(i64),
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MousePressureEvent {
pub position: Point,
pub pressure: f32,
pub stage: PressureStage,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PinchEvent {
pub position: Point,
pub delta: f32,
pub phase: GesturePhase,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RotationEvent {
pub position: Point,
pub delta: f32,
pub phase: GesturePhase,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SmartMagnifyEvent {
pub position: Point,
pub modifiers: Modifiers,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContextMenuEvent {
pub target: ElementId,
pub position: Point,
pub modifiers: Modifiers,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Key {
Character(String),
ArrowUp,
ArrowDown,
ArrowLeft,
ArrowRight,
PageUp,
PageDown,
Home,
End,
Enter,
Escape,
Space,
Tab,
Backspace,
Delete,
Insert,
Function(u8),
Other,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyDownEvent {
pub key: Key,
pub key_char: Option<Key>,
pub text: Option<String>,
pub modifiers: Modifiers,
pub repeat: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeyUpEvent {
pub key: Key,
pub key_char: Option<Key>,
pub modifiers: Modifiers,
}
bitflags! {
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct Modifiers: u8 {
const SHIFT = 1 << 0;
const CONTROL = 1 << 1;
const ALT = 1 << 2;
const SUPER = 1 << 3;
}
}