forked from 1b-agent/opencadstudio-upstream
feat: hatch PDF draw order (#1345), numeric CAS (#1348), web automation (#1349), DATALINK table, System theme; honest decode accounting
Upstream issues, fixed: #1345 — hatches plotted at draw_depth 0.0: the plot path cloned models from the hatch cache, which bakes the depth at seed time; the canvas re-reads the live depth map every frame, which is why the editor was right and every export (PDF and native printing — both route through the exporter) was wrong, with hatch-vs-hatch ties broken by HashMap order. The plot path now re-reads the depth map per entity, and the exporter's tie-break ranks follow the editor's own pass order (hatch < image < wire fill < wire < text < wipeout) instead of pinning hatches between fills and wires. Pinned by content-stream operator- order tests (back/front hatches, overlapping hatches, interleaved wire-between-hatches) and a scene test that fails pre-fix. #1348 — set_properties' optimistic-concurrency compare now matches numbers by value (10.0 == 10) through json_values_match, compatible with the shape of upstream PR #1350; nested objects/arrays recurse. #1349 — web automation contract: control protocol 2 (v1 clients still accepted) adds {op:'open', name, data_base64} routed through the guarded open queue; window.ocsControl.ready/request promise wrapper with an ocs-ready event (web/ocs-control.js); the startup donation prompt is suppressed once a control request is seen (opt-in pre-boot via localStorage); docs/automation documents the whole web contract. Also: DATALINK CSV-to-table works on web (picker + bytes through the session registry — was std::fs, silently dead); COLORSCHEME accepts System (prefers-color-scheme on web, AppsUseLightTheme on Windows). Decode accounting, made honest per the fix-of-fix review: into_rgba8 allocates the RGBA destination while the native buffer is alive for every non-Rgba8 layout (L8 5, La8 6, Rgb8 7, L16 6, La16 8 B/px peaks — the formula now says so), GIF bills the screen+frame coexistence at 8 B/px, and TIFF drops the 3x multipliers both ways — tiff 0.11 splits the given budget between frame and scratch (a total ceiling), so the old double-billing refused honest 16-bit GeoTIFFs ~2.25x early while admitting hostile chunk transients at 3x. The image-refusal-unknown-size locale key moves to the group the catalog always claimed (file).
This commit is contained in:
1 parent
84b093748f
commit
2c38de53e2
41 files changed
+1026
-92
No files matched your search
@@ -1108,6 +1108,34 @@ impl OpenCADStudio {
|
||||
Task::none()
|
||||
}
|
||||
|
||||
/// Web DATALINK: the picked .csv's bytes arrived. They are registered in
|
||||
/// the picked-source registry — so `DATALINKUPDATE` re-reads them
|
||||
/// in-session instead of failing on the absent filesystem — and fed to
|
||||
/// the same table-insert path the native typed-path command uses.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn on_datalink_csv_picked(
|
||||
&mut self,
|
||||
picked: Option<(String, Vec<u8>)>,
|
||||
) -> Task<Message> {
|
||||
let Some((name, bytes)) = picked else {
|
||||
return Task::none();
|
||||
};
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
if !register_picked_source(&name, Arc::new(bytes)) {
|
||||
if let Some(name) = take_last_collision().take() {
|
||||
self.command_line.push_warning(
|
||||
crate::tf!(
|
||||
"\"{name}\" is already loaded from another folder with different contents; re-picking it was ignored to keep the existing link."
|
||||
)
|
||||
.as_ref(),
|
||||
);
|
||||
}
|
||||
return Task::none();
|
||||
}
|
||||
self.place_data_link_table(&text, &name);
|
||||
Task::none()
|
||||
}
|
||||
|
||||
pub(super) fn on_data_link_browse(&mut self) -> Task<Message> {
|
||||
Task::perform(
|
||||
async {
|
||||
|
||||
+59
-38
@@ -1595,49 +1595,25 @@ impl OpenCADStudio {
|
||||
);
|
||||
return Some(Task::none());
|
||||
}
|
||||
// Web: nothing is behind a typed path — pick the .csv through
|
||||
// the browser, read its bytes at pick time, and register them
|
||||
// in the picked-source registry; the same table-insert path
|
||||
// then runs from `DataLinkCsvPicked`.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = path;
|
||||
return Some(Task::perform(
|
||||
crate::io::pick_datalink_csv_web(),
|
||||
Message::DataLinkCsvPicked,
|
||||
));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => {
|
||||
let rows_data = parse_csv_table(&text);
|
||||
let nrows = rows_data.len();
|
||||
let ncols = rows_data.iter().map(|r| r.len()).max().unwrap_or(0);
|
||||
if nrows == 0 || ncols == 0 {
|
||||
self.command_line
|
||||
.push_error(crate::t!("DATALINK: the CSV file is empty.").as_ref());
|
||||
return Some(Task::none());
|
||||
}
|
||||
use acadrust::entities::TableBuilder;
|
||||
use acadrust::types::Vector3;
|
||||
let mut table = TableBuilder::new(nrows, ncols)
|
||||
.at(Vector3::new(0.0, 0.0, 0.0))
|
||||
.row_height(0.5)
|
||||
.column_width(2.0)
|
||||
.build();
|
||||
for (r, row) in rows_data.iter().enumerate() {
|
||||
for (c, cell) in row.iter().enumerate() {
|
||||
table.set_cell_text(r, c, cell);
|
||||
}
|
||||
}
|
||||
let doc = &self.tabs[i].scene.document;
|
||||
let current_style = doc.header.current_table_style_name.clone();
|
||||
table.table_style_handle = doc.objects.iter().find_map(|(handle, object)| {
|
||||
match object {
|
||||
acadrust::objects::ObjectType::TableStyle(style)
|
||||
if style.name.eq_ignore_ascii_case(¤t_style) =>
|
||||
{
|
||||
Some(*handle)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let link_path = std::fs::canonicalize(path)
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|_| path.to_string());
|
||||
let command = crate::modules::annotate::data_link::DataLinkPlaceCommand::new(
|
||||
table, &link_path,
|
||||
);
|
||||
self.command_line
|
||||
.push_info(&crate::command::CadCommand::prompt(&command));
|
||||
self.tabs[i].active_cmd = Some(Box::new(command));
|
||||
self.place_data_link_table(&text, &link_path);
|
||||
}
|
||||
Err(e) => {
|
||||
self.command_line
|
||||
@@ -1849,6 +1825,51 @@ impl OpenCADStudio {
|
||||
}
|
||||
Some(self.finish_dispatch(cmd))
|
||||
}
|
||||
|
||||
/// Build the linked table from CSV text and start the placement command —
|
||||
/// the shared tail of the native typed-path `DATALINK` read and the web
|
||||
/// picker's `DataLinkCsvPicked` (which registers the picked bytes in the
|
||||
/// picked-source registry first so the link re-reads in-session).
|
||||
pub(in crate::app) fn place_data_link_table(&mut self, csv_text: &str, link_path: &str) {
|
||||
let i = self.active_tab;
|
||||
let rows_data = parse_csv_table(csv_text);
|
||||
let nrows = rows_data.len();
|
||||
let ncols = rows_data.iter().map(|r| r.len()).max().unwrap_or(0);
|
||||
if nrows == 0 || ncols == 0 {
|
||||
self.command_line
|
||||
.push_error(crate::t!("DATALINK: the CSV file is empty.").as_ref());
|
||||
return;
|
||||
}
|
||||
use acadrust::entities::TableBuilder;
|
||||
use acadrust::types::Vector3;
|
||||
let mut table = TableBuilder::new(nrows, ncols)
|
||||
.at(Vector3::new(0.0, 0.0, 0.0))
|
||||
.row_height(0.5)
|
||||
.column_width(2.0)
|
||||
.build();
|
||||
for (r, row) in rows_data.iter().enumerate() {
|
||||
for (c, cell) in row.iter().enumerate() {
|
||||
table.set_cell_text(r, c, cell);
|
||||
}
|
||||
}
|
||||
let doc = &self.tabs[i].scene.document;
|
||||
let current_style = doc.header.current_table_style_name.clone();
|
||||
table.table_style_handle = doc.objects.iter().find_map(|(handle, object)| {
|
||||
match object {
|
||||
acadrust::objects::ObjectType::TableStyle(style)
|
||||
if style.name.eq_ignore_ascii_case(¤t_style) =>
|
||||
{
|
||||
Some(*handle)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let command =
|
||||
crate::modules::annotate::data_link::DataLinkPlaceCommand::new(table, link_path);
|
||||
self.command_line
|
||||
.push_info(&crate::command::CadCommand::prompt(&command));
|
||||
self.tabs[i].active_cmd = Some(Box::new(command));
|
||||
}
|
||||
}
|
||||
|
||||
// Scan LandXML text for <CgPoint> survey points. Each element's text content is
|
||||
|
||||
@@ -458,7 +458,8 @@ impl OpenCADStudio {
|
||||
self.command_line.push_output(&crate::tf!("Available themes: {}",
|
||||
"DARK LIGHT DRACULA NORD SOLARIZED_LIGHT SOLARIZED_DARK \
|
||||
GRUVBOX_LIGHT GRUVBOX_DARK TOKYONIGHT TOKYONIGHTSTORM TOKYONIGHTLIGHT \
|
||||
KANAGAWAWAVE KANAGAWADRAGON KANAGAWALOTUS MOONFLY NIGHTFLY OXOCARBON FERRA",
|
||||
KANAGAWAWAVE KANAGAWADRAGON KANAGAWALOTUS MOONFLY NIGHTFLY OXOCARBON FERRA \
|
||||
SYSTEM (follows the OS or browser color scheme)",
|
||||
));
|
||||
self.command_line.push_info(&crate::tf!(
|
||||
"Current color scheme: <{}>",
|
||||
@@ -482,16 +483,40 @@ impl OpenCADStudio {
|
||||
self.command_line.push_output(&crate::tf!("Available themes: {}",
|
||||
"DARK LIGHT DRACULA NORD SOLARIZED_LIGHT SOLARIZED_DARK \
|
||||
GRUVBOX_LIGHT GRUVBOX_DARK TOKYONIGHT TOKYONIGHTSTORM TOKYONIGHTLIGHT \
|
||||
KANAGAWAWAVE KANAGAWADRAGON KANAGAWALOTUS MOONFLY NIGHTFLY OXOCARBON FERRA",
|
||||
KANAGAWAWAVE KANAGAWADRAGON KANAGAWALOTUS MOONFLY NIGHTFLY OXOCARBON FERRA \
|
||||
SYSTEM (follows the OS or browser color scheme)",
|
||||
));
|
||||
return Some(Task::none());
|
||||
}
|
||||
if sub == "0" || sub == "1" {
|
||||
self.command_line.push_error(
|
||||
crate::t!("COLORSCHEME: 0 and 1 are COLORTHEME options. Enter a theme name (e.g. DARK, LIGHT, DRACULA) or use COLORTHEME.").as_ref(),
|
||||
crate::t!("COLORSCHEME: 0 and 1 are COLORTHEME options. Enter a theme name (e.g. DARK, LIGHT, SYSTEM) or use COLORTHEME.").as_ref(),
|
||||
);
|
||||
return Some(Task::none());
|
||||
}
|
||||
// SYSTEM keeps its own name in the saved config and resolves
|
||||
// to a concrete Light/Dark theme at run time — the browser's
|
||||
// prefers-color-scheme on the web, the Windows personalization
|
||||
// setting natively. Re-running the command re-resolves; there
|
||||
// is no live preference listener.
|
||||
if upper_sub == "SYSTEM" {
|
||||
if self.ui_theme.name == "Custom" {
|
||||
self.saved_custom_palette = Some(self.ui_theme.palette);
|
||||
}
|
||||
let resolved = crate::app::config::resolve_system_theme();
|
||||
let name = format!("{resolved:?}");
|
||||
self.ui_theme.name = "System".to_string();
|
||||
self.ui_theme.palette =
|
||||
crate::app::config::UiThemePalette::from_iced(resolved.seed());
|
||||
self.theme_color_inputs = self.ui_theme.palette.hex_values();
|
||||
self.active_theme = resolved;
|
||||
self.sync_model_space_theme(true);
|
||||
self.persist_settings_if_changed();
|
||||
self.command_line.push_output(crate::tf!(
|
||||
"Color scheme set to 'System' (currently {name})."
|
||||
).as_ref());
|
||||
return Some(Task::none());
|
||||
}
|
||||
let theme = crate::app::config::parse_theme_name(sub);
|
||||
if let Some(t) = theme {
|
||||
if self.ui_theme.name == "Custom" {
|
||||
|
||||
@@ -102,12 +102,77 @@ impl UiThemeConfig {
|
||||
pub fn to_iced(&self) -> iced::Theme {
|
||||
if self.name == "Custom" {
|
||||
iced::Theme::custom("Custom", self.palette.to_iced())
|
||||
} else if self.name.eq_ignore_ascii_case("System") {
|
||||
resolve_system_theme()
|
||||
} else {
|
||||
builtin_theme(&self.name).unwrap_or(iced::Theme::Oxocarbon)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the `System` color scheme (COLORSCHEME SYSTEM) to a concrete
|
||||
/// theme: the browser `prefers-color-scheme` media query on the web, the
|
||||
/// Windows `AppsUseLightTheme` personalization value natively, and the dark
|
||||
/// default on the remaining native platforms (no cheap OS query there).
|
||||
/// Read at boot (`apply_config`) and re-read whenever COLORSCHEME SYSTEM
|
||||
/// runs again — there is no live preference listener by design.
|
||||
pub fn resolve_system_theme() -> iced::Theme {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let light = web_sys::window().is_some_and(|window| {
|
||||
window
|
||||
.match_media("(prefers-color-scheme: light)")
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some_and(|query| query.matches())
|
||||
});
|
||||
if light {
|
||||
iced::Theme::Light
|
||||
} else {
|
||||
iced::Theme::Dark
|
||||
}
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
|
||||
{
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD,
|
||||
};
|
||||
let sub_key: Vec<u16> = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let value: Vec<u16> = "AppsUseLightTheme"
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let mut data: u32 = 0;
|
||||
let mut size = std::mem::size_of::<u32>() as u32;
|
||||
// ERROR_SUCCESS (0) with data 1 means the apps theme is Light; a
|
||||
// missing value (older Windows, wiped personalization) is Dark.
|
||||
let light = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
sub_key.as_ptr(),
|
||||
value.as_ptr(),
|
||||
RRF_RT_REG_DWORD,
|
||||
std::ptr::null_mut(),
|
||||
&mut data as *mut u32 as *mut core::ffi::c_void,
|
||||
&mut size,
|
||||
) == 0
|
||||
&& data == 1
|
||||
};
|
||||
if light {
|
||||
iced::Theme::Light
|
||||
} else {
|
||||
iced::Theme::Dark
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_arch = "wasm32", target_os = "windows")))]
|
||||
{
|
||||
iced::Theme::Dark
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct UiThemePalette {
|
||||
@@ -503,6 +568,25 @@ fn config_path() -> Option<std::path::PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn system_scheme_resolves_to_a_concrete_theme_and_keeps_its_name() {
|
||||
// Fresh configs keep the existing default; SYSTEM is opt-in.
|
||||
assert_ne!(UiThemeConfig::default().name, "System");
|
||||
let mut cfg = UiThemeConfig::default();
|
||||
cfg.name = "System".to_string();
|
||||
let resolved = cfg.to_iced();
|
||||
// Case-insensitive like the other stored names.
|
||||
cfg.name = "system".to_string();
|
||||
assert_eq!(cfg.to_iced(), resolved);
|
||||
assert!(
|
||||
matches!(resolved, iced::Theme::Light | iced::Theme::Dark),
|
||||
"SYSTEM must resolve through the platform preference"
|
||||
);
|
||||
// The stored name survives resolution; re-runs re-resolve.
|
||||
assert_eq!(cfg.name, "system");
|
||||
assert_eq!(resolve_system_theme(), resolved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_model_space_defaults() {
|
||||
let cfg = ModelSpaceThemeConfig::default();
|
||||
|
||||
+93
-7
@@ -106,6 +106,10 @@ pub(super) struct State {
|
||||
completed: VecDeque<(String, Value, Value)>,
|
||||
owner: Option<(u64, String)>,
|
||||
pub enabled: bool,
|
||||
/// Set by the first control request of the session (or by a web host's
|
||||
/// boot-time opt-in): while control is enabled, startup prompts that
|
||||
/// would block automation — the donation prompt — are suppressed (#1349).
|
||||
pub automation_seen: bool,
|
||||
serial: u64,
|
||||
events: VecDeque<Value>,
|
||||
pub(super) routing: bool,
|
||||
@@ -346,7 +350,37 @@ impl OpenCADStudio {
|
||||
pub(super) fn control_state(&self) -> Value {
|
||||
let tab = &self.tabs[self.active_tab];
|
||||
let command = tab.active_cmd.as_deref().map(active_command_metadata);
|
||||
json!({"ok":true,"protocol":1,"session_id":session_id(),"version":env!("OCS_APP_VERSION"),
|
||||
// Protocol 2 adds the web in-memory `open` (base64 bytes); protocol 1
|
||||
// requests remain accepted unchanged.
|
||||
// The web-only `open_bytes` push below is the sole mutation, so
|
||||
// native builds see the binding as immutable.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(unused_mut))]
|
||||
let mut capabilities = vec![
|
||||
"commands",
|
||||
"command_manifest",
|
||||
"step_input",
|
||||
"batch",
|
||||
"compact_results",
|
||||
"entity_pick",
|
||||
"structure_pick",
|
||||
"selection",
|
||||
"properties",
|
||||
"records",
|
||||
"record_schemas",
|
||||
"record_filters",
|
||||
"atomic_record_updates",
|
||||
"layers",
|
||||
"history",
|
||||
"documents",
|
||||
"events",
|
||||
"capture",
|
||||
"viewport_capture",
|
||||
"measure",
|
||||
"spatial_query",
|
||||
];
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
capabilities.push("open_bytes");
|
||||
json!({"ok":true,"protocol":2,"session_id":session_id(),"version":env!("OCS_APP_VERSION"),
|
||||
"mode":if self.main_window.is_some(){"gui"}else{"headless"},"enabled":self.control.enabled,
|
||||
"document_id":tab.id,"revision":tab.edit_revision,"geometry_revision":tab.scene.geometry_epoch,"camera_revision":tab.scene.camera_generation,
|
||||
"plugins":plugin_ids(),
|
||||
@@ -361,11 +395,23 @@ impl OpenCADStudio {
|
||||
"mtext_editor":self.mtext_editor.as_ref().map(|e|json!({"text":e.content.text(),"height":e.height,"style":e.style})),
|
||||
"text_editor":self.text_inline.is_some(),"event_cursor":self.control.serial,
|
||||
"operation":self.control.pending.as_ref().map(|p| &p.id),
|
||||
"capabilities":["commands","command_manifest","step_input","batch","compact_results","entity_pick","structure_pick","selection","properties","records","record_schemas","record_filters","atomic_record_updates","layers","history","documents","events","capture","viewport_capture","measure","spatial_query"]
|
||||
"capabilities":capabilities
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn control_request(&mut self, req: Value) -> (Value, Task<Message>) {
|
||||
// First control contact marks the session automated (#1349): a
|
||||
// DonationPrompt that is still queued (not yet shown) is dropped so
|
||||
// automation never waits behind it, and `queue_startup_prompts`
|
||||
// stops queueing one. A prompt already on screen stays — a human
|
||||
// may be reading it; clients close it with `close_modal`.
|
||||
if !self.control.automation_seen && self.control.enabled {
|
||||
self.control.automation_seen = true;
|
||||
if self.active_modal != Some(super::ModalKind::DonationPrompt) {
|
||||
self.pending_startup_modals
|
||||
.retain(|kind| kind != &super::ModalKind::DonationPrompt);
|
||||
}
|
||||
}
|
||||
let op = req["op"].as_str().unwrap_or("");
|
||||
let query = matches!(
|
||||
op,
|
||||
@@ -391,9 +437,12 @@ impl OpenCADStudio {
|
||||
Task::none(),
|
||||
);
|
||||
}
|
||||
if req["protocol"].as_u64().is_some_and(|v| v != 1) {
|
||||
if req["protocol"]
|
||||
.as_u64()
|
||||
.is_some_and(|v| !(1..=2).contains(&v))
|
||||
{
|
||||
return (
|
||||
failure("protocol_mismatch", "Protocol 1 required"),
|
||||
failure("protocol_mismatch", "Protocol 1 or 2 required"),
|
||||
Task::none(),
|
||||
);
|
||||
}
|
||||
@@ -684,9 +733,46 @@ impl OpenCADStudio {
|
||||
let i = self.active_tab;
|
||||
Ok(match req["op"].as_str().unwrap_or("") {
|
||||
"new" => self.update(Message::TabNew),
|
||||
"open" => self.update(Message::OpenExternal(std::path::PathBuf::from(string(
|
||||
req, "path",
|
||||
)?))),
|
||||
"open" => {
|
||||
// Web automation opens in-memory drawings (#1349): decode the
|
||||
// base64 payload and route the bytes through the guarded open
|
||||
// queue drag-and-drop uses, so no OPFS copy or file picker is
|
||||
// involved.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
if req["data_base64"].as_str().is_some() {
|
||||
let name = string(req, "name")?.to_owned();
|
||||
let encoded = string(req, "data_base64")?;
|
||||
let bytes = base64::Engine::decode(
|
||||
&base64::engine::general_purpose::STANDARD,
|
||||
encoded,
|
||||
)
|
||||
.map_err(|_| failure("invalid_data", "data_base64 is not valid base64"))?;
|
||||
if !crate::io::web_drop::enqueue_open(name.clone(), bytes) {
|
||||
return Err(failure("busy", "Web open queue full"));
|
||||
}
|
||||
// The queue is normally drained by the control poll; drain
|
||||
// it now through the same guarded path so this operation
|
||||
// stays pending until the open settles instead of
|
||||
// completing before the drawing exists.
|
||||
let task = self.update(Message::PollWebControl);
|
||||
if self.opening.as_ref().is_none_or(|opening| opening.name != name) {
|
||||
// Another open holds the slot; the poll opens this
|
||||
// entry once it frees, after this operation settles.
|
||||
self.set_control_result(json!({"queued": true, "name": name}));
|
||||
}
|
||||
return Ok(task);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if req["data_base64"].as_str().is_some() {
|
||||
return Err(failure(
|
||||
"invalid_request",
|
||||
"data_base64 open is web-only; supply a native path",
|
||||
));
|
||||
}
|
||||
self.update(Message::OpenExternal(std::path::PathBuf::from(string(
|
||||
req, "path",
|
||||
)?)))
|
||||
}
|
||||
"activate" => {
|
||||
let i = self
|
||||
.tabs
|
||||
|
||||
@@ -2411,6 +2411,11 @@ pub enum Message {
|
||||
/// `None` = cancelled.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
CenterlineLinetypeFilePicked(Option<(String, String)>),
|
||||
/// Web DATALINK: the picked .csv file's name and raw bytes — registered
|
||||
/// in the picked-source registry, then fed to the same table-insert path
|
||||
/// the native typed-path command uses. `None` = cancelled.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
DataLinkCsvPicked(Option<(String, Vec<u8>)>),
|
||||
/// 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.)
|
||||
@@ -4403,6 +4408,16 @@ impl OpenCADStudio {
|
||||
fn boot_web() -> (Self, Task<Message>) {
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let mut s = Self::new();
|
||||
// A web host that intends to automate can opt in before the first
|
||||
// control request by setting `opencadstudio.automation` to "1" in
|
||||
// localStorage (the same pre-load mechanism the settings use): the
|
||||
// startup donation prompt then never queues (#1349).
|
||||
if web_sys::window().and_then(|window| window.local_storage().ok().flatten()).and_then(
|
||||
|storage| storage.get_item("opencadstudio.automation").ok().flatten(),
|
||||
) == Some("1".to_string())
|
||||
{
|
||||
s.control.automation_seen = true;
|
||||
}
|
||||
s.queue_startup_prompts();
|
||||
let focus = s.focus_cmd_input();
|
||||
let primary_font =
|
||||
|
||||
+96
-1
@@ -1104,6 +1104,37 @@ fn requested_handle(request: &Value) -> Result<acadrust::Handle, String> {
|
||||
.ok_or_else(|| "set_properties requires a hexadecimal handle".to_string())
|
||||
}
|
||||
|
||||
/// Compare-and-set equality for `set_properties` (#1348): serde_json keeps
|
||||
/// `10` and `10.0` as distinct numbers, and a JavaScript client cannot even
|
||||
/// send `10.0` (`JSON.stringify(10.0) === "10"`), so plain `Value` equality
|
||||
/// never matches a whole-number float. Numbers compare by value; strings,
|
||||
/// bools and null stay exact; objects and arrays recurse.
|
||||
fn json_values_match(stored: &Value, expected: &Value) -> bool {
|
||||
match (stored, expected) {
|
||||
(Value::Number(stored), Value::Number(expected)) => match (stored.as_f64(), expected.as_f64()) {
|
||||
(Some(stored), Some(expected)) => stored == expected,
|
||||
// Out-of-range or arbitrary-precision numbers keep exact equality.
|
||||
_ => stored == expected,
|
||||
},
|
||||
(Value::Object(stored), Value::Object(expected)) => {
|
||||
stored.len() == expected.len()
|
||||
&& stored.iter().all(|(key, value)| {
|
||||
expected
|
||||
.get(key)
|
||||
.is_some_and(|expected| json_values_match(value, expected))
|
||||
})
|
||||
}
|
||||
(Value::Array(stored), Value::Array(expected)) => {
|
||||
stored.len() == expected.len()
|
||||
&& stored
|
||||
.iter()
|
||||
.zip(expected)
|
||||
.all(|(stored, expected)| json_values_match(stored, expected))
|
||||
}
|
||||
_ => stored == expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_updates(
|
||||
properties: &mut Value,
|
||||
request: &Value,
|
||||
@@ -1136,7 +1167,7 @@ fn apply_updates(
|
||||
.pointer_mut(path)
|
||||
.ok_or_else(|| format!("property does not exist: {path}"))?;
|
||||
if let Some(expected) = update.get("expected") {
|
||||
if target != expected {
|
||||
if !json_values_match(target, expected) {
|
||||
return Err(format!("property changed before update: {path}"));
|
||||
}
|
||||
}
|
||||
@@ -1872,4 +1903,68 @@ mod tests {
|
||||
);
|
||||
assert_eq!(compare["code"], "invalid_update", "{compare}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_properties_expected_matches_whole_number_floats_by_value() {
|
||||
// Both directions of the #1348 mismatch: serde_json keeps 10 and 10.0
|
||||
// as different numbers, and a JS client can only send the integer.
|
||||
assert!(super::json_values_match(&json!(10.0), &json!(10)));
|
||||
assert!(super::json_values_match(&json!(10), &json!(10.0)));
|
||||
// A stale value must still be rejected: value comparison, not a
|
||||
// number-type blind spot.
|
||||
assert!(!super::json_values_match(&json!(10.0), &json!(10.5)));
|
||||
assert!(!super::json_values_match(&json!(10), &json!(10.5)));
|
||||
// Non-numerics keep exact structural equality.
|
||||
assert!(!super::json_values_match(&json!(10), &json!("10")));
|
||||
assert!(!super::json_values_match(&json!(10), &json!(true)));
|
||||
assert!(!super::json_values_match(&json!(null), &json!(10)));
|
||||
// Nested objects and arrays recurse by key/index.
|
||||
assert!(super::json_values_match(
|
||||
&json!({"x":12.0,"y":34.0,"z":[5.0]}),
|
||||
&json!({"x":12,"y":34,"z":[5]}),
|
||||
));
|
||||
assert!(!super::json_values_match(
|
||||
&json!({"x":12.0,"y":34.0}),
|
||||
&json!({"x":12,"y":34.5}),
|
||||
));
|
||||
assert!(!super::json_values_match(
|
||||
&json!({"x":12.0,"y":34.0}),
|
||||
&json!({"x":12.0}),
|
||||
));
|
||||
|
||||
let mut app = OpenCADStudio::new_for_test();
|
||||
app.automation_op(r#"{"op":"new"}"#);
|
||||
let i = app.active_tab;
|
||||
let entity = app.tabs[i]
|
||||
.scene
|
||||
.add_entity(EntityType::Insert(Insert::new("A", Vector3::new(12.0, 34.0, 5.0))));
|
||||
let handle = format!("{:X}", entity.value());
|
||||
|
||||
// A scalar whole-number float matches an integer expected value.
|
||||
let moved = execute(
|
||||
&mut app,
|
||||
json!({"op":"set_properties","collection":"entities","handle":handle,
|
||||
"updates":[{"path":"/insert_point/x","expected":12,"value":20.0}]}),
|
||||
"scalar",
|
||||
);
|
||||
assert_eq!(moved["status"], "completed", "{moved}");
|
||||
|
||||
// A nested expected object matches the stored whole-number floats.
|
||||
let nested = execute(
|
||||
&mut app,
|
||||
json!({"op":"set_properties","collection":"entities","handle":handle,
|
||||
"updates":[{"path":"/insert_point","expected":{"x":20,"y":34,"z":5},"value":{"x":20,"y":34,"z":6}}]}),
|
||||
"nested",
|
||||
);
|
||||
assert_eq!(nested["status"], "completed", "{nested}");
|
||||
|
||||
// A genuinely stale nested value is still rejected.
|
||||
let stale = execute(
|
||||
&mut app,
|
||||
json!({"op":"set_properties","collection":"entities","handle":handle,
|
||||
"updates":[{"path":"/insert_point","expected":{"x":20,"y":34,"z":5},"value":{"x":0,"y":0,"z":0}}]}),
|
||||
"stale",
|
||||
);
|
||||
assert_eq!(stale["code"], "invalid_update", "{stale}");
|
||||
}
|
||||
}
|
||||
+40
-1
@@ -8,7 +8,13 @@ impl OpenCADStudio {
|
||||
self.pending_startup_modals
|
||||
.push_back(ModalKind::AssocPrompt);
|
||||
}
|
||||
if self.donation_prompt_version != env!("OCS_APP_VERSION") {
|
||||
// Automation sessions (#1349): once control traffic has arrived (or a
|
||||
// web host opted in at boot) while control is enabled, the donation
|
||||
// prompt is suppressed — a modal would block every automated
|
||||
// operation until a client closed it by hand.
|
||||
if self.donation_prompt_version != env!("OCS_APP_VERSION")
|
||||
&& !(self.control.enabled && self.control.automation_seen)
|
||||
{
|
||||
self.pending_startup_modals
|
||||
.push_back(ModalKind::DonationPrompt);
|
||||
}
|
||||
@@ -226,6 +232,39 @@ mod tests {
|
||||
assert!(restarted.active_modal.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_sessions_skip_the_donation_prompt() {
|
||||
// First control contact drops a still-queued donation prompt and
|
||||
// stops later queueing while control stays enabled (#1349).
|
||||
let mut app = OpenCADStudio::new_for_test();
|
||||
app.default_assoc_prompted = true;
|
||||
app.queue_startup_prompts();
|
||||
assert_eq!(app.active_modal, Some(ModalKind::DonationPrompt));
|
||||
let _ = app.update(Message::CloseModal);
|
||||
app.donation_prompt_version = "previous-release".to_string();
|
||||
app.pending_startup_modals.push_back(ModalKind::DonationPrompt);
|
||||
let _ = app.control_request(serde_json::json!({"op":"state"}));
|
||||
assert!(app.pending_startup_modals.is_empty());
|
||||
app.queue_startup_prompts();
|
||||
assert_ne!(app.active_modal, Some(ModalKind::DonationPrompt));
|
||||
|
||||
// A still-queued (not yet shown) prompt is dropped on first contact.
|
||||
let mut queued = OpenCADStudio::new_for_test();
|
||||
queued.default_assoc_prompted = true;
|
||||
queued.donation_prompt_version = "previous-release".to_string();
|
||||
queued.pending_startup_modals.push_back(ModalKind::DonationPrompt);
|
||||
let _ = queued.control_request(serde_json::json!({"op":"state"}));
|
||||
queued.queue_startup_prompts();
|
||||
assert_ne!(queued.active_modal, Some(ModalKind::DonationPrompt));
|
||||
|
||||
// A prompt already on screen is left for its reader; clients close
|
||||
// it themselves, and a session with no control traffic still prompts.
|
||||
let mut human = OpenCADStudio::new_for_test();
|
||||
human.default_assoc_prompted = true;
|
||||
human.queue_startup_prompts();
|
||||
assert_eq!(human.active_modal, Some(ModalKind::DonationPrompt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_dialogs_wait_their_turn_and_preserve_unseen_prompts() {
|
||||
let mut app = OpenCADStudio::new_for_test();
|
||||
|
||||
@@ -883,6 +883,14 @@ impl OpenCADStudio {
|
||||
pub(in crate::app) fn apply_config(&mut self, cfg: crate::app::config::AppConfig) {
|
||||
self.apply_settings(&cfg.settings);
|
||||
self.ui_theme = cfg.theme.clone();
|
||||
// A saved `System` scheme re-resolves at boot: the stored palette is
|
||||
// whatever the last resolution produced, so refresh it alongside the
|
||||
// live theme (COLORSCHEME SYSTEM documents this boot-time read).
|
||||
if self.ui_theme.name.eq_ignore_ascii_case("System") {
|
||||
self.ui_theme.palette = crate::app::config::UiThemePalette::from_iced(
|
||||
crate::app::config::resolve_system_theme().seed(),
|
||||
);
|
||||
}
|
||||
self.active_theme = self.ui_theme.to_iced();
|
||||
self.theme_color_inputs = self.ui_theme.palette.hex_values();
|
||||
self.model_space = cfg.model_space;
|
||||
|
||||
@@ -2453,6 +2453,12 @@ impl OpenCADStudio {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Message::ScriptFilePicked(None) => Task::none(),
|
||||
|
||||
// Web DATALINK: the picked .csv's bytes arrived — register them
|
||||
// as the link's in-session source, then run the same table-insert
|
||||
// path the native typed-path command feeds.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Message::DataLinkCsvPicked(picked) => self.on_datalink_csv_picked(picked),
|
||||
|
||||
// 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
|
||||
|
||||
Reference in new issue
Block a user