* claim: #5467 * Warn when a design is open elsewhere or changed on disk (#5467) The desktop app keeps a lock file next to each open design (.~<file>.lock: computer, user, version, opened and refreshed times), refreshes it every minute and removes it on close; a lock not refreshed for three minutes is stale and ignored. Opening a design that another SolidCraft has open asks: Open Read-Only, Open Anyway or Cancel. A read-only design saves only to another file. A design remembers its file's size and modification time when it is opened or saved. Save over a file another program or computer changed since asks: Save a Copy (the default), Overwrite or Cancel. Programmatic calls never ask: doc.open reports open_elsewhere and takes read_only, and file.save over a changed file returns an error until it is given overwrite: true. ui.documents answers both questions.
This commit is contained in:
Generated
+1
@@ -4337,6 +4337,7 @@ dependencies = [
|
||||
"cadmpeg-registry",
|
||||
"chardetng",
|
||||
"encoding_rs",
|
||||
"gethostname",
|
||||
"gltf",
|
||||
"log",
|
||||
"quick-xml",
|
||||
|
||||
@@ -67,6 +67,9 @@ encoding_rs = "0.8"
|
||||
# glTF 2.0 import (MIT OR Apache-2.0): the document model and GLB container only; buffers are
|
||||
# read by crates/io itself, so no image decoding or file access comes with it.
|
||||
gltf = { version = "1.4", default-features = false, features = ["names"] }
|
||||
# The computer's name in a design's "open elsewhere" lock file (MIT OR Apache-2.0; already in the
|
||||
# tree through x11rb).
|
||||
gethostname = "1"
|
||||
|
||||
# FreeCAD and Rhino import (Apache-2.0, pure Rust; native and browser builds).
|
||||
# Pinned: its IR and codec APIs change between minor versions. Open formats only: no default
|
||||
|
||||
@@ -175,6 +175,7 @@ impl eframe::App for App {
|
||||
log::warn!("a picture was still being drawn as the app closed");
|
||||
}
|
||||
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
|
||||
solidcraft_ui_egui::open_elsewhere::close(&mut self.solve);
|
||||
solidcraft_engine::crash::end_session();
|
||||
if let Some(lost_at) = self.gpu.as_ref().and_then(|g| g.lost_at) {
|
||||
device_lost::restart(self.gpu.as_ref().is_some_and(|g| g.restart_on_software), lost_at);
|
||||
@@ -801,6 +802,9 @@ fn main() -> eframe::Result {
|
||||
app.session.mark_saved();
|
||||
app.session.undo.clear();
|
||||
}
|
||||
// Lock files next to open designs: a design open on another computer says so (#5467),
|
||||
// the files given at launch included.
|
||||
solidcraft_ui_egui::open_elsewhere::start(&mut app);
|
||||
// A launch from Finder: its files arrived before the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = {
|
||||
|
||||
@@ -1082,7 +1082,18 @@
|
||||
"dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.",
|
||||
"dialog.selection_step": "{step} of {total}: Select {input}",
|
||||
"dialog.step": "Step",
|
||||
"document.changed_on_disk": "{name} changed on disk",
|
||||
"document.changed_on_disk_detail": "{name} was changed by another program or computer since you opened or last saved it. Overwrite replaces those changes with yours; Save a Copy keeps both.",
|
||||
"document.copy_name": "{name} copy",
|
||||
"document.open_anyway": "Open Anyway",
|
||||
"document.open_elsewhere": "{name} is already open",
|
||||
"document.open_elsewhere_detail": "{name} is open in SolidCraft {app} on {who}, opened {when}. If you both save, one of you loses work. Open it read-only to look at it without saving over it.",
|
||||
"document.open_read_only": "Open Read-Only",
|
||||
"document.opened_read_only": "Opened read-only: Save asks for a new file",
|
||||
"document.overwrite": "Overwrite",
|
||||
"document.read_only_save": "This design was opened read-only: save it as a new file",
|
||||
"document.save_changes": "Save changes to {name}?",
|
||||
"document.save_copy": "Save a Copy…",
|
||||
"document.unsaved_changes": "{name} has unsaved changes. If you don't save, they are lost.",
|
||||
"drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}",
|
||||
"drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further",
|
||||
|
||||
@@ -1082,7 +1082,18 @@
|
||||
"dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。",
|
||||
"dialog.selection_step": "{total} ステップ中 {step}: {input} を選択",
|
||||
"dialog.step": "ステップ",
|
||||
"document.changed_on_disk": "{name} がディスク上で変更されました",
|
||||
"document.changed_on_disk_detail": "{name} は、開いたとき(または最後に保存したとき)以降に別のプログラムまたはコンピューターによって変更されました。上書きするとその変更は失われます。コピーを保存すると両方が残ります。",
|
||||
"document.copy_name": "{name} のコピー",
|
||||
"document.open_anyway": "このまま開く",
|
||||
"document.open_elsewhere": "{name} はすでに開かれています",
|
||||
"document.open_elsewhere_detail": "{name} は {who} の SolidCraft {app} で開かれています({when}に開かれました)。両方で保存すると、どちらかの作業が失われます。上書きせずに確認するには読み取り専用で開いてください。",
|
||||
"document.open_read_only": "読み取り専用で開く",
|
||||
"document.opened_read_only": "読み取り専用で開きました:保存すると新しいファイル名を尋ねます",
|
||||
"document.overwrite": "上書き",
|
||||
"document.read_only_save": "このデザインは読み取り専用で開かれています:新しいファイルとして保存してください",
|
||||
"document.save_changes": "{name} への変更を保存しますか?",
|
||||
"document.save_copy": "コピーを保存…",
|
||||
"document.unsaved_changes": "{name} には保存されていない変更があります。保存しない場合、変更内容は失われます。",
|
||||
"drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます",
|
||||
"drive.stopped_by_loop": "{value} で停止: {joint} を通るループはこれ以上閉じられません",
|
||||
|
||||
@@ -1082,7 +1082,18 @@
|
||||
"dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。",
|
||||
"dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}",
|
||||
"dialog.step": "步骤",
|
||||
"document.changed_on_disk": "{name} 已在磁盘上更改",
|
||||
"document.changed_on_disk_detail": "自您打开或上次保存 {name} 以来,它已被其他程序或计算机更改。覆盖会用您的更改替换这些更改;保存副本则两者都保留。",
|
||||
"document.copy_name": "{name} 副本",
|
||||
"document.open_anyway": "仍然打开",
|
||||
"document.open_elsewhere": "{name} 已被打开",
|
||||
"document.open_elsewhere_detail": "{name} 已在 {who} 上的 SolidCraft {app} 中打开({when}打开)。如果双方都保存,其中一方的工作会丢失。以只读方式打开即可查看而不会覆盖它。",
|
||||
"document.open_read_only": "以只读方式打开",
|
||||
"document.opened_read_only": "已以只读方式打开:保存时会要求新文件名",
|
||||
"document.overwrite": "覆盖",
|
||||
"document.read_only_save": "此设计以只读方式打开:请另存为新文件",
|
||||
"document.save_changes": "保存对 {name} 的更改?",
|
||||
"document.save_copy": "保存副本…",
|
||||
"document.unsaved_changes": "{name} 有未保存的更改。如果不保存,将丢失这些更改。",
|
||||
"drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}",
|
||||
"drive.stopped_by_loop": "停在 {value}:经过 {joint} 的环路无法再闭合",
|
||||
|
||||
@@ -20,7 +20,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("open")
|
||||
.key("Ctrl+O")
|
||||
.noundo()
|
||||
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step)"),
|
||||
.params("path: .solidcraft design, or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh)"),
|
||||
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
@@ -33,11 +33,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("save")
|
||||
.key("Ctrl+S")
|
||||
.noundo()
|
||||
.params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"),
|
||||
.params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"),
|
||||
CommandSpec::new("file.save_as", "Save As", save_as)
|
||||
.icon("save")
|
||||
.noundo()
|
||||
.params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"),
|
||||
.params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"),
|
||||
CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore")
|
||||
.noundo()
|
||||
.params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"),
|
||||
@@ -285,14 +285,27 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let read_only = bool_(p, "read_only").unwrap_or(false);
|
||||
// Stamped before it is read: a write while it is being read is a change too.
|
||||
let disk = solidcraft_io::design_lock::stamp(path);
|
||||
let (mut doc, saved) = solidcraft_io::read_design_file(path, s.open_preview.take()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if let Some(stem) = default_name_for(&doc.name, path) {
|
||||
doc.name = stem;
|
||||
}
|
||||
s.replace_design(Session::opened(doc, saved.as_ref()));
|
||||
s.path = Some(path.to_string());
|
||||
s.disk = disk;
|
||||
s.read_only = read_only;
|
||||
let errors = s.model.results.iter().filter(|r| r.error.is_some()).count();
|
||||
Ok(json!({"path": path, "features": s.doc.features.len(), "errors": errors, "name": s.doc.name}))
|
||||
let mut out = json!({"path": path, "features": s.doc.features.len(), "errors": errors, "name": s.doc.name});
|
||||
if read_only {
|
||||
out["read_only"] = json!(true);
|
||||
}
|
||||
let now = solidcraft_io::design_lock::now_secs();
|
||||
if let Some(lock) = solidcraft_io::design_lock::held_elsewhere(std::path::Path::new(path), now) {
|
||||
out["open_elsewhere"] = json!({"host": lock.host, "user": lock.user, "app": lock.app, "opened": lock.opened});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The name a design never given one by its user is shown under.
|
||||
@@ -344,8 +357,18 @@ fn rename_design(s: &mut Session, from: &str, to: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: bool, cache: bool) -> Result<Value> {
|
||||
fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: bool, cache: bool, overwrite: bool) -> Result<Value> {
|
||||
solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if s.path.as_deref() == Some(path) {
|
||||
if s.read_only {
|
||||
return Err(EngineError::Other(format!("{path}: the design was opened read-only; save it to another file with file.save_as")));
|
||||
}
|
||||
if !overwrite && s.disk_changed() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{path}: the file was changed by another program or computer since it was opened or last saved; save to another file with file.save_as, or pass `overwrite: true` to replace it"
|
||||
)));
|
||||
}
|
||||
}
|
||||
// Saving an unnamed design, or one named after the file it was saved as, names it after its
|
||||
// file (not an undoable edit).
|
||||
let renamed = saved_name(&s.doc.name, s.path.as_deref(), path).map(|stem| (s.doc.name.clone(), stem));
|
||||
@@ -395,6 +418,8 @@ fn write_bytes(
|
||||
// Atomic, keeping the version being replaced as `<file>.bak`.
|
||||
solidcraft_io::write_atomic(std::path::Path::new(path), &bytes, true).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
s.path = Some(path.to_string());
|
||||
s.disk = solidcraft_io::design_lock::stamp(path);
|
||||
s.read_only = false;
|
||||
s.mark_saved();
|
||||
Ok(json!({"path": path, "bytes": bytes.len(), "name": s.doc.name}))
|
||||
}
|
||||
@@ -413,9 +438,20 @@ impl Session {
|
||||
self.doc_mut().links.clone_from(&done.doc.links);
|
||||
}
|
||||
self.path.clone_from(&done.path);
|
||||
self.disk = done.disk;
|
||||
self.read_only = done.read_only;
|
||||
self.mark_saved();
|
||||
}
|
||||
|
||||
/// Another program or computer wrote the design's file since it was opened or last saved:
|
||||
/// saving to it would replace that work (#5467). A file that is gone has not changed.
|
||||
pub fn disk_changed(&self) -> bool {
|
||||
match (&self.path, &self.disk) {
|
||||
(Some(path), Some(known)) => solidcraft_io::design_lock::changed_since(path, known),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Container bytes for desktop and browser saves. Only already evaluated bodies
|
||||
/// and warm meshes are eligible; saving never forces evaluation or tessellation.
|
||||
pub fn design_container(&self, compression: solidcraft_io::DesignCompression, preview: bool, cache: bool) -> solidcraft_io::Result<Vec<u8>> {
|
||||
@@ -478,6 +514,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
str_(p, "compression").unwrap_or("fast"),
|
||||
bool_(p, "preview").unwrap_or(false),
|
||||
bool_(p, "cache").unwrap_or(true),
|
||||
bool_(p, "overwrite").unwrap_or(false),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -494,6 +531,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
str_(p, "compression").unwrap_or("fast"),
|
||||
bool_(p, "preview").unwrap_or(false),
|
||||
bool_(p, "cache").unwrap_or(true),
|
||||
bool_(p, "overwrite").unwrap_or(false),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -705,6 +743,46 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #5467: a script, the CLI or the control channel never gets a prompt. A Save over a file
|
||||
/// another program or computer changed since it was opened is refused with an error naming
|
||||
/// `overwrite`, which replaces it; a design opened read-only only saves to another file.
|
||||
#[test]
|
||||
fn a_save_over_a_file_changed_on_disk_or_opened_read_only_is_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-changed-on-disk-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let a = dir.join("Bracket.solidcraft");
|
||||
let a_str = a.to_string_lossy().to_string();
|
||||
let mut s = Session::default();
|
||||
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("file.save_as", &json!({"path": a_str})).unwrap();
|
||||
assert!(!s.disk_changed());
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
// Another computer writes the file.
|
||||
let mut other = Session::default();
|
||||
other.execute("doc.open", &json!({"path": a_str})).unwrap();
|
||||
other.execute("solid.sphere", &json!({"diameter": 4})).unwrap();
|
||||
other.execute("file.save", &json!({})).unwrap();
|
||||
assert!(s.disk_changed());
|
||||
s.execute("solid.sphere", &json!({"diameter": 6})).unwrap();
|
||||
let e = s.execute("file.save", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("changed by another program or computer") && e.contains("overwrite"), "{e}");
|
||||
assert!(s.is_dirty(), "nothing was saved");
|
||||
s.execute("file.save", &json!({"overwrite": true})).unwrap();
|
||||
assert!(!s.disk_changed() && !s.is_dirty());
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
|
||||
let mut ro = Session::default();
|
||||
let r = ro.execute("doc.open", &json!({"path": a_str, "read_only": true})).unwrap();
|
||||
assert_eq!(r["read_only"], json!(true));
|
||||
let e = ro.execute("file.save", &json!({"overwrite": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
let b = dir.join("Bracket copy.solidcraft");
|
||||
ro.execute("file.save_as", &json!({"path": b.to_string_lossy()})).unwrap();
|
||||
assert!(!ro.read_only);
|
||||
ro.execute("file.save", &json!({})).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual warmed engine save and provisional-open benchmark"]
|
||||
fn benchmark_warm_design_save_with_preview() {
|
||||
|
||||
@@ -269,6 +269,12 @@ pub struct Session {
|
||||
pub feature_edit_sketch: Option<u64>,
|
||||
pub selection: Vec<Sel>,
|
||||
pub path: Option<String>,
|
||||
/// `path`'s size and modification time when it was opened or last saved: a Save to it
|
||||
/// finding them changed would replace another program's or computer's work (#5467).
|
||||
pub disk: Option<solidcraft_io::design_lock::FileStamp>,
|
||||
/// Opened read-only (`doc.open {read_only}`, the "open elsewhere" notice): saving to its own
|
||||
/// file is refused; Save As to another file is how its changes are kept.
|
||||
pub read_only: bool,
|
||||
/// One-shot display-only notification during doc.open, before authoritative evaluation.
|
||||
/// Interactive loaders may show it provisionally; it never becomes model state.
|
||||
pub open_preview: Option<Box<dyn Fn(solidcraft_io::DesignPreview) + Send + Sync>>,
|
||||
@@ -457,6 +463,8 @@ impl Session {
|
||||
feature_edit_sketch: None,
|
||||
selection: Vec::new(),
|
||||
path: None,
|
||||
disk: None,
|
||||
read_only: false,
|
||||
open_preview: None,
|
||||
log: Vec::new(),
|
||||
revision: 1,
|
||||
@@ -1115,6 +1123,8 @@ impl Session {
|
||||
feature_edit_sketch: self.feature_edit_sketch,
|
||||
selection: self.selection.clone(),
|
||||
path: None,
|
||||
disk: self.disk,
|
||||
read_only: self.read_only,
|
||||
open_preview: None,
|
||||
saved: self.saved.clone(),
|
||||
log: Vec::new(),
|
||||
|
||||
@@ -35,3 +35,7 @@ cadmpeg-registry = { workspace = true }
|
||||
# the tree through tempfile.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
# The computer's name for a design's lock file (src/design_lock.rs; the browser keeps no lock files).
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
gethostname = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Two writers on one design file (#5467): a design kept in a shared or synced folder can be open
|
||||
//! on two computers at once, and the second Save would silently replace the first one's work.
|
||||
//!
|
||||
//! - **Lock files.** While the desktop app has a design open it keeps a small JSON file next to
|
||||
//! it, `.~<file>.lock` ([`lock_path`]): the computer, the user, the app version, the process
|
||||
//! and when it was opened and last refreshed. The app refreshes it every [`REFRESH_SECS`] and
|
||||
//! removes it on close, so a lock left by a crash or a lost connection goes stale
|
||||
//! ([`Lock::is_stale`]) and is ignored instead of blocking anyone. It is not a design file, so
|
||||
//! the file browser, Open and the recent lists never list it, and failing to write one (a
|
||||
//! read-only folder) never stops a design from opening.
|
||||
//! - **File stamps.** A design remembers its file's size and modification time when it is opened
|
||||
//! or saved ([`FileStamp`]); a different stamp at the next Save means another program or
|
||||
//! computer wrote the file meanwhile.
|
||||
//!
|
||||
//! The browser build keeps neither: it has no shared folders, and no clock in `std`.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// How often an open design's lock is written again.
|
||||
pub const REFRESH_SECS: u64 = 60;
|
||||
/// A lock not refreshed for this long belongs to an app that is gone (three missed refreshes).
|
||||
pub const STALE_SECS: u64 = 3 * REFRESH_SECS;
|
||||
/// Largest lock file read (a real one is a few hundred bytes).
|
||||
const MAX_LOCK_BYTES: u64 = 4096;
|
||||
|
||||
/// A file's size and modification time, to tell whether something else wrote it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FileStamp {
|
||||
pub len: u64,
|
||||
/// Nanoseconds since the Unix epoch (`None` where the file system keeps no time).
|
||||
pub modified_ns: Option<u128>,
|
||||
}
|
||||
|
||||
/// The stamp of the file at `path` now (`None`: it doesn't exist or can't be read; always `None`
|
||||
/// in the browser). A symbolic link is followed, as a save follows it.
|
||||
pub fn stamp(path: &str) -> Option<FileStamp> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let meta = std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file)?;
|
||||
let modified_ns = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos());
|
||||
Some(FileStamp { len: meta.len(), modified_ns })
|
||||
}
|
||||
|
||||
/// The file at `path` is not the one stamped `known`: something else wrote it since. A file that
|
||||
/// is gone counts as unchanged (saving puts it back and replaces nobody's work).
|
||||
pub fn changed_since(path: &str, known: &FileStamp) -> bool {
|
||||
stamp(path).is_some_and(|now| now != *known)
|
||||
}
|
||||
|
||||
/// The lock file of the design at `path`: `.~<file name>.lock` in the same folder.
|
||||
pub fn lock_path(path: &Path) -> PathBuf {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "design".into());
|
||||
path.with_file_name(format!(".~{name}.lock"))
|
||||
}
|
||||
|
||||
/// Seconds since the Unix epoch (0 in the browser, which keeps no lock files).
|
||||
pub fn now_secs() -> u64 {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return 0;
|
||||
}
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Who has a design open, as its lock file says.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Lock {
|
||||
/// The computer's name.
|
||||
pub host: String,
|
||||
pub user: String,
|
||||
/// The SolidCraft version that wrote it.
|
||||
pub app: String,
|
||||
pub pid: u32,
|
||||
/// When the design was opened, and when the lock was last written (Unix seconds).
|
||||
pub opened: u64,
|
||||
pub refreshed: u64,
|
||||
}
|
||||
|
||||
impl Lock {
|
||||
/// This app's lock on a design opened at `opened`.
|
||||
pub fn mine(opened: u64) -> Lock {
|
||||
Lock { host: host_name(), user: user_name(), app: env!("CARGO_PKG_VERSION").into(), pid: std::process::id(), opened, refreshed: opened }
|
||||
}
|
||||
|
||||
/// Not refreshed for [`STALE_SECS`] at `now`: the app that wrote it is gone. A lock dated
|
||||
/// further ahead than that (another computer's clock far off) is stale too, so a wrong clock
|
||||
/// can't keep a design locked.
|
||||
pub fn is_stale(&self, now: u64) -> bool {
|
||||
now.saturating_sub(self.refreshed) > STALE_SECS || self.refreshed.saturating_sub(now) > STALE_SECS
|
||||
}
|
||||
|
||||
/// Written by this process.
|
||||
pub fn is_mine(&self) -> bool {
|
||||
self.pid == std::process::id() && self.host == host_name()
|
||||
}
|
||||
}
|
||||
|
||||
/// The computer's name ("this computer" when it has none).
|
||||
pub fn host_name() -> String {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let name = gethostname::gethostname().to_string_lossy().trim().to_string();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let name = String::new();
|
||||
if name.is_empty() { "this computer".into() } else { name }
|
||||
}
|
||||
|
||||
fn user_name() -> String {
|
||||
["USER", "USERNAME", "LOGNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The lock next to the design at `path`, if there is a readable one.
|
||||
pub fn read(path: &Path) -> Option<Lock> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let file = lock_path(path);
|
||||
if std::fs::metadata(&file).ok()?.len() > MAX_LOCK_BYTES {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_slice(&std::fs::read(&file).ok()?).ok()
|
||||
}
|
||||
|
||||
/// Another app's fresh lock on the design at `path` at `now`: it is open elsewhere.
|
||||
pub fn held_elsewhere(path: &Path, now: u64) -> Option<Lock> {
|
||||
read(path).filter(|l| !l.is_mine() && !l.is_stale(now))
|
||||
}
|
||||
|
||||
/// Write `lock` next to the design at `path` (replacing whatever lock is there).
|
||||
pub fn write(path: &Path, lock: &Lock) -> std::io::Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(lock).map_err(std::io::Error::other)?;
|
||||
crate::safe_write::write_atomic(&lock_path(path), &bytes, false)
|
||||
}
|
||||
|
||||
/// Remove this process's lock on the design at `path`; another app's lock is left alone.
|
||||
pub fn remove(path: &Path) {
|
||||
if read(path).is_some_and(|l| l.is_mine()) {
|
||||
let _ = std::fs::remove_file(lock_path(path));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
pub mod catalog;
|
||||
mod design;
|
||||
pub mod design_lock;
|
||||
mod design_metadata;
|
||||
mod dxf;
|
||||
mod dxf_out;
|
||||
|
||||
@@ -216,6 +216,40 @@ pub fn stale_temps(path: &Path) -> Vec<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #5467: a lock is someone else's while it is refreshed; one left by a crash goes stale, and
|
||||
/// this app's own lock never counts as the design being open elsewhere. Writing a design's
|
||||
/// file changes its stamp.
|
||||
#[test]
|
||||
fn a_fresh_lock_from_another_app_holds_the_design_and_a_stale_or_own_one_does_not() {
|
||||
use crate::design_lock as lock;
|
||||
let d = dir("design-lock");
|
||||
let design = d.join("Bracket.solidcraft");
|
||||
std::fs::write(&design, b"one").unwrap();
|
||||
assert_eq!(lock::lock_path(&design), d.join(".~Bracket.solidcraft.lock"));
|
||||
assert!(!crate::is_design_path(&lock::lock_path(&design).to_string_lossy()), "never listed as a design");
|
||||
|
||||
let now = lock::now_secs();
|
||||
let theirs = lock::Lock { host: "WORKSHOP-PC".into(), pid: std::process::id().wrapping_add(1), ..lock::Lock::mine(now - 600) };
|
||||
lock::write(&design, &lock::Lock { refreshed: now - 30, ..theirs.clone() }).unwrap();
|
||||
assert_eq!(lock::held_elsewhere(&design, now).map(|l| l.host), Some("WORKSHOP-PC".into()));
|
||||
// Not refreshed for longer than three refreshes: left behind, ignored.
|
||||
lock::write(&design, &lock::Lock { refreshed: now - lock::STALE_SECS - 1, ..theirs.clone() }).unwrap();
|
||||
assert!(lock::held_elsewhere(&design, now).is_none());
|
||||
lock::remove(&design);
|
||||
assert!(lock::lock_path(&design).exists(), "another app's lock is left alone");
|
||||
// This app's own lock: not "elsewhere", and removed on close.
|
||||
lock::write(&design, &lock::Lock::mine(now)).unwrap();
|
||||
assert!(lock::held_elsewhere(&design, now).is_none());
|
||||
lock::remove(&design);
|
||||
assert!(!lock::lock_path(&design).exists());
|
||||
|
||||
let known = lock::stamp(&design.to_string_lossy()).unwrap();
|
||||
assert!(!lock::changed_since(&design.to_string_lossy(), &known));
|
||||
std::fs::write(&design, b"written elsewhere").unwrap();
|
||||
assert!(lock::changed_since(&design.to_string_lossy(), &known));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_does_not_replace_an_existing_destination() {
|
||||
let d = dir("create");
|
||||
|
||||
@@ -73,6 +73,11 @@ impl Documents {
|
||||
self.slots.iter_mut().filter_map(Option::as_mut)
|
||||
}
|
||||
|
||||
/// The designs in the tabs not shown.
|
||||
pub(crate) fn background(&self) -> impl Iterator<Item = &Session> {
|
||||
self.slots.iter().filter_map(Option::as_ref).map(|slot| &slot.session)
|
||||
}
|
||||
|
||||
/// Number of open designs (at least the active one).
|
||||
pub fn count(&self) -> usize {
|
||||
self.slots.len().max(1)
|
||||
@@ -430,7 +435,9 @@ fn tab_tooltip(name: &str, path: Option<&str>, cut: bool) -> String {
|
||||
|
||||
/// The control channel's `ui.documents`: list, `new`, `switch`, `close` (by index; `force`
|
||||
/// closes without asking), `close_others` (all but `index`), `close_all`, `move` (`from`, `to`)
|
||||
/// or `quit`; `answer`: save | dont_save | cancel answers "save changes?".
|
||||
/// or `quit`; `answer`: save | dont_save | cancel answers "save changes?"; `open_elsewhere`:
|
||||
/// read_only | anyway | cancel and `changed_on_disk`: save_copy | overwrite | cancel answer those
|
||||
/// questions (#5467).
|
||||
pub fn control(app: &mut SolveApp, p: &Value) -> Value {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(|x| x as usize);
|
||||
match p.get("action").and_then(Value::as_str) {
|
||||
@@ -460,8 +467,30 @@ pub fn control(app: &mut SolveApp, p: &Value) -> Value {
|
||||
if let Some(a) = answer {
|
||||
answer_prompt(app, a);
|
||||
}
|
||||
use crate::open_elsewhere::{DiskAnswer, LockAnswer, answer_disk, answer_lock};
|
||||
match p.get("open_elsewhere").and_then(Value::as_str) {
|
||||
Some("read_only") => answer_lock(app, LockAnswer::ReadOnly),
|
||||
Some("anyway") => answer_lock(app, LockAnswer::Anyway),
|
||||
Some("cancel") => answer_lock(app, LockAnswer::Cancel),
|
||||
_ => {}
|
||||
}
|
||||
match p.get("changed_on_disk").and_then(Value::as_str) {
|
||||
Some("save_copy") => answer_disk(app, DiskAnswer::SaveCopy),
|
||||
Some("overwrite") => answer_disk(app, DiskAnswer::Overwrite),
|
||||
Some("cancel") => answer_disk(app, DiskAnswer::Cancel),
|
||||
_ => {}
|
||||
}
|
||||
let tabs: Vec<Value> = tabs_info(app).into_iter().map(|(name, dirty)| json!({"name": name, "dirty": dirty})).collect();
|
||||
json!({"documents": tabs, "active": app.docs.active, "closing": app.docs.closing, "quitting": app.docs.quitting.is_some(), "batch": app.docs.batch})
|
||||
json!({
|
||||
"documents": tabs,
|
||||
"active": app.docs.active,
|
||||
"closing": app.docs.closing,
|
||||
"quitting": app.docs.quitting.is_some(),
|
||||
"batch": app.docs.batch,
|
||||
"read_only": app.session.read_only,
|
||||
"open_elsewhere": app.lock_prompts.len(),
|
||||
"changed_on_disk": app.disk_prompt,
|
||||
})
|
||||
}
|
||||
|
||||
/// A design tab being dragged along the strip to a new place: its index, and where the pointer
|
||||
|
||||
@@ -247,18 +247,26 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if app.file_load.queued.len() >= crate::documents::MAX_OPEN {
|
||||
let e = "too many queued files".to_string();
|
||||
app.set_status(e.clone(), true);
|
||||
request.answer(Err(e.clone()));
|
||||
return Err(e);
|
||||
}
|
||||
app.file_load.queued.push_back(request);
|
||||
start(app);
|
||||
Ok(())
|
||||
// A design open in another SolidCraft asks first (#5467).
|
||||
let Some(request) = crate::open_elsewhere::check_open(app, request) else { return Ok(()) };
|
||||
queue(app, request)
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a file operation and start it when nothing runs (the desktop app).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn queue(app: &mut SolveApp, request: Request) -> Result<(), String> {
|
||||
if app.file_load.queued.len() >= crate::documents::MAX_OPEN {
|
||||
let e = "too many queued files".to_string();
|
||||
app.set_status(e.clone(), true);
|
||||
request.answer(Err(e.clone()));
|
||||
return Err(e);
|
||||
}
|
||||
app.file_load.queued.push_back(request);
|
||||
start(app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A control-channel (MCP) `doc.open` or STEP/mesh import runs like File > Open: off the window
|
||||
/// thread, answered when the file is in. Other requests come back to be handled now.
|
||||
pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Option<crate::control::ControlRequest> {
|
||||
@@ -835,7 +843,9 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
recovered(app, request);
|
||||
} else {
|
||||
app.set_status(
|
||||
if let Some(w) = warnings.filter(|w| !w.is_empty()) {
|
||||
if made.result.get("read_only").and_then(Value::as_bool) == Some(true) {
|
||||
crate::i18n::tr("document.opened_read_only").to_string()
|
||||
} else if let Some(w) = warnings.filter(|w| !w.is_empty()) {
|
||||
format!("imported with {} warning(s): {}", w.len(), w.first().and_then(Value::as_str).unwrap_or(""))
|
||||
} else {
|
||||
format!("{} done", if request.insert() { "Insert" } else { "Open" })
|
||||
|
||||
@@ -31,7 +31,7 @@ impl SolveApp {
|
||||
/// Keep the target design and editors unchanged until the picker answers.
|
||||
/// (A save being written keeps it unchanged too, see [`crate::save_job`].)
|
||||
pub fn file_picker_busy(&self) -> bool {
|
||||
self.file_picker.is_some() || self.saving.is_some()
|
||||
self.file_picker.is_some() || self.saving.is_some() || self.disk_prompt
|
||||
}
|
||||
|
||||
pub(crate) fn pick_open(&mut self, complete: impl FnOnce(&mut SolveApp, Option<String>) + 'static) {
|
||||
|
||||
@@ -174,6 +174,7 @@ mod fillet_spline_handle_tests;
|
||||
pub mod mouse_gesture;
|
||||
pub(crate) mod navigation;
|
||||
pub use navigation::WebWheelGestures;
|
||||
pub mod open_elsewhere;
|
||||
pub(crate) mod open_meshing;
|
||||
pub mod params_dialog;
|
||||
pub(crate) mod pick_index;
|
||||
@@ -464,6 +465,12 @@ pub struct SolveApp {
|
||||
pub quit_requested: bool,
|
||||
/// Autosave into the recovery folder (the desktop app turns it on).
|
||||
pub autosave: Option<recovery_ui::Autosaves>,
|
||||
/// Lock files next to the open designs (the desktop app turns them on; #5467).
|
||||
pub locks: Option<open_elsewhere::Locks>,
|
||||
/// Opens waiting for "this design is open elsewhere" to be answered, first asked first.
|
||||
pub lock_prompts: Vec<open_elsewhere::LockPrompt>,
|
||||
/// A Save waiting for "the file changed on disk" to be answered.
|
||||
pub disk_prompt: bool,
|
||||
/// Designs left by crashed apps, offered for recovery.
|
||||
pub recoverable: Vec<solidcraft_engine::recovery::Entry>,
|
||||
/// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`).
|
||||
@@ -611,6 +618,9 @@ impl SolveApp {
|
||||
status_undo: false,
|
||||
quit_requested: false,
|
||||
autosave: None,
|
||||
locks: None,
|
||||
lock_prompts: Vec::new(),
|
||||
disk_prompt: false,
|
||||
recoverable: Vec::new(),
|
||||
stand_up: None,
|
||||
stand_up_occurrence: None,
|
||||
@@ -1666,6 +1676,7 @@ impl SolveApp {
|
||||
toolbar::shortcuts(self, ctx);
|
||||
}
|
||||
recovery_ui::tick(self);
|
||||
open_elsewhere::tick(self, ctx);
|
||||
update::tick(self, ctx);
|
||||
if self.issue_report.draft.is_none() && self.file_picker.is_none() {
|
||||
// Files dropped on the agent chat attach to its next message instead.
|
||||
@@ -1772,6 +1783,7 @@ impl SolveApp {
|
||||
file_load::show(self, ui.ctx());
|
||||
open_meshing::show(self, ui.ctx());
|
||||
documents::prompt(self, ui.ctx());
|
||||
open_elsewhere::show(self, ui.ctx());
|
||||
update::show(self, ui.ctx());
|
||||
install::show(self, ui.ctx());
|
||||
// Settings › AI's Add agent dialog: Settings opens over Home too (#3483).
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Two writers on one design (#5467): the desktop app keeps a lock file next to every design it
|
||||
//! has open (`solidcraft_engine::io::design_lock`), says so when a design it opens is open in
|
||||
//! another SolidCraft (on another computer, or in another window here), and asks before a Save
|
||||
//! replaces a file that another program or computer changed since it was opened.
|
||||
//!
|
||||
//! Only interactive actions ask. A control-channel or script `doc.open` opens and reports
|
||||
//! `open_elsewhere` in its result; a programmatic `file.save` over a changed file is refused with
|
||||
//! an error until it passes `overwrite: true`.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::io::design_lock::{self, Lock};
|
||||
|
||||
use crate::SolveApp;
|
||||
use crate::file_load::Request;
|
||||
use crate::ui_kit;
|
||||
|
||||
/// The lock files this app holds, one per open design file (the desktop app turns them on).
|
||||
#[derive(Default)]
|
||||
pub struct Locks {
|
||||
/// Each locked design's file, and when it was opened (Unix seconds).
|
||||
held: BTreeMap<String, u64>,
|
||||
/// When the locks were last written again.
|
||||
refreshed: u64,
|
||||
}
|
||||
|
||||
/// An Open waiting for the answer to "open elsewhere".
|
||||
pub struct LockPrompt {
|
||||
request: Request,
|
||||
lock: Lock,
|
||||
}
|
||||
|
||||
/// Keep lock files for the designs this app opens (the desktop app; never the browser or tests).
|
||||
pub fn start(app: &mut SolveApp) {
|
||||
if !cfg!(target_arch = "wasm32") {
|
||||
app.locks = Some(Locks::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// The design files open in this app that it should hold a lock on: every tab's file, except
|
||||
/// a design opened read-only (whoever has it open is the one writing it).
|
||||
fn wanted(app: &SolveApp) -> BTreeSet<String> {
|
||||
std::iter::once(&app.session)
|
||||
.chain(app.docs.background())
|
||||
.filter(|s| !s.read_only)
|
||||
.filter_map(|s| s.path.clone())
|
||||
.filter(|p| solidcraft_engine::io::is_design_path(p))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Take a lock for each design just opened or saved under a new name, drop the ones no longer
|
||||
/// open, and write them all again every [`design_lock::REFRESH_SECS`]. A lock that can't be
|
||||
/// written (a read-only folder) is no reason to stop anything: the design stays open without one.
|
||||
pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if app.locks.is_none() {
|
||||
return;
|
||||
}
|
||||
let wanted = wanted(app);
|
||||
let Some(locks) = app.locks.as_mut() else { return };
|
||||
let now = design_lock::now_secs();
|
||||
let refresh = now.saturating_sub(locks.refreshed) >= design_lock::REFRESH_SECS;
|
||||
if refresh {
|
||||
locks.refreshed = now;
|
||||
}
|
||||
locks.held.retain(|path, _| {
|
||||
let keep = wanted.contains(path);
|
||||
if !keep {
|
||||
design_lock::remove(std::path::Path::new(path));
|
||||
}
|
||||
keep
|
||||
});
|
||||
for path in wanted {
|
||||
let new = !locks.held.contains_key(&path);
|
||||
let opened = *locks.held.entry(path.clone()).or_insert(now);
|
||||
if new || refresh {
|
||||
let file = std::path::Path::new(&path);
|
||||
// Opened anyway while another app holds it: its lock stays until it goes stale.
|
||||
if design_lock::held_elsewhere(file, now).is_none() {
|
||||
let _ = design_lock::write(file, &Lock { refreshed: now, ..Lock::mine(opened) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if !locks.held.is_empty() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs(design_lock::REFRESH_SECS));
|
||||
}
|
||||
}
|
||||
|
||||
/// The app is closing: its locks go.
|
||||
pub fn close(app: &mut SolveApp) {
|
||||
if let Some(locks) = app.locks.take() {
|
||||
for path in locks.held.keys() {
|
||||
design_lock::remove(std::path::Path::new(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Before an interactive Open of a design: when another SolidCraft has it open, hold the request
|
||||
/// and ask (`None`); otherwise hand it back to be opened.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub(crate) fn check_open(app: &mut SolveApp, request: Request) -> Option<Request> {
|
||||
if app.locks.is_none() || request.reply.is_some() || !solidcraft_engine::io::is_design_path(&request.path) {
|
||||
return Some(request);
|
||||
}
|
||||
match design_lock::held_elsewhere(std::path::Path::new(&request.path), design_lock::now_secs()) {
|
||||
Some(lock) => {
|
||||
app.lock_prompts.push(LockPrompt { request, lock });
|
||||
None
|
||||
}
|
||||
None => Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save to the design's own file, unless it was opened read-only (Save As instead) or something
|
||||
/// else changed the file since it was opened or saved (ask first). `false`: Save As or the
|
||||
/// question is under way instead.
|
||||
pub(crate) fn check_save(app: &mut SolveApp) -> bool {
|
||||
if app.session.read_only {
|
||||
app.set_status(crate::i18n::tr("document.read_only_save"), false);
|
||||
crate::toolbar::save_copy(app);
|
||||
return false;
|
||||
}
|
||||
if app.session.disk_changed() {
|
||||
app.disk_prompt = true;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The file name a prompt names.
|
||||
fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// The "open elsewhere" and "changed on disk" questions, when one is waiting.
|
||||
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let _language = crate::i18n::scope(&app.preferences.language);
|
||||
show_lock_prompt(app, ctx);
|
||||
show_disk_prompt(app, ctx);
|
||||
}
|
||||
|
||||
fn show_lock_prompt(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let Some(prompt) = app.lock_prompts.first() else { return };
|
||||
let name = file_name(&prompt.request.path);
|
||||
let lock = &prompt.lock;
|
||||
let who = if lock.user.is_empty() { lock.host.clone() } else { format!("{} ({})", lock.host, lock.user) };
|
||||
let title = crate::i18n::format("document.open_elsewhere", &[("name", &name)]);
|
||||
let detail = crate::i18n::format(
|
||||
"document.open_elsewhere_detail",
|
||||
&[("name", &name), ("who", &who), ("when", &crate::recovery_ui::ago(lock.opened)), ("app", &lock.app)],
|
||||
);
|
||||
let (closed, action) = ui_kit::Confirm::new(egui::Id::new("sc_open_elsewhere"), "status_warning", &title)
|
||||
.tone(ui_kit::Tone::Warning)
|
||||
.actions(crate::i18n::tr("document.open_read_only"), crate::i18n::tr("ui.cancel"), Some(crate::i18n::tr("document.open_anyway")))
|
||||
.selected(ui_kit::Action::Ok)
|
||||
.show(ctx, true, |ui| {
|
||||
ui_kit::text(ui, &detail, ui_kit::Text::Report("open_elsewhere", false));
|
||||
});
|
||||
let mut answer = match action {
|
||||
ui_kit::Action::Ok => Some(LockAnswer::ReadOnly),
|
||||
ui_kit::Action::Apply => Some(LockAnswer::Anyway),
|
||||
ui_kit::Action::Cancel => Some(LockAnswer::Cancel),
|
||||
ui_kit::Action::None if closed => Some(LockAnswer::Cancel),
|
||||
ui_kit::Action::None => None,
|
||||
};
|
||||
if ctx.input(|x| x.key_pressed(egui::Key::Escape)) {
|
||||
answer = Some(LockAnswer::Cancel);
|
||||
app.esc_handled = true;
|
||||
}
|
||||
if let Some(a) = answer {
|
||||
answer_lock(app, a);
|
||||
}
|
||||
}
|
||||
|
||||
/// What "open elsewhere" was answered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LockAnswer {
|
||||
ReadOnly,
|
||||
Anyway,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// Act on the "open elsewhere" answer.
|
||||
pub fn answer_lock(app: &mut SolveApp, answer: LockAnswer) {
|
||||
if app.lock_prompts.is_empty() {
|
||||
return;
|
||||
}
|
||||
let LockPrompt { mut request, .. } = app.lock_prompts.remove(0);
|
||||
match answer {
|
||||
LockAnswer::ReadOnly => {
|
||||
request.options.insert("read_only".into(), json!(true));
|
||||
reopen(app, request);
|
||||
}
|
||||
LockAnswer::Anyway => reopen(app, request),
|
||||
LockAnswer::Cancel => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the held request now that it is answered (without asking again).
|
||||
fn reopen(app: &mut SolveApp, request: Request) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = crate::file_load::queue(app, request);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = crate::file_load::begin_request(app, request);
|
||||
}
|
||||
|
||||
/// What "changed on disk" was answered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DiskAnswer {
|
||||
SaveCopy,
|
||||
Overwrite,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
fn show_disk_prompt(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if !app.disk_prompt {
|
||||
return;
|
||||
}
|
||||
let name = app.session.path.as_deref().map(file_name).unwrap_or_default();
|
||||
let title = crate::i18n::format("document.changed_on_disk", &[("name", &name)]);
|
||||
let detail = crate::i18n::format("document.changed_on_disk_detail", &[("name", &name)]);
|
||||
let (closed, action) = ui_kit::Confirm::new(egui::Id::new("sc_changed_on_disk"), "status_warning", &title)
|
||||
.tone(ui_kit::Tone::Warning)
|
||||
.actions(crate::i18n::tr("document.save_copy"), crate::i18n::tr("ui.cancel"), Some(crate::i18n::tr("document.overwrite")))
|
||||
.selected(ui_kit::Action::Ok)
|
||||
.show(ctx, true, |ui| {
|
||||
ui_kit::text(ui, &detail, ui_kit::Text::Report("changed_on_disk", false));
|
||||
});
|
||||
let mut answer = match action {
|
||||
ui_kit::Action::Ok => Some(DiskAnswer::SaveCopy),
|
||||
ui_kit::Action::Apply => Some(DiskAnswer::Overwrite),
|
||||
ui_kit::Action::Cancel => Some(DiskAnswer::Cancel),
|
||||
ui_kit::Action::None if closed => Some(DiskAnswer::Cancel),
|
||||
ui_kit::Action::None => None,
|
||||
};
|
||||
if ctx.input(|x| x.key_pressed(egui::Key::Escape)) {
|
||||
answer = Some(DiskAnswer::Cancel);
|
||||
app.esc_handled = true;
|
||||
}
|
||||
if let Some(a) = answer {
|
||||
answer_disk(app, a);
|
||||
}
|
||||
}
|
||||
|
||||
/// Act on the "changed on disk" answer. A Save answering "save changes?" on close or quit goes on
|
||||
/// from here as it would have from the Save.
|
||||
pub fn answer_disk(app: &mut SolveApp, answer: DiskAnswer) {
|
||||
if !std::mem::take(&mut app.disk_prompt) {
|
||||
return;
|
||||
}
|
||||
match answer {
|
||||
DiskAnswer::SaveCopy => crate::toolbar::save_copy(app),
|
||||
DiskAnswer::Overwrite => {
|
||||
if !crate::save_job::start(app, "file.save", json!({"overwrite": true})) {
|
||||
crate::documents::saved_for_close(app);
|
||||
}
|
||||
}
|
||||
DiskAnswer::Cancel => crate::documents::saved_for_close(app),
|
||||
}
|
||||
}
|
||||
@@ -755,7 +755,10 @@ pub fn save(app: &mut SolveApp) {
|
||||
return;
|
||||
}
|
||||
if app.session.path.is_some() {
|
||||
crate::save_job::start(app, "file.save", json!({}));
|
||||
// Read-only, or changed on disk since it was opened: Save As, or a question, instead.
|
||||
if crate::open_elsewhere::check_save(app) {
|
||||
crate::save_job::start(app, "file.save", json!({}));
|
||||
}
|
||||
} else {
|
||||
save_as(app);
|
||||
}
|
||||
@@ -765,8 +768,19 @@ pub(crate) fn save_as(app: &mut SolveApp) {
|
||||
save_as_with_extension(app, solidcraft_engine::io::DESIGN_EXT);
|
||||
}
|
||||
|
||||
/// Save As offering a copy's name ("Bracket copy"), so the file it is a copy of is kept.
|
||||
pub(crate) fn save_copy(app: &mut SolveApp) {
|
||||
let name = crate::i18n::format("document.copy_name", &[("name", &app.session.doc.name)]);
|
||||
save_as_named(app, &name, solidcraft_engine::io::DESIGN_EXT);
|
||||
}
|
||||
|
||||
fn save_as_with_extension(app: &mut SolveApp, extension: &str) {
|
||||
let name = format!("{}.{extension}", app.session.doc.name);
|
||||
let name = app.session.doc.name.clone();
|
||||
save_as_named(app, &name, extension);
|
||||
}
|
||||
|
||||
fn save_as_named(app: &mut SolveApp, name: &str, extension: &str) {
|
||||
let name = format!("{name}.{extension}");
|
||||
app.pick_save(&name, &[solidcraft_engine::io::DESIGN_EXT, "json"], |app, path| {
|
||||
// A save under way answers a closing tab when it ends.
|
||||
if let Some(path) = path
|
||||
|
||||
@@ -168,6 +168,26 @@ Design properties are first saved in format 21. Inserting or linking another des
|
||||
copy its properties; Save As keeps them. A command script of the design
|
||||
(`timeline.export_script`) sets them in one step.
|
||||
|
||||
## Designs in shared or synced folders
|
||||
|
||||
A design kept on a network share or in a synced folder (Dropbox, OneDrive, Syncthing, Google
|
||||
Drive) can be open on two computers at once. The desktop app watches for two writers:
|
||||
|
||||
- **Open elsewhere.** While a design is open, SolidCraft keeps a small lock file next to it,
|
||||
`.~<file>.lock` (computer, user, SolidCraft version, when it was opened), refreshes it every
|
||||
minute and removes it when the design closes. Opening a design that another SolidCraft has open
|
||||
says so: **Open Read-Only** (look at it; Save asks for a new file), **Open Anyway** or
|
||||
**Cancel**. A lock not refreshed for three minutes (left by a crash or a lost connection) is
|
||||
ignored. Lock files never show in Open or the recent lists, and a design in a folder you can't
|
||||
write to still opens.
|
||||
- **Changed on disk.** SolidCraft remembers the file's size and modification time when it opens
|
||||
or saves a design. If another program or computer wrote the file since, Save asks first:
|
||||
**Save a Copy** (the default), **Overwrite** or **Cancel**.
|
||||
|
||||
Scripts, the CLI and the control channel never get these questions. `doc.open` opens the design
|
||||
and reports `open_elsewhere` in its result (`read_only: true` opens it read-only), and `file.save`
|
||||
over a file that changed on disk fails with an error until it is given `overwrite: true`.
|
||||
|
||||
## Saving in the web app
|
||||
|
||||
In Chrome, Edge and Opera, **Save As** opens your browser's save dialog and writes the
|
||||
|
||||
@@ -240,7 +240,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
|
||||
| `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | Render of the model with the current camera (no window needed), drawn on the app's GPU device with the viewport's pipelines (the reply's `renderer`: `gpu`, or `gpu-software` on a software adapter), in the window's theme (light or dark; `solidcraft-cli snapshot` keeps the light colours); cut by the section the viewport shows (`inspect.section`, an open Section Analysis dialog's preview, a sketch's Slice), with the cut face capped. The ground grid and the origin's axes are drawn as the window shows them (`ui.set` `showGrid` and `showOrigin`, `hiddenOrigin`); `grid` and `axes` (booleans) say otherwise for this render |
|
||||
| `ui.confirm` | `accept?`: bool | answers the Delete confirmation (shown when a delete takes other features with it or makes some fail); without `accept`, what it lists |
|
||||
| `ui.messages` | `clear?`: `true` (empty the list), `open?`: bool (show or hide the Messages window) | every status message of this run, oldest first (the last 200; a message repeated in a row is one entry with a `count`): `messages` `[{text, error, at, count}]` (`at` in ms since the Unix epoch), and whether the window is `open` (#2763) |
|
||||
| `ui.documents` | `action?`: `new`, `switch`, `close`, `quit`; `index?`; `force?` (close without asking); `answer?`: `save`, `dont_save`, `cancel` (answers "save changes?") | the open designs (tabs): names, unsaved flags, the active one, a pending "save changes?" prompt, whether a quit is asking |
|
||||
| `ui.documents` | `action?`: `new`, `switch`, `close`, `quit`; `index?`; `force?` (close without asking); `answer?`: `save`, `dont_save`, `cancel` (answers "save changes?"); `open_elsewhere?`: `read_only`, `anyway`, `cancel` (answers "open elsewhere" for the first Open waiting); `changed_on_disk?`: `save_copy`, `overwrite`, `cancel` (answers "changed on disk" before a Save) | the open designs (tabs): names, unsaved flags, the active one, a pending "save changes?" prompt, whether a quit is asking, whether the active design is `read_only`, the Opens waiting for "open elsewhere" (`open_elsewhere`) and a waiting "changed on disk" (`changed_on_disk`) |
|
||||
| `ui.file` | `path`; `insert?`: bool | starts an interactive background Open or Insert; poll `ui.inspect.file_busy` for completion; the window stays responsive |
|
||||
| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs |
|
||||
| `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) |
|
||||
|
||||
Reference in New Issue
Block a user