Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 34 additions & 13 deletions crates/ui-egui/src/bedit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,29 +118,50 @@ fn preview(app: &mut CadApp, name: &str) -> Option<Arc<DisplayList>> {
{
return Some(list.clone());
}
// The drawing itself shows its model space.
let entities = if name.eq_ignore_ascii_case(CURRENT_DRAWING) { &st.doc.model } else { &st.doc.block(name)?.entities };
let rough = cadcraft_render::build_entities(&st.doc, entities.iter().map(|e| e.as_ref()), &cadcraft_render::Options::default());
let size = rough.bounds.width().max(rough.bounds.height());
// About half a pixel of the preview's 200 points.
let opts = cadcraft_render::Options { tolerance: (size / 400.0).max(1e-9), ..Default::default() };
let list =
Arc::new(if rough.bounds.is_empty() { rough } else { cadcraft_render::build_entities(&st.doc, entities.iter().map(|e| e.as_ref()), &opts) });
let list = Arc::new(build_preview(&st.doc, name, 200.0)?);
app.bedit.preview = Some((key, list.clone()));
Some(list)
}

/// Draw `list` fitted into `rect`, or `note` when there is nothing to draw.
fn draw_preview(ui: &mut egui::Ui, list: Option<&DisplayList>, note: &str) {
/// The display list of block `name` in `d` for a preview `px` points across: a rough build for
/// the extents, then one at about half a pixel's tolerance. [`CURRENT_DRAWING`] is model space.
/// Rays and construction lines add nothing to a list's extents; with nothing else to frame, the
/// preview frames their base points.
pub(crate) fn build_preview(d: &Drawing, name: &str, px: f64) -> Option<DisplayList> {
let entities = if name.eq_ignore_ascii_case(CURRENT_DRAWING) { &d.model } else { &d.block(name)?.entities };
let mut rough = cadcraft_render::build_entities(d, entities.iter().map(|e| e.as_ref()), &cadcraft_render::Options::default());
if rough.bounds.is_empty() {
rough.bounds = infinite_frame(&rough);
return Some(rough);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
let size = rough.bounds.width().max(rough.bounds.height());
let opts = cadcraft_render::Options { tolerance: (size / (2.0 * px.max(1.0))).max(1e-9), ..Default::default() };
Some(cadcraft_render::build_entities(d, entities.iter().map(|e| e.as_ref()), &opts))
}

/// A frame around the base points of `list`'s rays and construction lines, padded by half their
/// spread (at least one drawing unit) so each line crosses the preview; empty when it has none.
fn infinite_frame(list: &DisplayList) -> cadcraft_geom::Bounds2 {
let bases =
list.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Infinite { .. })).filter_map(|p| list.points(p).first().copied());
let b = cadcraft_geom::Bounds2::from_points(bases.filter(|q| q.x.is_finite() && q.y.is_finite()));
if b.is_empty() {
return b;
}
b.expand((b.width() + b.height()).max(2.0) / 2.0)
}

