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
//! Show popup windows, tooltips, context menus etc.

use crate::*;

// ----------------------------------------------------------------------------

/// Same state for all tooltips.
#[derive(Clone, Debug, Default)]
pub(crate) struct MonoState {
    last_id: Option<Id>,
    last_size: Vec<Vec2>,
}

impl MonoState {
    fn tooltip_size(&self, id: Id, index: usize) -> Option<Vec2> {
        if self.last_id == Some(id) {
            self.last_size.get(index).cloned()
        } else {
            None
        }
    }

    fn set_tooltip_size(&mut self, id: Id, index: usize, size: Vec2) {
        if self.last_id == Some(id) {
            if let Some(stored_size) = self.last_size.get_mut(index) {
                *stored_size = size;
            } else {
                self.last_size
                    .extend((0..index - self.last_size.len()).map(|_| Vec2::ZERO));
                self.last_size.push(size);
            }
            return;
        }

        self.last_id = Some(id);
        self.last_size.clear();
        self.last_size.extend((0..index).map(|_| Vec2::ZERO));
        self.last_size.push(size);
    }
}

// ----------------------------------------------------------------------------

/// Show a tooltip at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_ui`].
///
/// See also [`show_tooltip_text`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # let mut ui = egui::Ui::__test();
/// if ui.ui_contains_pointer() {
///     egui::show_tooltip(ui.ctx(), egui::Id::new("my_tooltip"), |ui| {
///         ui.label("Helpful text");
///     });
/// }
/// ```
pub fn show_tooltip<R>(ctx: &CtxRef, id: Id, add_contents: impl FnOnce(&mut Ui) -> R) -> Option<R> {
    show_tooltip_at_pointer(ctx, id, add_contents)
}

/// Show a tooltip at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_ui`].
///
/// See also [`show_tooltip_text`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # let mut ui = egui::Ui::__test();
/// if ui.ui_contains_pointer() {
///     egui::show_tooltip_at_pointer(ui.ctx(), egui::Id::new("my_tooltip"), |ui| {
///         ui.label("Helpful text");
///     });
/// }
/// ```
pub fn show_tooltip_at_pointer<R>(
    ctx: &CtxRef,
    id: Id,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
    let suggested_pos = ctx
        .input()
        .pointer
        .hover_pos()
        .map(|pointer_pos| pointer_pos + vec2(16.0, 16.0));
    show_tooltip_at(ctx, id, suggested_pos, add_contents)
}

/// Show a tooltip under the given area.
///
/// If the tooltip does not fit under the area, it tries to place it above it instead.
pub fn show_tooltip_under<R>(
    ctx: &CtxRef,
    id: Id,
    rect: &Rect,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
    let expanded_rect = rect.expand2(vec2(2.0, 4.0));
    show_tooltip_at_avoid(
        ctx,
        id,
        Some(expanded_rect.left_bottom()),
        expanded_rect,
        add_contents,
    )
}

/// Show a tooltip at the given position.
///
/// Returns `None` if the tooltip could not be placed.
pub fn show_tooltip_at<R>(
    ctx: &CtxRef,
    id: Id,
    suggested_position: Option<Pos2>,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
    show_tooltip_at_avoid(ctx, id, suggested_position, Rect::NOTHING, add_contents)
}

