iced_aw 0.14.0

Additional widgets for the Iced GUI library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
//! Displays a [`TabBar`] to select the content to be displayed.
//!
//! You have to manage the logic to show the contend by yourself or you may want
//! to use the [`Tabs`](super::tabs::Tabs) widget instead.
//!
//! *This API requires the following crate features to be activated: `tab_bar`*

pub mod tab_label;

use iced_core::{
    Alignment, Background, Border, Clipboard, Color, Element, Event, Font, Layout, Length, Padding,
    Pixels, Point, Rectangle, Shadow, Shell, Size, Widget,
    alignment::{self, Vertical},
    layout::{Limits, Node},
    mouse::{self, Cursor},
    renderer, touch,
    widget::{Operation, Tree},
    window,
};
use iced_widget::{
    Column, Row, Text,
    text::{self, LineHeight, Wrapping},
};

use std::marker::PhantomData;

pub use crate::style::{
    Status, StyleFn,
    tab_bar::{self, Catalog, Style},
};
use crate::{ICED_AW_FONT, iced_aw_font::advanced_text::cancel};
pub use tab_label::TabLabel;

/// The default icon size.
const DEFAULT_ICON_SIZE: f32 = 16.0;
/// The default text size.
const DEFAULT_TEXT_SIZE: f32 = 16.0;
/// The default size of the close icon.
const DEFAULT_CLOSE_SIZE: f32 = 16.0;
/// The default padding between the tabs.
const DEFAULT_PADDING: Padding = Padding::new(5.0);
/// The default spacing around the tabs.
const DEFAULT_SPACING: Pixels = Pixels::ZERO;

/// A tab bar to show tabs.
///
/// # Example
/// ```ignore
/// # use iced_aw::{TabLabel, TabBar};
/// #
/// #[derive(Debug, Clone)]
/// enum Message {
///     TabSelected(TabId),
/// }
///
/// #[derive(PartialEq, Hash)]
/// enum TabId {
///    One,
///    Two,
///    Three,
/// }
///
/// let tab_bar = TabBar::new(
///     Message::TabSelected,
/// )
/// .push(TabId::One, TabLabel::Text(String::from("One")))
/// .push(TabId::Two, TabLabel::Text(String::from("Two")))
/// .push(TabId::Three, TabLabel::Text(String::from("Three")))
/// .set_active_tab(&TabId::One);
/// ```
#[allow(missing_debug_implementations)]
pub struct TabBar<'a, Message, TabId, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
where
    Renderer: renderer::Renderer + iced_core::text::Renderer,
    Theme: Catalog,
    TabId: Eq + Clone,
{
    /// The index of the currently active tab.
    active_tab: usize,
    /// The vector containing the labels of the tabs.
    tab_labels: Vec<TabLabel>,
    /// The vector containing the indices of the tabs.
    tab_indices: Vec<TabId>,
    /// The statuses of the [`TabLabel`] and cross
    tab_statuses: Vec<(Option<Status>, Option<bool>)>,
    /// The function that produces the message when a tab is selected.
    on_select: Box<dyn Fn(TabId) -> Message>,
    /// The function that produces the message when the close icon was pressed.
    on_close: Option<Box<dyn Fn(TabId) -> Message>>,
    /// The width of the [`TabBar`].
    width: Length,
    /// The width of the tabs of the [`TabBar`].
    tab_width: Length,
    /// The width of the [`TabBar`].
    height: Length,
    /// The maximum height of the [`TabBar`].
    max_height: f32,
    /// The icon size.
    icon_size: f32,
    /// The text size.
    text_size: f32,
    /// The size of the close icon.
    close_size: f32,
    /// The padding of the tabs of the [`TabBar`].
    padding: Padding,
    /// The spacing of the tabs of the [`TabBar`].
    spacing: Pixels,
    /// The optional icon font of the [`TabBar`].
    font: Option<Font>,
    /// The optional text font of the [`TabBar`].
    text_font: Option<Font>,
    /// The style of the [`TabBar`].
    class: <Theme as Catalog>::Class<'a>,
    /// Where the icon is placed relative to text
    position: Position,
    #[allow(clippy::missing_docs_in_private_items)]
    _renderer: PhantomData<Renderer>,
}

#[derive(Clone, Copy, Default)]
/// The [`Position`] of the icon relative to text, this enum is only relative if [`TabLabel::IconText`] is used.
pub enum Position {
    /// Icon is placed above of the text.
    Top,
    /// Icon is placed right of the text.
    Right,
    /// Icon is placed below of the text.
    Bottom,
    #[default]
    /// Icon is placed left of the text, the default.
    Left,
}

