1use std::collections::{BTreeMap, BTreeSet};
79use std::sync::{Arc, Mutex};
80
81use egui::{Id, RichText, Ui, WidgetInfo};
82use egui_pop_core::fonts::{Face, FontFile, Role, Weight};
83use egui_pop_core::state::Slot;
84use egui_pop_core::strings::{self, Arg};
85use egui_pop_core::theme::{ScopedTheme, Tokens, color32};
86use egui_pop_core::tokens::apca;
87use egui_pop_core::tokens::contract::{self, Tier};
88use egui_pop_core::tokens::contrast::{self, Level, Pair, PairKind};
89use egui_pop_core::tokens::package::{self, ThemePackage};
90use egui_pop_core::tokens::palette::{self, Scheme, Seed};
91use egui_pop_core::tokens::{
92 BUILT_IN_THEMES, Color, Counterpart, GeneratedVariant, ResolvedTokens, ThemeDraft, ThemeSpec,
93 TokenEdit, Value, Warning, theme_label,
94};
95use egui_pop_core::ui::{Tone, UiPop as _};
96use egui_pop_core::{focus, lock, widgets};
97use egui_pop_model::commands::{CommandSpec, Origin};
98use egui_pop_model::ids::{CommandId, PluginId, StepId};
99use serde_json::{Value as Json, json};
100
101use crate::app::AppHandle;
102use crate::files::{self, FileRequest};
103use crate::history::{Label, Line, LocalScope, Refusal, RefusalKind, ScopeId, ScopeInfo, StepInfo};
104use crate::host::Pending;
105use crate::services::ServiceToken;
106use crate::steps::{Outcome, StepSpec};
107use crate::strings as txt;
108use crate::{Ctx, Plugin, PluginError};
109
110pub const SURFACE: &str = "themeEditor";
114
115pub const SCOPE: ScopeId = ScopeId::from_static("theme");
117
118#[derive(Debug)]
122struct ThemeScope;
123
124impl ThemeScope {
125 fn cause(origin: &Origin, redo: bool) -> Cause {
126 match (origin, redo) {
127 (Origin::User, false) => Cause::Undo,
128 (Origin::User, true) => Cause::Redo,
129 _ => Cause::Agent,
130 }
131 }
132
133 fn walk(
134 &self,
135 app: &AppHandle,
136 origin: &Origin,
137 redo: bool,
138 ) -> Result<Option<StepInfo>, Refusal> {
139 let Some(editor) = app.service(&THEME_EDITOR) else {
140 return Ok(None);
141 };
142 let line = self.line(app);
143 let step = if redo { line.next() } else { line.head() }.cloned();
144 let made = if redo {
145 editor.redo(app, Self::cause(origin, true))
146 } else {
147 editor.undo(app, Self::cause(origin, false))
148 }
149 .map_err(|e| Refusal::new(RefusalKind::Owner, e))?;
150 Ok(made.and(step))
151 }
152}
153
154impl LocalScope for ThemeScope {
155 fn info(&self) -> ScopeInfo {
156 let mut info = ScopeInfo::new(SCOPE, "Theme editor");
157 info.local = true;
158 info.focus = vec![SURFACE.into()];
159 info.cap = egui_pop_core::tokens::DRAFT_HISTORY_CAP;
160 info
161 }
162
163 fn line(&self, app: &AppHandle) -> Line {
164 let Some(editor) = app.service(&THEME_EDITOR) else {
165 return Line::default();
166 };
167 let draft = editor.draft();
168 let (undo, redo) = (draft.undo_changes(), draft.redo_changes());
169 let step = |id: usize, change: &[TokenEdit]| {
172 let first = change.first().map_or("", |e| e.path.as_str());
173 let label = match change.len() {
174 1 => Label::message(
175 txt::THEME_EDITOR_STEP.key,
176 txt::THEME_EDITOR_STEP.fallback,
177 &[("token", first)],
178 ),
179 n => Label::message(
180 txt::THEME_EDITOR_STEP_MANY.key,
181 txt::THEME_EDITOR_STEP_MANY.fallback,
182 &[("token", first), ("more", &(n - 1).to_string())],
183 ),
184 };
185 StepInfo::new(id as u64, SCOPE, label, Origin::User)
186 };
187 let done = undo.len();
188 let undo_steps: Vec<StepInfo> = undo
189 .iter()
190 .enumerate()
191 .map(|(i, c)| step(i + 1, c))
192 .collect();
193 let redo_steps: Vec<StepInfo> = redo
194 .iter()
195 .enumerate()
196 .map(|(j, c)| step(done + redo.len() - j, c))
197 .collect();
198 let mut hasher = std::collections::hash_map::DefaultHasher::new();
200 std::hash::Hash::hash(
201 &(
202 undo.iter()
203 .flatten()
204 .map(|e| e.to_json().to_string())
205 .collect::<Vec<_>>(),
206 redo.iter()
207 .flatten()
208 .map(|e| e.to_json().to_string())
209 .collect::<Vec<_>>(),
210 ),
211 &mut hasher,
212 );
213 Line {
214 undo: undo_steps,
215 redo: redo_steps,
216 rev: std::hash::Hasher::finish(&hasher),
217 }
218 }
219
220 fn undo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
221 self.walk(app, origin, false)
222 }
223
224 fn redo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
225 self.walk(app, origin, true)
226 }
227}
228
229pub const THEME_EDITOR_PLUGIN: PluginId = PluginId::from_static("egui_pop.theme_editor");
231
232pub const THEME_EDITOR: ServiceToken<ThemeEditor> = ServiceToken::new("egui_pop.theme_editor");
234
235pub const STEP_THEME_TOKEN: StepId = StepId::from_static("theme.token");
237pub const STEP_THEME_LOAD: StepId = StepId::from_static("theme.load");
239
240pub const CMD_THEME_READ: CommandId = CommandId::from_static("theme.read");
241pub const CMD_THEME_SET: CommandId = CommandId::from_static("theme.set");
242pub const CMD_THEME_UNDO: CommandId = CommandId::from_static("theme.undo");
243pub const CMD_THEME_REDO: CommandId = CommandId::from_static("theme.redo");
244pub const CMD_THEME_START: CommandId = CommandId::from_static("theme.start");
245pub const CMD_THEME_EXPORT: CommandId = CommandId::from_static("theme.export");
246pub const CMD_THEME_IMPORT: CommandId = CommandId::from_static("theme.import");
247pub const CMD_THEME_GENERATE: CommandId = CommandId::from_static("theme.generate");
248pub const CMD_THEME_SWITCH: CommandId = CommandId::from_static("theme.switch");
249pub const CMD_THEME_COUNTERPART: CommandId = CommandId::from_static("theme.counterpart");
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub enum Cause {
254 Edit,
256 Reset,
258 Undo,
259 Redo,
260 Agent,
262}
263
264impl Cause {
265 pub fn name(self) -> &'static str {
266 match self {
267 Cause::Edit => "edit",
268 Cause::Reset => "reset",
269 Cause::Undo => "undo",
270 Cause::Redo => "redo",
271 Cause::Agent => "agent",
272 }
273 }
274}
275
276pub fn level_of(base: &str) -> Level {
279 if base.contains("high-contrast") {
280 Level::High
281 } else {
282 Level::Normal
283 }
284}
285
286#[derive(Clone, Debug, PartialEq)]
288pub struct Readout {
289 pub pair: Pair,
290 pub ratio: Option<f32>,
292 pub aa: f32,
294 pub aaa: Option<f32>,
297 pub required: f32,
299 pub lc: Option<f32>,
303}
304
305impl Readout {
306 pub fn passes_aa(&self) -> bool {
307 self.ratio.is_some_and(|r| r >= self.aa)
308 }
309
310 pub fn passes_aaa(&self) -> Option<bool> {
311 self.aaa.map(|a| self.ratio.is_some_and(|r| r >= a))
312 }
313
314 pub fn passes(&self) -> bool {
316 self.ratio.is_some_and(|r| r >= self.required)
317 }
318
319 pub fn to_json(&self) -> Json {
320 json!({
321 "foreground": self.pair.foreground,
322 "background": self.pair.background,
323 "kind": match self.pair.kind { PairKind::Text => "text", PairKind::Ui => "ui" },
324 "ratio": self.ratio.map(|r| (r * 100.0).round() / 100.0),
325 "aa": self.passes_aa(),
326 "aaa": self.passes_aaa(),
327 "required": self.required,
328 "passes": self.passes(),
329 "lc": self.lc.map(|l| (l * 10.0).round() / 10.0),
330 })
331 }
332}
333
334pub fn dependents(tokens: &ResolvedTokens, path: &str) -> BTreeSet<String> {
337 let mut out = BTreeSet::new();
338 for t in tokens.iter() {
339 let mut at = Some(t);
340 let mut hops = 0;
341 while let Some(token) = at {
342 if token.path == path {
343 out.insert(t.path.clone());
344 break;
345 }
346 hops += 1;
347 at = token
348 .alias
349 .as_deref()
350 .filter(|_| hops < 64)
351 .and_then(|a| tokens.get(a));
352 }
353 }
354 out
355}
356
357pub fn contrast_of(tokens: &ResolvedTokens, path: &str) -> Vec<Readout> {
360 let deps = dependents(tokens, path);
361 let level = level_of(&tokens.spec().base);
362 contrast::PAIRS
363 .iter()
364 .filter(|p| deps.contains(p.foreground) || deps.contains(p.background))
365 .map(|p| Readout {
366 pair: *p,
367 ratio: contrast::pair_ratio(tokens, p),
368 aa: Level::Normal.required(p.kind),
369 aaa: (p.kind == PairKind::Text).then(|| Level::High.required(p.kind)),
370 required: level.required(p.kind),
371 lc: tokens
372 .color(p.foreground)
373 .zip(tokens.color(p.background))
374 .map(|(f, b)| apca::lc(f, b)),
375 })
376 .collect()
377}
378
379#[derive(Debug)]
381struct Gesture {
382 path: String,
383 from: Option<Json>,
384 widget: Id,
385 keys: bool,
388}
389
390#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
392pub enum Tab {
393 #[default]
394 Tokens,
395 Fonts,
396}
397
398#[derive(Clone, Debug, Default)]
400struct FontsDraft {
401 files: Vec<FontFile>,
403 pending_files: Option<Vec<FontFile>>,
405 ui: Option<Vec<String>>,
407 mono: Option<Vec<String>>,
408 adding: [String; 2],
410 hovered: Option<(Role, String)>,
413 synced: [Option<Vec<String>>; 2],
417 face_role: Option<Role>,
420 face_search: String,
421 problems: Vec<String>,
423}
424
425fn family_token(role: Role) -> &'static str {
427 match role {
428 Role::Ui => "font.family.ui",
429 Role::Mono => "font.family.mono",
430 }
431}
432
433pub type FileDialog = Arc<dyn Fn(&AppHandle, FileRequest) -> Pending + Send + Sync>;
437
438pub type Sampler = Arc<dyn Fn(&mut Ui, &AppHandle) + Send + Sync>;
441
442type Installed = (
446 String,
447 BTreeMap<String, Json>,
448 Option<(String, BTreeMap<String, Json>)>,
449);
450
451fn installed(app: &AppHandle, spec: &ThemeSpec) -> Installed {
453 let service = app.theme();
454 let counterpart = service
455 .themes()
456 .counterpart(spec)
457 .filter(|c| service.is_dark(c) != service.is_dark(&spec.base))
458 .map(|c| {
459 let own = spec
460 .counterpart_overrides
461 .clone()
462 .unwrap_or_else(|| spec.overrides.clone());
463 (c, own)
464 });
465 (spec.base.clone(), spec.overrides.clone(), counterpart)
466}
467
468#[derive(Debug)]
470enum Choice {
471 Open(Pending),
472 Save(Pending),
473 Font(Pending),
474}
475
476#[derive(Default)]
477struct State {
478 draft: ThemeDraft,
479 preview_only: bool,
482 scoped: Option<(ThemeSpec, ScopedTheme)>,
484 file_dialog: Option<FileDialog>,
485 font_dir: Option<std::path::PathBuf>,
488 sampler: Option<Sampler>,
489 choice: Option<Choice>,
490 tab: Tab,
491 fonts: FontsDraft,
492 applied: Option<Installed>,
495 shown: Option<String>,
498 proposal: Option<GeneratedVariant>,
501 selected: Option<String>,
502 filter: String,
503 gesture: Option<Gesture>,
504 typing: Option<(String, String)>,
506 file_text: String,
508 file_name: String,
509 message: Option<(bool, String)>,
511 seed: Option<(String, Color)>,
513 hex: Option<(String, String)>,
515 resolved: Option<Arc<ResolvedTokens>>,
516}
517
518impl std::fmt::Debug for State {
519 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520 f.debug_struct("State")
521 .field("draft", &self.draft)
522 .field("preview_only", &self.preview_only)
523 .field("selected", &self.selected)
524 .field("tab", &self.tab)
525 .field("fonts", &self.fonts)
526 .field("choice", &self.choice)
527 .finish_non_exhaustive()
528 }
529}
530
531#[derive(Debug, Default)]
533pub struct ThemeEditor {
534 state: Mutex<State>,
535}
536
537impl ThemeEditor {
538 pub fn sync(&self, app: &AppHandle) {
545 let service = app.theme();
546 let spec = service.spec();
547 let now = installed(app, &spec);
548 let shown = service.shown(&app.egui());
549 let mut s = lock(&self.state);
550 if s.applied.as_ref() != Some(&now) {
551 let mut draft = ThemeDraft::from_pair_spec(service.themes(), &spec);
552 if draft.base() != shown {
553 draft.switch();
554 }
555 s.draft = draft;
556 s.applied = Some(now);
557 s.shown = Some(shown);
558 s.gesture = None;
559 s.typing = None;
560 s.proposal = None;
561 return;
562 }
563 if s.shown.as_deref() != Some(shown.as_str()) {
564 if s.draft.is_paired() && service.is_dark(s.draft.base()) != service.is_dark(&shown) {
565 s.draft.switch();
566 s.gesture = None;
567 s.typing = None;
568 s.proposal = None;
569 }
570 s.shown = Some(shown);
571 }
572 }
573
574 pub fn switch_variant(&self, app: &AppHandle) -> Result<String, String> {
579 self.sync(app);
580 let base = {
581 let mut s = lock(&self.state);
582 if !s.draft.switch() {
583 return Err(format!(
584 "`{}` has no light or dark counterpart",
585 s.draft.base()
586 ));
587 }
588 s.gesture = None;
589 s.typing = None;
590 s.proposal = None;
591 s.draft.base().to_string()
592 };
593 self.show_edited(app);
594 Ok(base)
595 }
596
597 fn show_edited(&self, app: &AppHandle) {
600 let service = app.theme();
601 let ctx = app.egui();
602 let (paired, base) = {
603 let s = lock(&self.state);
604 (s.draft.is_paired(), s.draft.base().to_string())
605 };
606 if paired && service.shown(&ctx) != base {
607 service.set_preference(if service.is_dark(&base) {
608 egui::ThemePreference::Dark
609 } else {
610 egui::ThemePreference::Light
611 });
612 }
613 lock(&self.state).shown = Some(service.shown(&ctx));
614 }
615
616 pub fn editing_dark(&self, app: &AppHandle) -> bool {
618 let base = lock(&self.state).draft.base().to_string();
619 app.theme().is_dark(&base)
620 }
621
622 pub fn propose_counterpart(&self, app: &AppHandle) -> Option<GeneratedVariant> {
627 self.sync(app);
628 let proposal = {
629 let themes = app.theme();
630 self.draft().generate_counterpart(themes.themes())
631 };
632 lock(&self.state).proposal = proposal.clone();
633 proposal
634 }
635
636 pub fn proposal(&self) -> Option<GeneratedVariant> {
638 lock(&self.state).proposal.clone()
639 }
640
641 pub fn drop_proposal(&self) {
643 lock(&self.state).proposal = None;
644 }
645
646 pub fn apply_counterpart(&self, app: &AppHandle, cause: Cause) -> Result<usize, String> {
651 self.sync(app);
652 let generated = {
653 let themes = app.theme();
654 self.draft().generate_counterpart(themes.themes())
655 }
656 .ok_or_else(|| format!("`{}` has no light or dark counterpart", self.draft().base()))?;
657 lock(&self.state).draft.switch();
658 let made = if generated.edits.is_empty() {
659 Ok(0)
660 } else {
661 self.record_all(app, generated.edits, cause)
662 };
663 let mut s = lock(&self.state);
664 if made.is_ok() {
665 let old: Vec<String> = s.draft.seeds().keys().cloned().collect();
666 for scale in old {
667 s.draft.set_seed(&scale, None);
668 }
669 for (scale, seed) in generated.seeds {
670 s.draft.set_seed(&scale, Some(seed));
671 }
672 }
673 s.draft.switch();
674 s.proposal = None;
675 made
676 }
677
678 fn proposal_spec(&self, app: &AppHandle) -> Option<ThemeSpec> {
680 let s = lock(&self.state);
681 let proposal = s.proposal.as_ref()?;
682 let mut other = s.draft.counterpart()?.clone();
683 for e in &proposal.edits {
684 other.preview(&e.path, e.to.clone());
685 }
686 Some(other.spec(&app.theme().spec()))
687 }
688
689 pub fn preview_only(&self) -> bool {
693 lock(&self.state).preview_only
694 }
695
696 pub fn set_preview_only(&self, app: &AppHandle, on: bool) {
699 let was = std::mem::replace(&mut lock(&self.state).preview_only, on);
700 if was && !on {
701 self.install(app);
702 }
703 }
704
705 pub fn pending(&self, app: &AppHandle) -> bool {
708 self.sync(app);
709 let spec = lock(&self.state).draft.pair_spec(&app.theme().spec());
710 let draft = installed(app, &spec);
711 lock(&self.state)
712 .applied
713 .as_ref()
714 .is_some_and(|applied| *applied != draft)
715 }
716
717 pub fn apply(&self, app: &AppHandle) {
720 self.install(app);
721 }
722
723 pub fn discard(&self, app: &AppHandle) {
726 lock(&self.state).applied = None;
727 self.sync(app);
728 }
729
730 pub fn set_file_dialog(&self, dialog: Option<FileDialog>) {
735 lock(&self.state).file_dialog = dialog;
736 }
737
738 pub fn set_sampler(&self, sampler: Option<Sampler>) {
741 lock(&self.state).sampler = sampler;
742 }
743
744 pub fn scoped(&self, app: &AppHandle) -> ScopedTheme {
748 let tokens = match self.proposal_spec(app) {
749 Some(spec) => Arc::new(app.theme().themes().resolve(&spec)),
750 None => self.resolved(app),
751 };
752 let spec = tokens.spec().clone();
753 if let Some((_, scoped)) = lock(&self.state)
754 .scoped
755 .as_ref()
756 .filter(|(s, _)| *s == spec)
757 {
758 return scoped.clone();
759 }
760 let scoped = ScopedTheme::new(&app.egui(), Tokens::new((*tokens).clone()));
761 lock(&self.state).scoped = Some((spec, scoped.clone()));
762 scoped
763 }
764
765 fn choose(&self, app: &AppHandle, request: FileRequest) -> Option<Pending> {
768 let dialog = lock(&self.state).file_dialog.clone();
769 match dialog {
770 Some(d) => Some(d(app, request)),
771 None => app.service(&files::FILES).map(|f| f.choose(app, request)),
772 }
773 }
774
775 fn can_choose(&self, app: &AppHandle) -> bool {
776 lock(&self.state).file_dialog.is_some() || app.service(&files::FILES).is_some()
777 }
778
779 pub fn set_font_dir(&self, dir: Option<std::path::PathBuf>) {
786 lock(&self.state).font_dir = dir;
787 }
788
789 pub fn open_file(
797 &self,
798 app: &AppHandle,
799 path: &std::path::Path,
800 ) -> Result<Vec<Warning>, String> {
801 let (package, mut warnings) = ThemePackage::read(path).map_err(|e| e.to_string())?;
802 let text = package.file.to_json_pretty();
803 lock(&self.state).file_text = text.clone();
804 warnings.extend(self.import_text(app, &text)?);
805 let beside = if path.is_dir() {
807 Some(path.to_path_buf())
808 } else if package::is_zip(path) {
809 None
810 } else {
811 path.parent().map(std::path::Path::to_path_buf)
812 };
813 warnings.extend(self.add_package_fonts(app, &package, beside.as_deref()));
814 warnings.extend(self.missing_families(app));
815 Ok(warnings)
816 }
817
818 fn add_package_fonts(
822 &self,
823 app: &AppHandle,
824 package: &ThemePackage,
825 beside: Option<&std::path::Path>,
826 ) -> Vec<Warning> {
827 if package.fonts.is_empty() {
828 return Vec::new();
829 }
830 let ctx = app.egui();
831 let font_dir = lock(&self.state).font_dir.clone();
832 let mut warnings = Vec::new();
833 let mut added = Vec::new();
834 for font in &package.fonts {
835 let name = std::path::Path::new(&font.file)
836 .file_name()
837 .map_or_else(|| font.file.clone(), |n| n.to_string_lossy().into_owned());
838 let at = match (&font_dir, beside) {
839 (Some(dir), _) => {
840 let to = dir.join(&name);
841 match std::fs::create_dir_all(dir)
842 .and_then(|()| std::fs::write(&to, &font.bytes))
843 {
844 Ok(()) => to,
845 Err(e) => {
846 warnings.push(Warning::Font {
847 file: font.file.clone(),
848 reason: format!("not copied to {}: {e}", dir.display()),
849 });
850 continue;
851 }
852 }
853 }
854 (None, Some(dir)) => dir.join(&font.file),
855 (None, None) => {
856 egui_pop_core::fonts::register(
857 &ctx,
858 Face::from_owned(&font.family, Weight(font.weight), font.bytes.clone()),
859 );
860 warnings.push(Warning::Font {
861 file: font.file.clone(),
862 reason: "registered for this run only: no font folder to keep it in".into(),
863 });
864 continue;
865 }
866 };
867 match FontFile::read(&at) {
868 Ok(f) => added.push(f),
869 Err(reason) => warnings.push(Warning::Font {
870 file: font.file.clone(),
871 reason,
872 }),
873 }
874 }
875 if !added.is_empty() {
876 let problems = egui_pop_core::fonts::register_files(&ctx, &added);
877 let mut s = lock(&self.state);
878 let merge = |files: &mut Vec<FontFile>| {
879 files.retain(|f| !added.iter().any(|a| a.path == f.path));
880 files.extend(added.iter().cloned());
881 };
882 merge(&mut s.fonts.files);
883 if let Some(pending) = s.fonts.pending_files.as_mut() {
884 merge(pending);
885 }
886 s.fonts.problems = problems;
887 }
888 egui_pop_core::fonts::reinstall(&ctx);
889 warnings
890 }
891
892 pub fn package(&self, app: &AppHandle, name: &str) -> Result<ThemePackage, String> {
896 self.sync(app);
897 let file = self.draft().to_file(app.theme().themes(), name);
898 let tokens = self.resolved(app);
899 let named: Vec<String> = Role::ALL
900 .into_iter()
901 .filter_map(|role| tokens.font_family(family_token(role)))
902 .flatten()
903 .cloned()
904 .collect();
905 let mut package = ThemePackage::new(file);
906 for f in self.font_files() {
907 if !named.contains(&f.family) {
908 continue;
909 }
910 let bytes = std::fs::read(&f.path).map_err(|e| format!("{}: {e}", f.path.display()))?;
911 let file_name = f.path.file_name().map_or_else(
912 || format!("{}.ttf", f.family),
913 |n| n.to_string_lossy().into_owned(),
914 );
915 package.add_font(&f.family, f.weight.0, &file_name, bytes);
916 }
917 Ok(package)
918 }
919
920 pub fn save_file(
927 &self,
928 app: &AppHandle,
929 path: &std::path::Path,
930 ) -> Result<std::path::PathBuf, String> {
931 let name = path
932 .file_name()
933 .and_then(|n| n.to_str())
934 .map(|n| {
935 n.trim_end_matches(".zip")
936 .trim_end_matches(".json")
937 .trim_end_matches(".tokens")
938 })
939 .filter(|n| !n.is_empty())
940 .unwrap_or("my-theme")
941 .to_string();
942 let package = self.package(app, &name)?;
943 let written = package.write(path).map_err(|e| e.to_string())?;
944 lock(&self.state).file_text = package.token_file().to_json_pretty();
945 Ok(written)
946 }
947
948 pub fn select(&self, path: &str) {
950 let mut s = lock(&self.state);
951 s.selected = Some(path.to_string());
952 s.typing = None;
953 }
954
955 pub fn selected(&self) -> Option<String> {
957 lock(&self.state).selected.clone()
958 }
959
960 pub fn draft(&self) -> ThemeDraft {
962 lock(&self.state).draft.clone()
963 }
964
965 pub fn resolved(&self, app: &AppHandle) -> Arc<ResolvedTokens> {
968 self.sync(app);
969 let service = app.theme();
970 let template = service.spec();
971 let mut s = lock(&self.state);
972 let spec = s.draft.spec(&template);
975 if let Some(r) = s.resolved.as_ref().filter(|r| *r.spec() == spec) {
976 return r.clone();
977 }
978 let r = Arc::new(service.themes().resolve(&spec));
979 s.resolved = Some(r.clone());
980 r
981 }
982
983 fn write(&self, app: &AppHandle) {
985 if lock(&self.state).preview_only {
986 return;
987 }
988 self.install(app);
989 }
990
991 fn install(&self, app: &AppHandle) {
993 let service = app.theme();
994 let new = lock(&self.state).draft.pair_spec(&service.spec());
995 let now = installed(app, &new);
996 lock(&self.state).applied = Some(now);
997 service.update(|spec| {
1001 spec.base = new.base;
1002 spec.overrides = new.overrides;
1003 spec.counterpart = new.counterpart;
1004 spec.counterpart_overrides = new.counterpart_overrides;
1005 });
1006 }
1007
1008 fn step(&self, app: &AppHandle, edit: TokenEdit, cause: Cause) -> Result<TokenEdit, String> {
1011 let mut args = edit.to_json();
1012 args["cause"] = json!(cause.name());
1013 match app.step(&STEP_THEME_TOKEN, args, |_, a| Ok(a["to"].clone())) {
1014 Outcome::Done(Ok(v)) => {
1015 let to = (!v.is_null()).then_some(v);
1016 if to == edit.to {
1017 return Ok(edit);
1018 }
1019 let themes = app.theme();
1020 let draft = self.draft();
1021 draft
1022 .edit(themes.themes(), &edit.path, to)?
1023 .ok_or_else(|| "redirected to the value it has".to_string())
1024 }
1025 Outcome::Done(Err(e)) => Err(e),
1026 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
1027 }
1028 }
1029
1030 pub fn set(
1034 &self,
1035 app: &AppHandle,
1036 path: &str,
1037 to: Option<Json>,
1038 cause: Cause,
1039 ) -> Result<Option<TokenEdit>, String> {
1040 self.sync(app);
1041 let edit = {
1042 let themes = app.theme();
1043 let draft = self.draft();
1044 draft.edit(themes.themes(), path, to)?
1045 };
1046 let Some(edit) = edit else {
1047 return Ok(None);
1048 };
1049 let edit = self.step(app, edit, cause)?;
1050 lock(&self.state).draft.apply(edit.clone());
1051 self.write(app);
1052 Ok(Some(edit))
1053 }
1054
1055 pub fn undo(&self, app: &AppHandle, cause: Cause) -> Result<Option<TokenEdit>, String> {
1058 self.history(app, cause, false)
1059 }
1060
1061 pub fn redo(&self, app: &AppHandle, cause: Cause) -> Result<Option<TokenEdit>, String> {
1063 self.history(app, cause, true)
1064 }
1065
1066 fn history(
1069 &self,
1070 app: &AppHandle,
1071 cause: Cause,
1072 redo: bool,
1073 ) -> Result<Option<TokenEdit>, String> {
1074 self.sync(app);
1075 let n = {
1076 let s = lock(&self.state);
1077 if redo {
1078 s.draft.redo_group()
1079 } else {
1080 s.draft.undo_group()
1081 }
1082 };
1083 let mut last = None;
1084 for _ in 0..n.max(1) {
1085 match self.history_one(app, cause, redo)? {
1086 Some(made) => last = Some(made),
1087 None => break,
1088 }
1089 }
1090 Ok(last)
1091 }
1092
1093 fn history_one(
1094 &self,
1095 app: &AppHandle,
1096 cause: Cause,
1097 redo: bool,
1098 ) -> Result<Option<TokenEdit>, String> {
1099 let next = {
1100 let s = lock(&self.state);
1101 if redo {
1102 s.draft.redo_edit()
1103 } else {
1104 s.draft.undo_edit()
1105 }
1106 };
1107 let Some(next) = next else {
1108 return Ok(None);
1109 };
1110 let made = self.step(app, next.clone(), cause)?;
1111 {
1112 let mut s = lock(&self.state);
1113 if made == next {
1114 if redo {
1115 s.draft.redo();
1116 } else {
1117 s.draft.undo();
1118 }
1119 } else {
1120 s.draft.apply(made.clone());
1122 }
1123 }
1124 self.write(app);
1125 Ok(Some(made))
1126 }
1127
1128 fn load(&self, app: &AppHandle, draft: ThemeDraft, cause: &str) -> Result<(), String> {
1130 let (first, second) = draft.variants();
1131 let args = json!({
1132 "base": first.base(),
1133 "overrides": first.overrides(),
1134 "counterpart": second.map(|c| json!({ "base": c.base(), "overrides": c.overrides() })),
1135 "cause": cause,
1136 });
1137 let v = match app.step(&STEP_THEME_LOAD, args, |_, a| Ok(a.clone())) {
1138 Outcome::Done(Ok(v)) => v,
1139 Outcome::Done(Err(e)) => return Err(e),
1140 Outcome::Vetoed { by, reason } => return Err(format!("vetoed by {by}: {reason}")),
1141 };
1142 let base = v["base"]
1143 .as_str()
1144 .ok_or("the step gave no `base`")?
1145 .to_string();
1146 let themes = app.theme();
1147 if themes.themes().get(&base).is_none() {
1148 return Err(format!("no theme `{base}`"));
1149 }
1150 let map = |v: &Json| -> BTreeMap<String, Json> {
1151 v.as_object()
1152 .map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1153 .unwrap_or_default()
1154 };
1155 let mut spec = ThemeSpec::new(base);
1156 spec.overrides = map(&v["overrides"]);
1157 spec.counterpart = Counterpart::None;
1158 if let Some(c) = v["counterpart"].as_object() {
1159 let other = c
1160 .get("base")
1161 .and_then(Json::as_str)
1162 .ok_or("the step gave a `counterpart` without a `base`")?;
1163 if themes.themes().get(other).is_none() {
1164 return Err(format!("no theme `{other}`"));
1165 }
1166 spec.counterpart = Counterpart::Theme(other.to_string());
1167 spec.counterpart_overrides = Some(c.get("overrides").map(map).unwrap_or_default());
1168 }
1169 let mut new = ThemeDraft::from_pair_spec(themes.themes(), &spec);
1170 drop(themes);
1171 let (first, second) = draft.variants();
1174 let carry = |to: &mut ThemeDraft, from: &ThemeDraft| {
1175 if to.base() == from.base() {
1176 for (scale, seed) in from.seeds() {
1177 to.set_seed(scale, Some(*seed));
1178 }
1179 }
1180 };
1181 carry(&mut new, first);
1182 if let Some(second) = second
1183 && new.switch()
1184 {
1185 carry(&mut new, second);
1186 new.switch();
1187 }
1188 {
1189 let mut s = lock(&self.state);
1190 s.draft = new;
1191 s.gesture = None;
1192 s.typing = None;
1193 s.proposal = None;
1194 }
1195 self.write(app);
1196 if !self.preview_only() {
1197 self.show_edited(app);
1198 }
1199 Ok(())
1200 }
1201
1202 pub fn start(&self, app: &AppHandle, base: &str) -> Result<(), String> {
1207 let draft = ThemeDraft::for_theme(app.theme().themes(), base);
1208 self.load(app, draft, "start")
1209 }
1210
1211 pub fn export(&self, app: &AppHandle, name: &str) -> String {
1215 self.sync(app);
1216 self.draft().export(app.theme().themes(), name)
1217 }
1218
1219 pub fn import(&self, app: &AppHandle, text: &str) -> Result<Vec<Warning>, String> {
1225 let mut warnings = self.import_text(app, text)?;
1226 warnings.extend(self.missing_families(app));
1227 Ok(warnings)
1228 }
1229
1230 fn import_text(&self, app: &AppHandle, text: &str) -> Result<Vec<Warning>, String> {
1233 let (draft, warnings) = {
1234 let themes = app.theme();
1235 ThemeDraft::import(themes.themes(), "import", text).map_err(|e| e.to_string())?
1236 };
1237 self.load(app, draft, "import")?;
1238 Ok(warnings)
1239 }
1240
1241 pub fn generate(
1256 &self,
1257 app: &AppHandle,
1258 scale: &str,
1259 seed: Color,
1260 cause: Cause,
1261 ) -> Result<usize, String> {
1262 self.sync(app);
1263 let tokens = self.resolved(app);
1264 let seed = Seed::new(seed, scheme_of(&tokens));
1265 let edits = {
1266 let themes = app.theme();
1267 let draft = self.draft();
1268 let ramp = draft.seeded_ramp(themes.themes(), scale, seed);
1269 draft.scale_edits(themes.themes(), scale, &ramp)?
1270 };
1271 let made = self.record_all(app, edits, cause)?;
1272 lock(&self.state).draft.set_seed(scale, Some(seed));
1274 Ok(made)
1275 }
1276
1277 fn record_all(
1280 &self,
1281 app: &AppHandle,
1282 edits: Vec<TokenEdit>,
1283 cause: Cause,
1284 ) -> Result<usize, String> {
1285 let mut made = 0;
1286 let mut failed = None;
1287 for edit in edits {
1288 match self.step(app, edit, cause) {
1289 Ok(edit) => {
1290 let mut s = lock(&self.state);
1291 if made == 0 {
1292 s.draft.record(edit);
1293 } else {
1294 s.draft.record_joined(edit);
1295 }
1296 made += 1;
1297 }
1298 Err(e) => failed = Some(e),
1299 }
1300 }
1301 if made > 0 {
1302 self.write(app);
1303 }
1304 match failed {
1305 Some(e) if made == 0 => Err(e),
1306 _ => Ok(made),
1307 }
1308 }
1309
1310 pub fn tab(&self) -> Tab {
1312 lock(&self.state).tab
1313 }
1314
1315 pub fn set_tab(&self, tab: Tab) {
1316 lock(&self.state).tab = tab;
1317 }
1318
1319 pub fn font_files(&self) -> Vec<FontFile> {
1323 lock(&self.state).fonts.files.clone()
1324 }
1325
1326 pub fn set_font_files(&self, ctx: &egui::Context, files: Vec<FontFile>) -> Vec<String> {
1330 let problems = egui_pop_core::fonts::register_files(ctx, &files);
1331 let mut s = lock(&self.state);
1332 s.fonts.files = files;
1333 s.fonts.pending_files = None;
1334 problems
1335 }
1336
1337 pub fn edited_font_files(&self) -> Vec<FontFile> {
1339 let s = lock(&self.state);
1340 s.fonts
1341 .pending_files
1342 .clone()
1343 .unwrap_or_else(|| s.fonts.files.clone())
1344 }
1345
1346 pub fn add_font_file(&self, path: &std::path::Path) -> Result<FontFile, String> {
1350 let file = FontFile::read(path)?;
1351 let mut files = self.edited_font_files();
1352 files.retain(|f| f.path != file.path);
1353 files.push(file.clone());
1354 lock(&self.state).fonts.pending_files = Some(files);
1355 Ok(file)
1356 }
1357
1358 pub fn remove_font_file(&self, path: &std::path::Path) {
1361 let mut files = self.edited_font_files();
1362 files.retain(|f| f.path != path);
1363 lock(&self.state).fonts.pending_files = Some(files);
1364 }
1365
1366 pub fn families(&self, app: &AppHandle, role: Role) -> Vec<String> {
1369 let edited = {
1370 let s = lock(&self.state);
1371 match role {
1372 Role::Ui => s.fonts.ui.clone(),
1373 Role::Mono => s.fonts.mono.clone(),
1374 }
1375 };
1376 edited.unwrap_or_else(|| {
1377 self.resolved(app)
1378 .font_family(family_token(role))
1379 .map(<[String]>::to_vec)
1380 .unwrap_or_default()
1381 })
1382 }
1383
1384 pub fn set_families(&self, role: Role, families: Vec<String>) {
1387 let mut s = lock(&self.state);
1388 match role {
1389 Role::Ui => s.fonts.ui = Some(families),
1390 Role::Mono => s.fonts.mono = Some(families),
1391 }
1392 }
1393
1394 pub fn fonts_pending(&self, app: &AppHandle) -> bool {
1396 let (files, ui, mono) = {
1397 let s = lock(&self.state);
1398 (
1399 s.fonts.pending_files.as_ref().map(|p| *p != s.fonts.files),
1400 s.fonts.ui.clone(),
1401 s.fonts.mono.clone(),
1402 )
1403 };
1404 let tokens = self.resolved(app);
1405 let differs = |role: Role, edited: Option<Vec<String>>| {
1406 edited.is_some_and(|e| tokens.font_family(family_token(role)) != Some(e.as_slice()))
1407 };
1408 files == Some(true) || differs(Role::Ui, ui) || differs(Role::Mono, mono)
1409 }
1410
1411 pub fn preview_face(&self, role: Role, name: Option<&str>) {
1415 lock(&self.state).fonts.hovered = name.map(|n| (role, n.to_string()));
1416 }
1417
1418 pub fn font_preview(&self, app: &AppHandle, role: Role) -> Option<Vec<String>> {
1423 let (hovered, edited) = {
1424 let s = lock(&self.state);
1425 let edited = match role {
1426 Role::Ui => s.fonts.ui.clone(),
1427 Role::Mono => s.fonts.mono.clone(),
1428 };
1429 let hovered = s
1430 .fonts
1431 .hovered
1432 .as_ref()
1433 .filter(|(r, _)| *r == role)
1434 .map(|(_, n)| n.clone());
1435 (hovered, edited)
1436 };
1437 let installed = self
1438 .resolved(app)
1439 .font_family(family_token(role))
1440 .map(<[String]>::to_vec)
1441 .unwrap_or_default();
1442 let edited = edited.filter(|e| *e != installed);
1443 match hovered {
1444 Some(name) => {
1445 let mut list = edited.unwrap_or(installed);
1446 list.retain(|n| !n.eq_ignore_ascii_case(&name));
1447 list.insert(0, name);
1448 Some(list)
1449 }
1450 None => edited,
1451 }
1452 }
1453
1454 fn sync_font_preview(&self, app: &AppHandle) {
1457 let ctx = app.egui();
1458 for (at, role) in Role::ALL.into_iter().enumerate() {
1459 let want = self.font_preview(app, role);
1460 let mut s = lock(&self.state);
1461 if s.fonts.synced[at] != want {
1462 s.fonts.synced[at] = want.clone();
1463 drop(s);
1464 egui_pop_core::fonts::set_preview(&ctx, role, want);
1465 }
1466 }
1467 }
1468
1469 pub fn installed_families(
1474 &self,
1475 app: &AppHandle,
1476 role: Role,
1477 ) -> Vec<egui_pop_core::fonts::FamilyInfo> {
1478 let search = lock(&self.state).fonts.face_search.trim().to_lowercase();
1479 egui_pop_core::fonts::families(&app.egui())
1480 .into_iter()
1481 .filter(|f| role == Role::Ui || f.monospace)
1482 .filter(|f| search.is_empty() || f.name.to_lowercase().contains(&search))
1483 .collect()
1484 }
1485
1486 pub fn set_face_search(&self, search: &str) {
1488 lock(&self.state).fonts.face_search = search.to_string();
1489 }
1490
1491 pub fn choose_face(&self, app: &AppHandle, role: Role, name: &str) {
1499 let mut list = self.families(app, role);
1500 list.retain(|n| !n.eq_ignore_ascii_case(name));
1501 list.insert(0, name.to_string());
1502 if !list.iter().any(|n| egui_pop_core::fonts::is_generic(n)) {
1503 list.push(
1504 match role {
1505 Role::Ui => "sans-serif",
1506 Role::Mono => "monospace",
1507 }
1508 .to_string(),
1509 );
1510 }
1511 self.set_families(role, list);
1512 }
1513
1514 fn missing_families(&self, app: &AppHandle) -> Vec<Warning> {
1520 let ctx = app.egui();
1521 let tokens = self.resolved(app);
1522 let mut warnings = Vec::new();
1523 for role in Role::ALL {
1524 let Some(list) = tokens.font_family(family_token(role)) else {
1525 continue;
1526 };
1527 let found = |n: &String| egui_pop_core::fonts::origin_of(&ctx, n).is_some();
1528 for (at, name) in list.iter().enumerate() {
1529 if found(name) {
1530 continue;
1531 }
1532 let fallback = list[at + 1..]
1533 .iter()
1534 .find(|n| found(n))
1535 .map_or_else(|| "egui's bundled fonts".to_string(), |n| format!("`{n}`"));
1536 warnings.push(Warning::FontMissing {
1537 path: family_token(role).to_string(),
1538 family: name.clone(),
1539 fallback,
1540 });
1541 }
1542 }
1543 warnings
1544 }
1545
1546 pub fn cancel_fonts(&self, app: &AppHandle) {
1549 {
1550 let mut s = lock(&self.state);
1551 s.fonts.pending_files = None;
1552 s.fonts.ui = None;
1553 s.fonts.mono = None;
1554 s.fonts.hovered = None;
1555 s.fonts.adding = Default::default();
1556 }
1557 self.sync_font_preview(app);
1558 }
1559
1560 pub fn apply_fonts(&self, app: &AppHandle, cause: Cause) -> Result<Vec<String>, String> {
1569 self.sync(app);
1570 let ctx = app.egui();
1571 let files = self.edited_font_files();
1572 let problems = egui_pop_core::fonts::register_files(&ctx, &files);
1573 let mut edits = Vec::new();
1574 for role in Role::ALL {
1575 let edited = {
1576 let s = lock(&self.state);
1577 match role {
1578 Role::Ui => s.fonts.ui.clone(),
1579 Role::Mono => s.fonts.mono.clone(),
1580 }
1581 };
1582 if let Some(list) = edited {
1583 let themes = app.theme();
1584 if let Some(e) =
1585 self.draft()
1586 .edit(themes.themes(), family_token(role), Some(json!(list)))?
1587 {
1588 edits.push(e);
1589 }
1590 }
1591 }
1592 let families_changed = !edits.is_empty();
1593 if families_changed {
1594 self.record_all(app, edits, cause)?;
1595 }
1596 self.install(app);
1597 if !families_changed {
1598 egui_pop_core::fonts::reinstall(&ctx);
1602 }
1603 {
1604 let mut s = lock(&self.state);
1605 s.fonts.files = files;
1606 s.fonts.pending_files = None;
1607 s.fonts.ui = None;
1608 s.fonts.mono = None;
1609 s.fonts.hovered = None;
1610 s.fonts.problems = problems.clone();
1611 }
1612 self.sync_font_preview(app);
1613 Ok(problems)
1614 }
1615
1616 pub fn read(&self, app: &AppHandle, path: Option<&str>) -> Result<Json, String> {
1618 self.sync(app);
1619 let tokens = self.resolved(app);
1620 let draft = self.draft();
1621 let Some(path) = path else {
1622 let level = level_of(draft.base());
1623 let dark = app.theme().is_dark(draft.base());
1624 return Ok(json!({
1625 "base": draft.base(),
1626 "variant": if dark { "dark" } else { "light" },
1627 "counterpart": draft.counterpart().map(|c| json!({
1628 "base": c.base(),
1629 "overrides": c.overrides(),
1630 "can_undo": c.can_undo(),
1631 })),
1632 "overrides": draft.overrides(),
1633 "history": draft.history().iter().map(TokenEdit::to_json).collect::<Vec<_>>(),
1634 "can_undo": draft.can_undo(),
1635 "can_redo": draft.can_redo(),
1636 "level": match level { Level::High => "high", Level::Normal => "normal" },
1637 "failing": contrast::check(&tokens, level).iter().map(ToString::to_string).collect::<Vec<_>>(),
1638 "problems": tokens.problems().iter().map(ToString::to_string).collect::<Vec<_>>(),
1639 }));
1640 };
1641 let t = tokens
1642 .get(path)
1643 .ok_or_else(|| format!("no token `{path}`"))?;
1644 Ok(json!({
1645 "path": t.path,
1646 "type": t.ty,
1647 "tier": t.tier().name(),
1648 "value": t.value.to_json(),
1649 "alias": t.alias,
1650 "own": draft.value(path),
1651 "description": description(path, t.description.as_deref()),
1652 "contrast": contrast_of(&tokens, path).iter().map(Readout::to_json).collect::<Vec<_>>(),
1653 }))
1654 }
1655}
1656
1657fn description(path: &str, own: Option<&str>) -> String {
1658 contract::required(path)
1659 .map(|r| r.description.to_string())
1660 .or_else(|| own.map(String::from))
1661 .unwrap_or_default()
1662}
1663
1664#[derive(Debug, Default)]
1666pub struct ThemeEditorPlugin;
1667
1668impl Plugin for ThemeEditorPlugin {
1669 fn id(&self) -> PluginId {
1670 THEME_EDITOR_PLUGIN
1671 }
1672
1673 fn title(&self) -> String {
1674 "Theme editor".into()
1675 }
1676
1677 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1678 const CAT: &str = "Theme";
1679 ctx.service(&THEME_EDITOR, ThemeEditor::default())?;
1680 ctx.step(
1681 StepSpec::new(
1682 STEP_THEME_TOKEN,
1683 "A theme token changes in the theme editor (`path`, `from`, `to`: raw DTCG values, null for the base theme's, `cause`); a veto keeps `from`, a redirect or a run-hook gives another value.",
1684 )
1685 .args(json!({
1686 "path": "accent.default",
1687 "from": null,
1688 "to": "#2060c0",
1689 "cause": "edit",
1690 })),
1691 )?;
1692 ctx.step(
1693 StepSpec::new(
1694 STEP_THEME_LOAD,
1695 "The theme editor starts from a theme or a file (`base`, `overrides`, `cause`: start or import); a veto keeps the theme, a redirect gives another base or other overrides.",
1696 )
1697 .args(json!({ "base": "pop-light", "overrides": {}, "cause": "start" })),
1698 )?;
1699 let editor = |call: &crate::Call<'_>| {
1700 call.app
1701 .service(&THEME_EDITOR)
1702 .ok_or_else(|| "the theme editor is not connected".to_string())
1703 };
1704 ctx.command(
1705 CommandSpec::new(CMD_THEME_READ, "Read the theme", CAT)
1706 .description("The theme being edited: its base, the tokens changed, the history and the failing contrast pairs; with `path`, one token, its value, alias and contrast readouts.")
1707 .hidden()
1708 .read_only()
1709 .args(json!({ "path": "accent.default" })),
1710 move |call| {
1711 let path = call.args.get("path").and_then(Json::as_str);
1712 editor(call)?.read(call.app, path)
1713 },
1714 )?;
1715 ctx.command(
1716 CommandSpec::new(CMD_THEME_SET, "Set a theme token", CAT)
1717 .description("Sets a token of the theme being edited (`path`, `value`: a raw DTCG value or an alias of another token, null for the base theme's), through the theme.token step; undoable.")
1718 .hidden()
1719 .args(json!({ "path": "accent.default", "value": "#2060c0" })),
1720 move |call| {
1721 let path = call
1722 .args
1723 .get("path")
1724 .and_then(Json::as_str)
1725 .ok_or("`path` is missing")?;
1726 let value = call.args.get("value").cloned().filter(|v| !v.is_null());
1727 let edit = editor(call)?.set(call.app, path, value, Cause::Agent)?;
1728 Ok(edit.map_or(json!({ "changed": false }), |e| {
1729 json!({ "changed": true, "edit": e.to_json() })
1730 }))
1731 },
1732 )?;
1733 ctx.local_scope(SURFACE, ThemeScope);
1736 for (id, title, description, redo) in [
1737 (
1738 CMD_THEME_UNDO,
1739 "Undo a theme change",
1740 "Takes the theme editor's last change back, through the theme.token step.",
1741 false,
1742 ),
1743 (
1744 CMD_THEME_REDO,
1745 "Redo a theme change",
1746 "Makes the theme editor's last undone change again.",
1747 true,
1748 ),
1749 ] {
1750 let spec = CommandSpec::new(id, title, CAT)
1751 .description(description)
1752 .hidden();
1753 ctx.command(spec, move |call| {
1754 let e = editor(call)?;
1755 let cause = match (call.origin, redo) {
1756 (Origin::User, false) => Cause::Undo,
1757 (Origin::User, true) => Cause::Redo,
1758 _ => Cause::Agent,
1759 };
1760 let made = if redo {
1761 e.redo(call.app, cause)?
1762 } else {
1763 e.undo(call.app, cause)?
1764 };
1765 Ok(made.map_or(Json::Null, |m| m.to_json()))
1766 })?;
1767 }
1768 ctx.command(
1769 CommandSpec::new(CMD_THEME_START, "Start a theme from", CAT)
1770 .description("Starts the theme editor again from a theme (`base`), its history emptied, through the theme.load step.")
1771 .hidden()
1772 .args(json!({ "base": "pop-light" })),
1773 move |call| {
1774 let base = call
1775 .args
1776 .get("base")
1777 .and_then(Json::as_str)
1778 .ok_or("`base` is missing")?;
1779 editor(call)?.start(call.app, base)?;
1780 Ok(json!({ "base": base }))
1781 },
1782 )?;
1783 ctx.command(
1784 CommandSpec::new(CMD_THEME_GENERATE, "Generate a colour scale", CAT)
1785 .description("Writes a scale generated from a seed colour (`seed`, #rrggbb) over one of the theme's colour scales (`scale`): steps 1 to 12 and contrast, for the variant edited, light or dark; undone as one change.")
1786 .hidden()
1787 .args(json!({ "scale": "blue", "seed": "#3a7bd5" })),
1788 move |call| {
1789 let scale = call
1790 .args
1791 .get("scale")
1792 .and_then(Json::as_str)
1793 .ok_or("`scale` is missing")?;
1794 let seed = call
1795 .args
1796 .get("seed")
1797 .and_then(Json::as_str)
1798 .and_then(Color::from_hex)
1799 .ok_or("`seed` is missing or not a #rrggbb colour")?;
1800 let count = editor(call)?.generate(call.app, scale, seed, Cause::Agent)?;
1801 Ok(json!({ "scale": scale, "changed": count }))
1802 },
1803 )?;
1804 ctx.command(
1805 CommandSpec::new(CMD_THEME_SWITCH, "Switch the variant edited", CAT)
1806 .description("Edits the other variant, light or dark, of the pair being edited, and shows it; each variant keeps its changes and history.")
1807 .hidden(),
1808 move |call| {
1809 let base = editor(call)?.switch_variant(call.app)?;
1810 Ok(json!({ "base": base }))
1811 },
1812 )?;
1813 ctx.command(
1814 CommandSpec::new(CMD_THEME_COUNTERPART, "Generate the other variant", CAT)
1815 .description("The pair's other variant generated from the one edited (colours mirrored: the same hue and saturation, the lightness inverted; aliases and other values as they are): the edits proposed, or, with `apply`, written as one change.")
1816 .hidden()
1817 .args(json!({ "apply": false })),
1818 move |call| {
1819 let e = editor(call)?;
1820 if call.args.get("apply").and_then(Json::as_bool) == Some(true) {
1821 let count = e.apply_counterpart(call.app, Cause::Agent)?;
1822 return Ok(json!({ "changed": count }));
1823 }
1824 let g = e
1825 .propose_counterpart(call.app)
1826 .ok_or("the theme edited has no light or dark counterpart")?;
1827 Ok(json!({
1828 "edits": g.edits.iter().map(TokenEdit::to_json).collect::<Vec<_>>(),
1829 "seeds": g.seeds.iter().map(|(k, v)| (k.clone(), v.to_json())).collect::<serde_json::Map<_, _>>(),
1830 "skipped": g.skipped,
1831 }))
1832 },
1833 )?;
1834 ctx.command(
1835 CommandSpec::new(CMD_THEME_EXPORT, "Export the theme", CAT)
1836 .description("The theme being edited as a .tokens.json file (`name`): $extends its base, the tokens changed with their types; a light and dark pair as one file carrying its counterpart.")
1837 .hidden()
1838 .args(json!({ "name": "my-theme" })),
1839 move |call| {
1840 let name = call
1841 .args
1842 .get("name")
1843 .and_then(Json::as_str)
1844 .unwrap_or("my-theme");
1845 Ok(json!({ "name": name, "text": editor(call)?.export(call.app, name) }))
1846 },
1847 )?;
1848 ctx.command(
1849 CommandSpec::new(CMD_THEME_IMPORT, "Import a theme", CAT)
1850 .description("Loads a .tokens.json file (`text`) into the theme editor, through the theme.load step; says which tokens were left out (`skipped`) and what it loaded with (`warnings`).")
1851 .hidden()
1852 .args(json!({ "text": "{ \"$extends\": \"pop-light\" }" })),
1853 move |call| {
1854 let text = call
1855 .args
1856 .get("text")
1857 .and_then(Json::as_str)
1858 .ok_or("`text` is missing")?;
1859 let warnings = editor(call)?.import(call.app, text)?;
1860 Ok(json!({
1861 "skipped": warnings.iter().filter(|w| w.left_out()).filter_map(Warning::path).collect::<Vec<_>>(),
1862 "warnings": warnings.iter().map(ToString::to_string).collect::<Vec<_>>(),
1863 }))
1864 },
1865 )?;
1866 Ok(())
1867 }
1868}
1869
1870struct Group {
1872 title: &'static strings::StrKey,
1873 paths: Vec<String>,
1874 open: bool,
1875}
1876
1877fn groups(tokens: &ResolvedTokens) -> Vec<Group> {
1880 let system = |test: &dyn Fn(&str) -> bool| -> Vec<String> {
1881 contract::contract()
1882 .filter(|r| r.tier == Tier::System && test(r.path))
1883 .map(|r| r.path.to_string())
1884 .collect()
1885 };
1886 let starts = |prefixes: &'static [&'static str]| {
1887 move |p: &str| prefixes.iter().any(|x| p.starts_with(x))
1888 };
1889 let accent = |p: &str| p.starts_with("accent.") || p == "selection" || p == "focus.ring";
1890 let states = |p: &str| ["danger", "warning", "success", "info"].contains(&p);
1891 vec![
1892 Group {
1893 title: &txt::THEME_EDITOR_SURFACES,
1894 paths: system(&starts(&["surface."])),
1895 open: true,
1896 },
1897 Group {
1898 title: &txt::THEME_EDITOR_TEXT,
1899 paths: system(&starts(&["text."])),
1900 open: true,
1901 },
1902 Group {
1903 title: &txt::THEME_EDITOR_ACCENT,
1904 paths: system(&accent),
1905 open: true,
1906 },
1907 Group {
1908 title: &txt::THEME_EDITOR_STATES,
1909 paths: system(&states),
1910 open: true,
1911 },
1912 Group {
1913 title: &txt::THEME_EDITOR_BORDERS,
1914 paths: system(&starts(&["border."])),
1915 open: false,
1916 },
1917 Group {
1918 title: &txt::THEME_EDITOR_SHAPE,
1919 paths: system(&starts(&[
1920 "radius.",
1921 "space.",
1922 "size.",
1923 "font.",
1924 "text-role.",
1925 "opacity.",
1926 "motion.",
1927 ])),
1928 open: false,
1929 },
1930 Group {
1931 title: &txt::THEME_EDITOR_COMPONENTS,
1932 paths: contract::contract()
1933 .filter(|r| r.tier == Tier::Component)
1934 .map(|r| r.path.to_string())
1935 .collect(),
1936 open: false,
1937 },
1938 Group {
1939 title: &txt::THEME_EDITOR_PALETTE,
1940 paths: tokens
1941 .iter()
1942 .filter(|t| t.tier() == Tier::Reference)
1943 .map(|t| t.path.clone())
1944 .collect(),
1945 open: false,
1946 },
1947 ]
1948}
1949
1950fn parse_typed(ty: &str, text: &str) -> Option<Json> {
1952 let text = text.trim();
1953 if text.starts_with('{') && text.ends_with('}') {
1954 return Some(json!(text));
1955 }
1956 let number = |t: &str| t.parse::<f64>().ok();
1957 let v = match ty {
1958 "color" => json!(Color::from_hex(text)?.to_hex()),
1959 "dimension" => {
1960 json!({ "value": number(text.trim_end_matches("px").trim())?, "unit": "px" })
1961 }
1962 "duration" => json!({ "value": number(text.trim_end_matches("ms").trim())?, "unit": "ms" }),
1963 "number" => json!(number(text)?),
1964 "fontFamily" => json!(
1965 text.split(',')
1966 .map(|f| f.trim().to_string())
1967 .filter(|f| !f.is_empty())
1968 .collect::<Vec<_>>()
1969 ),
1970 _ => serde_json::from_str(text).ok()?,
1971 };
1972 Some(v)
1973}
1974
1975fn typed_text(draft: &ThemeDraft, t: &egui_pop_core::tokens::Token) -> String {
1978 match draft.value(&t.path).and_then(Json::as_str) {
1979 Some(own) if own.starts_with('{') => own.to_string(),
1980 _ => match &t.alias {
1981 Some(a) => format!("{{{a}}}"),
1982 None => t.value.display(),
1983 },
1984 }
1985}
1986
1987pub fn show(ui: &mut Ui, app: &AppHandle) {
1989 let Some(editor) = app.service(&THEME_EDITOR) else {
1990 ui.weak(strings::tr(ui.ctx(), &txt::THEME_EDITOR_MISSING));
1991 return;
1992 };
1993 focus::scope(ui, SURFACE, &[], |ui| editor_ui(ui, app, &editor));
1995}
1996
1997fn editor_ui(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor) {
1998 editor.sync(app);
1999 let ctx = ui.ctx().clone();
2000 poll_choice(app, editor, &ctx);
2001 let tokens = editor.resolved(app);
2002 toolbar(ui, app, editor);
2003 ui.separator();
2004 if editor.tab() == Tab::Fonts {
2005 fonts_tab(ui, app, editor);
2006 return;
2007 }
2008 ui.horizontal_top(|ui| {
2009 let list_width = (ui.available_width() * 0.38).clamp(200.0, 320.0);
2010 ui.vertical(|ui| {
2011 ui.set_width(list_width);
2012 list(ui, editor, &tokens);
2013 });
2014 ui.separator();
2015 ui.vertical(|ui| {
2016 preview_pane(ui, app, editor, false);
2017 ui.add_space(Tokens::of(&ctx).space.m);
2018 let selected = lock(&editor.state).selected.clone();
2019 match selected.as_deref().and_then(|p| tokens.get(p)) {
2020 Some(t) => detail(ui, app, editor, &tokens, t),
2021 None => {
2022 ui.weak(strings::tr(&ctx, &txt::THEME_EDITOR_PICK));
2023 }
2024 }
2025 });
2026 });
2027 ui.separator();
2028 file(ui, app, editor);
2029 let problems = tokens.problems();
2030 if !problems.is_empty() {
2031 let t = Tokens::of(&ctx);
2032 ui.colored_label(
2033 t.status.warning,
2034 strings::tr(&ctx, &txt::THEME_EDITOR_PROBLEMS),
2035 );
2036 for p in problems {
2037 ui.colored_label(t.status.warning, p.to_string());
2038 }
2039 }
2040 finish_gesture(ui, app, editor);
2041}
2042
2043fn toolbar(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor) {
2044 let ctx = ui.ctx().clone();
2045 ui.horizontal(|ui| {
2046 let mut tab = editor.tab();
2047 widgets::selectable_value(
2048 ui,
2049 &mut tab,
2050 Tab::Tokens,
2051 strings::tr(&ctx, &txt::THEME_EDITOR_TAB_TOKENS),
2052 );
2053 widgets::selectable_value(
2054 ui,
2055 &mut tab,
2056 Tab::Fonts,
2057 strings::tr(&ctx, &txt::THEME_EDITOR_TAB_FONTS),
2058 );
2059 if tab != editor.tab() {
2060 editor.set_tab(tab);
2061 }
2062 });
2063 ui.horizontal_wrapped(|ui| {
2064 let base = editor.draft().base().to_string();
2065 let start = strings::tr(&ctx, &txt::THEME_EDITOR_START);
2066 let label = ui.label(&start);
2067 let mut picked = base.clone();
2068 let combo =
2069 widgets::combo_box("egui_pop.theme_editor.start").selected_text(theme_label(&base));
2070 ui.combo_box(combo, |ui| {
2071 for name in BUILT_IN_THEMES {
2072 widgets::selectable_value(ui, &mut picked, (*name).to_string(), theme_label(name));
2073 }
2074 })
2075 .response
2076 .labelled_by(label.id);
2077 if picked != base {
2078 say(editor, editor.start(app, &picked).map(|()| None));
2079 }
2080 let draft = editor.draft();
2081 for (redo, icon_key, can, next) in [
2082 (
2083 false,
2084 &txt::THEME_EDITOR_UNDO,
2085 draft.can_undo(),
2086 draft.undo_edit(),
2087 ),
2088 (
2089 true,
2090 &txt::THEME_EDITOR_REDO,
2091 draft.can_redo(),
2092 draft.redo_edit(),
2093 ),
2094 ] {
2095 let text = strings::tr(&ctx, icon_key);
2096 let r = ui.add_enabled(can, egui::Button::new(&text));
2097 let r = match next {
2098 Some(e) => r.on_hover_text(strings::tr_args(
2099 &ctx,
2100 &txt::THEME_EDITOR_CHANGE_OF,
2101 &[("token", &e.path)],
2102 )),
2103 None => r,
2104 };
2105 if r.clicked() {
2106 let out = if redo {
2107 editor.redo(app, Cause::Redo)
2108 } else {
2109 editor.undo(app, Cause::Undo)
2110 };
2111 say(editor, out.map(|_| None));
2112 }
2113 }
2114 let changed = draft.overrides().len();
2115 ui.weak(strings::tr_with(
2116 &ctx,
2117 &txt::THEME_EDITOR_CHANGED_COUNT,
2118 &[("count", changed.into())],
2119 ));
2120 });
2121 if draft_paired(editor) {
2122 pair_bar(ui, app, editor);
2123 }
2124 ui.horizontal_wrapped(|ui| {
2125 let mut preview_only = editor.preview_only();
2126 let r = widgets::checkbox(
2127 ui,
2128 &mut preview_only,
2129 strings::tr(&ctx, &txt::THEME_EDITOR_PREVIEW_ONLY),
2130 )
2131 .on_hover_text(strings::tr(&ctx, &txt::THEME_EDITOR_PREVIEW_ONLY_HINT));
2132 if r.changed() {
2133 editor.set_preview_only(app, preview_only);
2134 }
2135 if preview_only {
2136 let pending = editor.pending(app);
2137 if ui
2138 .add_enabled(
2139 pending,
2140 egui::Button::new(strings::tr(&ctx, &txt::THEME_EDITOR_APPLY)),
2141 )
2142 .clicked()
2143 {
2144 editor.apply(app);
2145 }
2146 if ui
2147 .add_enabled(
2148 pending,
2149 egui::Button::new(strings::tr(&ctx, &txt::THEME_EDITOR_DISCARD)),
2150 )
2151 .clicked()
2152 {
2153 editor.discard(app);
2154 }
2155 }
2156 });
2157 ui.horizontal(|ui| {
2158 let hint = strings::tr(&ctx, &txt::THEME_EDITOR_FILTER);
2159 let mut s = lock(&editor.state);
2160 let r = ui.add(
2161 egui::TextEdit::singleline(&mut s.filter)
2162 .hint_text(&hint)
2163 .desired_width(240.0),
2164 );
2165 drop(s);
2166 r.widget_info(|| WidgetInfo::labeled(egui::Role::TextInput, true, &hint));
2167 });
2168}
2169
2170fn draft_paired(editor: &ThemeEditor) -> bool {
2171 lock(&editor.state).draft.is_paired()
2172}
2173
2174fn pair_bar(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor) {
2177 let ctx = ui.ctx().clone();
2178 let other = editor
2179 .draft()
2180 .counterpart()
2181 .map(|c| theme_label(c.base()))
2182 .unwrap_or_default();
2183 ui.horizontal_wrapped(|ui| {
2184 ui.label(strings::tr(&ctx, &txt::THEME_EDITOR_VARIANT))
2185 .on_hover_text(strings::tr(&ctx, &txt::THEME_EDITOR_VARIANT_HINT));
2186 let dark = editor.editing_dark(app);
2187 let mut wanted = dark;
2188 widgets::selectable_value(
2189 ui,
2190 &mut wanted,
2191 true,
2192 strings::tr(&ctx, &txt::THEME_EDITOR_DARK),
2193 );
2194 widgets::selectable_value(
2195 ui,
2196 &mut wanted,
2197 false,
2198 strings::tr(&ctx, &txt::THEME_EDITOR_LIGHT),
2199 );
2200 if wanted != dark {
2201 say(editor, editor.switch_variant(app).map(|_| None));
2202 }
2203 let generate = strings::tr(&ctx, &txt::THEME_EDITOR_OTHER);
2204 if ui
2205 .button(&generate)
2206 .on_hover_text(strings::tr_args(
2207 &ctx,
2208 &txt::THEME_EDITOR_OTHER_HINT,
2209 &[("theme", &other)],
2210 ))
2211 .clicked()
2212 {
2213 editor.propose_counterpart(app);
2214 }
2215 });
2216 let Some(proposal) = editor.proposal() else {
2217 return;
2218 };
2219 let t = Tokens::of(&ctx);
2220 egui::Frame::new()
2221 .stroke(egui::Stroke::new(1.0, t.border.default))
2222 .inner_margin(egui::Margin::same(t.space.s.round().clamp(0.0, 127.0) as i8))
2223 .show(ui, |ui| {
2224 ui.strong(strings::tr_args(
2225 &ctx,
2226 &txt::THEME_EDITOR_OTHER_TITLE,
2227 &[("theme", &other)],
2228 ));
2229 if proposal.edits.is_empty() {
2230 ui.weak(strings::tr_args(
2231 &ctx,
2232 &txt::THEME_EDITOR_OTHER_NONE,
2233 &[("theme", &other)],
2234 ));
2235 } else {
2236 ui.weak(strings::tr(&ctx, &txt::THEME_EDITOR_OTHER_PREVIEWED));
2237 let draft = editor.draft();
2238 let before = draft.counterpart().map(|c| {
2239 let themes = app.theme();
2240 themes.themes().resolve(&c.spec(&themes.spec()))
2241 });
2242 ui.scroll_area(
2243 egui::ScrollArea::vertical()
2244 .id_salt("egui_pop.theme_editor.proposal")
2245 .max_height(160.0),
2246 |ui| {
2247 egui::Grid::new("egui_pop.theme_editor.proposal.grid")
2248 .num_columns(3)
2249 .show(ui, |ui| {
2250 for e in &proposal.edits {
2251 ui.monospace(&e.path);
2252 let was = before.as_ref().and_then(|b| b.color(&e.path));
2253 let to =
2254 e.to.as_ref()
2255 .and_then(Json::as_str)
2256 .and_then(Color::from_hex);
2257 swatch(ui, was.map(color32));
2258 match (&e.to, to) {
2259 (_, Some(c)) => swatch(ui, Some(color32(c))),
2260 (Some(v), None) => {
2261 ui.monospace(v.to_string());
2262 }
2263 (None, None) => {
2264 ui.weak(strings::tr_args(
2265 &ctx,
2266 &txt::THEME_EDITOR_FROM,
2267 &[("theme", &other)],
2268 ));
2269 }
2270 }
2271 ui.end_row();
2272 }
2273 });
2274 },
2275 );
2276 }
2277 if !proposal.skipped.is_empty() {
2278 ui.weak(strings::tr_args(
2279 &ctx,
2280 &txt::THEME_EDITOR_SKIPPED,
2281 &[("tokens", &proposal.skipped.join(", "))],
2282 ));
2283 }
2284 ui.horizontal(|ui| {
2285 let apply =
2286 strings::tr_args(&ctx, &txt::THEME_EDITOR_OTHER_APPLY, &[("theme", &other)]);
2287 if ui
2288 .add_enabled(!proposal.edits.is_empty(), egui::Button::new(&apply))
2289 .clicked()
2290 {
2291 let out = editor.apply_counterpart(app, Cause::Edit).map(|n| {
2292 Some(strings::tr_with(
2293 &ctx,
2294 &txt::THEME_EDITOR_OTHER_WRITTEN,
2295 &[("count", n.into()), ("theme", Arg::Str(&other))],
2296 ))
2297 });
2298 say(editor, out);
2299 }
2300 if ui
2301 .button(strings::tr(&ctx, &txt::THEME_EDITOR_OTHER_CANCEL))
2302 .clicked()
2303 {
2304 editor.drop_proposal();
2305 }
2306 });
2307 });
2308}
2309
2310fn say(editor: &ThemeEditor, out: Result<Option<String>, String>) {
2312 let mut s = lock(&editor.state);
2313 s.message = match out {
2314 Ok(None) => None,
2315 Ok(Some(m)) => Some((true, m)),
2316 Err(e) => Some((false, e)),
2317 };
2318}
2319
2320fn list(ui: &mut Ui, editor: &ThemeEditor, tokens: &ResolvedTokens) {
2321 let ctx = ui.ctx().clone();
2322 let (filter, selected, draft) = {
2323 let s = lock(&editor.state);
2324 (s.filter.to_lowercase(), s.selected.clone(), s.draft.clone())
2325 };
2326 let edited = strings::tr(&ctx, &txt::THEME_EDITOR_EDITED);
2327 ui.scroll_area(
2328 egui::ScrollArea::vertical()
2329 .id_salt("egui_pop.theme_editor.list")
2330 .max_height(ui.available_height().max(240.0))
2331 .auto_shrink([false, true]),
2332 |ui| {
2333 for group in groups(tokens) {
2334 let paths: Vec<&String> = group
2335 .paths
2336 .iter()
2337 .filter(|p| filter.is_empty() || p.contains(&filter))
2338 .collect();
2339 if paths.is_empty() {
2340 continue;
2341 }
2342 let title = strings::tr(&ctx, group.title);
2343 egui::CollapsingHeader::new(&title)
2344 .id_salt(("egui_pop.theme_editor.group", group.title.key))
2345 .default_open(group.open || !filter.is_empty())
2346 .open((!filter.is_empty()).then_some(true))
2347 .show(ui, |ui| {
2348 for path in paths {
2349 ui.horizontal(|ui| {
2350 let fill = tokens.color(path);
2351 swatch(ui, fill.map(color32));
2352 let own = draft.value(path).is_some();
2353 let text = if own {
2354 RichText::new(path.as_str()).strong()
2355 } else {
2356 RichText::new(path.as_str())
2357 };
2358 let is = selected.as_deref() == Some(path.as_str());
2359 let r = widgets::selectable_label(ui, is, text);
2360 if own {
2361 ui.weak(&edited);
2362 }
2363 if r.clicked() {
2364 let mut s = lock(&editor.state);
2365 s.selected = Some(path.clone());
2366 s.typing = None;
2367 }
2368 });
2369 }
2370 });
2371 }
2372 },
2373 );
2374}
2375
2376fn swatch(ui: &mut Ui, fill: Option<egui::Color32>) {
2378 let t = Tokens::of(ui.ctx());
2379 let side = ui.spacing().interact_size.y * 0.7;
2380 let (rect, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
2381 if let Some(fill) = fill {
2382 ui.painter().rect(
2383 rect,
2384 egui::CornerRadius::same(2),
2385 fill,
2386 egui::Stroke::new(1.0, t.border.strong),
2387 egui::StrokeKind::Inside,
2388 );
2389 }
2390}
2391
2392fn detail(
2393 ui: &mut Ui,
2394 app: &AppHandle,
2395 editor: &ThemeEditor,
2396 tokens: &ResolvedTokens,
2397 t: &egui_pop_core::tokens::Token,
2398) {
2399 let ctx = ui.ctx().clone();
2400 let draft = editor.draft();
2401 let path = t.path.as_str();
2402 ui.heading(path);
2403 let d = description(path, t.description.as_deref());
2404 if !d.is_empty() {
2405 ui.weak(d);
2406 }
2407 ui.label(strings::tr_args(
2408 &ctx,
2409 &txt::THEME_EDITOR_TYPE,
2410 &[("type", &t.ty)],
2411 ));
2412 let own = draft.value(path).is_some();
2413 let base = theme_label(draft.base());
2414 ui.label(if own {
2415 strings::tr(&ctx, &txt::THEME_EDITOR_OWN)
2416 } else {
2417 strings::tr_args(&ctx, &txt::THEME_EDITOR_FROM, &[("theme", &base)])
2418 });
2419 if let Some(a) = &t.alias {
2420 ui.label(strings::tr_args(
2421 &ctx,
2422 &txt::THEME_EDITOR_ALIAS_OF,
2423 &[("token", a)],
2424 ));
2425 }
2426 ui.horizontal(|ui| {
2427 value_widget(ui, app, editor, t);
2428 });
2429 ui.horizontal(|ui| {
2430 let label = strings::tr(&ctx, &txt::THEME_EDITOR_VALUE);
2431 ui.label(&label);
2432 let mut text = {
2433 let s = lock(&editor.state);
2434 match &s.typing {
2435 Some((p, text)) if p == path => text.clone(),
2436 _ => typed_text(&draft, t),
2437 }
2438 };
2439 let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(220.0));
2440 let name = strings::tr_args(&ctx, &txt::THEME_EDITOR_VALUE_OF, &[("token", path)]);
2441 egui_pop_core::a11y::name(&r, egui::Role::TextInput, &name);
2442 if r.changed() || r.has_focus() {
2443 lock(&editor.state).typing = Some((path.to_string(), text.clone()));
2444 }
2445 let enter = r.lost_focus();
2446 if enter {
2447 lock(&editor.state).typing = None;
2448 if text.trim() != typed_text(&draft, t) {
2449 let out = match parse_typed(&t.ty, &text) {
2450 Some(v) => editor.set(app, path, Some(v), Cause::Edit),
2451 None => Err(strings::tr_args(
2452 &ctx,
2453 &txt::THEME_EDITOR_NOT_A_VALUE,
2454 &[("type", &t.ty)],
2455 )),
2456 };
2457 say(editor, out.map(|_| None));
2458 }
2459 }
2460 let reset = strings::tr_args(&ctx, &txt::THEME_EDITOR_RESET, &[("theme", &base)]);
2461 if ui.add_enabled(own, egui::Button::new(&reset)).clicked() {
2462 say(
2463 editor,
2464 editor.set(app, path, None, Cause::Reset).map(|_| None),
2465 );
2466 }
2467 });
2468 if let Some(scale) = scale_of(tokens, path) {
2469 generator(ui, app, editor, tokens, &scale);
2470 }
2471 contrast_readouts(ui, tokens, path);
2472}
2473
2474pub fn scale_of(tokens: &ResolvedTokens, path: &str) -> Option<String> {
2477 let (scale, _) = path.rsplit_once('.')?;
2478 let nine = tokens.get(&format!("{scale}.9"))?;
2479 (nine.tier() == Tier::Reference && nine.ty == "color").then(|| scale.to_string())
2480}
2481
2482fn hex_field(
2486 ui: &mut Ui,
2487 editor: &ThemeEditor,
2488 key: &str,
2489 color: Color,
2490 name: &str,
2491 live: bool,
2492) -> Option<Color> {
2493 let mut text = {
2494 let s = lock(&editor.state);
2495 match &s.hex {
2496 Some((k, t)) if k == key => t.clone(),
2497 _ => color.to_hex(),
2498 }
2499 };
2500 let r = ui.add(
2501 egui::TextEdit::singleline(&mut text)
2502 .font(egui::TextStyle::Monospace)
2503 .desired_width(80.0),
2504 );
2505 egui_pop_core::a11y::name(&r, egui::Role::TextInput, name);
2506 if r.changed() || r.has_focus() {
2507 lock(&editor.state).hex = Some((key.to_string(), text.clone()));
2508 }
2509 let typed = Color::from_hex(text.trim()).filter(|c| c.to_hex() != color.to_hex());
2510 if r.lost_focus() {
2511 lock(&editor.state).hex = None;
2512 return typed;
2513 }
2514 if live && r.changed() { typed } else { None }
2515}
2516
2517fn generator(
2520 ui: &mut Ui,
2521 app: &AppHandle,
2522 editor: &ThemeEditor,
2523 tokens: &ResolvedTokens,
2524 scale: &str,
2525) {
2526 let ctx = ui.ctx().clone();
2527 let t = Tokens::of(&ctx);
2528 ui.add_space(t.space.m);
2529 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_GENERATE_TITLE));
2530 let current = tokens
2531 .color(&format!("{scale}.9"))
2532 .unwrap_or(Color::MISSING);
2533 let mut seed = {
2534 let s = lock(&editor.state);
2535 match &s.seed {
2536 Some((k, c)) if k == scale => *c,
2537 _ => s.draft.seed(scale).map_or(current, |seed| seed.color),
2539 }
2540 };
2541 let before = seed;
2542 ui.horizontal(|ui| {
2543 let name = strings::tr_args(&ctx, &txt::THEME_EDITOR_SEED_OF, &[("scale", scale)]);
2544 let mut c32 = color32(seed);
2545 let r = egui::color_picker::color_edit_button_srgba(
2546 ui,
2547 &mut c32,
2548 egui::color_picker::Alpha::Opaque,
2549 );
2550 r.widget_info(|| WidgetInfo::labeled(egui::Role::ColorWell, true, &name));
2551 if r.changed() {
2552 let [r8, g8, b8, _] = c32.to_srgba_unmultiplied();
2553 seed = Color::rgb(
2554 f32::from(r8) / 255.0,
2555 f32::from(g8) / 255.0,
2556 f32::from(b8) / 255.0,
2557 );
2558 }
2559 let hex_name = strings::tr_args(&ctx, &txt::THEME_EDITOR_SEED_HEX_OF, &[("scale", scale)]);
2560 if let Some(c) = hex_field(ui, editor, &format!("seed:{scale}"), seed, &hex_name, true) {
2561 seed = Color { a: 1.0, ..c };
2562 }
2563 let label = strings::tr_args(&ctx, &txt::THEME_EDITOR_GENERATE, &[("scale", scale)]);
2564 if ui.button(&label).clicked() {
2565 let out = editor.generate(app, scale, seed, Cause::Edit).map(|n| {
2566 Some(strings::tr_with(
2567 &ctx,
2568 &txt::THEME_EDITOR_GENERATED,
2569 &[("count", n.into()), ("scale", Arg::Str(scale))],
2570 ))
2571 });
2572 say(editor, out);
2573 }
2574 });
2575 if seed != before {
2576 lock(&editor.state).seed = Some((scale.to_string(), seed));
2577 }
2578 if !palette::is_usable_seed(seed) {
2579 ui.weak(strings::tr_args(
2580 &ctx,
2581 &txt::THEME_EDITOR_SEED_CLAMPED,
2582 &[("color", &palette::clamp_seed(seed).to_hex())],
2583 ));
2584 }
2585 let ramp = {
2587 let themes = app.theme();
2588 editor
2589 .draft()
2590 .seeded_ramp(themes.themes(), scale, Seed::new(seed, scheme_of(tokens)))
2591 };
2592 ui.horizontal(|ui| {
2593 ui.spacing_mut().item_spacing.x = 2.0;
2594 for c in ramp.steps {
2595 swatch(ui, Some(color32(c)));
2596 }
2597 });
2598 if editor.draft().is_paired() {
2599 ui.weak(strings::tr(&ctx, &txt::THEME_EDITOR_GENERATE_VARIANT));
2600 }
2601}
2602
2603fn scheme_of(tokens: &ResolvedTokens) -> Scheme {
2605 if tokens.is_dark() {
2606 Scheme::Dark
2607 } else {
2608 Scheme::Light
2609 }
2610}
2611
2612fn value_widget(
2614 ui: &mut Ui,
2615 app: &AppHandle,
2616 editor: &ThemeEditor,
2617 t: &egui_pop_core::tokens::Token,
2618) {
2619 let ctx = ui.ctx().clone();
2620 let path = t.path.as_str();
2621 let name = strings::tr_args(&ctx, &txt::THEME_EDITOR_ADJUST_OF, &[("token", path)]);
2622 let (response, to, keys) = match &t.value {
2623 Value::Color(c) => {
2624 let mut c32 = color32(*c);
2625 let r = egui::color_picker::color_edit_button_srgba(
2626 ui,
2627 &mut c32,
2628 egui::color_picker::Alpha::OnlyBlend,
2629 );
2630 let [r8, g8, b8, a8] = c32.to_srgba_unmultiplied();
2631 let picked = Color {
2632 r: f32::from(r8) / 255.0,
2633 g: f32::from(g8) / 255.0,
2634 b: f32::from(b8) / 255.0,
2635 a: f32::from(a8) / 255.0,
2636 };
2637 r.widget_info(|| WidgetInfo::labeled(egui::Role::ColorWell, true, &name));
2638 let hex_name = strings::tr_args(&ctx, &txt::THEME_EDITOR_HEX_OF, &[("token", path)]);
2639 if let Some(typed) = hex_field(ui, editor, path, *c, &hex_name, false) {
2640 say(
2641 editor,
2642 editor
2643 .set(app, path, Some(json!(typed.to_hex())), Cause::Edit)
2644 .map(|_| None),
2645 );
2646 }
2647 let to = json!(picked.to_hex());
2648 (r, to, false)
2649 }
2650 Value::Dimension(v) | Value::Number(v) | Value::Duration(v) => {
2651 let mut x = *v;
2652 let unit = match &t.value {
2653 Value::Dimension(_) => " px",
2654 Value::Duration(_) => " ms",
2655 _ => "",
2656 };
2657 let speed = if matches!(t.value, Value::Number(_)) {
2658 0.01
2659 } else {
2660 0.25
2661 };
2662 let r = ui.add(egui::DragValue::new(&mut x).speed(speed).suffix(unit));
2663 r.widget_info(|| WidgetInfo::labeled(egui::Role::SpinButton, true, &name));
2664 let to = match &t.value {
2665 Value::Dimension(_) => json!({ "value": x, "unit": "px" }),
2666 Value::Duration(_) => json!({ "value": x, "unit": "ms" }),
2667 _ => json!(x),
2668 };
2669 (r, to, true)
2670 }
2671 other => {
2672 ui.monospace(other.display());
2673 return;
2674 }
2675 };
2676 if response.changed() {
2677 let mut s = lock(&editor.state);
2678 if s.gesture.as_ref().is_none_or(|g| g.path != path) {
2679 let from = s.draft.value(path).cloned();
2680 s.gesture = Some(Gesture {
2681 path: path.to_string(),
2682 from,
2683 widget: response.id,
2684 keys,
2685 });
2686 }
2687 s.draft.preview(path, Some(to));
2688 drop(s);
2689 editor.write(app);
2690 }
2691}
2692
2693fn finish_gesture(ui: &Ui, app: &AppHandle, editor: &ThemeEditor) {
2696 let busy = ui.input(|i| i.pointer.any_down());
2697 let mut s = lock(&editor.state);
2698 let Some(g) = s.gesture.as_ref() else {
2699 return;
2700 };
2701 if busy || (g.keys && ui.ctx().memory(|m| m.has_focus(g.widget))) {
2702 return;
2703 }
2704 let g = s.gesture.take().expect("checked above");
2705 let to = s.draft.value(&g.path).cloned();
2706 s.draft.preview(&g.path, g.from.clone());
2708 drop(s);
2709 let out = editor.set(app, &g.path, to, Cause::Edit);
2710 if out.is_err() {
2711 editor.write(app);
2712 }
2713 say(editor, out.map(|_| None));
2714}
2715
2716fn contrast_readouts(ui: &mut Ui, tokens: &ResolvedTokens, path: &str) {
2717 let ctx = ui.ctx().clone();
2718 let t = Tokens::of(&ctx);
2719 let readouts = contrast_of(tokens, path);
2720 ui.add_space(t.space.m);
2721 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_CONTRAST));
2722 if readouts.is_empty() {
2723 ui.weak(strings::tr(&ctx, &txt::THEME_EDITOR_NO_PAIRS));
2724 return;
2725 }
2726 let pass = strings::tr(&ctx, &txt::THEME_EDITOR_PASS);
2727 let fail = strings::tr(&ctx, &txt::THEME_EDITOR_FAIL);
2728 let none = strings::tr(&ctx, &txt::THEME_EDITOR_NOT_APPLICABLE);
2729 let verdict = |ui: &mut Ui, ok: Option<bool>| match ok {
2730 Some(true) => {
2731 ui.colored_label(t.status.success, &pass);
2732 }
2733 Some(false) => {
2734 ui.colored_label(t.status.danger, &fail);
2735 }
2736 None => {
2737 ui.weak(&none);
2738 }
2739 };
2740 egui::Grid::new(("egui_pop.theme_editor.contrast", path))
2741 .num_columns(6)
2742 .striped(true)
2743 .show(ui, |ui| {
2744 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_PAIR));
2745 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_RATIO));
2746 ui.strong("AA");
2747 ui.strong("AAA");
2748 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_THEME_NEEDS));
2749 ui.strong("APCA Lc")
2750 .on_hover_text(strings::tr(&ctx, &txt::THEME_EDITOR_LC_HINT));
2751 ui.end_row();
2752 for r in &readouts {
2753 ui.label(strings::tr_args(
2754 &ctx,
2755 &txt::THEME_EDITOR_PAIR_ON,
2756 &[
2757 ("foreground", r.pair.foreground),
2758 ("background", r.pair.background),
2759 ],
2760 ));
2761 ui.monospace(r.ratio.map_or("-".into(), |x| format!("{x:.2}:1")));
2762 verdict(ui, Some(r.passes_aa()));
2763 verdict(ui, r.passes_aaa());
2764 let needs = format!("{}:1", r.required);
2765 if r.passes() {
2766 ui.colored_label(t.status.success, needs);
2767 } else {
2768 ui.colored_label(t.status.danger, needs);
2769 }
2770 ui.monospace(r.lc.map_or("-".into(), |l| format!("{l:.0}")));
2771 ui.end_row();
2772 }
2773 });
2774}
2775
2776fn poll_choice(app: &AppHandle, editor: &ThemeEditor, ctx: &egui::Context) {
2778 let answer = {
2779 let s = lock(&editor.state);
2780 let pending = match &s.choice {
2781 Some(Choice::Open(p) | Choice::Save(p) | Choice::Font(p)) => p.clone(),
2782 None => return,
2783 };
2784 drop(s);
2785 match pending.take() {
2786 Some(a) => a,
2787 None => return,
2788 }
2789 };
2790 let Some(choice) = lock(&editor.state).choice.take() else {
2791 return;
2792 };
2793 let path = match files::chosen(&answer) {
2794 Ok(files::Chosen::Paths(p)) => match p.into_iter().next() {
2795 Some(p) => p,
2796 None => return,
2797 },
2798 Ok(files::Chosen::Cancelled) => return,
2799 Err(e) => return say(editor, Err(e)),
2800 };
2801 let out = match choice {
2802 Choice::Open(_) => editor.open_file(app, &path).map(|w| {
2803 let base = theme_label(editor.draft().base());
2804 let mut m = strings::tr_args(ctx, &txt::THEME_EDITOR_IMPORTED, &[("theme", &base)]);
2805 if !w.is_empty() {
2806 let said: Vec<String> = w.iter().map(ToString::to_string).collect();
2807 m.push(' ');
2808 m.push_str(&strings::tr_args(
2809 ctx,
2810 &txt::THEME_EDITOR_WARNINGS,
2811 &[("warnings", &said.join("; "))],
2812 ));
2813 }
2814 Some(m)
2815 }),
2816 Choice::Font(_) => editor.add_font_file(&path).map(|f| {
2817 Some(strings::tr_args(
2818 ctx,
2819 &txt::THEME_EDITOR_FONT_ADDED,
2820 &[("family", &f.family), ("weight", &f.weight.0.to_string())],
2821 ))
2822 }),
2823 Choice::Save(_) => editor.save_file(app, &path).map(|written| {
2824 Some(strings::tr_args(
2825 ctx,
2826 &txt::THEME_EDITOR_SAVED,
2827 &[("path", &written.display().to_string())],
2828 ))
2829 }),
2830 };
2831 say(editor, out);
2832}
2833
2834fn fonts_tab(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor) {
2838 let ctx = ui.ctx().clone();
2839 let t = Tokens::of(&ctx);
2840 let tr = |k: &strings::StrKey| strings::tr(&ctx, k);
2841 ui.strong(tr(&txt::THEME_EDITOR_FAMILIES));
2842 ui.weak(tr(&txt::THEME_EDITOR_FAMILIES_HINT));
2843 let mut rested: Option<(Role, String)> = None;
2846 let mut over_row = false;
2847 for (i, role, title) in [
2848 (0, Role::Ui, &txt::THEME_EDITOR_FAMILY_UI),
2849 (1, Role::Mono, &txt::THEME_EDITOR_FAMILY_MONO),
2850 ] {
2851 ui.add_space(t.space.s);
2852 ui.label(RichText::new(tr(title)).strong());
2853 let mut list = editor.families(app, role);
2854 let mut changed = false;
2855 let last = list.len().saturating_sub(1);
2856 let mut action = None;
2857 for (at, name) in list.iter().enumerate() {
2858 ui.horizontal(|ui| {
2859 let r = ui.monospace(name);
2860 if rests_on(&r) {
2861 rested = Some((role, name.clone()));
2862 }
2863 over_row |= r.hovered();
2864 if egui_pop_core::fonts::origin_of(&ctx, name).is_none() {
2865 ui.colored_label(t.status.warning, tr(&txt::THEME_EDITOR_FAMILY_MISSING));
2866 }
2867 let args = [("family", name.as_str())];
2868 let up = strings::tr_args(&ctx, &txt::THEME_EDITOR_MOVE_UP, &args);
2869 let down = strings::tr_args(&ctx, &txt::THEME_EDITOR_MOVE_DOWN, &args);
2870 let remove = strings::tr_args(&ctx, &txt::THEME_EDITOR_REMOVE_FAMILY, &args);
2871 if ui.add_enabled(at > 0, egui::Button::new(&up)).clicked() {
2872 action = Some((at, -1));
2873 }
2874 if ui
2875 .add_enabled(at < last, egui::Button::new(&down))
2876 .clicked()
2877 {
2878 action = Some((at, 1));
2879 }
2880 if ui.button(&remove).clicked() {
2881 action = Some((at, 0));
2882 }
2883 });
2884 }
2885 match action {
2886 Some((at, 0)) => {
2887 list.remove(at);
2888 changed = true;
2889 }
2890 Some((at, d)) => {
2891 let to = if d < 0 { at - 1 } else { at + 1 };
2892 list.swap(at, to);
2893 changed = true;
2894 }
2895 None => {}
2896 }
2897 ui.horizontal(|ui| {
2898 let hint = strings::tr_args(
2899 &ctx,
2900 &txt::THEME_EDITOR_ADD_FAMILY_TO,
2901 &[("role", family_token(role))],
2902 );
2903 let mut typed = lock(&editor.state).fonts.adding[i].clone();
2904 let r = ui.add(
2905 egui::TextEdit::singleline(&mut typed)
2906 .hint_text(&hint)
2907 .desired_width(200.0),
2908 );
2909 egui_pop_core::a11y::name(&r, egui::Role::TextInput, &hint);
2910 let add = ui.button(tr(&txt::THEME_EDITOR_ADD)).clicked()
2911 || (r.lost_focus() && ui.input(|inp| inp.key_pressed(egui::Key::Enter)));
2912 if add && !typed.trim().is_empty() {
2913 let name = typed.trim().to_string();
2914 if !list.contains(&name) {
2915 list.push(name);
2916 changed = true;
2917 }
2918 typed.clear();
2919 }
2920 lock(&editor.state).fonts.adding[i] = typed;
2921 });
2922 if changed {
2923 editor.set_families(role, list);
2924 }
2925 }
2926 installed_families(ui, app, editor, &mut rested, &mut over_row);
2927 match rested {
2928 Some((role, name)) => editor.preview_face(role, Some(&name)),
2929 None if !over_row => editor.preview_face(Role::Ui, None),
2930 None => {}
2931 }
2932
2933 ui.add_space(t.space.m);
2934 ui.strong(tr(&txt::THEME_EDITOR_FONT_FILES));
2935 let files = editor.edited_font_files();
2936 if files.is_empty() {
2937 ui.weak(tr(&txt::THEME_EDITOR_NO_FONT_FILES));
2938 }
2939 for f in &files {
2940 ui.horizontal(|ui| {
2941 ui.label(format!("{} {}", f.family, f.weight.0));
2942 ui.weak(f.path.display().to_string());
2943 let remove = strings::tr_args(
2944 &ctx,
2945 &txt::THEME_EDITOR_REMOVE_FONT_FILE,
2946 &[("family", &f.family)],
2947 );
2948 if ui.button(&remove).clicked() {
2949 editor.remove_font_file(&f.path);
2950 }
2951 });
2952 }
2953 if editor.can_choose(app) {
2954 let add = tr(&txt::THEME_EDITOR_ADD_FONT_FILE);
2955 if ui.button(&add).clicked() {
2956 let request = FileRequest::open(&add).filter("Fonts", &["ttf", "otf", "ttc"]);
2957 if let Some(p) = editor.choose(app, request) {
2958 lock(&editor.state).choice = Some(Choice::Font(p));
2959 }
2960 }
2961 }
2962
2963 ui.add_space(t.space.m);
2964 editor.sync_font_preview(app);
2965 preview_pane(ui, app, editor, true);
2966 ui.weak(tr(&txt::THEME_EDITOR_FONT_SAMPLE_HINT));
2967
2968 ui.add_space(t.space.m);
2969 ui.horizontal(|ui| {
2970 let pending = editor.fonts_pending(app);
2971 if ui
2972 .add_enabled(
2973 pending,
2974 egui::Button::new(tr(&txt::THEME_EDITOR_APPLY_FONTS)),
2975 )
2976 .clicked()
2977 {
2978 let out = editor.apply_fonts(app, Cause::Edit).map(|_| None);
2979 say(editor, out);
2980 }
2981 if ui
2982 .add_enabled(
2983 pending,
2984 egui::Button::new(tr(&txt::THEME_EDITOR_CANCEL_FONTS)),
2985 )
2986 .clicked()
2987 {
2988 editor.cancel_fonts(app);
2989 }
2990 ui.weak(tr(&txt::THEME_EDITOR_APPLY_FONTS_HINT));
2991 });
2992 let problems = lock(&editor.state).fonts.problems.clone();
2993 for p in problems {
2994 ui.colored_label(t.status.warning, p);
2995 }
2996 let message = lock(&editor.state).message.clone();
2997 if let Some((ok, m)) = message {
2998 ui.colored_label(
2999 if ok {
3000 t.status.success
3001 } else {
3002 t.status.danger
3003 },
3004 m,
3005 );
3006 }
3007}
3008
3009fn installed_families(
3015 ui: &mut Ui,
3016 app: &AppHandle,
3017 editor: &ThemeEditor,
3018 rested: &mut Option<(Role, String)>,
3019 over_row: &mut bool,
3020) {
3021 let ctx = ui.ctx().clone();
3022 let t = Tokens::of(&ctx);
3023 let tr = |k: &strings::StrKey| strings::tr(&ctx, k);
3024 ui.add_space(t.space.m);
3025 ui.strong(tr(&txt::THEME_EDITOR_INSTALLED));
3026 ui.weak(tr(&txt::THEME_EDITOR_INSTALLED_HINT));
3027 let (mut role, mut search) = {
3028 let s = lock(&editor.state);
3029 (
3030 s.fonts.face_role.unwrap_or(Role::Ui),
3031 s.fonts.face_search.clone(),
3032 )
3033 };
3034 ui.horizontal(|ui| {
3035 widgets::selectable_value(ui, &mut role, Role::Ui, tr(&txt::THEME_EDITOR_FOR_UI));
3036 widgets::selectable_value(ui, &mut role, Role::Mono, tr(&txt::THEME_EDITOR_FOR_MONO));
3037 let hint = tr(&txt::THEME_EDITOR_SEARCH_FAMILIES);
3038 let r = ui.add(
3039 egui::TextEdit::singleline(&mut search)
3040 .hint_text(&hint)
3041 .desired_width(200.0),
3042 );
3043 egui_pop_core::a11y::name(&r, egui::Role::TextInput, &hint);
3044 });
3045 {
3046 let mut s = lock(&editor.state);
3047 s.fonts.face_role = Some(role);
3048 s.fonts.face_search = search;
3049 }
3050 let faces = editor.installed_families(app, role);
3051 if faces.is_empty() {
3052 ui.weak(tr(&txt::THEME_EDITOR_NO_FAMILY_MATCHES));
3053 return;
3054 }
3055 let first = editor.families(app, role).into_iter().next();
3056 let row = ui.spacing().interact_size.y;
3057 let mut picked = None;
3058 ui.scroll_area_rows(
3059 egui::ScrollArea::vertical()
3060 .id_salt("egui_pop.theme_editor.installed")
3061 .max_height(row * 8.0)
3062 .auto_shrink([false, true]),
3063 row,
3064 faces.len(),
3065 |ui, range| {
3066 for f in &faces[range] {
3067 ui.horizontal(|ui| {
3068 let first = first
3069 .as_deref()
3070 .is_some_and(|n| n.eq_ignore_ascii_case(&f.name));
3071 let r = ui.selectable_label(first, &f.name);
3072 *over_row |= r.hovered();
3073 if rests_on(&r) {
3074 *rested = Some((role, f.name.clone()));
3075 }
3076 if r.clicked() {
3077 picked = Some(f.name.clone());
3078 }
3079 ui.weak(crate::settings_window::origin_name(&ctx, f.origin));
3080 });
3081 }
3082 },
3083 );
3084 if let Some(name) = picked {
3085 editor.choose_face(app, role, &name);
3086 }
3087}
3088
3089pub fn font_sample(ui: &mut Ui) {
3094 let ctx = ui.ctx().clone();
3095 let size = Tokens::of(&ctx).font.body;
3096 let sample = strings::tr(&ctx, &txt::THEME_EDITOR_FONT_SAMPLE_TEXT);
3097 for role in Role::ALL {
3098 ui.label(
3099 RichText::new(&sample).font(egui_pop_core::fonts::shown_font_id(
3100 &ctx,
3101 role,
3102 egui_pop_core::fonts::Weight::REGULAR,
3103 size,
3104 )),
3105 );
3106 }
3107}
3108
3109const PREVIEW_REST: f32 = 0.15;
3112
3113pub(crate) fn rests_on(r: &egui::Response) -> bool {
3116 if !r.hovered() {
3117 return false;
3118 }
3119 let still = r.ctx.input(|i| i.pointer.time_since_last_movement());
3120 if still >= PREVIEW_REST {
3121 return true;
3122 }
3123 r.ctx
3124 .request_repaint_after(std::time::Duration::from_secs_f32(PREVIEW_REST - still));
3125 false
3126}
3127
3128fn preview_pane(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor, fonts: bool) {
3133 let ctx = ui.ctx().clone();
3134 ui.strong(strings::tr(&ctx, &txt::THEME_EDITOR_PREVIEW));
3135 let not_applied = if fonts {
3136 editor.fonts_pending(app)
3137 } else {
3138 editor.preview_only() && editor.pending(app)
3139 };
3140 if not_applied {
3141 ui.weak(strings::tr(&ctx, &txt::THEME_EDITOR_NOT_APPLIED));
3142 }
3143 let scoped = editor.scoped(app);
3144 let sampler = lock(&editor.state).sampler.clone();
3145 let draw = |ui: &mut Ui| {
3146 match sampler {
3147 Some(f) => f(ui, app),
3148 None => sample(ui),
3149 }
3150 if fonts {
3151 ui.separator();
3152 font_sample(ui);
3153 }
3154 };
3155 scoped.show(ui, |ui| {
3156 let t = Tokens::of(ui.ctx());
3157 egui::Frame::new()
3158 .fill(t.surface.panel)
3159 .stroke(egui::Stroke::new(1.0, t.border.default))
3160 .corner_radius(egui::CornerRadius::same(
3161 t.radius.window.round().clamp(0.0, 255.0) as u8,
3162 ))
3163 .inner_margin(egui::Margin::same(t.space.m.round().clamp(0.0, 127.0) as i8))
3164 .show(ui, |ui| {
3165 ui.set_width(ui.available_width());
3166 if fonts {
3167 egui_pop_core::fonts::with_preview(ui, draw);
3168 } else {
3169 draw(ui);
3170 }
3171 });
3172 });
3173}
3174
3175const SAMPLE: Slot<(bool, f32, String, usize)> = Slot::new("api.theme_editor.sample");
3177
3178pub fn sample(ui: &mut Ui) {
3183 let ctx = ui.ctx().clone();
3184 let t = Tokens::of(&ctx);
3185 let (mut on, mut level, mut text, mut option) =
3186 SAMPLE.get(&ctx).unwrap_or((true, 0.6, String::new(), 0));
3187 let tr = |k: &strings::StrKey| strings::tr(&ctx, k);
3188 ui.heading(tr(&txt::THEME_EDITOR_SAMPLE_HEADING));
3189 ui.label(tr(&txt::THEME_EDITOR_SAMPLE_TEXT));
3190 ui.weak(tr(&txt::THEME_EDITOR_SAMPLE_MUTED));
3191 ui.horizontal_wrapped(|ui| {
3192 for (name, color) in [
3193 ("danger", t.status.danger),
3194 ("warning", t.status.warning),
3195 ("success", t.status.success),
3196 ("info", t.status.info),
3197 ("accent", t.accent.default),
3198 ] {
3199 ui.colored_label(color, name);
3200 }
3201 });
3202 ui.horizontal_wrapped(|ui| {
3203 let _ = ui.button(tr(&txt::THEME_EDITOR_SAMPLE_BUTTON));
3204 let _ = ui.button_tone(Tone::Accent, tr(&txt::THEME_EDITOR_SAMPLE_PRIMARY));
3205 let _ = ui.button_tone(Tone::Danger, tr(&txt::THEME_EDITOR_SAMPLE_DANGER));
3206 ui.add_enabled(
3207 false,
3208 egui::Button::new(tr(&txt::THEME_EDITOR_SAMPLE_DISABLED)),
3209 );
3210 });
3211 ui.horizontal_wrapped(|ui| {
3212 widgets::checkbox(ui, &mut on, tr(&txt::THEME_EDITOR_SAMPLE_CHECKBOX));
3213 widgets::radio_value(ui, &mut option, 0, tr(&txt::THEME_EDITOR_SAMPLE_OPTION_A));
3214 widgets::radio_value(ui, &mut option, 1, tr(&txt::THEME_EDITOR_SAMPLE_OPTION_B));
3215 });
3216 ui.horizontal_wrapped(|ui| {
3217 ui.add(egui::Slider::new(&mut level, 0.0..=1.0).text(tr(&txt::THEME_EDITOR_SAMPLE_SLIDER)));
3218 let hint = tr(&txt::THEME_EDITOR_SAMPLE_FIELD);
3219 let r = ui.add(
3220 egui::TextEdit::singleline(&mut text)
3221 .hint_text(&hint)
3222 .desired_width(140.0),
3223 );
3224 egui_pop_core::a11y::name(&r, egui::Role::TextInput, &hint);
3225 });
3226 let _ = widgets::selectable_label(ui, true, tr(&txt::THEME_EDITOR_SAMPLE_SELECTED));
3227 ui.add(egui::ProgressBar::new(level).desired_width(220.0));
3228 SAMPLE.set(&ctx, (on, level, text, option));
3229}
3230
3231fn file(ui: &mut Ui, app: &AppHandle, editor: &ThemeEditor) {
3232 let ctx = ui.ctx().clone();
3233 let title = strings::tr(&ctx, &txt::THEME_EDITOR_FILE);
3234 egui::CollapsingHeader::new(&title)
3235 .id_salt("egui_pop.theme_editor.file")
3236 .default_open(false)
3237 .show(ui, |ui| {
3238 ui.horizontal(|ui| {
3239 let label = strings::tr(&ctx, &txt::THEME_EDITOR_NAME);
3240 let l = ui.label(&label);
3241 let mut name = {
3242 let s = lock(&editor.state);
3243 if s.file_name.is_empty() {
3244 "my-theme".to_string()
3245 } else {
3246 s.file_name.clone()
3247 }
3248 };
3249 if ui
3250 .add(egui::TextEdit::singleline(&mut name).desired_width(160.0))
3251 .labelled_by(l.id)
3252 .changed()
3253 {
3254 lock(&editor.state).file_name = name.clone();
3255 }
3256 if editor.can_choose(app) {
3257 if ui
3258 .button(strings::tr(&ctx, &txt::THEME_EDITOR_OPEN_FILE))
3259 .clicked()
3260 {
3261 let request =
3262 FileRequest::open(&strings::tr(&ctx, &txt::THEME_EDITOR_OPEN_FILE))
3263 .filter("Token files", &["json", "yaml", "yml"]);
3264 #[cfg(feature = "theme-zip")]
3265 let request = request.filter("Theme archives", &["zip"]);
3266 if let Some(p) = editor.choose(app, request) {
3267 lock(&editor.state).choice = Some(Choice::Open(p));
3268 }
3269 }
3270 if ui
3271 .button(strings::tr(&ctx, &txt::THEME_EDITOR_SAVE_FILE))
3272 .clicked()
3273 {
3274 let request = FileRequest::save(
3275 &strings::tr(&ctx, &txt::THEME_EDITOR_SAVE_FILE),
3276 &format!("{name}.tokens.json"),
3277 )
3278 .filter("Token files", &["json"]);
3279 #[cfg(feature = "theme-zip")]
3280 let request = request.filter("Theme archives", &["zip"]);
3281 if let Some(p) = editor.choose(app, request) {
3282 lock(&editor.state).choice = Some(Choice::Save(p));
3283 }
3284 }
3285 }
3286 if ui
3287 .button(strings::tr(&ctx, &txt::THEME_EDITOR_EXPORT))
3288 .clicked()
3289 {
3290 let text = editor.export(app, &name);
3291 lock(&editor.state).file_text = text;
3292 }
3293 if ui
3294 .button(strings::tr(&ctx, &txt::THEME_EDITOR_IMPORT))
3295 .clicked()
3296 {
3297 let text = lock(&editor.state).file_text.clone();
3298 let out = editor.import(app, &text).map(|warnings| {
3299 let base = theme_label(editor.draft().base());
3300 let mut m = strings::tr_args(
3301 &ctx,
3302 &txt::THEME_EDITOR_IMPORTED,
3303 &[("theme", &base)],
3304 );
3305 let (left, other): (Vec<&Warning>, Vec<&Warning>) =
3306 warnings.iter().partition(|w| w.left_out());
3307 let skipped: Vec<&str> = left.iter().filter_map(|w| w.path()).collect();
3308 if !skipped.is_empty() {
3309 m.push(' ');
3310 m.push_str(&strings::tr_args(
3311 &ctx,
3312 &txt::THEME_EDITOR_SKIPPED,
3313 &[("tokens", &skipped.join(", "))],
3314 ));
3315 }
3316 if !other.is_empty() {
3317 let said: Vec<String> = other.iter().map(ToString::to_string).collect();
3318 m.push(' ');
3319 m.push_str(&strings::tr_args(
3320 &ctx,
3321 &txt::THEME_EDITOR_WARNINGS,
3322 &[("warnings", &said.join("; "))],
3323 ));
3324 }
3325 Some(m)
3326 });
3327 say(editor, out);
3328 }
3329 });
3330 let label = strings::tr(&ctx, &txt::THEME_EDITOR_FILE_TEXT);
3331 let mut text = lock(&editor.state).file_text.clone();
3332 let r = ui.add(
3333 egui::TextEdit::multiline(&mut text)
3334 .code_editor()
3335 .desired_rows(6)
3336 .desired_width(f32::INFINITY),
3337 );
3338 r.widget_info(|| WidgetInfo::labeled(egui::Role::TextInput, true, &label));
3339 if r.changed() {
3340 lock(&editor.state).file_text = text;
3341 }
3342 });
3343 let message = lock(&editor.state).message.clone();
3344 if let Some((ok, m)) = message {
3345 let t = Tokens::of(&ctx);
3346 ui.colored_label(
3347 if ok {
3348 t.status.success
3349 } else {
3350 t.status.danger
3351 },
3352 m,
3353 );
3354 }
3355}