1use egui::{Rect, Response, Role, Sense, Ui, WidgetInfo, vec2};
37use egui_pop_core::icon::{Icon, Size};
38use egui_pop_core::kit::{Kit, KitCx, Part, State};
39use egui_pop_core::lock;
40use egui_pop_core::state::Slot;
41use egui_pop_core::strings;
42use egui_pop_core::theme::Tokens;
43use egui_pop_model::commands::{CommandSpec, Origin};
44use egui_pop_model::ids::{BlockId, CommandId, MenuId, OwnerId, SettingId};
45use egui_pop_model::menus::MenuItem;
46use egui_pop_model::panels::Area;
47use egui_pop_model::values::{Change, Set, Value};
48use serde_json::{Value as Json, json};
49
50use crate::app::{AppHandle, MENU_VIEW};
51use crate::arrangements;
52use crate::menus::ListItem;
53use crate::steps::Outcome;
54use crate::strings as txt;
55use crate::workbench::{PanelAlignment, SETTING_PANEL_ALIGNMENT, area_name};
56
57pub const MENU_LAYOUT: MenuId = MenuId::from_static("app.menu.layout");
59pub const BLOCK_LAYOUT_CONTROLS: BlockId = BlockId::from_static("egui_pop.frame.layout");
62
63pub const CMD_CUSTOMIZE: CommandId = CommandId::from_static("workbench.layout.customize");
65pub const CMD_SIDE_BAR_POSITION: CommandId =
68 CommandId::from_static("workbench.layout.sideBarPosition");
69pub const CMD_PANEL_ALIGNMENT: CommandId =
72 CommandId::from_static("workbench.layout.panelAlignment");
73
74const LIST_ARRANGEMENTS: &str = "workbench.layout.arrangements";
76const LIST_SAVE: &str = "workbench.layout.save";
77const LIST_SIDE_BAR: &str = "workbench.layout.side_bar";
78const LIST_PANEL: &str = "workbench.layout.panel";
79
80const BUTTON: Slot<Rect> = Slot::new("api.layout_controls.button");
82
83pub const CMD_TOGGLE_PRIMARY_SIDE_BAR: CommandId =
85 CommandId::from_static("workbench.toggle.primarySideBar");
86pub const CMD_TOGGLE_PANEL: CommandId = CommandId::from_static("workbench.toggle.panel");
88pub const CMD_TOGGLE_SECONDARY_SIDE_BAR: CommandId =
91 CommandId::from_static("workbench.toggle.secondarySideBar");
92
93pub const TOGGLES: [(Area, CommandId, &str); 3] = [
96 (
97 Area::StartSide,
98 CMD_TOGGLE_PRIMARY_SIDE_BAR,
99 "sideBarVisible",
100 ),
101 (Area::Bottom, CMD_TOGGLE_PANEL, "panelVisible"),
102 (
103 Area::EndSide,
104 CMD_TOGGLE_SECONDARY_SIDE_BAR,
105 "auxiliaryBarVisible",
106 ),
107];
108
109pub fn toggle_command(area: Area) -> Option<CommandId> {
111 TOGGLES.iter().find(|t| t.0 == area).map(|t| t.1.clone())
112}
113
114pub const SETTING_SIDE_BAR_POSITION: SettingId =
118 SettingId::from_static("workbench.side_bar_position");
119
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum SideBarPosition {
123 #[default]
125 Left,
126 Right,
128}
129
130impl SideBarPosition {
131 pub const CHOICES: [&'static str; 2] = ["left", "right"];
133
134 pub fn as_str(self) -> &'static str {
135 match self {
136 SideBarPosition::Left => "left",
137 SideBarPosition::Right => "right",
138 }
139 }
140
141 pub fn parse(s: &str) -> Option<SideBarPosition> {
142 match s {
143 "left" => Some(SideBarPosition::Left),
144 "right" => Some(SideBarPosition::Right),
145 _ => None,
146 }
147 }
148
149 pub fn other(self) -> SideBarPosition {
151 match self {
152 SideBarPosition::Left => SideBarPosition::Right,
153 SideBarPosition::Right => SideBarPosition::Left,
154 }
155 }
156
157 pub(crate) fn flipped(self) -> bool {
160 self == SideBarPosition::Right
161 }
162}
163
164pub fn side_bar_position(app: &AppHandle) -> SideBarPosition {
166 lock(&app.store())
167 .get(&format!("settings/{SETTING_SIDE_BAR_POSITION}"))
168 .and_then(|e| e.value.as_choice().and_then(SideBarPosition::parse))
169 .unwrap_or_default()
170}
171
172pub fn area_shown(app: &AppHandle, area: Area) -> bool {
176 let panels: Vec<_> = {
177 let Some(mut wb) = app.try_workbench() else {
178 return false;
179 };
180 let layout = wb.layout();
181 if layout.folded.contains(&area) {
182 return false;
183 }
184 layout
185 .areas
186 .iter()
187 .filter(|(a, _)| *a == area)
188 .flat_map(|(_, n)| n.panels().into_iter().cloned())
189 .collect()
190 };
191 panels.iter().any(|p| crate::workbench::drawable(app, p))
192}
193
194pub(crate) fn keys(app: &AppHandle) -> Vec<(&'static str, bool)> {
197 TOGGLES
198 .iter()
199 .map(|(area, _, key)| (*key, area_shown(app, *area)))
200 .collect()
201}
202
203fn done(outcome: Option<Outcome>) -> Result<(), String> {
206 match outcome {
207 None | Some(Outcome::Done(Ok(_))) => Ok(()),
208 Some(Outcome::Done(Err(e))) => Err(e),
209 Some(Outcome::Vetoed { by, reason }) => Err(format!("stopped by `{by}`: {reason}")),
210 }
211}
212
213pub fn toggle_area(app: &AppHandle, area: Area) -> Result<Json, String> {
217 if area_shown(app, area) {
218 done(app.fold_area(area, true))?;
219 return Ok(json!({ "area": area_name(area), "shown": false }));
220 }
221 if app.layout().folded.contains(&area) {
222 done(app.fold_area(area, false))?;
223 }
224 if !area_shown(app, area) {
225 let layout = app.layout();
226 let closed = app.panels().into_iter().find(|s| {
227 s.area == area
228 && !s.palette
229 && !layout.shows(&s.id)
230 && crate::workbench::drawable(app, &s.id)
231 });
232 let Some(spec) = closed else {
233 return Err(format!("nothing to show in {}", area.name()));
234 };
235 done(app.change_workbench(crate::workbench::Change::Show(spec.id)))?;
236 }
237 Ok(json!({ "area": area_name(area), "shown": area_shown(app, area) }))
238}
239
240pub fn toggle_icon(app: &AppHandle, area: Area) -> Icon {
244 let on = area_shown(app, area);
245 let left = crate::workbench::on_left(area, side_bar_position(app).flipped());
246 match (area, left, on) {
247 (Area::Bottom | Area::Center, _, true) => Icon::LayoutBottom,
248 (Area::Bottom | Area::Center, _, false) => Icon::LayoutBottomOff,
249 (_, true, true) => Icon::LayoutLeft,
250 (_, true, false) => Icon::LayoutLeftOff,
251 (_, false, true) => Icon::LayoutRight,
252 (_, false, false) => Icon::LayoutRightOff,
253 }
254}
255
256pub fn command_icon<'a>(app: &AppHandle, command: &CommandId, name: &'a str) -> &'a str {
262 let side_bar =
263 *command == CMD_TOGGLE_PRIMARY_SIDE_BAR || *command == CMD_TOGGLE_SECONDARY_SIDE_BAR;
264 if !side_bar || !side_bar_position(app).flipped() {
265 return name;
266 }
267 match name {
268 "layout-left" => "layout-right",
269 "layout-left-off" => "layout-right-off",
270 "layout-right" => "layout-left",
271 "layout-right-off" => "layout-left-off",
272 other => other,
273 }
274}
275
276fn write_choice(
278 app: &AppHandle,
279 setting: &SettingId,
280 value: &str,
281 origin: &Origin,
282) -> Result<Json, String> {
283 lock(&app.store())
284 .set(
285 Set::new(
286 &format!("settings/{setting}"),
287 Change::To(Value::Choice(value.into())),
288 origin.clone(),
289 )
290 .by(&OwnerId::FRAMEWORK),
291 )
292 .map_err(|e| e.to_string())?;
293 app.egui().request_repaint();
294 Ok(json!({ "setting": setting, "value": value }))
295}
296
297pub fn set_side_bar_position(app: &AppHandle, position: SideBarPosition) -> Result<Json, String> {
299 write_choice(
300 app,
301 &SETTING_SIDE_BAR_POSITION,
302 position.as_str(),
303 &Origin::User,
304 )
305}
306
307pub fn set_panel_alignment(app: &AppHandle, alignment: PanelAlignment) -> Result<Json, String> {
309 write_choice(
310 app,
311 &SETTING_PANEL_ALIGNMENT,
312 alignment.as_str(),
313 &Origin::User,
314 )
315}
316
317pub fn open_menu(app: &AppHandle, under: Option<Rect>) -> bool {
321 let ctx = app.egui();
322 let rect = under
323 .or_else(|| BUTTON.keyed(ctx.viewport_id()).get(&ctx))
324 .unwrap_or_else(|| {
325 let screen = ctx.content_rect();
326 Rect::from_min_size(
327 egui::pos2(screen.right() - 240.0, screen.top()),
328 egui::Vec2::ZERO,
329 )
330 });
331 crate::menus::popup_at(app, &MENU_LAYOUT, rect)
332}
333
334pub fn show(ui: &mut Ui, app: &AppHandle) {
342 let ctx = ui.ctx().clone();
343 let (left, right) = if side_bar_position(app).flipped() {
344 (Area::EndSide, Area::StartSide)
345 } else {
346 (Area::StartSide, Area::EndSide)
347 };
348 let mut items = [None, Some(left), Some(Area::Bottom), Some(right)];
349 if ui.layout().prefer_right_to_left() {
352 items.reverse();
353 }
354 ui.scope(|ui| {
356 ui.spacing_mut().item_spacing.x = Tokens::of(&ctx).space.xs;
357 for item in items {
358 match item {
359 None => {
360 let name = strings::tr(&ctx, &txt::LAYOUT_CUSTOMIZE);
361 let r = button(ui, Icon::Layout, &name, &name, None);
362 egui_pop_core::icon::registry::record(
363 &ctx,
364 "layout controls",
365 &name,
366 Icon::Layout.name(),
367 );
368 BUTTON.keyed(ctx.viewport_id()).set(&ctx, r.rect);
369 if r.clicked() {
370 open_menu(app, Some(r.rect));
371 }
372 }
373 Some(area) => {
374 let Some(command) = toggle_command(area) else {
375 continue;
376 };
377 let name = app.command_text(&command).title.unwrap_or_else(|| {
378 let english = app.command(&command).map(|c| c.title).unwrap_or_default();
379 strings::command_title(&ctx, command.as_str(), &english)
380 });
381 let tip = match app.keys_for(&command).first() {
382 Some(keys) => strings::tr_args(
383 &ctx,
384 &txt::LAYOUT_WITH_KEY,
385 &[("action", &name), ("keys", keys)],
386 ),
387 None => name.clone(),
388 };
389 let on = area_shown(app, area);
390 let icon = toggle_icon(app, area);
391 let r = button(ui, icon, &name, &tip, Some(on));
392 egui_pop_core::icon::registry::record(
393 &ctx,
394 "layout controls",
395 &name,
396 icon.name(),
397 );
398 if r.clicked() {
399 app.run(command, Json::Null);
400 }
401 }
402 }
403 }
404 });
405}
406
407fn button(ui: &mut Ui, icon: Icon, name: &str, tip: &str, on: Option<bool>) -> Response {
411 let t = Tokens::of(ui.ctx());
412 let side = Size::Toolbar.points(&t);
413 let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::click());
414 if ui.is_rect_visible(rect) {
415 let kit = Kit::of(ui.ctx());
416 let b = &kit.icon_button;
417 let state = State::from_response(&response);
418 let cx = KitCx {
419 painter: ui.painter(),
420 ppp: ui.ctx().pixels_per_point(),
421 };
422 b.paint(
423 &cx,
424 &Part {
425 rect,
426 room: rect,
427 state,
428 label: None,
429 },
430 );
431 icon.paint(ui.painter(), rect, b.style(state).text);
432 }
433 let enabled = ui.is_enabled();
434 let name = name.to_string();
435 match on {
436 Some(on) => {
437 response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, on, &name));
438 }
439 None => response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name)),
440 }
441 response.on_hover_text(tip)
442}
443
444fn arrangement_items(app: &AppHandle) -> Vec<ListItem> {
447 if app.command(&arrangements::CMD_SWITCH).is_none() {
448 return Vec::new();
449 }
450 let current = arrangements::current(app);
451 arrangements::names(app)
452 .into_iter()
453 .map(|name| {
454 let on = name == current;
455 ListItem::new(&name, arrangements::CMD_SWITCH, json!({ "name": name })).checked(on)
456 })
457 .collect()
458}
459
460fn main_window() -> egui_pop_model::keymap::BindOptions {
464 egui_pop_model::keymap::BindOptions::window(crate::windows::WindowId::MAIN)
465}
466
467pub(crate) fn declare(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::CtxError> {
475 let specs = [
476 CommandSpec::new(CMD_TOGGLE_PRIMARY_SIDE_BAR, "Toggle primary side bar", "View")
477 .icon("layout-left-off")
478 .icon_on("layout-left")
479 .description("Shows or hides the primary side bar: hidden, it folds to its strip and keeps its panels.")
480 .key_with("Ctrl+B", main_window()),
481 CommandSpec::new(CMD_TOGGLE_PANEL, "Toggle panel", "View")
482 .icon("layout-bottom-off")
483 .icon_on("layout-bottom")
484 .description("Shows or hides the bottom panel: hidden, it keeps its panels.")
485 .key_with("Ctrl+J", main_window()),
486 CommandSpec::new(CMD_TOGGLE_SECONDARY_SIDE_BAR, "Toggle secondary side bar", "View")
487 .icon("layout-right-off")
488 .icon_on("layout-right")
489 .description("Shows or hides the secondary side bar: hidden, it folds to its strip and keeps its panels.")
490 .key_with("Ctrl+Alt+B", main_window()),
491 ];
492 for (order, (spec, (area, _, key))) in specs.into_iter().zip(TOGGLES).enumerate() {
493 ctx.command(
494 spec.checked(key).menu(MENU_VIEW, "3_layout", order as i32),
495 move |call| toggle_area(call.app, area),
496 )?;
497 }
498 ctx.setting(
499 SETTING_SIDE_BAR_POSITION,
500 egui_pop_model::values::Descriptor::choice(
501 "Primary side bar position",
502 &SideBarPosition::CHOICES,
503 SideBarPosition::Left.as_str(),
504 )
505 .description(
506 "Where the primary side bar lies: on the left, the secondary one on the right (left), or the other way round (right).",
507 ),
508 )?;
509 ctx.command(
510 CommandSpec::new(CMD_CUSTOMIZE, "Customize layout…", "View")
511 .icon("layout")
512 .description(
513 "Opens the layout menu: the areas, the arrangements, saving the current one, where the side bars and the panel lie.",
514 ),
515 |call| Ok(json!({ "open": open_menu(call.app, None) })),
516 )?
517 .command(
518 CommandSpec::new(CMD_SIDE_BAR_POSITION, "Toggle primary side bar position", "View")
519 .description("Puts the primary side bar on the left or the right (`position`: `left` or `right`; without it, on the other side).")
520 .args(json!({ "position": "right" })),
521 |call| {
522 let position = match call.args.get("position").and_then(Json::as_str) {
523 Some(p) => SideBarPosition::parse(p)
524 .ok_or_else(|| format!("no position `{p}` (`left` or `right`)"))?,
525 None => side_bar_position(call.app).other(),
526 };
527 write_choice(call.app, &SETTING_SIDE_BAR_POSITION, position.as_str(), call.origin)
528 },
529 )?
530 .command(
531 CommandSpec::new(CMD_PANEL_ALIGNMENT, "Toggle full-width panel", "View")
532 .description("Lines the bottom panel up under the editors or across the full width (`alignment`: `center`, `justify`, `start` or `end`; without it, switches between `center` and `justify`).")
533 .args(json!({ "alignment": "justify" })),
534 |call| {
535 let alignment = match call.args.get("alignment").and_then(Json::as_str) {
536 Some(a) => PanelAlignment::parse(a).ok_or_else(|| {
537 format!("no alignment `{a}` (`center`, `justify`, `start` or `end`)")
538 })?,
539 None if crate::workbench::panel_alignment(call.app) == PanelAlignment::Center => {
540 PanelAlignment::Justify
541 }
542 None => PanelAlignment::Center,
543 };
544 write_choice(call.app, &SETTING_PANEL_ALIGNMENT, alignment.as_str(), call.origin)
545 },
546 )?;
547 for (order, (_, command, key)) in TOGGLES.into_iter().enumerate() {
549 ctx.menu_item(
550 MenuItem::command(MENU_LAYOUT, "1_areas", order as i32, command).checked(key),
551 )?;
552 }
553 for (group, list) in [
554 ("2_arrangements", LIST_ARRANGEMENTS),
555 ("3_save", LIST_SAVE),
556 ("4_side_bar", LIST_SIDE_BAR),
557 ("5_panel", LIST_PANEL),
558 ] {
559 ctx.menu_item(MenuItem::list(MENU_LAYOUT, group, 0, list))?;
560 }
561 ctx.submenu(MENU_VIEW, "3_layout", 9, MENU_LAYOUT, "Customize layout")?;
562 ctx.list_provider(LIST_ARRANGEMENTS, |app, _| arrangement_items(app))
563 .list_provider(LIST_SAVE, |app, _| {
564 if app.command(&arrangements::CMD_SAVE).is_none() {
565 return Vec::new();
566 }
567 let label = strings::tr(&app.egui(), &app.arrangement_strings().save_as);
568 vec![ListItem::new(
569 &label,
570 arrangements::CMD_SAVE,
571 json!({ "name": "" }),
572 )]
573 })
574 .list_provider(LIST_SIDE_BAR, |app, _| {
575 let ctx = app.egui();
576 let now = side_bar_position(app);
577 [
578 (SideBarPosition::Left, &txt::LAYOUT_SIDE_BAR_LEFT),
579 (SideBarPosition::Right, &txt::LAYOUT_SIDE_BAR_RIGHT),
580 ]
581 .into_iter()
582 .map(|(p, key)| {
583 ListItem::new(
584 &strings::tr(&ctx, key),
585 CMD_SIDE_BAR_POSITION,
586 json!({ "position": p.as_str() }),
587 )
588 .checked(now == p)
589 })
590 .collect()
591 })
592 .list_provider(LIST_PANEL, |app, _| {
593 let ctx = app.egui();
594 let now = crate::workbench::panel_alignment(app);
595 [
596 (PanelAlignment::Center, &txt::LAYOUT_PANEL_CENTER),
597 (PanelAlignment::Justify, &txt::LAYOUT_PANEL_JUSTIFY),
598 ]
599 .into_iter()
600 .map(|(a, key)| {
601 ListItem::new(
602 &strings::tr(&ctx, key),
603 CMD_PANEL_ALIGNMENT,
604 json!({ "alignment": a.as_str() }),
605 )
606 .checked(now == a)
607 })
608 .collect()
609 });
610 Ok(())
611}