impl<'a, Message, TabId, Theme, Renderer> TabBar<'a, Message, TabId, Theme, Renderer>
where
    Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
    Theme: Catalog,
    TabId: Eq + Clone,
{
    /// Creates a new [`TabBar`] with the index of the selected tab and a specified
    /// message which will be send when a tab is selected by the user.
    ///
    /// It expects:
    ///     * the index of the currently active tab.
    ///     * the function that will be called if a tab is selected by the user.
    ///         It takes the index of the selected tab.
    pub fn new<F>(on_select: F) -> Self
    where
        F: 'static + Fn(TabId) -> Message,
    {
        Self::with_tab_labels(Vec::new(), on_select)
    }

    /// Similar to [`new`](Self::new) but with a given Vector of the [`TabLabel`]s.
    ///
    /// It expects:
    ///     * the index of the currently active tab.
    ///     * a vector containing the [`TabLabel`]s of the [`TabBar`].
    ///     * the function that will be called if a tab is selected by the user.
    ///         It takes the index of the selected tab.
    pub fn with_tab_labels<F>(tab_labels: Vec<(TabId, TabLabel)>, on_select: F) -> Self
    where
        F: 'static + Fn(TabId) -> Message,
    {
        Self {
            active_tab: 0,
            tab_indices: tab_labels.iter().map(|(id, _)| id.clone()).collect(),
            tab_statuses: tab_labels.iter().map(|_| (None, None)).collect(),
            tab_labels: tab_labels.into_iter().map(|(_, label)| label).collect(),
            on_select: Box::new(on_select),
            on_close: None,
            width: Length::Fill,
            tab_width: Length::Fill,
            height: Length::Shrink,
            max_height: u32::MAX as f32,
            icon_size: DEFAULT_ICON_SIZE,
            text_size: DEFAULT_TEXT_SIZE,
            close_size: DEFAULT_CLOSE_SIZE,
            padding: DEFAULT_PADDING,
            spacing: DEFAULT_SPACING,
            font: None,
            text_font: None,
            class: <Theme as Catalog>::default(),
            position: Position::default(),
            _renderer: PhantomData,
        }
    }

    /// Sets the size of the close icon of the
    /// [`TabLabel`]s of the [`TabBar`].
    #[must_use]
    pub fn close_size(mut self, close_size: f32) -> Self {
        self.close_size = close_size;
        self
    }

    /// Gets the id of the currently active tab on the [`TabBar`].
    #[must_use]
    pub fn get_active_tab_id(&self) -> Option<&TabId> {
        self.tab_indices.get(self.active_tab)
    }

    /// Gets the index of the currently active tab on the [`TabBar`].
    #[must_use]
    pub fn get_active_tab_idx(&self) -> usize {
        self.active_tab
    }

    /// Gets the width of the [`TabBar`].
    #[must_use]
    pub fn get_height(&self) -> Length {
        self.height
    }

    /// Gets the width of the [`TabBar`].
    #[must_use]
    pub fn get_width(&self) -> Length {
        self.width
    }

    /// Sets the height of the [`TabBar`].
    #[must_use]
    pub fn height(mut self, height: impl Into<Length>) -> Self {
        self.height = height.into();
        self
    }

    /// Sets the font of the icons of the
    /// [`TabLabel`]s of the [`TabBar`].
    #[must_use]
    pub fn icon_font(mut self, font: Font) -> Self {
        self.font = Some(font);
        self
    }

    /// Sets the icon size of the [`TabLabel`]s of the [`TabBar`].
    #[must_use]
    pub fn icon_size(mut self, icon_size: f32) -> Self {
        self.icon_size = icon_size;
        self
    }

    /// Sets the maximum height of the [`TabBar`].
    #[must_use]
    pub fn max_height(mut self, max_height: f32) -> Self {
        self.max_height = max_height;
        self
    }

    /// Sets the message that will be produced when the close icon of a tab
    /// on the [`TabBar`] is pressed.
    ///
    /// Setting this enables the drawing of a close icon on the tabs.
    #[must_use]
    pub fn on_close<F>(mut self, on_close: F) -> Self
    where
        F: 'static + Fn(TabId) -> Message,
    {
        self.on_close = Some(Box::new(on_close));
        self
    }

    /// Sets the padding of the tabs of the [`TabBar`].
    #[must_use]
    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
        self.padding = padding.into();
        self
    }

    /// Pushes a [`TabLabel`] to the [`TabBar`].
    #[must_use]
    pub fn push(mut self, id: TabId, tab_label: TabLabel) -> Self {
        self.tab_labels.push(tab_label);
        self.tab_indices.push(id);
        self.tab_statuses.push((None, None));
        self
    }

    /// Gets the amount of tabs on the [`TabBar`].
    #[must_use]
    pub fn size(&self) -> usize {
        self.tab_indices.len()
    }

    /// Sets the spacing between the tabs of the [`TabBar`].
    #[must_use]
    pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
        self.spacing = spacing.into();
        self
    }

    /// Sets the font of the text of the
    /// [`TabLabel`]s of the [`TabBar`].
    #[must_use]
    pub fn text_font(mut self, text_font: Font) -> Self {
        self.text_font = Some(text_font);
        self
    }

    /// Sets the text size of the [`TabLabel`]s of the [`TabBar`].
    #[must_use]
    pub fn text_size(mut self, text_size: f32) -> Self {
        self.text_size = text_size;
        self
    }

    /// Sets the width of a tab on the [`TabBar`].
    #[must_use]
    pub fn tab_width(mut self, width: Length) -> Self {
        self.tab_width = width;
        self
    }

    /// Sets up the active tab on the [`TabBar`].
    #[must_use]
    pub fn set_active_tab(mut self, active_tab: &TabId) -> Self {
        self.active_tab = self
            .tab_indices
            .iter()
            .position(|id| id == active_tab)
            .map_or(0, |a| a);
        self
    }

    #[must_use]
    /// Sets the [`Position`] of the Icon next to Text, Only used in [`TabLabel::IconText`]
    pub fn set_position(mut self, position: Position) -> Self {
        self.position = position;
        self
    }

    /// Sets the style of the [`TabBar`].
    #[must_use]
    pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
    where
        <Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
    {
        self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
        self
    }

    /// Sets the class of the input of the [`TabBar`].
    #[must_use]
    pub fn class(mut self, class: impl Into<<Theme as Catalog>::Class<'a>>) -> Self {
        self.class = class.into();
        self
    }

    /// Sets the width of the [`TabBar`].
    #[must_use]
    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }
}