fn show_tooltip_at_avoid<R>(
    ctx: &CtxRef,
    mut id: Id,
    suggested_position: Option<Pos2>,
    mut avoid_rect: Rect,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
    let mut tooltip_rect = Rect::NOTHING;
    let mut count = 0;

    let position = if let Some((stored_id, stored_tooltip_rect, stored_count)) =
        ctx.frame_state().tooltip_rect
    {
        // if there are multiple tooltips open they should use the same id for the `tooltip_size` caching to work.
        id = stored_id;
        tooltip_rect = stored_tooltip_rect;
        count = stored_count;
        avoid_rect = avoid_rect.union(tooltip_rect);
        tooltip_rect.left_bottom()
    } else if let Some(position) = suggested_position {
        position
    } else if ctx.memory().everything_is_visible() {
        Pos2::default()
    } else {
        return None; // No good place for a tooltip :(
    };

    let expected_size = ctx
        .memory()
        .data_temp
        .get_or_default::<crate::containers::popup::MonoState>()
        .tooltip_size(id, count);
    let expected_size = expected_size.unwrap_or_else(|| vec2(64.0, 32.0));
    let position = position.min(ctx.input().screen_rect().right_bottom() - expected_size);
    // Place the tooltip above the avoid_rect if necessary.
    let new_rect = Rect::from_min_size(position, expected_size);
    // Note: We do not use Rect::intersects() since it returns true even if the rects only touch.
    let position = if avoid_rect.min.x < new_rect.max.x
        && new_rect.min.x < avoid_rect.max.x
        && avoid_rect.min.y < new_rect.max.y
        && new_rect.min.y < avoid_rect.max.y
    {
        Pos2::new(position.x, avoid_rect.min.y - expected_size.y)
    } else {
        position
    };

    let position = position.max(ctx.input().screen_rect().left_top());

    let InnerResponse { inner, response } = show_tooltip_area(ctx, id, position, add_contents);
    ctx.memory()
        .data_temp
        .get_mut_or_default::<crate::containers::popup::MonoState>()
        .set_tooltip_size(id, count, response.rect.size());

    ctx.frame_state().tooltip_rect = Some((id, tooltip_rect.union(response.rect), count + 1));
    Some(inner)
}

/// Show some text at the current pointer position (if any).
///
/// Most of the time it is easier to use [`Response::on_hover_text`].
///
/// See also [`show_tooltip`].
///
/// Returns `None` if the tooltip could not be placed.
///
/// ```
/// # let mut ui = egui::Ui::__test();
/// if ui.ui_contains_pointer() {
///     egui::show_tooltip_text(ui.ctx(), egui::Id::new("my_tooltip"), "Helpful text");
/// }
/// ```
pub fn show_tooltip_text(ctx: &CtxRef, id: Id, text: impl ToString) -> Option<()> {
    show_tooltip(ctx, id, |ui| {
        ui.add(crate::widgets::Label::new(text));
    })
}

/// Show a pop-over window.
fn show_tooltip_area<R>(
    ctx: &CtxRef,
    id: Id,
    window_pos: Pos2,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<R> {
    use containers::*;
    Area::new(id)
        .order(Order::Tooltip)
        .fixed_pos(window_pos)
        .interactable(false)
        .show(ctx, |ui| {
            Frame::popup(&ctx.style())
                .show(ui, |ui| {
                    ui.set_max_width(ui.spacing().tooltip_width);
                    add_contents(ui)
                })
                .inner
        })
}

/// Shows a popup below another widget.
///
/// Useful for drop-down menus (combo boxes) or suggestion menus under text fields.
///
/// You must open the popup with [`Memory::open_popup`] or  [`Memory::toggle_popup`].
///
/// Returns `None` if the popup is not open.
///
/// ```
/// # let ui = &mut egui::Ui::__test();
/// let response = ui.button("Open popup");
/// let popup_id = ui.make_persistent_id("my_unique_id");
/// if response.clicked() {
///     ui.memory().toggle_popup(popup_id);
/// }
/// egui::popup::popup_below_widget(ui, popup_id, &response, |ui| {
///     ui.set_min_width(200.0); // if you want to control the size
///     ui.label("Some more info, or things you can select:");
///     ui.label("…");
/// });
/// ```
pub fn popup_below_widget<R>(
    ui: &Ui,
    popup_id: Id,
    widget_response: &Response,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
    if ui.memory().is_popup_open(popup_id) {
        let parent_clip_rect = ui.clip_rect();

        let inner = Area::new(popup_id)
            .order(Order::Foreground)
            .fixed_pos(widget_response.rect.left_bottom())
            .show(ui.ctx(), |ui| {
                ui.set_clip_rect(parent_clip_rect); // for when the combo-box is in a scroll area.
                let frame = Frame::popup(ui.style());
                let frame_margin = frame.margin;
                frame
                    .show(ui, |ui| {
                        ui.with_layout(Layout::top_down_justified(Align::LEFT), |ui| {
                            ui.set_width(widget_response.rect.width() - 2.0 * frame_margin.x);
                            add_contents(ui)
                        })
                        .inner
                    })
                    .inner
            })
            .inner;

        if ui.input().key_pressed(Key::Escape) || widget_response.clicked_elsewhere() {
            ui.memory().close_popup();
        }
        Some(inner)
    } else {
        None
    }
}