/// Draw `list` fitted into a box of `size`, or `note` when there is nothing to draw.
pub(crate) fn draw_preview(ui: &mut egui::Ui, list: Option<&DisplayList>, note: &str, size: egui::Vec2) {
let t = Tokens::get();
let (rect, _) = ui.allocate_exact_size(vec2(220.0, 170.0), egui::Sense::hover());
let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
let p = ui.painter_at(rect);
p.rect_filled(rect, 4.0, t.canvas);
p.rect_stroke(rect, 4.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
match list.filter(|l| !l.bounds.is_empty() && !l.prims.is_empty()) {
Some(l) => {
let b = l.bounds;
let inner = rect.shrink(12.0);
let inner = rect.shrink(12.0_f32.min(size.min_elem() / 10.0));
let (w, h) = (b.width().max(1e-9), b.height().max(1e-9));
let scale = (f64::from(inner.width()) / w).min(f64::from(inner.height()) / h);
let xf = Xf { rect, center: Vec2::new((b.min.x + b.max.x) / 2.0, (b.min.y + b.max.y) / 2.0), scale, twist: 0.0 };
Expand Down Expand Up @@ -214,7 +235,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
} else {
String::new()
};
draw_preview(ui, list.as_deref(), &note);
draw_preview(ui, list.as_deref(), &note, vec2(220.0, 170.0));
ui.add_space(4.0);
ui.label(RichText::new(crate::tl!("Description")).color(t.text_dim));
let text = if description.is_empty() { "—".to_string() } else { description.clone() };
Expand Down
138 changes: 132 additions & 6 deletions crates/ui-egui/src/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
//! Layer Properties Manager ([`crate::layers`]), Quick Select ([`crate::quick`]), Parameters
//! Manager ([`crate::parametric`]) and the style and settings managers ([`crate::managers`]).

use std::collections::HashMap;
use std::sync::Arc;

use cadcraft_render::DisplayList;
use egui::{RichText, vec2};
use serde_json::json;

Expand Down Expand Up @@ -399,20 +403,83 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
}

/// The Blocks window's previews, for one drawing revision.
#[derive(Default)]
pub struct BlockPreviews {
/// (drawing uid, revision) the previews were built for.
key: Option<(u64, u64)>,
/// Previews by upper-cased block name.
lists: HashMap<String, Arc<DisplayList>>,
}

/// Thumbnail size in the Blocks window.
const THUMB: egui::Vec2 = vec2(64.0, 48.0);

/// The preview of block `name`, built at most once per drawing revision; `None` when the drawing
/// has no such block.
fn block_preview(app: &mut CadApp, name: &str) -> Option<Arc<DisplayList>> {
let st = app.session.state().ok()?;
let key = (st.uid, st.revision);
let cache = &mut app.block_previews;
if cache.key != Some(key) {
cache.key = Some(key);
cache.lists.clear();
}
let upper = name.to_ascii_uppercase();
if let Some(list) = cache.lists.get(&upper) {
return Some(list.clone());
}
let list = Arc::new(crate::bedit::build_preview(&st.doc, name, f64::from(THUMB.x))?);
cache.lists.insert(upper, list.clone());
Some(list)
}

/// Whether block `name`'s preview is already built for the current drawing revision.
fn block_preview_ready(app: &CadApp, name: &str) -> bool {
let Ok(st) = app.session.state() else { return false };
app.block_previews.key == Some((st.uid, st.revision)) && app.block_previews.lists.contains_key(&name.to_ascii_uppercase())
}

/// One row of the Blocks window: block `name`'s thumbnail (`list`; `None` while not built yet)
/// and its name. The whole row, to the window's edge, is a button named after the block.
fn block_row(ui: &mut egui::Ui, list: Option<&DisplayList>, name: &str) -> egui::Response {
let note = if list.is_some() { crate::tl!("Empty") } else { "" };
let row = ui
.horizontal(|ui| {
crate::bedit::draw_preview(ui, list, note, THUMB);
ui.label(name);
ui.allocate_space(vec2(ui.available_width(), 0.0));
})
.response
.interact(egui::Sense::click());
row.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, row.enabled(), name));
row.on_hover_text(crate::tl!("Insert this block"))
}

