Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Drag-and-drop: place onto the canvas in Free Transform, open at a tab slot (#739)

Carter Smith2a2459f57a6b
diff --git a/Cargo.lock b/Cargo.lock
index 5cce5656b..11eb8c2e1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3448,6 +3448,8 @@ dependencies = [
"ron",
"serde_json",
"winresource",
+ "winsafe",
+ "x11rb",
]
[[package]]
@@ -6257,6 +6259,12 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "winsafe"
+version = "0.0.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
+
[[package]]
name = "winx"
version = "0.36.4"
diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml
index cb2df1161..219db34a9 100644
--- a/apps/photocraft/Cargo.toml
+++ b/apps/photocraft/Cargo.toml
@@ -46,11 +46,21 @@ ron = "0.12"
# registers the handler (Objective-C interop needs unsafe, which our workspace forbids) behind a
# safe API. Pinned exactly: review the diff before bumping.
fmv-macos-events = "=0.1.0"
-# Turn off AppKit's title bar dragging (mac_window.rs) with safe AppKit calls. Already in
+# Safe AppKit calls only: turn off AppKit's title bar dragging (mac_window.rs) and find where the
+# pointer is when files are dropped (cursor.rs; winit 0.30 drops carry no position). Already in
# Cargo.lock (winit, photocraft-tablet); pinned exactly to the same versions.
objc2 = "=0.6.4"
-objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator"] }
-objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder", "NSWindow"] }
+objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator", "NSGeometry"] }
+objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSResponder", "NSView", "NSWindow"] }
+
+# Drop position on X11 (`cursor.rs`): pure-Rust X client, already in Cargo.lock; pinned exactly.
+[target.'cfg(target_os = "linux")'.dependencies]
+x11rb = { version = "=0.13.2", default-features = false }
+
+# Drop position on Windows (`cursor.rs`): safe Win32 wrappers (GetCursorPos), no dependencies of
+# its own. Pinned exactly: review the diff before bumping.
+[target.'cfg(target_os = "windows")'.dependencies]
+winsafe = { version = "=0.0.29", default-features = false, features = ["user"] }
[build-dependencies]
# Icon + VERSIONINFO for photocraft.exe; build.rs only uses it when targeting Windows.
diff --git a/apps/photocraft/src/cursor.rs b/apps/photocraft/src/cursor.rs
new file mode 100644
index 000000000..719e8239c
--- /dev/null
+++ b/apps/photocraft/src/cursor.rs
@@ -0,0 +1,126 @@
+//! Where the pointer is, read from the OS, so a file drop can tell the canvas (place as a layer)
+//! from the tab strip (open at that tab position) and the panels (open as a document), and the tab
+//! strip can show where a dragged file would go. winit 0.30's file drops carry no position, and
+//! during an OS drag the window gets no pointer events, so egui's last pointer is stale.
+//!
+//! - **macOS**: `NSEvent.mouseLocation`, converted into the content view of our window under it.
+//! - **X11**: `QueryPointer` on our window (a second, pure-Rust X connection).
+//! - **Windows**: `GetCursorPos`, relative to the window's client area.
+//! - **Wayland**: winit 0.30 delivers no file drops there, so there's nothing to place.
+//!
+//! No `unsafe`: every OS call goes through a safe binding.
+//!
+//! [`service`] builds the pointer-position service for the app's window, `None` where it can't
+//! be read.
+
+pub use platform::service;
+
+#[cfg(target_os = "macos")]
+mod platform {
+ use objc2::MainThreadMarker;
+ use objc2_app_kit::{NSApplication, NSEvent, NSWindow};
+ use photocraft_ui_egui::CursorPosFn;
+
+ pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
+ Some(Box::new(|ctx: &egui::Context| in_window_points().map(|(x, y)| egui::pos2(x as f32, y as f32) / ctx.zoom_factor())))
+ }
+
+ /// The pointer in points from the top-left of the content view of our frontmost window under
+ /// it (`None` when it's over none of ours, or off the main thread). Only our own windows are
+ /// searched: a drop that reached us landed on one of them.
+ fn in_window_points() -> Option<(f64, f64)> {
+ let mtm = MainThreadMarker::new()?;
+ let at = NSEvent::mouseLocation();
+ let contains = |w: &NSWindow| {
+ let f = w.frame();
+ (f.origin.x..f.origin.x + f.size.width).contains(&at.x) && (f.origin.y..f.origin.y + f.size.height).contains(&at.y)
+ };
+ let window = NSApplication::sharedApplication(mtm).orderedWindows().iter().find(|w| w.isVisible() && contains(w))?;
+ let view = window.contentView()?;
+ let p = view.convertPoint_fromView(window.convertPointFromScreen(at), None);
+ let y = if view.isFlipped() { p.y } else { view.bounds().size.height - p.y };
+ Some((p.x, y))
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod platform {
+ use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
+ use photocraft_ui_egui::CursorPosFn;
+ use x11rb::protocol::xproto::ConnectionExt;
+ use x11rb::rust_connection::RustConnection;
+
+ pub fn service(cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
+ let window = match cc.window_handle().ok()?.as_raw() {
+ RawWindowHandle::Xlib(h) => u32::try_from(h.window).ok()?,
+ RawWindowHandle::Xcb(h) => h.window.get(),
+ _ => return None,
+ };
+ // Opened on first use and kept: the pointer is read every frame while files hover.
+ let mut conn: Option<RustConnection> = None;
+ Some(Box::new(move |ctx: &egui::Context| match pointer_in(&mut conn, window) {
+ Ok(p) => p.map(|(x, y)| egui::pos2(f32::from(x), f32::from(y)) / ctx.pixels_per_point()),
+ Err(e) => {
+ log::warn!("couldn't read the pointer position: {e}");
+ conn = None;
+ None
+ }
+ }))
+ }
+
+ /// The pointer in pixels relative to `window` (`None` when it's on another screen).
+ fn pointer_in(conn: &mut Option<RustConnection>, window: u32) -> Result<Option<(i16, i16)>, String> {
+ let conn = match conn {
+ Some(c) => c,
+ None => conn.insert(RustConnection::connect(None).map_err(|e| e.to_string())?.0),
+ };
+ let reply = conn.query_pointer(window).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;
+ Ok(reply.same_screen.then_some((reply.win_x, reply.win_y)))
+ }
+}
+
+#[cfg(target_os = "windows")]
+mod platform {
+ use photocraft_ui_egui::CursorPosFn;
+
+ pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
+ Some(Box::new(|ctx: &egui::Context| {
+ let pt = winsafe::GetCursorPos().map_err(|e| log::warn!("couldn't read the pointer position: {e}")).ok()?;
+ let inner = ctx.input(|i| i.viewport().inner_rect)?;
+ Some(super::client_points(egui::pos2(pt.x as f32, pt.y as f32), inner.min, ctx.pixels_per_point()))
+ }))
+ }
+}
+
+/// A screen position in physical pixels to points in the window whose client area starts at
+/// `inner_min` (egui's `inner_rect.min`: the client origin in pixels over `ppp`). On Windows
+/// `GetCursorPos` and the client origin are both physical pixels (winit makes the process
+/// per-monitor DPI aware) and the window draws at one scale wherever it sits, so this holds across
+/// monitors with different DPIs.
+#[cfg(any(target_os = "windows", test))]
+fn client_points(screen_px: egui::Pos2, inner_min: egui::Pos2, ppp: f32) -> egui::Pos2 {
+ ((screen_px - inner_min * ppp) / ppp).to_pos2()
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
+mod platform {
+ use photocraft_ui_egui::CursorPosFn;
+
+ pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use egui::pos2;
+
+ #[test]
+ fn client_points_on_a_second_monitor_at_another_scale() {
+ // A 150% monitor left of a 100% primary: the window's client area starts at (-2400, 300) px.
+ let inner_min = pos2(-2400.0, 300.0) / 1.5;
+ assert_eq!(super::client_points(pos2(-2100.0, 450.0), inner_min, 1.5), pos2(200.0, 100.0));
+ // The same window on the 100% primary.
+ assert_eq!(super::client_points(pos2(500.0, 400.0), pos2(300.0, 300.0), 1.0), pos2(200.0, 100.0));
+ }
+}
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index f7889ca24..82f3346dd 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -23,6 +23,7 @@ mod app_icon;
mod apple_events;
mod control_server;
mod crash_guard;
+mod cursor;
mod gpu_startup;
#[cfg(target_os = "macos")]
mod mac_window;
@@ -353,6 +354,8 @@ fn main() -> eframe::Result {
{
app.services.os_events = Some(apple_events.connect(&cc.egui_ctx));
}
+ // Where file drags and drops are (winit 0.30 doesn't say).
+ app.services.cursor_pos = cursor::service(cc);
// Tablet pressure/tilt/eraser (winit drops them): the macOS monitor installed above
// and the X11 reader write into this feed.
app.stylus.feed = stylus_feed;
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 0f64de72d..603fbabd0 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -810,6 +810,28 @@ fn build() -> Vec<CommandSpec> {
},
journal: false,
},
+ CommandSpec {
+ id: "document.move",
+ label: "Move Document",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"document":index?,"to":index}"##,
+ enabled: has_doc,
+ run: |s, p| {
+ let index = |key: &str| {
+ p.get(key)
+ .map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index"))))
+ };
+ let from = match index("document") {
+ Some(i) => i?,
+ None => s.active_index().ok_or(EngineError::NoDocument)?,
+ };
+ let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??;
+ let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?;
+ Ok(json!({"document": to}))
+ },
+ journal: false,
+ },
CommandSpec {
id: "command.list",
label: "List Commands",
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index 8feaed941..b38c5bc97 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -789,13 +789,6 @@ fn preset_names(s: &Session, kind: &str) -> Option<Vec<String>> {
})
}
-/// Move item `i` of `v` to position `to`.
-fn move_item<T>(v: &mut Vec<T>, i: usize, to: usize) {
- let x = v.remove(i);
- let to = to.min(v.len());
- v.insert(to, x);
-}
-
fn preset_index(s: &Session, kind: &str, p: &Value) -> Result<usize> {
let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?;
if let Some(i) = p.get("index").and_then(Value::as_u64) {
@@ -844,10 +837,10 @@ fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
"move" => {
let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize;
match kind.as_str() {
- "brushes" => move_item(&mut s.tools.presets, i, to),
- "patterns" => move_item(&mut s.patterns.items, i, to),
- _ => move_item(&mut s.edit_state.custom_shapes, i, to),
- }
+ "brushes" => crate::move_item(&mut s.tools.presets, i, to),
+ "patterns" => crate::move_item(&mut s.patterns.items, i, to),
+ _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to),
+ };
}
other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))),
}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 1ca61e3b7..31966c963 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -351,6 +351,9 @@ fn open_as(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- place ----------
+/// History label of an embedded place.
+pub const PLACE_EMBEDDED: &str = "Place Embedded";
+
/// Place a file's bytes as a smart object layer, centred and (when larger than the canvas)
/// scaled down to fit, like Photoshop's Place with "Resize Image During Place". `linked` makes it
/// a linked smart object that refers to that path instead of embedding the bytes.
@@ -381,7 +384,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<S
};
let so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px));
let layer_name = stem(name);
- let label = if matches!(so.source, SmartSource::Linked { .. }) { "Place Linked" } else { "Place Embedded" };
+ let label = if matches!(so.source, SmartSource::Linked { .. }) { "Place Linked" } else { PLACE_EMBEDDED };
let id = s.edit(label, |doc, active| {
let id = doc.insert_above(*active, Layer::new(layer_name, LayerContent::Smart(so)));
*active = Some(id);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 08db85647..6a6f3230f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -307,6 +307,18 @@ pub struct Session {
jobs: jobs::Jobs,
}
+/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when
+/// `i` is out of range.
+pub fn move_item<T>(v: &mut Vec<T>, i: usize, to: usize) -> Option<usize> {
+ if i >= v.len() {
+ return None;
+ }
+ let x = v.remove(i);
+ let to = to.min(v.len());
+ v.insert(to, x);
+ Some(to)
+}
+
impl Session {
pub fn new() -> Self {
Self::default()
@@ -333,6 +345,15 @@ impl Session {
}
}
+ /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active
+ /// document active. Returns its new index; `None` when `from` is out of range.
+ pub fn move_document(&mut self, from: usize, to: usize) -> Option<usize> {
+ let active = self.active().map(|d| d.doc.id);
+ let to = move_item(&mut self.docs, from, to)?;
+ self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id));
+ Some(to)
+ }
+
/// Add a document (from File → New, an import, etc.) and make it active.
/// Preserve its identity unless another open document already owns it.
/// Identity-dependent callers must read the admitted document at the returned index.
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 36940424f..4bcd486fc 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -667,3 +667,35 @@ fn advanced_blending_channels() {
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().excluded_channels, 0);
}
+
+#[test]
+fn move_document_reorders_tabs_and_keeps_the_active_one() {
+ let mut s = Session::new();
+ for name in ["a", "b", "c"] {
+ s.execute("file.new", json!({"width": 4, "height": 4, "name": name})).unwrap();
+ }
+ let names = |s: &Session| s.documents().iter().map(|d| d.doc.name.clone()).collect::<Vec<_>>();
+ let first = names(&s);
+ s.set_active(0);
+ assert_eq!(s.move_document(2, 0), Some(0));
+ assert_eq!(names(&s), [first[2].clone(), first[0].clone(), first[1].clone()]);
+ assert_eq!(s.active_index(), Some(1), "the active document follows its tab");
+ // `to` past the end moves to the last tab; `from` out of range does nothing.
+ assert_eq!(s.move_document(0, 99), Some(2));
+ assert_eq!(names(&s), first);
+ assert_eq!(s.move_document(3, 0), None);
+ let mut v = vec![1, 2];
+ assert_eq!(move_item(&mut v, 2, 0), None, "out of range: no panic, nothing moves");
+ assert_eq!(v, [1, 2]);
+ assert_eq!(names(&s), first);
+ assert_eq!(s.active_index(), Some(0));
+ // The command (for the UI, agents and scripts) moves the active document by default.
+ assert_eq!(s.execute("document.move", json!({"to": 2})).unwrap(), json!({"document": 2}));
+ assert_eq!(names(&s), [first[1].clone(), first[2].clone(), first[0].clone()]);
+ assert_eq!(s.execute("document.move", json!({"document": 2, "to": 0})).unwrap(), json!({"document": 0}));
+ assert_eq!(names(&s), first);
+ for bad in [json!({}), json!({"to": -1}), json!({"to": "1"}), json!({"document": 3, "to": 0}), json!({"document": 1.5, "to": 0})] {
+ assert!(s.execute("document.move", bad.clone()).is_err(), "{bad}");
+ }
+ assert_eq!(names(&s), first);
+}
diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs
index 4eddfad07..e077ed23c 100644
--- a/crates/ui-egui/src/brushes_tab.rs
+++ b/crates/ui-egui/src/brushes_tab.rs
@@ -92,18 +92,6 @@ pub fn apply(app: &mut PhotocraftApp, acts: Vec<Action>) {
}
}
-/// An accent insertion line on one edge of `r` while a drag hovers it.
-fn drop_line(ui: &egui::Ui, r: egui::Rect, after: bool, vertical: bool, t: &Tokens) {
- let s = Stroke::new(2.0, t.accent);
- if vertical {
- let x = if after { r.right() } else { r.left() };
- ui.painter().line_segment([pos2(x, r.top() + 2.0), pos2(x, r.bottom() - 2.0)], s);
- } else {
- let y = if after { r.bottom() } else { r.top() };
- ui.painter().line_segment([pos2(r.left() + 4.0, y), pos2(r.right() - 4.0, y)], s);
- }
-}
-
/// Is the pointer on the second half of `r` (lower in a list, right in a grid)?
fn second_half(ui: &egui::Ui, r: egui::Rect, grid: bool) -> bool {
ui.ctx().pointer_interact_pos().is_some_and(|p| if grid { p.x > r.center().x } else { p.y > r.center().y })
@@ -116,7 +104,7 @@ fn preset_interactions(ui: &egui::Ui, resp: &egui::Response, r: egui::Rect, p: &
if let Some(d) = resp.dnd_hover_payload::<BrushDrag>()
&& matches!(&*d, BrushDrag::Preset(n) if *n != p.name)
{
- drop_line(ui, r, second_half(ui, r, grid), grid, &t);
+ widgets::drop_line(ui, r, second_half(ui, r, grid), grid, &t);
}
if let Some(d) = resp.dnd_release_payload::<BrushDrag>()
&& let BrushDrag::Preset(n) = &*d
@@ -225,7 +213,7 @@ fn group_header(ui: &mut egui::Ui, label: &str, key: &str, open: bool, count: us
resp.dnd_set_drag_payload(BrushDrag::Group(key.to_string()));
if let Some(d) = resp.dnd_hover_payload::<BrushDrag>() {
match &*d {
- BrushDrag::Group(g) if g != key => drop_line(ui, r, false, false, &t),
+ BrushDrag::Group(g) if g != key => widgets::drop_line(ui, r, false, false, &t),
BrushDrag::Preset(_) => {
ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);
}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 73cadc0ec..97958c08b 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -938,6 +938,8 @@ pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) {
/// Tabs + canvas for the active document, or the start screen.
pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ app.drop_canvas_rect = None;
+ app.tab_strip = None;
retain_gpu_documents(app);
crate::transform_tool::track_steps(app, ui.ctx());
let n = app.session.documents().len();
@@ -953,7 +955,8 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
return;
}
if !app.ui.view.hides_tabs() || opening {
- tabs(app, ui);
+ app.tab_strip = Some(tabs(app, ui));
+ drop_slot_line(app, ui);
}
if let Some(job) = app.jobs.focus.or_else(|| (n == 0).then(|| app.jobs.opens.last().map(|o| o.job)).flatten()) {
crate::jobs_ui::open_card(app, ui, job);
@@ -962,6 +965,7 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let Some(idx) = app.session.active_index() else { return };
let rect = ui.available_rect_before_wrap();
app.last_canvas_rect = rect;
+ app.drop_canvas_rect = Some(rect);
let n = app.session.documents().len();
// Window › Arrange: tiled / n-up layouts show several documents side by side; the active one
// takes input, a click elsewhere activates that document.
@@ -989,7 +993,8 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
canvas_view(app, ui, idx, rect, view, true);
}
-fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+/// The tab strip; returns where its document tabs are.
+fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {
let t = crate::theme::Tokens::get(ui.ctx());
if t.pro {
return pro_tabs(app, ui);
@@ -1001,7 +1006,8 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let tab_count = app.session.documents().len();
let (mut focus_open, mut cancel_open) = (None, None);
let focused_open = app.jobs.focus.is_some();
- egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| {
+ let mut doc_tabs = Vec::with_capacity(tab_count);
+ let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
for (i, st) in app.session.documents().iter().enumerate() {
@@ -1012,6 +1018,7 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let meta_g = ui.painter().layout_no_wrap(meta, egui::FontId::proportional(10.5), t.text_faint);
let w = name_g.size().x + meta_g.size().x + 44.0;
let (r, resp) = ui.allocate_exact_size(egui::vec2(w, 26.0), Sense::click());
+ doc_tabs.push(r);
if sel {
ui.painter().rect_filled(r, t.radius_sm, t.card);
ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);
@@ -1078,6 +1085,7 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.ui.status = e;
app.ui.status_error = true;
}
+ TabStrip { rect: frame.response.rect, tabs: doc_tabs }
}
/// All tab actions go through the same guarded File commands as the menu bar, including the
@@ -1122,7 +1130,7 @@ fn open_tab_clicks(
}
/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels.
-fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {
let t = crate::theme::Tokens::get(ui.ctx());
let active = app.session.active_index().filter(|_| app.jobs.focus.is_none());
let (mut activate, mut close) = (None, None);
@@ -1131,6 +1139,7 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 26.0), Sense::hover());
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
let mut x = strip.left();
+ let mut doc_tabs = Vec::with_capacity(tab_count);
for (i, st) in app.session.documents().iter().enumerate() {
let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0);
// Photoshop: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask is targeted;
@@ -1143,6 +1152,7 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let title = format!("{} @ {}% ({layer}{model}/{}){}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" });
let g = ui.painter().layout_no_wrap(title, egui::FontId::proportional(11.5), t.text);
let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(g.size().x + 42.0, strip.height()));
+ doc_tabs.push(r);
let resp = ui.interact(r, ui.id().with(("ptab", i)), Sense::click());
let sel = Some(i) == active;
if sel {
@@ -1201,6 +1211,35 @@ fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.ui.status = e;
app.ui.status_error = true;
}
+ TabStrip { rect: strip, tabs: doc_tabs }
+}
+
+/// Where the document tabs were drawn (opening files' tabs aren't slots): a file dropped on the
+/// strip opens at the slot under the pointer.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TabStrip {
+ pub rect: Rect,
+ /// The document tabs, left to right.
+ pub tabs: Vec<Rect>,
+}
+
+impl TabStrip {
+ /// The tab position a drop at `x` opens at: before the first tab whose middle is right of it.
+ pub fn slot(&self, x: f32) -> usize {
+ self.tabs.iter().filter(|r| r.center().x < x).count()
+ }
+}
+
+/// While files are dragged over the tab strip, an insertion line where they would open.
+fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) {
+ if ui.input(|i| i.raw.hovered_files.is_empty()) {
+ return;
+ }
+ let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx()));
+ let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return };
+ let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return };
+ let Some((r, after)) = tabs.get(slot).map(|r| (*r, false)).or_else(|| tabs.last().map(|r| (*r, true))) else { return };
+ crate::widgets::drop_line(ui, r, after, true, &crate::theme::Tokens::get(ui.ctx()));
}
/// Photoshop-style zoom label: "33.3", "100", "12.5".
diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs
index 9fcc8437c..6339ac77f 100644
--- a/crates/ui-egui/src/file_open.rs
+++ b/crates/ui-egui/src/file_open.rs
@@ -1,8 +1,9 @@
-//! Opening files from disk: File › Open, Open Recent, drag-and-drop onto the window, command-line
-//! paths at launch and the OS's "open these documents" requests (macOS Finder double-click, Open
-//! With, drops on the Dock icon) all go through [`PhotocraftApp::open_file`], so each one names the
-//! document after the file, remembers its path (File › Save writes back to it) and adds it to Open
-//! Recent. Failures are shown as errors (status bar + notice); import warnings as a notice.
+//! Opening files from disk: File › Open, Open Recent, drag-and-drop onto the window (except onto
+//! a document's canvas, which places the file as a layer), command-line paths at launch
+//! and the OS's "open these documents" requests (macOS Finder double-click, Open With, drops on the
+//! Dock icon) all go through [`PhotocraftApp::open_file`], so each one names the document after the
+//! file, remembers its path (File › Save writes back to it) and adds it to Open Recent. Failures
+//! are shown as errors (status bar + notice); import warnings as a notice.
use crate::{PhotocraftApp, notices};
use photocraft_engine::file_cmds::{is_template, untitled_name};
@@ -18,6 +19,25 @@ pub enum OsEvent {
Quit,
}
+/// Where files dropped on the window land, as in the reference app. winit 0.30's drops carry no
+/// position, so it comes from the OS ([`Services::cursor_pos`](crate::Services::cursor_pos));
+/// unknown counts as elsewhere.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum DropTarget {
+ /// The active document's canvas: placed as layers (Place Embedded), each in Free Transform.
+ Canvas,
+ /// The tab strip: opened with their tabs from this position (the strip shows it while files
+ /// hover).
+ Tabs(usize),
+ /// Anywhere else (panels, a dialog, no document): opened like File › Open.
+ Elsewhere,
+}
+
+/// A dropped file's name ("dropped" when it has none).
+fn dropped_name(f: &egui::DroppedFileHandle) -> String {
+ f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into())
+}
+
/// The file name of `path` (the document's display name), or `path` itself when it has none.
pub fn display_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string())
@@ -98,30 +118,100 @@ impl PhotocraftApp {
/// Show "Couldn't open <name>: <error>" as an error (status bar + notice).
pub fn open_failed(&mut self, name: &str, err: &str) {
- let msg = format!("Couldn't open {name}: {err}");
+ self.failed(format!("Couldn't open {name}: {err}"));
+ }
+
+ /// Log `msg` and show it as an error (status bar + notice).
+ fn failed(&mut self, msg: String) {
log::warn!("{msg}");
notices::error(self, msg);
}
- /// Files dropped onto the window. Native drops carry an absolute path and open like File ›
- /// Open; anything else (no path) opens by name only.
- pub fn open_dropped(&mut self, files: Vec<egui::DroppedFileHandle>) {
+ /// Files dropped onto the window at `at` (the pointer, when known), routed by [`DropTarget`].
+ /// Preset files (brushes, gradients) always go to their libraries. Native drops carry an
+ /// absolute path, read in bounded reads (#375) rather than egui's whole-file read.
+ pub fn open_dropped(&mut self, ctx: &egui::Context, files: Vec<egui::DroppedFileHandle>, at: Option<egui::Pos2>) {
+ let target = self.drop_target(ctx, at);
+ let mut slot = match target {
+ DropTarget::Tabs(slot) => Some(slot),
+ DropTarget::Canvas | DropTarget::Elsewhere => None,
+ };
for f in files {
- let path = f.path().to_string_lossy().to_string();
- let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
- // A desktop drop opens like File › Open: on the background worker when jobs are on, and
- // read in bounded reads either way (#375) rather than with egui's whole-file read.
- let opened = if f.path().is_absolute() {
- self.open_path(&path).map(|_| ())
+ let name = dropped_name(&f);
+ if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) {
+ self.drop_places.push_back(f);
+ continue;
+ }
+ match self.open_dropped_file(&f, &name, slot) {
+ Ok(true) => slot = slot.map(|s| s + 1),
+ Ok(false) => {}
+ Err(e) => self.open_failed(&name, &e),
+ }
+ }
+ }
+
+ /// Where a drop at `at` lands. Over a window or dialog it's neither the canvas nor the tabs.
+ pub(crate) fn drop_target(&self, ctx: &egui::Context, at: Option<egui::Pos2>) -> DropTarget {
+ let Some(p) = at.filter(|p| ctx.layer_id_at(*p).is_none_or(|l| l.order == egui::Order::Background)) else {
+ return DropTarget::Elsewhere;
+ };
+ if let Some(strip) = self.tab_strip.as_ref().filter(|s| s.rect.contains(p)) {
+ return DropTarget::Tabs(strip.slot(p.x));
+ }
+ // The canvas shown last frame may belong to a document closed since.
+ if self.session.active().is_some() && self.drop_canvas_rect.is_some_and(|r| r.contains(p)) {
+ return DropTarget::Canvas;
+ }
+ DropTarget::Elsewhere
+ }
+
+ /// Open one dropped file; with `slot`, its tab goes there (when it finishes opening, for
+ /// background opens). True when it took the slot.
+ fn open_dropped_file(&mut self, f: &egui::DroppedFileHandle, name: &str, slot: Option<usize>) -> Result<bool, String> {
+ // Opens append: a background open's tab, or a document.
+ let (docs, opens) = (self.session.documents().len(), self.jobs.opens.len());
+ if f.path().is_absolute() {
+ self.open_path(&f.path().to_string_lossy())?;
+ } else {
+ self.open_bytes(name, &crate::read_dropped(&**f)?)?;
+ }
+ let Some(slot) = slot else { return Ok(false) };
+ if let Some(tab) = self.jobs.opens.get_mut(opens) {
+ tab.slot = Some(slot);
+ return Ok(true);
+ }
+ Ok(self.run("document.move", serde_json::json!({"document": docs, "to": slot})).is_ok())
+ }
+
+ /// Place the next file dropped on the canvas and start Free Transform on it, once no other
+ /// transform is in progress (so several files are placed and transformed one after another).
+ pub(crate) fn place_next_dropped(&mut self, ctx: &egui::Context) {
+ while self.ui.transform.is_none() {
+ let Some(f) = self.drop_places.pop_front() else { return };
+ let placed = if f.path().is_absolute() {
+ self.run("file.placeEmbedded", serde_json::json!({"path": f.path().to_string_lossy()}))
} else {
- crate::read_dropped(&*f).and_then(|bytes| self.open_bytes(&name, &bytes)).map(|_| ())
+ crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&dropped_name(&f), bytes, None))
};
- if let Err(e) = opened {
- self.open_failed(&name, &e);
+ match placed {
+ Ok(_) => {
+ if let Err(e) = crate::transform_tool::begin_placed(self, ctx) {
+ self.ui.status = e;
+ }
+ }
+ Err(e) => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &dropped_name(&f)), ("error", &e)])),
}
}
}
+ /// Place a file's bytes as a smart object layer (File › Place; `linked`: Place Linked, to that
+ /// path), for files that weren't read from a path the command can read.
+ pub(crate) fn place_bytes(&mut self, name: &str, bytes: Vec<u8>, linked: Option<String>) -> Result<serde_json::Value, String> {
+ let r = photocraft_engine::file_cmds::place_bytes(&mut self.session, name, bytes, linked, &serde_json::json!({})).map_err(|e| e.to_string());
+ self.sync_views();
+ r
+ }
+
/// Handle the OS requests queued since the last frame.
pub(crate) fn drain_os_events(&mut self, ctx: &egui::Context) {
let events = self.services.os_events.as_mut().map(|f| f()).unwrap_or_default();
diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs
index 19a4fe85c..87573d104 100644
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@ -272,6 +272,15 @@ impl egui::DroppedFile for FakeDrop {
}
}
+/// A dropped file at `path` whose bytes (if read through egui) are `bytes`.
+fn dropped(path: impl Into<std::path::PathBuf>, bytes: Result<Vec<u8>, String>) -> egui::DroppedFileHandle {
+ std::sync::Arc::new(FakeDrop(path.into(), bytes))
+}
+
+fn doc_names(app: &PhotocraftApp) -> Vec<String> {
+ app.session.documents().iter().map(|d| d.doc.name.clone()).collect()
+}
+
#[test]
fn dropped_files_open_with_path_and_recent() {
let (mut app, _) = app_with(None, None);
@@ -280,15 +289,20 @@ fn dropped_files_open_with_path_and_recent() {
let abs = dir.join("dropped.psd");
std::fs::write(&abs, b"x").unwrap();
let abs_s = abs.to_string_lossy().to_string();
- app.open_dropped(vec![
- // A desktop drop (absolute path) is read from disk like File › Open (#375), never through
- // egui's whole-file `std::fs::read`.
- std::sync::Arc::new(FakeDrop(abs, Err("egui's reader must not be used".into()))),
- // Unreadable and undecodable drops are errors; no path means no recent entry.
- std::sync::Arc::new(FakeDrop("gone.psd".into(), Err("permission denied".into()))),
- std::sync::Arc::new(FakeDrop("rel.psd".into(), Ok(b"x".to_vec()))),
- std::sync::Arc::new(FakeDrop("".into(), Ok(b"bad".to_vec()))),
- ]);
+ // Dropped where the pointer can't be read: each file opens as a document.
+ app.open_dropped(
+ &egui::Context::default(),
+ vec![
+ // A desktop drop (absolute path) is read from disk like File › Open (#375), never
+ // through egui's whole-file `std::fs::read`.
+ dropped(abs, Err("egui's reader must not be used".into())),
+ // Unreadable and undecodable drops are errors; no path means no recent entry.
+ dropped("gone.psd", Err("permission denied".into())),
+ dropped("rel.psd", Ok(b"x".to_vec())),
+ dropped("", Ok(b"bad".to_vec())),
+ ],
+ None,
+ );
assert_eq!(app.session.documents().len(), 2);
assert_eq!(app.session.documents()[0].path.as_deref(), Some(abs_s.as_str()));
assert_eq!(app.session.documents()[0].doc.name, "dropped.psd");
@@ -299,6 +313,236 @@ fn dropped_files_open_with_path_and_recent() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// PNG bytes of a white `w`×`h` image.
+fn png_bytes(w: u32, h: u32) -> Vec<u8> {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
+ photocraft_io::export(&s.active().unwrap().doc, "p.png", &Default::default()).unwrap().bytes
+}
+
+/// An app with one open document whose canvas showed at (100, 50)–(700, 550) last frame.
+fn app_with_canvas() -> PhotocraftApp {
+ let (mut app, _) = app_with(None, None);
+ app.open_bytes("canvas.psd", b"x").unwrap();
+ app.drop_canvas_rect = Some(egui::Rect::from_min_max(egui::pos2(100.0, 50.0), egui::pos2(700.0, 550.0)));
+ app
+}
+
+fn layer_count(app: &PhotocraftApp) -> usize {
+ app.session.active().unwrap().doc.layers.len()
+}
+
+fn history_steps(app: &PhotocraftApp) -> usize {
+ app.session.active().unwrap().history.past_len()
+}
+
+/// As in the reference app, files dropped on the canvas are placed one at a time, each in Free
+/// Transform; the next is placed once the previous transform is committed or cancelled.
+#[test]
+fn files_dropped_onto_the_canvas_are_placed_in_free_transform_one_by_one() {
+ let dir = std::env::temp_dir().join(format!("photocraft-drop-place-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let abs = dir.join("photo.png");
+ std::fs::write(&abs, png_bytes(200, 100)).unwrap();
+ let ctx = egui::Context::default();
+ let mut app = app_with_canvas();
+ let (layers, steps) = (layer_count(&app), history_steps(&app));
+ app.open_dropped(
+ &ctx,
+ vec![
+ // Read from its path, placed like File › Place Embedded (fitted to the canvas).
+ dropped(abs, Err("egui's reader must not be used".into())),
+ // Undecodable: an error, skipped.
+ dropped("bad.png", Ok(b"bad".to_vec())),
+ // No path: placed from the dropped bytes.
+ dropped("small.png", Ok(png_bytes(2, 2))),
+ ],
+ Some(egui::pos2(400.0, 300.0)),
+ );
+ app.place_next_dropped(&ctx);
+ assert_eq!(app.session.documents().len(), 1, "drops onto the canvas don't open documents");
+ assert_eq!(layer_count(&app), layers + 1, "one at a time");
+ let t = app.ui.transform.as_ref().expect("the placed layer is in Free Transform");
+ assert_eq!(t.made, Some(crate::state::MadeLayer::Place));
+ let st = app.session.active().unwrap();
+ assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "photo");
+ // ↩ without changes: the place stays as it is.
+ crate::transform_tool::commit(&mut app);
+ assert_eq!((layer_count(&app), history_steps(&app)), (layers + 1, steps + 1));
+ assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Place Embedded"));
+ // Next frame: the undecodable file is reported, the next one placed and transformed.
+ app.place_next_dropped(&ctx);
+ assert_eq!(app.ui.notices.iter().filter(|n| n.error).count(), 1);
+ assert_eq!(layer_count(&app), layers + 2);
+ let st = app.session.active().unwrap();
+ let top = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ assert_eq!(top.name, "small");
+ assert!(matches!(top.content, photocraft_doc::LayerContent::Smart(_)));
+ // Esc takes the place back, leaving nothing to redo.
+ crate::transform_tool::cancel(&mut app);
+ assert_eq!((layer_count(&app), history_steps(&app)), (layers + 1, steps + 1));
+ assert!(!app.session.active().unwrap().history.can_redo());
+ app.place_next_dropped(&ctx);
+ assert!(app.ui.transform.is_none() && app.drop_places.is_empty());
+ assert!(app.ui.recent_files.is_empty(), "placing isn't opening");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Moving a placed file in its Free Transform and committing makes one Place Embedded step.
+#[test]
+fn a_transformed_place_is_one_history_step() {
+ let ctx = egui::Context::default();
+ let mut app = app_with_canvas();
+ let (layers, steps) = (layer_count(&app), history_steps(&app));
+ app.open_dropped(&ctx, vec![dropped("dot.png", Ok(png_bytes(2, 2)))], Some(egui::pos2(400.0, 300.0)));
+ app.place_next_dropped(&ctx);
+ let t = app.ui.transform.as_mut().expect("in Free Transform");
+ t.quad = t.quad.map(|[x, y]| [x - 1.0, y - 1.0]);
+ crate::transform_tool::commit(&mut app);
+ assert_eq!((layer_count(&app), history_steps(&app)), (layers + 1, steps + 1));
+ assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Place Embedded"));
+ app.session.undo();
+ assert_eq!(layer_count(&app), layers, "one undo removes the place and the move");
+}
+
+#[test]
+fn files_dropped_on_the_tabs_open_at_that_slot() {
+ let ctx = egui::Context::default();
+ let mut app = app_with_canvas();
+ app.ui.views[0].zoom = 3.0;
+ // One tab at (100, 20)–(200, 46): its left half is slot 0, its right half and beyond slot 1.
+ let tab = egui::Rect::from_min_max(egui::pos2(100.0, 20.0), egui::pos2(200.0, 46.0));
+ let strip = egui::Rect::from_min_max(egui::pos2(92.0, 14.0), egui::pos2(700.0, 50.0));
+ app.tab_strip = Some(crate::canvas::TabStrip { rect: strip, tabs: vec![tab] });
+ assert_eq!(app.drop_target(&ctx, Some(egui::pos2(120.0, 30.0))), crate::file_open::DropTarget::Tabs(0));
+ assert_eq!(app.drop_target(&ctx, Some(egui::pos2(180.0, 30.0))), crate::file_open::DropTarget::Tabs(1));
+ assert_eq!(app.drop_target(&ctx, Some(egui::pos2(600.0, 30.0))), crate::file_open::DropTarget::Tabs(1));
+ let files = vec![dropped("first.png", Ok(b"x".to_vec())), dropped("bad.png", Ok(b"bad".to_vec())), dropped("second.png", Ok(b"x".to_vec()))];
+ app.open_dropped(&ctx, files, Some(egui::pos2(120.0, 30.0)));
+ assert_eq!(doc_names(&app), ["first.png", "second.png", "canvas.psd"], "in drop order from the slot");
+ assert_eq!(app.session.active_index(), Some(1), "the last one opened is active");
+ assert_eq!(app.ui.views.len(), 3);
+ assert_eq!(app.ui.views[2].zoom, 3.0, "views move with their documents");
+ // Past the last tab: opened at the end.
+ let tabs = (0..3).map(|i| tab.translate(egui::vec2(104.0 * i as f32, 0.0))).collect();
+ app.tab_strip = Some(crate::canvas::TabStrip { rect: strip, tabs });
+ app.open_dropped(&ctx, vec![dropped("last.png", Ok(b"x".to_vec()))], Some(egui::pos2(600.0, 30.0)));
+ assert_eq!(app.session.documents().last().map(|d| d.doc.name.as_str()), Some("last.png"));
+}
+
+/// The whole app (eframe harness, real layout): over the tab strip, the pointer read from the OS
+/// service picks a slot; files dropped there open (in the background) at it; dropped on the canvas they're placed in Free Transform, and Esc takes the place back.
+#[test]
+fn drag_and_drop_in_the_running_app() {
+ let dir = std::env::temp_dir().join(format!("photocraft-drop-app-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("photo.png");
+ std::fs::write(&file, png_bytes(40, 30)).unwrap();
+ let pointer = Rc::new(std::cell::Cell::new(egui::Pos2::ZERO));
+ let reported = pointer.clone();
+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_max_steps(8).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ let mut s = photocraft_engine::Session::new();
+ for _ in 0..2 {
+ s.execute("file.new", json!({"width": 320, "height": 240, "background": "white"})).unwrap();
+ }
+ let services = Services { cursor_pos: Some(Box::new(move |_: &egui::Context| Some(reported.get()))), ..Default::default() };
+ let mut app = PhotocraftApp::new(s, services);
+ app.background_jobs = true;
+ app
+ });
+ h.run_steps(4);
+ let strip = h.state().tab_strip.clone().expect("the tab strip is drawn");
+ assert_eq!(strip.tabs.len(), 2);
+ // Hovering over the first tab's left half: slot 0.
+ let over_first = egui::pos2(strip.tabs[0].left() + 4.0, strip.tabs[0].center().y);
+ pointer.set(over_first);
+ h.input_mut().hovered_files.push(egui::HoveredFile { path: Some(file.clone()), ..Default::default() });
+ h.step();
+ assert_eq!(h.state().drop_target(&h.ctx, Some(over_first)), crate::file_open::DropTarget::Tabs(0));
+ // Dropped there: opens in the background, then takes the first tab.
+ h.input_mut().hovered_files.clear();
+ h.input_mut().dropped_files.push(dropped(file.clone(), Err("read from the path".into())));
+ h.step();
+ let t = std::time::Instant::now();
+ while !h.state().jobs.opens.is_empty() && t.elapsed() < std::time::Duration::from_secs(30) {
+ h.step();
+ }
+ h.run_steps(2);
+ let names = doc_names(h.state());
+ assert_eq!(names.len(), 3);
+ assert_eq!(names[0], "photo.png", "{names:?}");
+ assert_eq!(h.state().session.active_index(), Some(0));
+ // Dropped on the canvas: placed into the active document, in Free Transform.
+ let layers = h.state().session.active().unwrap().doc.layers.len();
+ pointer.set(h.state().drop_canvas_rect.expect("the canvas is shown").center());
+ h.input_mut().dropped_files.push(dropped(file, Err("read from the path".into())));
+ h.run_steps(2);
+ assert_eq!(h.state().session.documents().len(), 3, "no new document");
+ assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers + 1);
+ assert_eq!(h.state().ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place));
+ h.key_press(egui::Key::Escape);
+ h.run_steps(2);
+ assert!(h.state().ui.transform.is_none());
+ assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers, "Esc takes the place back");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn views_and_windows_stay_with_their_documents() {
+ let (mut app, _) = app_with(None, None);
+ for name in ["a.psd", "b.psd", "c.psd", "d.psd"] {
+ app.open_bytes(name, b"x").unwrap();
+ }
+ for (i, v) in app.ui.views.iter_mut().enumerate() {
+ v.zoom = i as f32 + 1.0;
+ }
+ app.ui.windows = (0..4).map(|document| crate::state::DocWindow { id: document as u64, document, view: Default::default(), open: true }).collect();
+ let zooms = |app: &PhotocraftApp| app.ui.views.iter().map(|v| v.zoom).collect::<Vec<_>>();
+ let windows = |app: &PhotocraftApp| app.ui.windows.iter().map(|w| (w.id, w.document)).collect::<Vec<_>>();
+ assert_eq!(app.run("document.move", json!({"document": 0, "to": 3})).unwrap(), json!({"document": 3}));
+ assert_eq!(doc_names(&app), ["b.psd", "c.psd", "d.psd", "a.psd"]);
+ assert_eq!(zooms(&app), [2.0, 3.0, 4.0, 1.0]);
+ assert_eq!(windows(&app), [(0, 3), (1, 0), (2, 1), (3, 2)]);
+ // Out of range: an error, nothing moves.
+ assert!(app.run("document.move", json!({"document": 7, "to": 0})).is_err());
+ assert_eq!(zooms(&app), [2.0, 3.0, 4.0, 1.0]);
+ // Closing a middle tab takes its view and windows with it; the others keep theirs.
+ app.run("file.close", json!({"document": 1})).unwrap();
+ assert_eq!(doc_names(&app), ["b.psd", "d.psd", "a.psd"]);
+ assert_eq!(zooms(&app), [2.0, 4.0, 1.0]);
+ assert_eq!(windows(&app), [(0, 2), (1, 0), (3, 1)]);
+}
+
+#[test]
+fn files_dropped_off_the_canvas_open_as_documents() {
+ let other = || vec![dropped("other.png", Ok(b"x".to_vec()))];
+ let ctx = egui::Context::default();
+ // On the tab bar or a panel (outside the canvas), or where the pointer can't be read.
+ for at in [Some(egui::pos2(400.0, 30.0)), Some(egui::pos2(750.0, 300.0)), None] {
+ let mut app = app_with_canvas();
+ let before = layer_count(&app);
+ app.open_dropped(&ctx, other(), at);
+ assert_eq!(app.session.documents().len(), 2, "{at:?}");
+ assert_eq!(app.session.documents()[0].doc.layers.len(), before, "{at:?}");
+ }
+ // Over a window floating above the canvas (shown from its second frame, once sized).
+ for _ in 0..2 {
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
+ egui::Window::new("panel").fixed_pos(egui::pos2(300.0, 200.0)).show(ui.ctx(), |ui| ui.label("over the canvas"));
+ });
+ out.textures_delta.clear();
+ }
+ let mut app = app_with_canvas();
+ app.open_dropped(&ctx, other(), Some(egui::pos2(320.0, 220.0)));
+ assert_eq!(app.session.documents().len(), 2);
+ // The start screen or an opening file's card (no canvas shown) opens too.
+ let mut app = app_with_canvas();
+ app.drop_canvas_rect = None;
+ app.open_dropped(&ctx, other(), Some(egui::pos2(400.0, 300.0)));
+ assert_eq!(app.session.documents().len(), 2);
+}
+
#[test]
fn notices_are_capped_and_dismissable_state_round_trips() {
let (mut app, _) = app_with(None, None);
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index a8868045c..9590be5ae 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2080,3 +2080,4 @@ cameraRaw Color Barvy
Don't show again Příště nezobrazovat
Save failed: {error} Uložení se nezdařilo: {error}
Save cancelled Ukládání zrušeno
+ Couldn't place {name}: {error} Nelze umístit {name}: {error}
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 4cedbba3b..e88cf5d75 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2124,4 +2124,5 @@
Don't show again Nicht mehr anzeigen
Save failed: {error} Speichern fehlgeschlagen: {error}
Save cancelled Speichern abgebrochen
+ Couldn't place {name}: {error} {name} konnte nicht platziert werden: {error}
Full-resolution preview unavailable Vorschau in voller Auflösung nicht verfügbar
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index d5c68f248..5f3db45f7 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1493,6 +1493,7 @@
Comic Book Cómic
Conform Conformar
Content-Aware Fill needs a selection on a pixel layer El relleno de contenido necesita una selección en una capa de píxeles
+ Couldn't place {name}: {error} No se pudo colocar {name}: {error}
Could not transform: the layer is empty No se pudo transformar: la capa está vacía
Could not use Perspective Warp: the layer is empty No se pudo usar la deformación en perspectiva: la capa está vacía
Could not use Puppet Warp: no opaque pixels No se pudo usar la deformación de clavos: no hay píxeles opacos
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 6529a52b8..4161a5706 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2514,3 +2514,4 @@ cameraRaw Blending Fusion
Don't show again Ne plus afficher
Save failed: {error} Échec de l'enregistrement : {error}
Save cancelled Enregistrement annulé
+ Couldn't place {name}: {error} Impossible d'importer {name} : {error}
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index e942da626..b4a6524be 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2501,3 +2501,4 @@ cameraRaw Blending Pembauran
Don't show again Jangan tampilkan lagi
Save failed: {error} Gagal menyimpan: {error}
Save cancelled Penyimpanan dibatalkan
+ Couldn't place {name}: {error} Tidak dapat menempatkan {name}: {error}
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 5fa159230..070c31779 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -1498,6 +1498,7 @@
Comic Book コミック
Conform 適合
Content-Aware Fill needs a selection on a pixel layer コンテンツに応じた塗りつぶしには、ピクセルレイヤー上の選択範囲が必要です
+ Couldn't place {name}: {error} {name} を配置できませんでした: {error}
Could not transform: the layer is empty 変形できません: レイヤーが空です
Could not use Perspective Warp: the layer is empty 遠近法ワープを使えません: レイヤーが空です
Could not use Puppet Warp: no opaque pixels パペットワープを使えません: 不透明なピクセルがありません
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 2e1681fd5..a486ca103 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2667,3 +2667,4 @@ cameraRaw Color 색상
Don't show again 다시 표시 안 함
Save failed: {error} 저장 실패: {error}
Save cancelled 저장이 취소되었습니다
+ Couldn't place {name}: {error} {name}을(를) 가져올 수 없습니다: {error}
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index c66c79f3c..167b573a0 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2523,4 +2523,5 @@ cameraRaw Whites Brancos
Don't show again Não mostrar novamente
Save failed: {error} Falha ao salvar: {error}
Save cancelled Salvamento cancelado
+ Couldn't place {name}: {error} Não foi possível inserir {name}: {error}
Full-resolution preview unavailable Pré-visualização em resolução total indisponível
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 636f5f8cb..24229736a 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2357,3 +2357,4 @@ cameraRaw Roughness Неровность
Don't show again Больше не показывать
Save failed: {error} Не удалось сохранить: {error}
Save cancelled Сохранение отменено
+ Couldn't place {name}: {error} Не удалось поместить {name}: {error}
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 1f1f57bbc..fa0119123 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1503,6 +1503,7 @@
Comic Book 漫画
Conform 拉伸
Content-Aware Fill needs a selection on a pixel layer 内容识别填充需要像素图层上的选区
+ Couldn't place {name}: {error} 无法置入 {name}:{error}
Could not transform: the layer is empty 无法变换:图层为空
Could not use Perspective Warp: the layer is empty 无法使用透视变形:图层为空
Could not use Puppet Warp: no opaque pixels 无法使用操控变形:没有不透明像素
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 5f92a80fb..251237693 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1497,6 +1497,7 @@
Comic Book 漫畫書
Conform 符合
Content-Aware Fill needs a selection on a pixel layer 內容感知填滿需要在像素圖層上建立選取範圍
+ Couldn't place {name}: {error} 無法置入 {name}:{error}
Could not transform: the layer is empty 無法變形:圖層是空的
Could not use Perspective Warp: the layer is empty 無法使用透視彎曲:圖層是空的
Could not use Puppet Warp: no opaque pixels 無法使用操控彎曲:沒有不透明像素
diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs
index 40af9a4dc..57cb50ded 100644
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@ -34,6 +34,8 @@ pub struct OpenTab {
pub name: String,
/// Where it was read from (File › Save writes back there; added to Open Recent).
pub path: Option<String>,
+ /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end.
+ pub slot: Option<usize>,
}
/// The shell's job bookkeeping.
@@ -74,9 +76,9 @@ pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, sou
let name = &app.open_name(name);
match app.session.start_open(name, source).map_err(|e| e.to_string())? {
// Inline (wasm): finish now, like a background open that ended at once.
- Started::Done(v) => finish_open(app, name, path.as_deref(), &v),
+ Started::Done(v) => finish_open(app, name, path.as_deref(), &v, None),
Started::Job(job) => {
- app.jobs.opens.push(OpenTab { job, name: name.to_string(), path });
+ app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot: None });
app.jobs.focus = Some(job);
app.ui.chrome.home = None;
app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]);
@@ -150,7 +152,7 @@ fn on_event(app: &mut PhotocraftApp, e: JobEvent) {
let tab = app.jobs.opens.remove(i);
match e.outcome {
JobOutcome::Done(v) => {
- if let Err(err) = finish_open(app, &tab.name, tab.path.as_deref(), &v) {
+ if let Err(err) = finish_open(app, &tab.name, tab.path.as_deref(), &v, tab.slot) {
app.open_failed(&tab.name, &err);
}
}
@@ -189,8 +191,13 @@ fn on_event(app: &mut PhotocraftApp, e: JobEvent) {
/// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result
/// (`{document, warnings, color}`).
-fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value) -> Result<(), String> {
- let index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
+fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option<usize>) -> Result<(), String> {
+ let mut index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
+ if let Some(slot) = slot
+ && let Ok(moved) = app.run("document.move", json!({"document": index, "to": slot}))
+ {
+ index = moved.get("document").and_then(Value::as_u64).map_or(index, |i| i as usize);
+ }
let warnings: Vec<String> =
v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default();
app.session.set_active(index);
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 114c12f49..59a41dff4 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -217,6 +217,8 @@ pub struct Recovered {
pub type AppendTextFn = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
/// Requests from the operating system since the last call (see [`OsEvent`]).
pub type OsEventsFn = Box<dyn FnMut() -> Vec<OsEvent>>;
+/// Where the OS pointer is now, in egui points within the window; `None` when unknown.
+pub type CursorPosFn = Box<dyn FnMut(&egui::Context) -> Option<egui::Pos2>>;
/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of
/// I/O dependencies.
@@ -267,6 +269,9 @@ pub struct Services {
pub append_text: Option<AppendTextFn>,
/// OS requests (macOS open-documents / quit Apple events), polled every frame.
pub os_events: Option<OsEventsFn>,
+ /// The pointer position read from the OS (desktop): winit 0.30's file drops carry none, and
+ /// the window gets no pointer events during an OS drag (see `file_open::DropTarget`).
+ pub cursor_pos: Option<CursorPosFn>,
/// The persistent brush preset store, loading in the background (desktop; see
/// `photocraft_engine::preset_store`). Attached to the session once it arrives; without
/// one, brush presets are session-only (web, tests).
@@ -331,6 +336,15 @@ pub struct PhotocraftApp {
fonts_ready: bool,
/// Screen rect of the main canvas last frame (for overlays and the navigator).
pub last_canvas_rect: egui::Rect,
+ /// The document area showing the active document's canvas last frame (not the tabs, the
+ /// start screen or an opening file's card): files dropped here are placed as layers.
+ pub(crate) drop_canvas_rect: Option<egui::Rect>,
+ /// The document tab strip last frame: a drop there opens the file at the slot under it.
+ pub(crate) tab_strip: Option<canvas::TabStrip>,
+ /// Files dropped on the canvas still to place, one Free Transform at a time.
+ pub(crate) drop_places: std::collections::VecDeque<egui::DroppedFileHandle>,
+ /// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`].
+ view_docs: Vec<DocId>,
pub fps: f32,
last_frame_time: f64,
thumbs: HashMap<(photocraft_doc::LayerId, u8), (u64, egui::TextureHandle)>,
@@ -456,6 +470,10 @@ impl PhotocraftApp {
integrated_titlebar: false,
fonts_ready: false,
last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)),
+ drop_canvas_rect: None,
+ tab_strip: None,
+ drop_places: Default::default(),
+ view_docs: Vec::new(),
fps: 0.0,
last_frame_time: 0.0,
thumbs: HashMap::new(),
@@ -632,12 +650,25 @@ impl PhotocraftApp {
r
}
- /// Keep one view per document.
+ /// Keep one view per document, in tab order: a view and its windows stay with their document
+ /// when tabs move (`document.move`) or close.
pub fn sync_views(&mut self) {
crate::lasso_ui::cancel_stale(self);
- let n = self.session.documents().len();
- self.ui.views.resize_with(n, Default::default);
- self.ui.windows.retain(|w| w.document < n);
+ let ids: Vec<DocId> = self.session.documents().iter().map(|d| d.doc.id).collect();
+ // Where the document of view `i` is now. Views not tracked yet keep their index.
+ let now = |i: usize| match self.view_docs.get(i) {
+ Some(id) => ids.iter().position(|d| d == id),
+ None => (i < ids.len()).then_some(i),
+ };
+ let mut views: Vec<Option<state::View>> = ids.iter().map(|_| None).collect();
+ for (i, v) in std::mem::take(&mut self.ui.views).into_iter().enumerate() {
+ if let Some(slot) = now(i).and_then(|to| views.get_mut(to)) {
+ *slot = Some(v);
+ }
+ }
+ self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect();
+ self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some());
+ self.view_docs = ids;
self.prune_thumbs();
self.sync_mask_targets();
// Channel-view textures outlive a hidden view (cheap re-show), not their document.
@@ -961,8 +992,17 @@ impl eframe::App for PhotocraftApp {
}
// Finder double-click / Open With / Dock drops (macOS open-documents events).
self.drain_os_events(ctx);
- // Files dropped onto the window open as documents (with their path, like File › Open).
- self.open_dropped(ctx.input(|i| i.raw.dropped_files.clone()));
+ // While files are dragged over the window it gets no pointer events: keep frames coming so
+ // the tab strip can follow the pointer.
+ if ctx.input(|i| !i.raw.hovered_files.is_empty()) {
+ ctx.request_repaint();
+ }
+ let dropped = ctx.input(|i| i.raw.dropped_files.clone());
+ if !dropped.is_empty() {
+ let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx));
+ self.open_dropped(ctx, dropped, at);
+ }
+ self.place_next_dropped(ctx);
// The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a
// screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.)
if !self.pending_screenshots.is_empty() {
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index dc9f7ab05..35b8efbb5 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -603,15 +603,25 @@ pub struct TransformSession {
/// the Quick Mask by itself (`None`: the layer, with its linked masks).
#[serde(default)]
pub target: Option<serde_json::Value>,
- /// Free Transform on a copy (⌥⌘T): the copy was made for this session, so Cancel takes it back
- /// and OK folds it into the transform's history step (#352).
+ /// The layer was made for this session (⌥⌘T's copy, #352; a file dropped on the canvas), so
+ /// Cancel takes it back and OK folds it into one history step with the transform.
#[serde(default)]
- pub copy: bool,
+ pub made: Option<MadeLayer>,
/// Edit › Transform › Skew / Distort / Perspective (`Free` for Free Transform).
#[serde(default)]
pub mode: TransformMode,
}
+/// Why a Free Transform session's layer was made for it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum MadeLayer {
+ /// Free Transform on a copy (⌥⌘T): OK makes the copy and the transform one Free Transform step.
+ Copy,
+ /// A file dropped on the canvas: OK makes the place and the transform one Place Embedded step.
+ Place,
+}
+
/// In-progress inline type editing (Type tool). Offsets are character indices.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextEdit {
diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs
index dbc1cca52..ee2a12992 100644
--- a/crates/ui-egui/src/transform_tool.rs
+++ b/crates/ui-egui/src/transform_tool.rs
@@ -18,7 +18,7 @@ use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, ViewXform};
-use crate::state::{Tool, TransformMode, TransformSession};
+use crate::state::{MadeLayer, Tool, TransformMode, TransformSession};
/// Which Split button is armed. The guide follows the pointer and the split is added on release.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -190,7 +190,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
warp: None,
selection: false,
target: None,
- copy: false,
+ made: None,
mode: Default::default(),
});
start_steps(app);
@@ -203,17 +203,28 @@ pub fn begin_copy(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St
let selection = app.session.active().is_some_and(|d| d.doc.selection.is_some());
app.run(if selection { "layer.new.layerViaCopy" } else { "layer.duplicate" }, json!({}))?;
if let Err(e) = begin(app, ctx) {
- take_back_copy(app);
+ take_back_made(app);
return Err(e);
}
if let Some(t) = app.ui.transform.as_mut() {
- t.copy = true;
+ t.made = Some(MadeLayer::Copy);
}
Ok(())
}
-/// Undoes the copy a cancelled or failed ⌥⌘T made, leaving nothing to redo.
-fn take_back_copy(app: &mut PhotocraftApp) {
+/// Free Transform on the layer a file dropped on the canvas just placed, like the reference app's
+/// Place: Esc takes the place back, ↩ makes the place and the transform one Place Embedded step.
+pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ begin(app, ctx)?;
+ if let Some(t) = app.ui.transform.as_mut() {
+ t.made = Some(MadeLayer::Place);
+ }
+ Ok(())
+}
+
+/// Undoes the layer a cancelled or failed session made (⌥⌘T's copy, a placed file), leaving
+/// nothing to redo.
+fn take_back_made(app: &mut PhotocraftApp) {
app.session.undo();
if let Some(st) = app.session.active_mut() {
st.history.clear_redo();
@@ -221,10 +232,14 @@ fn take_back_copy(app: &mut PhotocraftApp) {
app.sync_views();
}
-/// After ⌥⌘T's transform: the copy and the transform become one history step (the transform's).
-fn fold_copy(app: &mut PhotocraftApp) {
+/// After the transform: the step that made the layer and the transform become one history step,
+/// the transform's for a copy and Place Embedded for a placed file.
+fn fold_made(app: &mut PhotocraftApp, made: MadeLayer) {
if let Some(st) = app.session.active_mut() {
st.history.purge_last();
+ if made == MadeLayer::Place {
+ st.history.set_current_label(photocraft_engine::file_cmds::PLACE_EMBEDDED);
+ }
}
}
@@ -290,7 +305,7 @@ fn begin_lone(
warp: None,
selection: false,
target: Some(target),
- copy: false,
+ made: None,
mode: Default::default(),
});
start_steps(app);
@@ -349,7 +364,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(
warp: None,
selection: true,
target: None,
- copy: false,
+ made: None,
mode: Default::default(),
});
start_steps(app);
@@ -487,7 +502,7 @@ pub fn commit(app: &mut PhotocraftApp) {
}
return;
}
- let copy = t.copy;
+ let made = t.made;
let r = if let Some(w) = &t.warp {
if w.is_identity() {
return;
@@ -495,7 +510,7 @@ pub fn commit(app: &mut PhotocraftApp) {
app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation}))
} else {
if t.quad == corners(t.rect) {
- return; // untouched: nothing to do and no history step; a ⌥⌘T copy stays
+ return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays
}
let mut p = json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation});
if let Some(target) = t.target {
@@ -504,11 +519,14 @@ pub fn commit(app: &mut PhotocraftApp) {
app.run("edit.transform", p)
};
match r {
- Ok(_) if copy => fold_copy(app),
- Ok(_) => {}
+ Ok(_) => {
+ if let Some(made) = made {
+ fold_made(app, made);
+ }
+ }
Err(e) => {
- if copy {
- take_back_copy(app);
+ if made.is_some() {
+ take_back_made(app);
}
app.ui.status = e;
}
@@ -528,10 +546,10 @@ pub fn end_if_left(app: &mut PhotocraftApp) {
}
pub fn cancel(app: &mut PhotocraftApp) {
- let copy = app.ui.transform.take().is_some_and(|t| t.copy);
+ let made = app.ui.transform.take().is_some_and(|t| t.made.is_some());
app.transform_preview = None;
- if copy {
- take_back_copy(app);
+ if made {
+ take_back_made(app);
}
}
@@ -1536,7 +1554,7 @@ mod tests {
warp: None,
selection: false,
target: None,
- copy: false,
+ made: None,
mode: Default::default(),
}
}
@@ -1783,7 +1801,7 @@ mod tests {
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
let (layers, steps) = (app.session.active().unwrap().doc.layers.len(), app.session.active().unwrap().history.past_len());
crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap();
- assert!(app.ui.transform.as_ref().unwrap().copy);
+ assert_eq!(app.ui.transform.as_ref().unwrap().made, Some(MadeLayer::Copy));
assert!(!crate::menus::is_enabled(&app, "edit.freeTransformCopy"), "one transform at a time");
// Esc: the copy goes too.
cancel(&mut app);
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index e61387d4c..1184ea091 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -825,9 +825,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
Err(e) => return Some(Err(e)),
};
let linked = (id == "file.placeLinked").then(|| name.clone());
- let r = photocraft_engine::file_cmds::place_bytes(&mut app.session, &name, bytes, linked, &json!({})).map_err(|e| e.to_string());
- app.sync_views();
- Some(r)
+ Some(app.place_bytes(&name, bytes, linked))
}
"file.fileInfo" => {
let info = app.session.execute("file.fileInfo", json!({})).ok()?;
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index bcefc2bb7..be5f34f46 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -5,6 +5,19 @@ use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, S
use crate::theme::{self, Tokens};
+/// An accent insertion line on one edge of `r` while a drag hovers it (vertical: on its left or,
+/// `after`, right edge; else on its top or bottom).
+pub fn drop_line(ui: &Ui, r: Rect, after: bool, vertical: bool, t: &Tokens) {
+ let s = Stroke::new(2.0, t.accent);
+ if vertical {
+ let x = if after { r.right() } else { r.left() };
+ ui.painter().line_segment([pos2(x, r.top() + 2.0), pos2(x, r.bottom() - 2.0)], s);
+ } else {
+ let y = if after { r.bottom() } else { r.top() };
+ ui.painter().line_segment([pos2(r.left() + 4.0, y), pos2(r.right() - 4.0, y)], s);
+ }
+}
+
/// Draw a bevelled box (Classic theme) or a flat rounded box.
pub fn surface(ui: &Ui, rect: Rect, fill: Color32, raised: bool) {
let t = Tokens::get(ui.ctx());