1use std::cell::RefCell;
52use std::collections::BTreeMap;
53
54use egui::{Align, Layout, Popup, Ui};
55use egui_pop_core::icon::{Icon, IconRef, Size};
56use egui_pop_core::kit::Kit;
57use egui_pop_core::state::Slot;
58use egui_pop_core::strings;
59use egui_pop_core::theme::Tokens;
60use egui_pop_model::ids::{CommandId, MenuId};
61use egui_pop_model::menus::{Item, Shown, show_items};
62use egui_pop_model::when::{When, WhenContext};
63use egui_stack::toolbar::{self as row, ToolDisplay, ToolRow};
64use serde::Serialize;
65use serde_json::Value as Json;
66
67use crate::app::AppHandle;
68use crate::menus::{self, ListItem, Mark, RowTrace};
69use crate::strings as txt;
70
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
73#[serde(rename_all = "snake_case")]
74pub enum Labels {
75 #[default]
78 Icons,
79 Beside,
81 Text,
83}
84
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
87#[serde(rename_all = "snake_case")]
88pub enum Orientation {
89 #[default]
91 Horizontal,
92 Vertical,
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
98#[serde(rename_all = "snake_case")]
99pub enum ToolKind {
100 Command,
102 Submenu,
104 Separator,
106}
107
108#[derive(Clone, Debug, PartialEq, Serialize)]
110pub struct ToolTrace {
111 pub kind: ToolKind,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub command: Option<CommandId>,
115 #[serde(skip_serializing_if = "Json::is_null")]
117 pub args: Json,
118 #[serde(skip_serializing_if = "Option::is_none")]
120 pub submenu: Option<MenuId>,
121 pub label: String,
123 #[serde(skip_serializing_if = "Option::is_none")]
125 pub icon: Option<String>,
126 #[serde(skip_serializing_if = "Option::is_none")]
128 pub keys: Option<String>,
129 pub enabled: bool,
130 #[serde(skip_serializing_if = "Option::is_none")]
132 pub why: Option<String>,
133 #[serde(skip_serializing_if = "std::ops::Not::not")]
135 pub checkable: bool,
136 #[serde(skip_serializing_if = "std::ops::Not::not")]
137 pub checked: bool,
138 #[serde(skip_serializing_if = "std::ops::Not::not")]
139 pub radio: bool,
140 #[serde(skip_serializing_if = "std::ops::Not::not")]
142 pub busy: bool,
143 #[serde(skip_serializing_if = "std::ops::Not::not")]
145 pub overflow: bool,
146}
147
148#[derive(Clone, Debug, PartialEq, Serialize)]
150pub struct ToolbarLayout {
151 pub menu: MenuId,
152 pub orientation: Orientation,
153 pub labels: Labels,
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub name: Option<String>,
157 pub tools: Vec<ToolTrace>,
159 pub overflow: usize,
161}
162
163const LISTS: Slot<(WhenContext, Vec<ListItem>)> = Slot::new("api.toolbars.lists");
166
167#[derive(Default)]
169struct Layouts(RefCell<BTreeMap<String, ToolbarLayout>>);
170
171pub fn layout(app: &AppHandle, menu: &MenuId) -> Option<ToolbarLayout> {
173 app.local::<Layouts>()
174 .0
175 .borrow()
176 .get(menu.as_str())
177 .cloned()
178}
179
180pub(crate) fn layouts(app: &AppHandle) -> BTreeMap<String, ToolbarLayout> {
182 app.local::<Layouts>().0.borrow().clone()
183}
184
185#[derive(Debug)]
187#[must_use = "draw it with `show`"]
188pub struct Toolbar<'a> {
189 app: &'a AppHandle,
190 menu: MenuId,
191 orientation: Orientation,
192 labels: Labels,
193 args: Json,
194 name: Option<String>,
195}
196
197impl<'a> Toolbar<'a> {
198 pub fn new(app: &'a AppHandle, menu: &MenuId) -> Self {
200 Self {
201 app,
202 menu: menu.clone(),
203 orientation: Orientation::Horizontal,
204 labels: Labels::Icons,
205 args: Json::Null,
206 name: None,
207 }
208 }
209
210 pub fn name(mut self, name: impl Into<String>) -> Self {
215 self.name = Some(name.into());
216 self
217 }
218
219 pub fn vertical(mut self) -> Self {
221 self.orientation = Orientation::Vertical;
222 self
223 }
224
225 pub fn orientation(mut self, orientation: Orientation) -> Self {
227 self.orientation = orientation;
228 self
229 }
230
231 pub fn labels(mut self, labels: Labels) -> Self {
233 self.labels = labels;
234 self
235 }
236
237 pub fn args(mut self, args: Json) -> Self {
241 self.args = args;
242 self
243 }
244
245 pub fn show(self, ui: &mut Ui) -> ToolbarLayout {
250 let app = self.app;
251 let ctx = ui.ctx().clone();
252 let cx = menus::with_args(&app.when_context(), &self.args);
253 let shown = show_items(&app.menu(&self.menu), &cx);
254 let tools = self.tools(ui, &shown, &cx);
255 let t = Tokens::of(&ctx);
256 let icon = Size::Toolbar.points(&t);
257 let pad = t.space.xs;
258 let kit = Kit::of(&ctx);
259 let mut labels = egui_stack::Labels::ENGLISH;
261 labels.more_tools = strings::tr(&ctx, &txt::TOOLBAR_MORE).into();
262 if let Some(toolbar) = &self.name {
263 labels.more_tools_in =
264 strings::tr_args(&ctx, &txt::TOOLBAR_MORE_IN, &[("toolbar", toolbar)]).into();
265 }
266 let name = format!("egui-pop.toolbar:{}:{:?}", self.menu, ui.scope_id());
269 let mut bar = ToolRow::new(name)
270 .display(match self.labels {
271 Labels::Icons => ToolDisplay::Icons,
272 Labels::Beside => ToolDisplay::Beside,
273 Labels::Text => ToolDisplay::Text,
274 })
275 .icon_size(icon)
276 .padding(pad)
277 .spacing(pad / 2.0)
278 .painter(&*kit)
279 .labels(labels);
280 if self.orientation == Orientation::Vertical {
281 bar = bar.vertical();
282 }
283 if let Some(title) = &self.name {
284 bar = bar.title(title.clone());
285 }
286 let vertical = self.orientation == Orientation::Vertical;
287 let row_tools = tools
288 .iter()
289 .enumerate()
290 .map(|(i, tool)| self.row_tool(&ctx, i, tool, &cx));
291 let layout = if vertical {
292 Layout::top_down(Align::Min)
293 } else {
294 Layout::left_to_right(Align::Center)
295 };
296 let response = ui
297 .with_layout(layout, |ui| {
298 ui.spacing_mut().item_spacing.x = t.space.s;
300 if vertical {
301 return bar.show(ui, row_tools);
302 }
303 let line = ui.available_rect_before_wrap();
309 let text = ui.text_style_height(&egui::TextStyle::Button);
310 let height = (icon.max(text) + 2.0 * pad).round();
311 let room = egui::vec2(ui.available_width(), height);
312 let out = ui.allocate_ui(room, |ui| bar.show(ui, row_tools)).inner;
313 if line.height().is_finite() {
314 ui.expand_to_include_y(line.top());
315 ui.expand_to_include_y(line.bottom());
316 }
317 out
318 })
319 .inner;
320 if let Some(tool) = response
321 .clicked
322 .as_deref()
323 .and_then(|id| id.parse::<usize>().ok())
324 .and_then(|i| tools.get(i))
325 && let Some(id) = &tool.trace.command
326 {
327 app.request_run_in(
328 id.clone(),
329 menus::merge(&tool.trace.args, &self.args),
330 cx.clone(),
331 );
332 }
333 let mut traces = Vec::with_capacity(response.laid.tools.len());
335 let mut ours = tools.iter().enumerate();
336 for laid in &response.laid.tools {
337 let sep = laid.kind == row::ToolKind::Separator;
338 let found = ours.by_ref().find(|(i, t)| {
339 if sep {
340 t.trace.kind == ToolKind::Separator
341 } else {
342 laid.id == i.to_string()
343 }
344 });
345 if let Some((_, t)) = found {
346 let mut trace = t.trace.clone();
347 trace.overflow = laid.overflow;
348 traces.push(trace);
349 }
350 }
351 let more_open = response
353 .laid
354 .more
355 .is_some_and(|more| Popup::is_id_open(&ctx, more.with("popup")));
356 if let Some(more) = response.laid.more {
358 egui_pop_core::overlay::follow_popup(
359 &ctx,
360 more.with("popup"),
361 "toolbar overflow",
362 more_open,
363 None,
364 );
365 }
366 if more_open {
367 let gutter = icon + 2.0 * pad;
368 for tr in traces
369 .iter()
370 .filter(|t| t.overflow && t.kind != ToolKind::Separator)
371 {
372 let mark = match (tr.busy, tr.checked, tr.icon.is_some()) {
373 (true, ..) => Mark::Busy,
374 (false, true, true) => Mark::Framed,
375 (false, true, false) if tr.radio => Mark::Radio,
376 (false, true, false) => Mark::Check,
377 (false, false, true) => Mark::Icon,
378 (false, false, false) => Mark::None,
379 };
380 menus::record_row(
381 &ctx,
382 RowTrace {
383 menu: self.menu.clone(),
384 label: tr.label.clone(),
385 icon: tr.icon.clone(),
386 mark,
387 label_x: gutter,
388 gutter,
389 },
390 );
391 }
392 }
393 let out = ToolbarLayout {
394 menu: self.menu.clone(),
395 orientation: self.orientation,
396 labels: self.labels,
397 name: self.name.clone(),
398 overflow: response.laid.overflow,
399 tools: traces,
400 };
401 app.local::<Layouts>()
402 .0
403 .borrow_mut()
404 .insert(self.menu.to_string(), out.clone());
405 out
406 }
407
408 fn row_tool<'t>(
412 &'t self,
413 ctx: &egui::Context,
414 i: usize,
415 tool: &'t Tool,
416 cx: &'t WhenContext,
417 ) -> row::Tool<'t> {
418 let tr = &tool.trace;
419 let id = i.to_string();
420 let label = tr.label.clone();
421 let mut out = match tr.kind {
422 ToolKind::Separator => return row::Tool::separator(),
423 ToolKind::Submenu => {
424 let (app, args) = (self.app, &self.args);
425 let sub = tr.submenu.clone();
426 row::Tool::menu(id, label, move |ui| {
427 if let Some(sub) = sub {
428 let shown = show_items(&app.menu(&sub), cx);
429 menus::rows(ui, app, &sub, shown, cx, args, 1);
430 }
431 })
432 }
433 ToolKind::Command => match (tr.checkable, tr.radio) {
434 (true, true) => row::Tool::radio(id, label, tr.checked),
435 (true, false) => row::Tool::toggle(id, label, tr.checked),
436 _ => row::Tool::button(id, label),
437 },
438 };
439 let action = tr
442 .command
443 .as_ref()
444 .and_then(|c| self.app.command_text(c).tooltip)
445 .unwrap_or_else(|| tr.label.clone());
446 let tip = match &tr.keys {
447 Some(keys) => strings::tr_args(
448 ctx,
449 &txt::TOOLBAR_WITH_KEY,
450 &[("action", &action), ("keys", keys)],
451 ),
452 None => action,
453 };
454 let tip = match (&tr.why, &tool.failed) {
455 (Some(why), _) => format!("{tip}\n{why}"),
456 (None, Some(e)) => format!(
457 "{tip}\n{}",
458 strings::tr_args(ctx, &txt::MENU_LAST_RUN_FAILED, &[("error", e)])
459 ),
460 (None, None) => tip,
461 };
462 out = out.tooltip(tip).enabled(tr.enabled).busy(tr.busy);
463 if let Some(keys) = &tr.keys {
464 out = out.shortcut(keys.clone());
465 }
466 if let Some(icon) = tool.icon {
467 let (label, name) = (tr.label.as_str(), tr.icon.as_deref());
468 out = out.icon_painter(move |painter, rect, color| {
469 icon.paint(painter, rect, color);
470 if let Some(name) = name {
471 egui_pop_core::icon::registry::record(painter.ctx(), "toolbar", label, name);
472 }
473 });
474 }
475 out
476 }
477
478 fn tools(&self, ui: &Ui, shown: &[Shown], cx: &WhenContext) -> Vec<Tool> {
480 let app = self.app;
481 let mut out = Vec::new();
482 for s in shown {
483 match s {
484 Shown::Separator => out.push(Tool::separator()),
485 Shown::Item {
486 item,
487 enabled,
488 checked,
489 checkable,
490 radio,
491 } => match item {
492 Item::Command { id, args, label } => out.push(Tool::command(
493 ui.ctx(),
494 app,
495 cx,
496 CommandTool {
497 id,
498 args: args.clone(),
499 label: label.clone(),
500 own_icon: None,
501 enabled: *enabled,
502 checked: *checked,
503 checkable: *checkable,
504 radio: *radio,
505 },
506 )),
507 Item::Submenu { menu, label } => {
508 let label = strings::menu_label(ui.ctx(), menu.as_str(), label);
509 out.push(Tool::submenu(menu.clone(), label, *enabled));
510 }
511 Item::List { name } => {
512 for e in self.list_entries(ui, name, cx) {
513 out.push(Tool::command(
514 ui.ctx(),
515 app,
516 cx,
517 CommandTool {
518 id: &e.command,
519 args: e.args.clone(),
520 label: Some(e.label.clone()),
521 own_icon: e.icon,
522 enabled: *enabled && e.enabled,
523 checked: e.checked,
524 checkable: e.checked,
525 radio: false,
526 },
527 ));
528 }
529 }
530 },
531 }
532 }
533 out
534 }
535
536 fn list_entries(&self, ui: &Ui, name: &str, cx: &WhenContext) -> Vec<ListItem> {
540 let key = LISTS.keyed((self.menu.as_str(), name));
541 if let Some((at, entries)) = key.get(ui.ctx())
542 && at == *cx
543 {
544 return entries;
545 }
546 let entries = self.app.list_items(name, cx);
547 key.set(ui.ctx(), (cx.clone(), entries.clone()));
548 entries
549 }
550}
551
552struct CommandTool<'i> {
554 id: &'i CommandId,
555 args: Json,
556 label: Option<String>,
557 own_icon: Option<Icon>,
559 enabled: bool,
560 checked: bool,
561 checkable: bool,
562 radio: bool,
563}
564
565struct Tool {
567 trace: ToolTrace,
568 icon: Option<Icon>,
570 failed: Option<String>,
572}
573
574impl Tool {
575 fn separator() -> Tool {
576 Tool {
577 trace: ToolTrace {
578 kind: ToolKind::Separator,
579 command: None,
580 args: Json::Null,
581 submenu: None,
582 label: String::new(),
583 icon: None,
584 keys: None,
585 enabled: true,
586 why: None,
587 checkable: false,
588 checked: false,
589 radio: false,
590 busy: false,
591 overflow: false,
592 },
593 icon: None,
594 failed: None,
595 }
596 }
597
598 fn submenu(menu: MenuId, label: String, enabled: bool) -> Tool {
599 let mut tool = Tool::separator();
600 tool.trace.kind = ToolKind::Submenu;
601 tool.trace.submenu = Some(menu);
602 tool.trace.label = label;
603 tool.trace.enabled = enabled;
604 tool
605 }
606
607 fn command(ctx: &egui::Context, app: &AppHandle, cx: &WhenContext, c: CommandTool<'_>) -> Tool {
608 let spec = app.command(c.id);
609 let (title, why) = match &spec {
610 Some(s) => {
611 let applies = s.when.is_empty() || When::parse(&s.when).is_ok_and(|w| w.eval(cx));
612 let why = (!applies)
613 .then(|| strings::tr_args(ctx, &txt::MENU_DOES_NOT_APPLY, &[("when", &s.when)]))
614 .or_else(|| (!c.enabled).then(|| strings::tr(ctx, &txt::MENU_NOT_AVAILABLE)));
615 (
616 c.label.clone().unwrap_or_else(|| app.command_menu_title(s)),
617 why,
618 )
619 }
620 None => (
621 c.label.clone().unwrap_or_else(|| c.id.to_string()),
622 Some(strings::tr_args(
623 ctx,
624 &txt::MENU_NO_COMMAND,
625 &[("id", c.id.as_str())],
626 )),
627 ),
628 };
629 let running = app.running(c.id);
630 let why = why.or_else(|| running.then(|| strings::tr(ctx, &txt::MENU_RUNNING)));
631 let failed = app
632 .history()
633 .iter()
634 .rev()
635 .find(|r| r.id == *c.id)
636 .and_then(|r| r.result.clone().err());
637 let (icon, name) = match c.own_icon {
638 Some(i) => (Some(i), Some(i.name().to_string())),
639 None => match spec.as_ref().and_then(|s| s.icon_for(c.checked)) {
640 Some(n) => (
641 Some(IconRef::from(n).or_placeholder("toolbar")),
642 Some(n.to_string()),
643 ),
644 None => (None, None),
645 },
646 };
647 let busy = crate::busy::busy_shown(
648 app,
649 ctx,
650 egui::Id::unique(("egui_pop_toolbar_busy", c.id.as_str(), &title)),
651 c.id,
652 );
653 Tool {
654 trace: ToolTrace {
655 kind: ToolKind::Command,
656 command: Some(c.id.clone()),
657 args: c.args,
658 submenu: None,
659 label: title,
660 icon: name,
661 keys: app.keys_for(c.id).first().cloned(),
662 enabled: why.is_none(),
663 why,
664 checkable: c.checkable,
665 checked: c.checked,
666 radio: c.radio,
667 busy,
668 overflow: false,
669 },
670 icon,
671 failed,
672 }
673 }
674}