1use 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#[derive(Debug)]
36pub struct SystemContextMenu {
37 pub key: Option<KeyRef>,
39 pub anchor: Rect,
41 pub items: Vec<IOSSystemContextMenuItem>,
43 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 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 pub fn items(mut self, items: Vec<IOSSystemContextMenuItem>) -> SystemContextMenu {
90 self.items = items;
91 self
92 }
93
94 pub fn key(mut self, key: KeyRef) -> SystemContextMenu {
96 self.key = Some(key);
97 self
98 }
99
100 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 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 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
164pub 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#[derive(Clone, Debug)]
212pub enum IOSSystemContextMenuItem {
213 Copy,
215 Cut,
217 Paste,
219 SelectAll,
221 LookUp {
223 title: Option<String>,
225 },
226 SearchWeb {
228 title: Option<String>,
230 },
231 Share {
233 title: Option<String>,
235 },
236 LiveText,
238 Custom {
240 title: String,
242 on_pressed: Listener,
244 },
245}
246
247impl IOSSystemContextMenuItem {
248 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 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}