1use egui::{
5 IdSalt, Key, Modifiers, Rect, Response, Role, Sense, TextStyle, TextWrapMode, Ui, Vec2, Widget,
6 WidgetInfo, WidgetText, vec2,
7};
8
9use crate::icon::{Icon, Size};
10use crate::kit::{Glyph, Kit, State};
11use crate::strings;
12use crate::theme::Tokens;
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum SegmentOverflow {
18 #[default]
22 Menu,
23 Wrap,
25 Scroll,
27}
28
29#[derive(Clone, Debug, PartialEq)]
32pub struct SegmentOption<V> {
33 pub value: V,
34 pub label: String,
35 pub icon: Option<String>,
39 pub tip: Option<String>,
41 pub enabled: bool,
42}
43
44impl<V> SegmentOption<V> {
45 pub fn new(value: V, label: impl Into<String>) -> Self {
46 Self {
47 value,
48 label: label.into(),
49 icon: None,
50 tip: None,
51 enabled: true,
52 }
53 }
54
55 #[must_use]
57 pub fn icon(mut self, name: impl Into<String>) -> Self {
58 self.icon = Some(name.into());
59 self
60 }
61
62 #[must_use]
64 pub fn tip(mut self, tip: impl Into<String>) -> Self {
65 self.tip = Some(tip.into());
66 self
67 }
68
69 #[must_use]
71 pub fn enabled(mut self, enabled: bool) -> Self {
72 self.enabled = enabled;
73 self
74 }
75}
76
77#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
120pub struct Segmented<'a, V> {
121 salt: IdSalt,
122 value: &'a mut V,
123 options: Vec<SegmentOption<V>>,
124 name: String,
125 overflow: SegmentOverflow,
126}
127
128impl<V> std::fmt::Debug for Segmented<'_, V> {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 f.debug_struct("Segmented")
131 .field("salt", &self.salt)
132 .field("options", &self.options.len())
133 .field("name", &self.name)
134 .field("overflow", &self.overflow)
135 .finish_non_exhaustive()
136 }
137}
138
139impl<'a, V: PartialEq + Clone> Segmented<'a, V> {
140 pub fn new(
143 id_salt: impl egui::AsIdSalt,
144 value: &'a mut V,
145 options: impl IntoIterator<Item = SegmentOption<V>>,
146 ) -> Self {
147 Self {
148 salt: IdSalt::new(id_salt),
149 value,
150 options: options.into_iter().collect(),
151 name: String::new(),
152 overflow: SegmentOverflow::default(),
153 }
154 }
155
156 pub fn name(mut self, name: impl Into<String>) -> Self {
159 self.name = name.into();
160 self
161 }
162
163 pub fn overflow(mut self, overflow: SegmentOverflow) -> Self {
165 self.overflow = overflow;
166 self
167 }
168}
169
170pub fn segment_step(enabled: &[bool], at: usize, key: Key) -> Option<usize> {
176 let n = enabled.len();
177 if n == 0 || !enabled.iter().any(|e| *e) {
178 return None;
179 }
180 let to = match key {
181 Key::Home => enabled.iter().position(|e| *e)?,
182 Key::End => enabled.iter().rposition(|e| *e)?,
183 Key::ArrowLeft | Key::ArrowRight => {
184 let forward = key == Key::ArrowRight;
185 let mut i = at.min(n - 1);
186 loop {
187 i = if forward {
188 (i + 1) % n
189 } else {
190 (i + n - 1) % n
191 };
192 if enabled[i] || i == at {
193 break i;
194 }
195 }
196 }
197 _ => return None,
198 };
199 (to != at).then_some(to)
200}
201
202pub fn segment_fit(widths: &[f32], more: f32, room: f32, selected: Option<usize>) -> Vec<usize> {
207 let total: f32 = widths.iter().sum();
208 if total <= room {
209 return (0..widths.len()).collect();
210 }
211 let mut shown = Vec::new();
212 let mut used = more;
213 for (i, w) in widths.iter().enumerate() {
214 if used + w > room {
215 break;
216 }
217 used += w;
218 shown.push(i);
219 }
220 if let Some(sel) = selected
221 && sel < widths.len()
222 && !shown.contains(&sel)
223 {
224 while used + widths[sel] > room
225 && let Some(last) = shown.pop()
226 {
227 used -= widths[last];
228 }
229 shown.push(sel);
230 }
231 shown
232}
233
234struct Laid {
236 galley: std::sync::Arc<egui::Galley>,
237 icon: Option<Icon>,
238 size: Vec2,
239}
240
241impl<V: PartialEq + Clone> Widget for Segmented<'_, V> {
242 fn ui(self, ui: &mut Ui) -> Response {
243 let Segmented {
244 salt,
245 value,
246 options,
247 name,
248 overflow,
249 } = self;
250 let id = ui.make_persistent_id(salt);
251 let ctx = ui.ctx().clone();
252 let t = Tokens::of(&ctx);
253 let kit = Kit::of(&ctx);
254 let look = &kit.toggle_chip;
255 let room = look.border_room(ctx.pixels_per_point());
256 let padding = ui.spacing().button_padding.max(Vec2::splat(room));
257 let side = Size::Inline.points(&t);
258 let height = ui.spacing().interact_size.y;
259 let laid: Vec<Laid> = options
260 .iter()
261 .map(|o| {
262 let galley = WidgetText::from(o.label.as_str()).into_galley(
263 ui,
264 Some(TextWrapMode::Extend),
265 f32::INFINITY,
266 TextStyle::Button,
267 );
268 let icon = o.icon.as_deref().map(|n| {
269 crate::icon::registry::resolve(n, "segmented")
270 .unwrap_or(crate::icon::PLACEHOLDER)
271 });
272 let icon_w = if icon.is_some() {
273 side + t.space.xs
274 } else {
275 0.0
276 };
277 let size = vec2(
278 2.0 * padding.x + icon_w + galley.size().x,
279 height.max(galley.size().y + 2.0 * padding.y),
280 );
281 Laid { galley, icon, size }
282 })
283 .collect();
284 let selected = options.iter().position(|o| o.value == *value);
285 let seg_id = |i: usize| id.with(("segment", i));
286 let pending_id = id.with("pending focus");
289 let pending: Option<usize> = ctx.data_mut(|d| d.remove_temp(pending_id));
290 let more_w = 2.0 * padding.x + side;
291 let shown = match overflow {
292 SegmentOverflow::Menu => {
293 let widths: Vec<f32> = laid.iter().map(|l| l.size.x).collect();
294 segment_fit(&widths, more_w, ui.available_width(), selected)
295 }
296 _ => (0..options.len()).collect(),
297 };
298 let mut picked: Option<usize> = None;
299 let mut focused: Option<usize> = None;
300 let group_name = name.clone();
301 let body = |ui: &mut Ui, picked: &mut Option<usize>, focused: &mut Option<usize>| {
302 ui.spacing_mut().item_spacing.x = 0.0;
303 for &i in &shown {
304 let o = &options[i];
305 let l = &laid[i];
306 let on = selected == Some(i);
307 let r = ui
308 .add_enabled_ui(o.enabled, |ui| {
309 let (rect, _) = ui.allocate_exact_size(l.size, Sense::hover());
310 let r = ui.interact(rect, seg_id(i), Sense::click());
311 paint_segment(ui, &r, l, on, padding, side, t.space.xs);
312 r
313 })
314 .inner;
315 let enabled = o.enabled;
316 let label = o.label.clone();
317 r.widget_info(|| WidgetInfo::selected(Role::RadioButton, enabled, on, &label));
318 if pending == Some(i) {
319 r.request_focus();
320 }
321 if r.has_focus() {
322 *focused = Some(i);
323 }
324 let r = match &o.tip {
325 Some(tip) => r.on_hover_text(tip),
326 None => r,
327 };
328 if r.clicked() && !on {
329 *picked = Some(i);
330 }
331 }
332 if shown.len() < options.len() {
333 let more_name =
334 strings::tr_args(&ctx, &strings::SEGMENTED_MORE, &[("control", &group_name)]);
335 let (rect, _) = ui.allocate_exact_size(vec2(more_w, height), Sense::hover());
336 let r = ui.interact(rect, id.with("more"), Sense::click());
337 r.widget_info(|| WidgetInfo::labeled(Role::Button, true, &more_name));
338 if ui.is_rect_visible(rect) {
339 let state = State::from_response(&r).with(State::DISABLED, !ui.is_enabled());
340 paint_box(ui, rect, state);
341 let at = Rect::from_center_size(rect.center(), Vec2::splat(side));
342 Kit::of(ui.ctx()).glyph(Glyph::More).paint(
343 ui.painter(),
344 at,
345 Kit::of(ui.ctx()).toggle_chip.style(state).text,
346 );
347 }
348 egui::Popup::menu(&r).id(id.with("more menu")).show(|ui| {
349 for (i, o) in options.iter().enumerate() {
350 if shown.contains(&i) {
351 continue;
352 }
353 let on = selected == Some(i);
354 let r = ui.add_enabled(
355 o.enabled,
356 crate::widgets::SelectableRow::new(on, o.label.as_str()),
357 );
358 let label = o.label.clone();
359 let enabled = o.enabled;
360 r.widget_info(|| {
361 WidgetInfo::selected(Role::RadioButton, enabled, on, &label)
362 });
363 if r.clicked() {
364 *picked = Some(i);
365 ui.close();
366 }
367 }
368 });
369 }
370 };
371 let roving = format!("egui_pop.segmented.{id:?}");
372 let inner = crate::tab::roving(ui, &roving, crate::tab::Axis::Own, |ui| {
373 ui.scope_builder(
374 egui::UiBuilder::new()
375 .id_salt(id)
376 .accessibility_role(egui::accesskit::Role::RadioGroup)
377 .accessibility_label(name.clone()),
378 |ui| match overflow {
379 SegmentOverflow::Wrap => {
380 ui.horizontal_wrapped(|ui| body(ui, &mut picked, &mut focused));
381 }
382 SegmentOverflow::Scroll => {
383 egui::ScrollArea::horizontal()
384 .id_salt(id.with("scroll"))
385 .show(ui, |ui| {
386 ui.horizontal(|ui| body(ui, &mut picked, &mut focused));
387 });
388 }
389 SegmentOverflow::Menu => {
390 ui.horizontal(|ui| body(ui, &mut picked, &mut focused));
391 }
392 },
393 )
394 });
395 let mut response = inner.response;
396 if let Some(at) = focused {
398 let enabled: Vec<bool> = options.iter().map(|o| o.enabled).collect();
399 let step = [Key::ArrowLeft, Key::ArrowRight, Key::Home, Key::End]
400 .into_iter()
401 .find_map(|k| {
402 let to = segment_step(&enabled, at, k)?;
403 ui.input_mut(|i| i.consume_key(Modifiers::NONE, k))
404 .then_some(to)
405 });
406 if let Some(to) = step {
407 picked = Some(to);
408 if shown.contains(&to) {
409 ctx.memory_mut(|m| {
410 m.request_focus(seg_id(to));
411 m.move_focus(egui::FocusDirection::None);
412 });
413 } else {
414 ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
415 ctx.data_mut(|d| d.insert_temp(pending_id, to));
416 }
417 }
418 }
419 if let Some(i) = picked {
420 *value = options[i].value.clone();
421 response.mark_changed();
422 ctx.request_repaint();
423 }
424 response
425 }
426}
427
428fn paint_box(ui: &Ui, rect: Rect, state: State) {
430 let kit = Kit::of(ui.ctx());
431 kit.toggle_chip.paint(
432 &crate::kit::KitCx {
433 painter: ui.painter(),
434 ppp: ui.ctx().pixels_per_point(),
435 },
436 &crate::kit::Part {
437 rect,
438 room: rect,
439 state,
440 label: None,
441 },
442 );
443}
444
445fn paint_segment(ui: &Ui, r: &Response, l: &Laid, on: bool, padding: Vec2, side: f32, gap: f32) {
447 if !ui.is_rect_visible(r.rect) {
448 return;
449 }
450 let state = State::from_response(r).with(State::DISABLED, !ui.is_enabled());
451 let state = if on {
454 State::REST
455 .with(State::SELECTED, true)
456 .with(State::FOCUS, state.contains(State::FOCUS))
457 .with(State::ACTIVE, state.contains(State::ACTIVE))
458 .with(State::DISABLED, state.contains(State::DISABLED))
459 } else {
460 state
461 };
462 paint_box(ui, r.rect, state);
463 let kit = Kit::of(ui.ctx());
464 let colour = ui
465 .visuals()
466 .override_text_color
467 .unwrap_or(kit.toggle_chip.style(state).text);
468 let mut x = r.rect.left() + padding.x;
469 if let Some(icon) = l.icon {
470 let at = Rect::from_min_size(
471 egui::pos2(x, r.rect.center().y - side / 2.0),
472 Vec2::splat(side),
473 );
474 icon.paint(ui.painter(), at, colour);
475 x += side + gap;
476 }
477 let pos = egui::pos2(x, r.rect.center().y - l.galley.size().y / 2.0);
478 ui.painter().galley(pos, l.galley.clone(), colour);
479}