impl<Message, TabId, Theme, Renderer> Widget<Message, Theme, Renderer>
    for TabBar<'_, Message, TabId, Theme, Renderer>
where
    Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
    Theme: Catalog + text::Catalog,
    TabId: Eq + Clone,
{
    fn size(&self) -> Size<Length> {
        Size::new(self.width, self.height)
    }

    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
        fn layout_icon<Theme, Renderer>(
            icon: &char,
            size: f32,
            font: Option<Font>,
        ) -> Text<'_, Theme, Renderer>
        where
            Renderer: iced_core::text::Renderer,
            Renderer::Font: From<Font>,
            Theme: iced_widget::text::Catalog,
        {
            Text::<Theme, Renderer>::new(icon.to_string())
                .size(size)
                .font(font.unwrap_or_default())
                .align_x(alignment::Horizontal::Center)
                .align_y(alignment::Vertical::Center)
                .shaping(iced_core::text::Shaping::Advanced)
                .width(Length::Shrink)
        }

        fn layout_text<Theme, Renderer>(
            text: &str,
            size: f32,
            font: Option<Font>,
        ) -> Text<'_, Theme, Renderer>
        where
            Renderer: iced_core::text::Renderer,
            Renderer::Font: From<Font>,
            Theme: iced_widget::text::Catalog,
        {
            Text::<Theme, Renderer>::new(text)
                .size(size)
                .font(font.unwrap_or_default())
                .align_x(alignment::Horizontal::Center)
                .shaping(text::Shaping::Advanced)
                .width(Length::Shrink)
        }

        let row = self
            .tab_labels
            .iter()
            .fold(Row::<Message, Theme, Renderer>::new(), |row, tab_label| {
                let mut label_row = Row::new()
                    .push(
                        match tab_label {
                            TabLabel::Icon(icon) => Column::new()
                                .align_x(Alignment::Center)
                                .push(layout_icon(icon, self.icon_size + 1.0, self.font)),

                            TabLabel::Text(text) => Column::new()
                                .padding(5.0)
                                .align_x(Alignment::Center)
                                .push(layout_text(text, self.text_size + 1.0, self.text_font)),

                            TabLabel::IconText(icon, text) => {
                                let mut column = Column::new().align_x(Alignment::Center);

                                match self.position {
                                    Position::Top => {
                                        column = column
                                            .push(layout_icon(
                                                icon,
                                                self.icon_size + 1.0,
                                                self.font,
                                            ))
                                            .push(layout_text(
                                                text,
                                                self.text_size + 1.0,
                                                self.text_font,
                                            ));
                                    }
                                    Position::Right => {
                                        column = column.push(
                                            Row::new()
                                                .align_y(Alignment::Center)
                                                .push(layout_text(
                                                    text,
                                                    self.text_size + 1.0,
                                                    self.text_font,
                                                ))
                                                .push(layout_icon(
                                                    icon,
                                                    self.icon_size + 1.0,
                                                    self.font,
                                                )),
                                        );
                                    }
                                    Position::Left => {
                                        column = column.push(
                                            Row::new()
                                                .align_y(Alignment::Center)
                                                .push(layout_icon(
                                                    icon,
                                                    self.icon_size + 1.0,
                                                    self.font,
                                                ))
                                                .push(layout_text(
                                                    text,
                                                    self.text_size + 1.0,
                                                    self.text_font,
                                                )),
                                        );
                                    }
                                    Position::Bottom => {
                                        column = column
                                            .height(Length::Fill)
                                            .push(layout_text(
                                                text,
                                                self.text_size + 1.0,
                                                self.text_font,
                                            ))
                                            .push(layout_icon(
                                                icon,
                                                self.icon_size + 1.0,
                                                self.font,
                                            ));
                                    }
                                }

                                column
                            }
                        }
                        .width(self.tab_width)
                        .height(self.height),
                    )
                    .align_y(Alignment::Center)
                    .padding(self.padding)
                    .width(self.tab_width);

                if self.on_close.is_some() {
                    label_row = label_row.push(
                        Row::new()
                            .width(Length::Fixed(self.close_size * 1.3 + 1.0))
                            .height(Length::Fixed(self.close_size * 1.3 + 1.0))
                            .align_y(Alignment::Center),
                    );
                }

                row.push(label_row)
            })
            .width(self.width)
            .height(self.height)
            .spacing(self.spacing)
            .align_y(Alignment::Center);

        let mut element: Element<Message, Theme, Renderer> = Element::new(row);
        let tab_tree = if let Some(child_tree) = tree.children.get_mut(0) {
            child_tree.diff(element.as_widget_mut());
            child_tree
        } else {
            let child_tree = Tree::new(element.as_widget());
            tree.children.insert(0, child_tree);
            &mut tree.children[0]
        };

        element
            .as_widget_mut()
            .layout(tab_tree, renderer, &limits.loose())
    }

    fn update(
        &mut self,
        _state: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: Cursor,
        _renderer: &Renderer,
        _clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        _viewport: &Rectangle,
    ) {
        match event {
            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerPressed { .. })
                if cursor
                    .position()
                    .is_some_and(|pos| layout.bounds().contains(pos)) =>
            {
                let tabs_map: Vec<bool> = layout
                    .children()
                    .map(|layout| {
                        cursor
                            .position()
                            .is_some_and(|pos| layout.bounds().contains(pos))
                    })
                    .collect();

                if let Some(new_selected) = tabs_map.iter().position(|b| *b) {
                    shell.publish(
                        self.on_close
                            .as_ref()
                            .filter(|_on_close| {
                                let tab_layout = layout.children().nth(new_selected).expect(
                                    "widget: Layout should have a tab layout at the selected index",
                                );
                                let cross_layout = tab_layout
                                    .children()
                                    .nth(1)
                                    .expect("widget: Layout should have a close layout");

                                cursor
                                    .position()
                                    .is_some_and(|pos| cross_layout.bounds().contains(pos))
                            })
                            .map_or_else(
                                || (self.on_select)(self.tab_indices[new_selected].clone()),
                                |on_close| (on_close)(self.tab_indices[new_selected].clone()),
                            ),
                    );
                    shell.capture_event();
                }
            }
            _ => {}
        }

        let mut request_redraw = false;
        let children = layout.children();
        for ((i, _tab), layout) in self.tab_labels.iter().enumerate().zip(children) {
            let active_idx = self.get_active_tab_idx();
            let tab_status = self.tab_statuses.get_mut(i).expect("Should have a status.");

            let current_status = if cursor.is_over(layout.bounds()) {
                Status::Hovered
            } else if i == active_idx {
                Status::Active
            } else {
                Status::Disabled
            };

            let mut is_cross_hovered = None;
            let mut children = layout.children();
            if let Some(cross_layout) = children.next_back() {
                is_cross_hovered = Some(cursor.is_over(cross_layout.bounds()));
            }

            if let Event::Window(window::Event::RedrawRequested(_now)) = event {
                *tab_status = (Some(current_status), is_cross_hovered);
            } else if tab_status.0.is_some_and(|status| status != current_status)
                || tab_status.1 != is_cross_hovered
            {
                request_redraw = true;
            }
        }

        if request_redraw {
            shell.request_redraw();
        }
    }

    fn mouse_interaction(
        &self,
        _state: &Tree,
        layout: Layout<'_>,
        cursor: Cursor,
        _viewport: &Rectangle,
        _renderer: &Renderer,
    ) -> mouse::Interaction {
        let children = layout.children();
        let mut mouse_interaction = mouse::Interaction::default();

        for layout in children {
            let is_mouse_over = cursor
                .position()
                .is_some_and(|pos| layout.bounds().contains(pos));
            let new_mouse_interaction = if is_mouse_over {
                mouse::Interaction::Pointer
            } else {
                mouse::Interaction::default()
            };

            if new_mouse_interaction > mouse_interaction {
                mouse_interaction = new_mouse_interaction;
            }
        }

        mouse_interaction
    }

    fn draw(
        &self,
        _state: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        _style: &renderer::Style,
        layout: Layout<'_>,
        cursor: Cursor,
        viewport: &Rectangle,
    ) {
        let bounds = layout.bounds();
        let children = layout.children();
        let is_mouse_over = cursor.position().is_some_and(|pos| bounds.contains(pos));
        let style_sheet = if is_mouse_over {
            tab_bar::Catalog::style(theme, &self.class, Status::Hovered)
        } else {
            tab_bar::Catalog::style(theme, &self.class, Status::Disabled)
        };

        if bounds.intersects(viewport) {
            renderer.fill_quad(
                renderer::Quad {
                    bounds,
                    border: Border {
                        radius: (0.0).into(),
                        width: style_sheet.border_width,
                        color: style_sheet.border_color.unwrap_or(Color::TRANSPARENT),
                    },
                    shadow: Shadow::default(),
                    ..renderer::Quad::default()
                },
                style_sheet
                    .background
                    .unwrap_or_else(|| Color::TRANSPARENT.into()),
            );
        }

        for ((i, tab), layout) in self.tab_labels.iter().enumerate().zip(children) {
            let tab_status = self.tab_statuses.get(i).expect("Should have a status.");

            draw_tab(
                renderer,
                tab,
                tab_status,
                layout,
                self.position,
                theme,
                &self.class,
                cursor,
                (self.font.unwrap_or(ICED_AW_FONT), self.icon_size),
                (self.text_font.unwrap_or_default(), self.text_size),
                self.close_size,
                viewport,
            );
        }
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation<()>,
    ) {
        operation.container(None, layout.bounds());

        // Reconstruct the internal structure for operation traversal
        // This allows the simulator to find text in tab labels
        let row =
            self.tab_labels
                .iter()
                .fold(Row::<(), Theme, Renderer>::new(), |row, tab_label| {
                    let label_content: Element<'_, (), Theme, Renderer> = match tab_label {
                        TabLabel::Icon(icon) => Text::<Theme, Renderer>::new(icon.to_string())
                            .size(self.icon_size)
                            .font(self.font.unwrap_or_default())
                            .into(),
                        TabLabel::Text(text) => Text::<Theme, Renderer>::new(text.clone())
                            .size(self.text_size)
                            .font(self.text_font.unwrap_or_default())
                            .into(),
                        TabLabel::IconText(icon, text) => {
                            let mut column = Column::<(), Theme, Renderer>::new();
                            match self.position {
                                Position::Top => {
                                    column = column
                                        .push(
                                            Text::<Theme, Renderer>::new(icon.to_string())
                                                .size(self.icon_size)
                                                .font(self.font.unwrap_or_default()),
                                        )
                                        .push(
                                            Text::<Theme, Renderer>::new(text.clone())
                                                .size(self.text_size)
                                                .font(self.text_font.unwrap_or_default()),
                                        );
                                }
                                Position::Right => {
                                    let inner_row = Row::<(), Theme, Renderer>::new()
                                        .push(
                                            Text::<Theme, Renderer>::new(text.clone())
                                                .size(self.text_size)
                                                .font(self.text_font.unwrap_or_default()),
                                        )
                                        .push(
                                            Text::<Theme, Renderer>::new(icon.to_string())
                                                .size(self.icon_size)
                                                .font(self.font.unwrap_or_default()),
                                        );
                                    column = column.push(inner_row);
                                }
                                Position::Left => {
                                    let inner_row = Row::<(), Theme, Renderer>::new()
                                        .push(
                                            Text::<Theme, Renderer>::new(icon.to_string())
                                                .size(self.icon_size)
                                                .font(self.font.unwrap_or_default()),
                                        )
                                        .push(
                                            Text::<Theme, Renderer>::new(text.clone())
                                                .size(self.text_size)
                                                .font(self.text_font.unwrap_or_default()),
                                        );
                                    column = column.push(inner_row);
                                }
                                Position::Bottom => {
                                    column = column
                                        .push(
                                            Text::<Theme, Renderer>::new(text.clone())
                                                .size(self.text_size)
                                                .font(self.text_font.unwrap_or_default()),
                                        )
                                        .push(
                                            Text::<Theme, Renderer>::new(icon.to_string())
                                                .size(self.icon_size)
                                                .font(self.font.unwrap_or_default()),
                                        );
                                }
                            }
                            column.into()
                        }
                    };

                    let mut label_row = Row::<(), Theme, Renderer>::new().push(label_content);

                    // Add close button if present
                    if self.on_close.is_some() {
                        let (content, _font, _shaping) = cancel();
                        label_row = label_row.push(
                            Text::<Theme, Renderer>::new(content)
                                .size(self.close_size)
                                .font(ICED_AW_FONT),
                        );
                    }

                    row.push(label_row)
                });

        let mut element: Element<(), Theme, Renderer> = Element::new(row);
        let tab_tree = if let Some(child_tree) = tree.children.get_mut(0) {
            child_tree.diff(element.as_widget_mut());
            child_tree
        } else {
            let child_tree = Tree::new(element.as_widget());
            tree.children.insert(0, child_tree);
            &mut tree.children[0]
        };

        element
            .as_widget_mut()
            .operate(tab_tree, layout, renderer, operation);
    }
}

