Skip to main content

waft_widgets/widgets/
system_context_menu.rs

1//! Flutter counterpart: `widgets/system_context_menu.dart`.
2
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use waft_embedder::{Rect, TargetPlatform};
6use waft_foundation::{
7    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listener, ObjectFlagProperty,
8    OptionRetained, StringProperty,
9};
10use waft_rendering::RenderBox;
11use waft_services::TextSelectionDelegate;
12use waft_services::{IOSSystemContextMenuItemData, SystemContextMenuController};
13
14use crate::framework::{
15    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
16};
17use crate::widgets::basic::SizedBox;
18use crate::widgets::context_menu_button_item::ContextMenuButtonType;
19use crate::widgets::editable_text::EditableTextState;
20use crate::widgets::localizations::WidgetsLocalizations;
21use crate::widgets::media_query::MediaQuery;
22use crate::widgets::text_selection_toolbar_anchors::TextSelectionToolbarAnchors;
23use waft_foundation::Ref;
24
25static NEXT_CUSTOM_CALLBACK_ID: AtomicU64 = AtomicU64::new(1);
26
27/// Displays the system context menu on top of the Flutter view.
28///
29/// Currently, only supports iOS 16.0 and above and displays nothing on other
30/// platforms.
31///
32/// The context menu is the menu that appears, for example, when doing text
33/// selection. Flutter typically draws this menu itself, but this class deals
34/// with the platform-rendered context menu instead.
35#[derive(Debug)]
36pub struct SystemContextMenu {
37    /// See [`StatefulWidget::key`].
38    pub key: Option<KeyRef>,
39    /// The [`Rect`] that the context menu should point to.
40    pub anchor: Rect,
41    /// A list of the items to be displayed in the system context menu.
42    pub items: Vec<IOSSystemContextMenuItem>,
43    /// Called when the system hides this context menu.
44    pub on_system_hide: Option<Listener>,
45}
46
47impl SystemContextMenu {
48    fn from_fields(
49        anchor: Rect,
50        items: Vec<IOSSystemContextMenuItem>,
51        on_system_hide: Option<Listener>,
52    ) -> SystemContextMenu {
53        SystemContextMenu {
54            key: None,
55            anchor,
56            items,
57            on_system_hide,
58        }
59    }
60
61    /// Creates an instance of [`SystemContextMenu`] for the field indicated by the
62    /// given [`EditableTextState`].
63    pub fn editable_text(
64        app: &mut App,
65        editable_text_state: Handle<EditableTextState>,
66    ) -> SystemContextMenu {
67        let (start_glyph_height, end_glyph_height) = editable_text_state.get_glyph_heights(app);
68        let render_editable = editable_text_state.render_editable(app);
69        let selection = editable_text_state.text_editing_value(app).selection;
70        let endpoints = render_editable.get_endpoints_for_selection(app, selection);
71        let anchor = TextSelectionToolbarAnchors::get_selection_rect(
72            app,
73            render_editable.as_box(),
74            start_glyph_height,
75            end_glyph_height,
76            &endpoints,
77        );
78        let items = Self::get_default_items(app, editable_text_state);
79        SystemContextMenu::from_fields(
80            anchor,
81            items,
82            Some(Listener::new(move |app| {
83                TextSelectionDelegate::hide_toolbar(editable_text_state, app, false);
84            })),
85        )
86    }
87
88    /// Dart `SystemContextMenu.editableText(items:)`.
89    pub fn items(mut self, items: Vec<IOSSystemContextMenuItem>) -> SystemContextMenu {
90        self.items = items;
91        self
92    }
93
94    /// Dart `SystemContextMenu(key:)`.
95    pub fn key(mut self, key: KeyRef) -> SystemContextMenu {
96        self.key = Some(key);
97        self
98    }
99
100    /// Whether the current device supports showing the system context menu.
101    ///
102    /// Currently, this is only supported on newer versions of iOS.
103    pub fn is_supported(app: &mut App, context: BuildContext) -> bool {
104        app.platform().target_platform() == TargetPlatform::IOS
105            && MediaQuery::maybe_supports_showing_system_context_menu(app, context).unwrap_or(false)
106    }
107
108    /// Whether the given field supports showing the system context menu.
109    pub fn is_supported_by_field(
110        app: &mut App,
111        editable_text_state: Handle<EditableTextState>,
112    ) -> bool {
113        let read_only = editable_text_state.widget(app).read_only;
114        let context = editable_text_state.context(app);
115        !read_only && Self::is_supported(app, context)
116    }
117
118    /// The default [`items`](Self::items) for the given [`EditableTextState`].
119    pub fn get_default_items(
120        app: &mut App,
121        editable_text_state: Handle<EditableTextState>,
122    ) -> Vec<IOSSystemContextMenuItem> {
123        let mut items = Vec::new();
124        for button in editable_text_state.context_menu_button_items(app) {
125            match button.r#type {
126                ContextMenuButtonType::Copy => items.push(IOSSystemContextMenuItem::Copy),
127                ContextMenuButtonType::Cut => items.push(IOSSystemContextMenuItem::Cut),
128                ContextMenuButtonType::Paste => items.push(IOSSystemContextMenuItem::Paste),
129                ContextMenuButtonType::SelectAll => items.push(IOSSystemContextMenuItem::SelectAll),
130                ContextMenuButtonType::LookUp => {
131                    items.push(IOSSystemContextMenuItem::LookUp { title: None })
132                }
133                ContextMenuButtonType::SearchWeb => {
134                    items.push(IOSSystemContextMenuItem::SearchWeb { title: None })
135                }
136                ContextMenuButtonType::Share => {
137                    items.push(IOSSystemContextMenuItem::Share { title: None })
138                }
139                ContextMenuButtonType::LiveTextInput => {
140                    items.push(IOSSystemContextMenuItem::LiveText)
141                }
142                ContextMenuButtonType::Delete | ContextMenuButtonType::Custom => {}
143            }
144        }
145        items
146    }
147}
148
149impl StatefulWidget for SystemContextMenu {
150    type State = SystemContextMenuState;
151
152    fn key(&self) -> Option<&KeyRef> {
153        self.key.as_ref()
154    }
155
156    fn create_state(&self) -> SystemContextMenuState {
157        SystemContextMenuState {
158            state: StateData::new(),
159            controller: None,
160        }
161    }
162}
163
164/// State for [`SystemContextMenu`].
165pub struct SystemContextMenuState {
166    state: StateData<SystemContextMenu>,
167    controller: Option<Ref<SystemContextMenuController>>,
168}
169
170impl State for SystemContextMenuState {
171    type Widget = SystemContextMenu;
172    crate::state_accessors!();
173
174    fn init_state(self: Handle<Self>, app: &mut App) {
175        let on_hide = self.widget(app).on_system_hide.clone();
176        let controller = SystemContextMenuController::new(app, on_hide);
177        app.get_mut(self).controller = Some(controller);
178    }
179
180    fn dispose(self: Handle<Self>, app: &mut App) {
181        if let Some(controller) = app.get(self).controller.handle() {
182            controller.dispose(app);
183        }
184    }
185
186    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
187        debug_assert!(SystemContextMenu::is_supported(app, context));
188        let items = self.widget(app).items.clone();
189        let anchor = self.widget(app).anchor;
190        if !items.is_empty() {
191            let localizations = <dyn WidgetsLocalizations>::of(app, context);
192            let item_datas: Vec<IOSSystemContextMenuItemData> = items
193                .iter()
194                .map(|item| item.get_data(localizations.as_ref()))
195                .collect();
196            let controller = app
197                .get(self)
198                .controller
199                .handle()
200                .expect("created in initState");
201            controller.show_with_items(app, anchor, item_datas);
202        }
203        SizedBox::shrink().into_widget()
204    }
205}
206
207/// Describes a context menu button that will be rendered in the iOS system
208/// context menu and not by Flutter itself.
209///
210/// Dart's sealed `IOSSystemContextMenuItem` subclasses are the variants.
211#[derive(Clone, Debug)]
212pub enum IOSSystemContextMenuItem {
213    /// The system's built-in copy button.
214    Copy,
215    /// The system's built-in cut button.
216    Cut,
217    /// The system's built-in paste button.
218    Paste,
219    /// The system's built-in select-all button.
220    SelectAll,
221    /// The system's built-in look-up button.
222    LookUp {
223        /// Optional title; defaults to [`WidgetsLocalizations::look_up_button_label`].
224        title: Option<String>,
225    },
226    /// The system's built-in search-web button.
227    SearchWeb {
228        /// Optional title; defaults to [`WidgetsLocalizations::search_web_button_label`].
229        title: Option<String>,
230    },
231    /// The system's built-in share button.
232    Share {
233        /// Optional title; defaults to [`WidgetsLocalizations::share_button_label`].
234        title: Option<String>,
235    },
236    /// The system's built-in Live Text button.
237    LiveText,
238    /// A developer-defined button.
239    Custom {
240        /// Title shown in the menu.
241        title: String,
242        /// Callback when the item is selected.
243        on_pressed: Listener,
244    },
245}
246
247impl IOSSystemContextMenuItem {
248    /// Dart's `IOSSystemContextMenuItem` subclasses' `debugFillProperties`.
249    pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
250        match self {
251            Self::LookUp { title } | Self::SearchWeb { title } => {
252                properties.add(DiagnosticsProperty::<String>::new("title", title.clone()));
253            }
254            Self::Share { title } => {
255                properties.add(StringProperty::new("title", title.clone()));
256            }
257            Self::Custom { title, on_pressed } => {
258                properties.add(StringProperty::new("title", Some(title.clone())));
259                properties.add(ObjectFlagProperty::<String>::has(
260                    "onPressed",
261                    Some(format!("{on_pressed:?}")),
262                ));
263            }
264            Self::Copy | Self::Cut | Self::Paste | Self::SelectAll | Self::LiveText => {}
265        }
266    }
267
268    /// Returns the representation of this class used by the host.
269    pub fn get_data(
270        &self,
271        localizations: &dyn WidgetsLocalizations,
272    ) -> IOSSystemContextMenuItemData {
273        match self {
274            Self::Copy => IOSSystemContextMenuItemData::Copy,
275            Self::Cut => IOSSystemContextMenuItemData::Cut,
276            Self::Paste => IOSSystemContextMenuItemData::Paste,
277            Self::SelectAll => IOSSystemContextMenuItemData::SelectAll,
278            Self::LookUp { title } => IOSSystemContextMenuItemData::LookUp {
279                title: title
280                    .clone()
281                    .unwrap_or_else(|| localizations.look_up_button_label()),
282            },
283            Self::SearchWeb { title } => IOSSystemContextMenuItemData::SearchWeb {
284                title: title
285                    .clone()
286                    .unwrap_or_else(|| localizations.search_web_button_label()),
287            },
288            Self::Share { title } => IOSSystemContextMenuItemData::Share {
289                title: title
290                    .clone()
291                    .unwrap_or_else(|| localizations.share_button_label()),
292            },
293            Self::LiveText => IOSSystemContextMenuItemData::LiveText,
294            Self::Custom { title, on_pressed } => IOSSystemContextMenuItemData::Custom {
295                title: title.clone(),
296                on_pressed: on_pressed.clone(),
297                callback_id: NEXT_CUSTOM_CALLBACK_ID
298                    .fetch_add(1, Ordering::Relaxed)
299                    .to_string(),
300            },
301        }
302    }
303}
304
305impl PartialEq for IOSSystemContextMenuItem {
306    fn eq(&self, other: &IOSSystemContextMenuItem) -> bool {
307        match (self, other) {
308            (Self::Copy, Self::Copy)
309            | (Self::Cut, Self::Cut)
310            | (Self::Paste, Self::Paste)
311            | (Self::SelectAll, Self::SelectAll)
312            | (Self::LiveText, Self::LiveText) => true,
313            (Self::LookUp { title: a }, Self::LookUp { title: b })
314            | (Self::SearchWeb { title: a }, Self::SearchWeb { title: b })
315            | (Self::Share { title: a }, Self::Share { title: b }) => a == b,
316            (
317                Self::Custom {
318                    title: a,
319                    on_pressed: a_cb,
320                },
321                Self::Custom {
322                    title: b,
323                    on_pressed: b_cb,
324                },
325            ) => a == b && a_cb == b_cb,
326            _ => false,
327        }
328    }
329}