1use std::borrow::Cow;
5use std::sync::Arc;
6
7use super::menu_bar::MenuBarState;
8use super::menu_tree::MenuTree;
9#[cfg(wayland_platform)]
10use crate::app::cosmic::{WINDOWING_SYSTEM, WindowingSystem};
11use crate::style::menu_bar::StyleSheet;
12
13use iced::{Alignment, window};
14use iced_core::{Border, Renderer as IcedRenderer, Shadow, Widget};
15use iced_widget::core::layout::{Limits, Node};
16use iced_widget::core::mouse::{self, Cursor};
17use iced_widget::core::widget::Tree;
18use iced_widget::core::{
19 Clipboard, Layout, Length, Padding, Point, Rectangle, Shell, Size, Vector, event, overlay,
20 renderer, touch,
21};
22
23#[derive(Debug, Clone, Copy)]
25pub struct CloseCondition {
26 pub leave: bool,
28
29 pub click_outside: bool,
31
32 pub click_inside: bool,
34}
35
36#[derive(Debug, Clone, Copy)]
38pub enum ItemWidth {
39 Uniform(u16),
41 Static(u16),
47}
48
49#[derive(Debug, Clone, Copy)]
51pub enum ItemHeight {
52 Uniform(u16),
54 Static(u16),
57 Dynamic(u16),
66}
67
68#[derive(Debug, Clone, Copy)]
70pub enum PathHighlight {
71 Full,
73 OmitActive,
75 MenuActive,
77}
78
79#[derive(Debug, Clone, Copy)]
81pub(crate) enum Direction {
82 Positive,
83 Negative,
84}
85
86#[derive(Debug)]
88#[allow(clippy::struct_excessive_bools)]
89struct Aod {
90 horizontal: bool,
92 vertical: bool,
93
94 horizontal_overlap: bool,
96 vertical_overlap: bool,
97
98 horizontal_direction: Direction,
100 vertical_direction: Direction,
101
102 horizontal_offset: f32,
104 vertical_offset: f32,
105}
106impl Aod {
107 #[allow(clippy::too_many_arguments)]
109 fn adaptive(
110 parent_pos: f32,
111 parent_size: f32,
112 child_size: f32,
113 max_size: f32,
114 offset: f32,
115 on: bool,
116 overlap: bool,
117 direction: Direction,
118 ) -> (f32, f32) {
119 match direction {
149 Direction::Positive => {
150 let space_negative = parent_pos;
151 let space_positive = max_size - parent_pos - parent_size;
152
153 if overlap {
154 let overshoot = child_size - parent_size;
155 if on && space_negative > space_positive && overshoot > space_positive {
156 (parent_pos - overshoot, parent_pos - overshoot)
157 } else {
158 (parent_pos, parent_pos)
159 }
160 } else {
161 let overshoot = child_size + offset;
162 if on && space_negative > space_positive && overshoot > space_positive {
163 (parent_pos - overshoot, parent_pos - offset)
164 } else {
165 (parent_pos + parent_size + offset, parent_pos + parent_size)
166 }
167 }
168 }
169 Direction::Negative => {
170 let space_positive = parent_pos;
171 let space_negative = max_size - parent_pos - parent_size;
172
173 if overlap {
174 let overshoot = child_size - parent_size;
175 if on && space_negative > space_positive && overshoot > space_positive {
176 (parent_pos, parent_pos)
177 } else {
178 (parent_pos - overshoot, parent_pos - overshoot)
179 }
180 } else {
181 let overshoot = child_size + offset;
182 if on && space_negative > space_positive && overshoot > space_positive {
183 (parent_pos + parent_size + offset, parent_pos + parent_size)
184 } else {
185 (parent_pos - overshoot, parent_pos - offset)
186 }
187 }
188 }
189 }
190 }
191
192 fn resolve(
194 &self,
195 parent_bounds: Rectangle,
196 children_size: Size,
197 viewport_size: Size,
198 ) -> (Point, Point) {
199 let (x, ox) = Self::adaptive(
200 parent_bounds.x,
201 parent_bounds.width,
202 children_size.width,
203 viewport_size.width,
204 self.horizontal_offset,
205 self.horizontal,
206 self.horizontal_overlap,
207 self.horizontal_direction,
208 );
209 let (y, oy) = Self::adaptive(
210 parent_bounds.y,
211 parent_bounds.height,
212 children_size.height,
213 viewport_size.height,
214 self.vertical_offset,
215 self.vertical,
216 self.vertical_overlap,
217 self.vertical_direction,
218 );
219
220 ([x, y].into(), [ox, oy].into())
221 }
222}
223
224#[derive(Debug, Clone, Copy)]
230pub(super) struct MenuSlice {
231 pub(super) start_index: usize,
232 pub(super) end_index: usize,
233 pub(super) lower_bound_rel: f32,
234 pub(super) upper_bound_rel: f32,
235}
236
237#[derive(Debug, Clone)]
238pub struct MenuBounds {
240 pub(crate) child_positions: Vec<f32>,
241 child_sizes: Vec<Size>,
242 children_bounds: Rectangle,
243 pub parent_bounds: Rectangle,
244 check_bounds: Rectangle,
245 offset_bounds: Rectangle,
246}
247impl MenuBounds {
248 #[allow(clippy::too_many_arguments)]
249 fn new<Message>(
250 menu_tree: &MenuTree<Message>,
251 renderer: &crate::Renderer,
252 item_width: ItemWidth,
253 item_height: ItemHeight,
254 viewport_size: Size,
255 overlay_offset: Vector,
256 aod: &Aod,
257 bounds_expand: u16,
258 parent_bounds: Rectangle,
259 tree: &mut [Tree],
260 is_overlay: bool,
261 ) -> Self {
262 let (children_size, child_positions, child_sizes) =
263 get_children_layout(menu_tree, renderer, item_width, item_height, tree);
264
265 let view_parent_bounds = parent_bounds + overlay_offset;
267
268 let (children_position, offset_position) = {
270 let (cp, op) = aod.resolve(view_parent_bounds, children_size, viewport_size);
271 if is_overlay {
272 (cp - overlay_offset, op - overlay_offset)
273 } else {
274 (Point::ORIGIN, op - overlay_offset)
275 }
276 };
277
278 let delta = children_position - offset_position;
280 let offset_size = if delta.x.abs() > delta.y.abs() {
281 Size::new(delta.x, children_size.height)
282 } else {
283 Size::new(children_size.width, delta.y)
284 };
285 let offset_bounds = Rectangle::new(offset_position, offset_size);
286
287 let children_bounds = Rectangle::new(children_position, children_size);
288 let check_bounds = pad_rectangle(children_bounds, bounds_expand.into());
289
290 Self {
291 child_positions,
292 child_sizes,
293 children_bounds,
294 parent_bounds,
295 check_bounds,
296 offset_bounds,
297 }
298 }
299}
300
301#[derive(Clone)]
302pub(crate) struct MenuState {
303 pub(crate) index: Option<usize>,
305 scroll_offset: f32,
306 pub menu_bounds: MenuBounds,
307}
308impl MenuState {
309 pub(super) fn layout<Message>(
310 &mut self,
311 overlay_offset: Vector,
312 slice: MenuSlice,
313 renderer: &crate::Renderer,
314 menu_tree: &[MenuTree<Message>],
315 tree: &mut [Tree],
316 ) -> Node {
317 let MenuSlice {
318 start_index,
319 end_index,
320 lower_bound_rel,
321 upper_bound_rel,
322 } = slice;
323
324 debug_assert_eq!(menu_tree.len(), self.menu_bounds.child_positions.len());
325
326 let children_bounds = self.menu_bounds.children_bounds + overlay_offset;
328 let child_nodes = self.menu_bounds.child_positions[start_index..=end_index]
329 .iter_mut()
330 .zip(self.menu_bounds.child_sizes[start_index..=end_index].iter_mut())
331 .zip(menu_tree[start_index..=end_index].iter())
332 .map(|((cp, size), mt)| {
333 let mut position = *cp;
334 let mut size = *size;
335
336 if position < lower_bound_rel && (position + size.height) > lower_bound_rel {
337 size.height = position + size.height - lower_bound_rel;
338 position = lower_bound_rel;
339 } else if position <= upper_bound_rel && (position + size.height) > upper_bound_rel
340 {
341 size.height = upper_bound_rel - position;
342 }
343
344 let limits = Limits::new(size, size);
345
346 mt.item
347 .element
348 .with_data_mut(|e| {
349 e.as_widget_mut()
350 .layout(&mut tree[mt.index], renderer, &limits)
351 })
352 .move_to(Point::new(0.0, position + self.scroll_offset))
353 })
354 .collect::<Vec<_>>();
355
356 Node::with_children(children_bounds.size(), child_nodes).move_to(children_bounds.position())
357 }
358
359 fn layout_single<Message>(
360 &self,
361 overlay_offset: Vector,
362 index: usize,
363 renderer: &crate::Renderer,
364 menu_tree: &mut MenuTree<Message>,
365 tree: &mut Tree,
366 ) -> Node {
367 let children_bounds = self.menu_bounds.children_bounds + overlay_offset;
369
370 let position = self.menu_bounds.child_positions[index];
371 let limits = Limits::new(Size::ZERO, self.menu_bounds.child_sizes[index]);
372 let parent_offset = children_bounds.position() - Point::ORIGIN;
373 let node = menu_tree.item.layout(tree, renderer, &limits);
374 node.move_to(Point::new(
375 parent_offset.x,
376 parent_offset.y + position + self.scroll_offset,
377 ))
378 }
379
380 pub(super) fn slice(
382 &self,
383 viewport_size: Size,
384 overlay_offset: Vector,
385 item_height: ItemHeight,
386 ) -> MenuSlice {
387 let children_bounds = self.menu_bounds.children_bounds + overlay_offset;
389
390 let max_index = self.menu_bounds.child_positions.len().saturating_sub(1);
391
392 let lower_bound = children_bounds.y.max(0.0);
394 let upper_bound = (children_bounds.y + children_bounds.height).min(viewport_size.height);
395
396 let lower_bound_rel = lower_bound - (children_bounds.y + self.scroll_offset);
398 let upper_bound_rel = upper_bound - (children_bounds.y + self.scroll_offset);
399
400 let (start_index, end_index) = match item_height {
402 ItemHeight::Uniform(u) => {
403 let start_index = (lower_bound_rel / f32::from(u)).floor() as usize;
404 let end_index = ((upper_bound_rel / f32::from(u)).floor() as usize).min(max_index);
405 (start_index, end_index)
406 }
407 ItemHeight::Static(_) | ItemHeight::Dynamic(_) => {
408 let positions = &self.menu_bounds.child_positions;
409 let sizes = &self.menu_bounds.child_sizes;
410
411 let start_index = search_bound(0, 0, max_index, lower_bound_rel, positions, sizes);
412 let end_index = search_bound(
413 max_index,
414 start_index,
415 max_index,
416 upper_bound_rel,
417 positions,
418 sizes,
419 )
420 .min(max_index);
421
422 (start_index, end_index)
423 }
424 };
425
426 MenuSlice {
427 start_index,
428 end_index,
429 lower_bound_rel,
430 upper_bound_rel,
431 }
432 }
433}
434
435#[derive(Clone)]
436pub(crate) struct Menu<'b, Message: std::clone::Clone> {
437 pub(crate) tree: MenuBarState,
438 pub(crate) menu_roots: Cow<'b, [MenuTree<Message>]>,
440 pub(crate) bounds_expand: u16,
441 pub(crate) menu_overlays_parent: bool,
443 pub(crate) close_condition: CloseCondition,
444 pub(crate) item_width: ItemWidth,
445 pub(crate) item_height: ItemHeight,
446 pub(crate) bar_bounds: Rectangle,
447 pub(crate) main_offset: i32,
448 pub(crate) cross_offset: i32,
449 pub(crate) root_bounds_list: Vec<Rectangle>,
450 pub(crate) path_highlight: Option<PathHighlight>,
451 pub(crate) style: Cow<'b, <crate::Theme as StyleSheet>::Style>,
452 pub(crate) position: Point,
453 pub(crate) is_overlay: bool,
454 pub(crate) window_id: window::Id,
456 pub(crate) depth: usize,
457 pub(crate) on_surface_action:
458 Option<Arc<dyn Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static>>,
459}
460impl<'b, Message: Clone + 'static> Menu<'b, Message> {
461 pub(crate) fn overlay(self) -> overlay::Element<'b, Message, crate::Theme, crate::Renderer> {
462 overlay::Element::new(Box::new(self))
463 }
464
465 pub(crate) fn layout(&self, renderer: &crate::Renderer, limits: Limits) -> Node {
466 let position = self.position;
468 let mut intrinsic_size = Size::ZERO;
469
470 let empty = Vec::new();
471 self.tree.inner.with_data_mut(|data| {
472 if data.active_root.len() < self.depth + 1 || data.menu_states.len() < self.depth + 1 {
473 return Node::new(limits.min());
474 }
475
476 let overlay_offset = Point::ORIGIN - position;
477 let tree_children: &mut Vec<Tree> = &mut data.tree.children;
478
479 let children = (if self.is_overlay { 0 } else { self.depth }..=if self.is_overlay {
480 data.active_root.len() - 1
481 } else {
482 self.depth
483 })
484 .map(|active_root| {
485 if self.menu_roots.is_empty() {
486 return (&empty, vec![]);
487 }
488 let (active_tree, roots) =
489 data.active_root[..=active_root].iter().skip(1).fold(
490 (
491 &mut tree_children[data.active_root[0]].children,
492 &self.menu_roots[data.active_root[0]].children,
493 ),
494 |(tree, mt), next_active_root| (tree, &mt[*next_active_root].children),
495 );
496
497 data.menu_states[if self.is_overlay { 0 } else { self.depth }
498 ..=if self.is_overlay {
499 data.active_root.len() - 1
500 } else {
501 self.depth
502 }]
503 .iter_mut()
504 .enumerate()
505 .filter(|ms| self.is_overlay || ms.0 < 1)
506 .fold(
507 (roots, Vec::new()),
508 |(menu_root, mut nodes), (_i, ms)| {
509 let slice =
510 ms.slice(limits.max(), overlay_offset, self.item_height);
511 let _start_index = slice.start_index;
512 let _end_index = slice.end_index;
513 let children_node = ms.layout(
514 overlay_offset,
515 slice,
516 renderer,
517 menu_root,
518 active_tree,
519 );
520 let node_size = children_node.size();
521 intrinsic_size.height += node_size.height;
522
523 intrinsic_size.width = intrinsic_size.width.max(node_size.width);
524
525 nodes.push(children_node);
526 (
529 ms.index
530 .map_or(menu_root, |active| &menu_root[active].children),
531 nodes,
532 )
533 },
534 )
535 })
536 .map(|(_, l)| l)
537 .next()
538 .unwrap_or_default();
539
540 Node::with_children(
542 limits.resolve(Length::Shrink, Length::Shrink, intrinsic_size),
543 children,
544 )
545 .translate(Point::ORIGIN - position)
546 })
547 }
548
549 #[allow(clippy::too_many_lines)]
552 fn close_all(
553 &self,
554 state: &mut super::menu_bar::MenuBarStateInner,
555 shell: &mut Shell<'_, Message>,
556 ) {
557 #[cfg(wayland_platform)]
558 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
559 && let Some(handler) = self.on_surface_action.as_ref()
560 {
561 let mut root = self.window_id;
562 let mut depth = self.depth;
563 while let Some(parent) = state.popup_id.iter().find(|(_, v)| **v == root) {
564 if depth == 0 {
565 break;
566 }
567 root = *parent.0;
568 depth = depth.saturating_sub(1);
569 }
570 shell.publish((handler)(crate::surface::Action::DestroyPopup(root)));
571 }
572
573 state.reset();
574 }
575
576 fn close(
579 &self,
580 state: &mut super::menu_bar::MenuBarStateInner,
581 shell: &mut Shell<'_, Message>,
582 ) {
583 let handler = self.on_surface_action.as_ref();
584 close_innermost(state, &mut |id| {
585 if let Some(handler) = handler {
586 shell.publish((handler)(crate::surface::Action::DestroyPopup(id)));
587 }
588 });
589 }
590
591 fn update(
592 &mut self,
593 event: &event::Event,
594 layout: Layout<'_>,
595 view_cursor: Cursor,
596 renderer: &crate::Renderer,
597 clipboard: &mut dyn Clipboard,
598 shell: &mut Shell<'_, Message>,
599 ) -> Option<(usize, MenuState)> {
600 use event::Event::{Mouse, Touch};
601 use mouse::Button::Left;
602 use mouse::Event::{ButtonPressed, ButtonReleased, CursorMoved, WheelScrolled};
603 use touch::Event::{FingerLifted, FingerMoved, FingerPressed};
604
605 if !self
606 .tree
607 .inner
608 .with_data(|data| data.open || data.active_root.len() <= self.depth)
609 {
610 return None;
611 }
612
613 let viewport = layout.bounds();
614
615 let viewport_size = viewport.size();
616 let overlay_offset = Point::ORIGIN - viewport.position();
617 let overlay_cursor = view_cursor.position().unwrap_or_default() - overlay_offset;
618 let _menu_roots = match &mut self.menu_roots {
619 Cow::Borrowed(_) => panic!(),
620 Cow::Owned(o) => o.as_mut_slice(),
621 };
622 process_menu_events(
623 self,
624 event,
625 view_cursor,
626 renderer,
627 clipboard,
628 shell,
629 overlay_offset,
630 );
631
632 init_root_menu(
633 self,
634 renderer,
635 shell,
636 overlay_cursor,
637 viewport_size,
638 overlay_offset,
639 self.bar_bounds,
640 self.main_offset as f32,
641 );
642
643 match event {
644 event::Event::Keyboard(iced_widget::core::keyboard::Event::KeyPressed {
645 key:
646 iced_widget::core::keyboard::Key::Named(
647 iced_widget::core::keyboard::key::Named::Escape,
648 ),
649 ..
650 }) if !self.is_overlay => {
651 self.tree
652 .inner
653 .with_data_mut(|state| self.close(state, shell));
654 shell.capture_event();
655 }
656
657 Mouse(WheelScrolled { delta }) => process_scroll_events(
658 self,
659 shell,
660 *delta,
661 overlay_cursor,
662 viewport_size,
663 overlay_offset,
664 ),
665
666 Mouse(ButtonPressed(Left)) | Touch(FingerPressed { .. }) => {
667 self.tree.inner.with_data_mut(|data| {
668 data.pressed = true;
669 data.view_cursor = view_cursor;
670 });
671 }
672
673 Mouse(CursorMoved { position }) | Touch(FingerMoved { position, .. }) => {
674 let view_cursor = Cursor::Available(*position);
675 let overlay_cursor = view_cursor.position().unwrap_or_default() - overlay_offset;
676 if !self.is_overlay && !view_cursor.is_over(viewport) {
677 return None;
678 }
679 let new_root = process_overlay_events(
680 self,
681 renderer,
682 viewport_size,
683 overlay_offset,
684 view_cursor,
685 overlay_cursor,
686 self.cross_offset as f32,
687 shell,
688 );
689
690 if view_cursor.is_over(viewport) {
691 shell.request_redraw();
692 }
693
694 if self.is_overlay && view_cursor.is_over(viewport) {
695 shell.capture_event();
696 }
697
698 return new_root;
699 }
700
701 Mouse(ButtonReleased(_)) | Touch(FingerLifted { .. }) => {
702 self.tree.inner.with_data_mut(|state| {
703 state.pressed = false;
704
705 if state.open
707 && state
708 .view_cursor
709 .position()
710 .unwrap_or_default()
711 .distance(view_cursor.position().unwrap_or_default())
712 < 2.0
713 {
714 let is_inside = state.menu_states[..=if self.is_overlay {
715 state.active_root.len().saturating_sub(1)
716 } else {
717 self.depth
718 }]
719 .iter()
720 .any(|ms| ms.menu_bounds.check_bounds.contains(overlay_cursor));
721 let mut needs_reset = false;
722 needs_reset |= self.close_condition.click_inside
723 && is_inside
724 && matches!(
725 event,
726 Mouse(ButtonReleased(Left)) | Touch(FingerLifted { .. })
727 );
728
729 needs_reset |= self.close_condition.click_outside && !is_inside;
730
731 if needs_reset {
732 self.close_all(state, shell);
733 }
734 }
735
736 if self.bar_bounds.contains(overlay_cursor) {
738 state.reset();
739 }
740 });
741 }
742
743 _ => {}
744 }
745 None
746 }
747
748 #[allow(unused_results, clippy::too_many_lines)]
749 fn draw(
750 &self,
751 renderer: &mut crate::Renderer,
752 theme: &crate::Theme,
753 style: &renderer::Style,
754 layout: Layout<'_>,
755 view_cursor: Cursor,
756 ) {
757 self.tree.inner.with_data(|state| {
758 if !state.open || state.active_root.len() <= self.depth {
759 return;
760 }
761 let active_root = &state.active_root[..=if self.is_overlay { 0 } else { self.depth }];
762 let viewport = layout.bounds();
763 let viewport_size = viewport.size();
764 let overlay_offset = Point::ORIGIN - viewport.position();
765
766 let render_bounds = if self.is_overlay {
767 Rectangle::new(Point::ORIGIN, viewport.size())
768 } else {
769 Rectangle::new(Point::ORIGIN, Size::INFINITE)
770 };
771
772 let styling = theme.appearance(&self.style, self.is_overlay);
773 let roots = active_root.iter().skip(1).fold(
774 &self.menu_roots[active_root[0]].children,
775 |mt, next_active_root| &mt[*next_active_root].children,
776 );
777 let indices = state.get_trimmed_indices(self.depth).collect::<Vec<_>>();
778 state.menu_states[if self.is_overlay { 0 } else { self.depth }..=if self.is_overlay {
779 state.menu_states.len() - 1
780 } else {
781 self.depth
782 }]
783 .iter()
784 .zip(layout.children())
785 .enumerate()
786 .filter(|ms: &(usize, (&MenuState, Layout<'_>))| self.is_overlay || ms.0 < 1)
787 .fold(
788 roots,
789 |menu_roots: &Vec<MenuTree<Message>>, (i, (ms, children_layout))| {
790 let draw_path = self.path_highlight.as_ref().is_some_and(|ph| match ph {
791 PathHighlight::Full => true,
792 PathHighlight::OmitActive => {
793 !indices.is_empty() && i < indices.len() - 1
794 }
795 PathHighlight::MenuActive => {
796 !indices.is_empty()
797 && i < indices.len()
798 && menu_roots.len() > indices[i]
799 && (i < indices.len() - 1
800 || !menu_roots[indices[i]].children.is_empty())
801 }
802 });
803
804 let view_cursor = if self.depth == state.active_root.len() - 1
806 || i == state.menu_states.len() - 1
807 {
808 view_cursor
809 } else {
810 Cursor::Available([-1.0; 2].into())
811 };
812
813 let draw_menu = |r: &mut crate::Renderer| {
814 let slice = ms.slice(viewport_size, overlay_offset, self.item_height);
816 let start_index = slice.start_index;
817 let end_index = slice.end_index;
818
819 let children_bounds = children_layout.bounds();
820
821 let menu_quad = renderer::Quad {
827 bounds: pad_rectangle(
828 children_bounds.intersection(&viewport).unwrap_or_default(),
829 styling.background_expand.into(),
830 ),
831 border: Border {
832 radius: styling.menu_border_radius.into(),
833 width: styling.border_width,
834 color: styling.border_color,
835 },
836 shadow: Shadow::default(),
837 snap: true,
838 };
839 let menu_color = styling.background;
840 r.fill_quad(menu_quad, menu_color);
841 if let (true, Some(active)) = (draw_path, ms.index)
843 && let Some(active_layout) = children_layout
844 .children()
845 .nth(active.saturating_sub(start_index))
846 {
847 let i = active.saturating_sub(start_index);
848 let mut rad = styling.menu_border_radius;
849 let rad_0 = theme.cosmic().radius_0();
850 if start_index != end_index {
851 if 0 == i {
852 rad[2] = rad_0[0];
853 rad[3] = rad_0[1];
854 } else if i == end_index - start_index {
855 rad[0] = rad_0[2];
856 rad[1] = rad_0[3];
857 } else {
858 rad = rad_0;
859 }
860 }
861 let path_quad = renderer::Quad {
862 bounds: active_layout
863 .bounds()
864 .intersection(&viewport)
865 .unwrap_or_default(),
866 border: Border {
867 radius: rad.into(),
868 ..Default::default()
869 },
870 shadow: Shadow::default(),
871 snap: true,
872 };
873
874 r.fill_quad(path_quad, styling.path);
875 }
876 if start_index < menu_roots.len() {
877 menu_roots[start_index..=end_index]
879 .iter()
880 .enumerate()
881 .zip(children_layout.children())
882 .for_each(|((i, mt), clo)| {
883 let t = theme.with_list_item_position(
884 if start_index == end_index {
885 Some((Alignment::Center, i))
886 } else if 0 == i {
887 Some((Alignment::Start, i))
888 } else if i == end_index - start_index {
889 Some((Alignment::End, i))
890 } else {
891 None
892 },
893 );
894
895 mt.item.draw(
896 &state.tree.children[active_root[0]].children[mt.index],
897 r,
898 &t,
899 style,
900 clo,
901 view_cursor,
902 &children_layout
903 .bounds()
904 .intersection(&viewport)
905 .unwrap_or_default(),
906 );
907 });
908 }
909 };
910
911 renderer.with_layer(render_bounds, draw_menu);
912
913 ms.index
915 .map_or(menu_roots, |active| &menu_roots[active].children)
916 },
917 );
918 });
919 }
920}
921impl<Message: Clone + 'static> overlay::Overlay<Message, crate::Theme, crate::Renderer>
922 for Menu<'_, Message>
923{
924 fn layout(&mut self, renderer: &crate::Renderer, bounds: Size) -> iced_core::layout::Node {
925 Menu::layout(
926 self,
927 renderer,
928 Limits::NONE
929 .min_width(bounds.width)
930 .max_width(bounds.width)
931 .min_height(bounds.height)
932 .max_height(bounds.height),
933 )
934 }
935
936 fn update(
937 &mut self,
938 event: &iced::Event,
939 layout: Layout<'_>,
940 cursor: mouse::Cursor,
941 renderer: &crate::Renderer,
942 clipboard: &mut dyn Clipboard,
943 shell: &mut Shell<'_, Message>,
944 ) {
945 self.update(event, layout, cursor, renderer, clipboard, shell);
946 }
947
948 fn draw(
949 &self,
950 renderer: &mut crate::Renderer,
951 theme: &crate::Theme,
952 style: &renderer::Style,
953 layout: Layout<'_>,
954 cursor: mouse::Cursor,
955 ) {
956 self.draw(renderer, theme, style, layout, cursor);
957 }
958
959 fn mouse_interaction(
960 &self,
961 layout: Layout<'_>,
962 cursor: mouse::Cursor,
963 _renderer: &crate::Renderer,
964 ) -> mouse::Interaction {
965 if cursor.is_over(layout.bounds()) {
966 mouse::Interaction::Idle
967 } else {
968 mouse::Interaction::None
969 }
970 }
971}
972
973impl<Message: std::clone::Clone + 'static> Widget<Message, crate::Theme, crate::Renderer>
974 for Menu<'_, Message>
975{
976 fn size(&self) -> Size<Length> {
977 Size {
978 width: Length::Shrink,
979 height: Length::Shrink,
980 }
981 }
982
983 fn layout(
984 &mut self,
985 _tree: &mut Tree,
986 renderer: &crate::Renderer,
987 limits: &iced_core::layout::Limits,
988 ) -> iced_core::layout::Node {
989 Menu::layout(self, renderer, *limits)
990 }
991
992 fn draw(
993 &self,
994 _tree: &Tree,
995 renderer: &mut crate::Renderer,
996 theme: &crate::Theme,
997 style: &renderer::Style,
998 layout: Layout<'_>,
999 cursor: mouse::Cursor,
1000 _viewport: &Rectangle,
1001 ) {
1002 Menu::draw(self, renderer, theme, style, layout, cursor);
1003 }
1004
1005 #[allow(clippy::too_many_lines)]
1006 fn update(
1007 &mut self,
1008 _tree: &mut Tree,
1009 event: &iced::Event,
1010 layout: Layout<'_>,
1011 cursor: mouse::Cursor,
1012 renderer: &crate::Renderer,
1013 clipboard: &mut dyn Clipboard,
1014 shell: &mut Shell<'_, Message>,
1015 viewport: &Rectangle,
1016 ) {
1017 let new_root = self.update(event, layout, cursor, renderer, clipboard, shell);
1018
1019 #[cfg(wayland_platform)]
1020 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland))
1021 && let Some((new_root, _new_ms)) = new_root
1022 {
1023 use iced_runtime::platform_specific::wayland::CornerRadius;
1024 use iced_runtime::platform_specific::wayland::popup::{
1025 SctkPopupSettings, SctkPositioner,
1026 };
1027
1028 use crate::surface::action::LiveSettings;
1029 use crate::theme::THEME;
1030 let overlay_offset = Point::ORIGIN - viewport.position();
1031
1032 let _overlay_cursor = cursor.position().unwrap_or_default() - overlay_offset;
1033
1034 let Some((mut menu, popup_id)) = self.tree.inner.with_data_mut(|state| {
1035 let popup_id = *state
1036 .popup_id
1037 .entry(self.window_id)
1038 .or_insert_with(window::Id::unique);
1039 let _active_roots = state
1040 .active_root
1041 .get(self.depth)
1042 .cloned()
1043 .unwrap_or_default();
1044
1045 let root_bounds_list = layout
1046 .children()
1047 .next()
1048 .unwrap()
1049 .children()
1050 .map(|lo| lo.bounds())
1051 .collect();
1052
1053 let popup_menu = Menu {
1054 tree: self.tree.clone(),
1055 menu_roots: Cow::Owned(Cow::into_owned(self.menu_roots.clone())),
1056 bounds_expand: self.bounds_expand,
1057 menu_overlays_parent: false,
1058 close_condition: self.close_condition,
1059 item_width: self.item_width,
1060 item_height: self.item_height,
1061 bar_bounds: layout.bounds(),
1062 main_offset: self.main_offset,
1063 cross_offset: self.cross_offset,
1064 root_bounds_list,
1065 path_highlight: self.path_highlight,
1066 style: Cow::Owned(Cow::into_owned(self.style.clone())),
1067 position: Point::new(0., 0.),
1068 is_overlay: false,
1069 window_id: popup_id,
1070 depth: self.depth + 1,
1071 on_surface_action: self.on_surface_action.clone(),
1072 };
1073
1074 state.active_root.push(new_root);
1075
1076 Some((popup_menu, popup_id))
1077 }) else {
1078 return;
1079 };
1080 init_root_popup_menu(
1082 &mut menu,
1083 renderer,
1084 shell,
1085 cursor.position().unwrap_or_default(),
1086 layout.bounds().size(),
1087 Vector::new(0., 0.),
1088 layout.bounds(),
1089 self.main_offset as f32,
1090 );
1091 let (anchor_rect, gravity) = self.tree.inner.with_data_mut(|state| {
1092 (state
1093 .menu_states
1094 .get(self.depth + 1)
1095 .map(|s| s.menu_bounds.parent_bounds)
1096 .map_or_else(
1097 || {
1098 let bounds = layout.bounds();
1099 Rectangle {
1100 x: bounds.x as i32,
1101 y: bounds.y as i32,
1102 width: bounds.width as i32,
1103 height: bounds.height as i32,
1104 }
1105 },
1106 |r| Rectangle {
1107 x: r.x as i32,
1108 y: r.y as i32,
1109 width: r.width as i32,
1110 height: r.height as i32,
1111 },
1112 ), match (state.horizontal_direction, state.vertical_direction) {
1113 (Direction::Positive, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
1114 (Direction::Positive, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopRight,
1115 (Direction::Negative, Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomLeft,
1116 (Direction::Negative, Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopLeft,
1117 })
1118 });
1119
1120 let menu_node = Widget::layout(
1121 &mut menu,
1122 &mut Tree::empty(),
1123 renderer,
1124 &Limits::NONE.min_width(1.).min_height(1.),
1125 );
1126
1127 let popup_size = menu_node.size();
1128 let mut positioner = SctkPositioner {
1129 size: Some((
1130 popup_size.width.ceil() as u32 + 2,
1131 popup_size.height.ceil() as u32 + 2,
1132 )),
1133 anchor_rect,
1134 anchor:
1135 cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Anchor::TopRight,
1136 gravity,
1137 reactive: true,
1138 ..Default::default()
1139 };
1140 positioner.constraint_adjustment &= !(1 << 0);
1142 let parent = self.window_id;
1143
1144 let t = THEME.lock().unwrap();
1145 let styling = t.appearance(&crate::theme::menu_bar::MenuBarStyle::Default, false);
1146 drop(t);
1147 let rad = styling.menu_border_radius;
1148
1149 shell.publish((self.on_surface_action.as_ref().unwrap())(
1150 crate::surface::action::simple_popup(
1151 move || LiveSettings {
1152 corners: Some(CornerRadius {
1153 top_left: rad[0] as u32,
1154 top_right: rad[1] as u32,
1155 bottom_left: rad[2] as u32,
1156 bottom_right: rad[3] as u32,
1157 }),
1158 ..Default::default()
1159 },
1160 move || SctkPopupSettings {
1161 parent,
1162 id: popup_id,
1163 positioner: positioner.clone(),
1164 parent_size: None,
1165 grab: true,
1166 close_with_children: false,
1167 input_zone: None,
1168 },
1169 Some(move || {
1170 crate::Element::from(
1171 crate::widget::container(menu.clone()).center(Length::Fill),
1172 )
1173 .map(crate::action::app)
1174 }),
1175 ),
1176 ));
1177 }
1178 }
1179
1180 fn mouse_interaction(
1181 &self,
1182 _tree: &Tree,
1183 layout: Layout<'_>,
1184 cursor: mouse::Cursor,
1185 _viewport: &Rectangle,
1186 _renderer: &crate::Renderer,
1187 ) -> mouse::Interaction {
1188 if cursor.is_over(layout.bounds()) {
1189 mouse::Interaction::Idle
1190 } else {
1191 mouse::Interaction::None
1192 }
1193 }
1194}
1195
1196impl<'a, Message> From<Menu<'a, Message>>
1197 for iced::Element<'a, Message, crate::Theme, crate::Renderer>
1198where
1199 Message: std::clone::Clone + 'static,
1200{
1201 fn from(value: Menu<'a, Message>) -> Self {
1202 Self::new(value)
1203 }
1204}
1205
1206fn pad_rectangle(rect: Rectangle, padding: Padding) -> Rectangle {
1207 Rectangle {
1208 x: rect.x - padding.left,
1209 y: rect.y - padding.top,
1210 width: rect.width + padding.x(),
1211 height: rect.height + padding.y(),
1212 }
1213}
1214
1215#[allow(clippy::too_many_arguments)]
1216pub(crate) fn init_root_menu<Message: Clone>(
1217 menu: &mut Menu<'_, Message>,
1218 renderer: &crate::Renderer,
1219 shell: &mut Shell<'_, Message>,
1220 overlay_cursor: Point,
1221 viewport_size: Size,
1222 overlay_offset: Vector,
1223 bar_bounds: Rectangle,
1224 main_offset: f32,
1225) {
1226 menu.tree.inner.with_data_mut(|state| {
1227 if !(state.menu_states.get(menu.depth).is_none()
1228 && (!menu.is_overlay || bar_bounds.contains(overlay_cursor)))
1229 || menu.depth > 0
1230 || !state.open
1231 {
1232 return;
1233 }
1234
1235 for (i, (&root_bounds, mt)) in menu
1236 .root_bounds_list
1237 .iter()
1238 .zip(menu.menu_roots.iter())
1239 .enumerate()
1240 {
1241 if mt.children.is_empty() {
1242 continue;
1243 }
1244
1245 if root_bounds.contains(overlay_cursor) {
1246 let view_center = viewport_size.width * 0.5;
1247 let rb_center = root_bounds.center_x();
1248
1249 state.horizontal_direction = if menu.is_overlay && rb_center > view_center {
1250 Direction::Negative
1251 } else {
1252 Direction::Positive
1253 };
1254
1255 let aod = Aod {
1256 horizontal: true,
1257 vertical: true,
1258 horizontal_overlap: true,
1259 vertical_overlap: false,
1260 horizontal_direction: state.horizontal_direction,
1261 vertical_direction: state.vertical_direction,
1262 horizontal_offset: 0.0,
1263 vertical_offset: main_offset,
1264 };
1265 let menu_bounds = MenuBounds::new(
1266 mt,
1267 renderer,
1268 menu.item_width,
1269 menu.item_height,
1270 viewport_size,
1271 overlay_offset,
1272 &aod,
1273 menu.bounds_expand,
1274 root_bounds,
1275 &mut state.tree.children[0].children,
1276 menu.is_overlay,
1277 );
1278 state.active_root.push(i);
1279 let ms = MenuState {
1280 index: None,
1281 scroll_offset: 0.0,
1282 menu_bounds,
1283 };
1284 state.menu_states.push(ms);
1285 shell.invalidate_layout();
1287
1288 break;
1289 }
1290 }
1291 });
1292}
1293
1294#[cfg(wayland_platform)]
1295pub(super) fn init_root_popup_menu<Message>(
1296 menu: &mut Menu<'_, Message>,
1297 renderer: &crate::Renderer,
1298 shell: &mut Shell<'_, Message>,
1299 overlay_cursor: Point,
1300 viewport_size: Size,
1301 overlay_offset: Vector,
1302 bar_bounds: Rectangle,
1303 main_offset: f32,
1304) where
1305 Message: std::clone::Clone,
1306{
1307 menu.tree.inner.with_data_mut(|state| {
1308 if !(state.menu_states.get(menu.depth).is_none()
1309 && (!menu.is_overlay || bar_bounds.contains(overlay_cursor)))
1310 {
1311 return;
1312 }
1313
1314 let active_roots = &state.active_root[..=menu.depth];
1315
1316 let mt = active_roots
1317 .iter()
1318 .skip(1)
1319 .fold(&menu.menu_roots[active_roots[0]], |mt, next_active_root| {
1320 &mt.children[*next_active_root]
1321 });
1322 let i = active_roots.last().unwrap();
1323 let root_bounds = menu.root_bounds_list[*i];
1324
1325 assert!(!mt.children.is_empty(), "skipping menu with no children");
1326 let aod = Aod {
1327 horizontal: true,
1328 vertical: true,
1329 horizontal_overlap: true,
1330 vertical_overlap: false,
1331 horizontal_direction: state.horizontal_direction,
1332 vertical_direction: state.vertical_direction,
1333 horizontal_offset: 0.0,
1334 vertical_offset: main_offset,
1335 };
1336 let menu_bounds = MenuBounds::new(
1337 mt,
1338 renderer,
1339 menu.item_width,
1340 menu.item_height,
1341 viewport_size,
1342 overlay_offset,
1343 &aod,
1344 menu.bounds_expand,
1345 root_bounds,
1346 &mut state.tree.children[0].children,
1348 menu.is_overlay,
1349 );
1350
1351 let view_center = viewport_size.width * 0.5;
1352 let rb_center = root_bounds.center_x();
1353
1354 state.horizontal_direction = if rb_center > view_center {
1355 Direction::Negative
1356 } else {
1357 Direction::Positive
1358 };
1359
1360 let ms = MenuState {
1361 index: None,
1362 scroll_offset: 0.0,
1363 menu_bounds,
1364 };
1365 state.menu_states.push(ms);
1366
1367 shell.invalidate_layout();
1369 });
1370}
1371
1372#[allow(clippy::too_many_arguments)]
1373fn process_menu_events<Message: std::clone::Clone>(
1374 menu: &mut Menu<Message>,
1375 event: &event::Event,
1376 view_cursor: Cursor,
1377 renderer: &crate::Renderer,
1378 clipboard: &mut dyn Clipboard,
1379 shell: &mut Shell<'_, Message>,
1380 overlay_offset: Vector,
1381) {
1382 let my_state = &mut menu.tree;
1383 let menu_roots = match &mut menu.menu_roots {
1384 Cow::Borrowed(_) => panic!(),
1385 Cow::Owned(o) => o.as_mut_slice(),
1386 };
1387 my_state.inner.with_data_mut(|state| {
1388 if state.active_root.len() <= menu.depth {
1389 return;
1390 }
1391
1392 let Some(hover) = state.menu_states.last_mut() else {
1393 return;
1394 };
1395
1396 let Some(hover_index) = hover.index else {
1397 return;
1398 };
1399
1400 let mt = state.active_root.iter().skip(1).fold(
1401 &mut menu_roots[state.active_root[0]],
1403 |mt, next_active_root| &mut mt.children[*next_active_root],
1404 );
1405
1406 let mt = &mut mt.children[hover_index];
1407 let tree = &mut state.tree.children[state.active_root[0]].children[mt.index];
1408
1409 let child_node = hover.layout_single(
1411 overlay_offset,
1412 hover.index.expect("missing index within menu state."),
1413 renderer,
1414 mt,
1415 tree,
1416 );
1417 let child_layout = Layout::new(&child_node);
1418
1419 mt.item.update(
1421 tree,
1422 event,
1423 child_layout,
1424 view_cursor,
1425 renderer,
1426 clipboard,
1427 shell,
1428 &Rectangle::default(),
1429 );
1430 });
1431}
1432
1433#[allow(unused_results, clippy::too_many_lines, clippy::too_many_arguments)]
1434fn process_overlay_events<Message>(
1435 menu: &mut Menu<Message>,
1436 renderer: &crate::Renderer,
1437 viewport_size: Size,
1438 overlay_offset: Vector,
1439 view_cursor: Cursor,
1440 overlay_cursor: Point,
1441 cross_offset: f32,
1442 shell: &mut Shell<'_, Message>,
1443) -> Option<(usize, MenuState)>
1444where
1445 Message: std::clone::Clone,
1446{
1447 let mut new_menu_root = None;
1457
1458 menu.tree.inner.with_data_mut(|state| {
1459
1460 state.view_cursor = view_cursor;
1463
1464 if state.open {
1466 let mut prev_bounds = std::iter::once(menu.bar_bounds)
1467 .chain(
1468 if menu.is_overlay {
1469 state.menu_states[..state.menu_states.len().saturating_sub(1)].iter()
1470 } else {
1471 state.menu_states[..menu.depth].iter()
1472 }
1473 .map(|s| s.menu_bounds.children_bounds),
1474 )
1475 .collect::<Vec<_>>();
1476
1477 if menu.is_overlay && menu.close_condition.leave {
1478 for i in (0..state.menu_states.len()).rev() {
1479 let mb = &state.menu_states[i].menu_bounds;
1480
1481 if mb.parent_bounds.contains(overlay_cursor)
1482 || menu.is_overlay && mb.children_bounds.contains(overlay_cursor)
1483 || mb.offset_bounds.contains(overlay_cursor)
1484 || (mb.check_bounds.contains(overlay_cursor)
1485 && prev_bounds.iter().all(|pvb| !pvb.contains(overlay_cursor)))
1486 {
1487 break;
1488 }
1489 prev_bounds.pop();
1490 state.active_root.pop();
1491 state.menu_states.pop();
1492 }
1493 } else if menu.is_overlay {
1494 for i in (0..state.menu_states.len()).rev() {
1495 let mb = &state.menu_states[i].menu_bounds;
1496
1497 if mb.parent_bounds.contains(overlay_cursor)
1498 || mb.children_bounds.contains(overlay_cursor)
1499 || prev_bounds.iter().all(|pvb| !pvb.contains(overlay_cursor))
1500 {
1501 break;
1502 }
1503 prev_bounds.pop();
1504 state.active_root.pop();
1505 state.menu_states.pop();
1506 }
1507 }
1508 }
1509
1510 let menu_states_len = state.menu_states.len();
1512
1513 let Some(last_menu_state) = state.menu_states.get_mut(if menu.is_overlay {
1514 menu_states_len.saturating_sub(1)
1515 } else {
1516 menu.depth
1517 }) else {
1518 if menu.is_overlay {
1519 if !menu.bar_bounds.contains(overlay_cursor) {
1527 state.open = false;
1528 }
1529 }
1530 shell.capture_event();
1531 return new_menu_root;
1532 };
1533
1534 let last_menu_bounds = &last_menu_state.menu_bounds;
1535 let last_parent_bounds = last_menu_bounds.parent_bounds;
1536 let last_children_bounds = last_menu_bounds.children_bounds;
1537
1538 if (menu.is_overlay && !menu.menu_overlays_parent && last_parent_bounds.contains(overlay_cursor))
1539 || menu.is_overlay && !last_children_bounds.contains(overlay_cursor)
1541 {
1543
1544 if last_menu_state.index.take().is_some() {
1545 shell.request_redraw();
1546 }
1547 shell.capture_event();
1548 return new_menu_root;
1549 }
1550
1551 let height_diff = (overlay_cursor.y
1553 - (last_children_bounds.y + last_menu_state.scroll_offset))
1554 .clamp(0.0, last_children_bounds.height - 0.001);
1555
1556 let active_root = if menu.is_overlay {
1557 &state.active_root
1558 } else {
1559 &state.active_root[..=menu.depth]
1560 };
1561
1562 if state.pressed {
1563 return new_menu_root;
1564 }
1565 let roots = active_root.iter().skip(1).fold(
1566 &menu.menu_roots[active_root[0]].children,
1567 |mt, next_active_root| &mt[*next_active_root].children,
1568 );
1569 let tree = &mut state.tree.children[active_root[0]].children;
1570
1571 let active_menu: &Vec<MenuTree<Message>> = roots;
1572 let new_index = match menu.item_height {
1573 ItemHeight::Uniform(u) => (height_diff / f32::from(u)).floor() as usize,
1574 ItemHeight::Static(_) | ItemHeight::Dynamic(_) => {
1575 let max_index = active_menu.len() - 1;
1576 search_bound(
1577 0,
1578 0,
1579 max_index,
1580 height_diff,
1581 &last_menu_bounds.child_positions,
1582 &last_menu_bounds.child_sizes,
1583 )
1584 }
1585 };
1586
1587 let remove = last_menu_state
1588 .index
1589 .as_ref()
1590 .is_some_and(|i| *i != new_index && !active_menu[*i].children.is_empty());
1591
1592 #[cfg(wayland_platform)]
1593 if matches!(WINDOWING_SYSTEM.get(), Some(WindowingSystem::Wayland)) && remove
1594 && let Some(id) = state.popup_id.remove(&menu.window_id) {
1595 state.active_root.truncate(menu.depth + 1);
1596 shell.publish((menu.on_surface_action.as_ref().unwrap())({
1597 crate::surface::action::destroy_popup(id)
1598 }));
1599 }
1600 let item = &active_menu[new_index];
1601 let old_index = last_menu_state.index.replace(new_index);
1603
1604 if old_index != Some(new_index) {
1605 shell.request_redraw();
1606 }
1607
1608 if !item.children.is_empty() && old_index.is_none_or(|i| i != new_index) {
1611 let item_position = Point::new(
1612 0.0,
1613 last_menu_bounds.child_positions[new_index] + last_menu_state.scroll_offset,
1614 );
1615 let item_size = last_menu_bounds.child_sizes[new_index];
1616
1617 let item_bounds = Rectangle::new(item_position, item_size)
1619 + (last_menu_bounds.children_bounds.position() - Point::ORIGIN);
1620
1621 let aod = Aod {
1622 horizontal: true,
1623 vertical: true,
1624 horizontal_overlap: false,
1625 vertical_overlap: true,
1626 horizontal_direction: state.horizontal_direction,
1627 vertical_direction: state.vertical_direction,
1628 horizontal_offset: cross_offset,
1629 vertical_offset: 0.0,
1630 };
1631 let ms = MenuState {
1632 index: None,
1633 scroll_offset: 0.0,
1634 menu_bounds: MenuBounds::new(
1635 item,
1636 renderer,
1637 menu.item_width,
1638 menu.item_height,
1639 viewport_size,
1640 overlay_offset,
1641 &aod,
1642 menu.bounds_expand,
1643 item_bounds,
1644 tree,
1645 menu.is_overlay,
1646 ),
1647 };
1648
1649 new_menu_root = Some((new_index, ms.clone()));
1650 if menu.is_overlay {
1651 state.active_root.push(new_index);
1652 } else {
1653 state.menu_states.truncate(menu.depth + 1);
1654 }
1655 state.menu_states.push(ms);
1656 } else if !menu.is_overlay && remove {
1657 state.menu_states.truncate(menu.depth + 1);
1658 }
1659
1660 shell.capture_event();
1661 new_menu_root
1662 })
1663}
1664
1665fn process_scroll_events<Message>(
1666 menu: &mut Menu<'_, Message>,
1667 shell: &mut Shell<'_, Message>,
1668 delta: mouse::ScrollDelta,
1669 overlay_cursor: Point,
1670 viewport_size: Size,
1671 overlay_offset: Vector,
1672) where
1673 Message: Clone,
1674{
1675 use mouse::ScrollDelta;
1676
1677 menu.tree.inner.with_data_mut(|state| {
1678 let delta_y = match delta {
1679 ScrollDelta::Lines { y, .. } => y * 60.0,
1680 ScrollDelta::Pixels { y, .. } => y,
1681 };
1682
1683 let calc_offset_bounds = |menu_state: &MenuState, viewport_size: Size| -> (f32, f32) {
1684 let children_bounds = menu_state.menu_bounds.children_bounds + overlay_offset;
1686
1687 let max_offset = (0.0 - children_bounds.y).max(0.0);
1688 let min_offset =
1689 (viewport_size.height - (children_bounds.y + children_bounds.height)).min(0.0);
1690 (max_offset, min_offset)
1691 };
1692
1693 if state.menu_states.is_empty() {
1695 return;
1696 } else if state.menu_states.len() == 1 {
1697 let last_ms = &mut state.menu_states[0];
1698
1699 if last_ms.index.is_none() {
1700 return;
1701 }
1702
1703 let (max_offset, min_offset) = calc_offset_bounds(last_ms, viewport_size);
1704 last_ms.scroll_offset = (last_ms.scroll_offset + delta_y).clamp(min_offset, max_offset);
1705 } else {
1706 let max_index = state.menu_states.len() - 1;
1708 let last_two = &mut state.menu_states[max_index - 1..=max_index];
1709
1710 if last_two[1].index.is_some() {
1711 let (max_offset, min_offset) = calc_offset_bounds(&last_two[1], viewport_size);
1713 last_two[1].scroll_offset =
1714 (last_two[1].scroll_offset + delta_y).clamp(min_offset, max_offset);
1715 } else {
1716 if !last_two[0]
1717 .menu_bounds
1718 .children_bounds
1719 .contains(overlay_cursor)
1720 {
1721 shell.capture_event();
1722 return;
1723 }
1724
1725 let (max_offset, min_offset) = calc_offset_bounds(&last_two[0], viewport_size);
1727 let scroll_offset =
1728 (last_two[0].scroll_offset + delta_y).clamp(min_offset, max_offset);
1729 let clamped_delta_y = scroll_offset - last_two[0].scroll_offset;
1730 last_two[0].scroll_offset = scroll_offset;
1731
1732 last_two[1].menu_bounds.parent_bounds.y += clamped_delta_y;
1734 last_two[1].menu_bounds.children_bounds.y += clamped_delta_y;
1735 last_two[1].menu_bounds.check_bounds.y += clamped_delta_y;
1736 }
1737 }
1738 shell.capture_event();
1739 shell.request_redraw();
1740 });
1741}
1742
1743#[allow(clippy::pedantic)]
1744fn get_children_layout<Message>(
1746 menu_tree: &MenuTree<Message>,
1747 renderer: &crate::Renderer,
1748 item_width: ItemWidth,
1749 item_height: ItemHeight,
1750 tree: &mut [Tree],
1751) -> (Size, Vec<f32>, Vec<Size>) {
1752 let width = match item_width {
1753 ItemWidth::Uniform(u) => f32::from(u),
1754 ItemWidth::Static(s) => f32::from(menu_tree.width.unwrap_or(s)),
1755 };
1756
1757 let child_sizes: Vec<Size> = match item_height {
1758 ItemHeight::Uniform(u) => {
1759 let count = menu_tree.children.len();
1760 vec![Size::new(width, f32::from(u)); count]
1761 }
1762 ItemHeight::Static(s) => menu_tree
1763 .children
1764 .iter()
1765 .map(|mt| Size::new(width, f32::from(mt.height.unwrap_or(s))))
1766 .collect(),
1767 ItemHeight::Dynamic(d) => menu_tree
1768 .children
1769 .iter()
1770 .map(|mt| {
1771 mt.item
1772 .element
1773 .with_data_mut(|w| match w.as_widget_mut().size().height {
1774 Length::Fixed(f) => Size::new(width, f),
1775 Length::Shrink => {
1776 let l_height = w
1777 .as_widget_mut()
1778 .layout(
1779 &mut tree[mt.index],
1780 renderer,
1781 &Limits::new(Size::ZERO, Size::new(width, f32::MAX)),
1782 )
1783 .size()
1784 .height;
1785
1786 let height = if (f32::MAX - l_height) < 0.001 {
1787 f32::from(d)
1788 } else {
1789 l_height
1790 };
1791
1792 Size::new(width, height)
1793 }
1794 _ => mt.height.map_or_else(
1795 || Size::new(width, f32::from(d)),
1796 |h| Size::new(width, f32::from(h)),
1797 ),
1798 })
1799 })
1800 .collect(),
1801 };
1802
1803 let max_index = menu_tree.children.len().saturating_sub(1);
1804 let child_positions: Vec<f32> = std::iter::once(0.0)
1805 .chain(child_sizes[0..max_index].iter().scan(0.0, |acc, x| {
1806 *acc += x.height;
1807 Some(*acc)
1808 }))
1809 .collect();
1810
1811 let height = child_sizes.iter().fold(0.0, |acc, x| acc + x.height);
1812
1813 (Size::new(width, height), child_positions, child_sizes)
1814}
1815
1816pub(super) fn close_innermost(
1818 state: &mut super::menu_bar::MenuBarStateInner,
1819 destroy: &mut dyn FnMut(window::Id),
1820) {
1821 let outermost = state
1822 .popup_id
1823 .iter()
1824 .find(|(parent, _)| !state.popup_id.values().any(|id| id == *parent))
1825 .map(|(_, id)| *id);
1826 let innermost = state
1827 .popup_id
1828 .values()
1829 .find(|id| !state.popup_id.contains_key(id))
1830 .copied();
1831
1832 let levels = state.menu_states.len();
1833 if levels <= 1 {
1834 if let Some(id) = outermost {
1835 destroy(id);
1836 }
1837 state.popup_id.clear();
1838 state.reset();
1839 return;
1840 }
1841
1842 state.active_root.truncate(levels - 1);
1843 state.menu_states.truncate(levels - 1);
1844
1845 if let Some(parent) = state.menu_states.last_mut() {
1847 parent.index = None;
1848 }
1849 if let Some(id) = innermost {
1850 state.popup_id.retain(|_, popup| *popup != id);
1851 destroy(id);
1852 }
1853}
1854
1855fn search_bound(
1856 default: usize,
1857 default_left: usize,
1858 default_right: usize,
1859 bound: f32,
1860 positions: &[f32],
1861 sizes: &[Size],
1862) -> usize {
1863 let mut left = default_left;
1865 let mut right = default_right;
1866
1867 let mut index = default;
1868 while left != right {
1869 let m = ((left + right) / 2) + 1;
1870 if positions[m] > bound {
1871 right = m - 1;
1872 } else {
1873 left = m;
1874 }
1875 }
1876 let height = sizes[left].height;
1878 if positions[left] + height > bound {
1879 index = left;
1880 }
1881 index
1882}