/// Draws a tab.
#[allow(
    clippy::borrowed_box,
    clippy::too_many_lines,
    clippy::too_many_arguments
)]
fn draw_tab<Theme, Renderer>(
    renderer: &mut Renderer,
    tab: &TabLabel,
    tab_status: &(Option<Status>, Option<bool>),
    layout: Layout<'_>,
    position: Position,
    theme: &Theme,
    class: &<Theme as Catalog>::Class<'_>,
    _cursor: Cursor,
    icon_data: (Font, f32),
    text_data: (Font, f32),
    close_size: f32,
    viewport: &Rectangle,
) where
    Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
    Theme: Catalog + text::Catalog,
{
    fn icon_bound_rectangle(item: Option<Layout<'_>>) -> Rectangle {
        item.expect("Graphics: Layout should have an icons layout for an IconText")
            .bounds()
    }

    fn text_bound_rectangle(item: Option<Layout<'_>>) -> Rectangle {
        item.expect("Graphics: Layout should have an texts layout for an IconText")
            .bounds()
    }

    let bounds = layout.bounds();

    let style = tab_bar::Catalog::style(theme, class, tab_status.0.unwrap_or(Status::Disabled));

    let mut children = layout.children();
    let label_layout = children
        .next()
        .expect("Graphics: Layout should have a label layout");
    let mut label_layout_children = label_layout.children();

    if bounds.intersects(viewport) {
        renderer.fill_quad(
            renderer::Quad {
                bounds,
                border: Border {
                    radius: style.tab_border_radius,
                    width: style.tab_label_border_width,
                    color: style.tab_label_border_color,
                },
                shadow: Shadow::default(),
                ..renderer::Quad::default()
            },
            style.tab_label_background,
        );
    }

    match tab {
        TabLabel::Icon(icon) => {
            let icon_bounds = icon_bound_rectangle(label_layout_children.next());

            renderer.fill_text(
                iced_core::text::Text {
                    content: icon.to_string(),
                    bounds: Size::new(icon_bounds.width, icon_bounds.height),
                    size: Pixels(icon_data.1),
                    font: icon_data.0,
                    align_x: text::Alignment::Center,
                    align_y: Vertical::Center,
                    line_height: LineHeight::Relative(1.3),
                    shaping: iced_core::text::Shaping::Advanced,
                    wrapping: Wrapping::default(),
                },
                Point::new(icon_bounds.center_x(), icon_bounds.center_y()),
                style.icon_color,
                icon_bounds,
            );
        }

        TabLabel::Text(text) => {
            let text_bounds = text_bound_rectangle(label_layout_children.next());

            renderer.fill_text(
                iced_core::text::Text {
                    content: text.clone(),
                    bounds: Size::new(text_bounds.width, text_bounds.height),
                    size: Pixels(text_data.1),
                    font: text_data.0,
                    align_x: text::Alignment::Center,
                    align_y: Vertical::Center,
                    line_height: LineHeight::Relative(1.3),
                    shaping: iced_core::text::Shaping::Advanced,
                    wrapping: Wrapping::default(),
                },
                Point::new(text_bounds.center_x(), text_bounds.center_y()),
                style.text_color,
                text_bounds,
            );
        }
        TabLabel::IconText(icon, text) => {
            let icon_bounds: Rectangle;
            let text_bounds: Rectangle;

            match position {
                Position::Top => {
                    icon_bounds = icon_bound_rectangle(label_layout_children.next());
                    text_bounds = text_bound_rectangle(label_layout_children.next());
                }
                Position::Right => {
                    let mut row_childern = label_layout_children
                        .next()
                        .expect("Graphics: Right Layout should have have a row with one child")
                        .children();
                    text_bounds = text_bound_rectangle(row_childern.next());
                    icon_bounds = icon_bound_rectangle(row_childern.next());
                }
                Position::Left => {
                    let mut row_childern = label_layout_children
                        .next()
                        .expect("Graphics: Left Layout should have have a row with one child")
                        .children();
                    icon_bounds = icon_bound_rectangle(row_childern.next());
                    text_bounds = text_bound_rectangle(row_childern.next());
                }
                Position::Bottom => {
                    text_bounds = text_bound_rectangle(label_layout_children.next());
                    icon_bounds = icon_bound_rectangle(label_layout_children.next());
                }
            }

            renderer.fill_text(
                iced_core::text::Text {
                    content: icon.to_string(),
                    bounds: Size::new(icon_bounds.width, icon_bounds.height),
                    size: Pixels(icon_data.1),
                    font: icon_data.0,
                    align_x: text::Alignment::Center,
                    align_y: Vertical::Center,
                    line_height: LineHeight::Relative(1.3),
                    shaping: iced_core::text::Shaping::Advanced,
                    wrapping: Wrapping::default(),
                },
                Point::new(icon_bounds.center_x(), icon_bounds.center_y()),
                style.icon_color,
                icon_bounds,
            );

            renderer.fill_text(
                iced_core::text::Text {
                    content: text.clone(),
                    bounds: Size::new(text_bounds.width, text_bounds.height),
                    size: Pixels(text_data.1),
                    font: text_data.0,
                    align_x: text::Alignment::Center,
                    align_y: Vertical::Center,
                    line_height: LineHeight::Relative(1.3),
                    shaping: iced_core::text::Shaping::Advanced,
                    wrapping: Wrapping::default(),
                },
                Point::new(text_bounds.center_x(), text_bounds.center_y()),
                style.text_color,
                text_bounds,
            );
        }
    }

    if let Some(cross_layout) = children.next() {
        let cross_bounds = cross_layout.bounds();
        let is_mouse_over_cross = tab_status.1.unwrap_or(false);

        let (content, font, shaping) = cancel();

        renderer.fill_text(
            iced_core::text::Text {
                content,
                bounds: Size::new(cross_bounds.width, cross_bounds.height),
                size: Pixels(close_size + if is_mouse_over_cross { 1.0 } else { 0.0 }),
                font,
                align_x: text::Alignment::Center,
                align_y: Vertical::Center,
                line_height: LineHeight::Relative(1.3),
                shaping,
                wrapping: Wrapping::default(),
            },
            Point::new(cross_bounds.center_x(), cross_bounds.center_y()),
            style.text_color,
            cross_bounds,
        );

        if is_mouse_over_cross && cross_bounds.intersects(viewport) {
            renderer.fill_quad(
                renderer::Quad {
                    bounds: cross_bounds,
                    border: Border {
                        radius: style.icon_border_radius,
                        width: style.border_width,
                        color: style.border_color.unwrap_or(Color::TRANSPARENT),
                    },
                    shadow: Shadow::default(),
                    ..renderer::Quad::default()
                },
                style
                    .icon_background
                    .unwrap_or(Background::Color(Color::TRANSPARENT)),
            );
        }
    }
}

