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.
This commit is contained in:
Afonsop committed 2026-09-17 20:59:58 +01:00
1 parent fa7ef87f00
commit c643a10ed9
43 files changed
+3216 -1336

No files matched your search

+162 -81
View File
@@ -10,8 +10,9 @@ impl OpenCADStudio {
// Tabs without a path (never saved) are skipped with a note.
"SAVEALL" => {
if self.read_only {
self.command_line
.push_error(crate::t!("Read-only session (--read-only): saving is disabled.").as_ref());
self.command_line.push_error(
crate::t!("Read-only session (--read-only): saving is disabled.").as_ref(),
);
return Some(Task::none());
}
#[cfg(not(target_arch = "wasm32"))]
@@ -23,47 +24,47 @@ impl OpenCADStudio {
continue;
}
if let Some(path) = self.tabs[t].current_path.clone() {
if self
.active_save_jobs
.contains_key(&self.tabs[t].id)
{
self.command_line.push_info(crate::tf!(
"SAVEALL: {} already has a save running",
path.display()
).as_ref());
if self.active_save_jobs.contains_key(&self.tabs[t].id) {
self.command_line.push_info(
crate::tf!(
"SAVEALL: {} already has a save running",
path.display()
)
.as_ref(),
);
skipped += 1;
continue;
}
match self.save_tab_synchronously_protected(
t,
path.clone(),
false,
) {
match self.save_tab_synchronously_protected(t, path.clone(), false) {
Ok(()) => {
saved += 1;
}
Err(e) => self.command_line.push_error(crate::tf!(
"SAVEALL: {} failed: {e}",
path.display()
).as_ref()),
Err(e) => self.command_line.push_error(
crate::tf!("SAVEALL: {} failed: {e}", path.display()).as_ref(),
),
}
} else {
skipped += 1;
}
}
self.command_line.push_output(crate::tf!(
"SAVEALL: saved {saved} drawing(s){}.",
if skipped > 0 {
crate::tf!("; {skipped} need SAVEAS (no file path yet)").into_owned()
} else {
String::new()
}
).as_ref());
self.command_line.push_output(
crate::tf!(
"SAVEALL: saved {saved} drawing(s){}.",
if skipped > 0 {
crate::tf!("; {skipped} need SAVEAS (no file path yet)")
.into_owned()
} else {
String::new()
}
)
.as_ref(),
);
}
#[cfg(target_arch = "wasm32")]
{
self.command_line
.push_info(crate::t!("SAVEALL: save each tab individually in the web build.").as_ref());
// Web: every dirty saved tab is serialized and downloaded
// in one pass — see `saveall_web` for the flow.
self.saveall_web();
}
return Some(Task::none());
}
@@ -87,7 +88,8 @@ impl OpenCADStudio {
// without undoing any work done since.
"OOPS" => {
if self.oops_cache.is_empty() {
self.command_line.push_info(crate::t!("OOPS: nothing to restore.").as_ref());
self.command_line
.push_info(crate::t!("OOPS: nothing to restore.").as_ref());
} else {
let restored = std::mem::take(&mut self.oops_cache);
let pending = self.begin_undo(i, "OOPS", restored.len(), true);
@@ -181,7 +183,11 @@ impl OpenCADStudio {
}
for d in deps {
let dp = PathBuf::from(&d);
let resolved = if dp.is_absolute() { dp } else { parent.join(&dp) };
let resolved = if dp.is_absolute() {
dp
} else {
parent.join(&dp)
};
if resolved.exists() {
if let Some(fname) = resolved.file_name() {
if std::fs::copy(&resolved, folder.join(fname)).is_ok() {
@@ -190,18 +196,23 @@ impl OpenCADStudio {
}
}
}
self.command_line.push_output(crate::tf!(
"{cmd}: packaged {copied} file(s) into {}",
folder.display()
).as_ref());
self.command_line.push_output(
crate::tf!(
"{cmd}: packaged {copied} file(s) into {}",
folder.display()
)
.as_ref(),
);
}
Err(e) => self
.command_line
.push_error(crate::tf!("{cmd}: cannot create folder ({e}).").as_ref()),
}
} else {
self.command_line
.push_error(crate::t!("ARCHIVE: save the drawing first (it has no file path yet).").as_ref());
self.command_line.push_error(
crate::t!("ARCHIVE: save the drawing first (it has no file path yet).")
.as_ref(),
);
}
}
@@ -220,11 +231,14 @@ impl OpenCADStudio {
"PERF" => {
self.perf_hud = !self.perf_hud;
crate::perf::set_ui_enabled(self.perf_hud);
self.command_line.push_info(crate::t!(if self.perf_hud {
"PERF panel on — tracing render and interaction costs"
} else {
"PERF panel off"
}).as_ref());
self.command_line.push_info(
crate::t!(if self.perf_hud {
"PERF panel on — tracing render and interaction costs"
} else {
"PERF panel off"
})
.as_ref(),
);
return Some(Task::none());
}
@@ -256,14 +270,16 @@ impl OpenCADStudio {
self.model_space.mode = crate::app::config::ModelSpaceMode::MatchTheme;
self.sync_model_space_theme(true);
self.persist_settings_if_changed();
self.command_line
.push_output(crate::t!("Model space background set to Match Theme.").as_ref());
self.command_line.push_output(
crate::t!("Model space background set to Match Theme.").as_ref(),
);
} else if first_arg == "CLASSIC" {
self.model_space.mode = crate::app::config::ModelSpaceMode::ClassicDark;
self.sync_model_space_theme(true);
self.persist_settings_if_changed();
self.command_line
.push_output(crate::t!("Model space background set to Classic CAD Dark.").as_ref());
self.command_line.push_output(
crate::t!("Model space background set to Classic CAD Dark.").as_ref(),
);
} else if first_arg == "DEFAULT" || first_arg == "RESET" {
if is_paper {
self.model_space.custom_paper_bg = None;
@@ -279,31 +295,48 @@ impl OpenCADStudio {
.push_output(crate::t!("Background reset to default.").as_ref());
} else if first_arg == "DESK" {
let sub_args = &args[1..];
let sub_first = sub_args.first().map(|s| s.to_uppercase()).unwrap_or_default();
let sub_first = sub_args
.first()
.map(|s| s.to_uppercase())
.unwrap_or_default();
if sub_first == "DEFAULT" || sub_first == "RESET" {
self.model_space.custom_desk_bg = None;
self.sync_model_space_theme(false);
self.persist_settings_if_changed();
self.command_line
.push_output(crate::t!("Paper desk surround background reset to default.").as_ref());
self.command_line.push_output(
crate::t!("Paper desk surround background reset to default.").as_ref(),
);
} else if let Some(rgba) = parse_background_color(sub_args) {
let [r, g, b, _] = rgba;
let rgb = [(r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8];
let rgb = [
(r * 255.0).round() as u8,
(g * 255.0).round() as u8,
(b * 255.0).round() as u8,
];
self.model_space.custom_desk_bg = Some(rgb);
self.sync_model_space_theme(false);
self.persist_settings_if_changed();
self.command_line.push_output(crate::tf!(
"Desk surround background: rgb({}, {}, {})",
rgb[0],
rgb[1],
rgb[2]
).as_ref());
self.command_line.push_output(
crate::tf!(
"Desk surround background: rgb({}, {}, {})",
rgb[0],
rgb[1],
rgb[2]
)
.as_ref(),
);
} else {
self.command_line.push_info(crate::t!("Usage: BACKGROUND DESK <r> <g> <b> | DEFAULT").as_ref());
self.command_line.push_info(
crate::t!("Usage: BACKGROUND DESK <r> <g> <b> | DEFAULT").as_ref(),
);
}
} else if let Some(rgba) = parse_background_color(&args) {
let [r, g, b, _] = rgba;
let rgb = [(r * 255.0).round() as u8, (g * 255.0).round() as u8, (b * 255.0).round() as u8];
let rgb = [
(r * 255.0).round() as u8,
(g * 255.0).round() as u8,
(b * 255.0).round() as u8,
];
if is_paper {
self.model_space.custom_paper_bg = Some(rgb);
self.paper_bg_input = crate::app::config::rgb_to_hex(rgb);
@@ -314,12 +347,9 @@ impl OpenCADStudio {
}
self.sync_model_space_theme(true);
self.persist_settings_if_changed();
self.command_line.push_output(crate::tf!(
"Background: rgb({}, {}, {})",
rgb[0],
rgb[1],
rgb[2]
).as_ref());
self.command_line.push_output(
crate::tf!("Background: rgb({}, {}, {})", rgb[0], rgb[1], rgb[2]).as_ref(),
);
} else {
self.command_line.push_info(
crate::t!("Usage: BACKGROUND <r> <g> <b> (0–255) | THEME|CLASSIC|DEFAULT|DESK|BLACK|DARKGRAY|GRAY|LIGHTGRAY|WHITE").as_ref(),
@@ -347,25 +377,29 @@ impl OpenCADStudio {
cmd if cmd.starts_with("SCRIPT ") || cmd.starts_with("SCR ") => {
let path = cmd.split_once(' ').map(|(_, r)| r.trim().to_string());
match path {
Some(p) if !p.is_empty() => match std::fs::read_to_string(&p) {
Ok(text) => {
let cmds: Vec<Task<Message>> = text
.lines()
.map(str::trim)
.filter(|l| !l.starts_with('#') && !l.starts_with(';'))
.map(|l| Task::done(Message::ScriptLine(l.to_string())))
.collect();
self.command_line.push_output(crate::tf!(
"SCRIPT: running {} command(s) from {p}.",
cmds.len()
).as_ref());
return Some(Task::batch(cmds));
Some(p) if !p.is_empty() => {
#[cfg(not(target_arch = "wasm32"))]
match std::fs::read_to_string(&p) {
Ok(text) => return Some(self.run_script(&p, &text)),
Err(e) => {
self.command_line.push_error(
crate::tf!("SCRIPT: cannot read {p}: {e}").as_ref(),
);
}
}
Err(e) => {
self.command_line
.push_error(crate::tf!("SCRIPT: cannot read {p}: {e}").as_ref());
// Web: nothing is behind a typed path — pick the
// script through the browser and read its bytes at
// pick time (the `pick_and_load_web` pattern); the
// picked text is fed to the same runner.
#[cfg(target_arch = "wasm32")]
{
let _ = &p;
return Some(Task::perform(
crate::io::pick_script_web(),
Message::ScriptFilePicked,
));
}
},
}
_ => {
self.command_line
.push_info(crate::t!("Usage: SCRIPT <path to .scr file>").as_ref());
@@ -377,6 +411,53 @@ impl OpenCADStudio {
}
Some(self.finish_dispatch(cmd))
}
/// Announce a script and feed its rows to the same runner the `--script`
/// startup flag uses — shared by the native `SCRIPT <path>` read and the
/// web picker's `ScriptFilePicked`.
pub(in crate::app) fn run_script(&mut self, path: &str, text: &str) -> Task<Message> {
let p = path;
let cmds: Vec<Task<Message>> = script_command_lines(text)
.into_iter()
.map(|line| Task::done(Message::ScriptLine(line)))
.collect();
self.command_line.push_output(
crate::tf!("SCRIPT: running {} command(s) from {p}.", cmds.len()).as_ref(),
);
Task::batch(cmds)
}
}
/// One runnable row of a `.scr` script: trimmed, comment rows (`#`, `;`)
/// dropped, blank rows kept so they submit Enter to the active command.
fn script_command_lines(text: &str) -> Vec<String> {
text.lines()
.map(str::trim)
.filter(|line| !line.starts_with('#') && !line.starts_with(';'))
.map(str::to_string)
.collect()
}
#[cfg(test)]
mod script_tests {
use super::script_command_lines;
/// Comments drop, every other row survives trimmed, and blank or
/// whitespace-only rows stay as empty strings (Enter presses).
#[test]
fn comments_and_blanks_follow_the_scr_rules() {
let lines =
script_command_lines("# comment\n; also a comment\nLINE 0,0 10,0\n\n \n TRIM \n");
assert_eq!(
lines,
vec![
"LINE 0,0 10,0".to_string(),
String::new(),
String::new(),
"TRIM".to_string(),
]
);
}
}
/// Parse the argument list of the `BACKGROUND` command into an `[r,g,b,a]`
File diff suppressed because it is too large. Load diff
+21
View File
@@ -2191,6 +2191,19 @@ pub enum Message {
LayerTranslatorLoad,
/// A target set was read from `path`.
LayerTranslatorLoaded(std::path::PathBuf),
/// Web: a standards drawing picked and parsed in the browser, with the
/// target layers already extracted — a name-only path has nothing behind
/// it for `load_targets` to read. `Ok(None)` = cancelled.
#[cfg(target_arch = "wasm32")]
LayerTranslatorLoadedWeb(
Result<
Option<(
String,
Vec<crate::modules::draw::layers::laytrans::TargetLayer>,
)>,
String,
>,
),
LayerTranslatorSelectFrom(String),
LayerTranslatorSelectTo(String),
/// Pair the two selected layers.
@@ -2321,6 +2334,14 @@ pub enum Message {
/// dispatch, this accepts an interactive verb and all of its arguments on
/// the same line (`BOX 0,0,0 10,10,0 10`).
ScriptLine(String),
/// Web SCRIPT: the picked .scr file's name and text. `None` = the
/// browser dialog was cancelled.
#[cfg(target_arch = "wasm32")]
ScriptFilePicked(Option<(String, String)>),
/// Web CENTERLTYPEFILE: the picked .lin/.dnl file's name and text.
/// `None` = cancelled.
#[cfg(target_arch = "wasm32")]
CenterlineLinetypeFilePicked(Option<(String, String)>),
/// Append one typed character to the command-line input from the
/// global key-press subscription. Used when the text-input widget
/// itself isn't focused (focus parked on viewport / button / etc.)
+290 -219
View File
@@ -2,26 +2,24 @@
#![allow(unused_imports)]
use super::util::*;
use crate::ui::window::block_palette::BlockPaletteMsg;
use super::{format_size, VIEWCUBE_HIT_SIZE};
use crate::app::helpers::{
parse_coord, polar_constrain_near, ucs_rotate_vec, ucs_to_wcs, ucs_z_axis,
CoordKind,
parse_coord, polar_constrain_near, ucs_rotate_vec, ucs_to_wcs, ucs_z_axis, CoordKind,
};
use crate::app::{Message, OpenCADStudio, POLY_START_DELAY_MS};
use crate::modules::ModuleEvent;
use crate::scene::pick::grip::{find_hit_grip, find_hit_grip_paper, find_hit_grip_rte, GripEdit};
use crate::scene::model::object::GripApply;
use crate::scene::pick::grip::{find_hit_grip, find_hit_grip_paper, find_hit_grip_rte, GripEdit};
use crate::scene::{
self, hover_id, CubeRegion, Scene, VIEWCUBE_DRAW_PX, VIEWCUBE_PAD, VIEWCUBE_PX,
};
use crate::ui::window::block_palette::BlockPaletteMsg;
use crate::ui::PropertiesPanel;
use acadrust::types::Color as AcadColor;
use acadrust::{EntityType as AcadEntityType, Handle};
use iced::time::Instant;
use iced::{mouse, Point, Task};
impl OpenCADStudio {
pub(in crate::app) fn open_save_dialog_window(&mut self, tab_idx: usize) -> Task<Message> {
// Default the format dropdown to the loaded file's own format — its
@@ -65,7 +63,6 @@ impl OpenCADStudio {
Task::none()
}
pub(in crate::app) fn close_save_dialog_window(&mut self) -> Task<Message> {
self.aec_drop_acknowledged = false;
if self.active_modal == Some(crate::app::ModalKind::SaveDialog) {
@@ -75,7 +72,6 @@ impl OpenCADStudio {
Task::none()
}
pub(in crate::app) fn open_unsaved_dialog_window(&mut self) -> Task<Message> {
self.active_modal = Some(crate::app::ModalKind::Unsaved);
// The unsaved-changes prompt renders inside the main window, so bring
@@ -96,7 +92,6 @@ impl OpenCADStudio {
}
}
pub(in crate::app) fn close_unsaved_dialog_window(&mut self) -> Task<Message> {
if self.active_modal == Some(crate::app::ModalKind::Unsaved) {
self.active_modal = None;
@@ -105,158 +100,159 @@ impl OpenCADStudio {
Task::none()
}
pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEvent) -> Task<Message> {
// Commands use `start_allowed`; other events need a drawing
// and stay blocked on the Start page (#299, #388, #389).
if self.tabs[self.active_tab].is_start && !matches!(event, ModuleEvent::Command(_)) {
self.ribbon.close_dropdown();
self.command_line
.push_info(crate::t!("No drawing open — use New or Open first.").as_ref());
return Task::none();
pub(super) fn on_ribbon_tool_click(
&mut self,
tool_id: String,
event: ModuleEvent,
) -> Task<Message> {
// Commands use `start_allowed`; other events need a drawing
// and stay blocked on the Start page (#299, #388, #389).
if self.tabs[self.active_tab].is_start && !matches!(event, ModuleEvent::Command(_)) {
self.ribbon.close_dropdown();
self.command_line
.push_info(crate::t!("No drawing open — use New or Open first.").as_ref());
return Task::none();
}
// Dismiss any open dropdown / collapsed-panel flyout on tool use,
// and remember this tool as its panel's last-used one.
self.ribbon.close_dropdown();
self.ribbon.note_panel_tool(&tool_id);
self.ribbon.activate_tool(&tool_id);
match event {
ModuleEvent::Command(cmd) => {
let task = self.dispatch_command(&cmd);
// One-shot tools (view changes, clipboard, toggles,
// audits…) leave nothing running: no interactive
// command and no dialog. Their highlight would stick
// forever — turn it off now. Interactive commands and
// dialog owners keep theirs; the command end / modal
// close clears those. (#355)
let i = self.active_tab;
if self.tabs[i].active_cmd.is_none()
&& self.active_modal.is_none()
&& !self.tabs[i].pan_mode
&& !self.tabs[i].orbit_mode
&& !self.tabs[i].zoom_dynamic_mode
{
self.ribbon.deactivate_tool();
}
// Dismiss any open dropdown / collapsed-panel flyout on tool use,
// and remember this tool as its panel's last-used one.
self.ribbon.close_dropdown();
self.ribbon.note_panel_tool(&tool_id);
self.ribbon.activate_tool(&tool_id);
match event {
ModuleEvent::Command(cmd) => {
let task = self.dispatch_command(&cmd);
// One-shot tools (view changes, clipboard, toggles,
// audits…) leave nothing running: no interactive
// command and no dialog. Their highlight would stick
// forever — turn it off now. Interactive commands and
// dialog owners keep theirs; the command end / modal
// close clears those. (#355)
let i = self.active_tab;
if self.tabs[i].active_cmd.is_none()
&& self.active_modal.is_none()
&& !self.tabs[i].pan_mode
&& !self.tabs[i].orbit_mode
&& !self.tabs[i].zoom_dynamic_mode
{
self.ribbon.deactivate_tool();
}
return task;
}
ModuleEvent::OpenFileDialog => {
return task;
}
ModuleEvent::OpenFileDialog => {
self.command_line
.push_info(crate::t!("Open DWG/DXF: not yet implemented.").as_ref());
}
ModuleEvent::ClearModels => {
let i = self.active_tab;
self.tabs[i].scene.clear();
self.tabs[i].properties = PropertiesPanel::empty();
self.command_line
.push_output(crate::t!("Scene cleared.").as_ref());
}
ModuleEvent::SetVisualStyle(name) => {
use crate::modules::view::visual_style;
match visual_style::mode_for_keyword(&name) {
Some(mode) => return Task::done(Message::SetRenderMode(mode)),
None => {
// Name the styles that do exist, from the same
// list every other caller reads.
self.command_line
.push_info(crate::t!("Open DWG/DXF: not yet implemented.").as_ref());
}
ModuleEvent::ClearModels => {
let i = self.active_tab;
self.tabs[i].scene.clear();
self.tabs[i].properties = PropertiesPanel::empty();
self.command_line.push_output(crate::t!("Scene cleared.").as_ref());
}
ModuleEvent::SetVisualStyle(name) => {
use crate::modules::view::visual_style;
match visual_style::mode_for_keyword(&name) {
Some(mode) => return Task::done(Message::SetRenderMode(mode)),
None => {
// Name the styles that do exist, from the same
// list every other caller reads.
self.command_line.push_error(
crate::tf!("Unknown visual style \"{name}\".").as_ref(),
);
self.command_line
.push_info(crate::t!(visual_style::keyword_prompt()).as_ref());
}
}
}
ModuleEvent::ToggleLayers => {
return Task::done(Message::ToggleLayers);
}
ModuleEvent::PluginFileDialog {
command,
title,
filter_name,
extensions,
} => {
return Task::perform(
async move {
let exts: Vec<&str> =
extensions.iter().map(|s| s.as_str()).collect();
let path = crate::sys::file_dialog()
.set_title(title)
.add_filter(filter_name, &exts)
.add_filter(crate::t!("All Files").as_ref(), &["*"])
.pick_file()
.await
.map(|h| crate::sys::handle_path(&h));
(command, path)
},
|(command, path)| Message::PluginFileDialogResult { command, path },
);
.push_error(crate::tf!("Unknown visual style \"{name}\".").as_ref());
self.command_line
.push_info(crate::t!(visual_style::keyword_prompt()).as_ref());
}
}
// Every non-Command event above is a one-shot (state toggle,
// clear, dialog spawn) — nothing stays running to clear the
// highlight later, so turn it off here. (#355)
self.ribbon.deactivate_tool();
Task::none()
}
ModuleEvent::ToggleLayers => {
return Task::done(Message::ToggleLayers);
}
ModuleEvent::PluginFileDialog {
command,
title,
filter_name,
extensions,
} => {
return Task::perform(
async move {
let exts: Vec<&str> = extensions.iter().map(|s| s.as_str()).collect();
let path = crate::sys::file_dialog()
.set_title(title)
.add_filter(filter_name, &exts)
.add_filter(crate::t!("All Files").as_ref(), &["*"])
.pick_file()
.await
.map(|h| crate::sys::handle_path(&h));
(command, path)
},
|(command, path)| Message::PluginFileDialogResult { command, path },
);
}
}
// Every non-Command event above is a one-shot (state toggle,
// clear, dialog spawn) — nothing stays running to clear the
// highlight later, so turn it off here. (#355)
self.ribbon.deactivate_tool();
Task::none()
}
pub(super) fn on_unsaved_dialog_discard(&mut self) -> Task<Message> {
match self.pending_close.take() {
Some(crate::app::PendingClose::Tab(idx)) => {
let close_win = self.close_unsaved_dialog_window();
// Discarded — drop this tab's autosave recovery copy.
#[cfg(not(target_arch = "wasm32"))]
let _ = std::fs::remove_file(self.autosave_target(idx));
// Web counterpart: the OPFS snapshot must go too, or
// the drawing the user just declined to save is
// offered back at the next boot. A snapshot round
// still writing this tab's key would resurrect it
// after the remove, so defer to the round's end
// (the same guard the save flow uses).
#[cfg(target_arch = "wasm32")]
{
let key = Self::web_autosave_key(&self.tabs[idx]);
if self.web_autosave_in_flight {
self.web_autosave_clear_after.push(key);
} else {
wasm_bindgen_futures::spawn_local(async move {
let _ = crate::io::web_autosave::remove(&key).await;
});
}
}
if self.tabs.len() == 1 {
self.tab_counter += 1;
self.tabs[0] =
crate::app::document::DocumentTab::new_drawing(self.tab_counter);
self.active_tab = 0;
self.apply_display_defaults(0);
} else {
self.tabs.remove(idx);
if self.active_tab >= self.tabs.len() {
self.active_tab = self.tabs.len() - 1;
}
}
// The active tab is now a fresh blank or a
// different existing tab; sync ribbon chips so
// they don't keep showing the discarded tab's
// last selection. #21.
self.sync_ribbon_layers();
self.sync_ribbon_from_selection();
return Task::batch([close_win, self.continue_tab_close_queue()]);
match self.pending_close.take() {
Some(crate::app::PendingClose::Tab(idx)) => {
let close_win = self.close_unsaved_dialog_window();
// Discarded — drop this tab's autosave recovery copy.
#[cfg(not(target_arch = "wasm32"))]
let _ = std::fs::remove_file(self.autosave_target(idx));
// Web counterpart: the OPFS snapshot must go too, or
// the drawing the user just declined to save is
// offered back at the next boot. A snapshot round
// still writing this tab's key would resurrect it
// after the remove, so defer to the round's end
// (the same guard the save flow uses).
#[cfg(target_arch = "wasm32")]
{
let key = Self::web_autosave_key(&self.tabs[idx]);
if self.web_autosave_in_flight {
self.web_autosave_clear_after.push(key);
} else {
wasm_bindgen_futures::spawn_local(async move {
let _ = crate::io::web_autosave::remove(&key).await;
});
}
Some(crate::app::PendingClose::Quit) => {
if let Some(idx) = self.tabs.iter().position(|t| t.dirty) {
self.tabs[idx].dirty = false;
}
if self.tabs.iter().any(|t| t.dirty) {
// More dirty tabs remain — keep window open.
self.pending_close = Some(crate::app::PendingClose::Quit);
} else {
let close_win = self.close_unsaved_dialog_window();
return Task::batch(vec![close_win, self.exit_app()]);
}
}
None => {}
}
Task::none()
if self.tabs.len() == 1 {
self.tab_counter += 1;
self.tabs[0] = crate::app::document::DocumentTab::new_drawing(self.tab_counter);
self.active_tab = 0;
self.apply_display_defaults(0);
} else {
self.tabs.remove(idx);
if self.active_tab >= self.tabs.len() {
self.active_tab = self.tabs.len() - 1;
}
}
// The active tab is now a fresh blank or a
// different existing tab; sync ribbon chips so
// they don't keep showing the discarded tab's
// last selection. #21.
self.sync_ribbon_layers();
self.sync_ribbon_from_selection();
return Task::batch([close_win, self.continue_tab_close_queue()]);
}
Some(crate::app::PendingClose::Quit) => {
if let Some(idx) = self.tabs.iter().position(|t| t.dirty) {
self.tabs[idx].dirty = false;
}
if self.tabs.iter().any(|t| t.dirty) {
// More dirty tabs remain — keep window open.
self.pending_close = Some(crate::app::PendingClose::Quit);
} else {
let close_win = self.close_unsaved_dialog_window();
return Task::batch(vec![close_win, self.exit_app()]);
}
}
None => {}
}
Task::none()
}
pub(super) fn on_unsaved_dialog_save(&mut self) -> Task<Message> {
@@ -266,16 +262,11 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
return Task::none();
};
let (idx, continuation) = match pending {
crate::app::PendingClose::Tab(idx) => {
(idx, crate::app::SaveContinuation::CloseTab)
}
crate::app::PendingClose::Tab(idx) => (idx, crate::app::SaveContinuation::CloseTab),
crate::app::PendingClose::Quit => {
let Some(idx) = self.tabs.iter().position(|tab| tab.dirty) else {
self.pending_close = None;
return Task::batch([
self.close_unsaved_dialog_window(),
self.exit_app(),
]);
return Task::batch([self.close_unsaved_dialog_window(), self.exit_app()]);
};
(idx, crate::app::SaveContinuation::Quit)
}
@@ -331,10 +322,7 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
let save = self.save_with_default_format(idx);
Task::batch([close, save])
} else {
Task::batch([
self.close_unsaved_dialog_window(),
self.exit_app(),
])
Task::batch([self.close_unsaved_dialog_window(), self.exit_app()])
}
}
None => Task::none(),
@@ -377,6 +365,14 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
self.import_document_as_block(doc, stem)
}
/// A file import defined a new block — announce it and start placing it.
fn block_file_imported(&mut self, name: &str) {
self.command_line
.push_output(&crate::tf!("Inserting \"{name}\" from file."));
self.refresh_block_palette();
self.start_block_placement(name);
}
/// Define one block in the active drawing from a loaded `CadDocument`'s
/// model-space entities (base = the file's model-space insertion base).
fn import_document_as_block(
@@ -409,7 +405,10 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
.iter()
.filter_map(|h| doc.get_entity(*h))
.filter(|e| {
!matches!(e, acadrust::EntityType::Block(_) | acadrust::EntityType::BlockEnd(_))
!matches!(
e,
acadrust::EntityType::Block(_) | acadrust::EntityType::BlockEnd(_)
)
})
.cloned()
.collect()
@@ -422,7 +421,10 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
o == model_br || o.is_null()
})
.filter(|e| {
!matches!(e, acadrust::EntityType::Block(_) | acadrust::EntityType::BlockEnd(_))
!matches!(
e,
acadrust::EntityType::Block(_) | acadrust::EntityType::BlockEnd(_)
)
})
.cloned()
.collect()
@@ -516,7 +518,10 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
Ok(name)
}
pub(super) fn on_block_palette(&mut self, m: crate::ui::window::block_palette::BlockPaletteMsg) -> iced::Task<Message> {
pub(super) fn on_block_palette(
&mut self,
m: crate::ui::window::block_palette::BlockPaletteMsg,
) -> iced::Task<Message> {
use crate::ui::window::block_palette::{BlockEntry, BlockPaletteMsg};
match m {
BlockPaletteMsg::Search(s) => {
@@ -534,35 +539,84 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
self.refresh_block_palette();
iced::Task::none()
}
BlockPaletteMsg::PickFile => iced::Task::perform(
async {
let handle = rfd::AsyncFileDialog::new()
.set_title(crate::t!("Select Drawing to Insert as Block").as_ref())
.add_filter(crate::t!("DWG/DXF Files").as_ref(), &["dwg", "dxf", "DWG", "DXF"])
.pick_file()
.await;
match handle {
Some(h) => Ok(crate::sys::handle_path(&h)),
None => Err("Cancelled".to_string()),
}
},
|r| Message::BlockPalette(BlockPaletteMsg::FilePicked(r)),
),
BlockPaletteMsg::PickFile => {
// Native: pick a path; the file is read in `import_file_as_block`.
#[cfg(not(target_arch = "wasm32"))]
{
iced::Task::perform(
async {
let handle = rfd::AsyncFileDialog::new()
.set_title(crate::t!("Select Drawing to Insert as Block").as_ref())
.add_filter(
crate::t!("DWG/DXF Files").as_ref(),
&["dwg", "dxf", "DWG", "DXF"],
)
.pick_file()
.await;
match handle {
Some(h) => Ok(crate::sys::handle_path(&h)),
None => Err("Cancelled".to_string()),
}
},
|r| Message::BlockPalette(BlockPaletteMsg::FilePicked(r)),
)
}
// Web: read the picked file's bytes and parse them on the
// worker right away — the picker's name-only path has
// nothing behind it for `import_file_as_block` to read.
#[cfg(target_arch = "wasm32")]
{
iced::Task::perform(
async {
crate::io::pick_and_parse_web(
crate::t!("Select Drawing to Insert as Block").as_ref(),
crate::t!("DWG/DXF Files").as_ref(),
&["dwg", "dxf", "DWG", "DXF"],
)
.await
// The native pick reports a cancelled dialog the
// same way.
.and_then(|picked| picked.ok_or_else(|| "Cancelled".to_string()))
},
|r| Message::BlockPalette(BlockPaletteMsg::FilePickedDoc(r)),
)
}
}
BlockPaletteMsg::FilePicked(Ok(path)) => {
match self.import_file_as_block(path) {
Ok(name) => {
self.command_line
.push_output(&crate::tf!("Inserting \"{name}\" from file."));
self.refresh_block_palette();
self.start_block_placement(&name);
}
Ok(name) => self.block_file_imported(&name),
Err(e) if e != "Cancelled" => {
self.command_line.push_error(&crate::tf!("INSERT FILE: {e}"));
self.command_line
.push_error(&crate::tf!("INSERT FILE: {e}"));
}
Err(_) => {}
}
iced::Task::none()
}
// Web: the drawing arrived parsed — define the block from it
// directly (the tail of `import_file_as_block`).
#[cfg(target_arch = "wasm32")]
BlockPaletteMsg::FilePickedDoc(Ok((name, document))) => {
let stem = std::path::Path::new(&name)
.file_stem()
.map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_else(|| "Block".to_string());
match self.import_document_as_block(document, stem) {
Ok(name) => self.block_file_imported(&name),
Err(e) => {
self.command_line
.push_error(&crate::tf!("INSERT FILE: {e}"));
}
}
iced::Task::none()
}
#[cfg(target_arch = "wasm32")]
BlockPaletteMsg::FilePickedDoc(Err(e)) => {
if e != "Cancelled" {
self.command_line.push_error(&e);
}
iced::Task::none()
}
BlockPaletteMsg::FilePicked(Err(e)) => {
if e != "Cancelled" {
self.command_line.push_error(&e);
@@ -653,7 +707,12 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
}
DockMsg::DragMove(point) => {
if self.dock_dragging.is_some() {
let avail = self.tabs[self.active_tab].scene.selection.borrow().vp_size.1;
let avail = self.tabs[self.active_tab]
.scene
.selection
.borrow()
.vp_size
.1;
let side = if point.x < self.win_size.0 * 0.5 {
DockSide::Left
} else {
@@ -817,7 +876,9 @@ mod tests {
fn import_document_as_block_defines_block() {
let mut app = fresh();
let doc = foreign_doc(&app);
let name = app.import_document_as_block(doc, "Fixture".to_string()).unwrap();
let name = app
.import_document_as_block(doc, "Fixture".to_string())
.unwrap();
assert_eq!(name, "Fixture");
assert!(app.tabs[app.active_tab]
.scene
@@ -912,15 +973,14 @@ mod tests {
}
/// The nested-INSERT's block name inside a defined block record.
fn nested_insert_target(
doc: &acadrust::CadDocument,
block: &str,
) -> Option<String> {
fn nested_insert_target(doc: &acadrust::CadDocument, block: &str) -> Option<String> {
let br = doc.block_records.get(block)?;
br.entity_handles.iter().find_map(|h| match doc.get_entity(*h)? {
EntityType::Insert(ins) => Some(ins.block_name.clone()),
_ => None,
})
br.entity_handles
.iter()
.find_map(|h| match doc.get_entity(*h)? {
EntityType::Insert(ins) => Some(ins.block_name.clone()),
_ => None,
})
}
/// A foreign document whose model space INSERTs a `Fixture` block whose
@@ -997,7 +1057,9 @@ mod tests {
)
.unwrap();
let _ = app.import_document_as_block(doc, "Imported".to_string()).unwrap();
let _ = app
.import_document_as_block(doc, "Imported".to_string())
.unwrap();
let doc = &app.tabs[i].scene.document;
// The file's own "Door (2)" is kept intact and targets the file's
// renamed "Door" (now "Door (3)" — "Door (2)" was taken by the source).
@@ -1044,7 +1106,9 @@ mod tests {
)
.unwrap();
let name = app.import_document_as_block(doc, "Imported".to_string()).unwrap();
let name = app
.import_document_as_block(doc, "Imported".to_string())
.unwrap();
assert_eq!(name, "Imported");
let doc = &app.tabs[i].scene.document;
@@ -1075,11 +1139,16 @@ mod tests {
fn blockpalette_refresh_lists_and_places_block() {
let mut app = fresh();
let doc = foreign_doc(&app);
let name = app.import_document_as_block(doc, "Fixture".to_string()).unwrap();
let name = app
.import_document_as_block(doc, "Fixture".to_string())
.unwrap();
app.refresh_block_palette();
assert!(app.block_palette.blocks.iter().any(|b| b.name == "Fixture"));
app.start_block_placement(&name);
let cmd = app.tabs[app.active_tab].active_cmd.as_ref().expect("INSERT running");
let cmd = app.tabs[app.active_tab]
.active_cmd
.as_ref()
.expect("INSERT running");
assert_eq!(cmd.name(), "INSERT");
assert_eq!(app.block_palette.placing.as_deref(), Some("Fixture"));
}
@@ -1135,7 +1204,10 @@ mod tests {
let _ = app.on_dock(crate::ui::dock::DockMsg::AutoCollapseToggle(id));
assert!(app.dock.auto_collapse(id), "pin enables auto-collapse");
let _ = app.on_dock(crate::ui::dock::DockMsg::AutoCollapseToggle(id));
assert!(!app.dock.auto_collapse(id), "second pin disables auto-collapse");
assert!(
!app.dock.auto_collapse(id),
"second pin disables auto-collapse"
);
let _ = app.on_dock(crate::ui::dock::DockMsg::Close(id));
assert!(!app.show_block_palette, "close dismisses the sidebar");
}
@@ -1153,7 +1225,9 @@ mod tests {
);
let _ = app.on_dock(crate::ui::dock::DockMsg::DockGrab(id));
app.win_size = (1600.0, 900.0).into();
let _ = app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(100.0, 100.0)));
let _ = app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(
100.0, 100.0,
)));
assert_eq!(
app.dock_drag_target,
Some((crate::app::config::DockSide::Left, 0))
@@ -1176,22 +1250,13 @@ mod tests {
// Left: block palette hidden, properties shown -> 1 visible panel.
app.show_block_palette = false;
app.show_properties = true;
assert_eq!(
app.dock_visible_len(crate::app::config::DockSide::Left),
1
);
assert_eq!(app.dock_visible_len(crate::app::config::DockSide::Left), 1);
// Reveal the block palette -> both count.
app.show_block_palette = true;
assert_eq!(
app.dock_visible_len(crate::app::config::DockSide::Left),
2
);
assert_eq!(app.dock_visible_len(crate::app::config::DockSide::Left), 2);
// A hidden (closed) panel counts for nothing even when stacked.
app.show_block_palette = false;
assert_eq!(
app.dock_visible_len(crate::app::config::DockSide::Left),
1
);
assert_eq!(app.dock_visible_len(crate::app::config::DockSide::Left), 1);
}
#[test]
@@ -1215,8 +1280,9 @@ mod tests {
let _ = app.on_dock(crate::ui::dock::DockMsg::DockGrab(id));
// Pointer near the bottom of the left edge: one visible panel means a
// single slot, so every y maps to index 0 (no top/bottom split).
let _ =
app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(100.0, 850.0)));
let _ = app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(
100.0, 850.0,
)));
assert_eq!(
app.dock_drag_target,
Some((crate::app::config::DockSide::Left, 0))
@@ -1240,8 +1306,9 @@ mod tests {
app.win_size = (1600.0, 900.0).into();
let id = crate::ui::dock::PanelId::Properties;
let _ = app.on_dock(crate::ui::dock::DockMsg::DockGrab(id));
let _ =
app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(100.0, 850.0)));
let _ = app.on_dock(crate::ui::dock::DockMsg::DragMove(iced::Point::new(
100.0, 850.0,
)));
assert_eq!(
app.dock_drag_target,
Some((crate::app::config::DockSide::Left, 2))
@@ -1266,7 +1333,11 @@ mod tests {
line.end = Vector3::new(1.0, 0.0, 0.0);
app.tabs[i]
.scene
.define_block_from_owned_entities(vec![EntityType::Line(line)], "Chair", glam::DVec3::ZERO)
.define_block_from_owned_entities(
vec![EntityType::Line(line)],
"Chair",
glam::DVec3::ZERO,
)
.unwrap();
assert_eq!(app.block_name_from_file("Chair"), "Chair (2)");
assert_eq!(app.block_name_from_file("Table"), "Table");
+87 -8
View File
@@ -1695,12 +1695,95 @@ impl OpenCADStudio {
crate::modules::insert::wblock::extract_block_to_doc(&document, &worker_name)
}
.map_err(|e| e.to_string())?;
crate::io::save(&document, &worker_path).map_err(|e| e.to_string())
#[cfg(not(target_arch = "wasm32"))]
{
crate::io::save(&document, &worker_path).map_err(|e| e.to_string())
}
// Web: no filesystem behind the name-only path — serialize to
// bytes (the same document version `save` would pick, format
// from the chosen file name) and hand the browser a download,
// the way the other web exports do.
#[cfg(target_arch = "wasm32")]
{
let ext = worker_path
.extension()
.map(|ext| ext.to_string_lossy().into_owned())
.unwrap_or_else(|| "dwg".to_string());
let bytes = crate::io::save_to_bytes(&document, &ext, document.version)?;
let name = worker_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "block.dwg".into());
crate::sys::download_bytes(&name, &bytes);
Ok(())
}
},
move |result| Message::WblockWriteFinished(block_name, path, result),
)
}
/// Web SAVEALL: every dirty tab that already has a name-only path is
/// serialized and downloaded in one pass — the same
/// `save_to_bytes` + `download_bytes` route a single Save takes. The
/// browser may ask once for permission to download several files, which
/// is the platform's price. Clean tabs are skipped (re-downloading
/// identical bytes is noise); tabs with no path still need SAVEAS.
#[cfg(target_arch = "wasm32")]
pub(in crate::app) fn saveall_web(&mut self) {
let mut saved = 0usize;
let mut skipped = 0usize;
for t in 0..self.tabs.len() {
if self.tabs[t].is_start {
continue;
}
let Some(path) = self.tabs[t].current_path.clone() else {
skipped += 1;
continue;
};
if !self.tabs[t].dirty {
continue;
}
// The same preparation a single web Save makes on the tab.
self.sync_view_state_for_save(t);
sync_annotation_scale_header(&mut self.tabs[t].scene);
self.stamp_header_sysvars(t);
self.sync_solid_models_for_save(t);
self.tabs[t].scene.sync_native_parametric_graph();
let ext = path
.extension()
.map(|ext| ext.to_string_lossy().into_owned())
.unwrap_or_else(|| "dwg".to_string());
let version = self.tabs[t].scene.document.version;
let filename = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_string_lossy().into_owned());
match crate::io::save_to_bytes(&self.tabs[t].scene.document, &ext, version) {
Ok(bytes) => {
crate::sys::download_bytes(&filename, &bytes);
self.tabs[t].scene.document.version = version;
self.tabs[t].dirty = false;
self.tabs[t].recovery_save_as_required = false;
saved += 1;
}
Err(error) => self
.command_line
.push_error(crate::tf!("SAVEALL: {} failed: {error}", path.display()).as_ref()),
}
}
self.command_line.push_output(
crate::tf!(
"SAVEALL: saved {saved} drawing(s){}.",
if skipped > 0 {
crate::tf!("; {skipped} need SAVEAS (no file path yet)").into_owned()
} else {
String::new()
}
)
.as_ref(),
);
}
pub(super) fn on_stl_export_path_some(&mut self, path: std::path::PathBuf) -> Task<Message> {
// Re-build STL bytes (we can't easily pass them through the message).
let i = self.active_tab;
@@ -2894,9 +2977,7 @@ impl OpenCADStudio {
/// single derivation every web snapshot/remove site must agree on, or a
/// remove misses the snapshot a round wrote (and vice versa).
#[cfg(target_arch = "wasm32")]
pub(super) fn web_autosave_key(
tab: &crate::app::document::DocumentTab,
) -> String {
pub(super) fn web_autosave_key(tab: &crate::app::document::DocumentTab) -> String {
tab.current_path
.as_ref()
.and_then(|path| path.file_name())
@@ -3140,10 +3221,8 @@ impl OpenCADStudio {
// survives in OPFS and is re-offered on the next boot.
if !crate::io::web_drop::enqueue_restore(open_name, bytes, key) {
self.command_line.push_warning(
crate::tf!(
"Autosave copy could not be queued: too many pending opens"
)
.as_ref(),
crate::tf!("Autosave copy could not be queued: too many pending opens")
.as_ref(),
);
self.queue_next_web_autosave_prompt();
}
+125 -15
View File
@@ -400,6 +400,23 @@ impl OpenCADStudio {
} else {
Task::none()
};
// Dropped raster images register their bytes (name-keyed) and
// re-resolve any RasterImage the open drawings reference but
// couldn't load — the web stand-in for the drawing folder the
// images live beside natively.
let mut registered: Vec<String> = Vec::new();
while let Some((name, bytes)) = crate::io::web_drop::take_dropped_image() {
crate::scene::model::image_model::register_source(
&name,
std::sync::Arc::new(bytes),
);
registered.push(name);
}
if !registered.is_empty() {
for tab in self.tabs.iter_mut() {
tab.scene.resolve_registered_image_names(&registered);
}
}
Task::batch([control, dropped])
}
#[cfg(not(target_arch = "wasm32"))]
@@ -825,13 +842,11 @@ impl OpenCADStudio {
// open's id so cancelling an unrelated open leaves a pending
// restore marker alone.
#[cfg(target_arch = "wasm32")]
if cancelled_id
.is_some_and(|id| {
self.web_autosave_consumed
.as_ref()
.is_some_and(|(_, recorded)| *recorded == id)
})
&& self.web_autosave_consumed.take().is_some()
if cancelled_id.is_some_and(|id| {
self.web_autosave_consumed
.as_ref()
.is_some_and(|(_, recorded)| *recorded == id)
}) && self.web_autosave_consumed.take().is_some()
{
self.queue_next_web_autosave_prompt();
}
@@ -850,9 +865,7 @@ impl OpenCADStudio {
// warning only (the drop path has no user-facing
// surface for rejections by design — see QUEUE_CAP).
let _ = match restore_key {
Some(key) => {
crate::io::web_drop::enqueue_restore(name, bytes, key)
}
Some(key) => crate::io::web_drop::enqueue_restore(name, bytes, key),
None => crate::io::web_drop::enqueue_open(name, bytes),
};
return Task::none();
@@ -957,7 +970,20 @@ impl OpenCADStudio {
if self.opening.as_ref().map(|opening| opening.id) != Some(open_id) {
return Task::none();
}
self.on_file_opened(name, path, doc, caches)
let task = self.on_file_opened(name, path, doc, caches);
// Web: raster files dropped while this open was in flight
// registered after its caches were built — re-resolve any
// image the (possibly new) drawing references by name.
#[cfg(target_arch = "wasm32")]
{
let names = crate::scene::model::image_model::registered_image_names();
if !names.is_empty() {
for tab in self.tabs.iter_mut() {
tab.scene.resolve_registered_image_names(&names);
}
}
}
task
}
Message::FileOpened(open_id, Err(e)) => {
@@ -2299,6 +2325,39 @@ impl OpenCADStudio {
}
}
// Web SCRIPT: the picked .scr file arrived — run it through the
// same runner the native path feeds.
#[cfg(target_arch = "wasm32")]
Message::ScriptFilePicked(Some((name, text))) => self.run_script(&name, &text),
#[cfg(target_arch = "wasm32")]
Message::ScriptFilePicked(None) => Task::none(),
// Web CENTERLTYPEFILE: the picked .lin/.dnl file's text arrived —
// load its linetypes, then record the setting under the file's
// name (the native command reads the typed path inside
// `set_centerline_setting` instead).
#[cfg(target_arch = "wasm32")]
Message::CenterlineLinetypeFilePicked(Some((name, source))) => {
let i = self.active_tab;
crate::io::linetypes::populate_document_from_source(
&mut self.tabs[i].scene.document,
&source,
);
match self.tabs[i]
.scene
.set_centerline_setting("CENTERLTYPEFILE", &name)
{
Ok(message) => {
self.tabs[i].dirty = true;
self.command_line.push_output(&message);
}
Err(error) => self.command_line.push_error(&error),
}
Task::none()
}
#[cfg(target_arch = "wasm32")]
Message::CenterlineLinetypeFilePicked(None) => Task::none(),
Message::ToggleLayers => {
if self.active_modal == Some(super::ModalKind::Layers) {
self.ribbon.deactivate_tool_if("LAYERS");
@@ -2334,10 +2393,61 @@ impl OpenCADStudio {
}
// ── Layer Translator (#624) ──────────────────────────────────
Message::LayerTranslatorLoad => {
Task::perform(crate::io::pick_layer_standard_path(), |path| match path {
Some(path) => Message::LayerTranslatorLoaded(path),
None => Message::Noop,
})
#[cfg(not(target_arch = "wasm32"))]
{
Task::perform(crate::io::pick_layer_standard_path(), |path| match path {
Some(path) => Message::LayerTranslatorLoaded(path),
None => Message::Noop,
})
}
// Web: read the picked file's bytes and parse them on the
// worker right away — a name-only path has nothing behind it
// for `load_targets` to read later.
#[cfg(target_arch = "wasm32")]
{
Task::perform(
async {
crate::io::pick_and_parse_web(
crate::t!("Load layer standard").as_ref(),
crate::t!("Drawings and standards").as_ref(),
&["dwg", "dws", "dwt", "dxf", "DWG", "DWS", "DWT", "DXF"],
)
.await
.and_then(|picked| {
picked.map_or(Ok(None), |(name, document)| {
crate::modules::draw::layers::laytrans::targets_from_document(
&document,
)
.map(|targets| Some((name, targets)))
})
})
},
|loaded| Message::LayerTranslatorLoadedWeb(loaded),
)
}
}
#[cfg(target_arch = "wasm32")]
Message::LayerTranslatorLoadedWeb(loaded) => {
match loaded {
Ok(Some((source_file, targets))) => {
let state = self.layer_translator.get_or_insert_with(Default::default);
state.source_file = source_file;
state.targets = targets;
// A target set that no longer contains a mapped name
// would translate onto nothing.
let names: Vec<String> =
state.targets.iter().map(|t| t.name.clone()).collect();
state
.mappings
.retain(|m| names.iter().any(|n| n.eq_ignore_ascii_case(&m.to)));
state.selected_to = None;
}
Err(why) => self
.command_line
.push_error(crate::tf!("LAYTRANS: {why}.").as_ref()),
Ok(None) => {}
}
Task::none()
}
Message::LayerTranslatorLoaded(path) => {
use crate::modules::draw::layers::laytrans;