1use std::sync::{Arc, Mutex};
40
41use egui::{Key, Ui};
42use egui_pop_core::a11y;
43use egui_pop_core::fonts::{self, Origin as FaceOrigin, Role};
44use egui_pop_core::keys::chord_of;
45use egui_pop_core::lock;
46use egui_pop_core::overlay::{self, Kind, OverlaySpec};
47use egui_pop_core::param::{self, Mode};
48use egui_pop_core::state::Slot;
49use egui_pop_core::strings::{self, Arg, RESET};
50use egui_pop_core::theme::Tokens;
51use egui_pop_core::ui::UiPop as _;
52use egui_pop_core::widgets;
53use egui_pop_model::commands::{CommandSpec, Origin};
54use egui_pop_model::fuzzy;
55use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PanelId, PluginId};
56use egui_pop_model::keymap::{Action, KeyScope, Keys, Layer, Pointer};
57use egui_pop_model::values::{self, Change, Set};
58use serde_json::json;
59
60use crate::admin::{ADMIN, Admin};
61use crate::app::{AppHandle, MENU_FILE};
62use crate::history::StoreScope;
63use crate::hooks::SettingEntry;
64use crate::services::ServiceToken;
65use crate::settings_pages::{self, SettingsPage};
66use crate::strings as txt;
67use crate::zones::{self, Block};
68use crate::{Ctx, Plugin, PluginError};
69
70pub const CMD_SETTINGS: CommandId = CommandId::from_static("app.settings");
72
73pub const CMD_SETTINGS_PAGE: CommandId = CommandId::from_static("app.settings.page");
76
77pub const CMD_SETTINGS_WINDOW: CommandId = CommandId::from_static("app.settings.window");
80
81pub const SETTINGS_WINDOW: ServiceToken<SettingsWindow> = ServiceToken::new("app.settings_window");
83
84pub const CMD_VALUE_UNDO: CommandId = CommandId::from_static("value.undo");
87pub const CMD_VALUE_REDO: CommandId = CommandId::from_static("value.redo");
88
89pub const SURFACE: &str = "settingsWindow";
92
93pub use egui_pop_model::history::SETTINGS;
94
95pub const SHORTCUTS: &str = txt::SETTINGS_SHORTCUTS.fallback;
98
99pub const FONTS: &str = txt::SETTINGS_FONTS.fallback;
102
103#[derive(Debug, Default)]
104struct State {
105 open: bool,
106 filter: String,
107 section: Option<String>,
109 capture: Option<CommandId>,
111 capture_search: bool,
113 key_filter: Option<String>,
115 workspace_target: bool,
118 pointer_only: bool,
120 pointer_capture: Option<(CommandId, Option<String>)>,
123}
124
125#[derive(Clone, Debug, Default)]
127pub struct SettingsWindow(Arc<Mutex<State>>);
128
129impl SettingsWindow {
130 pub fn is_open(&self) -> bool {
131 lock(&self.0).open
132 }
133
134 pub fn open(&self, section: Option<&str>) {
137 let mut s = lock(&self.0);
138 s.open = true;
139 if let Some(sec) = section {
140 s.section = Some(sec.into());
141 }
142 }
143
144 pub fn close(&self) {
145 let mut s = lock(&self.0);
146 s.open = false;
147 s.capture = None;
148 s.capture_search = false;
149 s.pointer_capture = None;
150 s.key_filter = None;
151 s.filter.clear();
152 }
153
154 pub fn capturing(&self) -> Option<CommandId> {
156 lock(&self.0).capture.clone()
157 }
158
159 pub fn shown(&self) -> (Option<String>, String) {
162 let s = lock(&self.0);
163 (s.section.clone(), s.filter.clone())
164 }
165}
166
167pub fn is_open(app: &AppHandle) -> bool {
169 app.service(&SETTINGS_WINDOW).is_some_and(|w| w.is_open())
170}
171
172#[derive(Debug, Default)]
174pub struct SettingsPlugin;
175
176impl Plugin for SettingsPlugin {
177 fn id(&self) -> PluginId {
178 PluginId::from_static("egui_pop.settings")
179 }
180
181 fn title(&self) -> String {
182 "Settings".into()
183 }
184
185 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
186 ctx.service(&SETTINGS_WINDOW, SettingsWindow::default())?;
187 ctx.local_scope(SURFACE, StoreScope::new(SETTINGS, "Settings"));
188 ctx.command(
189 CommandSpec::new(CMD_SETTINGS, "Settings", "File")
190 .icon("settings")
191 .description("Every setting, searchable, and the keyboard shortcuts.")
192 .key("Ctrl+Comma")
193 .menu(MENU_FILE, "8_settings", 0)
194 .args(json!({ "section": "" })),
195 |call| {
196 let section = call
197 .args
198 .get("section")
199 .and_then(|s| s.as_str())
200 .filter(|s| !s.is_empty());
201 if let Some(admin) = call.app.service(&ADMIN) {
205 if admin.is_open() {
206 admin.close(call.app);
207 return Ok(json!({ "open": false }));
208 }
209 if let Some(w) = call.app.service(&SETTINGS_WINDOW) {
210 w.close();
211 call.app.close_overlay(
213 &call.app.egui(),
214 egui::Id::unique("egui_pop.settings"),
215 egui_pop_core::overlay::Closing::Owner,
216 );
217 }
218 let place = section.and_then(|s| page_path(call.app, s));
219 admin.open(call.app, place.as_deref())?;
220 return Ok(json!({ "open": true, "app": true }));
221 }
222 let w = call
223 .app
224 .service(&SETTINGS_WINDOW)
225 .ok_or("no settings window")?;
226 if w.is_open() {
227 w.close();
228 } else {
229 w.open(section);
230 }
231 Ok(json!({ "open": w.is_open() }))
232 },
233 )?;
234 ctx.command(
235 CommandSpec::new(CMD_SETTINGS_WINDOW, "Settings window", "File")
236 .description(
237 "Every setting and the keyboard shortcuts on one searchable form: the settings window of before.",
238 )
239 .hidden(),
240 |call| {
241 let w = call
242 .app
243 .service(&SETTINGS_WINDOW)
244 .ok_or("no settings window")?;
245 if w.is_open() {
246 w.close();
247 } else {
248 if let Some(admin) = call.app.service(&ADMIN) {
249 admin.close(call.app);
250 call.app.close_overlay(
253 &call.app.egui(),
254 egui::Id::unique("egui_pop.admin"),
255 egui_pop_core::overlay::Closing::Owner,
256 );
257 }
258 w.open(None);
259 }
260 Ok(json!({ "open": w.is_open() }))
261 },
262 )?;
263 ctx.command(
264 CommandSpec::new(CMD_SETTINGS_PAGE, "Settings page", "File")
265 .description("Opens the settings window on a custom page (its id).")
266 .hidden()
267 .args(json!({ "page": "" })),
268 |call| {
269 let page = call
270 .args
271 .get("page")
272 .and_then(|s| s.as_str())
273 .ok_or("`page` is missing")?;
274 if call.app.settings_page(page).is_none() {
275 return Err(format!("no settings page `{page}`"));
276 }
277 if let Some(admin) = call.app.service(&ADMIN)
278 && let Some(path) = page_path(call.app, page)
279 {
280 admin.open(call.app, Some(&path))?;
281 return Ok(json!({ "open": true, "page": page, "path": path }));
282 }
283 let w = call
284 .app
285 .service(&SETTINGS_WINDOW)
286 .ok_or("no settings window")?;
287 w.open(Some(page));
288 lock(&w.0).filter.clear();
289 Ok(json!({ "open": true, "page": page }))
290 },
291 )?;
292 ctx.block(
293 zones::OVERLAYS,
294 Block::add(BlockId::from_static("egui_pop.settings"), 5, show),
295 );
296 let w = ctx.app().downgrade();
297 ctx.collector(
298 egui_pop_core::debug::FnCollector::new(
299 "settings_window",
300 "The settings window: open or not, the section or page shown, the search, the tree (sections and custom pages) and the custom pages (id, title, parent, order, keywords, settings, component, reset, changed). `app.settings.page` opens a page.",
301 )
302 .snapshot(move |ctx| match w.get() {
303 Ok(app) => describe(ctx, &app),
304 Err(_) => serde_json::Value::Null,
305 }),
306 )?;
307 Ok(())
308 }
309}
310
311fn describe(ctx: &egui::Context, app: &AppHandle) -> serde_json::Value {
313 let (open, shown, filter) =
314 app.service(&SETTINGS_WINDOW)
315 .map_or((false, None, String::new()), |w| {
316 let (sec, filter) = w.shown();
317 (w.is_open(), sec, filter)
318 });
319 let all = app.settings();
320 let pages = app.settings_pages();
321 let entries = settings_pages::unclaimed(&all, &pages);
322 let tree: Vec<serde_json::Value> = settings_pages::tree(§ions(&entries), &pages)
323 .into_iter()
324 .map(|n| {
325 json!({
326 "key": n.key,
327 "title": node_title(ctx, app, &entries, &pages, &n.key),
328 "depth": n.depth,
329 "page": n.page,
330 })
331 })
332 .collect();
333 json!({
334 "open": open,
335 "section": shown,
336 "filter": filter,
337 "tree": tree,
338 "pages": settings_pages::describe(app),
339 })
340}
341
342fn node_title(
344 ctx: &egui::Context,
345 app: &AppHandle,
346 entries: &[SettingEntry],
347 pages: &[SettingsPage],
348 key: &str,
349) -> String {
350 match pages.iter().find(|p| p.id == key) {
351 Some(p) => p.title.clone(),
352 None => section_title(ctx, app, entries, key),
353 }
354}
355
356fn sections(entries: &[SettingEntry]) -> Vec<String> {
358 let mut out: Vec<String> = Vec::new();
359 for e in entries {
360 if !out.contains(&e.section) {
361 out.push(e.section.clone());
362 }
363 }
364 out.push(SHORTCUTS.into());
365 out
366}
367
368fn section_title(
370 ctx: &egui::Context,
371 app: &AppHandle,
372 entries: &[SettingEntry],
373 sec: &str,
374) -> String {
375 if sec == SHORTCUTS {
376 return strings::tr(ctx, &txt::SETTINGS_SHORTCUTS);
377 }
378 if sec == FONTS {
379 return strings::tr(ctx, &txt::SETTINGS_FONTS);
380 }
381 entries.iter().find(|e| e.section == sec).map_or_else(
382 || sec.to_string(),
383 |e| app.section_title(ctx, &e.owner, sec),
384 )
385}
386
387pub(crate) fn shown(ctx: &egui::Context, e: &SettingEntry) -> egui_pop_model::values::Descriptor {
390 let mut d = e.descriptor.clone();
391 let id = e.id.as_str();
392 d.label = strings::setting_label(ctx, id, &d.label);
393 d.description = strings::setting_description(ctx, id, &d.description);
394 d
395}
396
397pub(crate) fn fields(ctx: &egui::Context, app: &AppHandle, e: &SettingEntry) -> fuzzy::Fields {
401 let d = shown(ctx, e);
402 fuzzy::Fields::new()
403 .label(d.label)
404 .keyword(app.section_title(ctx, &e.owner, &e.section))
405 .description(d.description)
406}
407
408pub(crate) fn found(
410 ctx: &egui::Context,
411 app: &AppHandle,
412 e: &SettingEntry,
413 filter: &str,
414) -> Option<fuzzy::Found> {
415 fields(ctx, app, e).find(filter)
416}
417
418pub(crate) fn matches(
420 ctx: &egui::Context,
421 app: &AppHandle,
422 e: &SettingEntry,
423 filter: &str,
424) -> bool {
425 found(ctx, app, e, filter).is_some()
426}
427
428fn page_matches(
430 ctx: &egui::Context,
431 app: &AppHandle,
432 entries: &[SettingEntry],
433 all: &[SettingEntry],
434 page: &SettingsPage,
435 filter: &str,
436) -> bool {
437 let parent = page
438 .parent
439 .as_deref()
440 .map(|p| match app.settings_page(p) {
441 Some(parent) => parent.title,
442 None => section_title(ctx, app, entries, p),
443 })
444 .unwrap_or_default();
445 settings_pages::matches(ctx, page, &parent, all, filter)
446}
447
448fn show(ui: &mut Ui, app: &AppHandle) {
450 let Some(w) = app.service(&SETTINGS_WINDOW) else {
451 return;
452 };
453 if !w.is_open() {
454 let mut st = lock(&w.0);
457 if !crate::admin::is_open(app) {
458 st.capture = None;
459 st.capture_search = false;
460 st.pointer_capture = None;
461 }
462 app.capture_keys(st.capture.is_some() || st.capture_search || st.pointer_capture.is_some());
463 return;
464 }
465 let ctx = ui.ctx().clone();
466 let spec = OverlaySpec::new("egui_pop.settings", "Settings", Kind::Modal)
467 .width(860.0)
468 .keep_on_escape();
469 let mut open = true;
470 let mut close = false;
471 overlay::show(&ctx, &spec, &mut open, None, |ui| {
472 let _history = values::enter_history(&SETTINGS);
475 egui_pop_core::focus::scope(ui, SURFACE, &[], |ui| {
476 let t = Tokens::of(ui.ctx());
477 let capturing = w.capturing().is_some() || {
478 let st = lock(&w.0);
479 st.capture_search || st.pointer_capture.is_some()
480 };
481 if !capturing && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
482 close = true;
483 return;
484 }
485 let all = app.settings();
486 let pages = app.settings_pages();
487 let entries = settings_pages::unclaimed(&all, &pages);
489 let mut s = lock(&w.0);
490 ui.horizontal(|ui| {
491 let title = ui.heading(strings::tr(&ctx, &txt::SETTINGS_TITLE));
492 let search = ui
493 .add(
494 egui::TextEdit::singleline(&mut s.filter)
495 .hint_text(strings::tr(&ctx, &txt::SETTINGS_SEARCH_HINT))
496 .desired_width(360.0),
497 )
498 .labelled_by(title.id);
499 if search.changed() {
500 s.capture = None;
501 }
502 history(ui, app);
503 });
504 ui.separator();
505 let nodes = settings_pages::tree(§ions(&entries), &pages);
506 let secs: Vec<String> = nodes.iter().map(|n| n.key.clone()).collect();
507 let page_of = |key: &str| pages.iter().find(|p| p.id == key);
508 let current = s
509 .section
510 .clone()
511 .filter(|c| secs.contains(c))
512 .unwrap_or_else(|| secs[0].clone());
513 let filter = s.filter.trim().to_string();
514 let above = ui.cursor().min.y - ui.min_rect().top();
518 let left = egui_pop_core::overlay::modal_max_size(ui.ctx()).y - above;
519 let height = (ui.ctx().content_rect().height() * 0.6)
520 .max(240.0)
521 .min(left.max(0.0));
522 let form_width = (ui.max_rect().width() - 220.0).max(240.0);
525 ui.horizontal_top(|ui| {
526 ui.vertical(|ui| {
528 ui.set_width(200.0);
529 for node in &nodes {
530 let sec = &node.key;
531 let hits = if let Some(page) = page_of(sec) {
532 usize::from(
533 filter.is_empty()
534 || page_matches(&ctx, app, &entries, &all, page, &filter),
535 )
536 } else if sec == SHORTCUTS {
537 usize::from(
538 filter.is_empty()
539 || !shortcut_rows(&ctx, app, &filter, None, false).is_empty(),
540 )
541 } else {
542 entries
543 .iter()
544 .filter(|e| {
545 &e.section == sec
546 && (filter.is_empty() || matches(&ctx, app, e, &filter))
547 })
548 .count()
549 };
550 let enabled = filter.is_empty() || hits > 0;
551 let item = widgets::SelectableRow::new(
552 filter.is_empty() && *sec == current,
553 node_title(&ctx, app, &entries, &pages, sec),
554 );
555 let r = if node.depth > 0 || sec == FONTS {
558 ui.horizontal(|ui| {
559 ui.add_space(t.space.l);
560 ui.add_enabled(enabled, item)
561 })
562 .inner
563 } else {
564 ui.add_enabled(enabled, item)
565 };
566 if r.clicked() {
567 s.section = Some(sec.clone());
568 s.filter.clear();
569 }
570 }
571 });
572 ui.separator();
573 ui.scroll_area(
574 egui::ScrollArea::vertical()
575 .id_salt("egui_pop.settings.form")
576 .max_height(height)
577 .max_width(form_width)
578 .auto_shrink([false, false]),
579 |ui| {
580 ui.set_width(form_width - 16.0);
581 ui.vertical(|ui| {
584 if filter.is_empty() {
585 ui.strong(node_title(&ctx, app, &entries, &pages, ¤t));
586 ui.add_space(t.space.s);
587 if let Some(page) = page_of(¤t) {
588 settings_pages::header(ui, app, page);
589 ui.add_space(t.space.s);
590 settings_pages::draw(ui, app, &page.id);
591 } else if current == SHORTCUTS {
592 let st = &mut *s;
593 shortcuts(ui, app, st, "");
594 } else if current == FONTS {
595 fonts_page(ui, app, &entries);
596 } else {
597 for e in entries.iter().filter(|e| e.section == current) {
598 row(ui, app, e);
599 }
600 }
601 } else {
602 let mut any = false;
603 let mut open_page = None;
604 for sec in &secs {
605 if let Some(page) = page_of(sec) {
606 if page_matches(&ctx, app, &entries, &all, page, &filter) {
607 any = true;
608 if settings_pages::search_hit(
609 ui, app, page, &all, &filter,
610 ) {
611 open_page = Some(page.id.clone());
612 }
613 ui.add_space(t.space.m);
614 }
615 continue;
616 }
617 if sec == SHORTCUTS {
618 if !shortcut_rows(&ctx, app, &filter, None, false)
619 .is_empty()
620 {
621 any = true;
622 ui.strong(section_title(&ctx, app, &entries, sec));
623 let st = &mut *s;
624 shortcuts(ui, app, st, &filter);
625 }
626 continue;
627 }
628 let mut list: Vec<(fuzzy::Found, &SettingEntry)> = entries
631 .iter()
632 .filter(|e| &e.section == sec)
633 .filter_map(|e| {
634 found(&ctx, app, e, &filter).map(|f| (f, e))
635 })
636 .collect();
637 list.sort_by_key(|(f, _)| *f);
638 let list: Vec<&SettingEntry> =
639 list.into_iter().map(|(_, e)| e).collect();
640 if list.is_empty() {
641 continue;
642 }
643 any = true;
644 ui.strong(section_title(&ctx, app, &entries, sec));
645 for e in list {
646 row(ui, app, e);
647 }
648 ui.add_space(t.space.m);
649 }
650 if !any {
651 ui.weak(strings::tr(&ctx, &txt::NOTHING_MATCHES));
652 }
653 if let Some(id) = open_page {
654 s.section = Some(id);
655 s.filter.clear();
656 }
657 }
658 });
659 },
660 );
661 });
662 app.capture_keys(
663 s.capture.is_some() || s.capture_search || s.pointer_capture.is_some(),
664 );
665 });
666 });
667 if close || !open {
668 w.close();
669 app.capture_keys(false);
670 app.close_overlay(&ctx, spec.id, overlay::Closing::Owner);
671 }
672}
673
674fn history(ui: &mut Ui, app: &AppHandle) {
677 let (undo, redo) = {
678 let line = crate::history::line(app, &SETTINGS).unwrap_or_default();
679 let ctx = ui.ctx();
680 (
681 line.head()
682 .map(|st| crate::history::label_text(ctx, &st.label)),
683 line.next()
684 .map(|st| crate::history::label_text(ctx, &st.label)),
685 )
686 };
687 let ctx = ui.ctx().clone();
688 for (label, step, redo, with_step, nothing, name) in [
689 (
690 &txt::SETTINGS_UNDO,
691 undo,
692 false,
693 &txt::SETTINGS_UNDO_STEP,
694 &txt::SETTINGS_NOTHING_TO_UNDO,
695 &txt::SETTINGS_UNDO_NAME,
696 ),
697 (
698 &txt::SETTINGS_REDO,
699 redo,
700 true,
701 &txt::SETTINGS_REDO_STEP,
702 &txt::SETTINGS_NOTHING_TO_REDO,
703 &txt::SETTINGS_REDO_NAME,
704 ),
705 ] {
706 let r = ui
707 .add_enabled(
708 step.is_some(),
709 egui::Button::new(strings::tr(&ctx, label)).small(),
710 )
711 .on_hover_text(match &step {
712 Some(st) => strings::tr_args(&ctx, with_step, &[("change", st)]),
713 None => strings::tr(&ctx, nothing),
714 });
715 a11y::name(&r, egui::Role::Button, &strings::tr(&ctx, name));
716 if r.clicked() {
717 if redo {
718 crate::history::redo_in(app, &SETTINGS, &Origin::User);
719 } else {
720 crate::history::undo_in(app, &SETTINGS, &Origin::User);
721 }
722 }
723 }
724}
725
726pub fn setting_row(ui: &mut Ui, app: &AppHandle, id: &egui_pop_model::ids::SettingId) -> bool {
731 if crate::admin::setting_row(ui, app, id) {
732 return true;
733 }
734 match app.settings().into_iter().find(|e| e.id == *id) {
735 Some(e) => {
736 row(ui, app, &e);
737 true
738 }
739 None => false,
740 }
741}
742
743pub(crate) fn row(ui: &mut Ui, app: &AppHandle, e: &SettingEntry) {
746 let store = app.store();
747 let t = Tokens::of(ui.ctx());
748 let ctx = ui.ctx().clone();
749 let d = shown(&ctx, e);
750 ui.horizontal(|ui| {
751 let reset_width = 64.0;
752 let id = e.id.as_str();
753 ui.allocate_ui(
754 egui::vec2(ui.available_width() - reset_width - t.space.m, 0.0),
755 |ui| {
756 param::param_shown(ui, &d, Mode::Bound(&store, &e.path), &|c| {
757 strings::setting_choice(&ctx, id, c)
758 })
759 },
760 );
761 setting_reset_button(ui, app, e, &d.label);
762 });
763 if !d.description.is_empty() {
764 crate::links::Inline::new(&d.description)
765 .weak()
766 .show(ui, app);
767 }
768 ui.add_space(t.space.s);
769}
770
771fn is_gesture(id: &CommandId) -> bool {
773 egui_pop_model::pointer::gesture_spec(id).is_some()
774}
775
776fn setting_reset_button(ui: &mut Ui, app: &AppHandle, e: &SettingEntry, label: &str) {
778 let store = app.store();
779 let changed = lock(&store)
780 .get(&e.path)
781 .is_some_and(|x| x.value != x.descriptor.default);
782 let reset = strings::tr(ui.ctx(), &RESET);
783 let setting = [("setting", label)];
784 let r = ui
785 .add_enabled(changed, egui::Button::new(&reset).small())
786 .on_disabled_hover_text(strings::tr_args(
787 ui.ctx(),
788 &txt::SETTINGS_AT_DEFAULT,
789 &setting,
790 ));
791 a11y::name(
792 &r,
793 egui::Role::Button,
794 &strings::tr_args(ui.ctx(), &txt::SETTINGS_RESET_SETTING, &setting),
795 );
796 if r.clicked() {
797 let _ = lock(&store)
798 .set(Set::new(&e.path, Change::Reset, Origin::User).by(&OwnerId::FRAMEWORK));
799 }
800}
801
802fn fonts_page(ui: &mut Ui, app: &AppHandle, entries: &[SettingEntry]) {
806 let ctx = ui.ctx().clone();
807 let t = Tokens::of(&ctx);
808 for e in entries.iter().filter(|e| e.section == FONTS) {
809 match Role::ALL
810 .into_iter()
811 .find(|r| crate::text::font_setting(*r) == e.id)
812 {
813 Some(role) => family_row(ui, app, e, role),
814 None => row(ui, app, e),
815 }
816 }
817 ui.add_space(t.space.m);
818 ui.strong(strings::tr(&ctx, &txt::FONTS_PREVIEW));
819 egui::Frame::new()
820 .fill(t.surface.raised)
821 .stroke(egui::Stroke::new(1.0, t.border.default))
822 .corner_radius(egui::CornerRadius::same(
823 t.radius.widget.round().clamp(0.0, 255.0) as u8,
824 ))
825 .inner_margin(egui::Margin::same(t.space.m.round().clamp(0.0, 127.0) as i8))
826 .show(ui, |ui| {
827 ui.set_width(ui.available_width());
828 fonts::with_preview(ui, |ui| {
829 ui.heading(strings::tr(&ctx, &txt::THEME_EDITOR_SAMPLE_HEADING));
830 crate::theme_editor::font_sample(ui);
831 });
832 ui.add_space(t.space.s);
833 ui.label(strings::tr(&ctx, &txt::FONTS_NUMBERS));
834 let cell = egui::vec2(120.0, ui.spacing().interact_size.y);
835 for n in ["0.00", "1.11", "-1234.56", "88.88"] {
836 ui.allocate_ui_with_layout(
837 cell,
838 egui::Layout::right_to_left(egui::Align::Center),
839 |ui| {
840 ui.label(fonts::number_job(&ctx, n, t.font.body, t.text.default));
841 },
842 );
843 }
844 });
845}
846
847pub(crate) fn origin_name(ctx: &egui::Context, origin: FaceOrigin) -> String {
850 strings::tr(
851 ctx,
852 match origin {
853 FaceOrigin::Bundled => &txt::FONTS_ORIGIN_BUNDLED,
854 FaceOrigin::Registered => &txt::FONTS_ORIGIN_REGISTERED,
855 FaceOrigin::File => &txt::FONTS_ORIGIN_FILE,
856 FaceOrigin::System => &txt::FONTS_ORIGIN_SYSTEM,
857 },
858 )
859}
860
861const FONT_PREVIEW: Slot<[Option<String>; 2]> = Slot::opaque("api.settings.font_preview");
864
865fn family_row(ui: &mut Ui, app: &AppHandle, e: &SettingEntry, role: Role) {
869 let ctx = ui.ctx().clone();
870 let t = Tokens::of(&ctx);
871 let d = shown(&ctx, e);
872 let current = crate::text::font(app, role);
873 let themes = strings::tr(&ctx, &txt::FONTS_THEMES);
874 let mut pick: Option<Option<String>> = None;
875 let mut rested: Option<String> = None;
879 let mut over_row = false;
880 ui.horizontal(|ui| {
881 let reset_width = 64.0;
882 ui.allocate_ui(
883 egui::vec2(ui.available_width() - reset_width - t.space.m, 0.0),
884 |ui| {
885 let l = ui.label(&d.label);
886 let combo = widgets::combo_box(("egui_pop.fonts", e.id.as_str()))
887 .selected_text(current.clone().unwrap_or_else(|| themes.clone()));
888 ui.combo_box(combo, |ui| {
889 if ui.selectable_label(current.is_none(), &themes).clicked() {
890 pick = Some(None);
891 }
892 let families = fonts::families(&ctx)
893 .into_iter()
894 .filter(|f| role == Role::Ui || f.monospace);
895 for f in families {
896 let mut text = egui::RichText::new(&f.name);
897 if f.origin != FaceOrigin::System
900 && let Some(family) =
901 fonts::specimen(&ctx, &f.name, fonts::Weight::REGULAR)
902 && fonts::uncovered(
903 &ctx,
904 &egui::FontId::new(t.font.body, family.clone()),
905 &f.name,
906 )
907 .is_empty()
908 {
909 text = text.family(family);
910 }
911 let r = ui
912 .selectable_label(current.as_deref() == Some(f.name.as_str()), text)
913 .on_hover_text(origin_name(&ctx, f.origin));
914 over_row |= r.hovered();
915 if crate::theme_editor::rests_on(&r) {
916 rested = Some(f.name.clone());
917 }
918 if r.clicked() {
919 pick = Some(Some(f.name.clone()));
920 }
921 }
922 })
923 .response
924 .labelled_by(l.id);
925 },
926 );
927 setting_reset_button(ui, app, e, &d.label);
928 });
929 let at = usize::from(role == Role::Mono);
930 let mut previewed = FONT_PREVIEW.get_or_default(&ctx);
931 let want = if let Some(p) = pick {
932 crate::text::set_font(app, role, p.as_deref());
933 None
934 } else if rested.is_some() {
935 rested
936 } else if !over_row {
937 None
938 } else {
939 previewed[at].clone()
940 };
941 if previewed[at] != want {
944 fonts::set_preview(&ctx, role, want.clone().map(|n| vec![n]));
945 previewed[at] = want;
946 FONT_PREVIEW.set(&ctx, previewed);
947 }
948 if !d.description.is_empty() {
949 crate::links::Inline::new(&d.description)
950 .weak()
951 .show(ui, app);
952 }
953 ui.weak(strings::tr(&ctx, &txt::FONTS_PICKER_HINT));
954 ui.add_space(t.space.s);
955}
956
957fn shortcut_rows(
962 ctx: &egui::Context,
963 app: &AppHandle,
964 filter: &str,
965 keys: Option<&str>,
966 pointer_only: bool,
967) -> Vec<(CommandSpec, String)> {
968 let mut rows: Vec<(CommandSpec, String)> = app
969 .commands()
970 .into_iter()
971 .map(|(s, _)| s)
972 .filter(|s| s.palette || !app.keys_for(&s.id).is_empty() || is_gesture(&s.id))
973 .filter(|s| !pointer_only || is_gesture(&s.id))
974 .map(|s| {
975 let label = strings::tr_args(
976 ctx,
977 &txt::COMMAND_LABEL,
978 &[
979 ("category", &strings::category(ctx, &s.category)),
980 ("title", &command_title(ctx, &s)),
981 ],
982 );
983 (s, label)
984 })
985 .filter(|(s, _)| keys.is_none_or(|k| app.keys_for(&s.id).iter().any(|x| x == k)))
986 .filter(|(s, label)| {
987 filter.is_empty()
988 || filter.split_whitespace().all(|w| {
989 fuzzy::score(w, label).is_some()
990 || app
991 .keys_for(&s.id)
992 .iter()
993 .any(|k| k.to_lowercase().contains(&w.to_lowercase()))
994 })
995 })
996 .collect();
997 rows.sort_by(|a, b| a.1.cmp(&b.1));
998 rows
999}
1000
1001fn command_title(ctx: &egui::Context, spec: &CommandSpec) -> String {
1003 strings::command_title(ctx, spec.id.as_str(), &spec.title)
1004}
1005
1006fn title_of(ctx: &egui::Context, app: &AppHandle, id: &CommandId) -> String {
1008 app.command(id)
1009 .map_or_else(|| id.to_string(), |s| command_title(ctx, &s))
1010}
1011
1012fn scope_name(ctx: &egui::Context, app: &AppHandle, scope: &KeyScope) -> Option<String> {
1016 match scope {
1017 KeyScope::Global | KeyScope::System => None,
1018 KeyScope::Window(id) => {
1019 let open = app.windows().into_iter().find(|w| w.id.as_str() == id);
1020 let main = open
1021 .as_ref()
1022 .map_or(id == crate::windows::WindowId::MAIN, |w| w.main);
1023 Some(if main {
1024 strings::tr(ctx, &txt::SHORTCUTS_SCOPE_MAIN_WINDOW)
1025 } else {
1026 let title = open.map_or_else(|| id.clone(), |w| w.title);
1027 strings::tr_args(ctx, &txt::SHORTCUTS_SCOPE_WINDOW, &[("window", &title)])
1028 })
1029 }
1030 KeyScope::Panel(id) => {
1031 let title =
1032 PanelId::new(id.clone()).map_or_else(|_| id.clone(), |p| app.panel_title(ctx, &p));
1033 Some(strings::tr_args(
1034 ctx,
1035 &txt::SHORTCUTS_SCOPE_PANEL,
1036 &[("panel", &title)],
1037 ))
1038 }
1039 KeyScope::Surface(name) => Some(name.clone()),
1040 }
1041}
1042
1043fn system_note(ctx: &egui::Context, app: &AppHandle, id: &CommandId) -> Option<(String, bool)> {
1046 use crate::system_keys::{KeyStatus, SYSTEM_KEYS, Support};
1047 let keys: Vec<String> = app
1048 .system_bindings()
1049 .into_iter()
1050 .filter(|b| matches!(&b.action, Action::Run(c) if c == id))
1051 .map(|b| b.keys.to_string())
1052 .collect();
1053 if keys.is_empty() {
1054 return None;
1055 }
1056 let shown = keys.join(", ");
1057 let Some(service) = app.service(&SYSTEM_KEYS) else {
1058 return Some((
1059 strings::tr_args(ctx, &txt::SHORTCUTS_SYSTEM_NO_PLUGIN, &[("keys", &shown)]),
1060 false,
1061 ));
1062 };
1063 if let Support::Unavailable { reason } = service.support() {
1064 return Some((
1065 strings::tr_args(
1066 ctx,
1067 &txt::SHORTCUTS_SYSTEM_UNAVAILABLE,
1068 &[("keys", &shown), ("reason", &reason)],
1069 ),
1070 false,
1071 ));
1072 }
1073 for k in &keys {
1075 match service.status(k) {
1076 Some(KeyStatus::Registered) => {}
1077 Some(KeyStatus::Failed(reason)) => {
1078 return Some((
1079 strings::tr_args(
1080 ctx,
1081 &txt::SHORTCUTS_SYSTEM_FAILED,
1082 &[("keys", k), ("reason", &reason)],
1083 ),
1084 false,
1085 ));
1086 }
1087 Some(KeyStatus::Pending) | None => {
1088 return Some((
1089 strings::tr_args(ctx, &txt::SHORTCUTS_SYSTEM_PENDING, &[("keys", k)]),
1090 true,
1091 ));
1092 }
1093 }
1094 }
1095 Some((
1096 strings::tr_args(ctx, &txt::SHORTCUTS_SYSTEM_ON, &[("keys", &shown)]),
1097 true,
1098 ))
1099}
1100
1101fn pressed_keys(ui: &Ui) -> Option<(Key, egui::Modifiers)> {
1103 ui.input(|i| {
1104 i.events.iter().find_map(|e| match e {
1105 egui::Event::Key {
1106 key,
1107 pressed: true,
1108 modifiers,
1109 ..
1110 } => Some((*key, *modifiers)),
1111 _ => None,
1112 })
1113 })
1114}
1115
1116fn shortcuts(ui: &mut Ui, app: &AppHandle, st: &mut State, filter: &str) {
1118 shortcuts_of(ui, app, st, filter, None);
1119}
1120
1121fn shortcuts_of(ui: &mut Ui, app: &AppHandle, st: &mut State, filter: &str, pointer: Option<bool>) {
1124 if let Some(on) = pointer {
1125 st.pointer_only = on;
1126 }
1127 let t = Tokens::of(ui.ctx());
1128 let ctx = ui.ctx().clone();
1129 ui.horizontal(|ui| {
1131 if st.capture_search {
1132 ui.colored_label(
1133 t.accent.default,
1134 strings::tr(&ctx, &txt::SHORTCUTS_PRESS_TO_SEARCH),
1135 );
1136 match pressed_keys(ui) {
1137 Some((Key::Escape, m)) if !m.any() => st.capture_search = false,
1138 Some((key, modifiers)) => {
1139 st.key_filter = Some(Keys(vec![chord_of(key, modifiers)]).to_string());
1140 st.capture_search = false;
1141 }
1142 None => {}
1143 }
1144 ui.input_mut(|i| {
1145 i.events
1146 .retain(|e| !matches!(e, egui::Event::Key { .. } | egui::Event::Text(_)))
1147 });
1148 } else if ui
1149 .button(strings::tr(&ctx, &txt::SHORTCUTS_SEARCH_BY_KEY))
1150 .clicked()
1151 {
1152 st.capture_search = true;
1153 st.capture = None;
1154 }
1155 if let Some(k) = st.key_filter.clone() {
1156 ui.label(strings::tr_args(
1157 &ctx,
1158 &txt::SHORTCUTS_BOUND_TO,
1159 &[("keys", &k)],
1160 ));
1161 let clear = ui.small_button(strings::tr(&ctx, &txt::SHORTCUTS_SHOW_ALL));
1162 if clear.clicked() {
1163 st.key_filter = None;
1164 }
1165 }
1166 });
1167 let by_scope = app.key_conflicts_by_scope();
1169 if !by_scope.is_empty() {
1170 ui.add_space(t.space.s);
1171 ui.strong(strings::tr(&ctx, &txt::SHORTCUTS_CONFLICTS));
1172 for (scope, list) in &by_scope {
1173 for (lose, win) in list {
1174 let name = |b: &egui_pop_model::keymap::Binding| match &b.action {
1175 Action::Run(c) => title_of(&ctx, app, c),
1176 _ => String::new(),
1177 };
1178 ui.colored_label(
1179 t.status.warning,
1180 strings::tr_args(
1181 &ctx,
1182 &txt::SHORTCUTS_CONFLICT_IN_SCOPE,
1183 &[
1184 ("keys", &lose.keys.to_string()),
1185 ("scope", &scope.to_string()),
1186 ("loser", &name(lose)),
1187 ("winner", &name(win)),
1188 ],
1189 ),
1190 );
1191 }
1192 }
1193 ui.add_space(t.space.s);
1194 }
1195 if app.workspace_keys_offered() {
1198 ui.horizontal(|ui| {
1199 ui.label(strings::tr(&ctx, &txt::SHORTCUTS_TARGET));
1200 widgets::radio_value(
1201 ui,
1202 &mut st.workspace_target,
1203 false,
1204 strings::tr(&ctx, &txt::SHORTCUTS_TARGET_USER),
1205 );
1206 widgets::radio_value(
1207 ui,
1208 &mut st.workspace_target,
1209 true,
1210 strings::tr(&ctx, &txt::SHORTCUTS_TARGET_WORKSPACE),
1211 );
1212 });
1213 ui.add_space(t.space.s);
1214 } else {
1215 st.workspace_target = false;
1216 }
1217 let target = if st.workspace_target {
1218 Layer::Workspace
1219 } else {
1220 Layer::User
1221 };
1222 pointer_header(ui, app, st, pointer.is_none());
1223 pointer_pad(ui, app, st, target);
1224 let pointer_only = st.pointer_only;
1225 let admin = app.service(&ADMIN);
1228 let mark = admin.as_ref().and_then(|a| a.marked());
1229 if let Some(m) = &mark
1230 && st.key_filter.is_some()
1231 && !shortcut_rows(&ctx, app, filter, st.key_filter.as_deref(), pointer_only)
1232 .iter()
1233 .any(|(s, _)| s.id.as_str() == m)
1234 {
1235 st.key_filter = None;
1236 }
1237 let mut pointer_capture: Option<CommandId> = None;
1238 let capture = &mut st.capture;
1239 let key_filter = st.key_filter.clone();
1240 if let Some(c) = capture.clone() {
1241 let title = app
1242 .command(&c)
1243 .map(|s| command_title(&ctx, &s))
1244 .unwrap_or_default();
1245 ui.colored_label(
1246 t.accent.default,
1247 strings::tr_args(&ctx, &txt::SHORTCUTS_PRESS_NEW_KEYS, &[("command", &title)]),
1248 );
1249 match pressed_keys(ui) {
1250 Some((Key::Escape, m)) if !m.any() => *capture = None,
1251 Some((Key::Backspace, m)) if !m.any() => {
1252 app.rebind_in(target, c, None);
1253 *capture = None;
1254 }
1255 Some((key, modifiers)) => {
1256 let keys = Keys(vec![chord_of(key, modifiers)]).to_string();
1257 app.rebind_in(target, c, Some(keys));
1258 *capture = None;
1259 }
1260 None => {}
1261 }
1262 ui.input_mut(|i| {
1263 i.events
1264 .retain(|e| !matches!(e, egui::Event::Key { .. } | egui::Event::Text(_)))
1265 });
1266 ui.add_space(t.space.s);
1267 }
1268 let conflicts = app.key_conflicts();
1269 let rows = shortcut_rows(&ctx, app, filter, key_filter.as_deref(), pointer_only);
1270 let marked = mark
1271 .as_deref()
1272 .and_then(|m| rows.iter().position(|(s, _)| s.id.as_str() == m));
1273 let selection = t.accent.default.gamma_multiply(0.25);
1274 egui::Grid::new("egui_pop.shortcuts")
1275 .num_columns(4)
1276 .with_row_color(move |i, style| {
1277 if marked == Some(i) {
1278 Some(selection)
1279 } else if i % 2 == 1 {
1280 Some(style.visuals.faint_bg_color)
1281 } else {
1282 None
1283 }
1284 })
1285 .spacing([t.space.m, t.space.xs])
1286 .show(ui, |ui| {
1287 for (i, (spec, label)) in rows.into_iter().enumerate() {
1288 let name = ui.label(&label);
1289 if marked == Some(i) {
1290 let text = label.clone();
1292 name.widget_info(move || {
1293 let mut info = egui::WidgetInfo::labeled(egui::Role::Label, true, &text);
1294 info.selected = Some(true);
1295 info
1296 });
1297 if admin.as_ref().is_some_and(|a| a.take_key(spec.id.as_str())) {
1298 name.scroll_to_me(Some(egui::Align::Center));
1299 }
1300 }
1301 let keys = app.keys_for(&spec.id);
1302 let gesture = is_gesture(&spec.id);
1303 let sources = app.key_sources(&spec.id);
1306 if gesture {
1307 gesture_keys(ui, app, &ctx, &spec.id, &label, &keys, target, name.id);
1308 } else {
1309 ui.monospace(if sources.is_empty() {
1310 "—".to_string()
1311 } else {
1312 sources
1313 .iter()
1314 .map(|b| {
1315 let keys = match app.key_source_name(&ctx, b) {
1316 Some(source) => strings::tr_args(
1317 &ctx,
1318 &txt::SHORTCUTS_KEY_FROM,
1319 &[("keys", &b.keys.to_string()), ("source", &source)],
1320 ),
1321 None => b.keys.to_string(),
1322 };
1323 match scope_name(&ctx, app, &b.options.scope) {
1324 Some(scope) => strings::tr_args(
1325 &ctx,
1326 &txt::SHORTCUTS_KEY_IN,
1327 &[("keys", &keys), ("scope", &scope)],
1328 ),
1329 None => keys,
1330 }
1331 })
1332 .collect::<Vec<_>>()
1333 .join(", ")
1334 })
1335 .labelled_by(name.id);
1336 }
1337 let clash = conflicts.iter().find_map(|(lose, win)| {
1339 let mine = |b: &egui_pop_model::keymap::Binding| {
1340 matches!(&b.action, Action::Run(c) if *c == spec.id)
1341 };
1342 let other = |b: &egui_pop_model::keymap::Binding| match &b.action {
1343 Action::Run(c) => title_of(&ctx, app, c),
1344 _ => String::new(),
1345 };
1346 if mine(lose) {
1347 Some(strings::tr_args(
1348 &ctx,
1349 &txt::SHORTCUTS_GOES_TO,
1350 &[("keys", &lose.keys.to_string()), ("command", &other(win))],
1351 ))
1352 } else if mine(win) {
1353 Some(strings::tr_args(
1354 &ctx,
1355 &txt::SHORTCUTS_ALSO_BOUND,
1356 &[("keys", &win.keys.to_string()), ("command", &other(lose))],
1357 ))
1358 } else {
1359 None
1360 }
1361 });
1362 let system = system_note(&ctx, app, &spec.id)
1363 .or_else(|| gesture.then(|| alt_note(&ctx, &keys)).flatten());
1364 match (clash, system) {
1365 (None, None) => {
1366 ui.label("");
1367 }
1368 (clash, system) => {
1369 ui.vertical(|ui| {
1370 if let Some(c) = clash {
1371 ui.colored_label(t.status.warning, c);
1372 }
1373 if let Some((text, ok)) = system {
1374 if ok {
1375 ui.label(text);
1376 } else {
1377 ui.colored_label(t.status.warning, text);
1378 }
1379 }
1380 });
1381 }
1382 }
1383 ui.horizontal(|ui| {
1384 let command = [("command", label.as_str())];
1385 if gesture {
1386 let add = ui.small_button(strings::tr(&ctx, &txt::SHORTCUTS_POINTER_ADD));
1387 a11y::name(
1388 &add,
1389 egui::Role::Button,
1390 &strings::tr_args(&ctx, &txt::SHORTCUTS_POINTER_ADD_NAME, &command),
1391 );
1392 if add.clicked() {
1393 pointer_capture = Some(spec.id.clone());
1394 }
1395 reset_button(ui, app, &ctx, target, &spec.id, &command);
1396 return;
1397 }
1398 let change = ui.small_button(strings::tr(&ctx, &txt::SHORTCUTS_CHANGE));
1399 a11y::name(
1400 &change,
1401 egui::Role::Button,
1402 &strings::tr_args(&ctx, &txt::SHORTCUTS_CHANGE_NAME, &command),
1403 );
1404 if change.clicked() {
1405 *capture = Some(spec.id.clone());
1406 }
1407 if !keys.is_empty() {
1408 let none = ui.small_button(strings::tr(&ctx, &txt::SHORTCUTS_NO_KEY));
1409 a11y::name(
1410 &none,
1411 egui::Role::Button,
1412 &strings::tr_args(&ctx, &txt::SHORTCUTS_NO_KEY_NAME, &command),
1413 );
1414 if none.clicked() {
1415 app.rebind_in(target, spec.id.clone(), None);
1416 }
1417 }
1418 if app.rebound_in(target, &spec.id) {
1419 let reset = ui.small_button(strings::tr(ui.ctx(), &RESET));
1420 a11y::name(
1421 &reset,
1422 egui::Role::Button,
1423 &strings::tr_args(&ctx, &txt::SHORTCUTS_DEFAULT_NAME, &command),
1424 );
1425 if reset.clicked() {
1426 app.reset_keys_in(target, spec.id.clone());
1427 }
1428 }
1429 });
1430 ui.end_row();
1431 }
1432 });
1433 if let Some(id) = pointer_capture {
1434 st.pointer_capture = Some((id, None));
1435 st.capture = None;
1436 }
1437 dormant_keys(ui, app, filter, key_filter.as_deref());
1438 widget_uses(ui, filter, key_filter.as_deref());
1439}
1440
1441fn dormant_keys(ui: &mut Ui, app: &AppHandle, filter: &str, key_filter: Option<&str>) {
1446 let ctx = ui.ctx().clone();
1447 let t = Tokens::of(&ctx);
1448 let needle = filter.trim().to_lowercase();
1449 let rows: Vec<_> = app
1450 .dormant_keys()
1451 .into_iter()
1452 .filter(|k| key_filter.is_none_or(|f| k.binding.keys.to_string() == f))
1453 .filter(|k| {
1454 needle.is_empty()
1455 || k.binding
1456 .action
1457 .to_string()
1458 .to_lowercase()
1459 .contains(&needle)
1460 || k.plugin_title.to_lowercase().contains(&needle)
1461 || k.binding.keys.to_string().to_lowercase().contains(&needle)
1462 })
1463 .collect();
1464 if rows.is_empty() {
1465 return;
1466 }
1467 ui.add_space(t.space.m);
1468 ui.strong(strings::tr(&ctx, &txt::SHORTCUTS_DORMANT));
1469 ui.label(strings::tr(&ctx, &txt::SHORTCUTS_DORMANT_NOTE));
1470 egui::Grid::new("egui_pop.shortcuts.dormant")
1471 .num_columns(3)
1472 .striped(true)
1473 .spacing([t.space.m, t.space.xs])
1474 .show(ui, |ui| {
1475 for k in &rows {
1476 let name = ui.label(k.binding.action.to_string());
1478 let keys = k.binding.keys.to_string();
1479 ui.monospace(match app.key_source_name(&ctx, &k.binding) {
1480 Some(source) => strings::tr_args(
1481 &ctx,
1482 &txt::SHORTCUTS_KEY_FROM,
1483 &[("keys", &keys), ("source", &source)],
1484 ),
1485 None => keys,
1486 })
1487 .labelled_by(name.id);
1488 ui.weak(strings::tr_args(
1489 &ctx,
1490 &txt::SHORTCUTS_DORMANT_PLUGIN,
1491 &[("plugin", &k.plugin_title)],
1492 ));
1493 ui.end_row();
1494 }
1495 });
1496}
1497
1498fn widget_uses(ui: &mut Ui, filter: &str, key_filter: Option<&str>) {
1501 let ctx = ui.ctx().clone();
1502 let t = Tokens::of(&ctx);
1503 let needle = filter.trim().to_lowercase();
1504 let uses: Vec<_> = egui_pop_core::pointer::claim::uses(&ctx)
1505 .into_iter()
1506 .filter(|u| key_filter.is_none_or(|k| k.eq_ignore_ascii_case(&u.gesture)))
1507 .filter(|u| {
1508 needle.is_empty()
1509 || u.widget.to_lowercase().contains(&needle)
1510 || u.does.to_lowercase().contains(&needle)
1511 })
1512 .collect();
1513 if uses.is_empty() {
1514 return;
1515 }
1516 ui.add_space(t.space.m);
1517 ui.strong(strings::tr(&ctx, &txt::SHORTCUTS_WIDGET_USES));
1518 ui.label(strings::tr(&ctx, &txt::SHORTCUTS_WIDGET_USES_NOTE));
1519 egui::Grid::new("egui_pop.shortcuts.widget_uses")
1520 .num_columns(3)
1521 .striped(true)
1522 .spacing([t.space.m, t.space.xs])
1523 .show(ui, |ui| {
1524 for u in &uses {
1525 let name = ui.label(&u.widget);
1526 ui.monospace(&u.gesture).labelled_by(name.id);
1527 ui.label(&u.does);
1528 ui.end_row();
1529 }
1530 });
1531}
1532
1533fn reset_button(
1535 ui: &mut Ui,
1536 app: &AppHandle,
1537 ctx: &egui::Context,
1538 target: Layer,
1539 id: &CommandId,
1540 command: &[(&str, &str)],
1541) {
1542 if app.rebound_in(target, id) {
1543 let reset = ui.small_button(strings::tr(ctx, &RESET));
1544 a11y::name(
1545 &reset,
1546 egui::Role::Button,
1547 &strings::tr_args(ctx, &txt::SHORTCUTS_DEFAULT_NAME, command),
1548 );
1549 if reset.clicked() {
1550 app.reset_keys_in(target, id.clone());
1551 }
1552 }
1553}
1554
1555fn pointer_header(ui: &mut Ui, app: &AppHandle, st: &mut State, filter: bool) {
1558 let ctx = ui.ctx().clone();
1559 let profile = crate::pointer::profile(app);
1560 let changed = crate::pointer::overrides(app).len();
1561 ui.horizontal(|ui| {
1562 ui.label(if changed == 0 {
1563 strings::tr_args(
1564 &ctx,
1565 &txt::SHORTCUTS_POINTER_PROFILE,
1566 &[("profile", &profile.title)],
1567 )
1568 } else {
1569 strings::tr_with(
1570 &ctx,
1571 &txt::SHORTCUTS_POINTER_PROFILE_CHANGED,
1572 &[
1573 ("profile", Arg::Str(&profile.title)),
1574 ("count", changed.into()),
1575 ],
1576 )
1577 });
1578 if filter {
1579 widgets::checkbox(
1580 ui,
1581 &mut st.pointer_only,
1582 strings::tr(&ctx, &txt::SHORTCUTS_POINTER_ONLY),
1583 );
1584 }
1585 });
1586}
1587
1588#[allow(
1590 clippy::too_many_arguments,
1591 reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1592)]
1593fn gesture_keys(
1594 ui: &mut Ui,
1595 app: &AppHandle,
1596 ctx: &egui::Context,
1597 id: &CommandId,
1598 label: &str,
1599 keys: &[String],
1600 target: Layer,
1601 name: egui::Id,
1602) {
1603 ui.horizontal_wrapped(|ui| {
1604 if keys.is_empty() {
1605 ui.monospace("—").labelled_by(name);
1606 }
1607 for k in keys {
1608 ui.monospace(k).labelled_by(name);
1609 let remove = ui.add(
1611 egui_pop_core::icon::Icon::Close
1612 .size(egui_pop_core::icon::Size::Inline)
1613 .label(&strings::tr_args(
1614 ctx,
1615 &txt::SHORTCUTS_POINTER_REMOVE_NAME,
1616 &[("keys", k), ("command", label)],
1617 ))
1618 .sense_click(),
1619 );
1620 if remove.clicked() {
1621 let rest: Vec<&str> = keys
1622 .iter()
1623 .filter(|x| *x != k)
1624 .map(String::as_str)
1625 .collect();
1626 app.rebind_gestures(target, id.clone(), &rest);
1627 }
1628 }
1629 });
1630}
1631
1632fn alt_note(ctx: &egui::Context, keys: &[String]) -> Option<(String, bool)> {
1635 if !cfg!(target_os = "linux") {
1636 return None;
1637 }
1638 let risky = keys.iter().filter_map(|k| Keys::parse(k).ok()).any(|k| {
1639 k.pointer().is_some_and(|(c, p)| {
1640 c.alt && matches!(p, Pointer::Wheel | Pointer::Scroll | Pointer::Drag(_))
1641 })
1642 });
1643 risky.then(|| (strings::tr(ctx, &txt::SHORTCUTS_POINTER_ALT), false))
1644}
1645
1646fn pointer_pad(ui: &mut Ui, app: &AppHandle, st: &mut State, target: Layer) {
1649 use egui_pop_core::pointer::{self, chord};
1650 let Some((id, mut candidate)) = st.pointer_capture.clone() else {
1651 return;
1652 };
1653 let ctx = ui.ctx().clone();
1654 let t = Tokens::of(&ctx);
1655 let title = title_of(&ctx, app, &id);
1656 if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
1657 st.pointer_capture = None;
1658 return;
1659 }
1660 ui.add_space(t.space.s);
1661 ui.colored_label(
1662 t.accent.default,
1663 strings::tr_args(&ctx, &txt::SHORTCUTS_POINTER_PAD, &[("command", &title)]),
1664 );
1665 let size = egui::vec2(ui.available_width().min(420.0), 88.0);
1666 let (rect, pad) = ui.allocate_exact_size(size, egui::Sense::click_and_drag());
1667 a11y::name(
1668 &pad,
1669 egui::Role::Unknown,
1670 &strings::tr(&ctx, &txt::SHORTCUTS_POINTER_PAD_NAME),
1671 );
1672 if pad.hovered() {
1673 if let Some(input) = pointer::wheel_inputs(&ctx).last() {
1674 candidate = Some(input.chord().to_string());
1675 }
1676 pointer::take_wheel(&ctx);
1677 }
1678 let modifiers = ui.input(|i| i.modifiers);
1679 for b in [
1680 egui::PointerButton::Primary,
1681 egui::PointerButton::Secondary,
1682 egui::PointerButton::Middle,
1683 egui::PointerButton::Extra1,
1684 egui::PointerButton::Extra2,
1685 ] {
1686 let button = pointer::button(b);
1687 let done = if pad.double_clicked_by(b) {
1688 Some(Pointer::DoubleClick(button))
1689 } else if pad.clicked_by(b) {
1690 Some(Pointer::Click(button))
1691 } else if pad.drag_stopped_by(b) {
1692 Some(Pointer::Drag(button))
1693 } else {
1694 None
1695 };
1696 if let Some(p) = done {
1697 candidate = Some(chord(modifiers, p).to_string());
1698 }
1699 }
1700 let stroke = egui::Stroke::new(1.0, t.accent.default);
1701 ui.painter()
1702 .rect_stroke(rect, 4.0, stroke, egui::StrokeKind::Inside);
1703 if let Some(c) = &candidate {
1704 ui.painter().text(
1705 rect.center(),
1706 egui::Align2::CENTER_CENTER,
1707 c,
1708 egui::TextStyle::Monospace.resolve(ui.style()),
1709 ui.visuals().text_color(),
1710 );
1711 }
1712 ui.horizontal(|ui| {
1713 if let Some(c) = &candidate
1714 && ui
1715 .button(strings::tr_args(
1716 &ctx,
1717 &txt::SHORTCUTS_POINTER_USE,
1718 &[("keys", c)],
1719 ))
1720 .clicked()
1721 {
1722 let mut keys = app.keys_for(&id);
1723 if !keys.contains(c) {
1724 keys.push(c.clone());
1725 }
1726 let keys: Vec<&str> = keys.iter().map(String::as_str).collect();
1727 app.rebind_gestures(target, id.clone(), &keys);
1728 candidate = None;
1729 st.pointer_capture = None;
1730 return;
1731 }
1732 if ui
1733 .button(strings::tr(&ctx, &egui_pop_core::strings::CANCEL))
1734 .clicked()
1735 {
1736 st.pointer_capture = None;
1737 }
1738 });
1739 if let Some((_, slot)) = st.pointer_capture.as_mut() {
1740 *slot = candidate;
1741 }
1742 ui.add_space(t.space.s);
1743}
1744
1745fn page_scope(entries: &[SettingEntry], page: &SettingsPage) -> &'static str {
1748 use egui_pop_model::admin::generate::scope_of;
1749 if let Some(id) = page.settings.first() {
1750 return scope_of(id.as_str());
1751 }
1752 page.parent
1753 .as_deref()
1754 .and_then(|p| entries.iter().find(|e| e.section == p))
1755 .map_or("general", |e| scope_of(e.id.as_str()))
1756}
1757
1758pub fn page_path(app: &AppHandle, id: &str) -> Option<String> {
1760 let page = app.settings_page(id)?;
1761 let all = app.settings();
1762 Some(format!(
1763 "{}/{}",
1764 page_scope(&all, &page),
1765 egui_pop_model::admin::generate::slug(&page.id)
1766 ))
1767}
1768
1769pub(crate) fn admin_manifest(app: &AppHandle) -> egui_pop_model::admin::Manifest {
1778 use egui_pop_model::admin::{Action, FORMAT, Manifest, generate::slug};
1779 let all = app.settings();
1780 let pages = app.settings_pages();
1781 let fonts: Vec<&str> = all
1782 .iter()
1783 .filter(|e| e.section == FONTS)
1784 .map(|e| e.id.as_str())
1785 .collect();
1786 let mut m = Manifest::new(FORMAT)
1787 .section("input/shortcuts", SHORTCUTS, |s| {
1788 s.keywords(&["keys", "keyboard", "shortcuts", "bindings", "hotkeys"])
1789 .widget("shortcuts", "shortcuts", serde_json::Value::Null);
1790 })
1791 .section(
1792 "input/gestures",
1793 txt::ADMIN_SECTION_GESTURES.fallback,
1794 |s| {
1795 s.keywords(&["pointer", "mouse", "gestures", "trackpad", "wheel"])
1796 .widget("gestures", "gestures", serde_json::Value::Null);
1797 },
1798 );
1799 if !fonts.is_empty() {
1800 m = m.section("interface/fonts", FONTS, |s| {
1801 s.keywords(&["text", "font", "family", "size"]).widget(
1802 "fonts",
1803 "fonts",
1804 json!({ "settings": fonts }),
1805 );
1806 });
1807 }
1808 let ids: Vec<&str> = pages.iter().map(|p| p.id.as_str()).collect();
1809 for page in &pages {
1810 let scope = page_scope(&all, page);
1811 let parent = page
1812 .parent
1813 .as_deref()
1814 .filter(|p| ids.contains(p))
1815 .and_then(|p| pages.iter().find(|x| x.id == p))
1816 .filter(|p| page_scope(&all, p) == scope)
1817 .map(|p| slug(&p.id));
1818 m = m.section(&format!("{scope}/{}", slug(&page.id)), &page.title, |s| {
1819 let words: Vec<&str> = page.keywords.iter().map(String::as_str).collect();
1820 let settings: Vec<&str> = page.settings.iter().map(|id| id.as_str()).collect();
1821 s.keywords(&words).widget(
1822 "page",
1823 "settings-page",
1824 json!({ "page": page.id, "settings": settings }),
1825 );
1826 if let Some(parent) = &parent {
1827 s.under(parent);
1828 }
1829 });
1830 }
1831 m = m.section(
1832 "general/advanced",
1833 txt::ADMIN_SECTION_ADVANCED.fallback,
1834 |s| {
1835 s.description(txt::ADMIN_ADVANCED_ABOUT.fallback).action(
1836 Action::command(CMD_SETTINGS_WINDOW.as_str())
1837 .title(txt::ADMIN_ADVANCED_OPEN.fallback),
1838 );
1839 },
1840 );
1841 let last = m.sections.len();
1842 for (i, s) in m.sections.iter_mut().enumerate() {
1843 s.meta.order = if i + 1 == last { 2000 } else { 1000 + i as i32 };
1845 }
1846 m
1847}
1848
1849pub(crate) fn register_kinds(admin: &Admin) {
1853 fn editor(ui: &mut Ui, app: &AppHandle, pointer: bool) {
1854 let Some(w) = app.service(&SETTINGS_WINDOW) else {
1855 return;
1856 };
1857 let mut st = lock(&w.0);
1858 shortcuts_of(ui, app, &mut st, "", Some(pointer));
1859 }
1860 admin.widget_kind("shortcuts", |ui, app, _| editor(ui, app, false));
1861 admin.widget_kind("gestures", |ui, app, _| editor(ui, app, true));
1862 fn commands(
1865 ctx: &egui::Context,
1866 app: &AppHandle,
1867 query: &str,
1868 gestures: bool,
1869 ) -> Vec<(String, String)> {
1870 shortcut_rows(ctx, app, query, None, gestures)
1871 .into_iter()
1872 .filter(|(s, _)| is_gesture(&s.id) == gestures)
1873 .map(|(s, label)| {
1874 let keys = app.keys_for(&s.id);
1875 let title = if keys.is_empty() {
1876 label
1877 } else {
1878 format!("{label} ({})", keys.join(", "))
1879 };
1880 (s.id.as_str().to_string(), title)
1881 })
1882 .collect()
1883 }
1884 admin.widget_search("shortcuts", |ctx, app, _, query| {
1885 commands(ctx, app, query, false)
1886 });
1887 admin.widget_search("gestures", |ctx, app, _, query| {
1888 commands(ctx, app, query, true)
1889 });
1890 admin.widget_kind("fonts", |ui, app, _| {
1891 let all = app.settings();
1892 fonts_page(ui, app, &all);
1893 });
1894 admin.widget_kind("settings-page", |ui, app, options| {
1895 let Some(page) = options
1896 .get("page")
1897 .and_then(serde_json::Value::as_str)
1898 .and_then(|id| app.settings_page(id))
1899 else {
1900 return;
1901 };
1902 settings_pages::header(ui, app, &page);
1903 ui.add_space(Tokens::of(ui.ctx()).space.s);
1904 settings_pages::draw(ui, app, &page.id);
1905 });
1906}