Move to egui 0.37 and craft-ui's shared panel docking

egui, eframe and the craft-ui pin go to the suite's egui 0.37 forks and craft-libs f8f8829c.
The panels dock through craft_ui::docking (native floating windows on desktop) in place of
egui_dock, which has no egui 0.37 release. The viewport is the protected central canvas.
Layouts saved before load into the new workspace; an unreadable one becomes the default.
egui-phosphor has no egui 0.37 release, so a copy with the egui requirement raised is vendored.
This commit is contained in:
aiongg committed 2026-11-01 05:37:02 +00:00
1 parent b7bdb67b49
commit 5803904622
35 files changed
+5768 -878

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ These come from Rust crate dependencies (not files in this repository) and keep
| Asset | Used for | Author | Source | License |
|---|---|---|---|---|
| Phosphor Icons (regular), via the `egui-phosphor` crate | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
| Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web) and Noto Sans CJK SC Regular (desktop), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese and Chinese UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 |
Generated
+607 -222
View File
File diff suppressed because it is too large. Load diff
+21 -5
View File
@@ -1,6 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "apps/texturecraft-web", "xtask"]
exclude = ["vendor"]
default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"]
[workspace.package]
@@ -35,8 +36,8 @@ log = "0.4"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] }
half = "2"
exr = { version = "1.73", default-features = false }
eframe = { version = "0.36", default-features = false }
egui = "0.36"
eframe = { version = "0.37", default-features = false }
egui = "0.37"
wgpu = "30"
rfd = "0.17"
zip = { version = "2", default-features = false, features = ["deflate"] }
@@ -53,9 +54,24 @@ schemars = "1"
base64 = "0.22"
cap-std = "4"
getrandom = "0.3"
# Shared Craft egui components (widget palette, icon buttons): storytold/craft-libs, MIT OR
# Apache-2.0, pinned to the rev VectorCraft uses.
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675" }
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
# MIT OR Apache-2.0, pinned to one rev.
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md).
egui-phosphor = { path = "vendor/egui-phosphor" }
[workspace.lints.rust]
unsafe_code = "forbid"
+6 -2
View File
@@ -15,8 +15,6 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"]
egui = { workspace = true }
craft-ui = { workspace = true }
egui-phosphor = { version = "0.14", features = ["regular", "fill"] }
# Dockable, tabbed, floating panels (MIT).
egui_dock = { version = "0.21", features = ["serde"] }
serde = { workspace = true }
serde_json = { workspace = true }
rayon = { workspace = true }
@@ -29,6 +27,8 @@ zip = { workspace = true }
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
[target.'cfg(target_arch = "wasm32")'.dependencies]
@@ -36,3 +36,7 @@ wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
# winit needs a window system on Linux, so the crate's own tests build with X11.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
eframe = { workspace = true, features = ["x11"] }
+10 -16
View File
@@ -41,27 +41,21 @@ fn err(e: impl std::fmt::Display) -> Value {
}
pub fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Finished window screenshots.
let shots: Vec<std::sync::Arc<egui::ColorImage>> =
ctx.input(|i| i.raw.events.iter().filter_map(|e| if let egui::Event::Screenshot { image, .. } = e { Some(image.clone()) } else { None }).collect());
for img in shots {
let reply = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect())
.map(|(w, h, png)| ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })))
.unwrap_or_else(|| err("could not encode the screenshot"));
for w in app.screenshot_waiters.drain(..) {
let _ = w.send(reply.clone());
}
}
if !app.screenshot_waiters.is_empty() {
ctx.request_repaint();
}
let Some(rx) = app.control.as_ref() else { return };
let reqs: Vec<ControlRequest> = rx.try_iter().collect();
for r in reqs {
if r.method == "ui.screenshot" {
// Replies when the next frame has been captured.
app.screenshot_waiters.push(r.reply);
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::default()));
let reply = r.reply;
let repaint = ctx.clone();
let callback = egui::ScreenshotCallback::new(move |img| {
let answer = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect())
.map(|(w, h, png)| ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })))
.unwrap_or_else(|| err("could not encode the screenshot"));
let _ = reply.send(answer);
repaint.request_repaint();
});
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
ctx.request_repaint();
continue;
}
+6 -6
View File
@@ -63,7 +63,7 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0));
let eye_resp = ui.interact(eye, ui.id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set"));
let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text);
// Narrow panels drop the shader label, then the resolution, before cutting the name.
let cy = rect.center().y;
@@ -273,7 +273,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let x0 = rect.left() + 6.0 + depth as f32 * 14.0;
// Eye.
let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0));
let eye_resp = ui.interact(eye, ui.id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer"));
let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer"));
p.text(
eye.center(),
egui::Align2::CENTER_CENTER,
@@ -288,7 +288,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let mut x = x0 + 20.0;
if let LayerKind::Group { collapsed, .. } = layer.kind {
let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0));
let cr = ui.interact(caret, ui.id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder"));
let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder"));
p.text(
caret.center(),
egui::Align2::CENTER_CENTER,
@@ -357,7 +357,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger));
}
let mr = ui
.interact(mask_rect, ui.id().with(("mask", layer.id.0)), Sense::click())
.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click())
.on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)"));
if mr.clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"}));
@@ -401,7 +401,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0));
let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0));
if let Some(b) = blend {
let br = ui.interact(blend_rect, ui.id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel"));
let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel"));
p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text);
p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim);
egui::Popup::menu(&br).show(|ui| {
@@ -504,7 +504,7 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI
}
let x0 = rect.left() + 6.0 + depth as f32 * 14.0;
let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0));
let er = ui.interact(eye, ui.id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim);
p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim);
p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text);
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -259,7 +259,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]
for name in names {
match app.ui.export.renaming.as_mut().filter(|_| name == sel) {
Some(buf) => {
let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::new(RENAME_ID)).desired_width(f32::INFINITY));
let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY));
if r.lost_focus() {
act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { ListAction::Select(name) } else { ListAction::Rename(buf.clone()) });
}
@@ -294,7 +294,7 @@ fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
ListAction::StartRename(name) => {
app.ui.export.preset = name.clone();
app.ui.export.renaming = Some(name);
ctx.memory_mut(|m| m.request_focus(egui::Id::new(RENAME_ID)));
ctx.memory_mut(|m| m.request_focus(egui::Id::unique(RENAME_ID)));
}
ListAction::Rename(name) => rename(app, name.trim()),
ListAction::Remove => {
@@ -636,7 +636,7 @@ fn input_maps(ui: &mut Ui) {
&& let Some(at) = r.interact_pointer_pos()
{
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
egui::Area::new(egui::Id::new(("exp_input_drag", gi, k)))
egui::Area::new(egui::Id::unique(("exp_input_drag", gi, k)))
.order(egui::Order::Tooltip)
.fixed_pos(at + vec2(8.0, 8.0))
.show(ui.ctx(), |ui| chip(ui, label, true));
+5 -3
View File
@@ -190,7 +190,9 @@ fn load(script: Script) -> Option<FontData> {
fn aligned(mut data: FontData) -> FontData {
let defs = egui::FontDefinitions::default();
let primary = defs.families.get(&FontFamily::Proportional).and_then(|f| f.first()).and_then(|n| defs.font_data.get(n));
if let (Some((pa, pd, pg)), Some((ca, cd, cg))) = (primary.and_then(|p| line_metrics(&p.font, p.index)), line_metrics(&data.font, data.index)) {
if let (Some((pa, pd, pg)), Some((ca, cd, cg))) =
(primary.and_then(|p| line_metrics(p.font.as_ref().as_ref(), p.index)), line_metrics(data.font.as_ref().as_ref(), data.index))
{
// Baseline of a fallback glyph: its ascent plus half the difference of the line boxes.
let drift = ca + 0.5 * ((pa - pd + pg) - (ca - cd + cg)) - pa;
if drift.is_finite() && drift.abs() < 1.0 {
@@ -238,10 +240,10 @@ mod tests {
fn line_metrics_read_the_default_font_and_reject_garbage() {
let defs = egui::FontDefinitions::default();
let ubuntu = defs.font_data.get("Ubuntu-Light").unwrap();
let (a, d, g) = line_metrics(&ubuntu.font, 0).unwrap();
let (a, d, g) = line_metrics(ubuntu.font.as_ref().as_ref(), 0).unwrap();
assert!(a > 0.5 && a < 1.5 && d < 0.0 && d > -0.6 && g >= 0.0, "{a} {d} {g}");
// The primary font needs no shift against itself.
assert_eq!(aligned(FontData::from_owned(ubuntu.font.to_vec())).tweak.y_offset_factor, 0.0);
assert_eq!(aligned(FontData::from_owned(ubuntu.font.as_ref().as_ref().to_vec())).tweak.y_offset_factor, 0.0);
for junk in [&b""[..], b"ttcf", b"\0\x01\0\0\0\x09", &[0xff; 64]] {
assert!(line_metrics(junk, 0).is_none());
assert!(line_metrics(junk, 7).is_none());
+3 -3
View File
@@ -147,7 +147,7 @@ const CAPTURE: &str = "keymap_capture";
/// Whether the editor is waiting for a key combination (global shortcuts pause meanwhile).
pub fn capturing(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<usize>(Id::new(CAPTURE))).is_some()
ctx.data(|d| d.get_temp::<usize>(Id::unique(CAPTURE))).is_some()
}
/// The first key press this frame as a shortcut.
@@ -166,8 +166,8 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !app.ui.windows.shortcuts {
return;
}
let capture_id = Id::new(CAPTURE);
let filter_id = Id::new("keymap_filter");
let capture_id = Id::unique(CAPTURE);
let filter_id = Id::unique("keymap_filter");
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
if let (Some(i), Some(sc)) = (capture, pressed(ctx)) {
if (sc.logical_key != Key::Escape || !sc.modifiers.is_none())
+1 -4
View File
@@ -74,8 +74,6 @@ pub struct TextureCraftApp {
pub thumbs: thumbs::Thumbs,
/// Last frame's viewport rect (logical points), for scripted input.
pub viewport_rect: egui::Rect,
/// Pending screenshot requests from the control channel.
pub screenshot_waiters: Vec<std::sync::mpsc::Sender<Value>>,
pub fps: f32,
/// User smart materials found in the library folder (refreshed on demand).
pub library: Option<Vec<std::path::PathBuf>>,
@@ -127,7 +125,6 @@ impl TextureCraftApp {
resize: None,
thumbs: thumbs::Thumbs::default(),
viewport_rect: egui::Rect::NOTHING,
screenshot_waiters: Vec::new(),
fps: 0.0,
ui_ms: 0.0,
profiler: profile::Profiler::default(),
@@ -465,7 +462,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
ctx.request_repaint_after(std::time::Duration::from_millis(250));
let tk = theme::Tokens::get(ctx);
egui::Area::new(egui::Id::new("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
for t in &app.toasts {
egui::Frame::NONE
.fill(tk.panel)
+16 -2
View File
@@ -118,14 +118,14 @@ pub fn implemented(id: &str) -> bool {
/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`).
pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
if let Some(panel) = crate::docking::view_panel(id) {
app.ui.dock.toggle(panel, ctx.content_rect());
app.ui.dock.toggle(panel);
return;
}
match id {
"ui.newProject" => app.ui.windows.new_project = true,
"ui.export" => app.ui.windows.export = true,
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
"ui.projectConfig" => app.ui.dock.focus(crate::docking::Panel::Display, ctx.content_rect()),
"ui.projectConfig" => app.ui.dock.focus(crate::docking::Panel::Display),
"ui.settings" => app.ui.windows.settings = true,
"ui.mode.bake" => app.ui.mode = Mode::Baking,
"ui.mode.paint" => app.ui.mode = Mode::Painting,
@@ -254,6 +254,20 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui,
/// Global shortcuts: the catalog's and every engine command's (defaults or the user's keymap),
/// plus the fixed brush keys.
/// Keys pressed in a floating panel's own OS window run the shortcuts the main window's keys do.
#[cfg(not(target_arch = "wasm32"))]
pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec<egui::Event>, _modifiers: Modifiers) {
if crate::keymap::capturing(ctx) {
return;
}
let active = crate::keymap::active(&app.ui.keymap);
for event in events {
let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue };
let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue };
invoke(app, ctx, id);
}
}
pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) {
return;
+1 -1
View File
@@ -172,7 +172,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
fn drag_preview(ctx: &egui::Context) {
let tk = Tokens::get(ctx);
let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::<ShelfDrag>(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return };
let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("shelf_drag")));
let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("shelf_drag")));
let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), tk.text_strong);
let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0));
p.rect_filled(rect, 3.0, tk.row_selected);
+2 -3
View File
@@ -199,7 +199,7 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
app.ui.mode = if app.ui.mode == Mode::Rendering { Mode::Painting } else { Mode::Rendering };
}
if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() {
app.ui.dock.focus(Panel::Assets, ui.ctx().content_rect());
app.ui.dock.focus(Panel::Assets);
}
});
});
@@ -213,7 +213,6 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, 26.0).clicked() {
app.ui.windows.export = !app.ui.windows.export;
}
let screen = ui.ctx().content_rect();
for (panel, icon, id) in [
(Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"),
(Panel::Display, ic::MONITOR, "ui.view.display"),
@@ -221,7 +220,7 @@ pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
(Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"),
] {
if icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.dock.is_visible(panel), 26.0).clicked() {
app.ui.dock.toggle(panel, screen);
app.ui.dock.toggle(panel);
}
}
});
+4 -4
View File
@@ -23,7 +23,7 @@ pub const VIEW_2D: u64 = 2;
/// While on, a click in the 3D view focuses the depth of field there (a transient UI mode kept in
/// egui's memory).
fn focus_pick_id() -> egui::Id {
egui::Id::new("tc_focus_pick")
egui::Id::unique("tc_focus_pick")
}
pub fn focus_picking(ctx: &egui::Context) -> bool {
@@ -193,7 +193,7 @@ fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) {
}
fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
let resp = ui.interact(rect, ui.id().with("view3d"), Sense::click_and_drag());
let resp = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag());
app.viewport_rect = rect;
let size = rect.size();
app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0));
@@ -441,7 +441,7 @@ struct DecalDrag {
}
fn decal_drag_id() -> egui::Id {
egui::Id::new("tc_decal_drag")
egui::Id::unique("tc_decal_drag")
}
/// Screen distance from the top edge to the rotation handle (points).
@@ -788,7 +788,7 @@ fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3
fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
let tk = Tokens::get(ui.ctx());
let resp = ui.interact(rect, ui.id().with("view2d"), Sense::click_and_drag());
let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag());
let size = rect.size();
let alt = ui.input(|i| i.modifiers.alt);
let delta = ui.input(|i| i.pointer.delta());
+2 -2
View File
@@ -113,7 +113,7 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) {
if IMAGE_EXTS.contains(&ext.as_str()) {
match app.session.import_resource_bytes(name, bytes.to_vec()) {
Ok(res) => {
app.ui.dock.focus(crate::docking::Panel::Assets, egui::Rect::ZERO);
app.ui.dock.focus(crate::docking::Panel::Assets);
app.toast(trf("Imported {name}", &[("name", &res)]), false);
}
Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &name), ("error", &e)]), true),
@@ -142,7 +142,7 @@ pub fn dropped(app: &mut TextureCraftApp, ctx: &egui::Context, file: &egui::Drop
if IMAGE_EXTS.contains(&ext.as_str()) {
if let Some(r) = app.run("resource.import", serde_json::json!({ "path": path })) {
let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
app.ui.dock.focus(crate::docking::Panel::Assets, egui::Rect::ZERO);
app.ui.dock.focus(crate::docking::Panel::Assets);
app.toast(trf("Imported {name}", &[("name", &name)]), false);
}
} else {
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI
ui.label(RichText::new(label).color(tk.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut text = format!("{:.*}", decimals, value);
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).horizontal_align(egui::Align::RIGHT).frame(egui::Frame::NONE));
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE));
if r.lost_focus()
&& let Ok(v) = text.trim().parse::<f32>()
&& v.is_finite()
+11 -6
View File
@@ -33,7 +33,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
/// A titled tool window; `id` keeps its place across UI languages.
pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> {
egui::Window::new(RichText::new(title.to_uppercase()).size(10.5).strong())
.id(egui::Id::new(id))
.id(egui::Id::unique(id))
.open(open)
.resizable(true)
.collapsible(false)
@@ -42,7 +42,12 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win
/// A centered dialog; `id` keeps its place across UI languages.
fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> {
egui::Window::new(title.to_owned()).id(egui::Id::new(id)).open(open).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
egui::Window::new(title.to_owned())
.id(egui::Id::unique(id))
.open(open)
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
}
/// The Display Settings panel body (a dock tab).
@@ -127,7 +132,7 @@ fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) {
app.run("camera.select", json!({"index": i}));
}
// The name being typed lives in egui's memory until the field loses focus.
let id = ui.id().with(("camera_name", i));
let id = ui.scope_id().with(("camera_name", i));
let mut text = ui.data(|d| d.get_temp::<String>(id)).unwrap_or_else(|| name.clone());
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 26.0));
if r.changed() {
@@ -377,7 +382,7 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.label(tr("Accent color"));
for a in Accent::ALL {
let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, p.accent == a, tr(a.label())));
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label())));
let ring = if p.accent == a {
tk.text_strong
} else if resp.hovered() {
@@ -743,7 +748,7 @@ fn map_params(ui: &mut Ui, m: BakedMap, b: &mut BakeSettings) {
}
fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context) {
egui::Area::new(egui::Id::new("bake_bar")).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -40.0)).show(ctx, |ui| {
egui::Area::new(egui::Id::unique("bake_bar")).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -40.0)).show(ctx, |ui| {
ui.horizontal(|ui| {
if let Some(p) = app.bake_progress() {
ui.add(egui::ProgressBar::new(p).desired_width(220.0).show_percentage());
@@ -862,7 +867,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
app.toast(trf("Imported {name}", &[("name", &name)]), false);
}
}
app.ui.dock.focus(crate::docking::Panel::Assets, _ctx.content_rect());
app.ui.dock.focus(crate::docking::Panel::Assets);
true
}
"file.exportMesh" => {
+1 -1
View File
@@ -48,7 +48,7 @@ keeps its state in a throwaway file.
| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts |
| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` |
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window) |
| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout (`{main, windows}`: `{"tabs": {"tabs": [...], "active": 0}}` or `{"split": {"vertical", "fraction", "first", "second"}}` nodes over `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`; `closed` lists where each closed panel was, so reopening it puts it back), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` |
| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default, and the earlier `{main, windows, closed}` layout is converted), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` |
| `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) |
| `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame |
| `ui.resize` | `{width, height}` | Sets the window's inner size in points (640–7680), leaving maximized state; for recordings and screenshots at a fixed size |
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "egui-phosphor"
description = "Phosphor icons for egui"
version = "0.14.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/amPerl/egui-phosphor"
[dependencies]
egui = { version = "0.37", default-features = false }
[features]
default = ["regular"]
thin = []
light = []
regular = []
bold = []
fill = []
subset = ["thin", "light", "regular", "bold", "fill"]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Romet Tagobert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
# egui_phosphor
Bundles [Phosphor icons](https://phosphoricons.com/) with boilerplate to use in your egui app.
## Installation
Add the crate as a dependency in Cargo.toml:
```toml
egui-phosphor = "0.14"
```
On startup, update the fonts in your egui context:
```rust
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
cc.egui_ctx.set_fonts(fonts);
```
The above `add_to_fonts` helper adds the chosen variant (`Regular`) as a fallback to the primary egui `Proportional` font so that when you use Phosphor icons mixed with plain text in labels, the icon font will take over where necessary. If you want to add multiple variants of Phosphor icons, see [this example](examples/multiple_variants.rs) which shows all variants in use.
## Usage
Use the constants provided by the crate in your text:
```rust
ui.label(egui::RichText::new(format!("FILE_CODE {}", egui_phosphor::regular::FILE_CODE)).size(32.0));
```
**Note: Make sure to use the appropriate character codes for your chosen variant!** This means for `Variant::Regular` you should use `regular::FILE_CODE`, for `Variant::Fill` you should use `fill::FILE_CODE` etc.
## Subsetting
The optional `subset` feature reduces the font at compile time to only the icons you specify, at the cost of roughly 0.3s per rebuild of the crate that invokes it:
```toml
egui-phosphor = { version = "0.14", features = ["subset"] }
```
```rust
egui_phosphor::subset! {
pub mod icons {
use regular::{GEAR, HOUSE, TRASH};
}
}
// on startup:
let mut fonts = egui::FontDefinitions::default();
icons::regular::add_to_fonts(&mut fonts);
cc.egui_ctx.set_fonts(fonts);
// in your UI:
ui.label(format!("{} Settings", icons::regular::GEAR));
```
### Multiple variants
Because every variant uses the same codepoints, only one of the variants can be the default fallback for the proportional font. Add that one with `add_to_fonts`, the rest with `add_as_family`, and select those by family:
```rust
egui_phosphor::subset! {
pub mod icons {
use regular::{GEAR, HOUSE};
use fill::{GEAR, HEART};
}
}
icons::regular::add_to_fonts(&mut fonts);
icons::fill::add_as_family(&mut fonts);
ui.label(format!("{} Settings", icons::regular::GEAR));
ui.label(icons::fill::rich(format!("{} Favourite", icons::fill::HEART)));
```
## License
egui-phosphor is licensed under [MIT](LICENSE-MIT) OR [Apache-2.0](LICENSE-APACHE). Phosphor Icons are licensed under [MIT](https://github.com/phosphor-icons/web/blob/master/LICENSE).
+9
View File
@@ -0,0 +1,9 @@
# egui-phosphor 0.14.0 (vendored)
Source: https://github.com/amPerl/egui-phosphor (crates.io `egui-phosphor` 0.14.0), MIT OR Apache-2.0.
The crate has no release for egui 0.37, so the workspace patches `egui-phosphor` to this copy, which
depends on egui 0.37. Only the dependency version in `Cargo.toml` differs; examples, tests and the
unused font variants (thin, light, bold) are left out. The `regular` and `fill` fonts are the Phosphor
Icons font (MIT, https://phosphoricons.com). Drop this directory and the patch once the crate releases
for egui 0.37.
Binary file not shown.
Binary file not shown.
+65
View File
@@ -0,0 +1,65 @@
pub mod variants;
pub use variants::*;
#[cfg(feature = "subset")]
pub mod subset;
/// Re-exported for [`subset!`].
pub use egui;
pub fn add_to_fonts(fonts: &mut egui::FontDefinitions, variant: Variant) {
add_font_bytes_to_fonts(fonts, "phosphor", variant.font_bytes());
}
/// Insert `bytes` under `name`, make it a fallback for proportional text so
/// icons can be mixed into ordinary labels, and register a
/// [`FontFamily::Name(name)`](egui::FontFamily::Name) that resolves to it.
///
/// `name` must be unique per font, otherwise later calls overwrite earlier ones.
///
/// Because every Phosphor variant uses the same codepoints, proportional text
/// can only resolve an icon to one of them. Use [`add_font_bytes_as_family`] for
/// any additional variants and select them explicitly by family.
pub fn add_font_bytes_to_fonts(
fonts: &mut egui::FontDefinitions,
name: &str,
bytes: &'static [u8],
) {
add_font_bytes_as_family(fonts, name, bytes);
if let Some(font_keys) = fonts.families.get_mut(&egui::FontFamily::Proportional) {
// Second, so it does not shadow the text font -- but `Proportional` can
// be empty when egui is built without `default_fonts`.
let at = font_keys.len().min(1);
font_keys.insert(at, name.into());
}
}
/// Insert `bytes` under `name` and register a
/// [`FontFamily::Name(name)`](egui::FontFamily::Name) for it, without adding it
/// to the proportional fonts.
///
/// The family also contains the proportional fonts. `name` goes second, not
/// first: the subset maps `a`-`z` to the blank glyphs Phosphor's ligatures are
/// built from, so putting it ahead of the text font would blank out ordinary
/// lowercase text. Second still puts it ahead of any other icon font and of
/// egui's emoji fonts, so the icons themselves resolve from it.
pub fn add_font_bytes_as_family(
fonts: &mut egui::FontDefinitions,
name: &str,
bytes: &'static [u8],
) {
fonts
.font_data
.insert(name.into(), egui::FontData::from_static(bytes).into());
let mut keys = fonts
.families
.get(&egui::FontFamily::Proportional)
.cloned()
.unwrap_or_default();
keys.insert(keys.len().min(1), name.into());
fonts
.families
.insert(egui::FontFamily::Name(name.into()), keys);
}
+1016
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
pub use super::codepoints::*;
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
pub use super::codepoints::*;
+1
View File
@@ -0,0 +1 @@
pub use super::codepoints::*;
+83
View File
@@ -0,0 +1,83 @@
// Every variant uses the same codepoints, so they share one table and each
// variant module re-exports it. `update.py` verifies this still holds.
mod codepoints;
#[cfg(feature = "bold")]
pub mod bold;
#[cfg(feature = "fill")]
pub mod fill;
#[cfg(feature = "light")]
pub mod light;
#[cfg(feature = "regular")]
pub mod regular;
#[cfg(feature = "thin")]
pub mod thin;
#[cfg(not(any(
feature = "thin",
feature = "light",
feature = "regular",
feature = "bold",
feature = "fill",
)))]
compile_error!(
"At least one font variant must be selected as a crate feature. When in doubt, use default features."
);
pub mod bytes {
#[cfg(feature = "thin")]
pub mod thin {
pub const FONT: &[u8] = include_bytes!("../../res/Phosphor-Thin.ttf");
}
#[cfg(feature = "light")]
pub mod light {
pub const FONT: &[u8] = include_bytes!("../../res/Phosphor-Light.ttf");
}
#[cfg(feature = "regular")]
pub mod regular {
pub const FONT: &[u8] = include_bytes!("../../res/Phosphor.ttf");
}
#[cfg(feature = "bold")]
pub mod bold {
pub const FONT: &[u8] = include_bytes!("../../res/Phosphor-Bold.ttf");
}
#[cfg(feature = "fill")]
pub mod fill {
pub const FONT: &[u8] = include_bytes!("../../res/Phosphor-Fill.ttf");
}
}
#[derive(Debug, Clone, Copy)]
pub enum Variant {
#[cfg(feature = "thin")]
Thin,
#[cfg(feature = "light")]
Light,
#[cfg(feature = "regular")]
Regular,
#[cfg(feature = "bold")]
Bold,
#[cfg(feature = "fill")]
Fill,
}
impl Variant {
pub fn font_bytes(&self) -> &'static [u8] {
match self {
#[cfg(feature = "thin")]
Variant::Thin => bytes::thin::FONT,
#[cfg(feature = "light")]
Variant::Light => bytes::light::FONT,
#[cfg(feature = "regular")]
Variant::Regular => bytes::regular::FONT,
#[cfg(feature = "bold")]
Variant::Bold => bytes::bold::FONT,
#[cfg(feature = "fill")]
Variant::Fill => bytes::fill::FONT,
}
}
pub fn font_data(&self) -> egui::FontData {
egui::FontData::from_static(self.font_bytes())
}
}
+1
View File
@@ -0,0 +1 @@
pub use super::codepoints::*;
+1
View File
@@ -0,0 +1 @@
pub use super::codepoints::*;