Add installable theme packs and four example palettes
This commit is contained in:
parent
2b988f9c84
commit
31e545a426
|
|
@ -25,6 +25,7 @@ Versioned examples and sanitized fixtures remain beside their contracts and in
|
|||
| --- | --- |
|
||||
| [Project](docs/interfaces/canvas-pilot.md) | Project schema, versions and migrations |
|
||||
| [Settings](docs/interfaces/canvas-pilot-settings.md) | User preferences and settings compatibility |
|
||||
| [Theme packs](docs/interfaces/theme-packs.md) | Runtime palette ZIPs, installation, updates and fallback |
|
||||
| [Language packs](docs/interfaces/language-packs.md) | Runtime ZIP catalogs, installation and fallback |
|
||||
| [Recovery](docs/interfaces/canvas-pilot-recovery.md) | Recovery storage and restoration |
|
||||
| [Layer clipboard](docs/interfaces/canvas-pilot-clipboard.md) | Versioned geometry, crop, fit and blanking payload |
|
||||
|
|
|
|||
|
|
@ -548,7 +548,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "canvas-pilot"
|
||||
version = "0.9.25"
|
||||
version = "0.9.26"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"craft-dwg",
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"]
|
|||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.25"
|
||||
version = "0.9.26"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot"
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Toki Pona",
|
||||
"language.install-pack": "Install language pack…",
|
||||
"ui.crop-mask": "Crop & mask",
|
||||
"ui.canvas": "Canvas"
|
||||
"ui.canvas": "Canvas",
|
||||
"theme.packs": "Theme packs",
|
||||
"theme.install-pack": "Install theme pack…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Tokipono",
|
||||
"language.install-pack": "Instali lingvopakaĵon…",
|
||||
"ui.crop-mask": "Tondado kaj masko",
|
||||
"ui.canvas": "Kanvaso"
|
||||
"ui.canvas": "Kanvaso",
|
||||
"theme.packs": "Temaj pakoj",
|
||||
"theme.install-pack": "Instali teman pakon…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Toki Pona",
|
||||
"language.install-pack": "Instalar paquete de idiomas…",
|
||||
"ui.crop-mask": "Recorte y máscara",
|
||||
"ui.canvas": "Lienzo"
|
||||
"ui.canvas": "Lienzo",
|
||||
"theme.packs": "Paquetes de temas",
|
||||
"theme.install-pack": "Instalar paquete de temas…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Toki Pona",
|
||||
"language.install-pack": "Installer un pack de langues…",
|
||||
"ui.crop-mask": "Recadrage et masque",
|
||||
"ui.canvas": "Canevas"
|
||||
"ui.canvas": "Canevas",
|
||||
"theme.packs": "Packs de thèmes",
|
||||
"theme.install-pack": "Installer un pack de thèmes…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Τόκι Πόνα",
|
||||
"language.install-pack": "Install language pack…",
|
||||
"ui.crop-mask": "Περικοπὴ καὶ κάλυμμα",
|
||||
"ui.canvas": "Πίναξ"
|
||||
"ui.canvas": "Πίναξ",
|
||||
"theme.packs": "Δέσμαι θεμάτων",
|
||||
"theme.install-pack": "Ἐγκατάστησον δέσμην θεμάτων…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "टोकी पोना",
|
||||
"language.install-pack": "भाषा पैक स्थापित करें…",
|
||||
"ui.crop-mask": "क्रॉप और मास्क",
|
||||
"ui.canvas": "कैनवास"
|
||||
"ui.canvas": "कैनवास",
|
||||
"theme.packs": "थीम पैक",
|
||||
"theme.install-pack": "थीम पैक स्थापित करें…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "トキポナ",
|
||||
"language.install-pack": "言語パックをインストール…",
|
||||
"ui.crop-mask": "クロップとマスク",
|
||||
"ui.canvas": "キャンバス"
|
||||
"ui.canvas": "キャンバス",
|
||||
"theme.packs": "テーマパック",
|
||||
"theme.install-pack": "テーマパックをインストール…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "टोकी पोना",
|
||||
"language.install-pack": "भाषा प्याक स्थापना गर्नुहोस्…",
|
||||
"ui.crop-mask": "क्रप र मास्क",
|
||||
"ui.canvas": "क्यानभास"
|
||||
"ui.canvas": "क्यानभास",
|
||||
"theme.packs": "थिम प्याकहरू",
|
||||
"theme.install-pack": "थिम प्याक स्थापना गर्नुहोस्…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "Toki Pona",
|
||||
"language.install-pack": "Instalar pacote de idiomas…",
|
||||
"ui.crop-mask": "Recorte e máscara",
|
||||
"ui.canvas": "Tela"
|
||||
"ui.canvas": "Tela",
|
||||
"theme.packs": "Pacotes de temas",
|
||||
"theme.install-pack": "Instalar pacote de temas…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "โทกิโพนา",
|
||||
"language.install-pack": "ติดตั้งชุดภาษา…",
|
||||
"ui.crop-mask": "ครอบตัดและมาสก์",
|
||||
"ui.canvas": "พื้นที่ทำงาน"
|
||||
"ui.canvas": "พื้นที่ทำงาน",
|
||||
"theme.packs": "แพ็กธีม",
|
||||
"theme.install-pack": "ติดตั้งแพ็กธีม…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "toki pona",
|
||||
"language.install-pack": "o pana e kulupu toki…",
|
||||
"ui.crop-mask": "kipisi en len",
|
||||
"ui.canvas": "supa sitelen"
|
||||
"ui.canvas": "supa sitelen",
|
||||
"theme.packs": "kulupu kule",
|
||||
"theme.install-pack": "o pana e kulupu kule…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,5 +486,7 @@
|
|||
"language.name.tok": "道本语",
|
||||
"language.install-pack": "安装语言包…",
|
||||
"ui.crop-mask": "裁剪与遮罩",
|
||||
"ui.canvas": "画布"
|
||||
"ui.canvas": "画布",
|
||||
"theme.packs": "主题包",
|
||||
"theme.install-pack": "安装主题包…"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -599,6 +599,12 @@ impl Editor {
|
|||
store: settings::Store,
|
||||
saved: settings::Settings,
|
||||
) -> Self {
|
||||
let mut theme_errors = store
|
||||
.path
|
||||
.as_ref()
|
||||
.and_then(|p| p.parent())
|
||||
.map(|directory| crate::theme_packs::load(ctx, &directory.join("theme-packs")))
|
||||
.unwrap_or_default();
|
||||
theme::Theme::restore_recent(ctx, saved.recent_themes.clone());
|
||||
saved.theme.apply(ctx);
|
||||
let pack_errors = store
|
||||
|
|
@ -607,6 +613,7 @@ impl Editor {
|
|||
.and_then(|p| p.parent())
|
||||
.map(|directory| crate::language_packs::load(ctx, &directory.join("language-packs")))
|
||||
.unwrap_or_default();
|
||||
theme_errors.extend(pack_errors);
|
||||
saved.language.apply(ctx);
|
||||
preferences_ui::apply_scaling(ctx, saved.ui_scale, saved.text_scale);
|
||||
let mut device = device_ui::DeviceUi::with_connection_preferences(
|
||||
|
|
@ -618,7 +625,7 @@ impl Editor {
|
|||
Self {
|
||||
device,
|
||||
settings: store,
|
||||
error: pack_errors.join("\n"),
|
||||
error: theme_errors.join("\n"),
|
||||
language: saved.language,
|
||||
ui_scale: saved.ui_scale,
|
||||
text_scale: saved.text_scale,
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ mod gui;
|
|||
mod reference;
|
||||
mod settings;
|
||||
mod theme;
|
||||
mod theme_packs;
|
||||
mod widgets;
|
||||
use widgets::StableSelectableUi;
|
||||
|
||||
|
|
|
|||
|
|
@ -168,10 +168,10 @@ impl Editor {
|
|||
});
|
||||
let before = self.application_settings(ui.ctx());
|
||||
let current = theme::Theme::current(ui.ctx());
|
||||
ui.menu_button(format!("Theme: {}", current.name()), |ui| {
|
||||
ui.menu_button(format!("Theme: {}", current.display_name(ui.ctx())), |ui| {
|
||||
for choice in theme::Theme::recent(ui.ctx()) {
|
||||
if ui
|
||||
.stable_selectable_label(current == choice, choice.name())
|
||||
.stable_selectable_label(current == choice, choice.display_name(ui.ctx()))
|
||||
.clicked()
|
||||
{
|
||||
choice.select(ui.ctx());
|
||||
|
|
@ -229,6 +229,8 @@ impl Editor {
|
|||
.id(egui::Id::new("All themes"))
|
||||
.open(&mut self.themes_open)
|
||||
.default_width(540.0)
|
||||
.max_height((ctx.content_rect().height() - 100.0).max(200.0))
|
||||
.vscroll(true)
|
||||
.resizable(false)
|
||||
.collapsible(false)
|
||||
.show(ctx, |ui| {
|
||||
|
|
@ -236,19 +238,26 @@ impl Editor {
|
|||
ui.ctx(),
|
||||
"ui.choose-a-theme-your-three-most-recent-choices-stay-in-the-menu",
|
||||
));
|
||||
if ui.button(tr(ctx, "theme.packs")).clicked() {
|
||||
self.preferences_open = true;
|
||||
self.preferences_section = preferences_ui::Section::Themes;
|
||||
}
|
||||
ui.separator();
|
||||
ui.columns(2, |columns| {
|
||||
for (index, choice) in theme::Theme::ALL.into_iter().enumerate() {
|
||||
for (index, choice) in theme::Theme::choices(ctx).into_iter().enumerate() {
|
||||
columns[index % 2].horizontal(|ui| {
|
||||
let palette = choice.palette();
|
||||
let palette = choice.resolved_palette(ctx);
|
||||
for color in [palette.bg, palette.layer, palette.cyan] {
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(Vec2::splat(10.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(rect, 2.0, color);
|
||||
}
|
||||
if ui
|
||||
.stable_selectable_label(current == choice, choice.name())
|
||||
.on_hover_text(if choice.is_light() {
|
||||
.stable_selectable_label(
|
||||
current == choice,
|
||||
choice.display_name(ui.ctx()),
|
||||
)
|
||||
.on_hover_text(if choice.resolved_light(ctx) {
|
||||
"Light theme"
|
||||
} else {
|
||||
"Dark theme"
|
||||
|
|
|
|||
|
|
@ -42,15 +42,17 @@ pub(super) enum Section {
|
|||
#[default]
|
||||
Appearance,
|
||||
Languages,
|
||||
Themes,
|
||||
Editing,
|
||||
Reference,
|
||||
Storage,
|
||||
Device,
|
||||
}
|
||||
impl Section {
|
||||
const ALL: [(Self, &'static str); 6] = [
|
||||
const ALL: [(Self, &'static str); 7] = [
|
||||
(Self::Appearance, "ui.appearance"),
|
||||
(Self::Languages, "language.packs"),
|
||||
(Self::Themes, "theme.packs"),
|
||||
(Self::Editing, "ui.editing"),
|
||||
(Self::Reference, "ui.reference-images"),
|
||||
(Self::Storage, "ui.files-settings"),
|
||||
|
|
@ -66,6 +68,8 @@ pub(super) struct LanguagePreview {
|
|||
pub(super) enum PackAction {
|
||||
Install(crate::language_packs::Prepared),
|
||||
Remove(crate::language_packs::Installed),
|
||||
InstallTheme(crate::theme_packs::Prepared),
|
||||
RemoveTheme(crate::theme_packs::Installed),
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
|
|
@ -228,6 +232,102 @@ impl Editor {
|
|||
}
|
||||
}
|
||||
|
||||
fn refresh_pack_theme(&mut self, ctx: &egui::Context, was_available: bool) {
|
||||
let current = theme::Theme::current(ctx);
|
||||
if current.available(ctx) || !was_available {
|
||||
current.apply(ctx);
|
||||
} else {
|
||||
theme::Theme::Midra.apply(ctx);
|
||||
}
|
||||
let current = theme::Theme::current(ctx);
|
||||
let recent = theme::Theme::recent(ctx)
|
||||
.into_iter()
|
||||
.filter(|t| t.available(ctx) || *t == current)
|
||||
.collect();
|
||||
theme::Theme::restore_recent(ctx, recent);
|
||||
self.settings.save(&self.application_settings(ctx));
|
||||
}
|
||||
fn prepare_theme_pack(&mut self, ctx: &egui::Context, path: &std::path::Path) {
|
||||
let result = self
|
||||
.settings
|
||||
.path
|
||||
.as_ref()
|
||||
.and_then(|p| p.parent())
|
||||
.ok_or_else(|| "Settings directory unavailable".to_owned())
|
||||
.and_then(|directory| {
|
||||
crate::theme_packs::prepare(ctx, &directory.join("theme-packs"), path)
|
||||
});
|
||||
match result {
|
||||
Ok(pending) if pending.needs_confirmation() => {
|
||||
self.language_pack_action = Some(PackAction::InstallTheme(pending))
|
||||
}
|
||||
Ok(pending) => {
|
||||
let was_available = theme::Theme::current(ctx).available(ctx);
|
||||
match crate::theme_packs::commit(ctx, pending, false) {
|
||||
Ok(()) => self.refresh_pack_theme(ctx, was_available),
|
||||
Err(error) => self.error = error,
|
||||
}
|
||||
}
|
||||
Err(error) => self.error = error,
|
||||
}
|
||||
}
|
||||
fn theme_pack_settings(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
ui.heading(tr(&ctx, "theme.packs"));
|
||||
if ui.button(tr(&ctx, "theme.install-pack")).clicked()
|
||||
&& let Some(path) = rfd::FileDialog::new()
|
||||
.add_filter("Theme pack", &["zip"])
|
||||
.pick_file()
|
||||
{
|
||||
self.prepare_theme_pack(&ctx, &path);
|
||||
}
|
||||
ui.weak("Choose a ZIP to install or update. Newer revisions update immediately; equal or older revisions ask before replacing.");
|
||||
let packs = crate::theme_packs::installed(&ctx);
|
||||
if packs.is_empty() {
|
||||
ui.label("No theme packs installed.");
|
||||
}
|
||||
for pack in packs {
|
||||
ui.separator();
|
||||
egui::CollapsingHeader::new(
|
||||
egui::RichText::new(format!("{} · revision {}", pack.id, pack.revision)).strong(),
|
||||
)
|
||||
.id_salt(("theme-pack", &pack.id))
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
for entry in &pack.themes {
|
||||
let choice = theme::Theme::Pack(format!("{}/{}", pack.id, entry.id));
|
||||
ui.horizontal(|ui| {
|
||||
let palette = choice.resolved_palette(&ctx);
|
||||
for color in [palette.bg, palette.layer, palette.cyan] {
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(Vec2::splat(10.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(rect, 2.0, color);
|
||||
}
|
||||
if ui
|
||||
.stable_selectable_label(
|
||||
choice == theme::Theme::current(&ctx),
|
||||
&entry.name,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
choice.select(&ctx);
|
||||
}
|
||||
});
|
||||
}
|
||||
if !pack.notices.is_empty() {
|
||||
egui::CollapsingHeader::new("Attribution and licenses")
|
||||
.id_salt(("theme-notices", &pack.id))
|
||||
.show(ui, |ui| {
|
||||
ui.label(&pack.notices);
|
||||
});
|
||||
}
|
||||
if ui.button(tr(&ctx, "language.remove-pack")).clicked() {
|
||||
self.language_pack_action = Some(PackAction::RemoveTheme(pack.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn language_pack_confirmation(&mut self, ctx: &egui::Context) {
|
||||
let Some(action) = &self.language_pack_action else {
|
||||
return;
|
||||
|
|
@ -241,6 +341,19 @@ impl Editor {
|
|||
ui.label("This is not a newer revision. Replacing it overwrites the installed translations.");
|
||||
"language.overwrite-pack"
|
||||
},
|
||||
PackAction::InstallTheme(pack) => {
|
||||
ui.heading(tr(ctx, "language.overwrite-pack"));
|
||||
ui.label(format!("{}: installed revision {} → revision {}", pack.id(), pack.previous_revision.map_or_else(|| "unknown".into(), |v| v.to_string()), pack.revision()));
|
||||
ui.label("This is not a newer revision. Replacing it overwrites the installed themes.");
|
||||
"language.overwrite-pack"
|
||||
},
|
||||
PackAction::RemoveTheme(pack) => {
|
||||
ui.heading(tr(ctx, "language.remove-pack"));
|
||||
ui.label(&pack.id);
|
||||
ui.label(pack.themes.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", "));
|
||||
ui.label("All themes in this pack will be removed. If the current theme is removed, the interface switches to Midra Dark. You can reinstall the ZIP later.");
|
||||
"language.remove-pack"
|
||||
},
|
||||
PackAction::Remove(pack) => {
|
||||
ui.heading(tr(ctx, "language.remove-pack"));
|
||||
ui.label(&pack.id);
|
||||
|
|
@ -255,11 +368,19 @@ impl Editor {
|
|||
self.language_pack_action = None;
|
||||
} else if response.inner.0 {
|
||||
let previous = crate::language_packs::available(ctx);
|
||||
let theme_was_available = theme::Theme::current(ctx).available(ctx);
|
||||
let theme_action = matches!(
|
||||
self.language_pack_action,
|
||||
Some(PackAction::InstallTheme(_) | PackAction::RemoveTheme(_))
|
||||
);
|
||||
let result = match self.language_pack_action.take().unwrap() {
|
||||
PackAction::Install(pack) => crate::language_packs::commit(ctx, pack, true),
|
||||
PackAction::Remove(pack) => crate::language_packs::remove(ctx, &pack),
|
||||
PackAction::InstallTheme(pack) => crate::theme_packs::commit(ctx, pack, true),
|
||||
PackAction::RemoveTheme(pack) => crate::theme_packs::remove(ctx, &pack),
|
||||
};
|
||||
match result {
|
||||
Ok(()) if theme_action => self.refresh_pack_theme(ctx, theme_was_available),
|
||||
Ok(()) => self.refresh_pack_language(ctx, &previous),
|
||||
Err(error) => self.error = error,
|
||||
}
|
||||
|
|
@ -332,11 +453,11 @@ impl Editor {
|
|||
if scaling_before != (self.ui_scale, self.text_scale) { apply_scaling(ctx, self.ui_scale, self.text_scale); }
|
||||
if ui.button(tr(ctx, "access.contrast")).clicked() { theme::Theme::HighContrast.select(ctx); }
|
||||
ui.separator();
|
||||
ui.label(rust_i18n::t!("theme.current", locale = &localization::locale(ctx), name = theme::Theme::current(ctx).name()).into_owned());
|
||||
ui.label(rust_i18n::t!("theme.current", locale = &localization::locale(ctx), name = theme::Theme::current(ctx).display_name(ctx)).into_owned());
|
||||
if ui.button(tr(ui.ctx(), "ui.browse-all-themes")).clicked() { self.themes_open = true; }
|
||||
ui.label(tr(ui.ctx(), "ui.recently-used"));
|
||||
for choice in theme::Theme::recent(ctx) {
|
||||
if ui.stable_selectable_label(choice == theme::Theme::current(ctx), choice.name()).clicked() {
|
||||
if ui.stable_selectable_label(choice == theme::Theme::current(ctx), choice.display_name(ctx)).clicked() {
|
||||
choice.select(ctx);
|
||||
}
|
||||
}
|
||||
|
|
@ -346,6 +467,7 @@ impl Editor {
|
|||
ui.weak(tr(ui.ctx(), "ui.themes-also-apply-to-the-viewport-imported-pictures-retain-their-colors"));
|
||||
}
|
||||
Section::Languages => self.language_pack_settings(ui),
|
||||
Section::Themes => self.theme_pack_settings(ui),
|
||||
Section::Editing => {
|
||||
ui.heading(tr(ui.ctx(), "ui.editing"));
|
||||
self.resize_ratio_option(ui);
|
||||
|
|
@ -475,6 +597,72 @@ mod tests {
|
|||
writer.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_pack_manager_selects_updates_restarts_and_removes_with_confirmation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
let source = dir.path().join("theme.zip");
|
||||
let (store, saved) = settings::Store::at(path.clone());
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = Editor::with_settings(&ctx, store, saved);
|
||||
let project = app.project();
|
||||
std::fs::write(
|
||||
&source,
|
||||
include_bytes!("../../../docs/theme-packs/tokyo-night.zip"),
|
||||
)
|
||||
.unwrap();
|
||||
app.prepare_theme_pack(&ctx, &source);
|
||||
app.preferences_open = true;
|
||||
app.preferences_section = Section::Themes;
|
||||
click_label(&mut app, &ctx, "Tokyo Night");
|
||||
let choice = theme::Theme::Pack("tokyo-night/night".into());
|
||||
assert_eq!(theme::Theme::current(&ctx), choice);
|
||||
assert_eq!(settings::Store::at(path.clone()).1.theme, choice);
|
||||
let restarted = egui::Context::default();
|
||||
let (store, saved) = settings::Store::at(path.clone());
|
||||
let _restored = Editor::with_settings(&restarted, store, saved);
|
||||
assert_eq!(theme::palette(&restarted).bg, theme::palette(&ctx).bg);
|
||||
theme::Theme::HighContrast.select(&ctx);
|
||||
theme::Theme::HighContrast.select(&ctx);
|
||||
assert_eq!(theme::Theme::current(&ctx), choice);
|
||||
let mut manifest: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/theme-packs/tokyo-night/manifest.json"
|
||||
))
|
||||
.unwrap();
|
||||
manifest["revision"] = 2.into();
|
||||
manifest["themes"][0]["colors"]["bg"] = "#223344".into();
|
||||
manifest["themes"][0]["light"] = true.into();
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
use std::io::Write;
|
||||
zip.start_file("manifest.json", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(&serde_json::to_vec(&manifest).unwrap())
|
||||
.unwrap();
|
||||
std::fs::write(&source, zip.finish().unwrap().into_inner()).unwrap();
|
||||
app.prepare_theme_pack(&ctx, &source);
|
||||
assert_eq!(theme::palette(&ctx).bg, Color32::from_rgb(0x22, 0x33, 0x44));
|
||||
assert!(!ctx.global_style().visuals.dark_mode);
|
||||
app.prepare_theme_pack(&ctx, &source);
|
||||
assert!(matches!(
|
||||
app.language_pack_action,
|
||||
Some(PackAction::InstallTheme(_))
|
||||
));
|
||||
click_label(&mut app, &ctx, "Cancel");
|
||||
app.prepare_theme_pack(&ctx, &source);
|
||||
click_label(&mut app, &ctx, "Overwrite pack");
|
||||
assert!(app.language_pack_action.is_none());
|
||||
click_label(&mut app, &ctx, "Remove pack…");
|
||||
click_label(&mut app, &ctx, "Cancel");
|
||||
assert_eq!(theme::Theme::current(&ctx), choice);
|
||||
click_label(&mut app, &ctx, "Remove pack…");
|
||||
click_label(&mut app, &ctx, "Remove pack…");
|
||||
assert!(crate::theme_packs::installed(&ctx).is_empty());
|
||||
assert_eq!(theme::Theme::current(&ctx), theme::Theme::Midra);
|
||||
assert_eq!(settings::Store::at(path).1.theme, theme::Theme::Midra);
|
||||
assert_eq!(app.project(), project);
|
||||
assert!(source.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pack_manager_updates_confirms_overwrites_and_removes_active_language_live() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ pub struct Settings {
|
|||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 14,
|
||||
version: 15,
|
||||
ui_scale: 1.0,
|
||||
text_scale: None,
|
||||
language: Default::default(),
|
||||
|
|
@ -45,6 +45,14 @@ impl Default for Settings {
|
|||
impl Settings {
|
||||
fn parse(text: &str) -> Result<Self, String> {
|
||||
let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| e.to_string())?;
|
||||
if value["version"].as_u64().is_some_and(|v| v <= 14)
|
||||
&& (value["theme"].is_object()
|
||||
|| value["recent_themes"]
|
||||
.as_array()
|
||||
.is_some_and(|themes| themes.iter().any(|t| t.is_object())))
|
||||
{
|
||||
return Err("Theme packs require settings version 15".into());
|
||||
}
|
||||
if value["version"] == 1 {
|
||||
if value.get("recent_themes").is_some() {
|
||||
return Err("Unexpected recent_themes in version 1 settings".into());
|
||||
|
|
@ -173,17 +181,27 @@ impl Settings {
|
|||
snapping.insert("mask_edges".into(), false.into());
|
||||
value["version"] = 14.into();
|
||||
}
|
||||
if value["version"] == 14 && value.get("text_scale").is_none() {
|
||||
return Err("Missing text_scale in version 14 settings".into());
|
||||
if matches!(value["version"].as_u64(), Some(14 | 15)) && value.get("text_scale").is_none() {
|
||||
return Err("Missing text_scale in current settings".into());
|
||||
}
|
||||
if value["version"] == 14 {
|
||||
value["version"] = 15.into();
|
||||
}
|
||||
let settings: Self = serde_json::from_value(value).map_err(|e| e.to_string())?;
|
||||
settings.validate()?;
|
||||
Ok(settings)
|
||||
}
|
||||
fn validate(&self) -> Result<(), String> {
|
||||
if self.version != 14 {
|
||||
if self.version != 15 {
|
||||
return Err(format!("unsupported settings version {}", self.version));
|
||||
}
|
||||
for theme in std::iter::once(&self.theme).chain(&self.recent_themes) {
|
||||
if let Theme::Pack(id) = theme
|
||||
&& !crate::theme_packs::valid_choice(id)
|
||||
{
|
||||
return Err("Invalid installed theme identifier".into());
|
||||
}
|
||||
}
|
||||
if let crate::localization::Language::Pack(id) = &self.language
|
||||
&& !crate::language_packs::valid_id(id)
|
||||
{
|
||||
|
|
@ -323,12 +341,38 @@ impl Store {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn installed_themes_require_v15_and_round_trip_without_losing_other_options() {
|
||||
let legacy =
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v14.example.json");
|
||||
let current =
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v15.example.json");
|
||||
assert_eq!(
|
||||
Settings::parse(legacy).unwrap(),
|
||||
Settings::parse(current).unwrap()
|
||||
);
|
||||
let mut value: serde_json::Value = serde_json::from_str(current).unwrap();
|
||||
value["theme"] = serde_json::json!({"pack":"tokyo-night/night"});
|
||||
value["recent_themes"] =
|
||||
serde_json::json!([{"pack":"tokyo-night/night"},"high_contrast","midra"]);
|
||||
let saved = Settings::parse(&value.to_string()).unwrap();
|
||||
assert_eq!(serde_json::to_value(saved).unwrap(), value);
|
||||
value["version"] = 14.into();
|
||||
assert!(Settings::parse(&value.to_string()).is_err());
|
||||
value["version"] = 15.into();
|
||||
for id in ["", "no-slash", "../theme", "pack/a/b", "pack/Upper"] {
|
||||
value["theme"] = serde_json::json!({"pack":id});
|
||||
value["recent_themes"][0] = value["theme"].clone();
|
||||
assert!(Settings::parse(&value.to_string()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_snapping_migrates_and_requires_current_schema() {
|
||||
let legacy =
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v13.example.json");
|
||||
let current =
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v14.example.json");
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v15.example.json");
|
||||
assert_eq!(
|
||||
Settings::parse(legacy).unwrap(),
|
||||
Settings::parse(current).unwrap()
|
||||
|
|
@ -417,7 +461,7 @@ mod tests {
|
|||
let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v8.example.json");
|
||||
let migrated = Settings::parse(old).unwrap();
|
||||
assert_eq!(migrated.language, Language::System);
|
||||
assert_eq!(migrated.version, 14);
|
||||
assert_eq!(migrated.version, 15);
|
||||
let current =
|
||||
include_str!("../../../docs/interfaces/canvas-pilot-settings-v10.example.json");
|
||||
assert_eq!(Settings::parse(current).unwrap(), migrated);
|
||||
|
|
@ -426,12 +470,12 @@ mod tests {
|
|||
let mut old: serde_json::Value = serde_json::from_str(v9).unwrap();
|
||||
old["language"] = old_language.into();
|
||||
let upgraded = Settings::parse(&old.to_string()).unwrap();
|
||||
assert_eq!(upgraded.version, 14);
|
||||
assert_eq!(upgraded.version, 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&upgraded.language).unwrap(),
|
||||
old["language"]
|
||||
);
|
||||
old["version"] = 14.into();
|
||||
old["version"] = 15.into();
|
||||
old["snapping"]["mask_edges"] = false.into();
|
||||
old["ui_scale"] = serde_json::json!(1.0);
|
||||
old["text_scale"] = serde_json::Value::Null;
|
||||
|
|
@ -474,7 +518,7 @@ mod tests {
|
|||
assert!(Settings::parse(&value.to_string()).is_err());
|
||||
value["version"] = 13.into();
|
||||
let saved = Settings::parse(&value.to_string()).unwrap();
|
||||
value["version"] = 14.into();
|
||||
value["version"] = 15.into();
|
||||
value["snapping"]["mask_edges"] = false.into();
|
||||
assert_eq!(serde_json::to_value(saved).unwrap(), value);
|
||||
for id in ["", "../uk", "uk_UA"] {
|
||||
|
|
@ -510,7 +554,7 @@ mod tests {
|
|||
value["ui_scale"] = 1.5.into();
|
||||
value["text_scale"] = 1.25.into();
|
||||
let saved = Settings::parse(&value.to_string()).unwrap();
|
||||
value["version"] = 14.into();
|
||||
value["version"] = 15.into();
|
||||
value["snapping"]["mask_edges"] = false.into();
|
||||
assert_eq!(serde_json::to_value(saved).unwrap(), value);
|
||||
}
|
||||
|
|
@ -584,7 +628,7 @@ mod tests {
|
|||
for text in [
|
||||
"broken".to_string(),
|
||||
serde_json::to_string(&Settings {
|
||||
version: 15,
|
||||
version: 16,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Application palettes adapted from SOTV's song database; see docs/canvas-pilot/README.md.
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Theme {
|
||||
#[default]
|
||||
|
|
@ -25,6 +25,7 @@ pub enum Theme {
|
|||
Ustf,
|
||||
VerdantRebel,
|
||||
WeicatIndustrial,
|
||||
Pack(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
|
|
@ -68,8 +69,9 @@ impl Theme {
|
|||
Self::VerdantRebel,
|
||||
Self::WeicatIndustrial,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
Self::Pack(id) => id,
|
||||
Self::Midra => "Midra Dark",
|
||||
Self::HighContrast => "High Contrast",
|
||||
Self::FoxifiedDark => "Foxified Dark",
|
||||
|
|
@ -92,7 +94,7 @@ impl Theme {
|
|||
Self::WeicatIndustrial => "Weicat Industrial",
|
||||
}
|
||||
}
|
||||
pub fn is_light(self) -> bool {
|
||||
pub fn is_light(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::CorporateLight
|
||||
|
|
@ -102,6 +104,39 @@ impl Theme {
|
|||
| Self::Solarized
|
||||
)
|
||||
}
|
||||
pub fn display_name(&self, ctx: &egui::Context) -> String {
|
||||
match self {
|
||||
Self::Pack(id) => crate::theme_packs::find(ctx, id)
|
||||
.map_or_else(|| format!("{id} (unavailable)"), |t| t.name),
|
||||
_ => self.name().to_owned(),
|
||||
}
|
||||
}
|
||||
pub fn available(&self, ctx: &egui::Context) -> bool {
|
||||
match self {
|
||||
Self::Pack(id) => crate::theme_packs::find(ctx, id).is_some(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
pub fn resolved_palette(&self, ctx: &egui::Context) -> Palette {
|
||||
match self {
|
||||
Self::Pack(id) => crate::theme_packs::find(ctx, id)
|
||||
.and_then(|t| t.colors.palette().ok())
|
||||
.unwrap_or_else(|| Self::Midra.palette()),
|
||||
_ => self.palette(),
|
||||
}
|
||||
}
|
||||
pub fn resolved_light(&self, ctx: &egui::Context) -> bool {
|
||||
match self {
|
||||
Self::Pack(id) => crate::theme_packs::find(ctx, id).is_some_and(|t| t.light),
|
||||
_ => self.is_light(),
|
||||
}
|
||||
}
|
||||
pub fn choices(ctx: &egui::Context) -> Vec<Self> {
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.chain(crate::theme_packs::choices(ctx))
|
||||
.collect()
|
||||
}
|
||||
pub fn recent(ctx: &egui::Context) -> Vec<Self> {
|
||||
ctx.data(|d| d.get_temp(egui::Id::new("recent-themes")))
|
||||
.unwrap_or_else(|| vec![Self::current(ctx)])
|
||||
|
|
@ -115,9 +150,10 @@ impl Theme {
|
|||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
pub fn palette(self) -> Palette {
|
||||
pub fn palette(&self) -> Palette {
|
||||
let rgb = |hex: u32| Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8);
|
||||
match self {
|
||||
Self::Pack(_) => Self::Midra.palette(),
|
||||
Self::HighContrast => Palette {
|
||||
canvas: rgb(0x000000),
|
||||
banner: rgb(0x101010),
|
||||
|
|
@ -281,26 +317,26 @@ impl Theme {
|
|||
}
|
||||
}
|
||||
/// Apply a user choice; selecting active High Contrast restores the previous theme.
|
||||
pub fn select(self, ctx: &egui::Context) {
|
||||
let choice = if self == Self::HighContrast && Self::current(ctx) == self {
|
||||
pub fn select(&self, ctx: &egui::Context) {
|
||||
let choice = if *self == Self::HighContrast && Self::current(ctx) == *self {
|
||||
Self::recent(ctx)
|
||||
.into_iter()
|
||||
.find(|theme| *theme != Self::HighContrast)
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
self
|
||||
self.clone()
|
||||
};
|
||||
choice.apply(ctx);
|
||||
}
|
||||
|
||||
pub fn apply(self, ctx: &egui::Context) {
|
||||
pub fn apply(&self, ctx: &egui::Context) {
|
||||
let mut recent = Self::recent(ctx);
|
||||
recent.retain(|theme| *theme != self);
|
||||
recent.insert(0, self);
|
||||
recent.retain(|theme| theme != self);
|
||||
recent.insert(0, self.clone());
|
||||
recent.truncate(3);
|
||||
Self::restore_recent(ctx, recent);
|
||||
let p = self.palette();
|
||||
let mut v = if self.is_light() {
|
||||
let p = self.resolved_palette(ctx);
|
||||
let mut v = if self.resolved_light(ctx) {
|
||||
egui::Visuals::light()
|
||||
} else {
|
||||
egui::Visuals::dark()
|
||||
|
|
@ -314,7 +350,7 @@ impl Theme {
|
|||
v.code_bg_color = p.field;
|
||||
v.hyperlink_color = p.cyan;
|
||||
v.warn_fg_color = p.amber;
|
||||
v.error_fg_color = if self.is_light() {
|
||||
v.error_fg_color = if self.resolved_light(ctx) {
|
||||
Color32::from_rgb(165, 30, 40)
|
||||
} else {
|
||||
Color32::LIGHT_RED
|
||||
|
|
@ -335,7 +371,7 @@ impl Theme {
|
|||
widget.bg_stroke = Stroke::new(1.0_f32, border);
|
||||
widget.fg_stroke = Stroke::new(1.0_f32, p.text);
|
||||
}
|
||||
if self == Self::HighContrast {
|
||||
if *self == Self::HighContrast {
|
||||
v.window_stroke.width = 2.0;
|
||||
for widget in [
|
||||
&mut v.widgets.noninteractive,
|
||||
|
|
@ -349,13 +385,15 @@ impl Theme {
|
|||
}
|
||||
}
|
||||
ctx.set_visuals(v);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-theme"), self));
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-palette"), p));
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-theme"), self.clone()));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn palette(ctx: &egui::Context) -> Palette {
|
||||
Theme::current(ctx).palette()
|
||||
ctx.data(|d| d.get_temp::<Palette>(egui::Id::new("application-palette")))
|
||||
.unwrap_or_else(|| Theme::current(ctx).resolved_palette(ctx))
|
||||
}
|
||||
|
||||
// SOTV CSS tokens: body, panel, sidebar, tab, main/subtle text, button, border.
|
||||
|
|
@ -429,7 +467,7 @@ mod tests {
|
|||
fn selectable_hover_focus_and_selection_keep_rows_and_neighbors_stationary() {
|
||||
for (theme, menu) in Theme::ALL
|
||||
.into_iter()
|
||||
.flat_map(|theme| [(theme, false), (theme, true)])
|
||||
.flat_map(|theme| [(theme.clone(), false), (theme, true)])
|
||||
{
|
||||
let ctx = egui::Context::default();
|
||||
theme.apply(&ctx);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,568 @@
|
|||
//! Runtime palette packs. Contract: docs/interfaces/theme-packs.md.
|
||||
use crate::theme::Palette;
|
||||
use eframe::egui;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
const MAX_ARCHIVE: u64 = 2 * 1024 * 1024;
|
||||
const MAX_EXPANDED: u64 = 4 * 1024 * 1024;
|
||||
const MAX_PACKS: usize = 32;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Manifest {
|
||||
version: u32,
|
||||
id: String,
|
||||
revision: u64,
|
||||
themes: Vec<Description>,
|
||||
/// Attribution and license notices travel with the pack.
|
||||
#[serde(default)]
|
||||
notices: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Description {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub light: bool,
|
||||
pub colors: Colors,
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Colors {
|
||||
pub canvas: String,
|
||||
pub banner: String,
|
||||
pub grid: String,
|
||||
pub layer: String,
|
||||
pub bg: String,
|
||||
pub panel: String,
|
||||
pub field: String,
|
||||
pub line: String,
|
||||
pub text: String,
|
||||
pub muted: String,
|
||||
pub cyan: String,
|
||||
pub amber: String,
|
||||
pub purple: String,
|
||||
pub pattern: [String; 2],
|
||||
}
|
||||
fn color(text: &str) -> Result<egui::Color32, String> {
|
||||
if text.len() != 7
|
||||
|| !text.starts_with('#')
|
||||
|| !text[1..].bytes().all(|b| b.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(format!("Expected opaque #RRGGBB color: {text}"));
|
||||
}
|
||||
let value = u32::from_str_radix(&text[1..], 16).map_err(|e| e.to_string())?;
|
||||
Ok(egui::Color32::from_rgb(
|
||||
(value >> 16) as u8,
|
||||
(value >> 8) as u8,
|
||||
value as u8,
|
||||
))
|
||||
}
|
||||
impl Colors {
|
||||
pub fn palette(&self) -> Result<Palette, String> {
|
||||
Ok(Palette {
|
||||
canvas: color(&self.canvas)?,
|
||||
banner: color(&self.banner)?,
|
||||
grid: color(&self.grid)?,
|
||||
layer: color(&self.layer)?,
|
||||
bg: color(&self.bg)?,
|
||||
panel: color(&self.panel)?,
|
||||
field: color(&self.field)?,
|
||||
line: color(&self.line)?,
|
||||
text: color(&self.text)?,
|
||||
muted: color(&self.muted)?,
|
||||
cyan: color(&self.cyan)?,
|
||||
amber: color(&self.amber)?,
|
||||
purple: color(&self.purple)?,
|
||||
pattern: [color(&self.pattern[0])?, color(&self.pattern[1])?],
|
||||
})
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Pack {
|
||||
manifest: Manifest,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Installed {
|
||||
pub id: String,
|
||||
pub revision: u64,
|
||||
pub themes: Vec<Description>,
|
||||
pub notices: String,
|
||||
path: PathBuf,
|
||||
bytes: std::sync::Arc<[u8]>,
|
||||
}
|
||||
pub fn installed(ctx: &egui::Context) -> Vec<Installed> {
|
||||
ctx.data(|data| data.get_temp::<Vec<Installed>>(egui::Id::new("theme-packs")))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub fn valid_choice(id: &str) -> bool {
|
||||
id.split_once('/').is_some_and(|(pack, theme)| {
|
||||
crate::language_packs::valid_id(pack) && crate::language_packs::valid_id(theme)
|
||||
})
|
||||
}
|
||||
pub fn find(ctx: &egui::Context, id: &str) -> Option<Description> {
|
||||
let (pack, theme) = id.split_once('/')?;
|
||||
installed(ctx)
|
||||
.into_iter()
|
||||
.find(|p| p.id == pack)?
|
||||
.themes
|
||||
.into_iter()
|
||||
.find(|t| t.id == theme)
|
||||
}
|
||||
pub fn choices(ctx: &egui::Context) -> Vec<crate::theme::Theme> {
|
||||
installed(ctx)
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
p.themes
|
||||
.into_iter()
|
||||
.map(move |t| crate::theme::Theme::Pack(format!("{}/{}", p.id, t.id)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn register(ctx: &egui::Context, pack: &Pack, path: &Path, bytes: &[u8]) {
|
||||
let mut packs = installed(ctx);
|
||||
packs.retain(|p| p.id != pack.manifest.id);
|
||||
packs.push(Installed {
|
||||
id: pack.manifest.id.clone(),
|
||||
revision: pack.manifest.revision,
|
||||
themes: pack.manifest.themes.clone(),
|
||||
notices: pack.manifest.notices.clone(),
|
||||
path: path.into(),
|
||||
bytes: bytes.into(),
|
||||
});
|
||||
packs.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), packs));
|
||||
}
|
||||
fn parse(bytes: &[u8]) -> Result<Pack, String> {
|
||||
if bytes.len() as u64 > MAX_ARCHIVE {
|
||||
return Err("Theme pack exceeds 2 MiB".into());
|
||||
}
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?;
|
||||
if zip.len() != 1 {
|
||||
return Err("Expected only manifest.json in the theme pack".into());
|
||||
}
|
||||
let mut entry = zip.by_index(0).map_err(|e| e.to_string())?;
|
||||
if entry.name() != "manifest.json"
|
||||
|| entry.is_dir()
|
||||
|| entry
|
||||
.unix_mode()
|
||||
.is_some_and(|mode| mode & 0o170000 == 0o120000)
|
||||
{
|
||||
return Err("Expected a regular manifest.json at the ZIP root".into());
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
(&mut entry)
|
||||
.take(MAX_EXPANDED + 1)
|
||||
.read_to_end(&mut data)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if data.len() as u64 > MAX_EXPANDED {
|
||||
return Err("Expanded theme pack exceeds 4 MiB".into());
|
||||
}
|
||||
let manifest: Manifest = serde_json::from_slice(&data).map_err(|e| e.to_string())?;
|
||||
if manifest.version != 1
|
||||
|| manifest.revision == 0
|
||||
|| !crate::language_packs::valid_id(&manifest.id)
|
||||
|| manifest.themes.is_empty()
|
||||
|| manifest.themes.len() > 16
|
||||
{
|
||||
return Err("Invalid theme-pack manifest or unsupported version".into());
|
||||
}
|
||||
if manifest.notices.len() > 65536
|
||||
|| manifest
|
||||
.notices
|
||||
.chars()
|
||||
.any(|c| c.is_control() && c != '\n' && c != '\t' && c != '\r')
|
||||
{
|
||||
return Err("Invalid attribution notices".into());
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for theme in &manifest.themes {
|
||||
if !crate::language_packs::valid_id(&theme.id)
|
||||
|| !ids.insert(&theme.id)
|
||||
|| theme.name.trim().is_empty()
|
||||
|| theme.name.len() > 160
|
||||
|| theme.name.chars().any(char::is_control)
|
||||
{
|
||||
return Err("Invalid or duplicate theme identifier/name".into());
|
||||
}
|
||||
theme.colors.palette()?;
|
||||
}
|
||||
Ok(Pack { manifest })
|
||||
}
|
||||
fn read(path: &Path) -> Result<Vec<u8>, String> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| e.to_string())?
|
||||
.take(MAX_ARCHIVE + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(bytes)
|
||||
}
|
||||
fn check_collisions(ctx: &egui::Context, pack: &Pack, replacing: bool) -> Result<(), String> {
|
||||
if !replacing && installed(ctx).iter().any(|p| p.id == pack.manifest.id) {
|
||||
return Err("Pack identifier is already installed".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Load once at application startup; invalid files do not prevent startup.
|
||||
pub fn load(ctx: &egui::Context, directory: &Path) -> Vec<String> {
|
||||
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), Vec::<Installed>::new()));
|
||||
let entries = match std::fs::read_dir(directory) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return vec![],
|
||||
Err(error) => return vec![error.to_string()],
|
||||
};
|
||||
let mut paths = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Ok(entry) if entry.path().extension().is_some_and(|ext| ext == "zip") => {
|
||||
paths.push(entry.path())
|
||||
}
|
||||
Ok(_) => (),
|
||||
Err(error) => errors.push(error.to_string()),
|
||||
}
|
||||
if paths.len() > MAX_PACKS {
|
||||
errors.push("Too many theme packs (maximum 32)".into());
|
||||
break;
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
for path in paths.into_iter().take(MAX_PACKS) {
|
||||
let result = read(&path).and_then(|bytes| {
|
||||
let pack = parse(&bytes)?;
|
||||
check_collisions(ctx, &pack, false)?;
|
||||
register(ctx, &pack, &path, &bytes);
|
||||
Ok(())
|
||||
});
|
||||
if let Err(error) = result {
|
||||
errors.push(format!("{}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
errors
|
||||
}
|
||||
/// Validated bytes and the exact destination reviewed by the user. Never re-read the source on confirmation.
|
||||
pub struct Prepared {
|
||||
pack: Pack,
|
||||
bytes: Vec<u8>,
|
||||
path: PathBuf,
|
||||
previous: Option<Vec<u8>>,
|
||||
pub previous_revision: Option<u64>,
|
||||
}
|
||||
impl Prepared {
|
||||
pub fn id(&self) -> &str {
|
||||
&self.pack.manifest.id
|
||||
}
|
||||
pub fn revision(&self) -> u64 {
|
||||
self.pack.manifest.revision
|
||||
}
|
||||
pub fn needs_confirmation(&self) -> bool {
|
||||
self.previous.is_some()
|
||||
&& self
|
||||
.previous_revision
|
||||
.is_none_or(|old| self.revision() <= old)
|
||||
}
|
||||
}
|
||||
fn existing_bytes(path: &Path) -> Result<Option<Vec<u8>>, String> {
|
||||
match read(path) {
|
||||
Ok(bytes) if bytes.len() as u64 <= MAX_ARCHIVE => Ok(Some(bytes)),
|
||||
Ok(_) => Err("Existing pack exceeds 2 MiB; remove it manually before replacing it".into()),
|
||||
Err(_error) if !path.exists() => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
pub fn prepare(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<Prepared, String> {
|
||||
let bytes = read(source)?;
|
||||
let pack = parse(&bytes)?;
|
||||
check_collisions(ctx, &pack, true)?;
|
||||
let path = installed(ctx)
|
||||
.into_iter()
|
||||
.find(|p| p.id == pack.manifest.id)
|
||||
.map_or_else(
|
||||
|| directory.join(format!("{}.zip", pack.manifest.id)),
|
||||
|p| p.path,
|
||||
);
|
||||
let previous = existing_bytes(&path)?;
|
||||
if let Some(old) = previous.as_ref().and_then(|bytes| parse(bytes).ok())
|
||||
&& old.manifest.id != pack.manifest.id
|
||||
{
|
||||
return Err("Destination belongs to a different pack; remove that pack first".into());
|
||||
}
|
||||
let previous_revision = previous
|
||||
.as_ref()
|
||||
.and_then(|bytes| parse(bytes).ok())
|
||||
.filter(|old| old.manifest.id == pack.manifest.id)
|
||||
.map(|old| old.manifest.revision);
|
||||
Ok(Prepared {
|
||||
pack,
|
||||
bytes,
|
||||
path,
|
||||
previous,
|
||||
previous_revision,
|
||||
})
|
||||
}
|
||||
pub fn commit(ctx: &egui::Context, pending: Prepared, overwrite: bool) -> Result<(), String> {
|
||||
if pending.needs_confirmation() && !overwrite {
|
||||
return Err("Replacing this pack requires overwrite confirmation".into());
|
||||
}
|
||||
check_collisions(ctx, &pending.pack, true)?;
|
||||
if existing_bytes(&pending.path)? != pending.previous {
|
||||
return Err("Installed pack changed during review; choose the ZIP again".into());
|
||||
}
|
||||
let directory = pending.path.parent().ok_or("Missing pack directory")?;
|
||||
std::fs::create_dir_all(directory).map_err(|e| e.to_string())?;
|
||||
if pending.previous.is_none()
|
||||
&& std::fs::read_dir(directory)
|
||||
.map_err(|e| e.to_string())?
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| e.path().extension().is_some_and(|ext| ext == "zip"))
|
||||
.count()
|
||||
>= MAX_PACKS
|
||||
{
|
||||
return Err("Too many theme packs (maximum 32)".into());
|
||||
}
|
||||
let mut file = tempfile::NamedTempFile::new_in(directory).map_err(|e| e.to_string())?;
|
||||
file.write_all(&pending.bytes).map_err(|e| e.to_string())?;
|
||||
file.as_file().sync_all().map_err(|e| e.to_string())?;
|
||||
if pending.previous.is_some() {
|
||||
file.persist(&pending.path).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
file.persist_noclobber(&pending.path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
register(ctx, &pending.pack, &pending.path, &pending.bytes);
|
||||
Ok(())
|
||||
}
|
||||
pub fn remove(ctx: &egui::Context, pack: &Installed) -> Result<(), String> {
|
||||
if read(&pack.path)?.as_slice() != pack.bytes.as_ref() {
|
||||
return Err("Installed pack changed; restart before removing it".into());
|
||||
}
|
||||
std::fs::remove_file(&pack.path).map_err(|e| e.to_string())?;
|
||||
let mut packs = installed(ctx);
|
||||
packs.retain(|p| p.id != pack.id);
|
||||
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), packs));
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn install(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<(), String> {
|
||||
commit(ctx, prepare(ctx, directory, source)?, false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::theme::Theme;
|
||||
const EXAMPLES: [(&str, &[u8], &str); 4] = [
|
||||
(
|
||||
"tokyo-night",
|
||||
include_bytes!("../../../docs/theme-packs/tokyo-night.zip"),
|
||||
include_str!("../../../docs/theme-packs/tokyo-night/manifest.json"),
|
||||
),
|
||||
(
|
||||
"catppuccin",
|
||||
include_bytes!("../../../docs/theme-packs/catppuccin.zip"),
|
||||
include_str!("../../../docs/theme-packs/catppuccin/manifest.json"),
|
||||
),
|
||||
(
|
||||
"detroit-become-human",
|
||||
include_bytes!("../../../docs/theme-packs/detroit-become-human.zip"),
|
||||
include_str!("../../../docs/theme-packs/detroit-become-human/manifest.json"),
|
||||
),
|
||||
(
|
||||
"minecraft",
|
||||
include_bytes!("../../../docs/theme-packs/minecraft.zip"),
|
||||
include_str!("../../../docs/theme-packs/minecraft/manifest.json"),
|
||||
),
|
||||
];
|
||||
fn zip(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for (name, bytes) in files {
|
||||
zip.start_file(
|
||||
*name,
|
||||
zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated),
|
||||
)
|
||||
.unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
}
|
||||
zip.finish().unwrap().into_inner()
|
||||
}
|
||||
fn modified(change: impl FnOnce(&mut serde_json::Value)) -> Vec<u8> {
|
||||
let mut manifest: serde_json::Value = serde_json::from_str(EXAMPLES[0].2).unwrap();
|
||||
change(&mut manifest);
|
||||
zip(&[("manifest.json", &serde_json::to_vec(&manifest).unwrap())])
|
||||
}
|
||||
#[test]
|
||||
fn examples_install_restart_preserve_bytes_and_have_legible_text() {
|
||||
fn luminance(c: egui::Color32) -> f64 {
|
||||
let channel = |v: u8| {
|
||||
let v = v as f64 / 255.0;
|
||||
if v <= 0.04045 {
|
||||
v / 12.92
|
||||
} else {
|
||||
((v + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
};
|
||||
0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let packs = dir.path().join("packs");
|
||||
for (id, bytes, source) in EXAMPLES {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut text = String::new();
|
||||
archive
|
||||
.by_name("manifest.json")
|
||||
.unwrap()
|
||||
.read_to_string(&mut text)
|
||||
.unwrap();
|
||||
assert_eq!(text, source);
|
||||
let path = dir.path().join("source.zip");
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
install(&ctx, &packs, &path).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(packs.join(format!("{id}.zip"))).unwrap(),
|
||||
bytes
|
||||
);
|
||||
let pack = parse(bytes).unwrap();
|
||||
for t in pack.manifest.themes {
|
||||
let choice = Theme::Pack(format!("{id}/{}", t.id));
|
||||
choice.select(&ctx);
|
||||
assert_eq!(Theme::current(&ctx), choice);
|
||||
assert_eq!(choice.display_name(&ctx), t.name);
|
||||
assert_eq!(ctx.global_style().visuals.dark_mode, !t.light);
|
||||
let p = choice.resolved_palette(&ctx);
|
||||
for bg in [p.bg, p.panel, p.field, p.purple, p.pattern[0], p.pattern[1]] {
|
||||
let (text, bg) = (luminance(p.text), luminance(bg));
|
||||
assert!(
|
||||
(text.max(bg) + 0.05) / (text.min(bg) + 0.05) >= 4.5,
|
||||
"{id} text contrast"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(choices(&ctx).len(), 4);
|
||||
let restarted = egui::Context::default();
|
||||
assert!(load(&restarted, &packs).is_empty());
|
||||
assert_eq!(choices(&restarted), choices(&ctx));
|
||||
let isolated = egui::Context::default();
|
||||
assert!(choices(&isolated).is_empty());
|
||||
let missing = Theme::Pack("minecraft/overworld".into());
|
||||
missing.apply(&isolated);
|
||||
assert_eq!(Theme::current(&isolated), missing);
|
||||
assert_eq!(
|
||||
missing.resolved_palette(&isolated).bg,
|
||||
Theme::Midra.palette().bg
|
||||
);
|
||||
assert!(missing.display_name(&isolated).contains("unavailable"));
|
||||
Theme::HighContrast.select(&ctx);
|
||||
Theme::HighContrast.select(&ctx);
|
||||
assert_eq!(Theme::current(&ctx), missing);
|
||||
}
|
||||
#[test]
|
||||
fn updates_require_review_and_detect_disk_changes_before_commit_or_remove() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let packs = dir.path().join("packs");
|
||||
let source = dir.path().join("source.zip");
|
||||
let ctx = egui::Context::default();
|
||||
std::fs::write(&source, EXAMPLES[0].1).unwrap();
|
||||
install(&ctx, &packs, &source).unwrap();
|
||||
let original = installed(&ctx)[0].clone();
|
||||
let pending = prepare(&ctx, &packs, &source).unwrap();
|
||||
assert!(pending.needs_confirmation());
|
||||
assert!(commit(&ctx, pending, false).is_err());
|
||||
let updated = modified(|m| {
|
||||
m["revision"] = 2.into();
|
||||
m["themes"][0]["colors"]["bg"] = "#112233".into();
|
||||
});
|
||||
std::fs::write(&source, &updated).unwrap();
|
||||
let pending = prepare(&ctx, &packs, &source).unwrap();
|
||||
assert!(!pending.needs_confirmation());
|
||||
commit(&ctx, pending, false).unwrap();
|
||||
assert_eq!(installed(&ctx)[0].revision, 2);
|
||||
assert!(remove(&ctx, &original).is_err());
|
||||
std::fs::write(&source, EXAMPLES[0].1).unwrap();
|
||||
let pending = prepare(&ctx, &packs, &source).unwrap();
|
||||
assert!(pending.needs_confirmation());
|
||||
let destination = packs.join("tokyo-night.zip");
|
||||
std::fs::write(&destination, b"external change").unwrap();
|
||||
assert!(commit(&ctx, pending, true).is_err());
|
||||
assert_eq!(installed(&ctx)[0].revision, 2);
|
||||
assert!(remove(&ctx, &installed(&ctx)[0]).is_err());
|
||||
std::fs::write(&destination, &updated).unwrap();
|
||||
commit(&ctx, prepare(&ctx, &packs, &source).unwrap(), true).unwrap();
|
||||
assert_eq!(installed(&ctx)[0].revision, 1);
|
||||
remove(&ctx, &installed(&ctx)[0]).unwrap();
|
||||
assert!(installed(&ctx).is_empty());
|
||||
assert!(source.exists());
|
||||
assert!(!destination.exists());
|
||||
}
|
||||
#[test]
|
||||
fn invalid_archives_never_register_or_replace_installed_data() {
|
||||
let mut cases = vec![
|
||||
b"not zip".to_vec(),
|
||||
vec![0; MAX_ARCHIVE as usize + 1],
|
||||
zip(&[]),
|
||||
zip(&[("../manifest.json", EXAMPLES[0].2.as_bytes())]),
|
||||
zip(&[
|
||||
("manifest.json", EXAMPLES[0].2.as_bytes()),
|
||||
("extra.json", b"{}"),
|
||||
]),
|
||||
zip(&[("manifest.json", &vec![b' '; MAX_EXPANDED as usize + 1])]),
|
||||
];
|
||||
for (pointer, value) in [
|
||||
("/version", serde_json::json!(2)),
|
||||
("/revision", serde_json::json!(0)),
|
||||
("/id", serde_json::json!("../escape")),
|
||||
("/themes/0/id", serde_json::json!("bad/id")),
|
||||
("/themes/0/name", serde_json::json!("\n")),
|
||||
("/themes/0/colors/text", serde_json::json!("#ffffff00")),
|
||||
("/themes/0/colors/bg", serde_json::json!("#gggggg")),
|
||||
("/themes/0/light", serde_json::json!("dark")),
|
||||
("/themes", serde_json::json!([])),
|
||||
] {
|
||||
cases.push(modified(|m| *m.pointer_mut(pointer).unwrap() = value));
|
||||
}
|
||||
cases.push(modified(|m| {
|
||||
m["unknown"] = true.into();
|
||||
}));
|
||||
cases.push(modified(|m| {
|
||||
let theme = m["themes"][0].clone();
|
||||
m["themes"].as_array_mut().unwrap().push(theme);
|
||||
}));
|
||||
cases.push(modified(|m| {
|
||||
m["themes"][0]["colors"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("line");
|
||||
}));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = dir.path().join("source.zip");
|
||||
let packs = dir.path().join("packs");
|
||||
let ctx = egui::Context::default();
|
||||
std::fs::write(&source, EXAMPLES[0].1).unwrap();
|
||||
install(&ctx, &packs, &source).unwrap();
|
||||
for bytes in cases {
|
||||
std::fs::write(&source, bytes).unwrap();
|
||||
assert!(prepare(&ctx, &packs, &source).is_err());
|
||||
assert_eq!(installed(&ctx).len(), 1);
|
||||
assert_eq!(
|
||||
std::fs::read(packs.join("tokyo-night.zip")).unwrap(),
|
||||
EXAMPLES[0].1
|
||||
);
|
||||
}
|
||||
std::fs::write(packs.join("bad.zip"), b"bad").unwrap();
|
||||
std::fs::write(packs.join("duplicate.zip"), EXAMPLES[0].1).unwrap();
|
||||
assert_eq!(load(&ctx, &packs).len(), 2);
|
||||
assert_eq!(installed(&ctx).len(), 1);
|
||||
for i in 0..32 {
|
||||
std::fs::write(packs.join(format!("invalid-{i}.zip")), b"bad").unwrap();
|
||||
}
|
||||
assert!(load(&ctx, &packs).iter().any(|e| e.contains("maximum 32")));
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,21 @@
|
|||
|
||||
## Unreleased
|
||||
|
||||
### v0.9.26
|
||||
|
||||
- Added offline theme ZIP packs with bounded validation, live installation/update,
|
||||
reviewed overwrites/removal and collapsible management with swatches and notices.
|
||||
Packed themes appear in the persistent picker/recent history and work with the
|
||||
High Contrast return toggle. Missing packs retain their saved choice with a
|
||||
Midra Dark fallback; removing an active theme saves Midra Dark.
|
||||
- Added downloadable Tokyo Night, Catppuccin Mocha, Detroit: Become Human and
|
||||
Minecraft Overworld examples, editable manifests and reproducible ZIP tooling.
|
||||
Upstream notices are included; game-inspired palettes contain no game assets.
|
||||
- Settings v15 migrates versions 1–14 and documents namespaced theme references.
|
||||
Project, recovery, geometry and device formats are unchanged.
|
||||
- All required Rust/Python checks, reproducible example ZIP checks, native palette
|
||||
rendering and the pinned manual build pass. Whole-application coverage: 91.92%.
|
||||
|
||||
### v0.9.25
|
||||
|
||||
- Fix Load collapsing Device mapping & transfer to its title bar: the shared
|
||||
|
|
|
|||
|
|
@ -114,6 +114,8 @@ history across restarts. The picker stays open so you can try several themes;
|
|||
close it with its window close button when finished. Reusing a theme moves it to
|
||||
the top without duplicates.
|
||||
Closing the picker without choosing leaves the theme and history unchanged.
|
||||
Use **Theme packs** to install additional palettes; see [Add a theme pack](theme-packs.md)
|
||||
for Tokyo Night, Catppuccin, Detroit: Become Human and Minecraft examples.
|
||||
|
||||
The viewport, grid, layer boxes and source test patterns use the selected palette;
|
||||
selected layers remain gold (darker gold for contrast in light themes). Imported
|
||||
|
|
@ -169,6 +171,7 @@ Open **Menu → Open all settings…**, **Options → Open all settings…**, th
|
|||
**Open all settings…** entry, or **Ctrl/Cmd+,**. The window groups the available controls:
|
||||
|
||||
- **Appearance:** themes, recent choices, icon captions and source-coordinate preview.
|
||||
- **Theme packs:** install/update ZIP palettes, try their themes and remove packs.
|
||||
- **Editing:** aspect-ratio lock, movement snapping and a keyboard/mouse reference.
|
||||
- **Reference images:** import and access to the current project's image settings.
|
||||
- **Files & settings:** the settings-file path, copy-path action and restore defaults.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
# Add a theme pack
|
||||
|
||||
Theme packs add palettes without rebuilding Canvas Pilot. They change the app,
|
||||
viewport and source-coordinate helper colors; they do not change projects,
|
||||
device transfers, imported pictures, fonts or interface size.
|
||||
|
||||
## Install and try the examples
|
||||
|
||||
Download a ZIP, leave it zipped, then open **Settings → Theme packs → Install theme
|
||||
pack…**. Click a theme beneath its pack heading to try it immediately. It also
|
||||
appears in **More themes…** and recent themes. The picker stays open while you
|
||||
try alternatives. Selecting **High Contrast** twice returns to your last theme,
|
||||
including an installed one.
|
||||
|
||||
| Pack | Palette | Editable manifest |
|
||||
| --- | --- | --- |
|
||||
| [Tokyo Night](../../theme-packs/tokyo-night.zip) | Dark blue with cool cyan accents | [manifest.json](../../theme-packs/tokyo-night/manifest.json) |
|
||||
| [Catppuccin Mocha](../../theme-packs/catppuccin.zip) | Soft charcoal and pastel accents | [manifest.json](../../theme-packs/catppuccin/manifest.json) |
|
||||
| [Detroit: Become Human](../../theme-packs/detroit-become-human.zip) | Deep blue, pale text and cyan android-inspired accents | [manifest.json](../../theme-packs/detroit-become-human/manifest.json) |
|
||||
| [Minecraft Overworld](../../theme-packs/minecraft.zip) | Earth and stone surfaces with grass-green accents | [manifest.json](../../theme-packs/minecraft/manifest.json) |
|
||||
|
||||
Tokyo Night adapts the [upstream palette](https://github.com/folke/tokyonight.nvim),
|
||||
and Catppuccin uses [Mocha colors](https://catppuccin.com/palette/). Their license
|
||||
notices travel inside the ZIP and can be viewed under **Attribution and licenses**.
|
||||
The Detroit and Minecraft themes are original, unofficial color interpretations;
|
||||
they include no game artwork, fonts or code and are not endorsed by the games' owners.
|
||||
|
||||
## Manage packs
|
||||
|
||||
Each pack has a bold, collapsible heading with its ID and revision. Expand it to
|
||||
see theme swatches, select a theme, read its attribution or choose **Remove pack…**.
|
||||
Packs start expanded. Theme changes save immediately and survive restart.
|
||||
|
||||
Install a newer revision of the same pack to update it immediately. Equal or older
|
||||
revisions ask before replacing the installed copy. Updating an active theme refreshes
|
||||
its colors. Removing a pack asks for confirmation; if it contains the active theme,
|
||||
Canvas Pilot returns to Midra Dark. The downloaded ZIP is kept for reinstalling.
|
||||
|
||||
If a pack disappears outside the app, Canvas Pilot keeps your saved choice but
|
||||
uses Midra Dark and marks the theme unavailable. Reinstalling that pack restores
|
||||
its colors. Invalid packs are reported and skipped; they do not prevent startup.
|
||||
|
||||
## Make your own
|
||||
|
||||
Start with one of the editable manifests above. Change the pack `id`, each theme's
|
||||
`id` and `name`, and its `colors`; keep the required fields. Choose `light: true`
|
||||
for a light palette or `false` for a dark one. Every color is opaque `#RRGGBB`.
|
||||
Put the file at the ZIP root as `manifest.json`, with no folder or other files.
|
||||
A pack may contain up to 16 themes. Increase its positive `revision` for updates.
|
||||
|
||||
Use your own pack ID when distributing a variant. Retain relevant upstream notices
|
||||
when adapting licensed palettes. Check primary and secondary text on every surface,
|
||||
selection fills and both checkerboard tile colors. Light/dark mode does not fix
|
||||
poorly contrasted colors automatically.
|
||||
|
||||
The [theme-pack contract](../../interfaces/theme-packs.md) lists all palette roles,
|
||||
validation limits, settings compatibility and round-trip behavior. Repository
|
||||
contributors regenerate the four ZIPs with `python3 scripts/build-theme-packs.py`.
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"version": 15,
|
||||
"theme": "midra",
|
||||
"recent_themes": [
|
||||
"midra"
|
||||
],
|
||||
"show_toolbar_icon_names": false,
|
||||
"keep_aspect_ratio": true,
|
||||
"show_source_pattern": false,
|
||||
"snapping": {
|
||||
"enabled": false,
|
||||
"pixels": true,
|
||||
"screen_edges": true,
|
||||
"layer_edges": true,
|
||||
"grid": false,
|
||||
"show_grid": true,
|
||||
"grid_divisions": [
|
||||
8,
|
||||
6
|
||||
],
|
||||
"mask_edges": false
|
||||
},
|
||||
"midra_host": "",
|
||||
"allow_sending_to_program": false,
|
||||
"autoconnect_at_startup": false,
|
||||
"recent_midra_hosts": [],
|
||||
"language": "system",
|
||||
"ui_scale": 1.0,
|
||||
"text_scale": null
|
||||
}
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
# Canvas Pilot application settings, version 14
|
||||
# Canvas Pilot application settings, version 15
|
||||
|
||||
Canvas Pilot was formerly named Midra Layout. The rename preserves existing wire-format identifiers, `.midra.json` projects, settings/recovery locations and `MIDRA_VECTORCRAFT_CLI` configuration. No schema version changes are needed. New exports use Canvas Pilot in human-readable titles; legacy files remain readable.
|
||||
|
||||
Implementation: `crates/canvas-pilot/src/settings.rs`. This per-user JSON file is
|
||||
independent of the [project JSON and SVG contracts](canvas-pilot.md).
|
||||
[Complete default example](canvas-pilot-settings-v14.example.json).
|
||||
[Complete default example](canvas-pilot-settings-v15.example.json).
|
||||
Version 1 files migrate automatically: the saved theme becomes the only entry in
|
||||
`recent_themes`, with all other preferences preserved. The [version 1 example](canvas-pilot-settings-v1.example.json)
|
||||
remains a migration fixture. Version 2 files then migrate by adding disabled
|
||||
snapping with all target types enabled. The [version 2 example](canvas-pilot-settings-v2.example.json)
|
||||
remains a migration fixture too. Version 3 files migrate by adding an empty `midra_host`; the [version 3 example](canvas-pilot-settings-v3.example.json) remains a migration fixture. Version 4 files migrate by adding `allow_sending_to_program: false`; the [version 4 example](canvas-pilot-settings-v4.example.json) remains a migration fixture. Version 5 files migrate with `autoconnect_at_startup: false`; the [version 5 example](canvas-pilot-settings-v5.example.json) remains a migration fixture. Version 6 files migrate with the overlay grid visible, snapping to it disabled, and `grid_divisions: [8, 6]`; the [version 6 example](canvas-pilot-settings-v6.example.json) remains a migration fixture. Version 7 migrates with an empty `recent_midra_hosts` list; the [version 7 example](canvas-pilot-settings-v7.example.json) remains a migration fixture. Version 8 migrates with `language: "system"`; the [version 8 example](canvas-pilot-settings-v8.example.json) remains a migration fixture. Version 9 migrates without changing any preferences; its `system`, `en` and `fr` values remain valid. The [version 9 example](canvas-pilot-settings-v9.example.json) remains a migration fixture. Version 10 adds language choices. Version 11 adds `ui_scale` and `text_scale`; v1–v10 settings migrate to 100% interface scale with separate text scaling disabled, preserving all existing preferences. The [version 10 example](canvas-pilot-settings-v10.example.json) remains a migration fixture. Version 12 adds `pt-PT`, `ne`, `th`, `hi` and `tok`; v1–v11 settings migrate without changing existing preferences. Values outside each old version’s language set are rejected before migration. The [version 11 example](canvas-pilot-settings-v11.example.json) remains a migration fixture. Version 13 adds installed language choices; v12 preferences migrate unchanged. The [version 12 example](canvas-pilot-settings-v12.example.json) remains a fixture. Version 14 adds required `snapping.mask_edges` (false). Versions 1–13 migrate with mask snapping disabled; supplying the field under an older version is rejected. The [version 13 example](canvas-pilot-settings-v13.example.json) remains a migration fixture. Saving writes version 14, which older applications reject.
|
||||
remains a migration fixture too. Version 3 files migrate by adding an empty `midra_host`; the [version 3 example](canvas-pilot-settings-v3.example.json) remains a migration fixture. Version 4 files migrate by adding `allow_sending_to_program: false`; the [version 4 example](canvas-pilot-settings-v4.example.json) remains a migration fixture. Version 5 files migrate with `autoconnect_at_startup: false`; the [version 5 example](canvas-pilot-settings-v5.example.json) remains a migration fixture. Version 6 files migrate with the overlay grid visible, snapping to it disabled, and `grid_divisions: [8, 6]`; the [version 6 example](canvas-pilot-settings-v6.example.json) remains a migration fixture. Version 7 migrates with an empty `recent_midra_hosts` list; the [version 7 example](canvas-pilot-settings-v7.example.json) remains a migration fixture. Version 8 migrates with `language: "system"`; the [version 8 example](canvas-pilot-settings-v8.example.json) remains a migration fixture. Version 9 migrates without changing any preferences; its `system`, `en` and `fr` values remain valid. The [version 9 example](canvas-pilot-settings-v9.example.json) remains a migration fixture. Version 10 adds language choices. Version 11 adds `ui_scale` and `text_scale`; v1–v10 settings migrate to 100% interface scale with separate text scaling disabled, preserving all existing preferences. The [version 10 example](canvas-pilot-settings-v10.example.json) remains a migration fixture. Version 12 adds `pt-PT`, `ne`, `th`, `hi` and `tok`; v1–v11 settings migrate without changing existing preferences. Values outside each old version’s language set are rejected before migration. The [version 11 example](canvas-pilot-settings-v11.example.json) remains a migration fixture. Version 13 adds installed language choices; v12 preferences migrate unchanged. The [version 12 example](canvas-pilot-settings-v12.example.json) remains a fixture. Version 14 adds required `snapping.mask_edges` (false). Versions 1–13 migrate with mask snapping disabled; supplying the field under an older version is rejected. The [version 13 example](canvas-pilot-settings-v13.example.json) remains a migration fixture. Version 15 adds installed theme choices and migrates v1–v14 without changing other preferences. The [version 14 example](canvas-pilot-settings-v14.example.json) remains a migration fixture. Saving writes version 15, which older applications reject.
|
||||
|
||||
The `directories` 6 crate resolves `ProjectDirs::from("org", "beffroi", "midra-layout")`.
|
||||
The filename is `settings.json` beneath `config_dir()`:
|
||||
|
|
@ -26,15 +26,15 @@ unknown theme names are rejected. There are no numeric coordinates or units.
|
|||
|
||||
| Field | Values / default |
|
||||
| --- | --- |
|
||||
| `version` | Integer `14` |
|
||||
| `version` | Integer `15` |
|
||||
| `ui_scale` | Finite number, 0.5–4.0 inclusive; default 1.0. egui interface zoom relative to the OS display scale. |
|
||||
| `text_scale` | `null` (default, disabled) or finite number 0.5–2.0 inclusive. Additional standard-widget text multiplier. |
|
||||
| `language` | `"system"` (default), `"en"`, `"fr"`, `"ja"`, `"zh-CN"`, `"es"`, `"grc"`, `"eo"`, `"pt-PT"`, `"ne"`, `"th"`, `"hi"`, `"tok"`, or `{"pack":"uk"}` for an installed language. Pack identifiers use 1–63 lowercase ASCII letters, digits and hyphens, without a leading/trailing hyphen. Unknown built-in string values are rejected. |
|
||||
| `autoconnect_at_startup` | Boolean; default false. Try one background connection at application startup if the saved address is nonblank. |
|
||||
| `allow_sending_to_program` | Boolean; default false. Enables the Program destination in the exporter. Turning it off restores Preview; applies to quick Apply too. |
|
||||
| `midra_host` | Device IP address text with optional TCP port (e.g. `192.168.10.146:3000`, `[::1]:3000`; default port 80); default `""`. Saved as typed, including incomplete drafts; validated when connecting. |
|
||||
| `theme` | Theme ID from the catalog below; default `"midra"` |
|
||||
| `recent_themes` | 1–3 unique theme IDs, newest first; first must equal `theme`; default `["midra"]` |
|
||||
| `theme` | Built-in theme ID below or `{"pack":"pack-id/theme-id"}`; default `"midra"` |
|
||||
| `recent_themes` | 1–3 unique built-in IDs or pack references, newest first; first must equal `theme`; default `["midra"]` |
|
||||
| `show_toolbar_icon_names` | Boolean; default false |
|
||||
| `keep_aspect_ratio` | Boolean; default true |
|
||||
| `show_source_pattern` | Boolean; default false. Shows source patterns on other layers only during crop editing; normal editing always hides patterns. |
|
||||
|
|
@ -211,3 +211,13 @@ Installed language choices are described by the [language-pack contract](languag
|
|||
They are allowed only in v13; older versions reject object-valued language fields.
|
||||
Unavailable packs preserve the identifier and render English rather than discarding
|
||||
preferences. Installation re-applies a saved missing-pack choice.
|
||||
|
||||
## Installed themes
|
||||
|
||||
Theme packs use `{"pack":"pack-id/theme-id"}` in `theme` and `recent_themes`.
|
||||
Identifiers follow the [theme-pack contract](theme-packs.md). Built-in string IDs
|
||||
remain unchanged; packed choices in settings versions 1–14 are rejected. Missing
|
||||
packs retain the preference with Midra Dark rendering and an unavailable label.
|
||||
Explicit removal or updates that remove the active theme save Midra Dark instead.
|
||||
Re-clicking active High Contrast restores the preceding recent theme, including a
|
||||
packed theme; applying startup settings never toggles High Contrast off.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
# Canvas Pilot theme packs, version 1
|
||||
|
||||
Implementation: `crates/canvas-pilot/src/theme_packs.rs`. User instructions and
|
||||
editable examples: [Add a theme pack](../canvas-pilot/guide/theme-packs.md).
|
||||
Supported from Canvas Pilot v0.9.26.
|
||||
|
||||
## Archive and palette representation
|
||||
|
||||
A ZIP contains exactly one regular root file named `manifest.json`. Directories,
|
||||
symlinks, other paths, extra entries and unsupported ZIP compression/encryption
|
||||
are rejected. Nothing is extracted. Maximum archive size is 2 MiB; the manifest
|
||||
has a 4 MiB expanded limit enforced while reading. CRC/decompression failures
|
||||
reject the pack. JSON is UTF-8; unknown fields and unsupported versions fail.
|
||||
Repeated JSON object keys have serde's last-value behavior; authors must use unique
|
||||
keys. Array order determines theme order within the pack.
|
||||
|
||||
| Field | Representation and validation |
|
||||
| --- | --- |
|
||||
| `version` | Required integer `1` |
|
||||
| `id` | Required pack ID: 1–63 lowercase ASCII letters, digits or hyphens, no leading/trailing hyphen |
|
||||
| `revision` | Required positive `u64`, 1–18446744073709551615; revision comparison is numeric |
|
||||
| `themes` | Required array of 1–16 themes |
|
||||
| `themes[].id` | Same identifier syntax, unique within this pack |
|
||||
| `themes[].name` | Nonblank display name, 1–160 UTF-8 bytes, no control characters |
|
||||
| `themes[].light` | Required boolean selecting egui light/dark base visuals |
|
||||
| `themes[].colors` | Required complete palette object, fields below |
|
||||
| `notices` | Optional attribution/license text, default empty; at most 65,536 UTF-8 bytes; controls forbidden except newline, tab and carriage return |
|
||||
|
||||
Every color is an opaque sRGB string `#RRGGBB`, exactly six hexadecimal digits
|
||||
(case-insensitive). Channels have 8-bit precision; no alpha, gradients, numeric
|
||||
units or geometry are represented. The original ZIP bytes are preserved.
|
||||
|
||||
| Palette field | Use |
|
||||
| --- | --- |
|
||||
| `bg`, `panel`, `field` | App background, panels/windows, input fields |
|
||||
| `line`, `text`, `muted` | Borders, primary text, secondary text |
|
||||
| `cyan`, `amber`, `purple` | Accent/handles, selected-layer/warning accent, selection/button fill |
|
||||
| `canvas`, `banner`, `grid`, `layer` | Viewport background, example banner, grid, layer fill |
|
||||
| `pattern` | Exactly two color strings for alternating source-helper tiles |
|
||||
|
||||
The theme system derives hover colors from these roles and uses its existing
|
||||
light/dark error colors. Font families, text sizes, interface scale, geometry,
|
||||
layout metrics, source images and device behavior are not supplied by packs.
|
||||
There is no executable content or network loading. Authors are responsible for
|
||||
contrast; the examples test at least 4.5:1 for primary text on panel, field,
|
||||
selection and both source-helper tiles. Theme packs cannot override built-ins.
|
||||
|
||||
## Installation, updates and removal
|
||||
|
||||
Packs live in `<settings-parent>/theme-packs/<id>.zip`. The logical choice is
|
||||
`<pack-id>/<theme-id>`, so separate packs can reuse a local theme ID. Installation
|
||||
validates the entire archive before writing; an update replaces the previously
|
||||
loaded path for that ID, even if its ZIP was manually renamed. A valid destination
|
||||
owned by another pack ID cannot be overwritten.
|
||||
|
||||
A new pack or higher revision installs immediately. Equal/lower revisions and an
|
||||
unreadable existing destination require overwrite confirmation. The reviewed
|
||||
source bytes are retained in memory; cancellation changes neither disk nor the
|
||||
loaded palettes. Before commit, destination bytes must still match those reviewed.
|
||||
Writes use a flushed temporary file in the destination directory, atomically
|
||||
persisted with no-clobber behavior for a new pack. Runtime registration changes
|
||||
only after persistence succeeds. Existing destinations over 2 MiB are not replaced.
|
||||
|
||||
Updates replace the entire theme list. The active palette refreshes immediately;
|
||||
if an update removes the active theme, Midra Dark is selected and saved. Removing
|
||||
a pack confirms its ID and included names, requires exact equality with its loaded
|
||||
ZIP bytes, then deletes only the installed copy. A changed/unreadable file leaves
|
||||
runtime state intact. Removing an active theme also selects and saves Midra Dark;
|
||||
other themes keep their selection. Unavailable recent entries are pruned during
|
||||
management, retaining a currently selected missing preference if unrelated to the
|
||||
operation. Source downloads are untouched.
|
||||
|
||||
Startup is offline, scans at most 33 ZIP paths to detect the 32-pack limit, sorts
|
||||
them and considers at most 32. Too many packs, invalid files and duplicate IDs
|
||||
produce errors without stopping startup; the first valid sorted file for an ID
|
||||
wins. Installing a 33rd ZIP is refused; updates at the limit are allowed. Manual
|
||||
changes to installed files take effect after restart.
|
||||
|
||||
## Settings, missing packs and round trips
|
||||
|
||||
[Settings version 15](canvas-pilot-settings.md) stores a packed theme as
|
||||
`{"pack":"tokyo-night/night"}` in `theme` and `recent_themes`; built-in string IDs
|
||||
are unchanged. Versions 1–14 migrate preserving preferences and history, but pack
|
||||
choices under a legacy version are rejected. Older applications reject version 15.
|
||||
The [default fixture](canvas-pilot-settings-v15.example.json) is the migration target.
|
||||
|
||||
Missing/invalid packs preserve the saved theme choice and show an unavailable
|
||||
label, rendering with Midra Dark until the pack is installed again or the user
|
||||
selects another theme. Installation alone does not select an unrelated theme.
|
||||
Loaded palettes and selection are scoped to an egui context. High Contrast can
|
||||
return to a packed previous theme. Project, recovery and exchange files contain
|
||||
no pack palettes or theme preferences; their representations remain unchanged.
|
||||
|
||||
The editable manifests and ZIPs contain identical bytes, checked by Rust tests
|
||||
and `python3 scripts/build-theme-packs.py --check`. Lifecycle tests cover startup,
|
||||
selection persistence, live updates, overwrite review/cancellation, changed-file
|
||||
protection, removal, limits, malformed colors/archives and context isolation.
|
||||
|
|
@ -21,6 +21,7 @@
|
|||
- [Import, export and project files](../../canvas-pilot/guide/files.md)
|
||||
- [Menus and preferences](../../canvas-pilot/guide/preferences.md)
|
||||
- [Add a language pack](../../canvas-pilot/guide/language-packs.md)
|
||||
- [Add a theme pack](../../canvas-pilot/guide/theme-packs.md)
|
||||
- [Device connection and transfers](../../canvas-pilot/guide/device.md)
|
||||
- [Resolution and cropping model](../../canvas-pilot/resolutions.md)
|
||||
- [Changelog](../../canvas-pilot/changelog.md)
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"version": 1,
|
||||
"id": "catppuccin",
|
||||
"revision": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "mocha",
|
||||
"name": "Catppuccin Mocha",
|
||||
"light": false,
|
||||
"colors": {
|
||||
"canvas": "#1e1e2e",
|
||||
"banner": "#181825",
|
||||
"grid": "#585b70",
|
||||
"layer": "#313244",
|
||||
"pattern": [
|
||||
"#313244",
|
||||
"#11111b"
|
||||
],
|
||||
"bg": "#1e1e2e",
|
||||
"panel": "#181825",
|
||||
"field": "#11111b",
|
||||
"line": "#585b70",
|
||||
"text": "#cdd6f4",
|
||||
"muted": "#bac2de",
|
||||
"cyan": "#74c7ec",
|
||||
"amber": "#f9e2af",
|
||||
"purple": "#45475a"
|
||||
}
|
||||
}
|
||||
],
|
||||
"notices": "Catppuccin Mocha palette adapted to Canvas Pilot color roles.\nSource: https://github.com/catppuccin/palette\n\nMIT License\n\nCopyright (c) 2021 Catppuccin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
||||
}
|
||||
Binary file not shown.
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"version": 1,
|
||||
"id": "detroit-become-human",
|
||||
"revision": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "android",
|
||||
"name": "Detroit: Become Human",
|
||||
"light": false,
|
||||
"colors": {
|
||||
"canvas": "#101a26",
|
||||
"banner": "#172b3d",
|
||||
"grid": "#42617c",
|
||||
"layer": "#203b50",
|
||||
"pattern": [
|
||||
"#203b50",
|
||||
"#0c1521"
|
||||
],
|
||||
"bg": "#101a26",
|
||||
"panel": "#172b3d",
|
||||
"field": "#0c1521",
|
||||
"line": "#42617c",
|
||||
"text": "#edf6ff",
|
||||
"muted": "#b6cddd",
|
||||
"cyan": "#66d9ff",
|
||||
"amber": "#f3ce79",
|
||||
"purple": "#214e6a"
|
||||
}
|
||||
}
|
||||
],
|
||||
"notices": "Original Canvas Pilot palette inspired by the blue-and-white android interface aesthetic of Detroit: Become Human. Unofficial; no game artwork, fonts or code included. Not affiliated with Quantic Dream or Sony. Palette provided under the Canvas Pilot MIT license."
|
||||
}
|
||||
Binary file not shown.
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"version": 1,
|
||||
"id": "minecraft",
|
||||
"revision": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "overworld",
|
||||
"name": "Minecraft Overworld",
|
||||
"light": false,
|
||||
"colors": {
|
||||
"canvas": "#182018",
|
||||
"banner": "#283024",
|
||||
"grid": "#65704b",
|
||||
"layer": "#363d28",
|
||||
"pattern": [
|
||||
"#363d28",
|
||||
"#1e241b"
|
||||
],
|
||||
"bg": "#182018",
|
||||
"panel": "#283024",
|
||||
"field": "#1e241b",
|
||||
"line": "#65704b",
|
||||
"text": "#f1eddb",
|
||||
"muted": "#c5cbb2",
|
||||
"cyan": "#a8dc70",
|
||||
"amber": "#f2ce76",
|
||||
"purple": "#3e5830"
|
||||
}
|
||||
}
|
||||
],
|
||||
"notices": "Original Canvas Pilot palette inspired by Minecraft grass, stone and earth colors. Unofficial; no game artwork, fonts or code included. Not affiliated with Mojang or Microsoft. Palette provided under the Canvas Pilot MIT license."
|
||||
}
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Build deterministic example theme ZIPs, or check their exact source bytes."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def archive(manifest):
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, 'w') as output:
|
||||
info = zipfile.ZipInfo('manifest.json', (2026, 1, 1, 0, 0, 0))
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.external_attr = 0o100644 << 16
|
||||
output.writestr(info, manifest)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--check', action='store_true')
|
||||
args = parser.parse_args()
|
||||
for source in sorted((ROOT / 'docs/theme-packs').glob('*/manifest.json')):
|
||||
target = source.parent.with_suffix('.zip')
|
||||
data = archive(source.read_bytes())
|
||||
if args.check:
|
||||
if not target.exists() or target.read_bytes() != data:
|
||||
raise SystemExit(f'Out-of-date theme pack: {target}')
|
||||
else:
|
||||
target.write_bytes(data)
|
||||
print(target.relative_to(ROOT))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
"""Example ZIPs remain reproducible and contain only their editable manifest."""
|
||||
import importlib.util
|
||||
import io
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('build_theme_packs', ROOT / 'scripts/build-theme-packs.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
class ThemePackExamples(unittest.TestCase):
|
||||
def test_archives_match_sources_and_rebuild_exactly(self):
|
||||
manifests = list((ROOT / 'docs/theme-packs').glob('*/manifest.json'))
|
||||
self.assertEqual(len(manifests), 4)
|
||||
for source in manifests:
|
||||
with self.subTest(pack=source.parent.name):
|
||||
expected = source.parent.with_suffix('.zip').read_bytes()
|
||||
self.assertEqual(module.archive(source.read_bytes()), expected)
|
||||
with zipfile.ZipFile(io.BytesIO(expected)) as archive:
|
||||
self.assertEqual(archive.namelist(), ['manifest.json'])
|
||||
self.assertEqual(archive.read('manifest.json'), source.read_bytes())
|
||||
Loading…
Reference in New Issue