1use super::model::{Entity, Model, Selectable};
5use super::{InsertPosition, ReorderEvent};
6use crate::theme::{SegmentedButton as Style, THEME};
7use crate::widget::dnd_destination::DragId;
8use crate::widget::menu::{
9 self, CloseCondition, ItemHeight, ItemWidth, MenuBarState, PathHighlight, menu_roots_children,
10 menu_roots_diff,
11};
12use crate::widget::{Icon, icon};
13use crate::{Element, Renderer};
14use derive_setters::Setters;
15use iced::clipboard::dnd::{
16 self, DndAction, DndDestinationRectangle, DndEvent, OfferEvent, SourceEvent,
17};
18use iced::clipboard::mime::AllowedMimeTypes;
19use iced::touch::Finger;
20use iced::{
21 Alignment, Background, Color, Event, Length, Padding, Rectangle, Size, Task, Vector, alignment,
22 keyboard, mouse, touch, window,
23};
24use iced_core::id::Internal;
25use iced_core::mouse::ScrollDelta;
26use iced_core::text::{self, Ellipsize, LineHeight, Renderer as TextRenderer, Shaping, Wrapping};
27use iced_core::widget::operation::Focusable;
28use iced_core::widget::{self, Tree, operation, tree};
29use iced_core::{
30 Border, Clipboard, Layout, Point, Renderer as IcedRenderer, Shadow, Shell, Text, Widget,
31 layout, renderer,
32};
33use iced_runtime::{Action, task};
34use slotmap::{Key, SecondaryMap};
35use std::borrow::Cow;
36use std::cell::{Cell, LazyCell};
37use std::collections::HashSet;
38use std::collections::hash_map::DefaultHasher;
39use std::hash::{Hash, Hasher};
40use std::marker::PhantomData;
41use std::sync::Arc;
42use std::time::{Duration, Instant};
43
44thread_local! {
45 static LAST_FOCUS_UPDATE: LazyCell<Cell<Instant>> = LazyCell::new(|| Cell::new(Instant::now()));
47}
48
49const TAB_REORDER_LOG_TARGET: &str = "libcosmic::widget::tab_reorder";
50
51pub fn focus<Message: 'static>(id: Id) -> Task<Message> {
53 task::effect(Action::Widget(Box::new(operation::focusable::focus(id.0))))
54}
55
56pub enum ItemBounds {
57 Button(Entity, Rectangle),
58 Divider(Rectangle, bool),
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62enum DropSide {
63 Before,
64 After,
65}
66
67impl From<DropSide> for InsertPosition {
68 fn from(side: DropSide) -> Self {
69 match side {
70 DropSide::Before => InsertPosition::Before,
71 DropSide::After => InsertPosition::After,
72 }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77struct DropHint {
78 entity: Entity,
79 side: DropSide,
80}
81
82pub trait SegmentedVariant {
84 const VERTICAL: bool;
85
86 fn variant_appearance(
88 theme: &crate::Theme,
89 style: &crate::theme::SegmentedButton,
90 ) -> super::Appearance;
91
92 fn variant_bounds<'b>(
94 &'b self,
95 state: &'b LocalState,
96 bounds: Rectangle,
97 ) -> Box<dyn Iterator<Item = ItemBounds> + 'b>;
98
99 fn variant_layout(
101 &self,
102 state: &mut LocalState,
103 renderer: &crate::Renderer,
104 limits: &layout::Limits,
105 ) -> Size;
106}
107
108#[derive(Setters)]
110#[must_use]
111pub struct SegmentedButton<'a, Variant, SelectionMode, Message: Clone + 'static>
112where
113 Model<SelectionMode>: Selectable,
114 SelectionMode: Default,
115{
116 #[setters(skip)]
118 pub(super) model: &'a Model<SelectionMode>,
119 pub(super) id: Id,
121 pub(super) close_icon: Icon,
123 pub(super) scrollable_focus: bool,
125 pub(super) show_close_icon_on_hover: bool,
127 #[setters(into)]
129 pub(super) padding: Padding,
130 pub(super) dividers: bool,
132 pub(super) button_alignment: Alignment,
134 pub(super) button_padding: [u16; 4],
136 pub(super) button_height: u16,
138 pub(super) button_spacing: u16,
140 pub(super) maximum_button_width: u16,
142 pub(super) minimum_button_width: u16,
144 pub(super) indent_spacing: u16,
146 pub(super) font_active: crate::font::Font,
148 pub(super) font_hovered: crate::font::Font,
150 pub(super) font_inactive: crate::font::Font,
152 pub(super) font_size: f32,
154 pub(super) width: Length,
156 pub(super) height: Length,
158 pub(super) spacing: u16,
160 pub(super) line_height: LineHeight,
162 pub(super) ellipsize: Ellipsize,
164 #[setters(into)]
166 pub(super) style: Style,
167 #[setters(skip)]
169 pub(super) context_menu: Option<Vec<menu::Tree<Message>>>,
170 #[setters(skip)]
172 pub(super) on_activate: Option<Box<dyn Fn(Entity) -> Message + 'static>>,
173 #[setters(skip)]
174 pub(super) on_close: Option<Box<dyn Fn(Entity) -> Message + 'static>>,
175 #[setters(skip)]
176 pub(super) on_context: Option<Box<dyn Fn(Entity) -> Message + 'static>>,
177 #[setters(skip)]
178 pub(super) on_middle_press: Option<Box<dyn Fn(Entity) -> Message + 'static>>,
179 #[setters(skip)]
180 pub(super) on_dnd_drop:
181 Option<Box<dyn Fn(Entity, Vec<u8>, String, DndAction) -> Message + 'static>>,
182 pub(super) mimes: Vec<String>,
183 #[setters(skip)]
184 pub(super) on_dnd_enter: Option<Box<dyn Fn(Entity, Vec<String>) -> Message + 'static>>,
185 #[setters(skip)]
186 pub(super) on_dnd_leave: Option<Box<dyn Fn(Entity) -> Message + 'static>>,
187 #[setters(strip_option)]
188 pub(super) drag_id: Option<DragId>,
189 #[setters(skip)]
190 tab_drag: Option<TabDragSource<Message>>,
191 #[setters(skip)]
192 pub(super) on_drop_hint: Option<Box<dyn Fn(Option<(Entity, bool)>) -> Message + 'static>>,
193
194 #[setters(skip)]
195 pub(super) on_reorder: Option<Box<dyn Fn(ReorderEvent) -> Message + 'static>>,
196 #[setters(skip)]
197 window_id: window::Id,
198 #[cfg(wayland_platform)]
199 positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
200 #[setters(skip)]
201 pub(crate) on_surface_action:
202 Option<Arc<dyn Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static>>,
203
204 variant: PhantomData<Variant>,
206}
207
208impl<'a, Variant, SelectionMode, Message: Clone + 'static>
209 SegmentedButton<'a, Variant, SelectionMode, Message>
210where
211 Self: SegmentedVariant,
212 Model<SelectionMode>: Selectable,
213 SelectionMode: Default,
214{
215 #[inline]
216 pub fn new(model: &'a Model<SelectionMode>) -> Self {
217 Self {
218 model,
219 id: Id::unique(),
220 close_icon: icon::from_name("window-close-symbolic").size(16).icon(),
221 scrollable_focus: false,
222 show_close_icon_on_hover: false,
223 button_alignment: Alignment::Start,
224 padding: Padding::from(0.0),
225 dividers: false,
226 button_padding: [0, 0, 0, 0],
227 button_height: 32,
228 button_spacing: 0,
229 minimum_button_width: u16::MIN,
230 maximum_button_width: u16::MAX,
231 indent_spacing: 16,
232 font_active: crate::font::semibold(),
233 font_hovered: crate::font::default(),
234 font_inactive: crate::font::default(),
235 font_size: 14.0,
236 height: Length::Shrink,
237 width: Length::Fill,
238 spacing: 0,
239 line_height: LineHeight::default(),
240 ellipsize: Ellipsize::default(),
241 style: Style::default(),
242 context_menu: None,
243 on_activate: None,
244 on_close: None,
245 on_context: None,
246 on_middle_press: None,
247 on_dnd_drop: None,
248 on_dnd_enter: None,
249 on_dnd_leave: None,
250 mimes: Vec::new(),
251 variant: PhantomData,
252 drag_id: None,
253 tab_drag: None,
254 on_drop_hint: None,
255 on_reorder: None,
256 window_id: window::Id::RESERVED,
257 #[cfg(wayland_platform)]
258 positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner::default(),
259 on_surface_action: None,
260 }
261 }
262
263 fn update_entity_paragraph(&mut self, state: &mut LocalState, key: Entity) {
264 if let Some(text) = self.model.text.get(key) {
265 let font = if self.button_is_focused(state, key)
266 || state.show_context == Some(key)
267 || self.model.is_active(key)
268 {
269 self.font_active
270 } else if self.button_is_hovered(state, key) {
271 self.font_hovered
272 } else {
273 self.font_inactive
274 };
275
276 let mut hasher = DefaultHasher::new();
277 text.hash(&mut hasher);
278 font.hash(&mut hasher);
279 let text_hash = hasher.finish();
280
281 if let Some(prev_hash) = state.text_hashes.insert(key, text_hash)
282 && prev_hash == text_hash
283 {
284 return;
285 }
286
287 if let Some(paragraph) = state.paragraphs.get_mut(key) {
288 let text = Text {
289 content: text.as_ref(),
290 size: iced::Pixels(self.font_size),
291 bounds: Size::INFINITE,
292 font,
293 align_x: text::Alignment::Left,
294 align_y: alignment::Vertical::Center,
295 shaping: Shaping::Advanced,
296 wrapping: Wrapping::None,
297 line_height: self.line_height,
298 ellipsize: self.ellipsize,
299 };
300 paragraph.update(text);
301 } else {
302 let text = Text {
303 content: text.to_string(),
304 size: iced::Pixels(self.font_size),
305 bounds: Size::INFINITE,
306 font,
307 align_x: text::Alignment::Left,
308 align_y: alignment::Vertical::Center,
309 shaping: Shaping::Advanced,
310 wrapping: Wrapping::None,
311 line_height: self.line_height,
312 ellipsize: self.ellipsize,
313 };
314 state.paragraphs.insert(key, crate::Plain::new(text));
315 }
316 }
317 }
318
319 pub fn context_menu(mut self, context_menu: Option<Vec<menu::Tree<Message>>>) -> Self
320 where
321 Message: Clone + 'static,
322 {
323 self.context_menu = context_menu;
324
325 if let Some(ref mut context_menu) = self.context_menu {
326 context_menu.iter_mut().for_each(menu::Tree::set_index);
327 }
328
329 self
330 }
331
332 pub fn on_activate<T>(mut self, on_activate: T) -> Self
334 where
335 T: Fn(Entity) -> Message + 'static,
336 {
337 self.on_activate = Some(Box::new(on_activate));
338 self
339 }
340
341 pub fn on_close<T>(mut self, on_close: T) -> Self
343 where
344 T: Fn(Entity) -> Message + 'static,
345 {
346 self.on_close = Some(Box::new(on_close));
347 self
348 }
349
350 pub fn on_context<T>(mut self, on_context: T) -> Self
352 where
353 T: Fn(Entity) -> Message + 'static,
354 {
355 self.on_context = Some(Box::new(on_context));
356 self
357 }
358
359 pub fn on_middle_press<T>(mut self, on_middle_press: T) -> Self
361 where
362 T: Fn(Entity) -> Message + 'static,
363 {
364 self.on_middle_press = Some(Box::new(on_middle_press));
365 self
366 }
367
368 pub fn enable_tab_drag(mut self, mime: String) -> Self {
370 self.tab_drag = Some(TabDragSource::new(mime));
371 self
372 }
373
374 pub fn on_drop_hint(
376 mut self,
377 callback: impl Fn(Option<(Entity, bool)>) -> Message + 'static,
378 ) -> Self {
379 self.on_drop_hint = Some(Box::new(callback));
380 self
381 }
382
383 pub fn on_reorder(mut self, callback: impl Fn(ReorderEvent) -> Message + 'static) -> Self {
385 self.on_reorder = Some(Box::new(callback));
386 self
387 }
388
389 pub fn tab_drag_threshold(mut self, threshold: f32) -> Self {
391 if let Some(tab_drag) = self.tab_drag.as_mut() {
392 tab_drag.threshold = threshold.max(1.0);
393 }
394 self
395 }
396
397 fn reorder_event_for_drop(&self, state: &LocalState, target: Entity) -> Option<ReorderEvent> {
398 let dragged = state.dragging_tab?;
399 if dragged == target
400 || !self.model.contains_item(dragged)
401 || !self.model.contains_item(target)
402 {
403 return None;
404 }
405 let position = state
406 .drop_hint
407 .filter(|hint| hint.entity == target)
408 .map(|hint| InsertPosition::from(hint.side))
409 .unwrap_or_else(|| self.default_insert_position(dragged, target));
410 Some(ReorderEvent {
411 dragged,
412 target,
413 position,
414 })
415 }
416
417 fn default_insert_position(&self, dragged: Entity, target: Entity) -> InsertPosition {
418 let len = self.model.len();
419 let target_pos = self
420 .model
421 .position(target)
422 .map(|pos| pos as usize)
423 .unwrap_or(len);
424 let from_pos = self
425 .model
426 .position(dragged)
427 .map(|pos| pos as usize)
428 .unwrap_or(target_pos);
429 if from_pos < target_pos {
430 InsertPosition::After
431 } else {
432 InsertPosition::Before
433 }
434 }
435
436 fn is_enabled(&self, key: Entity) -> bool {
438 self.model.items.get(key).is_some_and(|item| item.enabled)
439 }
440
441 pub fn on_dnd_drop<D: AllowedMimeTypes>(
443 mut self,
444 dnd_drop_handler: impl Fn(Entity, Option<D>, DndAction) -> Message + 'static,
445 ) -> Self {
446 self.on_dnd_drop = Some(Box::new(move |entity, data, mime, action| {
447 dnd_drop_handler(entity, D::try_from((data, mime)).ok(), action)
448 }));
449 self.mimes = D::allowed().into_owned();
450 self
451 }
452
453 pub fn on_dnd_enter(
455 mut self,
456 dnd_enter_handler: impl Fn(Entity, Vec<String>) -> Message + 'static,
457 ) -> Self {
458 self.on_dnd_enter = Some(Box::new(dnd_enter_handler));
459 self
460 }
461
462 pub fn on_dnd_leave(mut self, dnd_leave_handler: impl Fn(Entity) -> Message + 'static) -> Self {
464 self.on_dnd_leave = Some(Box::new(dnd_leave_handler));
465 self
466 }
467
468 fn focus_previous(&mut self, state: &mut LocalState, shell: &mut Shell<'_, Message>) {
470 match state.focused_item {
471 Item::Tab(entity) => {
472 let mut keys = self.iterate_visible_tabs(state).rev();
473
474 while let Some(key) = keys.next() {
475 if key == entity {
476 for key in keys {
477 if !self.is_enabled(key) {
479 continue;
480 }
481
482 state.focused_item = Item::Tab(key);
483 shell.capture_event();
484 return;
485 }
486
487 break;
488 }
489 }
490
491 if self.prev_tab_sensitive(state) {
492 state.focused_item = Item::PrevButton;
493 shell.capture_event();
494 return;
495 }
496 }
497
498 Item::NextButton => {
499 if let Some(last) = self.last_tab(state) {
500 state.focused_item = Item::Tab(last);
501 shell.capture_event();
502 return;
503 }
504 }
505
506 Item::None => {
507 if self.next_tab_sensitive(state) {
508 state.focused_item = Item::NextButton;
509 shell.capture_event();
510 return;
511 } else if let Some(last) = self.last_tab(state) {
512 state.focused_item = Item::Tab(last);
513 shell.capture_event();
514 return;
515 }
516 }
517
518 Item::PrevButton | Item::Set => (),
519 }
520
521 state.focused_item = Item::None;
522 }
523
524 fn focus_next(&mut self, state: &mut LocalState, shell: &mut Shell<'_, Message>) {
526 match state.focused_item {
527 Item::Tab(entity) => {
528 let mut keys = self.iterate_visible_tabs(state);
529 while let Some(key) = keys.next() {
530 if key == entity {
531 for key in keys {
532 if !self.is_enabled(key) {
534 continue;
535 }
536
537 state.focused_item = Item::Tab(key);
538 shell.capture_event();
539 return;
540 }
541
542 break;
543 }
544 }
545
546 if self.next_tab_sensitive(state) {
547 state.focused_item = Item::NextButton;
548 shell.capture_event();
549 return;
550 }
551 }
552
553 Item::PrevButton => {
554 if let Some(first) = self.first_tab(state) {
555 state.focused_item = Item::Tab(first);
556 shell.capture_event();
557 return;
558 }
559 }
560
561 Item::None => {
562 if self.prev_tab_sensitive(state) {
563 state.focused_item = Item::PrevButton;
564 shell.capture_event();
565 return;
566 } else if let Some(first) = self.first_tab(state) {
567 state.focused_item = Item::Tab(first);
568 shell.capture_event();
569 return;
570 }
571 }
572
573 Item::NextButton | Item::Set => (),
574 }
575
576 state.focused_item = Item::None;
577 }
578
579 fn iterate_visible_tabs<'b>(
580 &'b self,
581 state: &LocalState,
582 ) -> impl DoubleEndedIterator<Item = Entity> + 'b {
583 self.model
584 .order
585 .iter()
586 .copied()
587 .skip(state.buttons_offset)
588 .take(state.buttons_visible)
589 }
590
591 fn first_tab(&self, state: &LocalState) -> Option<Entity> {
592 self.model.order.get(state.buttons_offset).copied()
593 }
594
595 fn last_tab(&self, state: &LocalState) -> Option<Entity> {
596 self.model
597 .order
598 .get(state.buttons_offset + state.buttons_visible)
599 .copied()
600 }
601
602 #[allow(clippy::unused_self)]
603 fn prev_tab_sensitive(&self, state: &LocalState) -> bool {
604 state.buttons_offset > 0
605 }
606
607 fn next_tab_sensitive(&self, state: &LocalState) -> bool {
608 state.buttons_offset < self.model.order.len() - state.buttons_visible
609 }
610
611 pub(super) fn button_dimensions(
612 &self,
613 state: &mut LocalState,
614 font: crate::font::Font,
615 button: Entity,
616 ) -> (f32, f32) {
617 let mut width = 0.0f32;
618 let mut icon_spacing = 0.0f32;
619
620 if let Some((text, entry)) = self
622 .model
623 .text
624 .get(button)
625 .zip(state.paragraphs.entry(button))
626 && !text.is_empty()
627 {
628 icon_spacing = f32::from(self.button_spacing);
629 let paragraph = entry.or_insert_with(|| {
630 crate::Plain::new(Text {
631 content: text.to_string(), size: iced::Pixels(self.font_size),
633 bounds: Size::INFINITE,
634 font,
635 align_x: text::Alignment::Left,
636 align_y: alignment::Vertical::Center,
637 shaping: Shaping::Advanced,
638 wrapping: Wrapping::default(),
639 ellipsize: self.ellipsize,
640 line_height: self.line_height,
641 })
642 });
643
644 let size = paragraph.min_bounds();
645 width += size.width;
646 }
647
648 if let Some(indent) = self.model.indent(button) {
650 width = f32::from(indent).mul_add(f32::from(self.indent_spacing), width);
651 }
652
653 if let Some(icon) = self.model.icon(button) {
655 width += f32::from(icon.size) + icon_spacing;
656 } else if self.model.is_active(button) {
657 if let crate::theme::SegmentedButton::Control = self.style {
659 width += 16.0 + icon_spacing;
660 }
661 }
662
663 if self.model.is_closable(button) {
665 width += f32::from(self.close_icon.size) + f32::from(self.button_spacing);
666 }
667
668 width += f32::from(self.button_padding[0]) + f32::from(self.button_padding[2]);
670 width = width.min(f32::from(self.maximum_button_width));
671
672 (width, f32::from(self.button_height))
673 }
674
675 pub(super) fn resize_paragraphs(&self, state: &mut LocalState, available_width: f32) {
679 if matches!(self.ellipsize, Ellipsize::None) {
680 return;
681 }
682
683 for (nth, key) in self.model.order.iter().copied().enumerate() {
684 if self.model.text(key).is_some_and(|text| !text.is_empty()) {
685 let mut non_text_width =
686 f32::from(self.button_padding[0]) + f32::from(self.button_padding[2]);
687
688 if let Some(icon) = self.model.icon(key) {
689 non_text_width += f32::from(icon.size) + f32::from(self.button_spacing);
690 } else if self.model.is_active(key)
691 && let crate::theme::SegmentedButton::Control = self.style
692 {
693 non_text_width += 16.0 + f32::from(self.button_spacing);
694 }
695
696 if self.model.is_closable(key) {
697 non_text_width +=
698 f32::from(self.close_icon.size) + f32::from(self.button_spacing);
699 }
700
701 let text_width = (available_width - non_text_width).max(0.0);
702
703 if let Some(paragraph) = state.paragraphs.get_mut(key) {
704 paragraph.resize(Size::new(text_width, f32::INFINITY));
705
706 let content_width = paragraph.min_bounds().width + non_text_width
709 - f32::from(self.button_padding[0])
710 - f32::from(self.button_padding[2]);
711 if let Some(entry) = state.internal_layout.get_mut(nth) {
712 entry.1.width = content_width;
713 }
714 }
715 }
716 }
717 }
718
719 pub(super) fn max_button_dimensions(
720 &self,
721 state: &mut LocalState,
722 renderer: &Renderer,
723 ) -> (f32, f32) {
724 let mut width = 0.0f32;
725 let mut height = 0.0f32;
726 let font = renderer.default_font();
727
728 for key in self.model.order.iter().copied() {
729 let (button_width, button_height) = self.button_dimensions(state, font, key);
730
731 state.internal_layout.push((
732 Size::new(button_width, button_height),
733 Size::new(
734 button_width
735 - f32::from(self.button_padding[0])
736 - f32::from(self.button_padding[2]),
737 button_height,
738 ),
739 ));
740
741 height = height.max(button_height);
742 width = width.max(button_width);
743 }
744
745 for (size, actual) in &mut state.internal_layout {
746 size.height = height;
747 actual.height = height;
748 }
749
750 (width, height)
751 }
752
753 fn button_is_focused(&self, state: &LocalState, key: Entity) -> bool {
754 state.focused.is_some()
755 && self.on_activate.is_some()
756 && Item::Tab(key) == state.focused_item
757 }
758
759 fn button_is_hovered(&self, state: &LocalState, key: Entity) -> bool {
760 self.on_activate.is_some() && state.hovered == Item::Tab(key)
761 || state
762 .dnd_state
763 .drag_offer
764 .as_ref()
765 .is_some_and(|id| id.data.is_some_and(|d| d == key))
766 }
767
768 fn button_is_pressed(&self, state: &LocalState, key: Entity) -> bool {
769 state.pressed_item == Some(Item::Tab(key))
770 }
771
772 fn emit_drop_hint(&self, shell: &mut Shell<'_, Message>, hint: Option<DropHint>) {
773 if let Some(on_hint) = self.on_drop_hint.as_ref() {
774 let mapped = hint.map(|hint| (hint.entity, matches!(hint.side, DropSide::After)));
775 shell.publish(on_hint(mapped));
776 }
777 }
778
779 fn drop_hint_for_position(
780 &self,
781 state: &LocalState,
782 bounds: Rectangle,
783 cursor: Point,
784 ) -> Option<DropHint> {
785 let _ = state.dragging_tab?;
786
787 self.variant_bounds(state, bounds)
788 .filter_map(|item| match item {
789 ItemBounds::Button(entity, rect) if rect.contains(cursor) => Some((entity, rect)),
790 _ => None,
791 })
792 .map(|(entity, rect)| {
793 let before = if Self::VERTICAL {
794 cursor.y < rect.center_y()
795 } else {
796 cursor.x < rect.center_x()
797 };
798 DropHint {
799 entity,
800 side: if before {
801 DropSide::Before
802 } else {
803 DropSide::After
804 },
805 }
806 })
807 .next()
808 }
809
810 fn start_tab_drag(
811 &self,
812 state: &mut LocalState,
813 entity: Entity,
814 bounds: Rectangle,
815 cursor: Point,
816 clipboard: &mut dyn Clipboard,
817 ) -> bool {
818 let Some(tab_drag) = self.tab_drag.as_ref() else {
819 return false;
820 };
821
822 log::trace!(
823 target: TAB_REORDER_LOG_TARGET,
824 "start_tab_drag requested entity={:?} cursor=({:.2},{:.2}) bounds=({:.2},{:.2},{:.2},{:.2}) threshold={}",
825 entity,
826 cursor.x,
827 cursor.y,
828 bounds.x,
829 bounds.y,
830 bounds.width,
831 bounds.height,
832 tab_drag.threshold
833 );
834
835 let data_len = 0;
836
837 iced_core::clipboard::start_dnd::<crate::Theme, crate::Renderer>(
838 clipboard,
839 false,
840 Some(iced_core::clipboard::DndSource::Widget(self.id.0.clone())),
841 None,
842 Box::new(SimpleDragData::new(tab_drag.mime.clone(), vec![1])),
843 DndAction::Move,
844 );
845 log::trace!(
846 target: TAB_REORDER_LOG_TARGET,
847 "tab drag started entity={:?} mime={} bytes={}",
848 entity,
849 tab_drag.mime,
850 data_len
851 );
852
853 state.dragging_tab = Some(entity);
854 state.tab_drag_candidate = None;
855 state.pressed_item = None;
856 true
857 }
858
859 #[must_use]
864 pub fn get_drag_id(&self) -> u128 {
865 self.drag_id.map_or_else(
866 || {
867 u128::from(match &self.id.0.0 {
868 Internal::Unique(id) | Internal::Custom(id, _) => *id,
869 Internal::Set(_) => panic!("Invalid Id assigned to dnd destination."),
870 })
871 },
872 |id| id.0,
873 )
874 }
875
876 #[cfg(wayland_platform)]
877 pub fn with_positioner(
878 mut self,
879 positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
880 ) -> Self {
881 self.positioner = positioner;
882 self
883 }
884
885 pub fn window_id(mut self, id: window::Id) -> Self {
886 self.window_id = id;
887 self
888 }
889
890 pub fn window_id_maybe(mut self, id: Option<window::Id>) -> Self {
891 if let Some(id) = id {
892 self.window_id = id;
893 }
894 self
895 }
896
897 pub fn on_surface_action(
898 mut self,
899 handler: impl Fn(crate::surface::Action<Message>) -> Message + Send + Sync + 'static,
900 ) -> Self {
901 self.on_surface_action = Some(Arc::new(handler));
902 self
903 }
904
905 #[cfg(wayland_platform)]
906 #[allow(clippy::too_many_lines)]
907 fn create_popup<'b>(
908 &mut self,
909 layout: Layout<'b>,
910 view_cursor: mouse::Cursor,
911 renderer: &'b Renderer,
912 shell: &'b mut Shell<'_, Message>,
913 viewport: &'b Rectangle,
914 tree: &'b mut Tree,
915 ) {
916 let state = tree.state.downcast_mut::<LocalState>();
917 let my_state = state.menu_state.clone();
918
919 if self.window_id != window::Id::NONE {
920 use crate::surface::action::{LiveSettings, destroy_popup};
921 use crate::widget::menu::StyleSheet;
922 use iced_runtime::platform_specific::wayland::CornerRadius;
923 use iced_runtime::platform_specific::wayland::popup::{
924 SctkPopupSettings, SctkPositioner,
925 };
926
927 let Some(surface_action) = self.on_surface_action.as_ref() else {
928 return;
929 };
930
931 let id = my_state.inner.with_data_mut(|state| {
932 if let Some(id) = state.popup_id.get(&self.window_id).copied() {
933 state.menu_states.clear();
935 state.active_root.clear();
936 shell.publish(surface_action(destroy_popup(id)));
937 state.view_cursor = view_cursor;
938 }
939 window::Id::unique()
941 });
942 let Some(entity) = state.show_context else {
943 return;
944 };
945
946 let Some((mut bounds, i)) = self
947 .variant_bounds(state, layout.bounds())
948 .filter_map(|item| match item {
949 ItemBounds::Button(entity, bounds) => Some((bounds, entity)),
950 _ => None,
951 })
952 .enumerate()
953 .find_map(|(i, (bounds, e))| if e == entity { Some((bounds, i)) } else { None })
954 else {
955 return;
956 };
957
958 assert!(
959 self.context_menu
960 .as_ref()
961 .is_none_or(|m| m[0].children.len() == self.model.len()),
962 "model length must match the number of context menus"
963 );
964 let menu = self
965 .context_menu
966 .as_mut()
967 .map(|m| m[0].children[i].clone())
968 .unwrap();
969
970 bounds.x = state.context_cursor.x;
971 bounds.y = state.context_cursor.y;
972
973 let mut popup_menu: menu::Menu<'static, _> = menu::Menu {
974 tree: my_state.clone(),
975 menu_roots: std::borrow::Cow::Owned(vec![menu]),
976 bounds_expand: 0,
977 menu_overlays_parent: false,
978 close_condition: CloseCondition {
979 leave: false,
980 click_outside: true,
981 click_inside: true,
982 },
983 item_width: ItemWidth::Uniform(240),
984 item_height: ItemHeight::Dynamic(40),
985 bar_bounds: bounds,
986 main_offset: 0,
987 cross_offset: 0,
988 root_bounds_list: vec![bounds],
989 path_highlight: Some(PathHighlight::MenuActive),
990 style: std::borrow::Cow::Borrowed(&crate::theme::menu_bar::MenuBarStyle::Default),
991 position: Point::new(0., 0.),
992 is_overlay: false,
993 window_id: id,
994 depth: 0,
995 on_surface_action: self.on_surface_action.clone(),
996 };
997
998 menu::init_root_menu(
999 &mut popup_menu,
1000 renderer,
1001 shell,
1002 view_cursor.position().unwrap(),
1003 viewport.size(),
1004 Vector::new(0., 0.),
1005 bounds,
1006 0., );
1008 let (anchor_rect, gravity) = my_state.inner.with_data_mut(|state| {
1009 state.popup_id.insert(self.window_id, id);
1010 (state
1011 .menu_states
1012 .iter()
1013 .find(|s| s.index.is_none())
1014 .map(|s| s.menu_bounds.parent_bounds)
1015 .map_or_else(
1016 || {
1017 let bounds = layout.bounds();
1018 Rectangle {
1019 x: bounds.x as i32,
1020 y: bounds.y as i32,
1021 width: 1,
1022 height: 1,
1023 }
1024 },
1025 |r| Rectangle {
1026 x: r.x as i32,
1027 y: r.y as i32,
1028 width: 1,
1029 height: 1,
1030 },
1031 ), match (state.horizontal_direction, state.vertical_direction) {
1032 (menu::Direction::Positive, menu::Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
1033 (menu::Direction::Positive, menu::Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopRight,
1034 (menu::Direction::Negative, menu::Direction::Positive) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomLeft,
1035 (menu::Direction::Negative, menu::Direction::Negative) => cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::TopLeft,
1036 })
1037 });
1038
1039 let menu_node =
1040 popup_menu.layout(renderer, layout::Limits::NONE.min_width(1.).min_height(1.));
1041 let popup_size = menu_node.size();
1042 let positioner = SctkPositioner {
1043 size: Some((
1044 popup_size.width.ceil() as u32 + 2,
1045 popup_size.height.ceil() as u32 + 2,
1046 )),
1047 anchor_rect,
1048 anchor:
1049 cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Anchor::BottomLeft,
1050 gravity,
1051 reactive: true,
1052 ..Default::default()
1053 };
1054 let parent = self.window_id;
1055
1056 let t = THEME.lock().unwrap();
1057 let styling = t.appearance(&crate::theme::menu_bar::MenuBarStyle::Default, false);
1058 drop(t);
1059 let rad = styling.menu_border_radius;
1060
1061 #[cfg(wayland_platform)]
1063 #[must_use]
1064 pub fn simple_popup<Message: 'static>(
1065 live_settings: impl Fn() -> LiveSettings + Send + Sync + 'static,
1066 settings: impl Fn()
1067 -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
1068 + Send
1069 + Sync
1070 + 'static,
1071 view: Option<impl Fn() -> crate::Element<'static, Message> + Send + Sync + 'static>,
1072 ) -> crate::surface::Action<Message> {
1073 use std::any::Any;
1074
1075 let boxed: Box<
1076 dyn Fn() -> iced_runtime::platform_specific::wayland::popup::SctkPopupSettings
1077 + Send
1078 + Sync
1079 + 'static,
1080 > = Box::new(settings);
1081 let boxed: Box<dyn Any + Send + Sync + 'static> = Box::new(boxed);
1082
1083 let boxed_live: Box<dyn Fn() -> LiveSettings + Send + Sync + 'static> =
1084 Box::new(live_settings);
1085 let boxed_live: Box<dyn Any + Send + Sync + 'static> = Box::new(boxed_live);
1086
1087 crate::surface::Action::Popup(
1088 Arc::new(boxed),
1089 Arc::new(boxed_live),
1090 view.map(|view| {
1091 Arc::new(move || view().map(crate::Action::App))
1092 as crate::surface::View<Message>
1093 }),
1094 )
1095 }
1096 shell.publish((surface_action)(simple_popup(
1097 move || LiveSettings {
1098 corners: Some(CornerRadius {
1099 top_left: rad[0] as u32,
1100 top_right: rad[1] as u32,
1101 bottom_left: rad[2] as u32,
1102 bottom_right: rad[3] as u32,
1103 }),
1104 ..Default::default()
1105 },
1106 move || SctkPopupSettings {
1107 parent,
1108 id,
1109 positioner: positioner.clone(),
1110 parent_size: None,
1111 grab: true,
1112 close_with_children: false,
1113 input_zone: None,
1114 },
1115 Some(move || {
1116 Element::from(crate::widget::container(popup_menu.clone()).center(Length::Fill))
1117 }),
1118 )));
1119 }
1120 }
1121}
1122
1123impl<Variant, SelectionMode, Message> Widget<Message, crate::Theme, Renderer>
1124 for SegmentedButton<'_, Variant, SelectionMode, Message>
1125where
1126 Self: SegmentedVariant,
1127 Model<SelectionMode>: Selectable,
1128 SelectionMode: Default,
1129 Message: 'static + Clone,
1130{
1131 fn id(&self) -> Option<widget::Id> {
1132 Some(self.id.0.clone())
1133 }
1134
1135 fn set_id(&mut self, id: widget::Id) {
1136 self.id = Id(id);
1137 }
1138
1139 fn children(&self) -> Vec<Tree> {
1140 let mut children = Vec::new();
1141
1142 if let Some(ref context_menu) = self.context_menu {
1144 let mut tree = Tree::empty();
1145 tree.state = tree::State::new(MenuBarState::default());
1146 tree.children = menu_roots_children(context_menu);
1147 children.push(tree);
1148 }
1149
1150 children
1151 }
1152
1153 fn tag(&self) -> tree::Tag {
1154 tree::Tag::of::<LocalState>()
1155 }
1156
1157 fn state(&self) -> tree::State {
1158 #[allow(clippy::default_trait_access)]
1159 tree::State::new(LocalState {
1160 menu_state: Default::default(),
1161 paragraphs: SecondaryMap::new(),
1162 text_hashes: SecondaryMap::new(),
1163 buttons_visible: Default::default(),
1164 buttons_offset: Default::default(),
1165 collapsed: Default::default(),
1166 focused: Default::default(),
1167 focused_item: Default::default(),
1168 focused_visible: false,
1169 hovered: Default::default(),
1170 known_length: Default::default(),
1171 middle_clicked: Default::default(),
1172 internal_layout: Default::default(),
1173 context_cursor: Point::default(),
1174 show_context: Default::default(),
1175 wheel_timestamp: Default::default(),
1176 dnd_state: Default::default(),
1177 fingers_pressed: Default::default(),
1178 pressed_item: None,
1179 tab_drag_candidate: None,
1180 dragging_tab: None,
1181 drop_hint: None,
1182 offer_mimes: Vec::new(),
1183 })
1184 }
1185
1186 fn diff(&mut self, tree: &mut Tree) {
1187 let state = tree.state.downcast_mut::<LocalState>();
1188 for key in self.model.order.iter().copied() {
1189 self.update_entity_paragraph(state, key);
1190 }
1191
1192 if let Some(context_menu) = &mut self.context_menu {
1194 state.menu_state.inner.with_data_mut(|inner| {
1195 menu_roots_diff(context_menu, &mut inner.tree);
1196 });
1197 }
1198
1199 if let Some(f) = state.focused.as_ref()
1201 && f.updated_at != LAST_FOCUS_UPDATE.with(|f| f.get())
1202 {
1203 state.unfocus();
1204 }
1205 }
1206
1207 fn size(&self) -> Size<Length> {
1208 Size::new(self.width, self.height)
1209 }
1210
1211 fn layout(
1212 &mut self,
1213 tree: &mut Tree,
1214 renderer: &Renderer,
1215 limits: &layout::Limits,
1216 ) -> layout::Node {
1217 let state = tree.state.downcast_mut::<LocalState>();
1218 let limits = limits.shrink(self.padding);
1219 let size = self
1220 .variant_layout(state, renderer, &limits)
1221 .expand(self.padding);
1222 layout::Node::new(size)
1223 }
1224
1225 #[allow(clippy::too_many_lines)]
1226 fn update(
1227 &mut self,
1228 tree: &mut Tree,
1229 mut event: &Event,
1230 layout: Layout<'_>,
1231 cursor_position: mouse::Cursor,
1232 renderer: &Renderer,
1233 clipboard: &mut dyn Clipboard,
1234 shell: &mut Shell<'_, Message>,
1235 viewport: &iced::Rectangle,
1236 ) {
1237 let my_bounds = layout.bounds();
1238 let state = tree.state.downcast_mut::<LocalState>();
1239
1240 #[cfg(wayland_platform)]
1242 if let iced::Event::PlatformSpecific(iced::event::PlatformSpecific::Wayland(
1243 iced::event::wayland::Event::Popup(iced::event::wayland::PopupEvent::Done, _, popup),
1244 )) = &event
1245 {
1246 let dismissed = state.menu_state.inner.with_data_mut(|data| {
1247 if data.popup_id.get(&self.window_id) == Some(popup) {
1248 data.popup_id.clear();
1249 data.reset();
1250 true
1251 } else {
1252 false
1253 }
1254 });
1255 if dismissed {
1256 state.show_context = None;
1257 for key in self.model.order.iter().copied() {
1258 self.update_entity_paragraph(state, key);
1259 }
1260 }
1261 }
1262
1263 let hovered_before = state.hovered;
1264
1265 let my_id = self.get_drag_id();
1266
1267 if let Event::Dnd(e) = &mut event {
1268 let entity = state
1269 .dnd_state
1270 .drag_offer
1271 .as_ref()
1272 .map(|dnd_state| dnd_state.data);
1273 log::trace!(
1274 target: TAB_REORDER_LOG_TARGET,
1275 "segmented button {:?} received DnD event: {:?} entity={entity:?}",
1276 my_id,
1277 e
1278 );
1279 match e {
1280 DndEvent::Source(SourceEvent::Cancelled | SourceEvent::Finished) => {
1281 if state.dragging_tab.take().is_some() {
1282 state.tab_drag_candidate = None;
1283 state.drop_hint = None;
1284 self.emit_drop_hint(shell, state.drop_hint);
1285 log::trace!(
1286 target: TAB_REORDER_LOG_TARGET,
1287 "tab drag source finished id={:?}",
1288 my_id
1289 );
1290 shell.capture_event();
1291 return;
1292 }
1293 }
1294 DndEvent::Offer(
1295 id,
1296 OfferEvent::Enter {
1297 x, y, mime_types, ..
1298 },
1299 ) if Some(my_id) == *id => {
1300 let entity = self
1301 .variant_bounds(state, my_bounds)
1302 .filter_map(|item| match item {
1303 ItemBounds::Button(entity, bounds) => Some((entity, bounds)),
1304 _ => None,
1305 })
1306 .find(|(_key, bounds)| bounds.contains(Point::new(*x as f32, *y as f32)))
1307 .map(|(key, _)| key);
1308 state.drop_hint = self.drop_hint_for_position(
1309 state,
1310 my_bounds,
1311 Point::new(*x as f32, *y as f32),
1312 );
1313 self.emit_drop_hint(shell, state.drop_hint);
1314 log::trace!(
1315 target: TAB_REORDER_LOG_TARGET,
1316 "offer enter id={my_id:?} entity={entity:?} @ ({x},{y}) mimes={mime_types:?}"
1317 );
1318 if let Some(entity) = entity {
1320 state.hovered = Item::Tab(entity);
1321 for key in self.model.order.iter().copied() {
1322 self.update_entity_paragraph(state, key);
1323 }
1324 }
1325
1326 let on_dnd_enter = self
1327 .on_dnd_enter
1328 .as_ref()
1329 .zip(entity)
1330 .map(|(on_enter, entity)| move |_, _, mimes| on_enter(entity, mimes));
1331 let mimes = if let Some(mime) = self.tab_drag.as_ref().map(|d| &d.mime)
1332 && mime_types.is_empty()
1333 {
1334 vec![mime.clone()]
1335 } else {
1336 mime_types.clone()
1337 };
1338 state.offer_mimes.clone_from(&mimes);
1339
1340 _ = state
1341 .dnd_state
1342 .on_enter::<Message>(*x, *y, mimes, on_dnd_enter, entity);
1343 }
1344 DndEvent::Offer(id, OfferEvent::LeaveDestination) if Some(my_id) != *id => {}
1345 DndEvent::Offer(id, leave)
1346 if matches!(leave, OfferEvent::Leave | OfferEvent::LeaveDestination)
1347 && Some(my_id) == *id =>
1348 {
1349 state.drop_hint = None;
1350 self.emit_drop_hint(shell, state.drop_hint);
1351 if let Some(Some(entity)) = entity
1352 && let Some(on_dnd_leave) = self.on_dnd_leave.as_ref()
1353 {
1354 shell.publish(on_dnd_leave(entity));
1355 }
1356 log::trace!(
1357 target: TAB_REORDER_LOG_TARGET,
1358 "offer leave id={my_id:?} entity={entity:?}"
1359 );
1360 state.hovered = Item::None;
1361 for key in self.model.order.iter().copied() {
1362 self.update_entity_paragraph(state, key);
1363 }
1364 _ = state.dnd_state.on_leave::<Message>(None);
1365 }
1366 DndEvent::Offer(id, OfferEvent::Motion { x, y }) if Some(my_id) == *id => {
1367 log::trace!(
1368 target: TAB_REORDER_LOG_TARGET,
1369 "offer motion id={my_id:?} cursor=({x},{y}) current_entity={entity:?}"
1370 );
1371 let new = self
1372 .variant_bounds(state, my_bounds)
1373 .filter_map(|item| match item {
1374 ItemBounds::Button(entity, bounds) => Some((entity, bounds)),
1375 _ => None,
1376 })
1377 .find(|(_key, bounds)| bounds.contains(Point::new(*x as f32, *y as f32)))
1378 .map(|(key, _)| key);
1379 if let Some(new_entity) = new {
1380 state.dnd_state.on_motion::<Message>(
1381 *x,
1382 *y,
1383 None::<fn(_, _) -> Message>,
1384 None::<fn(_, _, _) -> Message>,
1385 Some(new_entity),
1386 );
1387 state.drop_hint = self.drop_hint_for_position(
1388 state,
1389 my_bounds,
1390 Point::new(*x as f32, *y as f32),
1391 );
1392 self.emit_drop_hint(shell, state.drop_hint);
1393 if Some(Some(new_entity)) != entity {
1394 state.hovered = Item::Tab(new_entity);
1395 for key in self.model.order.iter().copied() {
1396 self.update_entity_paragraph(state, key);
1397 }
1398 let prev_action = state
1399 .dnd_state
1400 .drag_offer
1401 .as_ref()
1402 .map(|dnd| dnd.selected_action);
1403 if let Some(on_dnd_enter) = self.on_dnd_enter.as_ref() {
1404 shell.publish(on_dnd_enter(new_entity, state.offer_mimes.clone()));
1405 }
1406 if let Some(dnd) = state.dnd_state.drag_offer.as_mut() {
1407 dnd.data = Some(new_entity);
1408 if let Some(prev_action) = prev_action {
1409 dnd.selected_action = prev_action;
1410 }
1411 }
1412 }
1413 } else if entity.is_some() {
1414 state.hovered = Item::None;
1415 for key in self.model.order.iter().copied() {
1416 self.update_entity_paragraph(state, key);
1417 }
1418 log::trace!(
1419 target: TAB_REORDER_LOG_TARGET,
1420 "offer motion leaving id={my_id:?}"
1421 );
1422 state.drop_hint = None;
1423 self.emit_drop_hint(shell, state.drop_hint);
1424 state.dnd_state.on_motion::<Message>(
1425 *x,
1426 *y,
1427 None::<fn(_, _) -> Message>,
1428 None::<fn(_, _, _) -> Message>,
1429 None,
1430 );
1431 if let Some(on_dnd_leave) = self.on_dnd_leave.as_ref()
1432 && let Some(Some(entity)) = entity
1433 {
1434 shell.publish(on_dnd_leave(entity));
1435 }
1436 }
1437 }
1438 DndEvent::Offer(id, OfferEvent::Drop) if Some(my_id) == *id => {
1439 log::trace!(
1440 target: TAB_REORDER_LOG_TARGET,
1441 "offer drop id={my_id:?} entity={entity:?}"
1442 );
1443 _ = state
1444 .dnd_state
1445 .on_drop::<Message>(None::<fn(_, _) -> Message>);
1446 }
1447 DndEvent::Offer(id, OfferEvent::SelectedAction(action)) if Some(my_id) == *id => {
1448 if state.dnd_state.drag_offer.is_some() {
1449 log::trace!(
1450 target: TAB_REORDER_LOG_TARGET,
1451 "offer selected action id={my_id:?} action={action:?} entity={entity:?}"
1452 );
1453 _ = state
1454 .dnd_state
1455 .on_action_selected::<Message>(*action, None::<fn(_) -> Message>);
1456 }
1457 }
1458 DndEvent::Offer(id, OfferEvent::Data { data, mime_type }) if Some(my_id) == *id => {
1459 log::trace!(
1460 target: TAB_REORDER_LOG_TARGET,
1461 "offer data id={my_id:?} entity={entity:?} mime={mime_type:?}"
1462 );
1463 let drop_entity = entity
1464 .flatten()
1465 .or_else(|| state.drop_hint.map(|hint| hint.entity));
1466 let allow_reorder = state
1467 .dnd_state
1468 .drag_offer
1469 .as_ref()
1470 .is_some_and(|offer| offer.selected_action.contains(DndAction::Move));
1471 let pending_reorder = if allow_reorder
1472 && self.on_reorder.is_some()
1473 && self.tab_drag.as_ref().is_some_and(|d| d.mime == *mime_type)
1474 && state.dragging_tab.is_some()
1475 {
1476 drop_entity.and_then(|target| self.reorder_event_for_drop(state, target))
1477 } else {
1478 None
1479 };
1480 if let Some(entity) = drop_entity {
1481 let on_drop = self.on_dnd_drop.as_ref();
1482 let on_drop = on_drop.map(|on_drop| {
1483 |mime, data, action, _, _| on_drop(entity, data, mime, action)
1484 });
1485
1486 let (maybe_msg, ret) = state.dnd_state.on_data_received(
1487 mime_type.clone(),
1488 data.clone(),
1489 None::<fn(_, _) -> Message>,
1490 on_drop,
1491 );
1492 if matches!(ret, iced::event::Status::Captured) {
1493 shell.capture_event();
1494 }
1495 if let Some(msg) = maybe_msg {
1496 log::trace!(
1497 target: TAB_REORDER_LOG_TARGET,
1498 "publishing drop message entity={entity:?}"
1499 );
1500 shell.publish(msg);
1501 }
1502 state.drop_hint = None;
1503
1504 self.emit_drop_hint(shell, state.drop_hint);
1505 if let Some(event) = pending_reorder {
1506 state.focused_item = Item::Tab(event.dragged);
1507 state.hovered = Item::None;
1508 for key in self.model.order.iter().copied() {
1509 self.update_entity_paragraph(state, key);
1510 }
1511 if let Some(on_reorder) = self.on_reorder.as_ref() {
1512 shell.publish(on_reorder(event));
1513 shell.capture_event();
1514 return;
1515 }
1516 }
1517 return;
1518 }
1519 }
1520 _ => {}
1521 }
1522 }
1523
1524 if cursor_position.is_over(my_bounds) {
1525 let fingers_pressed = state.fingers_pressed.len();
1526
1527 match event {
1528 Event::Touch(touch::Event::FingerPressed { id, .. }) => {
1529 state.fingers_pressed.insert(*id);
1530 }
1531
1532 Event::Touch(touch::Event::FingerLifted { id, .. }) => {
1533 state.fingers_pressed.remove(id);
1534 }
1535 _ => (),
1536 }
1537
1538 if state.collapsed {
1540 if cursor_position
1542 .is_over(prev_tab_bounds(&my_bounds, f32::from(self.button_height)))
1543 && self.prev_tab_sensitive(state)
1544 {
1545 state.hovered = Item::PrevButton;
1546 for key in self.model.order.iter().copied() {
1547 self.update_entity_paragraph(state, key);
1548 }
1549 if let Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1550 | Event::Touch(touch::Event::FingerLifted { .. }) = event
1551 {
1552 state.buttons_offset -= 1;
1553 }
1554 } else {
1555 if cursor_position
1557 .is_over(next_tab_bounds(&my_bounds, f32::from(self.button_height)))
1558 && self.next_tab_sensitive(state)
1559 {
1560 state.hovered = Item::NextButton;
1561 for key in self.model.order.iter().copied() {
1562 self.update_entity_paragraph(state, key);
1563 }
1564 if let Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1565 | Event::Touch(touch::Event::FingerLifted { .. }) = event
1566 {
1567 state.buttons_offset += 1;
1568 }
1569 }
1570 }
1571 }
1572
1573 for (key, bounds) in self
1574 .variant_bounds(state, my_bounds)
1575 .filter_map(|item| match item {
1576 ItemBounds::Button(entity, bounds) => Some((entity, bounds)),
1577 _ => None,
1578 })
1579 .collect::<Vec<_>>()
1580 {
1581 if cursor_position.is_over(bounds) {
1582 if self.model.items[key].enabled {
1583 if state.hovered != Item::Tab(key) {
1585 state.hovered = Item::Tab(key);
1586 for key in self.model.order.iter().copied() {
1587 self.update_entity_paragraph(state, key);
1588 }
1589 }
1590
1591 let close_button_bounds =
1592 close_bounds(bounds, f32::from(self.close_icon.size));
1593 let over_close_button = self.model.items[key].closable
1594 && cursor_position.is_over(close_button_bounds);
1595
1596 if self.model.items[key].closable {
1598 if let Some(on_close) = self.on_close.as_ref() {
1600 if over_close_button
1601 && (left_button_released(event)
1602 || (touch_lifted(event) && fingers_pressed == 1))
1603 {
1604 shell.publish(on_close(key));
1605 shell.capture_event();
1606 return;
1607 }
1608
1609 if self.on_middle_press.is_none() {
1610 if let Event::Mouse(mouse::Event::ButtonReleased(
1612 mouse::Button::Middle,
1613 )) = event
1614 {
1615 if state.middle_clicked == Some(Item::Tab(key)) {
1616 shell.publish(on_close(key));
1617 shell.capture_event();
1618 return;
1619 }
1620
1621 state.middle_clicked = None;
1622 }
1623 }
1624 }
1625 }
1626
1627 if self.tab_drag.is_some()
1628 && matches!(
1629 event,
1630 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
1631 )
1632 && !over_close_button
1633 && let Some(position) = cursor_position.position()
1634 {
1635 state.tab_drag_candidate = Some(TabDragCandidate {
1636 entity: key,
1637 bounds,
1638 origin: position,
1639 });
1640 if let Some(tab_drag) = self.tab_drag.as_ref() {
1641 log::trace!(
1642 target: TAB_REORDER_LOG_TARGET,
1643 "tab drag candidate entity={:?} origin=({:.2},{:.2}) bounds=({:.2},{:.2},{:.2},{:.2}) threshold={}",
1644 key,
1645 position.x,
1646 position.y,
1647 bounds.x,
1648 bounds.y,
1649 bounds.width,
1650 bounds.height,
1651 tab_drag.threshold
1652 );
1653 }
1654 }
1655
1656 if is_lifted(event) {
1657 state.unfocus();
1658 }
1659
1660 #[cfg(wayland_platform)]
1661 if is_pressed(event)
1662 && let Some(_on_context) = self.on_context.as_ref()
1663 {
1664 let (was_open, id) = state.menu_state.inner.with_data_mut(|data| {
1665 let was_open = data.open;
1666 data.reset();
1667 data.open = false;
1668 data.view_cursor = cursor_position;
1669 let root = data.popup_id.remove(&self.window_id);
1670 data.popup_id.clear();
1671 (was_open, root)
1672 });
1673 if let Some(w) = id
1674 && let Some(surface_action) = self.on_surface_action.as_ref()
1675 && was_open
1676 {
1677 use crate::surface::action::destroy_popup;
1678
1679 shell.publish((surface_action)(destroy_popup(w)));
1680 return;
1681 }
1682 }
1683
1684 if let Some(on_activate) = self.on_activate.as_ref() {
1685 if is_pressed(event) {
1686 state.pressed_item = Some(Item::Tab(key));
1687 } else if is_lifted(event) && self.button_is_pressed(state, key) {
1688 shell.publish(on_activate(key));
1689 state.set_focused();
1690 state.focused_item = Item::Tab(key);
1691 state.pressed_item = None;
1692 shell.capture_event();
1693 return;
1694 }
1695 }
1696
1697 if self.context_menu.is_some()
1699 && let Some(on_context) = self.on_context.as_ref()
1700 && (right_button_released(event)
1701 || (touch_lifted(event) && fingers_pressed == 2))
1702 {
1703 state.show_context = Some(key);
1704 state.context_cursor = cursor_position.position().unwrap_or_default();
1705
1706 state.menu_state.inner.with_data_mut(|data| {
1707 data.reset();
1709 data.open = true;
1710 data.view_cursor = cursor_position;
1711 });
1712
1713 shell.publish(on_context(key));
1714 shell.capture_event();
1715
1716 #[cfg(wayland_platform)]
1717 if matches!(
1718 crate::app::cosmic::WINDOWING_SYSTEM.get(),
1719 Some(crate::app::cosmic::WindowingSystem::Wayland)
1720 ) {
1721 self.create_popup(
1722 layout,
1723 cursor_position,
1724 renderer,
1725 shell,
1726 viewport,
1727 tree,
1728 );
1729 }
1730 return;
1731 }
1732 if let Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) =
1733 event
1734 {
1735 state.middle_clicked = Some(Item::Tab(key));
1736 if let Some(on_middle_press) = self.on_middle_press.as_ref() {
1737 shell.publish(on_middle_press(key));
1738 shell.capture_event();
1739 return;
1740 }
1741 }
1742 }
1743
1744 break;
1745 } else if state.hovered == Item::Tab(key) {
1746 state.hovered = Item::None;
1747 self.update_entity_paragraph(state, key);
1748 }
1749 }
1750
1751 if self.scrollable_focus
1752 && let Some(on_activate) = self.on_activate.as_ref()
1753 && let Event::Mouse(mouse::Event::WheelScrolled { delta }) = event
1754 {
1755 let current = Instant::now();
1756
1757 if state.wheel_timestamp.is_none_or(|previous| {
1759 current.duration_since(previous) > Duration::from_millis(250)
1760 }) {
1761 state.wheel_timestamp = Some(current);
1762
1763 match delta {
1764 ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } => {
1765 let mut activate_key = None;
1766
1767 if *y < 0.0 {
1768 let mut prev_key = Entity::null();
1769
1770 for key in self.model.order.iter().copied() {
1771 if self.model.is_active(key) && !prev_key.is_null() {
1772 activate_key = Some(prev_key);
1773 }
1774
1775 if self.model.is_enabled(key) {
1776 prev_key = key;
1777 }
1778 }
1779 } else if *y > 0.0 {
1780 let mut buttons = self.model.order.iter().copied();
1781 while let Some(key) = buttons.next() {
1782 if self.model.is_active(key) {
1783 for key in buttons {
1784 if self.model.is_enabled(key) {
1785 activate_key = Some(key);
1786 break;
1787 }
1788 }
1789 break;
1790 }
1791 }
1792 }
1793
1794 if let Some(key) = activate_key {
1795 shell.publish(on_activate(key));
1796 state.set_focused();
1797 state.focused_item = Item::Tab(key);
1798 shell.capture_event();
1799 return;
1800 }
1801 }
1802 }
1803 }
1804 }
1805 } else {
1806 if let Item::Tab(_key) = std::mem::replace(&mut state.hovered, Item::None) {
1807 for key in self.model.order.iter().copied() {
1808 self.update_entity_paragraph(state, key);
1809 }
1810 }
1811 if state.is_focused() {
1812 if is_pressed(event) {
1814 state.unfocus();
1815 state.pressed_item = None;
1816 return;
1817 }
1818 } else if is_lifted(event) {
1819 state.pressed_item = None;
1820 }
1821 }
1822
1823 if let (Some(tab_drag), Some(candidate)) =
1824 (self.tab_drag.as_ref(), state.tab_drag_candidate)
1825 && let Event::Mouse(mouse::Event::CursorMoved { .. }) = event
1826 && let Some(position) = cursor_position.position()
1827 && position.distance(candidate.origin) >= tab_drag.threshold
1828 && let Some(candidate) = state.tab_drag_candidate.take()
1829 {
1830 log::trace!(
1831 target: TAB_REORDER_LOG_TARGET,
1832 "tab drag threshold met entity={:?} distance={:.2} threshold={}",
1833 candidate.entity,
1834 position.distance(candidate.origin),
1835 tab_drag.threshold
1836 );
1837 if self.start_tab_drag(
1838 state,
1839 candidate.entity,
1840 candidate.bounds,
1841 position,
1842 clipboard,
1843 ) {
1844 shell.capture_event();
1845 return;
1846 }
1847 }
1848
1849 if (matches!(event, Event::Mouse(mouse::Event::ButtonReleased(_))) || (touch_lifted(event)))
1850 && let Some(_id) = state
1851 .menu_state
1852 .inner
1853 .with_data_mut(|ms| ms.popup_id.remove(&self.window_id))
1854 {
1855 #[cfg(wayland_platform)]
1856 {
1857 let surface_action = self.on_surface_action.as_ref().unwrap();
1858 shell.capture_event();
1859
1860 shell.publish(surface_action(crate::surface::action::destroy_popup(_id)));
1861 }
1862 state.show_context = None;
1863
1864 state.menu_state.inner.with_data_mut(|data| {
1865 data.reset();
1867 data.open = false;
1868 data.view_cursor = cursor_position;
1869 });
1870 }
1871
1872 if matches!(
1873 event,
1874 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1875 ) {
1876 state.tab_drag_candidate = None;
1877 }
1878
1879 if state.is_focused() {
1880 if let Event::Keyboard(keyboard::Event::KeyPressed {
1881 key: keyboard::Key::Named(keyboard::key::Named::Tab),
1882 modifiers,
1883 ..
1884 }) = event
1885 {
1886 shell.request_redraw();
1887 state.focused_visible = true;
1888 return if *modifiers == keyboard::Modifiers::SHIFT {
1889 self.focus_previous(state, shell);
1890 } else if modifiers.is_empty() {
1891 self.focus_next(state, shell);
1892 };
1893 }
1894
1895 if let Some(on_activate) = self.on_activate.as_ref()
1896 && let Event::Keyboard(keyboard::Event::KeyReleased {
1897 key: keyboard::Key::Named(keyboard::key::Named::Enter),
1898 ..
1899 }) = event
1900 {
1901 match state.focused_item {
1902 Item::Tab(entity) => {
1903 shell.publish(on_activate(entity));
1904 }
1905
1906 Item::PrevButton => {
1907 if self.prev_tab_sensitive(state) {
1908 state.buttons_offset -= 1;
1909
1910 if !self.prev_tab_sensitive(state)
1912 && let Some(first) = self.first_tab(state)
1913 {
1914 state.focused_item = Item::Tab(first);
1915 }
1916 }
1917 }
1918
1919 Item::NextButton => {
1920 if self.next_tab_sensitive(state) {
1921 state.buttons_offset += 1;
1922
1923 if !self.next_tab_sensitive(state)
1925 && let Some(last) = self.last_tab(state)
1926 {
1927 state.focused_item = Item::Tab(last);
1928 }
1929 }
1930 }
1931
1932 Item::None | Item::Set => (),
1933 }
1934
1935 shell.capture_event();
1936 }
1937 }
1938
1939 if hovered_before != state.hovered {
1940 shell.request_redraw();
1941 }
1942 }
1943
1944 fn operate(
1945 &mut self,
1946 tree: &mut Tree,
1947 layout: Layout<'_>,
1948 _renderer: &Renderer,
1949 operation: &mut dyn iced_core::widget::Operation<()>,
1950 ) {
1951 let state = tree.state.downcast_mut::<LocalState>();
1952 operation.focusable(Some(&self.id.0), layout.bounds(), state);
1953 operation.custom(Some(&self.id.0), layout.bounds(), state);
1954
1955 if let Item::Set = state.focused_item {
1956 if self.prev_tab_sensitive(state) {
1957 state.focused_item = Item::PrevButton;
1958 } else if let Some(first) = self.first_tab(state) {
1959 state.focused_item = Item::Tab(first);
1960 }
1961 }
1962 }
1963
1964 fn mouse_interaction(
1965 &self,
1966 tree: &Tree,
1967 layout: Layout<'_>,
1968 cursor_position: mouse::Cursor,
1969 _viewport: &iced::Rectangle,
1970 _renderer: &Renderer,
1971 ) -> iced_core::mouse::Interaction {
1972 if self.on_activate.is_none() {
1973 return iced_core::mouse::Interaction::default();
1974 }
1975 let state = tree.state.downcast_ref::<LocalState>();
1976 let bounds = layout.bounds();
1977
1978 if cursor_position.is_over(bounds) {
1979 let hovered_button = self
1980 .variant_bounds(state, bounds)
1981 .filter_map(|item| match item {
1982 ItemBounds::Button(entity, bounds) => Some((entity, bounds)),
1983 _ => None,
1984 })
1985 .find(|(_key, bounds)| cursor_position.is_over(*bounds));
1986
1987 if let Some((key, _bounds)) = hovered_button {
1988 return if self.model.items[key].enabled {
1989 iced_core::mouse::Interaction::Pointer
1990 } else {
1991 iced_core::mouse::Interaction::Idle
1992 };
1993 }
1994 }
1995
1996 iced_core::mouse::Interaction::default()
1997 }
1998
1999 #[allow(clippy::too_many_lines)]
2000 fn draw(
2001 &self,
2002 tree: &Tree,
2003 renderer: &mut Renderer,
2004 theme: &crate::Theme,
2005 style: &renderer::Style,
2006 layout: Layout<'_>,
2007 cursor: mouse::Cursor,
2008 viewport: &iced::Rectangle,
2009 ) {
2010 let state = tree.state.downcast_ref::<LocalState>();
2011 let appearance = Self::variant_appearance(theme, &self.style);
2012 let bounds: Rectangle = layout.bounds();
2013 let button_amount = self.model.items.len();
2014 let show_drop_hint = state.dragging_tab.is_some();
2015 let drop_hint = if show_drop_hint {
2016 state.drop_hint
2017 } else {
2018 None
2019 };
2020
2021 if let Some(background) = appearance.background {
2023 renderer.fill_quad(
2024 renderer::Quad {
2025 bounds,
2026 border: appearance.border,
2027 shadow: Shadow::default(),
2028 snap: true,
2029 },
2030 background,
2031 );
2032 }
2033
2034 if state.collapsed {
2036 let mut tab_bounds = prev_tab_bounds(&bounds, f32::from(self.button_height));
2037
2038 let mut background_appearance =
2040 if self.on_activate.is_some() && Item::PrevButton == state.focused_item {
2041 Some(appearance.active)
2042 } else if self.on_activate.is_some() && Item::PrevButton == state.hovered {
2043 Some(appearance.hover)
2044 } else {
2045 None
2046 };
2047
2048 if let Some(background_appearance) = background_appearance.take() {
2049 renderer.fill_quad(
2050 renderer::Quad {
2051 bounds: tab_bounds,
2052 border: Border {
2053 radius: theme.cosmic().radius_s().into(),
2054 ..Default::default()
2055 },
2056 shadow: Shadow::default(),
2057 snap: true,
2058 },
2059 background_appearance
2060 .background
2061 .unwrap_or(Background::Color(Color::TRANSPARENT)),
2062 );
2063 }
2064
2065 draw_icon::<Message>(
2066 renderer,
2067 theme,
2068 style,
2069 cursor,
2070 viewport,
2071 if state.buttons_offset == 0 {
2072 appearance.inactive.text_color
2073 } else {
2074 appearance.active.text_color
2075 },
2076 Rectangle {
2077 x: tab_bounds.x + 8.0,
2078 y: tab_bounds.y + f32::from(self.button_height) / 4.0,
2079 width: 16.0,
2080 height: 16.0,
2081 },
2082 icon::from_name("go-previous-symbolic").size(16).icon(),
2083 );
2084
2085 tab_bounds = next_tab_bounds(&bounds, f32::from(self.button_height));
2086
2087 background_appearance =
2089 if self.on_activate.is_some() && Item::NextButton == state.focused_item {
2090 Some(appearance.active)
2091 } else if self.on_activate.is_some() && Item::NextButton == state.hovered {
2092 Some(appearance.hover)
2093 } else {
2094 None
2095 };
2096
2097 if let Some(background_appearance) = background_appearance {
2098 renderer.fill_quad(
2099 renderer::Quad {
2100 bounds: tab_bounds,
2101 border: Border {
2102 radius: theme.cosmic().radius_s().into(),
2103 ..Default::default()
2104 },
2105 shadow: Shadow::default(),
2106 snap: true,
2107 },
2108 background_appearance
2109 .background
2110 .unwrap_or(Background::Color(Color::TRANSPARENT)),
2111 );
2112 }
2113
2114 draw_icon::<Message>(
2115 renderer,
2116 theme,
2117 style,
2118 cursor,
2119 viewport,
2120 if self.next_tab_sensitive(state) {
2121 appearance.active.text_color
2122 } else if let Item::NextButton = state.focused_item {
2123 appearance.active.text_color
2124 } else {
2125 appearance.inactive.text_color
2126 },
2127 Rectangle {
2128 x: tab_bounds.x + 8.0,
2129 y: tab_bounds.y + f32::from(self.button_height) / 4.0,
2130 width: 16.0,
2131 height: 16.0,
2132 },
2133 icon::from_name("go-next-symbolic").size(16).icon(),
2134 );
2135 }
2136
2137 let rad_0 = THEME.lock().unwrap().cosmic().corner_radii.radius_0;
2138
2139 let divider_background = Background::Color(
2140 crate::theme::active()
2141 .cosmic()
2142 .primary_component_divider()
2143 .into(),
2144 );
2145
2146 let mut nth = 0;
2148 let drop_hint_marker = drop_hint;
2149 let show_drop_hint_marker = show_drop_hint;
2150 self.variant_bounds(state, bounds).for_each(move |item| {
2151 let (key, mut bounds) = match item {
2152 ItemBounds::Button(entity, bounds) => (entity, bounds),
2154
2155 ItemBounds::Divider(bounds, accented) => {
2157 renderer.fill_quad(
2158 renderer::Quad {
2159 bounds,
2160 border: Border::default(),
2161 shadow: Shadow::default(),
2162 snap: true,
2163 },
2164 {
2165 let theme = crate::theme::active();
2166 if accented {
2167 Background::Color(theme.cosmic().small_widget_divider().into())
2168 } else {
2169 Background::Color(theme.cosmic().primary_container_divider().into())
2170 }
2171 },
2172 );
2173
2174 return;
2175 }
2176 };
2177
2178 let original_bounds = bounds;
2179 let center_y = bounds.center_y();
2180
2181 if show_drop_hint_marker
2182 && matches!(
2183 drop_hint_marker,
2184 Some(DropHint {
2185 entity,
2186 side: DropSide::Before
2187 }) if entity == key
2188 )
2189 {
2190 draw_drop_indicator(
2191 renderer,
2192 original_bounds,
2193 DropSide::Before,
2194 Self::VERTICAL,
2195 appearance.active.text_color,
2196 );
2197 }
2198
2199 let menu_open = || {
2200 state.show_context == Some(key)
2201 && state.menu_state.inner.with_data(|data| data.open)
2202 };
2203
2204 let key_is_active = self.model.is_active(key);
2205 let key_is_focused = state.focused_visible && self.button_is_focused(state, key);
2206 let key_is_hovered = self.button_is_hovered(state, key);
2207 let status_appearance = if self.button_is_pressed(state, key) {
2208 appearance.pressed
2209 } else if key_is_hovered || menu_open() {
2210 appearance.hover
2211 } else if key_is_active {
2212 appearance.active
2213 } else {
2214 appearance.inactive
2215 };
2216
2217 let button_appearance = if nth == 0 {
2218 status_appearance.first
2219 } else if nth + 1 == button_amount {
2220 status_appearance.last
2221 } else {
2222 status_appearance.middle
2223 };
2224
2225 if appearance.active_width > 0.0 {
2227 let active_width = if key_is_active {
2228 appearance.active_width
2229 } else {
2230 1.0
2231 };
2232
2233 renderer.fill_quad(
2234 renderer::Quad {
2235 bounds: if Self::VERTICAL {
2236 Rectangle {
2237 x: bounds.x + bounds.width - active_width,
2238 width: active_width,
2239 ..bounds
2240 }
2241 } else {
2242 Rectangle {
2243 y: bounds.y + bounds.height - active_width,
2244 height: active_width,
2245 ..bounds
2246 }
2247 },
2248 border: Border {
2249 radius: rad_0.into(),
2250 ..Default::default()
2251 },
2252 shadow: Shadow::default(),
2253 snap: true,
2254 },
2255 appearance.active.text_color,
2256 );
2257 }
2258
2259 bounds.x += f32::from(self.button_padding[0]);
2260 bounds.width -= f32::from(self.button_padding[0]) - f32::from(self.button_padding[2]);
2261 let mut indent_padding = 0.0;
2262
2263 if let Some(indent) = self.model.indent(key)
2265 && indent > 0
2266 {
2267 let adjustment = f32::from(indent) * f32::from(self.indent_spacing);
2268 bounds.x += adjustment;
2269 bounds.width -= adjustment;
2270
2271 if let crate::theme::SegmentedButton::FileNav = self.style
2273 && indent > 1
2274 {
2275 indent_padding = 7.0;
2276
2277 for level in 1..indent {
2278 renderer.fill_quad(
2279 renderer::Quad {
2280 bounds: Rectangle {
2281 x: (level as f32)
2282 .mul_add(-(self.indent_spacing as f32), bounds.x)
2283 + indent_padding,
2284 width: 1.0,
2285 ..bounds
2286 },
2287 border: Border {
2288 radius: rad_0.into(),
2289 ..Default::default()
2290 },
2291 shadow: Shadow::default(),
2292 snap: true,
2293 },
2294 divider_background,
2295 );
2296 }
2297
2298 indent_padding += 4.0;
2299 }
2300 }
2301
2302 if key_is_focused || status_appearance.background.is_some() {
2304 renderer.fill_quad(
2305 renderer::Quad {
2306 bounds: Rectangle {
2307 x: bounds.x - f32::from(self.button_padding[0]) + indent_padding,
2308 width: bounds.width + f32::from(self.button_padding[0])
2309 - f32::from(self.button_padding[2])
2310 - indent_padding,
2311 ..bounds
2312 },
2313 border: if key_is_focused {
2314 Border {
2315 width: 1.0,
2316 color: appearance.active.text_color,
2317 radius: button_appearance.border.radius,
2318 }
2319 } else {
2320 button_appearance.border
2321 },
2322 shadow: Shadow::default(),
2323 snap: true,
2324 },
2325 status_appearance
2326 .background
2327 .unwrap_or(Background::Color(Color::TRANSPARENT)),
2328 );
2329 }
2330
2331 {
2333 let actual_width = state.internal_layout[nth].1.width.min(bounds.width);
2336
2337 let offset = match self.button_alignment {
2338 Alignment::Start => None,
2339 Alignment::Center => Some((bounds.width - actual_width) / 2.0),
2340 Alignment::End => Some(bounds.width - actual_width),
2341 };
2342
2343 if let Some(offset) = offset {
2344 bounds.x += offset - f32::from(self.button_padding[0]);
2345 bounds.width = actual_width;
2346 }
2347 }
2348
2349 if let Some(icon) = self.model.icon(key) {
2351 let mut image_bounds = bounds;
2352 let width = f32::from(icon.size);
2353 let offset = width + f32::from(self.button_spacing);
2354 image_bounds.y = center_y - width / 2.0;
2355
2356 draw_icon::<Message>(
2357 renderer,
2358 theme,
2359 style,
2360 cursor,
2361 viewport,
2362 status_appearance.text_color,
2363 Rectangle {
2364 width,
2365 height: width,
2366 ..image_bounds
2367 },
2368 icon.clone(),
2369 );
2370
2371 bounds.x += offset;
2372 } else {
2373 if key_is_active && let crate::theme::SegmentedButton::Control = self.style {
2375 let mut image_bounds = bounds;
2376 image_bounds.y = center_y - 8.0;
2377
2378 draw_icon::<Message>(
2379 renderer,
2380 theme,
2381 style,
2382 cursor,
2383 viewport,
2384 status_appearance.text_color,
2385 Rectangle {
2386 width: 16.0,
2387 height: 16.0,
2388 ..image_bounds
2389 },
2390 crate::widget::icon(match crate::widget::common::object_select().data() {
2391 iced_core::svg::Data::Bytes(bytes) => {
2392 crate::widget::icon::from_svg_bytes(bytes.as_ref()).symbolic(true)
2393 }
2394 iced_core::svg::Data::Path(path) => {
2395 crate::widget::icon::from_path(path.clone())
2396 }
2397 }),
2398 );
2399
2400 let offset = 16.0 + f32::from(self.button_spacing);
2401
2402 bounds.x += offset;
2403 }
2404 }
2405
2406 let show_close_button =
2408 (key_is_active || !self.show_close_icon_on_hover || key_is_hovered)
2409 && self.model.is_closable(key);
2410
2411 let close_icon_width = if show_close_button {
2413 f32::from(self.close_icon.size)
2414 } else {
2415 0.0
2416 };
2417
2418 bounds.width = original_bounds.width
2419 - (bounds.x - original_bounds.x)
2420 - close_icon_width
2421 - f32::from(self.button_padding[2]);
2422
2423 bounds.y = center_y;
2424
2425 if self.model.text(key).is_some_and(|text| !text.is_empty()) {
2426 bounds.y -= state.paragraphs[key].min_height() / 2.;
2428
2429 renderer.fill_paragraph(
2431 state.paragraphs[key].raw(),
2432 bounds.position(),
2433 status_appearance.text_color,
2434 Rectangle {
2435 x: bounds.x,
2436 width: bounds.width,
2437 height: original_bounds.height,
2438 y: bounds.y,
2439 },
2441 );
2442 }
2443
2444 if show_close_button {
2446 let close_button_bounds = close_bounds(original_bounds, close_icon_width);
2447
2448 draw_icon::<Message>(
2449 renderer,
2450 theme,
2451 style,
2452 cursor,
2453 viewport,
2454 status_appearance.text_color,
2455 close_button_bounds,
2456 self.close_icon.clone(),
2457 );
2458 }
2459
2460 if show_drop_hint_marker
2461 && matches!(
2462 drop_hint_marker,
2463 Some(DropHint {
2464 entity,
2465 side: DropSide::After
2466 }) if entity == key
2467 )
2468 {
2469 draw_drop_indicator(
2470 renderer,
2471 original_bounds,
2472 DropSide::After,
2473 Self::VERTICAL,
2474 appearance.active.text_color,
2475 );
2476 }
2477
2478 nth += 1;
2479 });
2480 }
2481
2482 fn overlay<'b>(
2483 &'b mut self,
2484 tree: &'b mut Tree,
2485 layout: iced_core::Layout<'b>,
2486 _renderer: &Renderer,
2487 _viewport: &iced_core::Rectangle,
2488 translation: Vector,
2489 ) -> Option<iced_core::overlay::Element<'b, Message, crate::Theme, Renderer>> {
2490 #[cfg(wayland_platform)]
2491 if matches!(
2492 crate::app::cosmic::WINDOWING_SYSTEM.get(),
2493 Some(crate::app::cosmic::WindowingSystem::Wayland)
2494 ) && self.on_surface_action.is_some()
2495 && self.window_id != window::Id::NONE
2496 {
2497 return None;
2498 }
2499
2500 let state = tree.state.downcast_mut::<LocalState>();
2501 let menu_state = state.menu_state.clone();
2502
2503 let entity = state.show_context?;
2504
2505 let (mut bounds, i) = self
2506 .variant_bounds(state, layout.bounds())
2507 .filter_map(|item| match item {
2508 ItemBounds::Button(entity, bounds) => Some((bounds, entity)),
2509 _ => None,
2510 })
2511 .enumerate()
2512 .find_map(|(i, (bounds, e))| if e == entity { Some((bounds, i)) } else { None })?;
2513
2514 assert!(
2515 self.context_menu
2516 .as_ref()
2517 .is_none_or(|m| m[0].children.len() == self.model.len())
2518 );
2519 let menu = self
2520 .context_menu
2521 .as_mut()
2522 .map(|m| m[0].children[i].clone())?;
2523
2524 if !menu_state.inner.with_data(|data| data.open) {
2525 state.show_context = None;
2529 for key in self.model.order.iter().copied() {
2530 self.update_entity_paragraph(state, key);
2531 }
2532 return None;
2533 }
2534 bounds.x = state.context_cursor.x;
2535 bounds.y = state.context_cursor.y;
2536
2537 Some(
2538 crate::widget::menu::Menu {
2539 tree: menu_state,
2540 menu_roots: std::borrow::Cow::Owned(vec![menu]),
2541 bounds_expand: 16,
2542 menu_overlays_parent: true,
2543 close_condition: CloseCondition {
2544 leave: false,
2545 click_outside: true,
2546 click_inside: true,
2547 },
2548 item_width: ItemWidth::Uniform(240),
2549 item_height: ItemHeight::Dynamic(40),
2550 bar_bounds: bounds,
2551 main_offset: -bounds.height as i32,
2552 cross_offset: 0,
2553 root_bounds_list: vec![bounds],
2554 path_highlight: Some(PathHighlight::MenuActive),
2555 style: std::borrow::Cow::Borrowed(&crate::theme::menu_bar::MenuBarStyle::Default),
2556 position: Point::new(translation.x, translation.y),
2557 is_overlay: true,
2558 window_id: window::Id::NONE,
2559 depth: 0,
2560 on_surface_action: None,
2561 }
2562 .overlay(),
2563 )
2564 }
2565
2566 fn drag_destinations(
2567 &self,
2568 tree: &Tree,
2569 layout: Layout<'_>,
2570 _renderer: &Renderer,
2571 dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
2572 ) {
2573 let local_state = tree.state.downcast_ref::<LocalState>();
2574 let my_id = self.get_drag_id();
2575 let mut pushed = false;
2576
2577 for item in self.variant_bounds(local_state, layout.bounds()) {
2578 if let ItemBounds::Button(_entity, rect) = item {
2579 pushed = true;
2580 log::trace!(
2581 target: TAB_REORDER_LOG_TARGET,
2582 "register drag destination id={:?} bounds=({:.2},{:.2},{:.2},{:.2}) mimes={:?}",
2583 my_id,
2584 rect.x,
2585 rect.y,
2586 rect.width,
2587 rect.height,
2588 self.mimes
2589 );
2590 dnd_rectangles.push(DndDestinationRectangle {
2591 id: my_id,
2592 rectangle: dnd::Rectangle {
2593 x: f64::from(rect.x),
2594 y: f64::from(rect.y),
2595 width: f64::from(rect.width),
2596 height: f64::from(rect.height),
2597 },
2598 mime_types: self.mimes.clone().into_iter().map(Cow::Owned).collect(),
2599 actions: DndAction::Copy | DndAction::Move,
2600 preferred: DndAction::Move,
2601 });
2602 }
2603 }
2604
2605 if let Some(mime) = self.tab_drag.as_ref().map(|d| &d.mime) {
2606 for item in self.variant_bounds(local_state, layout.bounds()) {
2607 if let ItemBounds::Button(_entity, rect) = item {
2608 pushed = true;
2609 log::trace!(
2610 target: TAB_REORDER_LOG_TARGET,
2611 "register drag destination id={:?} bounds=({:.2},{:.2},{:.2},{:.2}) mimes={:?}",
2612 my_id,
2613 rect.x,
2614 rect.y,
2615 rect.width,
2616 rect.height,
2617 mime
2618 );
2619 dnd_rectangles.push(DndDestinationRectangle {
2620 id: my_id,
2621 rectangle: dnd::Rectangle {
2622 x: f64::from(rect.x),
2623 y: f64::from(rect.y),
2624 width: f64::from(rect.width),
2625 height: f64::from(rect.height),
2626 },
2627 mime_types: vec![Cow::Owned(mime.clone())],
2628 actions: DndAction::Copy | DndAction::Move,
2629 preferred: DndAction::Move,
2630 });
2631 }
2632 }
2633 }
2634
2635 if !pushed {
2636 let bounds = layout.bounds();
2637 log::trace!(
2638 target: TAB_REORDER_LOG_TARGET,
2639 "register drag destination id={:?} bounds=({:.2},{:.2},{:.2},{:.2}) mimes={:?}",
2640 my_id,
2641 bounds.x,
2642 bounds.y,
2643 bounds.width,
2644 bounds.height,
2645 self.mimes
2646 );
2647 dnd_rectangles.push(DndDestinationRectangle {
2648 id: my_id,
2649 rectangle: dnd::Rectangle {
2650 x: f64::from(bounds.x),
2651 y: f64::from(bounds.y),
2652 width: f64::from(bounds.width),
2653 height: f64::from(bounds.height),
2654 },
2655 mime_types: self.mimes.clone().into_iter().map(Cow::Owned).collect(),
2656 actions: DndAction::Copy | DndAction::Move,
2657 preferred: DndAction::Move,
2658 });
2659 }
2660 }
2661}
2662
2663impl<'a, Variant, SelectionMode, Message> From<SegmentedButton<'a, Variant, SelectionMode, Message>>
2664 for Element<'a, Message>
2665where
2666 SegmentedButton<'a, Variant, SelectionMode, Message>: SegmentedVariant,
2667 Variant: 'static,
2668 Model<SelectionMode>: Selectable,
2669 SelectionMode: Default,
2670 Message: 'static + Clone,
2671{
2672 fn from(mut widget: SegmentedButton<'a, Variant, SelectionMode, Message>) -> Self {
2673 if widget.model.items.is_empty() {
2674 widget.spacing = 0;
2675 }
2676
2677 Self::new(widget)
2678 }
2679}
2680
2681struct TabDragSource<Message> {
2682 mime: String,
2683 threshold: f32,
2684 _marker: PhantomData<Message>,
2685}
2686
2687impl<Message> TabDragSource<Message> {
2688 fn new(mime: String) -> Self {
2689 Self {
2690 mime,
2691 threshold: 8.0,
2692 _marker: PhantomData,
2693 }
2694 }
2695}
2696
2697struct SimpleDragData {
2698 mime: String,
2699 bytes: Vec<u8>,
2700}
2701
2702impl SimpleDragData {
2703 fn new(mime: String, bytes: Vec<u8>) -> Self {
2704 Self { mime, bytes }
2705 }
2706}
2707
2708impl iced::clipboard::mime::AsMimeTypes for SimpleDragData {
2709 fn available(&self) -> Cow<'static, [String]> {
2710 Cow::Owned(vec![self.mime.clone()])
2711 }
2712
2713 fn as_bytes(&self, mime_type: &str) -> Option<Cow<'static, [u8]>> {
2714 if mime_type == self.mime {
2715 Some(Cow::Owned(self.bytes.clone()))
2716 } else {
2717 None
2718 }
2719 }
2720}
2721
2722#[derive(Clone, Copy)]
2723struct TabDragCandidate {
2724 entity: Entity,
2725 bounds: Rectangle,
2726 origin: Point,
2727}
2728
2729#[derive(Debug, Clone, Copy)]
2730struct Focus {
2731 updated_at: Instant,
2732 now: Instant,
2733}
2734
2735pub struct LocalState {
2737 pub(crate) menu_state: MenuBarState,
2739 pub(super) buttons_visible: usize,
2741 pub(super) buttons_offset: usize,
2743 pub(super) collapsed: bool,
2745 focused_visible: bool,
2747 focused: Option<Focus>,
2749 focused_item: Item,
2751 hovered: Item,
2753 middle_clicked: Option<Item>,
2755 pub(super) known_length: usize,
2757 pub(super) internal_layout: Vec<(Size, Size)>,
2759 paragraphs: SecondaryMap<Entity, crate::Plain>,
2761 text_hashes: SecondaryMap<Entity, u64>,
2763 context_cursor: Point,
2765 show_context: Option<Entity>,
2767 wheel_timestamp: Option<Instant>,
2769 pub dnd_state: crate::widget::dnd_destination::State<Option<Entity>>,
2771 pub offer_mimes: Vec<String>,
2773 fingers_pressed: HashSet<Finger>,
2775 pressed_item: Option<Item>,
2777 tab_drag_candidate: Option<TabDragCandidate>,
2779 dragging_tab: Option<Entity>,
2781 drop_hint: Option<DropHint>,
2783}
2784
2785#[derive(Clone, Copy, Debug, Default, PartialEq)]
2786enum Item {
2787 NextButton,
2788 #[default]
2789 None,
2790 PrevButton,
2791 Set,
2792 Tab(Entity),
2793}
2794
2795impl LocalState {
2796 fn set_focused(&mut self) {
2797 let now = Instant::now();
2798 LAST_FOCUS_UPDATE.with(|x| x.set(now));
2799
2800 self.focused = Some(Focus {
2801 updated_at: now,
2802 now,
2803 });
2804 }
2805}
2806
2807#[cfg(test)]
2808mod tests {
2809 use super::*;
2810 use crate::widget::segmented_button::{self, Appearance as SegAppearance};
2811 use iced::Size;
2812 use slotmap::SecondaryMap;
2813 use std::collections::HashSet;
2814
2815 #[derive(Clone, Debug)]
2816 enum TestMessage {}
2817
2818 struct TestVariant;
2819
2820 impl<SelectionMode, Message> SegmentedVariant
2821 for SegmentedButton<'_, TestVariant, SelectionMode, Message>
2822 where
2823 Model<SelectionMode>: Selectable,
2824 SelectionMode: Default,
2825 Message: Clone,
2826 {
2827 const VERTICAL: bool = false;
2828
2829 fn variant_appearance(
2830 _theme: &crate::Theme,
2831 _style: &crate::theme::SegmentedButton,
2832 ) -> SegAppearance {
2833 SegAppearance::default()
2834 }
2835
2836 fn variant_bounds<'b>(
2837 &'b self,
2838 _state: &'b LocalState,
2839 bounds: Rectangle,
2840 ) -> Box<dyn Iterator<Item = ItemBounds> + 'b> {
2841 let len = self.model.order.len();
2842 if len == 0 {
2843 return Box::new(std::iter::empty());
2844 }
2845 let width = bounds.width / len as f32;
2846 Box::new(
2847 self.model
2848 .order
2849 .iter()
2850 .copied()
2851 .enumerate()
2852 .map(move |(idx, entity)| {
2853 let rect = Rectangle {
2854 x: bounds.x + (idx as f32) * width,
2855 y: bounds.y,
2856 width,
2857 height: bounds.height,
2858 };
2859 ItemBounds::Button(entity, rect)
2860 }),
2861 )
2862 }
2863
2864 fn variant_layout(
2865 &self,
2866 _state: &mut LocalState,
2867 _renderer: &crate::Renderer,
2868 _limits: &layout::Limits,
2869 ) -> Size {
2870 Size::ZERO
2871 }
2872 }
2873
2874 fn sample_model() -> (
2875 segmented_button::SingleSelectModel,
2876 Vec<segmented_button::Entity>,
2877 ) {
2878 let mut entities = Vec::new();
2879 let model = segmented_button::Model::builder()
2880 .insert(|b| b.text("One").with_id(|id| entities.push(id)))
2881 .insert(|b| b.text("Two").with_id(|id| entities.push(id)))
2882 .insert(|b| b.text("Three").with_id(|id| entities.push(id)))
2883 .build();
2884 (model, entities)
2885 }
2886
2887 fn test_state(dragging: segmented_button::Entity, len: usize) -> LocalState {
2888 let mut state = LocalState {
2889 menu_state: MenuBarState::default(),
2890 paragraphs: SecondaryMap::new(),
2891 text_hashes: SecondaryMap::new(),
2892 buttons_visible: 0,
2893 buttons_offset: 0,
2894 collapsed: false,
2895 focused: None,
2896 focused_item: Item::default(),
2897 focused_visible: false,
2898 hovered: Item::default(),
2899 known_length: 0,
2900 middle_clicked: None,
2901 internal_layout: Vec::new(),
2902 context_cursor: Point::ORIGIN,
2903 show_context: None,
2904 wheel_timestamp: None,
2905 dnd_state: crate::widget::dnd_destination::State::<Option<Entity>>::new(),
2906 fingers_pressed: HashSet::new(),
2907 pressed_item: None,
2908 tab_drag_candidate: None,
2909 dragging_tab: Some(dragging),
2910 drop_hint: None,
2911 offer_mimes: Vec::new(),
2912 };
2913 state.buttons_visible = len;
2914 state.known_length = len;
2915 state
2916 }
2917
2918 #[test]
2919 fn drop_hint_reports_before_and_after() {
2920 let (model, ids) = sample_model();
2921 let button =
2922 SegmentedButton::<TestVariant, segmented_button::SingleSelect, TestMessage>::new(
2923 &model,
2924 );
2925 let state = test_state(ids[0], model.order.len());
2926 let bounds = Rectangle {
2927 x: 0.0,
2928 y: 0.0,
2929 width: 300.0,
2930 height: 30.0,
2931 };
2932 let before = button
2933 .drop_hint_for_position(&state, bounds, Point::new(10.0, 15.0))
2934 .expect("hint");
2935 assert_eq!(before.entity, ids[0]);
2936 assert!(matches!(before.side, DropSide::Before));
2937
2938 let after = button
2939 .drop_hint_for_position(&state, bounds, Point::new(290.0, 15.0))
2940 .expect("hint");
2941 assert_eq!(after.entity, ids[2]);
2942 assert!(matches!(after.side, DropSide::After));
2943 }
2944}
2945
2946impl operation::Focusable for LocalState {
2947 fn is_focused(&self) -> bool {
2948 self.focused
2949 .is_some_and(|f| f.updated_at == LAST_FOCUS_UPDATE.with(|f| f.get()))
2950 }
2951
2952 fn focus(&mut self) {
2953 self.set_focused();
2954 self.focused_visible = true;
2955 self.focused_item = Item::Set;
2956 }
2957
2958 fn unfocus(&mut self) {
2959 self.focused = None;
2960 self.focused_item = Item::None;
2961 self.focused_visible = false;
2962 self.show_context = None;
2963 }
2964}
2965
2966#[derive(Debug, Clone, PartialEq)]
2968pub struct Id(widget::Id);
2969
2970impl Id {
2971 pub fn new(id: impl Into<std::borrow::Cow<'static, str>>) -> Self {
2973 Self(widget::Id::new(id))
2974 }
2975
2976 #[must_use]
2980 #[inline]
2981 pub fn unique() -> Self {
2982 Self(widget::Id::unique())
2983 }
2984}
2985
2986impl From<Id> for widget::Id {
2987 fn from(id: Id) -> Self {
2988 id.0
2989 }
2990}
2991
2992fn close_bounds(area: Rectangle<f32>, icon_size: f32) -> Rectangle<f32> {
2994 Rectangle {
2995 x: area.x + area.width - icon_size - 8.0,
2996 y: area.center_y() - (icon_size / 2.0),
2997 width: icon_size,
2998 height: icon_size,
2999 }
3000}
3001
3002fn next_tab_bounds(bounds: &Rectangle, button_height: f32) -> Rectangle {
3004 Rectangle {
3005 x: bounds.x + bounds.width - button_height,
3006 y: bounds.y,
3007 width: button_height,
3008 height: button_height,
3009 }
3010}
3011
3012fn prev_tab_bounds(bounds: &Rectangle, button_height: f32) -> Rectangle {
3014 Rectangle {
3015 x: bounds.x,
3016 y: bounds.y,
3017 width: button_height,
3018 height: button_height,
3019 }
3020}
3021
3022#[allow(clippy::too_many_arguments)]
3023fn draw_icon<Message: 'static>(
3024 renderer: &mut Renderer,
3025 theme: &crate::Theme,
3026 style: &renderer::Style,
3027 cursor: mouse::Cursor,
3028 viewport: &Rectangle,
3029 color: Color,
3030 bounds: Rectangle,
3031 icon: Icon,
3032) {
3033 let layout_node = layout::Node::new(Size {
3034 width: bounds.width,
3035 height: bounds.width,
3036 })
3037 .move_to(Point {
3038 x: bounds.x,
3039 y: bounds.y,
3040 });
3041
3042 Widget::<Message, crate::Theme, Renderer>::draw(
3043 Element::<Message>::from(icon).as_widget(),
3044 &Tree::empty(),
3045 renderer,
3046 theme,
3047 &renderer::Style {
3048 icon_color: color,
3049 text_color: color,
3050 scale_factor: style.scale_factor,
3051 },
3052 Layout::new(&layout_node),
3053 cursor,
3054 viewport,
3055 );
3056}
3057
3058fn draw_drop_indicator(
3059 renderer: &mut Renderer,
3060 bounds: Rectangle,
3061 side: DropSide,
3062 vertical: bool,
3063 color: Color,
3064) {
3065 let thickness = 4.0;
3066 let quad_bounds = if vertical {
3067 let y = match side {
3068 DropSide::Before => bounds.y - thickness / 2.0,
3069 DropSide::After => bounds.y + bounds.height - thickness / 2.0,
3070 };
3071
3072 Rectangle {
3073 x: bounds.x,
3074 y,
3075 width: bounds.width,
3076 height: thickness,
3077 }
3078 } else {
3079 let x = match side {
3080 DropSide::Before => bounds.x - thickness / 2.0,
3081 DropSide::After => bounds.x + bounds.width - thickness / 2.0,
3082 };
3083
3084 Rectangle {
3085 x,
3086 y: bounds.y,
3087 width: thickness,
3088 height: bounds.height,
3089 }
3090 };
3091
3092 renderer.fill_quad(
3093 renderer::Quad {
3094 bounds: quad_bounds,
3095 border: Border {
3096 radius: 2.0.into(),
3097 ..Default::default()
3098 },
3099 shadow: Shadow::default(),
3100 snap: true,
3101 },
3102 Background::Color(color),
3103 );
3104}
3105
3106fn left_button_released(event: &Event) -> bool {
3107 matches!(
3108 event,
3109 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left,))
3110 )
3111}
3112
3113fn right_button_released(event: &Event) -> bool {
3114 matches!(
3115 event,
3116 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right,))
3117 )
3118}
3119
3120fn is_pressed(event: &Event) -> bool {
3121 matches!(
3122 event,
3123 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
3124 | Event::Touch(touch::Event::FingerPressed { .. })
3125 )
3126}
3127
3128fn is_lifted(event: &Event) -> bool {
3129 matches!(
3130 event,
3131 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left,))
3132 | Event::Touch(touch::Event::FingerLifted { .. })
3133 )
3134}
3135
3136fn touch_lifted(event: &Event) -> bool {
3137 matches!(event, Event::Touch(touch::Event::FingerLifted { .. }))
3138}