impl<'a, Message, TabId, Theme, Renderer> From<TabBar<'a, Message, TabId, Theme, Renderer>>
    for Element<'a, Message, Theme, Renderer>
where
    Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
    Theme: 'a + Catalog + text::Catalog,
    Message: 'a,
    TabId: 'a + Eq + Clone,
{
    fn from(tab_bar: TabBar<'a, Message, TabId, Theme, Renderer>) -> Self {
        Element::new(tab_bar)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    enum TestTabId {
        One,
        Two,
        Three,
    }

    #[derive(Clone)]
    #[allow(dead_code)]
    enum TestMessage {
        TabSelected(TestTabId),
        TabClosed(TestTabId),
    }

    type TestTabBar<'a> =
        TabBar<'a, TestMessage, TestTabId, iced_widget::Theme, iced_widget::Renderer>;

    #[test]
    fn tab_bar_new_has_default_values() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected);

        assert_eq!(tab_bar.active_tab, 0);
        assert_eq!(tab_bar.tab_labels.len(), 0);
        assert_eq!(tab_bar.tab_indices.len(), 0);
        assert_eq!(tab_bar.width, Length::Fill);
        assert_eq!(tab_bar.height, Length::Shrink);
        assert!((tab_bar.icon_size - DEFAULT_ICON_SIZE).abs() < f32::EPSILON);
        assert!((tab_bar.text_size - DEFAULT_TEXT_SIZE).abs() < f32::EPSILON);
        assert!((tab_bar.close_size - DEFAULT_CLOSE_SIZE).abs() < f32::EPSILON);
    }

    #[test]
    fn tab_bar_push_adds_tab() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected)
            .push(TestTabId::One, TabLabel::Text("Tab 1".to_owned()));

        assert_eq!(tab_bar.tab_labels.len(), 1);
        assert_eq!(tab_bar.tab_indices.len(), 1);
        assert_eq!(tab_bar.tab_indices[0], TestTabId::One);
    }

    #[test]
    fn tab_bar_push_multiple_tabs() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected)
            .push(TestTabId::One, TabLabel::Text("Tab 1".to_owned()))
            .push(TestTabId::Two, TabLabel::Text("Tab 2".to_owned()))
            .push(TestTabId::Three, TabLabel::Text("Tab 3".to_owned()));

        assert_eq!(tab_bar.tab_labels.len(), 3);
        assert_eq!(tab_bar.tab_indices.len(), 3);
    }

    #[test]
    fn tab_bar_set_active_tab_sets_correct_index() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected)
            .push(TestTabId::One, TabLabel::Text("Tab 1".to_owned()))
            .push(TestTabId::Two, TabLabel::Text("Tab 2".to_owned()))
            .push(TestTabId::Three, TabLabel::Text("Tab 3".to_owned()))
            .set_active_tab(&TestTabId::Two);

        assert_eq!(tab_bar.active_tab, 1);
        assert_eq!(tab_bar.get_active_tab_id(), Some(&TestTabId::Two));
    }

    #[test]
    fn tab_bar_get_active_tab_idx_returns_index() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected)
            .push(TestTabId::One, TabLabel::Text("Tab 1".to_owned()))
            .push(TestTabId::Two, TabLabel::Text("Tab 2".to_owned()))
            .set_active_tab(&TestTabId::Two);

        assert_eq!(tab_bar.get_active_tab_idx(), 1);
    }

    #[test]
    fn tab_bar_size_returns_number_of_tabs() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected)
            .push(TestTabId::One, TabLabel::Text("Tab 1".to_owned()))
            .push(TestTabId::Two, TabLabel::Text("Tab 2".to_owned()))
            .push(TestTabId::Three, TabLabel::Text("Tab 3".to_owned()));

        assert_eq!(tab_bar.size(), 3);
    }

    #[test]
    fn tab_bar_width_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).width(200);
        assert_eq!(tab_bar.width, Length::Fixed(200.0));
    }

    #[test]
    fn tab_bar_height_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).height(50);
        assert_eq!(tab_bar.height, Length::Fixed(50.0));
    }

    #[test]
    fn tab_bar_icon_size_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).icon_size(24.0);
        assert!((tab_bar.icon_size - 24.0).abs() < f32::EPSILON);
    }

    #[test]
    fn tab_bar_text_size_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).text_size(20.0);
        assert!((tab_bar.text_size - 20.0).abs() < f32::EPSILON);
    }

    #[test]
    fn tab_bar_close_size_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).close_size(18.0);
        assert!((tab_bar.close_size - 18.0).abs() < f32::EPSILON);
    }

    #[test]
    fn tab_bar_on_close_enables_close_button() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).on_close(TestMessage::TabClosed);

        assert!(tab_bar.on_close.is_some());
    }

    #[test]
    fn tab_bar_with_tab_labels_creates_tabs() {
        let labels = vec![
            (TestTabId::One, TabLabel::Text("Tab 1".to_owned())),
            (TestTabId::Two, TabLabel::Text("Tab 2".to_owned())),
        ];

        let tab_bar = TestTabBar::with_tab_labels(labels, TestMessage::TabSelected);

        assert_eq!(tab_bar.tab_labels.len(), 2);
        assert_eq!(tab_bar.tab_indices.len(), 2);
    }

    #[test]
    fn tab_bar_tab_width_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).tab_width(Length::Fixed(100.0));
        assert_eq!(tab_bar.tab_width, Length::Fixed(100.0));
    }

    #[test]
    fn tab_bar_max_height_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).max_height(200.0);
        assert!((tab_bar.max_height - 200.0).abs() < f32::EPSILON);
    }

    #[test]
    fn tab_bar_padding_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).padding(10.0);
        assert_eq!(tab_bar.padding, Padding::from(10.0));
    }

    #[test]
    fn tab_bar_spacing_sets_value() {
        let tab_bar = TestTabBar::new(TestMessage::TabSelected).spacing(5.0);
        assert_eq!(tab_bar.spacing, Pixels::from(5.0));
    }
}