web: raster images, WBLOCK/SAVEALL/SCRIPT/CTB/LAYTRANS/INSERT, filled TTF text

A fresh web-vs-desktop audit found the remaining gaps; this closes the
top ten.

Raster images: IMAGE attach read the picked file via image::open on a
name-only path (dead on wasm), and raster references inside opened
drawings decoded the same way. Picked bytes are now registered in a
name-keyed store (the PDF-underlay pattern), decoding runs from memory,
and dropped .png/.jpg/.bmp/.tif files register by name so unresolved
references in opened drawings re-resolve and render (and export to PDF).

Command gaps fixed with the bytes-at-pick / download_bytes pattern:
- WBLOCK now downloads the extracted block instead of failing on fs.
- SAVEALL saves every dirty tab instead of printing a no-op message.
- SCRIPT picks and reads the .scr file through the browser picker.
- CENTERLTYPEFILE picks the .lin/.dnl file and populates from text.
- Custom .ctb tables picked on web now parse, register for the
  session, appear in the plot dialog list, and apply (load_named
  previously returned builtin-only on wasm).
- LAYTRANS 'Load standards file' parses the picked drawing on the
  existing web worker.
- INSERT 'from file' in the block palette parses picked bytes and
  feeds the shared import path.

Text fidelity: TTF-named styles rendered as thin stroke glyphs on web
because the font database was empty. Fetched Noto faces are now
registered into it with a family alias table (Arial, Times New Roman,
Cambria, ... -> Noto Sans/Serif), so those styles render filled, shape,
export to PDF as vector fills, and appear in the style picker.
ViewCube labels request semibold again on web.

docs/native-vs-web.md: the hatch and font rows were stale (both work on
web now), the GPU row claimed WebGPU is used where available (the
backend is pinned to OpenGL), and the parallelism row missed the parse
worker — all corrected.

(cherry picked from commit c643a10e)

