diff --git a/apps/gpui_components/lib/gpui/components/schema_declarations.ex b/apps/gpui_components/lib/gpui/components/schema_declarations.ex index 69db4a4..ede5f51 100644 --- a/apps/gpui_components/lib/gpui/components/schema_declarations.ex +++ b/apps/gpui_components/lib/gpui/components/schema_declarations.ex @@ -4,7 +4,10 @@ defmodule GPUI.Components.Schema.Declarations do @components [ %{ __struct__: GPUI.Schema.Component, - attrs: [id: :required_string], + attrs: [ + id: :required_string, + accepts: {:default, {:enum, ["files", "values"]}, "files"} + ], children: true, events: [ drag_enter: :"phx-drag-enter", @@ -21,6 +24,20 @@ defmodule GPUI.Components.Schema.Declarations do stateful: true, tag: :ui_drop_target }, + %{ + __struct__: GPUI.Schema.Component, + attrs: [id: :required_string, value: :required_string], + children: true, + events: [], + extension: nil, + kind: :drag_source_component, + public_hidden_attrs: [], + public_required_attrs: [], + public_slots: [], + required_events: [], + stateful: false, + tag: :ui_drag_source + }, %{ __struct__: GPUI.Schema.Component, attrs: [ diff --git a/apps/gpui_components/lib/gpui/ui.ex b/apps/gpui_components/lib/gpui/ui.ex index 606f2db..5975f7a 100644 --- a/apps/gpui_components/lib/gpui/ui.ex +++ b/apps/gpui_components/lib/gpui/ui.ex @@ -51,6 +51,7 @@ defmodule GPUI.UI do virtual_collection_options: :ui_virtual_collection, virtual_item_options: :ui_virtual_item, drop_target_options: :ui_drop_target, + drag_source_options: :ui_drag_source, rich_text_options: :ui_rich_text, data_table_options: :ui_data_table, table_column_options: :ui_table_column, @@ -516,10 +517,13 @@ defmodule GPUI.UI do end @doc """ - Builds a neutral operating-system external-path drop target. + Builds a neutral drop target. - Paths always refer to the display machine. The renderer bounds and validates - paths before emitting typed drag events and never reads dropped files. + With `accepts: "files"` (the default) it takes operating-system external + paths, which always refer to the display machine; the renderer bounds and + validates them before emitting typed drag events and never reads dropped + files. With `accepts: "values"` it takes in-app drags started on a + `drag_source/1`, whose value arrives as the payload's `text`. #{ComponentsSchema.component_options_doc(:ui_drop_target)} """ @@ -536,6 +540,24 @@ defmodule GPUI.UI do component(:ui_drop_target, assigns) end + @doc """ + Builds an in-app drag source around its children. + + Pressing on the children and moving starts a drag carrying `value`, which + drop targets with `accepts: "values"` receive as the payload's `text`. A + press that doesn't move still clicks the children. Values must be valid + UTF-8 and fit the transfer payload's 1 MiB text limit. + + #{ComponentsSchema.component_options_doc(:ui_drag_source)} + """ + @spec drag_source(drag_source_options()) :: Element.t() + def drag_source(assigns) when is_map(assigns) do + assigns = ComponentsSchema.apply_defaults(assigns, :ui_drag_source) + ComponentsSchema.validate_component_assigns!(assigns, :ui_drag_source) + GPUI.Transfer.Payload.new(text: assigns.value) + component(:ui_drag_source, assigns) + end + @doc """ Builds immutable, selectable, natively shaped rich text. diff --git a/apps/gpui_components/native/src/generated/schema.rs b/apps/gpui_components/native/src/generated/schema.rs index bea7448..17f89ec 100644 --- a/apps/gpui_components/native/src/generated/schema.rs +++ b/apps/gpui_components/native/src/generated/schema.rs @@ -13,6 +13,7 @@ pub enum GeneratedComponentKind { FrostComponent, PaintComponent, DropTargetComponent, + DragSourceComponent, SplitComponent, ButtonComponent, ProgressComponent, @@ -2294,6 +2295,7 @@ pub(crate) fn decode_generated_paint_component<'a>( pub(crate) struct DropTargetComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, + pub(crate) accepts: Option, pub(crate) children: Vec, pub(crate) drag_enter: Option, pub(crate) drag_move: Option, @@ -2309,6 +2311,14 @@ pub(crate) fn decode_generated_drop_target_component<'a>( Ok(DropTargetComponentNode { style: decode_style(term)?, id: component_required_string_attr(term, atoms::id())?, + accepts: match component_enum_attr( + term, + atoms::accepts(), + &vec!["files", "values"], + )? { + Some(value) => Some(value), + None => Some("files".to_string()), + }, children: decode_children(term)?, drag_enter: component_string_attr(term, atoms::phx_drag_enter())?, drag_move: component_string_attr(term, atoms::phx_drag_move())?, @@ -2319,6 +2329,28 @@ pub(crate) fn decode_generated_drop_target_component<'a>( #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct DragSourceComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) value: String, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_drag_source_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(DragSourceComponentNode { + style: decode_style(term)?, + id: component_required_string_attr(term, atoms::id())?, + value: component_required_string_attr(term, atoms::value())?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct SplitComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -3840,6 +3872,7 @@ pub(crate) enum ElementNode { FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), DropTargetComponent(DropTargetComponentNode), + DragSourceComponent(DragSourceComponentNode), SplitComponent(SplitComponentNode), ButtonComponent(ButtonComponentNode), ProgressComponent(ProgressComponentNode), @@ -3905,6 +3938,7 @@ pub enum GeneratedElementTag { UiFrost, UiPaint, UiDropTarget, + UiDragSource, UiSplit, UiButton, UiProgress, @@ -3969,6 +4003,7 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, "ui_drop_target" => GeneratedElementTag::UiDropTarget, + "ui_drag_source" => GeneratedElementTag::UiDragSource, "ui_split" => GeneratedElementTag::UiSplit, "ui_button" => GeneratedElementTag::UiButton, "ui_progress" => GeneratedElementTag::UiProgress, @@ -4034,6 +4069,7 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, GeneratedElementTag::UiDropTarget => GeneratedComponentKind::DropTargetComponent, + GeneratedElementTag::UiDragSource => GeneratedComponentKind::DragSourceComponent, GeneratedElementTag::UiSplit => GeneratedComponentKind::SplitComponent, GeneratedElementTag::UiButton => GeneratedComponentKind::ButtonComponent, GeneratedElementTag::UiProgress => GeneratedComponentKind::ProgressComponent, @@ -4147,6 +4183,10 @@ pub(crate) fn decode_generated_element_node<'a>( decode_generated_drop_target_component(term) .map(|node| ElementNode::DropTargetComponent(node)) } + GeneratedComponentKind::DragSourceComponent => { + decode_generated_drag_source_component(term) + .map(|node| ElementNode::DragSourceComponent(node)) + } GeneratedComponentKind::SplitComponent => { decode_generated_split_component(term) .map(|node| ElementNode::SplitComponent(node)) @@ -4345,6 +4385,9 @@ pub(crate) fn render_generated_component_node( ElementNode::DropTargetComponent(node) => { element::component::drop_target::render(node, context) } + ElementNode::DragSourceComponent(node) => { + element::component::drag_source::render(node, context) + } ElementNode::SplitComponent(node) => { element::component::split::render(node, context) } diff --git a/apps/gpui_components/test/test/gpui/ui/data_views_test.exs b/apps/gpui_components/test/test/gpui/ui/data_views_test.exs index a0e6a1f..9d991ac 100644 --- a/apps/gpui_components/test/test/gpui/ui/data_views_test.exs +++ b/apps/gpui_components/test/test/gpui/ui/data_views_test.exs @@ -63,6 +63,33 @@ defmodule GPUI.UI.DataViewsTest do assert attrs[:"phx-drop"] == "dropped" end + test "builds in-app drag sources and value-accepting drop targets" do + child = %Element{type: :text, children: ["Worker"]} + + assert %Element{type: :ui_drag_source, attrs: source, children: [^child]} = + UI.drag_source(%{id: "worker", value: "sprite:worker", children: [child]}) + + assert source[:value] == "sprite:worker" + + assert %Element{type: :ui_drop_target, attrs: target} = + UI.drop_target(%{id: "group", accepts: "values", "phx-drop": "add_worker"}) + + assert target[:accepts] == "values" + assert target[:"phx-drop"] == "add_worker" + assert UI.drop_target(%{id: "files"}).attrs[:accepts] == "files" + end + + test "drag source values obey the transfer payload UTF-8 and size limits" do + value = String.duplicate("x", 1_048_576) + assert UI.drag_source(%{id: "limit", value: value}).attrs[:value] == value + + for invalid <- [value <> "x", <<255>>] do + assert_raise ArgumentError, fn -> + UI.drag_source(%{id: "invalid", value: invalid}) + end + end + end + test "adds bounded clipboard reads to an ordinary button" do assert %Element{type: :ui_button, attrs: attrs} = UI.button(%{ diff --git a/apps/gpui_native/native/src/element/component.rs b/apps/gpui_native/native/src/element/component.rs index 7cb1c88..bef988a 100644 --- a/apps/gpui_native/native/src/element/component.rs +++ b/apps/gpui_native/native/src/element/component.rs @@ -9,6 +9,8 @@ pub(crate) mod data_table; #[cfg(feature = "components")] pub(crate) mod display; #[cfg(feature = "components")] +pub(crate) mod drag_source; +#[cfg(feature = "components")] pub(crate) mod drop_target; pub(crate) mod edge_fade; #[cfg(feature = "components")] diff --git a/apps/gpui_native/native/src/element/component/drag_source.rs b/apps/gpui_native/native/src/element/component/drag_source.rs new file mode 100644 index 0000000..2b240eb --- /dev/null +++ b/apps/gpui_native/native/src/element/component/drag_source.rs @@ -0,0 +1,57 @@ +use crate::{gpui, DragSourceComponentNode, ElementRenderContext}; + +/// The value an in-app drag carries to drop targets that accept values. +#[derive(Clone, Debug)] +pub(crate) struct DraggedValue { + pub(crate) value: String, +} + +/// Nothing follows the pointer: the application draws its own feedback +/// from the drop target's move events. +#[cfg(feature = "components")] +struct DragPreview; + +#[cfg(feature = "components")] +impl gpui::Render for DragPreview { + fn render( + &mut self, + _window: &mut gpui::Window, + _cx: &mut gpui::Context, + ) -> impl gpui::IntoElement { + gpui::div() + } +} + +#[cfg(feature = "components")] +pub(crate) fn render( + node: DragSourceComponentNode, + context: &mut ElementRenderContext<'_, '_>, +) -> gpui::AnyElement { + use crate::element::apply_generated_render_styles; + use gpui::{ + AppContext, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, + }; + + let children = node + .children + .into_iter() + .map(|child| child.render(context)) + .collect::>(); + let value = DraggedValue { value: node.value }; + + apply_generated_render_styles(gpui::div(), node.style) + .id(node.id) + .children(children) + .on_drag(value, |_value, _offset, _window, cx| { + cx.new(|_| DragPreview) + }) + .into_any_element() +} + +#[cfg(not(feature = "components"))] +pub(crate) fn render( + node: DragSourceComponentNode, + context: &mut ElementRenderContext<'_, '_>, +) -> gpui::AnyElement { + super::render_component_fallback(node.style, None, node.children, context) +} diff --git a/apps/gpui_native/native/src/element/component/drop_target.rs b/apps/gpui_native/native/src/element/component/drop_target.rs index ec3bb61..43ef773 100644 --- a/apps/gpui_native/native/src/element/component/drop_target.rs +++ b/apps/gpui_native/native/src/element/component/drop_target.rs @@ -1,5 +1,7 @@ use crate::{gpui, DropTargetComponentNode, ElementRenderContext}; +#[cfg(feature = "components")] +use super::drag_source::DraggedValue; #[cfg(feature = "components")] use std::sync::atomic::{AtomicU64, Ordering}; #[cfg(feature = "components")] @@ -47,7 +49,7 @@ impl ComponentDropTarget { target_id: &self.id, session_id: active.session_id, position: active.last_position, - paths: None, + payload: None, }, ); } @@ -71,148 +73,106 @@ pub(crate) fn render( .drop_target_mut(&node.id) .expect("drop target must exist after insertion"); component.update(&node); - let move_session = component.session.clone(); - let drop_session = component.session.clone(); - let exit_session = component.session.clone(); + + let target = TargetEvents { + session: component.session.clone(), + runtime: context.runtime.clone(), + window_id: context.window_id, + target_id: node.id.clone(), + enter: node.drag_enter.clone(), + moved: node.drag_move.clone(), + leave: node.drag_leave.clone(), + drop: node.drop.clone(), + }; + let accepts_values = node.accepts.as_deref() == Some("values"); let children = node .children .into_iter() .map(|child| child.render(context)) .collect::>(); - let move_runtime = context.runtime.clone(); - let drop_runtime = context.runtime.clone(); - let exit_runtime = context.runtime.clone(); - let window_id = context.window_id; - let target_id = node.id.clone(); - let move_target_id = target_id.clone(); - let exit_target_id = target_id.clone(); - let move_event = node.drag_move.clone(); - let enter_event = node.drag_enter.clone(); - let leave_event = node.drag_leave.clone(); - let exit_event = node.drag_leave.clone(); - let drop_event = node.drop.clone(); - - apply_generated_render_styles(gpui::div(), node.style) + let exit_target = target.clone(); + + let element = apply_generated_render_styles(gpui::div(), node.style) .id(node.id) .children(children) .child(gpui::canvas( |_bounds, _window, _cx| (), move |_bounds, (), window, _cx| { - let session = exit_session.clone(); - let runtime = exit_runtime.clone(); - let event = exit_event.clone(); - let target_id = exit_target_id.clone(); + let target = exit_target.clone(); window.on_mouse_event( move |file_event: &gpui::FileDropEvent, phase, _window, _cx| { - if phase != gpui::DispatchPhase::Bubble - || !matches!(file_event, gpui::FileDropEvent::Exited) + if phase == gpui::DispatchPhase::Bubble + && matches!(file_event, gpui::FileDropEvent::Exited) { - return; - } - let Ok(mut session) = session.lock() else { - return; - }; - let position = session.as_ref().map(|active| active.last_position); - if let Some(position) = position { - terminate_session( - &mut session, - &runtime, - window_id, - event.as_deref(), - &target_id, - position, - ); + target.exited(); } }, ); - }, - )) - .can_drop(|value, _window, _cx| value.is::()) - .on_drag_move::(move |event, _window, cx| { - let paths = bounded_paths(event.drag(cx)); - let Ok(mut session) = move_session.lock() else { - return; - }; - let position = event.event.position; - if !event.bounds.contains(&position) { - terminate_session( - &mut session, - &move_runtime, - window_id, - leave_event.as_deref(), - &move_target_id, - position, - ); - return; - } - if session.is_none() { - let Some(paths) = paths else { - return; - }; - let session_id = NEXT_TRANSFER_SESSION_ID.fetch_add(1, Ordering::Relaxed); - *session = Some(TransferSession { - session_id, - last_position: position, - paths: paths.clone(), + // A value drag ends with the mouse button. Once the release has + // been dispatched, a drop here has taken the session; one still + // open was released somewhere else. + let target = exit_target.clone(); + window.on_mouse_event(move |event: &gpui::MouseUpEvent, phase, window, cx| { + if phase == gpui::DispatchPhase::Bubble { + let target = target.clone(); + let position = event.position; + window.defer(cx, move |_window, _cx| target.released_elsewhere(position)); + } }); - if let Some(event_name) = enter_event.as_deref() { - emit_transfer( - &move_runtime, - crate::InputKind::DragEnter, - window_id, - event_name, - TransferEmission { - target_id: &move_target_id, - session_id, - position, - paths: Some(paths), - }, - ); - } - } - if let (Some(event_name), Some(session)) = (move_event.as_deref(), session.as_mut()) { - if session.last_position == position { - return; - } - session.last_position = position; - emit_transfer( - &move_runtime, - crate::InputKind::DragMove, - window_id, - event_name, - TransferEmission { - target_id: &move_target_id, - session_id: session.session_id, - position, - paths: None, - }, - ); - } - }) - .on_drop::(move |_paths, window, _cx| { - let Ok(mut session) = drop_session.lock() else { - return; - }; - let Some(active) = session.take() else { - return; - }; - if let Some(event_name) = drop_event.as_deref() { - emit_transfer( - &drop_runtime, - crate::InputKind::Drop, - window_id, - event_name, - TransferEmission { - target_id: &target_id, - session_id: active.session_id, - position: window.mouse_position(), - paths: Some(active.paths), - }, - ); - } - }) - .into_any_element() + }, + )); + + let move_target = target.clone(); + let drop_target = target; + + if accepts_values { + element + .can_drop(|value, _window, _cx| value.is::()) + .on_drag_move::(move |event, _window, cx| { + let carried = Carried::Value(event.drag(cx).value.clone()); + move_target.moved(event.event.position, event.bounds, Some(carried)); + }) + .on_drop::(move |_value, window, _cx| { + drop_target.dropped(window.mouse_position()); + }) + .into_any_element() + } else { + element + .can_drop(|value, _window, _cx| value.is::()) + .on_drag_move::(move |event, _window, cx| { + let carried = bounded_paths(event.drag(cx)).map(Carried::Paths); + move_target.moved(event.event.position, event.bounds, carried); + }) + .on_drop::(move |_paths, window, _cx| { + drop_target.dropped(window.mouse_position()); + }) + .into_any_element() + } +} + +/// What a drag brings: operating-system paths, or an in-app drag source's value. +#[cfg(feature = "components")] +#[derive(Clone)] +enum Carried { + Paths(Vec), + Value(String), +} + +#[cfg(feature = "components")] +impl Carried { + fn payload(self) -> crate::TransferPayload { + match self { + Carried::Paths(external_paths) => crate::TransferPayload { + text: None, + external_paths, + }, + Carried::Value(value) => crate::TransferPayload { + text: Some(value), + external_paths: Vec::new(), + }, + } + } } #[cfg(feature = "components")] @@ -220,29 +180,145 @@ pub(crate) fn render( struct TransferSession { session_id: u64, last_position: gpui::Point, - paths: Vec, + carried: Carried, } +/// One rendered target's session and the events it reports. #[cfg(feature = "components")] -fn terminate_session( - session: &mut Option, - runtime: &crate::SharedRuntime, +#[derive(Clone)] +struct TargetEvents { + session: Arc>>, + runtime: crate::SharedRuntime, window_id: u64, - event: Option<&str>, - target_id: &str, - position: gpui::Point, -) { - if let (Some(active), Some(event)) = (session.take(), event) { + target_id: String, + enter: Option, + moved: Option, + leave: Option, + drop: Option, +} + +#[cfg(feature = "components")] +impl TargetEvents { + fn moved( + &self, + position: gpui::Point, + bounds: gpui::Bounds, + carried: Option, + ) { + let Ok(mut session) = self.session.lock() else { + return; + }; + if !bounds.contains(&position) { + self.leave(&mut session, position); + return; + } + if session.is_none() { + let Some(carried) = carried else { + return; + }; + let session_id = NEXT_TRANSFER_SESSION_ID.fetch_add(1, Ordering::Relaxed); + *session = Some(TransferSession { + session_id, + last_position: position, + carried: carried.clone(), + }); + if let Some(event) = self.enter.as_deref() { + self.emit( + crate::InputKind::DragEnter, + event, + session_id, + position, + Some(carried.payload()), + ); + } + } + if let (Some(event), Some(active)) = (self.moved.as_deref(), session.as_mut()) { + if active.last_position == position { + return; + } + active.last_position = position; + self.emit( + crate::InputKind::DragMove, + event, + active.session_id, + position, + None, + ); + } + } + + fn exited(&self) { + let Ok(mut session) = self.session.lock() else { + return; + }; + if let Some(position) = session.as_ref().map(|active| active.last_position) { + self.leave(&mut session, position); + } + } + + fn released_elsewhere(&self, position: gpui::Point) { + let Ok(mut session) = self.session.lock() else { + return; + }; + if matches!( + session.as_ref(), + Some(TransferSession { + carried: Carried::Value(_), + .. + }) + ) { + self.leave(&mut session, position); + } + } + + fn dropped(&self, position: gpui::Point) { + let Ok(mut session) = self.session.lock() else { + return; + }; + let Some(active) = session.take() else { + return; + }; + if let Some(event) = self.drop.as_deref() { + self.emit( + crate::InputKind::Drop, + event, + active.session_id, + position, + Some(active.carried.payload()), + ); + } + } + + fn leave(&self, session: &mut Option, position: gpui::Point) { + if let (Some(active), Some(event)) = (session.take(), self.leave.as_deref()) { + self.emit( + crate::InputKind::DragLeave, + event, + active.session_id, + position, + None, + ); + } + } + + fn emit( + &self, + kind: crate::InputKind, + event: &str, + session_id: u64, + position: gpui::Point, + payload: Option, + ) { emit_transfer( - runtime, - crate::InputKind::DragLeave, - window_id, + &self.runtime, + kind, + self.window_id, event, TransferEmission { - target_id, - session_id: active.session_id, + target_id: &self.target_id, + session_id, position, - paths: None, + payload, }, ); } @@ -265,7 +341,7 @@ struct TransferEmission<'a> { target_id: &'a str, session_id: u64, position: gpui::Point, - paths: Option>, + payload: Option, } #[cfg(feature = "components")] @@ -276,10 +352,6 @@ fn emit_transfer( event: &str, emission: TransferEmission<'_>, ) { - let payload = emission.paths.map(|external_paths| crate::TransferPayload { - text: None, - external_paths, - }); let _ = crate::push_event( runtime, crate::NativeEvent::Transfer { @@ -292,7 +364,7 @@ fn emit_transfer( x: f32::from(emission.position.x) as f64, y: f32::from(emission.position.y) as f64, coordinate_space: "window_native_pixels".to_string(), - payload, + payload: emission.payload, }, }, ); @@ -472,6 +544,188 @@ mod tests { ); } + #[cfg(feature = "components")] + #[gpui::test] + fn value_drags_enter_move_and_drop_with_their_value(cx: &mut gpui::TestAppContext) { + use gpui::{point, px, Modifiers, MouseButton}; + + let runtime = value_drag_window(cx, Some("values".to_string()), |cx| { + cx.simulate_mouse_down( + point(px(20.0), px(20.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(30.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(70.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(40.0), px(90.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_up( + point(px(40.0), px(90.0)), + MouseButton::Left, + Modifiers::none(), + ); + }); + + let events = runtime.events.lock().unwrap(); + assert_eq!(transfer_kinds(&events), vec!["enter", "move", "drop"]); + let carried = Some(crate::TransferPayload { + text: Some("sprite:a".to_string()), + external_paths: Vec::new(), + }); + assert_eq!( + transfer_payloads(&events), + vec![carried.clone(), None, carried] + ); + } + + #[cfg(feature = "components")] + #[gpui::test] + fn a_value_drag_released_elsewhere_leaves(cx: &mut gpui::TestAppContext) { + use gpui::{point, px, Modifiers, MouseButton}; + + let runtime = value_drag_window(cx, Some("values".to_string()), |cx| { + cx.simulate_mouse_down( + point(px(20.0), px(20.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(30.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(70.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_up( + point(px(180.0), px(20.0)), + MouseButton::Left, + Modifiers::none(), + ); + }); + + assert_eq!( + transfer_kinds(&runtime.events.lock().unwrap()), + vec!["enter", "leave"] + ); + } + + #[cfg(feature = "components")] + #[gpui::test] + fn a_file_target_ignores_value_drags(cx: &mut gpui::TestAppContext) { + use gpui::{point, px, Modifiers, MouseButton}; + + let runtime = value_drag_window(cx, None, |cx| { + cx.simulate_mouse_down( + point(px(20.0), px(20.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(30.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_move( + point(px(30.0), px(70.0)), + MouseButton::Left, + Modifiers::none(), + ); + cx.simulate_mouse_up( + point(px(30.0), px(70.0)), + MouseButton::Left, + Modifiers::none(), + ); + }); + + assert!(transfer_kinds(&runtime.events.lock().unwrap()).is_empty()); + } + + // A 160×40 drag source carrying "sprite:a" above a 160×80 drop target. + #[cfg(feature = "components")] + fn value_drag_window( + cx: &mut gpui::TestAppContext, + accepts: Option, + drive: impl FnOnce(&mut gpui::VisualTestContext), + ) -> std::sync::Arc { + use gpui::{point, px, size, IntoElement}; + + let mut source_style = crate::StyleAttrs::default(); + source_style.width = Some(gpui::px(160.0).into()); + source_style.height = Some(gpui::px(40.0).into()); + let source = crate::ElementNode::DragSourceComponent(crate::DragSourceComponentNode { + style: source_style, + id: "handle".to_string(), + value: "sprite:a".to_string(), + children: Vec::new(), + }); + + let crate::ElementNode::DropTargetComponent(mut target) = drop_target_tree() else { + unreachable!("drop_target_tree builds a drop target"); + }; + target.accepts = accepts; + + let tree = crate::ElementNode::Div(crate::ContainerNode { + tag: crate::GeneratedElementTag::Div, + style: crate::StyleAttrs::default(), + id: None, + accessibility: crate::AccessibilitySemantics::default(), + children: vec![source, crate::ElementNode::DropTargetComponent(target)], + click: None, + bounds_change: None, + focus_request: 0, + focus: None, + blur: None, + motion_request: 0, + motion_duration: 180, + motion_delay: 0, + motion_easing: "ease_out".to_string(), + motion_policy: "respect_system".to_string(), + motion_from_opacity: 1.0, + motion_from_x: 0.0, + motion_from_y: 0.0, + window_control: None, + }); + + let runtime = std::sync::Arc::new(crate::runtime::RuntimeState::new()); + let state = std::sync::Arc::new(crate::WindowState::new(tree, Vec::new())); + let runtime_for_view = runtime.clone(); + let (view, cx) = cx.add_window_view(move |_window, _cx| { + crate::ElixirRoot::new(state, runtime_for_view, 7, false, false) + }); + cx.draw( + point(px(0.0), px(0.0)), + size(px(200.0), px(160.0)), + |_window, _cx| view.clone().into_any_element(), + ); + drive(cx); + runtime + } + + #[cfg(feature = "components")] + fn transfer_payloads(events: &[crate::NativeEvent]) -> Vec> { + events + .iter() + .filter_map(|event| match event { + crate::NativeEvent::Transfer { value, .. } => Some(value.payload.clone()), + _ => None, + }) + .collect() + } + #[cfg(feature = "components")] fn drop_target_tree() -> crate::ElementNode { let mut style = crate::StyleAttrs::default(); @@ -480,6 +734,7 @@ mod tests { crate::ElementNode::DropTargetComponent(crate::DropTargetComponentNode { style, id: "drop-zone".to_string(), + accepts: None, children: Vec::new(), drag_enter: Some("enter".to_string()), drag_move: Some("move".to_string()), diff --git a/apps/gpui_native/native/src/generated/atoms.rs b/apps/gpui_native/native/src/generated/atoms.rs index 566aca1..32583d1 100644 --- a/apps/gpui_native/native/src/generated/atoms.rs +++ b/apps/gpui_native/native/src/generated/atoms.rs @@ -2,24 +2,25 @@ mod atoms { rustler::atoms! { - __extension_version__ = "__extension_version__", __type__ = "__type__", - accessibility_checked = "accessibility_checked", accessibility_description = - "accessibility_description", accessibility_disabled = "accessibility_disabled", - accessibility_expanded = "accessibility_expanded", accessibility_label = - "accessibility_label", accessibility_orientation = "accessibility_orientation", - accessibility_role = "accessibility_role", accessibility_selected = - "accessibility_selected", accessibility_value = "accessibility_value", active = - "active", align = "align", align_items = "align_items", alignment = "alignment", - anchor = "anchor", appearance = "appearance", attrs = "attrs", auto_grow = - "auto_grow", background = "background", block_projections = "block_projections", - blur = "blur", border_color = "border_color", border_radius = "border_radius", - border_width = "border_width", bordered = "bordered", bottom = "bottom", bounds = - "bounds", branch = "branch", buffer = "buffer", cancelled = "cancelled", - cell_change = "cell_change", change = "change", checked = "checked", children = - "children", cleanable = "cleanable", click = "click", clipboard = "clipboard", - clipboard_text = "clipboard_text", clipboard_write = "clipboard_write", closable - = "closable", close_button = "close_button", collapsed = "collapsed", collapsible - = "collapsible", color = "color", command = "command", commands = "commands", + __extension_version__ = "__extension_version__", __type__ = "__type__", accepts = + "accepts", accessibility_checked = "accessibility_checked", + accessibility_description = "accessibility_description", accessibility_disabled = + "accessibility_disabled", accessibility_expanded = "accessibility_expanded", + accessibility_label = "accessibility_label", accessibility_orientation = + "accessibility_orientation", accessibility_role = "accessibility_role", + accessibility_selected = "accessibility_selected", accessibility_value = + "accessibility_value", active = "active", align = "align", align_items = + "align_items", alignment = "alignment", anchor = "anchor", appearance = + "appearance", attrs = "attrs", auto_grow = "auto_grow", background = + "background", block_projections = "block_projections", blur = "blur", + border_color = "border_color", border_radius = "border_radius", border_width = + "border_width", bordered = "bordered", bottom = "bottom", bounds = "bounds", + branch = "branch", buffer = "buffer", cancelled = "cancelled", cell_change = + "cell_change", change = "change", checked = "checked", children = "children", + cleanable = "cleanable", click = "click", clipboard = "clipboard", clipboard_text + = "clipboard_text", clipboard_write = "clipboard_write", closable = "closable", + close_button = "close_button", collapsed = "collapsed", collapsible = + "collapsible", color = "color", command = "command", commands = "commands", compact = "compact", content = "content", copy = "copy", cursor = "cursor", dark = "dark", dashed = "dashed", data = "data", decorations = "decorations", delay = "delay", disabled = "disabled", display = "display", drag_enter = "drag_enter", diff --git a/apps/gpui_native/native/src/generated/schema.rs b/apps/gpui_native/native/src/generated/schema.rs index bea7448..17f89ec 100644 --- a/apps/gpui_native/native/src/generated/schema.rs +++ b/apps/gpui_native/native/src/generated/schema.rs @@ -13,6 +13,7 @@ pub enum GeneratedComponentKind { FrostComponent, PaintComponent, DropTargetComponent, + DragSourceComponent, SplitComponent, ButtonComponent, ProgressComponent, @@ -2294,6 +2295,7 @@ pub(crate) fn decode_generated_paint_component<'a>( pub(crate) struct DropTargetComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, + pub(crate) accepts: Option, pub(crate) children: Vec, pub(crate) drag_enter: Option, pub(crate) drag_move: Option, @@ -2309,6 +2311,14 @@ pub(crate) fn decode_generated_drop_target_component<'a>( Ok(DropTargetComponentNode { style: decode_style(term)?, id: component_required_string_attr(term, atoms::id())?, + accepts: match component_enum_attr( + term, + atoms::accepts(), + &vec!["files", "values"], + )? { + Some(value) => Some(value), + None => Some("files".to_string()), + }, children: decode_children(term)?, drag_enter: component_string_attr(term, atoms::phx_drag_enter())?, drag_move: component_string_attr(term, atoms::phx_drag_move())?, @@ -2319,6 +2329,28 @@ pub(crate) fn decode_generated_drop_target_component<'a>( #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct DragSourceComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) value: String, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_drag_source_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(DragSourceComponentNode { + style: decode_style(term)?, + id: component_required_string_attr(term, atoms::id())?, + value: component_required_string_attr(term, atoms::value())?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct SplitComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -3840,6 +3872,7 @@ pub(crate) enum ElementNode { FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), DropTargetComponent(DropTargetComponentNode), + DragSourceComponent(DragSourceComponentNode), SplitComponent(SplitComponentNode), ButtonComponent(ButtonComponentNode), ProgressComponent(ProgressComponentNode), @@ -3905,6 +3938,7 @@ pub enum GeneratedElementTag { UiFrost, UiPaint, UiDropTarget, + UiDragSource, UiSplit, UiButton, UiProgress, @@ -3969,6 +4003,7 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, "ui_drop_target" => GeneratedElementTag::UiDropTarget, + "ui_drag_source" => GeneratedElementTag::UiDragSource, "ui_split" => GeneratedElementTag::UiSplit, "ui_button" => GeneratedElementTag::UiButton, "ui_progress" => GeneratedElementTag::UiProgress, @@ -4034,6 +4069,7 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, GeneratedElementTag::UiDropTarget => GeneratedComponentKind::DropTargetComponent, + GeneratedElementTag::UiDragSource => GeneratedComponentKind::DragSourceComponent, GeneratedElementTag::UiSplit => GeneratedComponentKind::SplitComponent, GeneratedElementTag::UiButton => GeneratedComponentKind::ButtonComponent, GeneratedElementTag::UiProgress => GeneratedComponentKind::ProgressComponent, @@ -4147,6 +4183,10 @@ pub(crate) fn decode_generated_element_node<'a>( decode_generated_drop_target_component(term) .map(|node| ElementNode::DropTargetComponent(node)) } + GeneratedComponentKind::DragSourceComponent => { + decode_generated_drag_source_component(term) + .map(|node| ElementNode::DragSourceComponent(node)) + } GeneratedComponentKind::SplitComponent => { decode_generated_split_component(term) .map(|node| ElementNode::SplitComponent(node)) @@ -4345,6 +4385,9 @@ pub(crate) fn render_generated_component_node( ElementNode::DropTargetComponent(node) => { element::component::drop_target::render(node, context) } + ElementNode::DragSourceComponent(node) => { + element::component::drag_source::render(node, context) + } ElementNode::SplitComponent(node) => { element::component::split::render(node, context) }