re_ui/
icon_text.rs

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
use std::fmt::Debug;
use std::iter::once;
use std::{fmt, vec};

use egui::{Context, ModifierNames, Modifiers, WidgetText};

use crate::{icon_text, icons, Icon};

#[derive(Clone)]
pub enum IconTextItem {
    Icon(Icon),
    Text(WidgetText),
}

impl Debug for IconTextItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Icon(icon) => write!(f, "Icon({})", icon.id),
            Self::Text(text) => write!(f, "Text({})", text.text()),
        }
    }
}

impl IconTextItem {
    pub fn icon(icon: Icon) -> Self {
        Self::Icon(icon)
    }

    pub fn text(text: impl Into<WidgetText>) -> Self {
        Self::Text(text.into())
    }
}

/// Helper to show text with icons in a row.
/// Usually created via the [`crate::icon_text!`] macro.
#[derive(Default, Debug, Clone)]
pub struct IconText(pub Vec<IconTextItem>);

impl From<String> for IconText {
    fn from(value: String) -> Self {
        Self(vec![IconTextItem::Text(value.into())])
    }
}

impl From<&str> for IconText {
    fn from(value: &str) -> Self {
        Self(vec![IconTextItem::Text(value.into())])
    }
}

impl From<Icon> for IconText {
    fn from(icon: Icon) -> Self {
        Self(vec![IconTextItem::Icon(icon)])
    }
}

impl From<IconTextItem> for IconText {
    fn from(value: IconTextItem) -> Self {
        Self(vec![value])
    }
}

impl IconText {
    /// Create a new, empty `IconText`.
    pub fn new() -> Self {
        Self(Vec::new())
    }

    /// Add an icon to the row.
    pub fn icon(&mut self, icon: Icon) {
        self.0.push(IconTextItem::Icon(icon));
    }

    /// Add text to the row.
    pub fn text(&mut self, text: impl Into<WidgetText>) {
        self.0.push(IconTextItem::Text(text.into()));
    }

    /// Add an item to the row.
    pub fn add(&mut self, item: impl Into<Self>) {
        self.0.extend(item.into().0);
    }
}

/// Create an [`IconText`] with the given items.
#[macro_export]
macro_rules! icon_text {
    ($($item:expr),* $(,)?) => {{
        let mut icon_text = $crate::IconText::new();
        $(icon_text.add($item);)*
        icon_text
    }};
}

fn is_mac(ctx: &Context) -> bool {
    matches!(
        ctx.os(),
        egui::os::OperatingSystem::Mac | egui::os::OperatingSystem::IOS
    )
}

/// Shows a "+" if the OS is not Mac.
/// Useful if you want to e.g. show an icon after a [`modifiers_text`]
pub fn maybe_plus(ctx: &Context) -> IconText {
    if is_mac(ctx) {
        IconText::default()
    } else {
        icon_text!("+")
    }
}

/// Shows a keyboard shortcut with a modifier and the given icon.
///
/// On Mac, this will show the symbol for the modifier.
/// Otherwise, it will show the name of the modifier, and a "+" between the modifier and the icon.
pub fn shortcut_with_icon(
    ctx: &Context,
    modifiers: Modifiers,
    icon: impl Into<IconText>,
) -> IconText {
    icon_text!(modifiers_text(modifiers, ctx), maybe_plus(ctx), icon.into())
}

/// Helper to add [`egui::Modifiers`] as text with icons.
/// Will automatically show Cmd/Ctrl based on the OS.
pub fn modifiers_text(modifiers: Modifiers, ctx: &egui::Context) -> IconText {
    let is_mac = is_mac(ctx);

    let names = if is_mac {
        let mut names = ModifierNames::SYMBOLS;
        names.concat = "";
        names
    } else {
        let mut names = ModifierNames::NAMES;
        names.concat = "+";
        names
    };
    let text = names.format(&modifiers, is_mac);

    let mut icon_text = IconText::new();

    if is_mac {
        for char in text.chars() {
            if char == '⌘' {
                icon_text.add(IconTextItem::icon(icons::COMMAND));
            } else if char == '⌃' {
                icon_text.add(IconTextItem::icon(icons::CONTROL));
            } else if char == '⇧' {
                icon_text.add(IconTextItem::icon(icons::SHIFT));
            } else if char == '⌥' {
                icon_text.add(IconTextItem::icon(icons::OPTION));
            } else {
                // If there is anything else than the modifier symbols, just show the text.
                return text.into();
            }
        }
        icon_text
    } else {
        let mut vec: Vec<_> = text
            .split('+')
            .map(IconTextItem::text)
            // We want each + to be an extra item so the spacing looks nicer
            .flat_map(|item| once(item).chain(once(IconTextItem::text("+"))))
            .collect();
        vec.pop(); // Remove the last "+"
        IconText(vec)
    }
}

/// Helper to show mouse buttons as text/icons.
pub struct MouseButtonText(pub egui::PointerButton);

impl From<MouseButtonText> for IconText {
    fn from(value: MouseButtonText) -> Self {
        match value.0 {
            egui::PointerButton::Primary => icons::LEFT_MOUSE_CLICK.into(),
            egui::PointerButton::Secondary => icons::RIGHT_MOUSE_CLICK.into(),
            egui::PointerButton::Middle => "middle mouse button".into(),
            egui::PointerButton::Extra1 => "extra 1 mouse button".into(),
            egui::PointerButton::Extra2 => "extra 2 mouse button".into(),
        }
    }
}