Ported onto main (#1717 review): conflicts resolved toward main — the
font-file lookup, PDF searchable text, purge service, block palette and
plot-style copy stay as they are on main; the web pieces (font registry
and aliases, session plot styles, SCRIPT/SAVEALL/CENTERLTYPEFILE picks,
block-from-file on the web) are layered on top.
This commit is contained in:
Afonsop authored and Hakan Seven committed 2026-10-12 12:02:04 +03:00
1 parent 69fa7cae4f
commit 9cd898a17a
42 files changed
+1315 -155

No files matched your search

+126 -17
View File
@@ -232,6 +232,42 @@ pub async fn pick_layer_mapping_path(save: bool) -> Option<PathBuf> {
Some(crate::sys::handle_path(&handle))
}
/// Web SCRIPT: pick the .scr file through the browser and read its text —
/// the byte-level stand-in for the typed path the native command reads with
/// `std::fs::read_to_string`. `None` means the user cancelled.
#[cfg(target_arch = "wasm32")]
pub async fn pick_script_web() -> Option<(String, String)> {
let Some(handle) = crate::sys::file_dialog()
.set_title(crate::t!("SCRIPT path to the .scr file:").as_ref())
.add_filter(crate::t!("All Files").as_ref(), &["*"])
.pick_file()
.await
else {
return None;
};
let name = handle.file_name();
let bytes = handle.read().await;
Some((name, String::from_utf8_lossy(&bytes).into_owned()))
}
/// Web CENTERLTYPEFILE: pick the linetype (.lin/.dnl) file through the
/// browser and read its text — the stand-in for the typed path the native
/// command reads inside `set_centerline_setting`. `None` = cancelled.
#[cfg(target_arch = "wasm32")]
pub async fn pick_linetype_file_web() -> Option<(String, String)> {
let Some(handle) = crate::sys::file_dialog()
.set_title(crate::t!("Load linetype file").as_ref())
.add_filter(crate::t!("All Files").as_ref(), &["*"])
.pick_file()
.await
else {
return None;
};
let name = handle.file_name();
let bytes = handle.read().await;
Some((name, String::from_utf8_lossy(&bytes).into_owned()))
}
/// Load a CAD file from a known path. Parsing and cache building run on a
/// dedicated OS thread so the async executor stays free for rendering during
/// the load. Writes phase markers into `phase` so the UI can show
@@ -734,6 +770,50 @@ async fn load_web_bytes(
Ok((name.to_string(), path, doc, caches))
}
/// Web: parse a *second* drawing (a block to insert, a layer-standards
/// file) from bytes on the parse worker, with the same post-parse fixups
/// `load_web_bytes` applies — the byte-level counterpart of `load_file`.
#[cfg(target_arch = "wasm32")]
async fn parse_web_document(name: &str, bytes: &[u8]) -> Result<CadDocument, String> {
let (outcome, _) = web_worker::parse_document(name, bytes, false, "")
.await
.map_err(|error| error.message)?;
let mut doc = outcome.document;
normalize_block_origins(&mut doc);
if name.to_ascii_lowercase().ends_with(".dxf") {
fix_dxf_dimension_rotations(&mut doc);
fix_dxf_layout_plot_settings(&mut doc);
}
fix_viewport_status_flags(&mut doc);
fix_current_style_names(&mut doc);
Ok(doc)
}
/// Web: show the browser picker, read the chosen file's bytes, and parse it
/// as a drawing on the worker — `pick_and_load_web`'s pick-read-parse core
/// for features that consume a second drawing instead of opening a tab.
/// `Ok(None)` means the user cancelled.
#[cfg(target_arch = "wasm32")]
pub async fn pick_and_parse_web(
title: &str,
filter_label: &str,
extensions: &[&str],
) -> Result<Option<(String, CadDocument)>, String> {
let Some(handle) = crate::sys::file_dialog()
.set_title(title)
.add_filter(filter_label, extensions)
.add_filter(crate::t!("All Files").as_ref(), &["*"])
.pick_file()
.await
else {
return Ok(None);
};
let name = handle.file_name();
let bytes = handle.read().await;
let document = parse_web_document(&name, &bytes).await?;
Ok(Some((name, document)))
}
/// Parse a drawing from bytes using its name or recovery-file signature.
#[cfg(not(target_arch = "wasm32"))]
pub fn load_bytes(name: &str, bytes: Vec<u8>) -> Result<CadDocument, String> {
@@ -1766,29 +1846,51 @@ pub async fn pick_plot_style() -> Result<Option<plot_style::PlotStyleTable>, Str
let Some(handle) = dialog.pick_file().await else {
return Ok(None);
};
let path = crate::sys::handle_path(&handle);
let table = plot_style::PlotStyleTable::load(&path)?;
#[cfg(not(target_arch = "wasm32"))]
if let (Ok(dir), Some(file_name)) = (plot_style::ensure_plot_styles_dir(), path.file_name()) {
let destination = dir.join(file_name);
let same_place = path.parent().is_some_and(|parent| {
parent
.canonicalize()
.ok()
.zip(dir.canonicalize().ok())
.is_some_and(|(a, b)| a == b)
});
if !same_place && !destination.exists() {
let _ = std::fs::copy(&path, &destination);
{
let path = crate::sys::handle_path(&handle);
let table = plot_style::PlotStyleTable::load(&path)?;
if let (Ok(dir), Some(file_name)) =
(plot_style::ensure_plot_styles_dir(), path.file_name())
{
let destination = dir.join(file_name);
let same_place = path.parent().is_some_and(|parent| {
parent
.canonicalize()
.ok()
.zip(dir.canonicalize().ok())
.is_some_and(|(a, b)| a == b)
});
if !same_place && !destination.exists() {
let _ = std::fs::copy(&path, &destination);
}
}
Ok(Some(table))
}
// Web: read the picked file's bytes now — the name-only path has nothing
// behind it — parse them, and remember them in the session registry so
// `load_named` resolves the name afterwards. There is no plot-styles
// folder on the web, so registration lasts for the session.
#[cfg(target_arch = "wasm32")]
{
let name = handle.file_name();
let bytes: std::sync::Arc<Vec<u8>> = std::sync::Arc::new(handle.read().await);
let table = plot_style::PlotStyleTable::from_bytes(&name, &bytes)?;
plot_style::register_session_table(&name, bytes);
Ok(Some(table))
}
Ok(Some(table))
}
// ── Image file picker ─────────────────────────────────────────────────────
/// Show a file-open dialog for raster images and decode the selected file.
/// Returns `(path, pixel_width, pixel_height)` or an error string.
///
/// The bytes are read through the dialog handle and registered against the
/// returned path (name-only on the web — there is no filesystem behind it),
/// mirroring the PDF-underlay pick. Decoding then comes from those bytes, and
/// the entity the IMAGE command commits resolves through the same registry
/// instead of a `image::open` on a path that only exists natively.
pub async fn pick_image_file() -> Result<(PathBuf, u32, u32), String> {
let handle = crate::sys::file_dialog()
.set_title(crate::t!("Select Image File").as_ref())
@@ -1803,9 +1905,16 @@ pub async fn pick_image_file() -> Result<(PathBuf, u32, u32), String> {
.await
.ok_or_else(|| "Cancelled".to_string())?;
let path = crate::sys::handle_path(&handle);
let img = image::open(&path).map_err(|e| e.to_string())?;
let (w, h) = image::GenericImageView::dimensions(&img);
Ok((path, w, h))
let bytes = std::sync::Arc::new(handle.read().await);
let reference = path.to_string_lossy().into_owned();
let short = std::path::Path::new(&reference)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| reference.clone());
crate::scene::model::image_model::register_source(&reference, bytes);
let decoded = crate::scene::model::image_model::resolve_image(&reference)
.ok_or_else(|| format!("Unsupported or corrupt image \"{short}\""))?;
Ok((path, decoded.width, decoded.height))
}
/// Pick an image file and prepare it for embedding (IMAGEEMBED). The bytes