/// Blocks window listing named (non-anonymous) blocks; clicking one starts INSERT with that block name already supplied.
fn blocks(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let mut pick = None;
let names: Vec<String> = app.session.doc().map(|d| d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect()).unwrap_or_default();
egui::Window::new(crate::tl!("Blocks")).id(egui::Id::unique("Blocks")).open(open).default_size(vec2(320.0, 360.0)).show(ctx, |ui| {
let Ok(d) = app.session.doc() else { return };
let names: Vec<&String> = d.blocks.keys().filter(|k| !k.starts_with('*')).collect();
if names.is_empty() {
ui.label(crate::tl!("No blocks defined in this drawing."));
}
for n in names {
if ui.button(n).on_hover_text(crate::tl!("Insert this block")).clicked() {
pick = Some(n.clone());
// Only the rows in view are laid out, and at most one preview is built per frame, so a
// large library opens at once.
egui::ScrollArea::vertical().auto_shrink([false, false]).show_rows(ui, THUMB.y, names.len(), |ui, rows| {
let mut build = true;
for n in rows.filter_map(|k| names.get(k)) {
let list = if block_preview_ready(app, n) || std::mem::take(&mut build) {
block_preview(app, n)
} else {
ui.ctx().request_repaint();
None
};
if block_row(ui, list.as_deref(), n).clicked() {
pick = Some(n.clone());
}
}
}
});
});
if let Some(n) = pick {
insert_block(app, &n);
Expand Down Expand Up @@ -501,4 +568,63 @@ mod tests {
assert!(app.session.running.as_ref().is_some_and(|r| r.id == "insert"));
assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Enter block name".to_string()));
}

#[test]
fn block_previews_are_built_once_per_revision() {
let mut app = CadApp::new(Session::new(), Services::default());
let c = app.session.execute("circle", &json!({"center": [10, 20], "radius": 5})).unwrap();
let h = c["handle"].as_str().unwrap().to_string();
app.session.execute("block", &json!({"name": "Door 2", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap();

let first = super::block_preview(&mut app, "Door 2").expect("a preview");
assert!(!first.prims.is_empty());
let b = first.bounds;
assert!((b.min.x - 5.0).abs() < 0.1 && (b.max.x - 15.0).abs() < 0.1, "{b:?}");
assert!((b.min.y - 15.0).abs() < 0.1 && (b.max.y - 25.0).abs() < 0.1, "{b:?}");
assert!(super::block_preview_ready(&app, "door 2"));

let again = super::block_preview(&mut app, "Door 2").unwrap();
assert!(std::sync::Arc::ptr_eq(&first, &again));

app.session.execute("line", &json!({"points": [[0, 0], [1, 1]]})).unwrap();
assert!(!super::block_preview_ready(&app, "Door 2"));
let after = super::block_preview(&mut app, "Door 2").unwrap();
assert!(!std::sync::Arc::ptr_eq(&first, &after));

assert!(super::block_preview(&mut app, "Nope").is_none());
}

#[test]
fn a_block_of_rays_and_construction_lines_is_framed_on_their_base_points() {
let mut app = CadApp::new(Session::new(), Services::default());
let r = app.session.execute("ray", &json!({"base": [10, 20], "through": [11, 20]})).unwrap();
let x = app.session.execute("xline", &json!({"base": [30, 40], "ver": true})).unwrap();
let hs = [r["handle"].as_str().unwrap().to_string(), x["handle"].as_str().unwrap().to_string()];
app.session.execute("block", &json!({"name": "Guides", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap();

let list = super::block_preview(&mut app, "Guides").expect("a preview");
assert_eq!(list.prims.len(), 2);
let b = list.bounds;
assert!(!b.is_empty());
for q in [Vec2::new(10.0, 20.0), Vec2::new(30.0, 40.0)] {
assert!(b.contains(q), "{q:?} in {b:?}");
}
assert!(b.width() > 20.0 && b.height() > 20.0, "{b:?}");
}

#[test]
fn a_block_row_spans_the_window_width() {
let ctx = egui::Context::default();
let mut widths = None;
let mut out = ctx.run_ui(
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0))), ..Default::default() },
|ui| {
let row = super::block_row(ui, None, "Door");
widths = Some((row.rect.width(), ui.max_rect().width()));
},
);
out.textures_delta.clear();
let (row, available) = widths.expect("the frame ran");
assert!((row - available).abs() < 1.0, "row {row} of {available}");
}
}
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/ar.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1239,6 +1239,7 @@ menu View عرض
Check for Updates… التحقق من وجود تحديثات…
CADCraft is up to date. CADCraft محدّث.
Could not check for updates. تعذّر التحقق من وجود تحديثات.
Empty فارغ
Add to Working Set إضافة إلى مجموعة العمل
Add: Pick points إضافة: انتقاء نقاط
Add: Select objects إضافة: تحديد كائنات
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/cs.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1220,6 +1220,7 @@ menu Modify Modifikace
Search for pattern Hledat vzor
Not a number or distance: {text} Není číslo ani vzdálenost: {text}
Query Texts Dotaz na texty
Empty Prázdný
Analyze Shapes Analyzovat tvary
Check for Updates… Zkontrolovat aktualizace…
CADCraft is up to date. CADCraft je aktuální.
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/de.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,7 @@
Check for Updates… Nach Updates suchen…
CADCraft is up to date. CADCraft ist auf dem neuesten Stand.
Could not check for updates. Die Suche nach Updates ist fehlgeschlagen.
Empty Leer
Find All Find All
Find what: Find what:
Match case Match case
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/es.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,7 @@
Search for pattern Buscar patrón
Not a number or distance: {text} No es un número ni una distancia: {text}
Query Texts Consultar textos
Empty Vacío
Analyze Shapes Analizar formas
Check for Updates… Buscar actualizaciones…
CADCraft is up to date. CADCraft está actualizado.
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/fr.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,7 @@
Search for pattern Rechercher un motif
Not a number or distance: {text} Ni un nombre ni une distance : {text}
Query Texts Interroger les textes
Empty Vide
Analyze Shapes Analyser les formes
Check for Updates… Rechercher des mises à jour…
CADCraft is up to date. CADCraft est à jour.
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/it.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,7 @@ menu Modify Edita
Search for pattern Cerca modello
Run Script... Esegui script...
Select closed objects (regions, closed polylines, circles). Selezionare oggetti chiusi (regioni, polilinee chiuse, cerchi).
Empty Vuoto
Type an alias name. Digitare un nome di alias.
Choose the command the alias starts. Scegliere il comando che l'alias avvia.
{command} is an unknown command. {command} è un comando sconosciuto.
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/ko.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,7 @@ menu Modify 수정
Check for Updates… 업데이트 확인…
CADCraft is up to date. CADCraft가 최신 버전입니다.
Could not check for updates. 업데이트를 확인하지 못했습니다.
Empty 비어 있음
Find All Find All
Find what: Find what:
Match case Match case
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/pt_br.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,7 @@
Analyze Shapes Analisar formas
Run Script... Executar script...
Not a number or distance: {text} Não é um número nem uma distância: {text}
Empty Vazio
Select using two clicks only Selecionar apenas com dois cliques
Define each corner of the selection window with a separate click. Defina cada canto da janela de seleção com um clique separado.
Check for Updates… Verificar atualizações…
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/ru.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,7 @@
Sheet Books to PDF... Книги листов в PDF...
Not a number or distance: {text} Не число и не расстояние: {text}
Query Texts Запрос текстов
Empty Пустой
Analyze Shapes Анализ фигур
Check for Updates… Проверить обновления…
CADCraft is up to date. У вас последняя версия CADCraft.
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/sv.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,7 @@ menu View Visa
menu Draw Rita
menu Dimension Måttsättning
menu Modify Ändra
Empty Tom

# Strings added upstream after the first Swedish catalog (Ukrainian reference order, then menus).
Hatch and Gradient Skraffering och gradient
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/uk.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,7 @@
This drawing Це креслення
contains authoring elements. Open in Block Editor? містить елементи розробки. Відкрити в редакторі блоків?
New block Новий блок
Empty Порожній
Italic Курсив
Underline Підкреслений
Overline Надкреслений
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/i18n/zh.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,7 @@
Polar angle measurement 极轴角测量
Relative to last segment 相对于上一线段
Show command prompting near the crosshairs 在光标附近显示命令提示
Empty 空
Open Recent 打开最近的图形
Sheet Books to PDF... 图纸册转 PDF...
Drawing Recovery Manager... 图形恢复管理器...
Expand Down
3 changes: 3 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,8 @@ pub struct CadApp {
pub hatch_dlg: Option<hatchdlg::HatchDlgState>,
/// The Edit Block Definition dialog ([`bedit`]).
pub bedit: bedit::State,
/// The Blocks window's previews.
pub block_previews: dialogs::BlockPreviews,
/// A file dialog shown with [`Services::start_pick`]: its answer, and what to do with it.
pending_pick: Option<PendingPick>,
/// The startup update check and its prompt (desktop; [`updates_ui`]).
Expand Down Expand Up @@ -425,6 +427,7 @@ impl CadApp {
alias_dlg: None,
hatch_dlg: None,
bedit: bedit::State::default(),
block_previews: dialogs::BlockPreviews::default(),
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime::default(),
pending_pick: None,
Expand Down
Loading