mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-20 12:55:43 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5da799a8c | ||
|
|
9537bbbb48 | ||
|
|
d83bf7be22 | ||
|
|
5f44be5bdf | ||
|
|
3e4068246d | ||
|
|
032b73347c | ||
|
|
45065cc061 | ||
|
|
7dc9e0ec6f | ||
|
|
54d0e034e4 | ||
|
|
2a9c14e96e | ||
|
|
bfadb1a94e |
Generated
+12
@@ -661,6 +661,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -2056,6 +2057,17 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
|
||||
|
||||
[[package]]
|
||||
name = "fmv-macos-events"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
|
||||
@@ -62,6 +62,11 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
# in Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
|
||||
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
|
||||
# Pinned exactly: review the implementation before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod apple_events;
|
||||
mod control_server;
|
||||
mod desktop_theme;
|
||||
mod env;
|
||||
@@ -54,6 +56,9 @@ struct App {
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -102,6 +107,9 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
|
||||
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
|
||||
self.cad.guarded_logic(ctx);
|
||||
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
|
||||
@@ -435,6 +443,12 @@ fn main() -> eframe::Result {
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"CADCraft",
|
||||
options,
|
||||
@@ -498,6 +512,14 @@ fn main() -> eframe::Result {
|
||||
for f in &files {
|
||||
app.open_path(f);
|
||||
}
|
||||
// Start reading any launch-time documents before the first frame. Later events use
|
||||
// this same inbox, including the normal unsaved-changes handling for quit requests.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = {
|
||||
let inbox = apple_events.connect(&cc.egui_ctx);
|
||||
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
|
||||
inbox
|
||||
};
|
||||
if app.session.docs.is_empty() {
|
||||
// In the units the profile asks for (MEASUREINIT, restored above).
|
||||
let metric = app.session.settings.measureinit;
|
||||
@@ -525,6 +547,8 @@ fn main() -> eframe::Result {
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -79,6 +79,9 @@
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
<!-- With AutoCAD or LibreOffice installed, .dwg and .dxf files carry their exported types
|
||||
(com.autodesk.autocad.dwg, org.libreoffice.dxf-document) instead of ours, so those are
|
||||
claimed too. Otherwise Finder never offers CADCraft in Open With. -->
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
@@ -89,7 +92,7 @@
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array><string>ai.storyteller.cadcraft.dxf</string></array>
|
||||
<array><string>ai.storyteller.cadcraft.dxf</string><string>org.libreoffice.dxf-document</string></array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>CADCraft</string>
|
||||
</dict>
|
||||
@@ -101,7 +104,7 @@
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array><string>ai.storyteller.cadcraft.dwg</string></array>
|
||||
<array><string>ai.storyteller.cadcraft.dwg</string><string>com.autodesk.autocad.dwg</string></array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>CADCraft</string>
|
||||
</dict>
|
||||
|
||||
Reference in New Issue
Block a user