mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95c1ab81f3 | ||
|
|
7ae7bda3d3 | ||
|
|
1648e33c1f | ||
|
|
8a38af5be7 | ||
|
|
7c870d9426 | ||
|
|
0882637801 | ||
|
|
9626c047a4 | ||
|
|
3e674c939b | ||
|
|
2a3f1a12a8 | ||
|
|
6ee0239b96 | ||
|
|
244b25708d |
No files matched your search
@@ -302,6 +302,7 @@ jobs:
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -358,7 +359,7 @@ jobs:
|
||||
tar -xzf "$env:RUNNER_TEMP\binaryen.tar.gz" -C $env:RUNNER_TEMP
|
||||
"$env:RUNNER_TEMP\binaryen-version_$env:BINARYEN_VERSION\bin" | Out-File -FilePath $env:GITHUB_PATH -Append
|
||||
|
||||
cargo binstall --no-confirm --force cargo-about
|
||||
cargo binstall --no-confirm --force "cargo-about@$env:CARGO_ABOUT_VERSION"
|
||||
cargo binstall --no-confirm --force "wasm-bindgen-cli@$env:WASM_BINDGEN_CLI_VERSION"
|
||||
|
||||
- name: 🏗 Build Windows bundle
|
||||
@@ -496,6 +497,7 @@ jobs:
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -554,7 +556,7 @@ jobs:
|
||||
fi
|
||||
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
|
||||
|
||||
cargo binstall --no-confirm --force cargo-about
|
||||
cargo binstall --no-confirm --force "cargo-about@${CARGO_ABOUT_VERSION}"
|
||||
cargo binstall --no-confirm --force "wasm-bindgen-cli@${WASM_BINDGEN_CLI_VERSION}"
|
||||
|
||||
- name: 🏗 Build Mac bundle
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "147.0.14+g76d2442+chromium-147.0.7727.138";
|
||||
version = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-Gy2Xs1NHwmIr+buzoqDso1QJVkKlA/UMXytHjNGqpNk=";
|
||||
x86_64-linux = "sha256-os7wAFJ+mVK65HCikvEjhMeQUj2ty7y+6Ad0OlOcbeA=";
|
||||
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
|
||||
Generated
+21
-85
@@ -594,8 +594,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cef"
|
||||
version = "148.1.0+147.0.14"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
|
||||
version = "149.2.0+149.0.5"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ash",
|
||||
@@ -615,14 +615,14 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"wgpu",
|
||||
"windows 0.62.2",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cef-dll-sys"
|
||||
version = "148.1.0+147.0.14"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
|
||||
version = "149.2.0+149.0.5"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cmake",
|
||||
@@ -1223,7 +1223,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1318,7 +1318,7 @@ checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
|
||||
[[package]]
|
||||
name = "download-cef"
|
||||
version = "2.3.2"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite#b36fbe355fdb0cb101295da4554dbb285f2d91f2"
|
||||
source = "git+https://github.com/timon-schelling/cef-rs.git?branch=graphite-149#877c9cd8f7776e6c52e365d501ad44c73e17117a"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"clap",
|
||||
@@ -1474,7 +1474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1931,7 +1931,7 @@ dependencies = [
|
||||
"log",
|
||||
"presser",
|
||||
"thiserror 2.0.18",
|
||||
"windows 0.62.2",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2211,7 +2211,7 @@ dependencies = [
|
||||
"vello",
|
||||
"wgpu",
|
||||
"window_clipboard",
|
||||
"windows 0.58.0",
|
||||
"windows",
|
||||
"winit",
|
||||
]
|
||||
|
||||
@@ -3947,7 +3947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4507,7 +4507,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4983,7 +4983,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5051,7 +5051,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5784,7 +5784,7 @@ dependencies = [
|
||||
"getrandom 0.3.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6999,7 +6999,7 @@ dependencies = [
|
||||
"web-sys",
|
||||
"wgpu-naga-bridge",
|
||||
"wgpu-types",
|
||||
"windows 0.62.2",
|
||||
"windows",
|
||||
"windows-core 0.62.2",
|
||||
"windows-result 0.4.1",
|
||||
]
|
||||
@@ -7056,7 +7056,7 @@ version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7079,16 +7079,6 @@ dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
|
||||
dependencies = [
|
||||
"windows-core 0.58.0",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
@@ -7110,27 +7100,14 @@ dependencies = [
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
|
||||
dependencies = [
|
||||
"windows-implement 0.58.0",
|
||||
"windows-interface 0.58.0",
|
||||
"windows-result 0.2.0",
|
||||
"windows-strings 0.1.0",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
|
||||
dependencies = [
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link 0.1.3",
|
||||
"windows-result 0.3.4",
|
||||
"windows-strings 0.4.2",
|
||||
@@ -7142,8 +7119,8 @@ version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link 0.2.1",
|
||||
"windows-result 0.4.1",
|
||||
"windows-strings 0.5.1",
|
||||
@@ -7160,17 +7137,6 @@ dependencies = [
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
@@ -7182,17 +7148,6 @@ dependencies = [
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.58.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
@@ -7237,15 +7192,6 @@ dependencies = [
|
||||
"windows-strings 0.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.3.4"
|
||||
@@ -7264,16 +7210,6 @@ dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
|
||||
dependencies = [
|
||||
"windows-result 0.2.0",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.4.2"
|
||||
|
||||
+4
-4
@@ -214,8 +214,8 @@ gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "148"
|
||||
cef-dll-sys = "148"
|
||||
cef = "149"
|
||||
cef-dll-sys = "149"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -257,5 +257,5 @@ debug = true
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
|
||||
+1
-1
@@ -55,7 +55,7 @@ window_clipboard = "0.5"
|
||||
|
||||
# Windows-specific dependencies
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows = { version = "0.58.0", features = [
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Dwm",
|
||||
"Win32_Graphics_Gdi",
|
||||
|
||||
@@ -61,9 +61,9 @@ impl NativeWindowHandle {
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
main,
|
||||
Some(main),
|
||||
None,
|
||||
None,
|
||||
HINSTANCE(std::ptr::null_mut()),
|
||||
// Pass the main window's HWND to WM_NCCREATE so the helper can store it.
|
||||
Some(&main as *const _ as _),
|
||||
)
|
||||
@@ -103,18 +103,36 @@ impl NativeWindowHandle {
|
||||
};
|
||||
let _ = unsafe { DwmExtendFrameIntoClientArea(main, &margins) };
|
||||
|
||||
let hinst = unsafe { GetModuleHandleW(None) }.unwrap();
|
||||
let hinst: HINSTANCE = unsafe { GetModuleHandleW(None) }.unwrap().into();
|
||||
|
||||
// Set taskbar icon
|
||||
if let Ok(big) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_SHARED) } {
|
||||
if let Ok(big) = unsafe {
|
||||
LoadImageW(
|
||||
Some(hinst),
|
||||
PCWSTR(1usize as *const u16),
|
||||
IMAGE_ICON,
|
||||
GetSystemMetrics(SM_CXICON),
|
||||
GetSystemMetrics(SM_CYICON),
|
||||
LR_SHARED,
|
||||
)
|
||||
} {
|
||||
unsafe { SetClassLongPtrW(main, GCLP_HICON, big.0 as isize) };
|
||||
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_BIG as usize), LPARAM(big.0 as isize)) };
|
||||
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_BIG as usize)), Some(LPARAM(big.0 as isize))) };
|
||||
}
|
||||
|
||||
// Set window icon
|
||||
if let Ok(small) = unsafe { LoadImageW(hinst, PCWSTR(1usize as *const u16), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED) } {
|
||||
if let Ok(small) = unsafe {
|
||||
LoadImageW(
|
||||
Some(hinst),
|
||||
PCWSTR(1usize as *const u16),
|
||||
IMAGE_ICON,
|
||||
GetSystemMetrics(SM_CXSMICON),
|
||||
GetSystemMetrics(SM_CYSMICON),
|
||||
LR_SHARED,
|
||||
)
|
||||
} {
|
||||
unsafe { SetClassLongPtrW(main, GCLP_HICONSM, small.0 as isize) };
|
||||
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_SMALL as usize), LPARAM(small.0 as isize)) };
|
||||
unsafe { SendMessageW(main, WM_SETICON, Some(WPARAM(ICON_SMALL as usize)), Some(LPARAM(small.0 as isize))) };
|
||||
}
|
||||
|
||||
// Force window update
|
||||
@@ -197,7 +215,7 @@ unsafe fn ensure_helper_class() {
|
||||
lpfnWndProc: Some(helper_window_handle_message),
|
||||
hInstance: unsafe { GetModuleHandleW(None).unwrap().into() },
|
||||
hIcon: HICON::default(),
|
||||
hCursor: unsafe { LoadCursorW(HINSTANCE(std::ptr::null_mut()), IDC_ARROW).unwrap() },
|
||||
hCursor: unsafe { LoadCursorW(None, IDC_ARROW).unwrap() },
|
||||
// No painting; the ring is invisible.
|
||||
hbrBackground: HBRUSH::default(),
|
||||
lpszClassName: PCWSTR(class_name.as_ptr()),
|
||||
@@ -292,7 +310,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
|
||||
// Extract the main window's HWND from GWLP_USERDATA that we saved earlier.
|
||||
let main_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *mut std::ffi::c_void;
|
||||
let main = HWND(main_ptr);
|
||||
if unsafe { IsWindow(main).as_bool() } {
|
||||
if unsafe { IsWindow(Some(main)).as_bool() } {
|
||||
let Some(wmsz) = (unsafe { calculate_resize_direction(hwnd, lparam) }) else {
|
||||
return LRESULT(0);
|
||||
};
|
||||
@@ -301,7 +319,7 @@ unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wpa
|
||||
let _ = unsafe { SetForegroundWindow(main) };
|
||||
|
||||
// Start sizing on the main window in the calculated direction. (SC_SIZE + WMSZ_*)
|
||||
let _ = unsafe { PostMessageW(main, WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
|
||||
let _ = unsafe { PostMessageW(Some(main), WM_SYSCOMMAND, WPARAM((SC_SIZE + wmsz) as usize), lparam) };
|
||||
}
|
||||
return LRESULT(0);
|
||||
}
|
||||
@@ -325,7 +343,7 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
|
||||
let w = (r.right - r.left) + RESIZE_BAND_THICKNESS * 2;
|
||||
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
|
||||
|
||||
let _ = unsafe { SetWindowPos(helper, main, x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
|
||||
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
|
||||
}
|
||||
|
||||
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
|
||||
|
||||
+8
-136
@@ -186,7 +186,14 @@ impl Dispatcher {
|
||||
self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {});
|
||||
}
|
||||
Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Clipboard(message) => self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Clipboard(message) => {
|
||||
let context = ClipboardMessageContext {
|
||||
portfolio: &mut self.message_handlers.portfolio_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
resource_storage: &self.message_handlers.resource_storage_message_handler,
|
||||
};
|
||||
self.message_handlers.clipboard_message_handler.process_message(message, &mut queue, context);
|
||||
}
|
||||
Message::ColorPicker(message) => self.message_handlers.color_picker_message_handler.process_message(message, &mut queue, ()),
|
||||
Message::Debug(message) => {
|
||||
self.message_handlers.debug_message_handler.process_message(message, &mut queue, ());
|
||||
@@ -419,141 +426,6 @@ impl Dispatcher {
|
||||
mod test {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
|
||||
/// Create an editor with three layers
|
||||
/// 1. A red rectangle
|
||||
/// 2. A blue shape
|
||||
/// 3. A green ellipse
|
||||
async fn create_editor_with_three_layers() -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
editor.new_document().await;
|
||||
|
||||
editor.select_primary_color(Color::RED).await;
|
||||
editor.draw_rect(100., 200., 300., 400.).await;
|
||||
|
||||
editor.select_primary_color(Color::BLUE).await;
|
||||
editor.draw_polygon(10., 1200., 1300., 400.).await;
|
||||
|
||||
editor.select_primary_color(Color::GREEN).await;
|
||||
editor.draw_ellipse(104., 1200., 1300., 400.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// - create rect, shape and ellipse
|
||||
/// - copy
|
||||
/// - paste
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
async fn copy_paste_single_layer() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteIntoFolder {
|
||||
clipboard: Clipboard::Internal,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
})
|
||||
.await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 4);
|
||||
|
||||
// Existing layers are unaffected
|
||||
for i in 0..=2 {
|
||||
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
/// - create rect, shape and ellipse
|
||||
/// - select shape
|
||||
/// - copy
|
||||
/// - paste
|
||||
/// - assert that shape was copied
|
||||
#[tokio::test]
|
||||
async fn copy_paste_single_layer_from_middle() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
let shape_id = editor.active_document().metadata().all_layers().nth(1).unwrap();
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![shape_id.to_node()] }).await;
|
||||
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteIntoFolder {
|
||||
clipboard: Clipboard::Internal,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
})
|
||||
.await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 4);
|
||||
|
||||
// Existing layers are unaffected
|
||||
for i in 0..=2 {
|
||||
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
/// - create rect, shape and ellipse
|
||||
/// - select ellipse and rect
|
||||
/// - copy
|
||||
/// - delete
|
||||
/// - create another rect
|
||||
/// - paste
|
||||
/// - paste
|
||||
#[tokio::test]
|
||||
async fn copy_paste_deleted_layers() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 3);
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
let rect_id = layers_before_copy[0];
|
||||
let shape_id = layers_before_copy[1];
|
||||
let ellipse_id = layers_before_copy[2];
|
||||
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: vec![rect_id.to_node(), ellipse_id.to_node()],
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(PortfolioMessage::Copy { clipboard: Clipboard::Internal }).await;
|
||||
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
|
||||
editor.draw_rect(0., 800., 12., 200.).await;
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteIntoFolder {
|
||||
clipboard: Clipboard::Internal,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
})
|
||||
.await;
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteIntoFolder {
|
||||
clipboard: Clipboard::Internal,
|
||||
parent: LayerNodeIdentifier::ROOT_PARENT,
|
||||
insert_index: 0,
|
||||
})
|
||||
.await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 6);
|
||||
|
||||
println!("{layers_after_copy:?} {layers_before_copy:?}");
|
||||
|
||||
assert_eq!(layers_after_copy[5], shape_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
/// This test will fail when you make changes to the underlying serialization format for a document.
|
||||
async fn check_if_demo_art_opens() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardVectorEntry};
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, Clipboard)]
|
||||
@@ -10,4 +10,11 @@ pub enum ClipboardMessage {
|
||||
ReadClipboard { content: ClipboardContentRaw },
|
||||
ReadSelection { content: Option<String>, cut: bool },
|
||||
Write { content: ClipboardContent },
|
||||
|
||||
CopyLayers,
|
||||
CutLayers,
|
||||
WriteItems { items: Vec<ClipboardItem> },
|
||||
PasteItems { data: String },
|
||||
PasteLayers { entries: Vec<ClipboardLayer> },
|
||||
PasteVectors { paths: Vec<ClipboardVectorEntry> },
|
||||
}
|
||||
@@ -1,36 +1,58 @@
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw};
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::clipboard::utility_types::{ClipboardContent, ClipboardContentRaw, ClipboardItem, ClipboardLayer, ClipboardResource, ResourceData};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface;
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
use graphite_proc_macros::{ExtractField, message_handler_data};
|
||||
use std::sync::Arc;
|
||||
|
||||
const CLIPBOARD_PREFIX_LAYER: &str = "graphite/layer: ";
|
||||
const CLIPBOARD_PREFIX_NODES: &str = "graphite/nodes: ";
|
||||
const CLIPBOARD_PREFIX_VECTOR: &str = "graphite/vector: ";
|
||||
const CLIPBOARD_PREFIX: &str = "graphite: ";
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct ClipboardMessageContext<'a> {
|
||||
pub portfolio: &'a mut PortfolioMessageHandler,
|
||||
pub current_tool: &'a ToolType,
|
||||
pub resource_storage: &'a ResourceStorageMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct ClipboardMessageHandler {}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
|
||||
fn process_message(&mut self, message: ClipboardMessage, responses: &mut std::collections::VecDeque<Message>, _: ()) {
|
||||
impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for ClipboardMessageHandler {
|
||||
fn process_message(&mut self, message: ClipboardMessage, responses: &mut std::collections::VecDeque<Message>, context: ClipboardMessageContext) {
|
||||
let ClipboardMessageContext {
|
||||
portfolio,
|
||||
current_tool,
|
||||
resource_storage,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
ClipboardMessage::Cut => responses.add(FrontendMessage::TriggerSelectionRead { cut: true }),
|
||||
ClipboardMessage::Copy => responses.add(FrontendMessage::TriggerSelectionRead { cut: false }),
|
||||
ClipboardMessage::Paste => responses.add(FrontendMessage::TriggerClipboardRead),
|
||||
ClipboardMessage::ReadClipboard { content } => match content {
|
||||
ClipboardContentRaw::Text(text) => {
|
||||
if let Some(layer) = text.strip_prefix(CLIPBOARD_PREFIX_LAYER) {
|
||||
responses.add(PortfolioMessage::PasteSerializedData { data: layer.to_string() });
|
||||
} else if let Some(nodes) = text.strip_prefix(CLIPBOARD_PREFIX_NODES) {
|
||||
responses.add(NodeGraphMessage::PasteNodes { serialized_nodes: nodes.to_string() });
|
||||
} else if let Some(vector) = text.strip_prefix(CLIPBOARD_PREFIX_VECTOR) {
|
||||
responses.add(PortfolioMessage::PasteSerializedVector { data: vector.to_string() });
|
||||
if let Some(graphite) = text.strip_prefix(CLIPBOARD_PREFIX) {
|
||||
responses.add(ClipboardMessage::PasteItems { data: graphite.to_string() });
|
||||
} else {
|
||||
responses.add(FrontendMessage::TriggerSelectionWrite { content: text });
|
||||
}
|
||||
}
|
||||
ClipboardContentRaw::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::PasteSvg {
|
||||
responses.add(PortfolioMessage::InsertSvg {
|
||||
svg,
|
||||
name: None,
|
||||
mouse: None,
|
||||
@@ -38,7 +60,7 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
|
||||
});
|
||||
}
|
||||
ClipboardContentRaw::Image { data, width, height } => {
|
||||
responses.add(PortfolioMessage::PasteImage {
|
||||
responses.add(PortfolioMessage::InsertImage {
|
||||
image: Image::from_image_data(&data, width, height),
|
||||
name: None,
|
||||
mouse: None,
|
||||
@@ -47,15 +69,14 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
|
||||
}
|
||||
},
|
||||
ClipboardMessage::ReadSelection { content, cut } => {
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
if let Some(text) = content {
|
||||
responses.add(ClipboardMessage::Write {
|
||||
content: ClipboardContent::Text(text),
|
||||
});
|
||||
} else if cut {
|
||||
responses.add(PortfolioMessage::Cut { clipboard: Clipboard::Device });
|
||||
responses.add(ClipboardMessage::CutLayers);
|
||||
} else {
|
||||
responses.add(PortfolioMessage::Copy { clipboard: Clipboard::Device });
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
}
|
||||
}
|
||||
ClipboardMessage::Write { content } => {
|
||||
@@ -68,13 +89,381 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
|
||||
log::error!("Image copying is not yet supported");
|
||||
return;
|
||||
}
|
||||
ClipboardContent::Layer(layer) => format!("{CLIPBOARD_PREFIX_LAYER}{layer}"),
|
||||
ClipboardContent::Nodes(nodes) => format!("{CLIPBOARD_PREFIX_NODES}{nodes}"),
|
||||
ClipboardContent::Vector(vector) => format!("{CLIPBOARD_PREFIX_VECTOR}{vector}"),
|
||||
ClipboardContent::Graphite(graphite) => format!("{CLIPBOARD_PREFIX}{graphite}"),
|
||||
ClipboardContent::Text(text) => text,
|
||||
};
|
||||
responses.add(FrontendMessage::TriggerClipboardWrite { content: text });
|
||||
}
|
||||
|
||||
ClipboardMessage::CopyLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active_document) = portfolio.active_document_id.and_then(|id| portfolio.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if active_document.graph_view_overlay_open() {
|
||||
responses.add(NodeGraphMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
|
||||
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
ordered_last_elements.sort_by_key(|layer| {
|
||||
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
|
||||
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
|
||||
});
|
||||
|
||||
for layer in ordered_last_elements.into_iter() {
|
||||
let layer_node_id = layer.to_node();
|
||||
|
||||
let mut copy_ids = HashMap::new();
|
||||
copy_ids.insert(layer_node_id, NodeId(0));
|
||||
|
||||
active_document
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(vec![layer_node_id], &[], network_interface::FlowType::LayerChildrenUpstreamFlow)
|
||||
.enumerate()
|
||||
.for_each(|(index, node_id)| {
|
||||
copy_ids.insert(node_id, NodeId((index + 1) as u64));
|
||||
});
|
||||
|
||||
// The layer panel keys collapse state on the top-down path of node IDs down to the layer
|
||||
let mut tree_path = layer
|
||||
.ancestors(active_document.metadata())
|
||||
.filter(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT)
|
||||
.map(|ancestor| ancestor.to_node())
|
||||
.collect::<Vec<_>>();
|
||||
tree_path.reverse();
|
||||
|
||||
buffer.push(ClipboardLayer {
|
||||
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
||||
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
|
||||
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
|
||||
collapsed: active_document.collapsed.0.contains(&tree_path),
|
||||
});
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: buffer.into_iter().map(ClipboardItem::Layer).collect(),
|
||||
});
|
||||
}
|
||||
ClipboardMessage::CutLayers => {
|
||||
if current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(active_document) = portfolio.active_document()
|
||||
&& active_document.graph_view_overlay_open()
|
||||
{
|
||||
responses.add(NodeGraphMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(ClipboardMessage::CopyLayers);
|
||||
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||
}
|
||||
ClipboardMessage::WriteItems { items } => {
|
||||
let has_content = items.iter().any(|item| match item {
|
||||
ClipboardItem::Layer(entry) => !entry.nodes.is_empty(),
|
||||
ClipboardItem::Nodes(nodes) => !nodes.is_empty(),
|
||||
ClipboardItem::Vector(vector) => !vector.is_empty(),
|
||||
ClipboardItem::Resource(_) => true,
|
||||
});
|
||||
if !has_content {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut resource_ids = HashSet::new();
|
||||
for item in &items {
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => entry
|
||||
.nodes
|
||||
.iter()
|
||||
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
|
||||
ClipboardItem::Nodes(nodes) => nodes
|
||||
.iter()
|
||||
.for_each(|(_, template)| network_interface::collect_node_resources(&template.document_node, &mut resource_ids)),
|
||||
ClipboardItem::Vector(_) | ClipboardItem::Resource(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Snapshot each resource's registry entry; embedded ones also need their bytes
|
||||
let mut resources = Vec::new();
|
||||
let mut bytes_to_load = Vec::new();
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
for id in resource_ids {
|
||||
let Some(info) = document.resources.registry.info(&id) else { continue };
|
||||
if let Some(hash) = info.hash
|
||||
&& info.sources.contains(&DataSource::Embedded)
|
||||
{
|
||||
bytes_to_load.push((resources.len(), *hash));
|
||||
}
|
||||
resources.push(ClipboardResource {
|
||||
id,
|
||||
hash: info.hash.copied(),
|
||||
sources: info.sources.to_vec(),
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if bytes_to_load.is_empty() {
|
||||
let mut items = items;
|
||||
items.extend(resources.into_iter().map(ClipboardItem::Resource));
|
||||
if let Some(content) = serialize_clipboard(&items) {
|
||||
responses.add(ClipboardMessage::Write { content });
|
||||
}
|
||||
} else {
|
||||
// Load the embedded bytes from the resource storage, then write
|
||||
let load_handle = resource_storage.resources();
|
||||
responses.add(async move {
|
||||
let mut resources = resources;
|
||||
for (index, hash) in bytes_to_load {
|
||||
if let Some(resource) = load_handle.load(hash).await {
|
||||
resources[index].data = Some(ResourceData(resource.as_ref().to_vec()));
|
||||
}
|
||||
}
|
||||
let mut items = items;
|
||||
items.extend(resources.into_iter().map(ClipboardItem::Resource));
|
||||
match serialize_clipboard(&items) {
|
||||
Some(content) => ClipboardMessage::Write { content }.into(),
|
||||
None => Message::NoOp,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteItems { data } => {
|
||||
let items = match serde_json::from_str::<Vec<ClipboardItem>>(&data) {
|
||||
Ok(items) => items,
|
||||
Err(error) => {
|
||||
log::error!("Failed to deserialize clipboard payload: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut layers = Vec::new();
|
||||
let mut node_groups = Vec::new();
|
||||
let mut vectors = Vec::new();
|
||||
let mut resources = Vec::new();
|
||||
for item in items {
|
||||
match item {
|
||||
ClipboardItem::Layer(entry) => layers.push(entry),
|
||||
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
|
||||
ClipboardItem::Vector(vector) => vectors.push(vector),
|
||||
ClipboardItem::Resource(resource) => resources.push(resource),
|
||||
}
|
||||
}
|
||||
|
||||
// Re-register the carried resources and store their bytes
|
||||
let mut needs_resolve = false;
|
||||
if !resources.is_empty()
|
||||
&& let Some(document) = portfolio.active_document_mut()
|
||||
{
|
||||
for resource in resources {
|
||||
if document.resources.registry.contains(&resource.id) {
|
||||
continue;
|
||||
}
|
||||
for source in resource.sources {
|
||||
document.resources.registry.push_source_back(&resource.id, source);
|
||||
}
|
||||
match resource.data {
|
||||
Some(data) => match resource.hash {
|
||||
Some(hash) if ResourceHash::from(data.0.as_slice()) == hash => {
|
||||
document.resources.registry.resolve(&resource.id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data: Arc::from(data.0) });
|
||||
}
|
||||
_ => warn!("Discarding pasted resource {:?}: embedded bytes do not match its advertised hash", resource.id),
|
||||
},
|
||||
None => needs_resolve = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Paste the content through the existing per-type handlers
|
||||
if !layers.is_empty() {
|
||||
responses.add(ClipboardMessage::PasteLayers { entries: layers });
|
||||
}
|
||||
for nodes in node_groups {
|
||||
responses.add(NodeGraphMessage::InsertNodes { nodes });
|
||||
}
|
||||
for paths in vectors {
|
||||
responses.add(ClipboardMessage::PasteVectors { paths });
|
||||
}
|
||||
|
||||
// Re-resolve resources that carried no bytes (URL- or font-backed)
|
||||
if needs_resolve && let Some(document_id) = portfolio.active_document_id {
|
||||
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteLayers { entries } => {
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let parent = document.new_layer_parent(false);
|
||||
|
||||
// Top-down node ID path of the destination parent, used to derive each pasted layer's collapse path
|
||||
let mut parent_tree_path = parent
|
||||
.ancestors(document.metadata())
|
||||
.filter(|ancestor| *ancestor != LayerNodeIdentifier::ROOT_PARENT)
|
||||
.map(|ancestor| ancestor.to_node())
|
||||
.collect::<Vec<_>>();
|
||||
parent_tree_path.reverse();
|
||||
|
||||
let mut all_new_ids = Vec::new();
|
||||
let mut layers = Vec::new();
|
||||
|
||||
let mut added_nodes = false;
|
||||
|
||||
for entry in entries.into_iter().rev() {
|
||||
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let Some(&root_id) = new_ids.get(&NodeId(0)) else {
|
||||
warn!("Skipping pasted layer missing its root node");
|
||||
continue;
|
||||
};
|
||||
let layer = LayerNodeIdentifier::new_unchecked(root_id);
|
||||
|
||||
if !added_nodes {
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
all_new_ids.extend(new_ids.values().copied());
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
||||
|
||||
// Restore the copied layer's visibility, lock, and collapse state
|
||||
if !entry.visible {
|
||||
responses.add(NodeGraphMessage::SetVisibility {
|
||||
node_id: root_id,
|
||||
network_path: Vec::new(),
|
||||
visible: false,
|
||||
});
|
||||
}
|
||||
if entry.locked {
|
||||
responses.add(NodeGraphMessage::SetLocked {
|
||||
node_id: root_id,
|
||||
network_path: Vec::new(),
|
||||
locked: true,
|
||||
});
|
||||
}
|
||||
if entry.collapsed {
|
||||
let mut tree_path = parent_tree_path.clone();
|
||||
tree_path.push(root_id);
|
||||
responses.add(DocumentMessage::ToggleLayerExpansion { tree_path, recursive: false });
|
||||
}
|
||||
|
||||
layers.push(layer);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
ClipboardMessage::PasteVectors { paths } => {
|
||||
// If using Path tool then send the operation to Path tool
|
||||
// TODO: Consider if this is actually the correct place to put this logic
|
||||
// TODO: Consider making paste in general go through the current tool, so that the tool can decide what to do
|
||||
if *current_tool == ToolType::Path {
|
||||
responses.add(PathToolMessage::Paste { paths });
|
||||
return;
|
||||
}
|
||||
|
||||
// If not using Path tool, create new layers and add paths into those
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let mut layers = Vec::new();
|
||||
|
||||
for (_, new_vector, transform) in paths {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
error!("Path node does not exist");
|
||||
continue;
|
||||
};
|
||||
let nodes = vec![(NodeId(0), node_type.default_node_template())];
|
||||
|
||||
let parent = document.new_layer_parent(false);
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
layers.push(layer);
|
||||
|
||||
// Adding the transform back into the layer
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform,
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
// Add default fill and stroke to the layer
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
|
||||
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
|
||||
warn!("Skipping pasted vector segment with an unknown endpoint");
|
||||
continue;
|
||||
};
|
||||
|
||||
let new_segment_id = SegmentId::generate();
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let handles = match bezier.handles {
|
||||
BezierHandles::Linear => [None, None],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
|
||||
};
|
||||
|
||||
let points = [start_point, end_point];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
let to_new_handle = |handle: HandleId| -> Option<HandleId> {
|
||||
Some(HandleId {
|
||||
ty: handle.ty,
|
||||
segment: *segments_map.get(&handle.segment)?,
|
||||
})
|
||||
};
|
||||
let (Some(first), Some(second)) = (to_new_handle(handles[0]), to_new_handle(handles[1])) else {
|
||||
continue;
|
||||
};
|
||||
let modification_type = VectorModificationType::SetG1Continuous {
|
||||
handles: [first, second],
|
||||
enabled: true,
|
||||
};
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers }.into()],
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
advertise_actions!(ClipboardMessageDiscriminant;
|
||||
@@ -83,3 +472,183 @@ impl MessageHandler<ClipboardMessage, ()> for ClipboardMessageHandler {
|
||||
Paste,
|
||||
);
|
||||
}
|
||||
|
||||
/// Serialize the clipboard items, logging on failure.
|
||||
fn serialize_clipboard(items: &[ClipboardItem]) -> Option<ClipboardContent> {
|
||||
match serde_json::to_string(items) {
|
||||
Ok(data) => Some(ClipboardContent::Graphite(data)),
|
||||
Err(error) => {
|
||||
log::error!("Failed to serialize clipboard payload: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardResource, ResourceData};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
|
||||
|
||||
/// Create an editor with three layers
|
||||
/// 1. A red rectangle
|
||||
/// 2. A blue shape
|
||||
/// 3. A green ellipse
|
||||
async fn create_editor_with_three_layers() -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
editor.new_document().await;
|
||||
|
||||
editor.select_primary_color(Color::RED).await;
|
||||
editor.draw_rect(100., 200., 300., 400.).await;
|
||||
|
||||
editor.select_primary_color(Color::BLUE).await;
|
||||
editor.draw_polygon(10., 1200., 1300., 400.).await;
|
||||
|
||||
editor.select_primary_color(Color::GREEN).await;
|
||||
editor.draw_ellipse(104., 1200., 1300., 400.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// Copies the layer selection and returns the written clipboard payload.
|
||||
async fn copy_layers_to_clipboard(editor: &mut EditorTestUtils) -> String {
|
||||
editor
|
||||
.handle_message(ClipboardMessage::CopyLayers)
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("copying layers should write a payload to the clipboard")
|
||||
}
|
||||
|
||||
/// Pastes a clipboard string as if read from the system clipboard.
|
||||
async fn paste_from_clipboard(editor: &mut EditorTestUtils, clipboard: &str) {
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard.to_string()),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// - create rect, shape and ellipse
|
||||
/// - copy
|
||||
/// - paste
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
async fn copy_paste_single_layer() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
paste_from_clipboard(&mut editor, &clipboard).await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 4);
|
||||
|
||||
// Existing layers are unaffected
|
||||
for i in 0..=2 {
|
||||
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
/// - create rect, shape and ellipse
|
||||
/// - select shape
|
||||
/// - copy
|
||||
/// - paste
|
||||
/// - assert that shape was copied
|
||||
#[tokio::test]
|
||||
async fn copy_paste_single_layer_from_middle() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
let shape_id = editor.active_document().metadata().all_layers().nth(1).unwrap();
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![shape_id.to_node()] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
paste_from_clipboard(&mut editor, &clipboard).await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 4);
|
||||
|
||||
// Existing layers are unaffected
|
||||
for i in 0..=2 {
|
||||
assert_eq!(layers_before_copy[i], layers_after_copy[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
/// - create rect, shape and ellipse
|
||||
/// - select ellipse and rect
|
||||
/// - copy
|
||||
/// - delete
|
||||
/// - create another rect
|
||||
/// - paste
|
||||
/// - paste
|
||||
#[tokio::test]
|
||||
async fn copy_paste_deleted_layers() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 3);
|
||||
|
||||
let layers_before_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
let rect_id = layers_before_copy[0];
|
||||
let shape_id = layers_before_copy[1];
|
||||
let ellipse_id = layers_before_copy[2];
|
||||
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: vec![rect_id.to_node(), ellipse_id.to_node()],
|
||||
})
|
||||
.await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
editor.handle_message(NodeGraphMessage::DeleteSelectedNodes { delete_children: true }).await;
|
||||
editor.draw_rect(0., 800., 12., 200.).await;
|
||||
paste_from_clipboard(&mut editor, &clipboard).await;
|
||||
paste_from_clipboard(&mut editor, &clipboard).await;
|
||||
|
||||
let layers_after_copy = editor.active_document().metadata().all_layers().collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(layers_before_copy.len(), 3);
|
||||
assert_eq!(layers_after_copy.len(), 6);
|
||||
|
||||
assert_eq!(layers_after_copy[5], shape_id);
|
||||
}
|
||||
|
||||
/// A pasted `graphite:` payload re-registers the resources it carries into the active document.
|
||||
#[tokio::test]
|
||||
async fn paste_carries_embedded_resource() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let id = ResourceId::new();
|
||||
assert!(!editor.active_document().resources.registry.contains(&id));
|
||||
|
||||
// Carry the resource and its bytes through the clipboard
|
||||
let bytes = b"a pretend png".to_vec();
|
||||
let hash = ResourceHash::from(bytes.as_slice());
|
||||
let items = vec![ClipboardItem::Resource(ClipboardResource {
|
||||
id,
|
||||
hash: Some(hash),
|
||||
sources: vec![DataSource::Embedded],
|
||||
data: Some(ResourceData(bytes)),
|
||||
})];
|
||||
let payload = format!("graphite: {}", serde_json::to_string(&items).unwrap());
|
||||
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(payload),
|
||||
})
|
||||
.await;
|
||||
|
||||
let registry = &editor.active_document().resources.registry;
|
||||
assert!(registry.contains(&id), "the carried resource should be registered after paste");
|
||||
assert_eq!(registry.hash(&id), Some(hash), "the carried resource should resolve to the carried bytes' hash");
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,4 @@ pub mod utility_types;
|
||||
#[doc(inline)]
|
||||
pub use clipboard_message::{ClipboardMessage, ClipboardMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use clipboard_message_handler::ClipboardMessageHandler;
|
||||
pub use clipboard_message_handler::{ClipboardMessageContext, ClipboardMessageHandler};
|
||||
@@ -1,3 +1,12 @@
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContentRaw {
|
||||
Text(String),
|
||||
@@ -7,10 +16,55 @@ pub enum ClipboardContentRaw {
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardContent {
|
||||
Layer(String),
|
||||
Nodes(String),
|
||||
Vector(String),
|
||||
Graphite(String),
|
||||
Text(String),
|
||||
Svg(String),
|
||||
Image { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2);
|
||||
|
||||
/// An entry in the `graphite:` clipboard payload.
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ClipboardItem {
|
||||
Layer(ClipboardLayer),
|
||||
Nodes(Vec<(NodeId, NodeTemplate)>),
|
||||
Vector(Vec<ClipboardVectorEntry>),
|
||||
Resource(ClipboardResource),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ClipboardLayer {
|
||||
pub nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ClipboardResource {
|
||||
pub id: ResourceId,
|
||||
pub hash: Option<ResourceHash>,
|
||||
pub sources: Vec<DataSource>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data: Option<ResourceData>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone)]
|
||||
pub struct ResourceData(pub Vec<u8>);
|
||||
impl std::fmt::Debug for ResourceData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResourceData").field("len", &self.0.len()).finish()
|
||||
}
|
||||
}
|
||||
impl serde::Serialize for ResourceData {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(&BASE64.encode(&self.0))
|
||||
}
|
||||
}
|
||||
impl<'de> serde::Deserialize<'de> for ResourceData {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let encoded = String::deserialize(deserializer)?;
|
||||
Ok(Self(BASE64.decode(&encoded).map_err(serde::de::Error::custom)?))
|
||||
}
|
||||
}
|
||||
@@ -339,6 +339,31 @@ impl ColorPickerMessageHandler {
|
||||
self.snapshot_old();
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::InsertDuplicate { index, position } => {
|
||||
let source = index as usize;
|
||||
let Some(insert_index) = gradient.duplicate_stop(source, position) else { return };
|
||||
// The dragged stop (the duplication source) stays active. Its index shifts up if the frozen copy landed at or before it.
|
||||
let dragged_index = if insert_index <= source { source + 1 } else { source };
|
||||
self.active_marker_index = Some(dragged_index as u32);
|
||||
self.active_marker_is_midpoint = false;
|
||||
}
|
||||
SpectrumInputUpdate::RemoveDuplicate { index } => {
|
||||
let anchor = index as usize;
|
||||
if anchor >= gradient.position.len() || gradient.position.len() <= 2 {
|
||||
return;
|
||||
}
|
||||
// Never remove the active (dragged) stop itself, this should only ever target the frozen copy.
|
||||
if self.active_marker_index == Some(anchor as u32) {
|
||||
return;
|
||||
}
|
||||
gradient.remove(anchor);
|
||||
// Keep the dragged stop active. Its index shifts down if the removed copy came before it.
|
||||
if let Some(active) = self.active_marker_index
|
||||
&& (anchor as u32) < active
|
||||
{
|
||||
self.active_marker_index = Some(active - 1);
|
||||
}
|
||||
}
|
||||
SpectrumInputUpdate::DeleteMarker { index } => {
|
||||
// Enforce minimum stop count. The gradient editor needs at least 2 stops to remain meaningful.
|
||||
if gradient.position.len() <= 2 || (index as usize) >= gradient.position.len() {
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::messages::input_mapper::utility_types::macros::*;
|
||||
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
|
||||
use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapping};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpdate;
|
||||
@@ -224,8 +223,8 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(Backspace); modifiers=[Accel], action_dispatch=PathToolMessage::DeleteAndBreakPath),
|
||||
entry!(KeyDown(Delete); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
|
||||
entry!(KeyDown(Backspace); modifiers=[Shift], action_dispatch=PathToolMessage::BreakPath),
|
||||
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PathToolMessage::Cut { clipboard: Clipboard::Device }),
|
||||
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PathToolMessage::Copy { clipboard: Clipboard::Device }),
|
||||
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PathToolMessage::Cut),
|
||||
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PathToolMessage::Copy),
|
||||
entry!(KeyDown(KeyD); modifiers=[Accel], action_dispatch=PathToolMessage::Duplicate),
|
||||
entry!(KeyDownNoRepeat(Tab); action_dispatch=PathToolMessage::SwapSelectedHandles),
|
||||
entry!(KeyDown(MouseLeft); action_dispatch=PathToolMessage::MouseDown { extend_selection: Shift, lasso_select: Control, handle_drag_from_anchor: Alt, drag_restore_handle: Control, segment_editing_modifier: Control }),
|
||||
@@ -447,8 +446,6 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
entry!(KeyDown(KeyW); modifiers=[Accel, Alt], action_dispatch=PortfolioMessage::CloseAllDocumentsWithConfirmation),
|
||||
entry!(KeyDown(KeyO); modifiers=[Accel], action_dispatch=PortfolioMessage::Open),
|
||||
entry!(KeyDown(KeyI); modifiers=[Accel], action_dispatch=PortfolioMessage::Import),
|
||||
entry!(KeyDown(KeyX); modifiers=[Accel], action_dispatch=PortfolioMessage::Cut { clipboard: Clipboard::Device }),
|
||||
entry!(KeyDown(KeyC); modifiers=[Accel], action_dispatch=PortfolioMessage::Copy { clipboard: Clipboard::Device }),
|
||||
entry!(KeyDown(KeyR); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleRulers),
|
||||
entry!(KeyDown(KeyD); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleDataPanelOpen),
|
||||
entry!(KeyDown(Enter); modifiers=[Alt], action_dispatch=PortfolioMessage::ToggleFocusDocument),
|
||||
|
||||
@@ -370,14 +370,25 @@ pub struct WidgetTable {
|
||||
pub unstyled: bool,
|
||||
}
|
||||
|
||||
/// A collapsible Properties panel section for a single node: a header with its name and pin, delete, and visibility controls, above its input parameter widgets.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct WidgetSection {
|
||||
/// The node's name shown in the section header: its given alias with the implementation name in parentheses, or just the implementation name.
|
||||
pub name: String,
|
||||
/// The node definition's description, shown as the header's tooltip (empty when it has none).
|
||||
pub description: String,
|
||||
/// Whether the node is visible rather than hidden (shown as the eye icon).
|
||||
pub visible: bool,
|
||||
/// Whether the node is pinned, keeping its section shown in the Properties panel when nothing is selected (shown as the pin icon).
|
||||
pub pinned: bool,
|
||||
/// Whether this section can be dragged to reorder it within its layer's chain of nodes (true for a layer chain's nodes, but not its terminal layer node).
|
||||
pub draggable: bool,
|
||||
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
|
||||
pub expanded: bool,
|
||||
/// The ID of the node whose properties this section displays.
|
||||
pub id: u64,
|
||||
/// The node's properties content, rendered as the section's body when expanded.
|
||||
pub layout: Layout,
|
||||
}
|
||||
|
||||
@@ -405,12 +416,14 @@ impl LayoutGroup {
|
||||
Self::Table(WidgetTable { rows, unstyled })
|
||||
}
|
||||
|
||||
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, id: u64, layout: Layout) -> Self {
|
||||
pub fn section(name: impl Into<String>, description: impl Into<String>, visible: bool, pinned: bool, expanded: bool, id: u64, layout: Layout) -> Self {
|
||||
Self::Section(WidgetSection {
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
visible,
|
||||
pinned,
|
||||
draggable: false,
|
||||
expanded,
|
||||
id,
|
||||
layout,
|
||||
})
|
||||
@@ -507,6 +520,8 @@ impl Diffable for LayoutGroup {
|
||||
description: current_description,
|
||||
visible: current_visible,
|
||||
pinned: current_pinned,
|
||||
draggable: current_draggable,
|
||||
expanded: current_expanded,
|
||||
id: current_id,
|
||||
layout: current_layout,
|
||||
}),
|
||||
@@ -515,6 +530,8 @@ impl Diffable for LayoutGroup {
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
}),
|
||||
@@ -526,6 +543,8 @@ impl Diffable for LayoutGroup {
|
||||
|| *current_description != new_description
|
||||
|| *current_visible != new_visible
|
||||
|| *current_pinned != new_pinned
|
||||
|| *current_draggable != new_draggable
|
||||
|| *current_expanded != new_expanded
|
||||
|| *current_id != new_id
|
||||
{
|
||||
// Update self to reflect new changes
|
||||
@@ -533,6 +552,8 @@ impl Diffable for LayoutGroup {
|
||||
current_description.clone_from(&new_description);
|
||||
*current_visible = new_visible;
|
||||
*current_pinned = new_pinned;
|
||||
*current_draggable = new_draggable;
|
||||
*current_expanded = new_expanded;
|
||||
*current_id = new_id;
|
||||
current_layout.clone_from(&new_layout);
|
||||
|
||||
@@ -542,6 +563,8 @@ impl Diffable for LayoutGroup {
|
||||
description: new_description,
|
||||
visible: new_visible,
|
||||
pinned: new_pinned,
|
||||
draggable: new_draggable,
|
||||
expanded: new_expanded,
|
||||
id: new_id,
|
||||
layout: new_layout,
|
||||
})
|
||||
|
||||
@@ -612,6 +612,16 @@ pub enum SpectrumInputUpdate {
|
||||
DeleteMarker {
|
||||
index: u32,
|
||||
},
|
||||
/// Insert a copy (same color and midpoint) of the marker at `index` at `position`, keeping the marker at `index` active.
|
||||
InsertDuplicate {
|
||||
index: u32,
|
||||
position: f64,
|
||||
},
|
||||
/// Remove the marker at `index` while keeping the currently active marker active (renumbered to account for the removal).
|
||||
/// Used to un-duplicate when Alt is released mid-drag, deleting the frozen copy left by [`InsertDuplicate`](Self::InsertDuplicate).
|
||||
RemoveDuplicate {
|
||||
index: u32,
|
||||
},
|
||||
/// Emitted when the user double-clicks a marker. The consumer decides what (if anything) to reset the marker to.
|
||||
ResetMarker {
|
||||
index: u32,
|
||||
|
||||
@@ -103,6 +103,10 @@ pub enum DocumentMessage {
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
ReorderPropertiesSection {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
MoveSelectedLayersToGroup {
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
@@ -112,7 +116,7 @@ pub enum DocumentMessage {
|
||||
resize: Key,
|
||||
resize_opposite: Key,
|
||||
},
|
||||
PasteImage {
|
||||
InsertImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
mouse: Option<(f64, f64)>,
|
||||
@@ -121,7 +125,7 @@ pub enum DocumentMessage {
|
||||
/// can wrap it without a content Transform node. When false, place at the cursor or viewport center.
|
||||
place_at_origin: bool,
|
||||
},
|
||||
PasteSvg {
|
||||
InsertSvg {
|
||||
name: Option<String>,
|
||||
svg: String,
|
||||
mouse: Option<(f64, f64)>,
|
||||
@@ -212,6 +216,9 @@ pub enum DocumentMessage {
|
||||
tree_path: Vec<NodeId>,
|
||||
recursive: bool,
|
||||
},
|
||||
ToggleNodePropertiesSectionExpanded {
|
||||
node_id: NodeId,
|
||||
},
|
||||
ToggleSelectedVisibility,
|
||||
ToggleSelectedLocked,
|
||||
ToggleGridVisibility,
|
||||
|
||||
@@ -94,6 +94,9 @@ pub struct DocumentMessageHandler {
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
|
||||
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
|
||||
pub collapsed: CollapsedLayers,
|
||||
/// The node IDs whose section is collapsed in the Properties panel.
|
||||
#[serde(default)]
|
||||
pub properties_panel_collapsed_sections: Vec<NodeId>,
|
||||
/// The full Git commit hash of the Graphite repository that was used to build the editor.
|
||||
/// We save this to provide a hint about which version of the editor was used to create the document.
|
||||
pub commit_hash: String,
|
||||
@@ -173,6 +176,7 @@ impl Default for DocumentMessageHandler {
|
||||
network_interface: default_document_network_interface(),
|
||||
resources: ResourceMessageHandler::default(),
|
||||
collapsed: CollapsedLayers::default(),
|
||||
properties_panel_collapsed_sections: Vec::new(),
|
||||
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
|
||||
document_ptz: PTZ::default(),
|
||||
render_mode: RenderMode::default(),
|
||||
@@ -248,6 +252,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
document_name: self.name.as_str(),
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections: &self.properties_panel_collapsed_sections,
|
||||
};
|
||||
self.properties_panel_message_handler.process_message(message, responses, context);
|
||||
}
|
||||
@@ -271,6 +276,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
breadcrumb_network_path: &self.breadcrumb_network_path,
|
||||
document_id,
|
||||
collapsed: &mut self.collapsed,
|
||||
properties_panel_collapsed_sections: &mut self.properties_panel_collapsed_sections,
|
||||
ipp,
|
||||
graph_view_overlay_open: self.graph_view_overlay_open,
|
||||
graph_fade_artwork_percentage: self.graph_fade_artwork_percentage,
|
||||
@@ -726,6 +732,39 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MoveSelectedLayersTo { parent, insert_index } => {
|
||||
self.move_selected_layers_to(parent, insert_index, responses);
|
||||
}
|
||||
DocumentMessage::ReorderPropertiesSection { node_id, insert_index } => {
|
||||
// The Properties panel shows draggable sections in two cases, disambiguated by the current selection:
|
||||
// a single selected layer (reorder within its node chain) or no selection (reorder the pinned nodes).
|
||||
let selected_nodes = self.network_interface.selected_nodes_in_nested_network(&self.selection_network_path);
|
||||
let Some(selected_nodes) = selected_nodes else { return };
|
||||
|
||||
let (mut layers, mut nodes) = (Vec::new(), Vec::new());
|
||||
|
||||
for selected in selected_nodes.selected_nodes() {
|
||||
if self.network_interface.is_layer(selected, &self.selection_network_path) {
|
||||
layers.push(*selected);
|
||||
} else {
|
||||
nodes.push(*selected);
|
||||
}
|
||||
}
|
||||
|
||||
layers.sort();
|
||||
layers.dedup();
|
||||
|
||||
if layers.len() == 1 {
|
||||
// Reorder a node within the selected layer's chain by rewiring the graph
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderChainNode { node_id, insert_index });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
} else if layers.is_empty() && nodes.is_empty() {
|
||||
// Reorder a pinned node, which is purely a Properties panel display order (no graph rerender needed)
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::ReorderPinnedNode { node_id, insert_index });
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
}
|
||||
DocumentMessage::MoveSelectedLayersToGroup { parent } => {
|
||||
// Group all shallowest unique selected layers in order
|
||||
let all_layers_to_group_sorted = self.network_interface.shallowest_unique_layers_sorted(&self.selection_network_path);
|
||||
@@ -753,7 +792,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let resize_opposite = ipp.keyboard.key(resize_opposite);
|
||||
self.nudge_selected_layers(delta_x, delta_y, resize, resize_opposite, responses);
|
||||
}
|
||||
DocumentMessage::PasteImage {
|
||||
DocumentMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
@@ -817,7 +856,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
// Force chosen tool to be Select Tool after importing image.
|
||||
responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select });
|
||||
}
|
||||
DocumentMessage::PasteSvg {
|
||||
DocumentMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
@@ -1330,6 +1369,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id } => {
|
||||
if let Some(index) = self.properties_panel_collapsed_sections.iter().position(|id| *id == node_id) {
|
||||
self.properties_panel_collapsed_sections.remove(index);
|
||||
} else {
|
||||
self.properties_panel_collapsed_sections.push(node_id);
|
||||
}
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
}
|
||||
DocumentMessage::ToggleSelectedLocked => responses.add(NodeGraphMessage::ToggleSelectedLocked),
|
||||
DocumentMessage::ToggleSelectedVisibility => {
|
||||
responses.add(NodeGraphMessage::ToggleSelectedVisibility);
|
||||
|
||||
@@ -34,6 +34,8 @@ pub struct NodePropertiesContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub selection_network_path: &'a [NodeId],
|
||||
pub document_name: &'a str,
|
||||
/// The node IDs whose Properties panel sections the user has collapsed.
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
}
|
||||
|
||||
impl NodePropertiesContext<'_> {
|
||||
|
||||
@@ -94,11 +94,19 @@ pub enum NodeGraphMessage {
|
||||
node_id: NodeId,
|
||||
parent: LayerNodeIdentifier,
|
||||
},
|
||||
ReorderChainNode {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
ReorderPinnedNode {
|
||||
node_id: NodeId,
|
||||
insert_index: usize,
|
||||
},
|
||||
SetChainPosition {
|
||||
node_id: NodeId,
|
||||
},
|
||||
PasteNodes {
|
||||
serialized_nodes: String,
|
||||
InsertNodes {
|
||||
nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
},
|
||||
PointerDown {
|
||||
shift_click: bool,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::node_properties;
|
||||
use super::utility_types::{BoxSelection, ContextMenuInformation, DragStart, FrontendNode};
|
||||
use crate::consts::GRID_SIZE;
|
||||
use crate::messages::clipboard::utility_types::ClipboardContent;
|
||||
use crate::messages::clipboard::utility_types::ClipboardItem;
|
||||
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
@@ -12,9 +12,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, InputConnector, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, Previewing,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
use crate::messages::prelude::*;
|
||||
@@ -41,6 +39,7 @@ pub struct NodeGraphMessageContext<'a> {
|
||||
pub breadcrumb_network_path: &'a [NodeId],
|
||||
pub document_id: DocumentId,
|
||||
pub collapsed: &'a mut CollapsedLayers,
|
||||
pub properties_panel_collapsed_sections: &'a mut Vec<NodeId>,
|
||||
pub ipp: &'a InputPreprocessorMessageHandler,
|
||||
pub graph_view_overlay_open: bool,
|
||||
pub graph_fade_artwork_percentage: f64,
|
||||
@@ -112,6 +111,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
breadcrumb_network_path,
|
||||
document_id,
|
||||
collapsed,
|
||||
properties_panel_collapsed_sections,
|
||||
ipp,
|
||||
graph_view_overlay_open,
|
||||
graph_fade_artwork_percentage,
|
||||
@@ -188,8 +188,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
on: EventMessage::SelectionChanged,
|
||||
send: Box::new(NodeGraphMessage::SelectedNodesUpdated.into()),
|
||||
});
|
||||
|
||||
network_interface.load_structure();
|
||||
|
||||
// Prune the Layers panel collapsed state for any layer tree paths whose nodes no longer exist, so it doesn't accumulate across loads
|
||||
collapsed.0.retain(|path| path.iter().all(|&node_id| network_interface.document_network().nodes.contains_key(&node_id)));
|
||||
|
||||
// Prune the Properties panel node section collapsed state for any nodes (in any nested network) that no longer exist, so it doesn't accumulate across loads
|
||||
let existing_nodes = network_interface.document_network().recursive_nodes().map(|(node_id, ..)| *node_id).collect::<HashSet<_>>();
|
||||
properties_panel_collapsed_sections.retain(|node_id| existing_nodes.contains(node_id));
|
||||
}
|
||||
NodeGraphMessage::SelectedNodesUpdated => {
|
||||
let selected_layers = network_interface.selected_nodes().selected_layers(network_interface.document_metadata()).collect::<Vec<_>>();
|
||||
@@ -248,12 +255,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let new_ids = &all_selected_nodes.iter().enumerate().map(|(new, old)| (*old, NodeId(new as u64))).collect();
|
||||
let copied_nodes = network_interface.copy_nodes(new_ids, selection_network_path).collect::<Vec<_>>();
|
||||
|
||||
let Ok(data) = serde_json::to_string(&copied_nodes) else {
|
||||
log::error!("Failed to serialize nodes for clipboard");
|
||||
return;
|
||||
};
|
||||
responses.add(ClipboardMessage::Write {
|
||||
content: ClipboardContent::Nodes(data),
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: vec![ClipboardItem::Nodes(copied_nodes)],
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::CreateNodeInLayerNoTransaction { node_type, layer } => {
|
||||
@@ -759,29 +762,27 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::MoveNodeToChainStart { node_id, parent } => {
|
||||
network_interface.move_node_to_chain_start(&node_id, parent, selection_network_path, false);
|
||||
}
|
||||
NodeGraphMessage::ReorderChainNode { node_id, insert_index } => {
|
||||
network_interface.reorder_chain_node(node_id, insert_index, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::ReorderPinnedNode { node_id, insert_index } => {
|
||||
network_interface.reorder_pinned_node(node_id, insert_index, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::SetChainPosition { node_id } => {
|
||||
network_interface.set_chain_position(&node_id, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::PasteNodes { serialized_nodes } => {
|
||||
let data = match serde_json::from_str::<Vec<(NodeId, NodeTemplate)>>(&serialized_nodes) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
warn!("Invalid node data {e:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if data.is_empty() {
|
||||
NodeGraphMessage::InsertNodes { nodes } => {
|
||||
if nodes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
|
||||
let new_ids: HashMap<_, _> = data.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
|
||||
|
||||
let nodes: Vec<_> = new_ids.values().copied().collect();
|
||||
responses.add(NodeGraphMessage::AddNodes {
|
||||
nodes: data,
|
||||
new_ids: new_ids.clone(),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes })
|
||||
}
|
||||
NodeGraphMessage::PointerDown {
|
||||
@@ -1785,6 +1786,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
|
||||
responses.add(SelectToolMessage::SelectionChanged);
|
||||
responses.add(PenToolMessage::SelectionChanged);
|
||||
responses.add(FreehandToolMessage::SelectionChanged);
|
||||
responses.add(SplineToolMessage::SelectionChanged);
|
||||
@@ -2538,25 +2540,18 @@ impl NodeGraphMessageHandler {
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
])];
|
||||
|
||||
let Some(network) = context.network_interface.nested_network(context.selection_network_path) else {
|
||||
warn!("No network in collate_properties");
|
||||
return Vec::new();
|
||||
};
|
||||
// And if no nodes are selected, show properties for all pinned nodes
|
||||
let pinned_node_properties = network
|
||||
.nodes
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
if context.network_interface.is_pinned(node_id, context.selection_network_path) {
|
||||
Some(node_properties::generate_node_properties(*node_id, context))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
// And if no nodes are selected, show properties for all pinned nodes (in the user's saved order, each draggable to reorder)
|
||||
let mut pinned_node_properties = context
|
||||
.network_interface
|
||||
.ordered_pinned_nodes(context.selection_network_path)
|
||||
.into_iter()
|
||||
.map(|node_id| node_properties::generate_node_properties(node_id, context))
|
||||
.collect::<Vec<_>>();
|
||||
for pinned_section in pinned_node_properties.iter_mut() {
|
||||
if let LayoutGroup::Section(section) = pinned_section {
|
||||
section.draggable = true;
|
||||
}
|
||||
}
|
||||
|
||||
properties.extend(pinned_node_properties);
|
||||
properties
|
||||
@@ -2618,7 +2613,7 @@ impl NodeGraphMessageHandler {
|
||||
])];
|
||||
|
||||
// Iterate through all the upstream nodes, but stop when we reach another layer (since that's a point where we switch from horizontal to vertical flow)
|
||||
let node_properties = context
|
||||
let mut node_properties = context
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(vec![layer], context.selection_network_path, network_interface::FlowType::HorizontalFlow)
|
||||
.enumerate()
|
||||
@@ -2635,6 +2630,14 @@ impl NodeGraphMessageHandler {
|
||||
.map(|node_id| node_properties::generate_node_properties(node_id, context))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Mark each chain node (but not the layer node itself, which is first) draggable so its section can be reordered.
|
||||
// A node without a primary input (e.g. a generator) is left non-draggable.
|
||||
for chain_node_section in node_properties.iter_mut().skip(1) {
|
||||
if let LayoutGroup::Section(section) = chain_node_section {
|
||||
section.draggable = context.network_interface.has_primary_input(&NodeId(section.id), context.selection_network_path);
|
||||
}
|
||||
}
|
||||
|
||||
layer_properties.extend(node_properties);
|
||||
layer_properties
|
||||
}
|
||||
|
||||
@@ -2373,8 +2373,9 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
|
||||
let visible = context.network_interface.is_visible(&node_id, context.selection_network_path);
|
||||
let pinned = context.network_interface.is_pinned(&node_id, context.selection_network_path);
|
||||
let expanded = !context.properties_panel_collapsed_sections.contains(&node_id);
|
||||
|
||||
LayoutGroup::section(name, description, visible, pinned, node_id.0, Layout(layout))
|
||||
LayoutGroup::section(name, description, visible, pinned, expanded, node_id.0, Layout(layout))
|
||||
}
|
||||
|
||||
/// Resolve the viewport-space orientation of a Fill node's gradient by walking downstream to its owning layer
|
||||
|
||||
+3
@@ -15,6 +15,7 @@ pub struct PropertiesPanelMessageContext<'a> {
|
||||
pub document_name: &'a str,
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
pub properties_panel_open: bool,
|
||||
pub properties_panel_collapsed_sections: &'a [NodeId],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -31,6 +32,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_open,
|
||||
properties_panel_collapsed_sections,
|
||||
} = context;
|
||||
|
||||
match message {
|
||||
@@ -54,6 +56,7 @@ impl MessageHandler<PropertiesPanelMessage, PropertiesPanelMessageContext<'_>> f
|
||||
selection_network_path,
|
||||
document_name,
|
||||
fonts,
|
||||
properties_panel_collapsed_sections,
|
||||
};
|
||||
let layout = Layout(NodeGraphMessageHandler::collate_properties(&mut node_properties_context));
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
use super::network_interface::NodeTemplate;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
#[repr(u8)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Clipboard {
|
||||
Internal,
|
||||
Device,
|
||||
|
||||
_InternalClipboardCount, // Keep this as the last entry of **internal** clipboards since it is used for counting the number of enum variants
|
||||
}
|
||||
|
||||
pub const INTERNAL_CLIPBOARD_COUNT: u8 = Clipboard::_InternalClipboardCount as u8;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct CopyBufferEntry {
|
||||
pub nodes: Vec<(NodeId, NodeTemplate)>,
|
||||
pub selected: bool,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod clipboards;
|
||||
pub mod document_metadata;
|
||||
pub mod error;
|
||||
pub mod misc;
|
||||
|
||||
@@ -352,6 +352,12 @@ impl NodeNetworkInterface {
|
||||
node.inputs.len()
|
||||
}
|
||||
|
||||
/// Whether the node has an exposed input at index 0 to accept the horizontal flow from upstream.
|
||||
/// A node without one (e.g. a generator) can only be the most-upstream node in a chain.
|
||||
pub fn has_primary_input(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.input_from_connector(&InputConnector::node(*node_id, 0), network_path).is_some_and(|input| input.is_exposed())
|
||||
}
|
||||
|
||||
pub fn number_of_outputs(&self, node_id: &NodeId, network_path: &[NodeId]) -> usize {
|
||||
let Some(implementation) = self.implementation(node_id, network_path) else {
|
||||
log::error!("Could not get node {node_id} in number_of_outputs");
|
||||
@@ -1054,6 +1060,35 @@ impl NodeNetworkInterface {
|
||||
node_metadata.persistent_metadata.pinned
|
||||
}
|
||||
|
||||
/// The given network's pinned nodes in display order: pinning appends, dragging rearranges, and any not yet recorded go last.
|
||||
pub fn ordered_pinned_nodes(&self, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
|
||||
|
||||
let order = self
|
||||
.network_metadata(network_path)
|
||||
.map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
// Follow the saved order, keeping only nodes that still exist and are still pinned
|
||||
let mut pinned_nodes = order
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|node_id| network.nodes.contains_key(node_id) && self.is_pinned(node_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Append any pinned nodes missing from the saved order at the end
|
||||
let mut unordered = network
|
||||
.nodes
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|node_id| self.is_pinned(node_id, network_path) && !order.contains(node_id))
|
||||
.collect::<Vec<_>>();
|
||||
unordered.sort();
|
||||
pinned_nodes.extend(unordered);
|
||||
|
||||
pinned_nodes
|
||||
}
|
||||
|
||||
pub fn is_visible(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
let Some(node) = self.document_node(node_id, network_path) else {
|
||||
log::error!("Could not get node in is_visible");
|
||||
@@ -4542,6 +4577,15 @@ impl NodeNetworkInterface {
|
||||
self.set_chain_position(&previous_chain_node, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Prune this network's pinned display order down to the nodes that still exist, dropping any that were actually removed
|
||||
let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::<HashSet<_>>());
|
||||
if let Some(surviving_nodes) = surviving_nodes
|
||||
&& let Some(network_metadata) = self.network_metadata_mut(network_path)
|
||||
{
|
||||
network_metadata.persistent_metadata.pinned_node_order.retain(|node_id| surviving_nodes.contains(node_id));
|
||||
}
|
||||
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
// Instead of unloaded all node click targets, just unload the nodes upstream from the deleted nodes. unload_upstream_node_click_targets will not work since the nodes have been deleted.
|
||||
self.unload_all_nodes_click_targets(network_path);
|
||||
@@ -4724,6 +4768,43 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
node_metadata.persistent_metadata.pinned = pinned;
|
||||
|
||||
// Track the node in this network's pinned display order: append when newly pinned, prune when unpinned
|
||||
if let Some(network_metadata) = self.network_metadata_mut(network_path) {
|
||||
let order = &mut network_metadata.persistent_metadata.pinned_node_order;
|
||||
if pinned {
|
||||
if !order.contains(node_id) {
|
||||
order.push(*node_id);
|
||||
}
|
||||
} else {
|
||||
order.retain(|id| id != node_id);
|
||||
}
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
/// Reorders a pinned node within its network's Properties panel display order so it ends up at `insert_index` among the
|
||||
/// pinned nodes (0 being the topmost). Rebuilds the order from the list as currently shown, which also drops stale entries.
|
||||
pub fn reorder_pinned_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let shown = self.ordered_pinned_nodes(network_path);
|
||||
|
||||
let Some(from) = shown.iter().position(|id| *id == node_id) else { return };
|
||||
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(shown.len().saturating_sub(1));
|
||||
if to == from {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut new_order = shown;
|
||||
let moved = new_order.remove(from);
|
||||
new_order.insert(to, moved);
|
||||
|
||||
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
|
||||
log::error!("Could not get network_metadata in reorder_pinned_node");
|
||||
return;
|
||||
};
|
||||
network_metadata.persistent_metadata.pinned_node_order = new_order;
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
@@ -6002,6 +6083,68 @@ impl NodeNetworkInterface {
|
||||
self.force_set_upstream_to_chain(node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reorders a node within its layer's horizontal chain so it ends up at `insert_index` among the chain's nodes,
|
||||
/// where index 0 is the node closest to the layer. The connection feeding the top (most-upstream end) of the chain
|
||||
/// is preserved, as are each node's other (non-primary) inputs.
|
||||
pub fn reorder_chain_node(&mut self, node_id: NodeId, insert_index: usize, network_path: &[NodeId]) {
|
||||
let Some(layer) = self.downstream_layer_for_chain_node(&node_id, network_path) else {
|
||||
log::error!("Could not find downstream layer for chain node {node_id} in reorder_chain_node");
|
||||
return;
|
||||
};
|
||||
|
||||
// The nodes in the layer's chain, ordered from closest-to-layer outward, stopping at the next layer
|
||||
let chain = self
|
||||
.upstream_flow_back_from_nodes(vec![layer], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.take_while(|upstream_id| !self.is_layer(upstream_id, network_path))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// A source node (no primary input) stays pinned at the most-upstream end; only the nodes below it reorder
|
||||
let pinned_source = chain.last().copied().filter(|last| !self.has_primary_input(last, network_path));
|
||||
let reorderable = &chain[..chain.len() - pinned_source.is_some() as usize];
|
||||
|
||||
let Some(from) = reorderable.iter().position(|id| *id == node_id) else {
|
||||
log::error!("Node {node_id} is not a reorderable node in its layer's chain in reorder_chain_node");
|
||||
return;
|
||||
};
|
||||
|
||||
// The drop gap is measured against the reorderable nodes that still include the dragged node, so shift it down by one if the node is being removed from before the gap
|
||||
let to = (if insert_index > from { insert_index - 1 } else { insert_index }).min(reorderable.len() - 1);
|
||||
if to == from {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut new_order = reorderable.to_vec();
|
||||
new_order.remove(from);
|
||||
new_order.insert(to, node_id);
|
||||
|
||||
// The most-upstream reorderable node connects up to the pinned source, or else whatever fed the top of the chain
|
||||
let tail_input = if let Some(source) = pinned_source {
|
||||
NodeInput::node(source, 0)
|
||||
} else {
|
||||
let Some(input) = self.input_from_connector(&InputConnector::node(*chain.last().unwrap(), 0), network_path).cloned() else {
|
||||
log::error!("Could not get the upstream input of the chain in reorder_chain_node");
|
||||
return;
|
||||
};
|
||||
input
|
||||
};
|
||||
|
||||
// Disconnect first so the rewiring can't transiently form a cycle (the pinned source keeps its wiring)
|
||||
for &chain_node in reorderable {
|
||||
self.disconnect_input(&InputConnector::node(chain_node, 0), network_path);
|
||||
}
|
||||
|
||||
// Rewire in the new order: layer's secondary input -> new_order[0] -> ... -> new_order[last] -> tail input
|
||||
self.set_input(&InputConnector::node(layer, 1), NodeInput::node(new_order[0], 0), network_path);
|
||||
for pair in new_order.windows(2) {
|
||||
self.set_input(&InputConnector::node(pair[0], 0), NodeInput::node(pair[1], 0), network_path);
|
||||
}
|
||||
self.set_input(&InputConnector::node(*new_order.last().unwrap(), 0), tail_input, network_path);
|
||||
|
||||
// Re-establish chain positioning for the reordered nodes
|
||||
self.force_set_upstream_to_chain(&new_order[0], network_path);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
@@ -6346,6 +6489,9 @@ pub struct NodeNetworkPersistentMetadata {
|
||||
/// Node metadata must exist for every document node in the network
|
||||
#[serde(serialize_with = "graphene_std::vector::serialize_hashmap", deserialize_with = "graphene_std::vector::deserialize_hashmap")]
|
||||
pub node_metadata: HashMap<NodeId, DocumentNodeMetadata>,
|
||||
/// The display order of pinned nodes in the Properties panel (shown when nothing is selected in this network), keyed by node ID.
|
||||
#[serde(default)]
|
||||
pub pinned_node_order: Vec<NodeId>,
|
||||
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
||||
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
||||
pub previewing: Previewing,
|
||||
@@ -6832,17 +6978,22 @@ pub enum TransactionStatus {
|
||||
|
||||
fn collect_network_resources(network: &NodeNetwork, out: &mut HashSet<ResourceId>) {
|
||||
for node in network.nodes.values() {
|
||||
for input in &node.inputs {
|
||||
if let NodeInput::Value { tagged_value, .. } = input
|
||||
&& let TaggedValue::Resource(id) = &**tagged_value
|
||||
{
|
||||
out.insert(*id);
|
||||
}
|
||||
}
|
||||
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
|
||||
collect_network_resources(nested, out);
|
||||
collect_node_resources(node, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects resource IDs referenced by a node and its nested networks.
|
||||
pub fn collect_node_resources(node: &DocumentNode, out: &mut HashSet<ResourceId>) {
|
||||
for input in &node.inputs {
|
||||
if let NodeInput::Value { tagged_value, .. } = input
|
||||
&& let TaggedValue::Resource(id) = &**tagged_value
|
||||
{
|
||||
out.insert(*id);
|
||||
}
|
||||
}
|
||||
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
|
||||
collect_network_resources(nested, out);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -6857,18 +7008,19 @@ mod network_interface_tests {
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle] }).await;
|
||||
let frontend_messages = editor.handle_message(NodeGraphMessage::Copy).await;
|
||||
let serialized_nodes = frontend_messages
|
||||
let clipboard = frontend_messages
|
||||
.into_iter()
|
||||
.find_map(|msg| match msg {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
})
|
||||
.expect("copy message should be dispatched")
|
||||
.strip_prefix("graphite/nodes: ")
|
||||
.expect("should start with magic string")
|
||||
.to_string();
|
||||
println!("Serialized: {serialized_nodes}");
|
||||
editor.handle_message(NodeGraphMessage::PasteNodes { serialized_nodes }).await;
|
||||
.expect("copy message should be dispatched");
|
||||
println!("Clipboard: {clipboard}");
|
||||
editor
|
||||
.handle_message(ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(clipboard),
|
||||
})
|
||||
.await;
|
||||
let nodes = &mut editor.active_document_mut().network_interface.network_mut(&[]).unwrap().nodes;
|
||||
let orignal = nodes.remove(&rectangle).expect("original node should exist");
|
||||
assert!(
|
||||
|
||||
@@ -2,7 +2,6 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::Image;
|
||||
@@ -39,12 +38,6 @@ pub enum PortfolioMessage {
|
||||
CloseDocumentWithConfirmation {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
Copy {
|
||||
clipboard: Clipboard,
|
||||
},
|
||||
Cut {
|
||||
clipboard: Clipboard,
|
||||
},
|
||||
DeleteDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
@@ -113,31 +106,19 @@ pub enum PortfolioMessage {
|
||||
name: Option<String>,
|
||||
svg: String,
|
||||
},
|
||||
PasteSerializedData {
|
||||
data: String,
|
||||
},
|
||||
PasteSerializedVector {
|
||||
data: String,
|
||||
},
|
||||
PasteImage {
|
||||
InsertImage {
|
||||
name: Option<String>,
|
||||
image: Image<Color>,
|
||||
mouse: Option<(f64, f64)>,
|
||||
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
|
||||
},
|
||||
PasteSvg {
|
||||
InsertSvg {
|
||||
name: Option<String>,
|
||||
svg: String,
|
||||
mouse: Option<(f64, f64)>,
|
||||
parent_and_insert_index: Option<(LayerNodeIdentifier, usize)>,
|
||||
},
|
||||
// TODO: Unused except by tests, remove?
|
||||
PasteIntoFolder {
|
||||
clipboard: Clipboard,
|
||||
parent: LayerNodeIdentifier,
|
||||
insert_index: usize,
|
||||
},
|
||||
CenterPastedLayers {
|
||||
CenterLayers {
|
||||
layers: Vec<LayerNodeIdentifier>,
|
||||
},
|
||||
PrevDocument,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::document::utility_types::network_interface;
|
||||
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
|
||||
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
|
||||
use crate::application::{Editor, generate_uuid};
|
||||
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION};
|
||||
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION};
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::clipboard::utility_types::ClipboardContent;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
@@ -13,15 +11,12 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageContext;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{self, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::{Clipboard, CopyBufferEntry, INTERNAL_CLIPBOARD_COUNT};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
use crate::messages::portfolio::document_migration::*;
|
||||
use crate::messages::portfolio::utility_types::FileContent;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::utility_types::{HintData, ToolType};
|
||||
use crate::messages::viewport::ToPhysical;
|
||||
use crate::node_graph_executor::{ExportConfig, NodeGraphExecutor};
|
||||
@@ -31,9 +26,6 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::subpath::BezierHandles;
|
||||
use graphene_std::vector::misc::HandleId;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::vec;
|
||||
@@ -68,7 +60,6 @@ pub struct PortfolioMessageHandler {
|
||||
pub(crate) active_document_id: Option<DocumentId>,
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
copy_buffer: [Vec<CopyBufferEntry>; INTERNAL_CLIPBOARD_COUNT as usize],
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
@@ -281,86 +272,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
}
|
||||
PortfolioMessage::Copy { clipboard } => {
|
||||
if context.current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Copy { clipboard });
|
||||
return;
|
||||
}
|
||||
|
||||
// We can't use `self.active_document()` because it counts as an immutable borrow of the entirety of `self`
|
||||
let Some(active_document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if active_document.graph_view_overlay_open() {
|
||||
responses.add(NodeGraphMessage::Copy);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut copy_val = |buffer: &mut Vec<CopyBufferEntry>| {
|
||||
let mut ordered_last_elements = active_document.network_interface.shallowest_unique_layers(&[]).collect::<Vec<_>>();
|
||||
|
||||
ordered_last_elements.sort_by_key(|layer| {
|
||||
let Some(parent) = layer.parent(active_document.metadata()) else { return usize::MAX };
|
||||
DocumentMessageHandler::get_calculated_insert_index(active_document.metadata(), &SelectedNodes(vec![layer.to_node()]), parent)
|
||||
});
|
||||
|
||||
for layer in ordered_last_elements.into_iter() {
|
||||
let layer_node_id = layer.to_node();
|
||||
|
||||
let mut copy_ids = HashMap::new();
|
||||
copy_ids.insert(layer_node_id, NodeId(0));
|
||||
|
||||
active_document
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes(vec![layer_node_id], &[], network_interface::FlowType::LayerChildrenUpstreamFlow)
|
||||
.enumerate()
|
||||
.for_each(|(index, node_id)| {
|
||||
copy_ids.insert(node_id, NodeId((index + 1) as u64));
|
||||
});
|
||||
|
||||
buffer.push(CopyBufferEntry {
|
||||
nodes: active_document.network_interface.copy_nodes(©_ids, &[]).collect(),
|
||||
selected: active_document.network_interface.selected_nodes().selected_layers_contains(layer, active_document.metadata()),
|
||||
visible: active_document.network_interface.selected_nodes().layer_visible(layer, &active_document.network_interface),
|
||||
locked: active_document.network_interface.selected_nodes().layer_locked(layer, &active_document.network_interface),
|
||||
collapsed: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if clipboard == Clipboard::Device {
|
||||
let mut buffer = Vec::new();
|
||||
copy_val(&mut buffer);
|
||||
let Ok(data) = serde_json::to_string(&buffer) else {
|
||||
log::error!("Failed to serialize nodes for clipboard");
|
||||
return;
|
||||
};
|
||||
responses.add(ClipboardMessage::Write {
|
||||
content: ClipboardContent::Layer(data),
|
||||
});
|
||||
} else {
|
||||
let copy_buffer = &mut self.copy_buffer;
|
||||
copy_buffer[clipboard as usize].clear();
|
||||
copy_val(&mut copy_buffer[clipboard as usize]);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::Cut { clipboard } => {
|
||||
if context.current_tool == &ToolType::Path {
|
||||
responses.add(PathToolMessage::Cut { clipboard });
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(active_document) = self.active_document()
|
||||
&& active_document.graph_view_overlay_open()
|
||||
{
|
||||
responses.add(NodeGraphMessage::Cut);
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::Copy { clipboard });
|
||||
responses.add(DocumentMessage::DeleteSelectedLayers);
|
||||
}
|
||||
PortfolioMessage::DeleteDocument { document_id } => {
|
||||
let document_index = self.document_index(document_id);
|
||||
self.documents.remove(&document_id);
|
||||
@@ -759,7 +670,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
}
|
||||
FileContent::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::PasteSvg {
|
||||
responses.add(PortfolioMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse: None,
|
||||
@@ -767,7 +678,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
}
|
||||
FileContent::Image(image) => {
|
||||
responses.add(PortfolioMessage::PasteImage {
|
||||
responses.add(PortfolioMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse: None,
|
||||
@@ -959,7 +870,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
name: name.clone().unwrap_or_default(),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::PasteImage {
|
||||
responses.add(DocumentMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse: None,
|
||||
@@ -1014,7 +925,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
})
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::PasteSvg {
|
||||
responses.add(DocumentMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse: None,
|
||||
@@ -1036,153 +947,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
});
|
||||
}
|
||||
// TODO: Unused except by tests, remove?
|
||||
PortfolioMessage::PasteIntoFolder { clipboard, parent, insert_index } => {
|
||||
let mut all_new_ids = Vec::new();
|
||||
let paste = |entry: &CopyBufferEntry, responses: &mut VecDeque<_>, all_new_ids: &mut Vec<NodeId>| {
|
||||
if self.active_document().is_some() {
|
||||
trace!("Pasting into folder {parent:?} as index: {insert_index}");
|
||||
let nodes = entry.clone().nodes;
|
||||
let new_ids: HashMap<_, _> = nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
|
||||
all_new_ids.extend(new_ids.values().cloned());
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes, new_ids: new_ids.clone() });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index });
|
||||
}
|
||||
};
|
||||
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
|
||||
for entry in self.copy_buffer[clipboard as usize].iter().rev() {
|
||||
paste(entry, responses, &mut all_new_ids)
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
}
|
||||
PortfolioMessage::PasteSerializedData { data } => {
|
||||
if let Some(document) = self.active_document() {
|
||||
let mut all_new_ids = Vec::new();
|
||||
if let Ok(data) = serde_json::from_str::<Vec<CopyBufferEntry>>(&data) {
|
||||
let parent = document.new_layer_parent(false);
|
||||
let mut layers = Vec::new();
|
||||
|
||||
let mut added_nodes = false;
|
||||
|
||||
for entry in data.into_iter().rev() {
|
||||
if !added_nodes {
|
||||
responses.add(DocumentMessage::DeselectAllLayers);
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
added_nodes = true;
|
||||
}
|
||||
|
||||
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
|
||||
let layer = LayerNodeIdentifier::new_unchecked(new_ids[&NodeId(0)]);
|
||||
all_new_ids.extend(new_ids.values().cloned());
|
||||
|
||||
responses.add(NodeGraphMessage::AddNodes { nodes: entry.nodes, new_ids });
|
||||
responses.add(NodeGraphMessage::MoveLayerToStack { layer, parent, insert_index: 0 });
|
||||
layers.push(layer);
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: all_new_ids });
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Custom paste implementation for Path tool
|
||||
PortfolioMessage::PasteSerializedVector { data } => {
|
||||
// If using Path tool then send the operation to Path tool
|
||||
if *current_tool == ToolType::Path {
|
||||
responses.add(PathToolMessage::Paste { data });
|
||||
return;
|
||||
}
|
||||
|
||||
// If not using Path tool, create new layers and add paths into those
|
||||
if let Some(document) = self.active_document() {
|
||||
let Ok(data) = serde_json::from_str::<Vec<(LayerNodeIdentifier, Vector, DAffine2)>>(&data) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut layers = Vec::new();
|
||||
|
||||
for (_, new_vector, transform) in data {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
error!("Path node does not exist");
|
||||
continue;
|
||||
};
|
||||
let nodes = vec![(NodeId(0), node_type.default_node_template())];
|
||||
|
||||
let parent = document.new_layer_parent(false);
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
layers.push(layer);
|
||||
|
||||
// Adding the transform back into the layer
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform,
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
// Add default fill and stroke to the layer
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Create new segment ids and add the segments into the existing Vector path
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
|
||||
let new_segment_id = SegmentId::generate();
|
||||
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let handles = match bezier.handles {
|
||||
BezierHandles::Linear => [None, None],
|
||||
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
|
||||
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
|
||||
};
|
||||
|
||||
let points = [points_map[&start], points_map[&end]];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
let to_new_handle = |handle: HandleId| -> HandleId {
|
||||
HandleId {
|
||||
ty: handle.ty,
|
||||
segment: segments_map[&handle.segment],
|
||||
}
|
||||
};
|
||||
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterPastedLayers { layers }.into()],
|
||||
}));
|
||||
}
|
||||
}
|
||||
PortfolioMessage::CenterPastedLayers { layers } => {
|
||||
PortfolioMessage::CenterLayers { layers } => {
|
||||
if let Some(document) = self.active_document_mut() {
|
||||
let viewport_bounds_quad_pixels = Quad::from_box([DVec2::ZERO, viewport.size().into_dvec2()]); // In viewport pixel coordinates
|
||||
let viewport_center_pixels = viewport_bounds_quad_pixels.center(); // In viewport pixel coordinates
|
||||
@@ -1287,7 +1052,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PasteImage {
|
||||
PortfolioMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
@@ -1296,7 +1061,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
if self.document_ids.is_empty() {
|
||||
responses.add(PortfolioMessage::OpenImage { name, image });
|
||||
} else {
|
||||
responses.add(DocumentMessage::PasteImage {
|
||||
responses.add(DocumentMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
@@ -1305,7 +1070,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
}
|
||||
}
|
||||
PortfolioMessage::PasteSvg {
|
||||
PortfolioMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
@@ -1314,7 +1079,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
if self.document_ids.is_empty() {
|
||||
responses.add(PortfolioMessage::OpenSvg { name, svg });
|
||||
} else {
|
||||
responses.add(DocumentMessage::PasteSvg {
|
||||
responses.add(DocumentMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
@@ -1418,7 +1183,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
PortfolioMessage::RequestStatusBarInfoLayout => {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let widgets = vec![TextLabel::new("Graphite 1.0.0-RC5").disabled(true).widget_instance()]; // TODO: After the RCs, call this "Graphite (beta) x.y.z"
|
||||
let widgets = vec![TextLabel::new("Graphite 1.0.0-RC6").disabled(true).widget_instance()]; // TODO: After the RCs, call this "Graphite (beta) x.y.z"
|
||||
#[cfg(target_family = "wasm")]
|
||||
let widgets = vec![];
|
||||
|
||||
@@ -1816,14 +1581,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
PrevDocument,
|
||||
Import,
|
||||
));
|
||||
|
||||
// Extend with actions that must have a selected layer
|
||||
if document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some() {
|
||||
common.extend(actions!(PortfolioMessageDiscriminant;
|
||||
Copy,
|
||||
Cut,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Extend with actions that are disabled when focusing the document
|
||||
|
||||
@@ -7,7 +7,7 @@ pub use crate::messages::animation::{AnimationMessage, AnimationMessageDiscrimin
|
||||
pub use crate::messages::app_window::{AppWindowMessage, AppWindowMessageDiscriminant, AppWindowMessageHandler};
|
||||
pub use crate::messages::broadcast::event::{EventMessage, EventMessageContext, EventMessageDiscriminant, EventMessageHandler};
|
||||
pub use crate::messages::broadcast::{BroadcastMessage, BroadcastMessageDiscriminant, BroadcastMessageHandler};
|
||||
pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageDiscriminant, ClipboardMessageHandler};
|
||||
pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext, ClipboardMessageDiscriminant, ClipboardMessageHandler};
|
||||
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
|
||||
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
|
||||
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
|
||||
|
||||
@@ -5,13 +5,12 @@ use crate::consts::{
|
||||
DOUBLE_CLICK_MILLISECONDS, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, DRAG_THRESHOLD, DRILL_THROUGH_THRESHOLD, HANDLE_ROTATE_SNAP_ANGLE, SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE,
|
||||
SELECTION_THRESHOLD, SELECTION_TOLERANCE,
|
||||
};
|
||||
use crate::messages::clipboard::utility_types::ClipboardContent;
|
||||
use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardVectorEntry};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::portfolio::document::utility_types::transformation::Axis;
|
||||
@@ -141,14 +140,11 @@ pub enum PathToolMessage {
|
||||
overlay_context: OverlayContext,
|
||||
},
|
||||
StartSlidingPoint,
|
||||
Copy {
|
||||
clipboard: Clipboard,
|
||||
},
|
||||
Cut {
|
||||
clipboard: Clipboard,
|
||||
},
|
||||
Copy,
|
||||
Cut,
|
||||
Paste {
|
||||
data: String,
|
||||
#[cfg_attr(feature = "wasm", tsify(type = "unknown"))]
|
||||
paths: Vec<ClipboardVectorEntry>,
|
||||
},
|
||||
DeleteSelected,
|
||||
Duplicate,
|
||||
@@ -2749,7 +2745,7 @@ impl Fsm for PathToolFsmState {
|
||||
PathToolFsmState::Ready
|
||||
}
|
||||
}
|
||||
(_, PathToolMessage::Copy { clipboard }) => {
|
||||
(_, PathToolMessage::Copy) => {
|
||||
// TODO: Add support for selected segments
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
@@ -2808,131 +2804,121 @@ impl Fsm for PathToolFsmState {
|
||||
buffer.push((layer, new_vector, transform));
|
||||
}
|
||||
|
||||
if clipboard == Clipboard::Device {
|
||||
if let Ok(data) = serde_json::to_string(&buffer) {
|
||||
responses.add(ClipboardMessage::Write {
|
||||
content: ClipboardContent::Vector(data),
|
||||
});
|
||||
} else {
|
||||
log::error!("Failed to serialize nodes for clipboard");
|
||||
}
|
||||
}
|
||||
// TODO: Add implementation for internal clipboard
|
||||
responses.add(ClipboardMessage::WriteItems {
|
||||
items: vec![ClipboardItem::Vector(buffer)],
|
||||
});
|
||||
|
||||
PathToolFsmState::Ready
|
||||
}
|
||||
(_, PathToolMessage::Cut { clipboard }) => {
|
||||
responses.add(PathToolMessage::Copy { clipboard });
|
||||
(_, PathToolMessage::Cut) => {
|
||||
responses.add(PathToolMessage::Copy);
|
||||
// Delete the selected points/segments
|
||||
responses.add(PathToolMessage::DeleteSelected);
|
||||
|
||||
PathToolFsmState::Ready
|
||||
}
|
||||
(_, PathToolMessage::Paste { data }) => {
|
||||
// Deserialize the data
|
||||
if let Ok(data) = serde_json::from_str::<Vec<(LayerNodeIdentifier, Vector, DAffine2)>>(&data) {
|
||||
shape_editor.deselect_all_points();
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
let mut new_layers = Vec::new();
|
||||
for (layer, new_vector, transform) in data {
|
||||
// If layer is not selected then create a new selected layer
|
||||
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
|
||||
layer
|
||||
} else {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
error!("Could not resolve node type for Path");
|
||||
continue;
|
||||
};
|
||||
let nodes = vec![(NodeId(0), node_type.default_node_template())];
|
||||
|
||||
let parent = document.new_layer_parent(false);
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
|
||||
// Defaults chosen because the pasted geometry has no inherent associated style
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
new_layers.push(layer);
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform,
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
layer
|
||||
};
|
||||
|
||||
// Create new point ids and add those into the existing vector content
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Create new segment ids and add the segments into the existing vector content
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_iter() {
|
||||
let new_segment_id = SegmentId::generate();
|
||||
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let points = pathseg_points(bezier);
|
||||
let handles = [points.p1.map(|handle| handle - points.p0), points.p2.map(|handle| handle - points.p3)];
|
||||
|
||||
let points = [points_map[&start], points_map[&end]];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
let to_new_handle = |handle: HandleId| -> HandleId {
|
||||
HandleId {
|
||||
ty: handle.ty,
|
||||
segment: segments_map[&handle.segment],
|
||||
}
|
||||
};
|
||||
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
shape_editor.selected_shape_state.entry(layer).or_insert(Default::default());
|
||||
|
||||
// Set selection to newly inserted points
|
||||
let Some(state) = shape_editor.selected_shape_state.get_mut(&layer) else {
|
||||
error!("No state for layer: {layer:?}");
|
||||
(_, PathToolMessage::Paste { paths }) => {
|
||||
shape_editor.deselect_all_points();
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
let mut new_layers = Vec::new();
|
||||
for (layer, new_vector, transform) in paths {
|
||||
// If layer is not selected then create a new selected layer
|
||||
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
|
||||
layer
|
||||
} else {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
error!("Could not resolve node type for Path");
|
||||
continue;
|
||||
};
|
||||
let nodes = vec![(NodeId(0), node_type.default_node_template())];
|
||||
|
||||
// If point editing mode is enabled, select all the pasted points
|
||||
if tool_options.path_editing_mode.point_editing_mode {
|
||||
points_map.values().for_each(|point| state.select_point(ManipulatorPointId::Anchor(*point)));
|
||||
}
|
||||
// If segment editing mode is enabled, select all the pasted segments
|
||||
if tool_options.path_editing_mode.segment_editing_mode {
|
||||
segments_map.values().for_each(|segment| state.select_segment(*segment));
|
||||
}
|
||||
let parent = document.new_layer_parent(false);
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
|
||||
// Defaults chosen because the pasted geometry has no inherent associated style
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
new_layers.push(layer);
|
||||
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform,
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
layer
|
||||
};
|
||||
|
||||
// Create new point ids and add those into the existing vector content
|
||||
let mut points_map = HashMap::new();
|
||||
for (point, position) in new_vector.point_domain.iter() {
|
||||
let new_point_id = PointId::generate();
|
||||
points_map.insert(point, new_point_id);
|
||||
|
||||
let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// If there are new layers created, we need to center them in the viewport
|
||||
if !new_layers.is_empty() {
|
||||
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterPastedLayers { layers: new_layers }.into()],
|
||||
}));
|
||||
// Create new segment ids and add the segments into the existing vector content
|
||||
let mut segments_map = HashMap::new();
|
||||
for (segment_id, bezier, start, end) in new_vector.segment_iter() {
|
||||
let new_segment_id = SegmentId::generate();
|
||||
|
||||
segments_map.insert(segment_id, new_segment_id);
|
||||
|
||||
let points = pathseg_points(bezier);
|
||||
let handles = [points.p1.map(|handle| handle - points.p0), points.p2.map(|handle| handle - points.p3)];
|
||||
|
||||
let points = [points_map[&start], points_map[&end]];
|
||||
let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
// Set G1 continuity
|
||||
for handles in new_vector.colinear_manipulators {
|
||||
let to_new_handle = |handle: HandleId| -> HandleId {
|
||||
HandleId {
|
||||
ty: handle.ty,
|
||||
segment: segments_map[&handle.segment],
|
||||
}
|
||||
};
|
||||
let new_handles = [to_new_handle(handles[0]), to_new_handle(handles[1])];
|
||||
let modification_type = VectorModificationType::SetG1Continuous { handles: new_handles, enabled: true };
|
||||
|
||||
responses.add(GraphOperationMessage::Vector { layer, modification_type });
|
||||
}
|
||||
|
||||
shape_editor.selected_shape_state.entry(layer).or_insert(Default::default());
|
||||
|
||||
// Set selection to newly inserted points
|
||||
let Some(state) = shape_editor.selected_shape_state.get_mut(&layer) else {
|
||||
error!("No state for layer: {layer:?}");
|
||||
continue;
|
||||
};
|
||||
|
||||
// If point editing mode is enabled, select all the pasted points
|
||||
if tool_options.path_editing_mode.point_editing_mode {
|
||||
points_map.values().for_each(|point| state.select_point(ManipulatorPointId::Anchor(*point)));
|
||||
}
|
||||
// If segment editing mode is enabled, select all the pasted segments
|
||||
if tool_options.path_editing_mode.segment_editing_mode {
|
||||
segments_map.values().for_each(|segment| state.select_segment(*segment));
|
||||
}
|
||||
}
|
||||
|
||||
// If there are new layers created, we need to center them in the viewport
|
||||
if !new_layers.is_empty() {
|
||||
responses.add(Message::Defer(DeferMessage::AfterGraphRun {
|
||||
messages: vec![PortfolioMessage::CenterLayers { layers: new_layers }.into()],
|
||||
}));
|
||||
}
|
||||
|
||||
PathToolFsmState::Ready
|
||||
|
||||
@@ -245,7 +245,7 @@ impl EditorTestUtils {
|
||||
}
|
||||
|
||||
pub async fn create_raster_image(&mut self, image: graphene_std::raster::Image<Color>, mouse: Option<(f64, f64)>) {
|
||||
self.handle_message(PortfolioMessage::PasteImage {
|
||||
self.handle_message(PortfolioMessage::InsertImage {
|
||||
name: None,
|
||||
image,
|
||||
mouse,
|
||||
@@ -346,10 +346,10 @@ pub mod test_prelude {
|
||||
pub use super::FrontendMessageTestUtils;
|
||||
pub use crate::application::Editor;
|
||||
pub use crate::float_eq;
|
||||
pub use crate::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
pub use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
|
||||
pub use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
pub use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
pub use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
pub use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
pub use crate::messages::prelude::*;
|
||||
pub use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, is_layer_fed_by_node_of_name};
|
||||
|
||||
Generated
+9
-9
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1778106249,
|
||||
"narHash": "sha256-cM/AuKy5tMhwOOQIbha8ZRRMHVfNf7cv2aljIw+qoCg=",
|
||||
"lastModified": 1781825982,
|
||||
"narHash": "sha256-SlXKwIRIhrOSAcTjCB3ftPLzJWZStQIPS7J1FlZPnKk=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "6d015ea29630b7ad2402841386da2cb617a470a7",
|
||||
"rev": "469fd08d0bcf6926321fa973c6777fbc87785dd7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -17,11 +17,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1778869304,
|
||||
"narHash": "sha256-30sZNZoA1cqF5JNO9fVX+wgiQYjB7HJqqJ4ztCDeBZE=",
|
||||
"lastModified": 1782723713,
|
||||
"narHash": "sha256-oPXCU/SSUokcGaJREHibG1CBX3+s/W7orDWQOZDsEeQ=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "d233902339c02a9c334e7e593de68855ad26c4cb",
|
||||
"rev": "b5aa0fbd538984f6e3d201be0005b4463d8b09f8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -45,11 +45,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1778987862,
|
||||
"narHash": "sha256-V3qGt9P1eJP/r/1ONablphfGiH0RP4agQhrRANpDYx8=",
|
||||
"lastModified": 1782789458,
|
||||
"narHash": "sha256-CR55gKCChD9ffN1Ag5az20Z3RD4tylHlcM1SSohkMA8=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "6f44d8874ac29806c8d5cae42bf8e19ebb5ce0d3",
|
||||
"rev": "067959ef838c440558ca519cf08ca87f43c3db3a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -1,12 +1,171 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onMount, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { propertiesPanelLayout } from "/src/stores/portfolio";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
|
||||
let sectionsCol: LayoutCol | undefined;
|
||||
|
||||
// Interactive dragging to reorder Properties panel node sections (a selected layer's chain nodes, or pinned nodes)
|
||||
type DragState = { nodeId: bigint; startX: number; startY: number; active: boolean };
|
||||
let dragState: DragState | undefined = undefined;
|
||||
let dragging = false;
|
||||
let fromIndex: number | undefined = undefined;
|
||||
let insertIndex: number | undefined = undefined;
|
||||
let insertMarkerTop: number | undefined = undefined;
|
||||
let justFinishedDrag = false; // Used to suppress the click event that follows a drag release (which would otherwise toggle a section)
|
||||
|
||||
onMount(() => {
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
addEventListener("pointerup", draggingPointerUp);
|
||||
addEventListener("keydown", draggingKeyDown);
|
||||
addEventListener("mousedown", draggingMouseDown);
|
||||
// Capture phase so this runs before a section header's own click handler
|
||||
addEventListener("click", suppressClickAfterDrag, true);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("keydown", draggingKeyDown);
|
||||
removeEventListener("mousedown", draggingMouseDown);
|
||||
removeEventListener("click", suppressClickAfterDrag, true);
|
||||
});
|
||||
|
||||
function suppressClickAfterDrag(e: MouseEvent) {
|
||||
if (!justFinishedDrag) return;
|
||||
justFinishedDrag = false;
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
function reorderableSections(): Element[] {
|
||||
const container = sectionsCol?.div();
|
||||
if (!container) return [];
|
||||
return Array.from(container.querySelectorAll("[data-properties-reorderable-section]"));
|
||||
}
|
||||
|
||||
function sectionPointerDown(e: PointerEvent) {
|
||||
// Only left click drags
|
||||
if (e.button !== 0) return;
|
||||
|
||||
const target = e.target instanceof Element ? e.target : undefined;
|
||||
if (!target) return;
|
||||
|
||||
// The drag handle is the section header
|
||||
const handle = target.closest("[data-properties-reorder-handle]");
|
||||
if (!handle) return;
|
||||
|
||||
// Don't begin a drag when pressing one of the header's own buttons (pin/delete/visibility); only the header itself grabs
|
||||
if (target.closest("button") !== handle) return;
|
||||
|
||||
const section = target.closest("[data-properties-reorderable-section]");
|
||||
const nodeIdAttribute = section?.getAttribute("data-node-id");
|
||||
if (!section || !nodeIdAttribute) return;
|
||||
|
||||
dragState = { nodeId: BigInt(nodeIdAttribute), startX: e.clientX, startY: e.clientY, active: false };
|
||||
}
|
||||
|
||||
function draggingPointerMove(e: PointerEvent) {
|
||||
if (!dragState) return;
|
||||
|
||||
// Wait until the cursor has moved beyond the threshold before treating it as a drag (so a click still toggles the section)
|
||||
if (!dragState.active) {
|
||||
const distance = Math.hypot(e.clientX - dragState.startX, e.clientY - dragState.startY);
|
||||
const DRAG_THRESHOLD = 5;
|
||||
if (distance <= DRAG_THRESHOLD) return;
|
||||
|
||||
dragState.active = true;
|
||||
dragging = true;
|
||||
fromIndex = reorderableSections().findIndex((section) => section.getAttribute("data-node-id") === String(dragState?.nodeId));
|
||||
}
|
||||
|
||||
calculateInsertIndex(e.clientY);
|
||||
}
|
||||
|
||||
function calculateInsertIndex(clientY: number) {
|
||||
const container = sectionsCol?.div();
|
||||
const sections = reorderableSections();
|
||||
if (!container || sections.length === 0) {
|
||||
insertIndex = undefined;
|
||||
insertMarkerTop = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const scrollTop = container.scrollTop;
|
||||
// Convert a viewport Y to a position within the (scrollable) container's content, so the marker tracks the content when scrolled
|
||||
const toContentOffset = (viewportY: number) => viewportY - containerRect.top + scrollTop;
|
||||
|
||||
// The insertion index is the number of sections whose vertical midpoint sits above the cursor. The index flips only when
|
||||
// the cursor crosses a section's midpoint, so each gap maps to exactly one index (and gaps between sections are handled).
|
||||
let index = 0;
|
||||
for (let i = 0; i < sections.length; i += 1) {
|
||||
const rect = sections[i].getBoundingClientRect();
|
||||
if (clientY < (rect.top + rect.bottom) / 2) break;
|
||||
index = i + 1;
|
||||
}
|
||||
|
||||
// Position the marker purely from the gap index so it has one fixed spot per gap, rather than snapping between adjacent
|
||||
// sections' edges as the cursor crosses their shared boundary.
|
||||
let markerViewportY;
|
||||
if (index <= 0) {
|
||||
markerViewportY = sections[0].getBoundingClientRect().top - 2;
|
||||
} else if (index >= sections.length) {
|
||||
markerViewportY = sections[sections.length - 1].getBoundingClientRect().bottom + 2;
|
||||
} else {
|
||||
markerViewportY = (sections[index - 1].getBoundingClientRect().bottom + sections[index].getBoundingClientRect().top) / 2;
|
||||
}
|
||||
|
||||
insertIndex = index;
|
||||
insertMarkerTop = toContentOffset(markerViewportY);
|
||||
}
|
||||
|
||||
function draggingPointerUp() {
|
||||
if (dragState?.active) {
|
||||
// Suppress the click that the browser fires after the drag release, so it doesn't toggle the dropped section
|
||||
justFinishedDrag = true;
|
||||
|
||||
// Skip drops that don't actually move the node (into its own slot), or where the dragged section vanished from the DOM mid-drag (fromIndex of -1)
|
||||
if (insertIndex !== undefined && fromIndex !== undefined && fromIndex !== -1 && insertIndex !== fromIndex && insertIndex !== fromIndex + 1) {
|
||||
editor.reorderPropertiesSection(dragState.nodeId, insertIndex);
|
||||
}
|
||||
}
|
||||
|
||||
abortDrag();
|
||||
}
|
||||
|
||||
function draggingKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape" && dragState?.active) {
|
||||
abortDrag();
|
||||
}
|
||||
}
|
||||
|
||||
function draggingMouseDown(e: MouseEvent) {
|
||||
// Abort an in-progress drag if the user presses the right mouse button
|
||||
if (e.button === 2 && dragState?.active) {
|
||||
abortDrag();
|
||||
}
|
||||
}
|
||||
|
||||
function abortDrag() {
|
||||
dragState = undefined;
|
||||
dragging = false;
|
||||
fromIndex = undefined;
|
||||
insertIndex = undefined;
|
||||
insertMarkerTop = undefined;
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutCol class="properties">
|
||||
<LayoutCol class="sections" scrollableY={true}>
|
||||
<LayoutCol class="sections" classes={{ dragging }} scrollableY={true} bind:this={sectionsCol} on:pointerdown={sectionPointerDown}>
|
||||
<WidgetLayout layout={$propertiesPanelLayout} layoutTarget="PropertiesPanel" />
|
||||
{#if dragging && insertMarkerTop !== undefined}
|
||||
<div class="insert-mark" style:top={`${insertMarkerTop}px`}></div>
|
||||
{/if}
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
|
||||
@@ -17,6 +176,13 @@
|
||||
|
||||
.sections {
|
||||
flex: 1 1 100%;
|
||||
position: relative;
|
||||
|
||||
// While dragging a section, disable pointer events (which inherit down to the sections) so the drop doesn't toggle a section's expansion, and prevent text selection
|
||||
&.dragging {
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Used as a placeholder for empty assist widgets
|
||||
.separator.section.horizontal {
|
||||
@@ -27,6 +193,18 @@
|
||||
width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.insert-mark {
|
||||
position: absolute;
|
||||
left: 4px;
|
||||
right: 4px;
|
||||
background: var(--color-e-nearwhite);
|
||||
height: 5px;
|
||||
// The marker's `top` is the center of the gap, so shift up by half its height to straddle that line
|
||||
transform: translateY(-50%);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.text-button {
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
<LayoutCol class="bottom-message">
|
||||
{#if import.meta.env.MODE === "native"}
|
||||
<TextLabel italic={true} disabled={true}>
|
||||
You are testing Release Candidate 5 of the 1.0 desktop release. Please regularly check Discord for the next testing build and report issues you encounter.
|
||||
You are testing Release Candidate 6 of the 1.0 desktop release. Please regularly check Discord for the next testing build and report issues you encounter.
|
||||
</TextLabel>
|
||||
{:else if new Date() < new Date(2026, 10, 1)}
|
||||
<TextLabel italic={true} disabled={true}>
|
||||
|
||||
@@ -13,14 +13,24 @@
|
||||
export { className as class };
|
||||
export let classes: Record<string, boolean> = {};
|
||||
|
||||
let expanded = true;
|
||||
// Whether the section is expanded is owned by the backend (persisted per node), so just reflect it here
|
||||
$: expanded = widgetData.expanded;
|
||||
|
||||
// A reorderable section is a Properties panel node section the user can drag to reorder (a layer chain's node, or a pinned node)
|
||||
$: reorderable = layoutTarget === "PropertiesPanel" && widgetData.draggable;
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with properties system -->
|
||||
<LayoutCol class={`widget-section ${className}`.trim()} {classes}>
|
||||
<button class="header" class:expanded on:click|stopPropagation={() => (expanded = !expanded)} tabindex="0">
|
||||
<LayoutCol class={`widget-section ${className}`.trim()} {classes} data-properties-reorderable-section={reorderable ? "" : undefined} data-node-id={reorderable ? String(widgetData.id) : undefined}>
|
||||
<button
|
||||
class="header"
|
||||
class:expanded
|
||||
data-properties-reorder-handle={reorderable ? "" : undefined}
|
||||
on:click|stopPropagation={() => editor.toggleNodePropertiesSectionExpanded(widgetData.id)}
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="expand-arrow"></div>
|
||||
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description} bold={true}>{widgetData.name}</TextLabel>
|
||||
<IconButton
|
||||
|
||||
@@ -36,6 +36,13 @@
|
||||
let activeMarkerIsMidpointRestore = false;
|
||||
// Tracks whether a midpoint drag has actually moved by at least one frame, to distinguish click-to-select from drag.
|
||||
let midpointDragged = false;
|
||||
// Mirrors whether Alt is currently held during the drag (the desired state).
|
||||
let duplicateRequested = false;
|
||||
// Mirrors whether a frozen copy currently exists in the gradient (the materialized state).
|
||||
let duplicateActive = false;
|
||||
// Set when a key-triggered reconcile inserts/removes the frozen copy, so the next pointer move skips emitting a `MoveMarker`
|
||||
// that would otherwise race the structural change before Rust has reported the dragged marker's new index.
|
||||
let skipNextMove = false;
|
||||
|
||||
function emit(intent: SpectrumInputUpdate) {
|
||||
dispatch("update", intent);
|
||||
@@ -68,6 +75,9 @@
|
||||
activeMarkerIsMidpointRestore = activeMarkerIsMidpoint;
|
||||
dragRestorePosition = markers[index].position;
|
||||
dragInsertedMarker = false;
|
||||
// Only offer duplication where new stops are allowed. Don't materialize yet: wait for the first move so an Alt-click without a drag leaves no stray copy.
|
||||
duplicateRequested = allowInsert && e.altKey;
|
||||
duplicateActive = false;
|
||||
setActive(index, false);
|
||||
addEvents();
|
||||
return;
|
||||
@@ -118,7 +128,10 @@
|
||||
activeMarkerIsMidpointRestore = activeMarkerIsMidpoint;
|
||||
dragRestorePosition = position;
|
||||
dragInsertedMarker = true;
|
||||
// Don't dispatch an `ActiveMarker` here — the Rust handler already updates the active marker in response to `InsertMarker` and a duplicate `ActiveMarker` would race the layout update.
|
||||
// A stop being created by this drag can't be duplicated; duplication is only for dragging an existing stop.
|
||||
duplicateRequested = false;
|
||||
duplicateActive = false;
|
||||
// Don't dispatch an `ActiveMarker` here. The Rust handler already updates the active marker in response to `InsertMarker` and a duplicate `ActiveMarker` would race the layout update.
|
||||
activeMarkerIndex = insertIndex;
|
||||
activeMarkerIsMidpoint = false;
|
||||
addEvents();
|
||||
@@ -134,10 +147,78 @@
|
||||
else if (allowDelete) emit({ DeleteMarker: { index: activeMarkerIndex } });
|
||||
}
|
||||
|
||||
// Locate the frozen copy left by a duplicate: the non-dragged marker sitting (within epsilon) at the drag's start position.
|
||||
// Returns undefined if no marker is close enough, so a stale `markers` prop can never delete an unrelated stop.
|
||||
function findDuplicateAnchorIndex(): number | undefined {
|
||||
// The frozen copy is inserted at exactly the drag's start position and round-trips through Rust losslessly, so it matches within this tolerance
|
||||
const DUPLICATE_POSITION_EPSILON = 1e-6;
|
||||
|
||||
if (dragRestorePosition === undefined) return undefined;
|
||||
|
||||
const startPosition = dragRestorePosition;
|
||||
|
||||
let best: number | undefined = undefined;
|
||||
let bestDistance = DUPLICATE_POSITION_EPSILON;
|
||||
|
||||
markers.forEach((marker, index) => {
|
||||
if (index === activeMarkerIndex) return;
|
||||
|
||||
const distance = Math.abs(marker.position - startPosition);
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
best = index;
|
||||
}
|
||||
});
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
// Bring the materialized duplicate state in line with whether Alt is currently held, inserting or removing the frozen copy.
|
||||
// Returns whether a structural change was emitted, so callers can skip the next move that would race it.
|
||||
function reconcileDuplicate(): boolean {
|
||||
if (!allowInsert || activeMarkerIndex === undefined || activeMarkerIsMidpoint) return false;
|
||||
|
||||
if (duplicateRequested && !duplicateActive) {
|
||||
// Drop a frozen copy at the drag's start position. The dragged marker stays active and becomes the duplicate being moved.
|
||||
|
||||
if (dragRestorePosition === undefined) return false;
|
||||
|
||||
emit({ InsertDuplicate: { index: activeMarkerIndex, position: dragRestorePosition } });
|
||||
duplicateActive = true;
|
||||
|
||||
return true;
|
||||
} else if (!duplicateRequested && duplicateActive) {
|
||||
// Remove the frozen copy so only the dragged marker remains, as if it had been dragged all along.
|
||||
|
||||
const anchor = findDuplicateAnchorIndex();
|
||||
if (anchor === undefined) return false;
|
||||
|
||||
emit({ RemoveDuplicate: { index: anchor } });
|
||||
duplicateActive = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function moveActiveMarker(e: PointerEvent) {
|
||||
if (disabled || activeMarkerIndex === undefined) return;
|
||||
if (e.buttons === 0) {
|
||||
stopDrag();
|
||||
endDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
// Materialize/remove the frozen copy if Alt's state changed without a key event reconciling it first (e.g. Alt held at drag start).
|
||||
// Skip this frame's move. The next move runs once Rust has reported the dragged marker's new index.
|
||||
if (duplicateRequested !== duplicateActive) {
|
||||
reconcileDuplicate();
|
||||
return;
|
||||
}
|
||||
|
||||
// A key event (Alt press/release) already reconciled. Skip the one move that would race that structural change.
|
||||
if (skipNextMove) {
|
||||
skipNextMove = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -152,7 +233,7 @@
|
||||
function moveActiveMidpoint(e: PointerEvent) {
|
||||
if (disabled || activeMarkerIndex === undefined) return;
|
||||
if (e.buttons === 0) {
|
||||
stopDrag();
|
||||
endDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -173,18 +254,30 @@
|
||||
function abortDrag() {
|
||||
if (disabled || activeMarkerIndex === undefined) return;
|
||||
|
||||
// Restore the dragged value, or delete the marker if it was inserted as part of this drag.
|
||||
const dragged = activeMarkerIndex;
|
||||
const anchor = duplicateActive ? findDuplicateAnchorIndex() : undefined;
|
||||
|
||||
if (dragInsertedMarker) {
|
||||
emit({ DeleteMarker: { index: activeMarkerIndex } });
|
||||
// The dragged marker was created by this drag, so delete it.
|
||||
emit({ DeleteMarker: { index: dragged } });
|
||||
} else if (anchor !== undefined) {
|
||||
// A duplicated pre-existing marker: the frozen copy already sits at the start position, so deleting the dragged copy restores the original.
|
||||
emit({ DeleteMarker: { index: dragged } });
|
||||
} else if (dragRestorePosition !== undefined) {
|
||||
if (activeMarkerIsMidpoint) emit({ MoveMidpoint: { index: activeMarkerIndex, position: dragRestorePosition } });
|
||||
else emit({ MoveMarker: { index: activeMarkerIndex, position: dragRestorePosition } });
|
||||
// Plain drag: return the marker (or midpoint) to where it began.
|
||||
if (activeMarkerIsMidpoint) emit({ MoveMidpoint: { index: dragged, position: dragRestorePosition } });
|
||||
else emit({ MoveMarker: { index: dragged, position: dragRestorePosition } });
|
||||
}
|
||||
|
||||
setActive(activeMarkerIndexRestore, activeMarkerIsMidpointRestore);
|
||||
stopDrag();
|
||||
}
|
||||
|
||||
function endDrag() {
|
||||
if (!duplicateRequested && duplicateActive) reconcileDuplicate();
|
||||
stopDrag();
|
||||
}
|
||||
|
||||
function stopDrag() {
|
||||
removeEvents();
|
||||
dragRestorePosition = undefined;
|
||||
@@ -192,6 +285,9 @@
|
||||
activeMarkerIndexRestore = undefined;
|
||||
activeMarkerIsMidpointRestore = false;
|
||||
midpointDragged = false;
|
||||
duplicateRequested = false;
|
||||
duplicateActive = false;
|
||||
skipNextMove = false;
|
||||
dispatch("dragging", false);
|
||||
}
|
||||
|
||||
@@ -201,7 +297,7 @@
|
||||
}
|
||||
|
||||
function onPointerUp() {
|
||||
stopDrag();
|
||||
endDrag();
|
||||
}
|
||||
|
||||
function onMouseDown(e: MouseEvent) {
|
||||
@@ -214,6 +310,23 @@
|
||||
const element = markerTrackElement?.div();
|
||||
if (element) preventEscapeClosingParentFloatingMenu(element);
|
||||
abortDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
// Pressing Alt mid-drag duplicates the marker, leaving a frozen copy where the drag began. Reconcile immediately for instant
|
||||
// feedback, and arm a skip so the next pointer move doesn't race the just-emitted structural change. Only when dragging an
|
||||
// existing stop (not one being created by this drag).
|
||||
if (e.key === "Alt" && allowInsert && !activeMarkerIsMidpoint && !dragInsertedMarker && !duplicateRequested) {
|
||||
duplicateRequested = true;
|
||||
if (reconcileDuplicate()) skipNextMove = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onKeyUp(e: KeyboardEvent) {
|
||||
// Releasing Alt mid-drag removes the frozen copy immediately, as if the marker had been dragged all along (likewise armed to skip the next move).
|
||||
if (e.key === "Alt" && duplicateRequested) {
|
||||
duplicateRequested = false;
|
||||
if (reconcileDuplicate()) skipNextMove = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,6 +335,7 @@
|
||||
document.addEventListener("pointerup", onPointerUp);
|
||||
document.addEventListener("mousedown", onMouseDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
document.addEventListener("keyup", onKeyUp);
|
||||
}
|
||||
|
||||
function removeEvents() {
|
||||
@@ -229,6 +343,7 @@
|
||||
document.removeEventListener("pointerup", onPointerUp);
|
||||
document.removeEventListener("mousedown", onMouseDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
document.removeEventListener("keyup", onKeyUp);
|
||||
}
|
||||
|
||||
// Map midpoint pairs to absolute track positions for rendering the diamond markers.
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
{#if $tooltip.visible}
|
||||
<Tooltip />
|
||||
{/if}
|
||||
{#if import.meta.env.MODE === "native" && new Date() > new Date("2026-07-01")}
|
||||
{#if import.meta.env.MODE === "native" && new Date() > new Date("2026-12-31")}
|
||||
<LayoutCol class="release-candidate-expiry">
|
||||
<TextLabel>
|
||||
<p>
|
||||
|
||||
@@ -756,6 +756,15 @@ impl EditorWrapper {
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Reorder a draggable Properties panel section to the given index among its peers.
|
||||
#[wasm_bindgen(js_name = reorderPropertiesSection)]
|
||||
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
|
||||
self.dispatch(DocumentMessage::ReorderPropertiesSection {
|
||||
node_id: NodeId(node_id),
|
||||
insert_index,
|
||||
});
|
||||
}
|
||||
|
||||
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
|
||||
/// If the folder is `None`, they are inserted into the document root.
|
||||
/// If the insert index is `None`, they are inserted at the start of the folder.
|
||||
@@ -877,7 +886,7 @@ impl EditorWrapper {
|
||||
None
|
||||
};
|
||||
|
||||
let message = PortfolioMessage::PasteImage {
|
||||
let message = PortfolioMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
@@ -899,7 +908,7 @@ impl EditorWrapper {
|
||||
None
|
||||
};
|
||||
|
||||
let message = PortfolioMessage::PasteSvg {
|
||||
let message = PortfolioMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
@@ -922,6 +931,12 @@ impl EditorWrapper {
|
||||
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
|
||||
}
|
||||
|
||||
/// Collapse or expand a node's section in the Properties panel
|
||||
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
|
||||
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
|
||||
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
|
||||
}
|
||||
|
||||
/// Delete a layer or node given its node ID
|
||||
#[wasm_bindgen(js_name = deleteNode)]
|
||||
pub fn delete_node(&self, id: u64) {
|
||||
|
||||
@@ -2202,7 +2202,7 @@ impl Render for List<GradientStops> {
|
||||
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Premultiplied,
|
||||
..Default::default()
|
||||
});
|
||||
let brush_transform = kurbo::Affine::new((gradient_transform).to_cols_array());
|
||||
let brush_transform = kurbo::Affine::new(gradient_placement(gradient_transform, gradient_type).to_cols_array());
|
||||
let rect = kurbo::Rect::from_origin_size(kurbo::Point::ZERO, kurbo::Size::new(1., 1.));
|
||||
|
||||
let mut layer = false;
|
||||
|
||||
@@ -274,6 +274,18 @@ impl GradientStops {
|
||||
index
|
||||
}
|
||||
|
||||
/// Insert a copy of the stop at `source_index` (same color and midpoint) at `position`, keeping the stops sorted by position.
|
||||
/// Returns the index where the copy was inserted, or `None` if `source_index` is out of range.
|
||||
pub fn duplicate_stop(&mut self, source_index: usize, position: f64) -> Option<usize> {
|
||||
let color = *self.color.get(source_index)?;
|
||||
let midpoint = *self.midpoint.get(source_index)?;
|
||||
let index = self.position.iter().position(|p| *p > position).unwrap_or(self.position.len());
|
||||
self.position.insert(index, position);
|
||||
self.midpoint.insert(index, midpoint);
|
||||
self.color.insert(index, color);
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Reset the midpoint for the interval starting at `index` to its default `0.5`.
|
||||
pub fn reset_midpoint(&mut self, index: usize) {
|
||||
if let Some(midpoint) = self.midpoint.get_mut(index) {
|
||||
|
||||
@@ -58,7 +58,7 @@ impl graphene_hash::CacheHash for Vector {
|
||||
impl core_types::ops::FromAnchorPosition for Vector {
|
||||
fn from_anchor_position(position: DVec2) -> Self {
|
||||
let mut point_domain = PointDomain::new();
|
||||
point_domain.push(PointId::generate(), position);
|
||||
point_domain.push(PointId::ZERO, position);
|
||||
|
||||
Self { point_domain, ..Default::default() }
|
||||
}
|
||||
@@ -646,7 +646,7 @@ mod tests {
|
||||
let vector = Vector::from_anchor_position(DVec2::new(3., 4.));
|
||||
|
||||
assert_eq!(vector.point_domain.positions(), [DVec2::new(3., 4.)]);
|
||||
assert_eq!(vector.point_domain.ids().len(), 1);
|
||||
assert_eq!(vector.point_domain.ids(), [PointId::ZERO], "expected the anchor position to be assigned the default PointId::ZERO",);
|
||||
assert!(vector.segment_domain.ids().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,10 @@ pub fn frontend_dir() -> PathBuf {
|
||||
workspace_dir().join("frontend")
|
||||
}
|
||||
|
||||
fn wasm_glue_path() -> PathBuf {
|
||||
frontend_dir().join("wrapper").join("pkg").join(format!("{OUT_NAME}.js"))
|
||||
}
|
||||
|
||||
pub fn setup() -> Result<(), Error> {
|
||||
let frontend = frontend_dir();
|
||||
let node_modules = frontend.join("node_modules");
|
||||
@@ -52,7 +56,13 @@ pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
|
||||
cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET)
|
||||
.arg_if(release, "--release")
|
||||
.args_if(native, ["--no-default-features", "--features", "native"])
|
||||
.dir(workspace_dir()),
|
||||
.dir(workspace_dir())
|
||||
.before_spawn(|_| {
|
||||
if is_build_corrupted() {
|
||||
clean_wasm();
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
cmd!("wasm-bindgen", "--target", "web", "--out-name", OUT_NAME, "--out-dir", &pkg_dir, &wasm_artifact)
|
||||
.arg_if(release, "--no-demangle")
|
||||
.arg_if(!release, "--debug"),
|
||||
@@ -66,6 +76,25 @@ pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
|
||||
steps
|
||||
}
|
||||
|
||||
pub fn clean_wasm() -> bool {
|
||||
let wasm_target_dir = target_dir().join(WASM_TARGET);
|
||||
eprintln!("The Wasm build emitted undefined `env` imports, a sign of corrupt incremental artifacts (typically from an interrupted build).");
|
||||
eprintln!("Fixing by wiping `{}` and rebuilding...", wasm_target_dir.display());
|
||||
match std::fs::remove_dir_all(&wasm_target_dir) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => eprintln!("warning: could not fully clean `{}`: {e}", wasm_target_dir.display()),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn is_build_corrupted() -> bool {
|
||||
let Ok(js) = std::fs::read_to_string(wasm_glue_path()) else {
|
||||
return false;
|
||||
};
|
||||
js.contains("from \"env\"") || js.contains("from 'env'")
|
||||
}
|
||||
|
||||
pub fn vite() -> Expression {
|
||||
utils::node_bin("vite/bin/vite.js").dir(frontend_dir()).env("CARGO_TARGET_DIR", target_dir())
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ meta_description = "Open source free software. A vector graphics creativity suit
|
||||
<section id="screenshots" class="carousel window-size-1" data-carousel data-carousel-jostle-hint>
|
||||
|
||||
<div class="carousel-slide" data-carousel-slide>
|
||||
<img src="https://static.graphite.art/content/index/gui-demo-creative-coding-poster.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="" style="transform: translateX(-100%)" data-carousel-image />
|
||||
<img src="https://static.graphite.art/content/index/gui-demo-fractal__4.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="" style="transform: translateX(-100%)" data-carousel-image />
|
||||
<!-- Above is a copy of the last -->
|
||||
<img onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="" style="transform: translateX(-100%)" data-carousel-image width="1920" height="1080" loading="lazy" src="https://static.graphite.art/content/index/gui-demo-painted-dreams__4.avif" />
|
||||
<img onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="" style="transform: translateX(-100%)" data-carousel-image width="1920" height="1080" loading="lazy" src="https://static.graphite.art/content/index/gui-demo-magazine-page-layout.avif" />
|
||||
@@ -165,9 +165,7 @@ The latest major update is out now! See what the team has been cooking up recent
|
||||
|
||||
<div class="block video-container">
|
||||
<div>
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="U3E-sWo2H_M" loading="lazy" src="https://static.graphite.art/content/index/video-may-2026-update.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="May Update - Graphite, the Open Source 2D Graphics Suite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="U3E-sWo2H_M", title="May Update - Graphite, the Open Source 2D Graphics Suite") }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -496,9 +494,7 @@ Get started with Graphite by following along to a hands-on quickstart tutorial.
|
||||
|
||||
<div class="block video-container">
|
||||
<div>
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="7gjUhl_3X10" loading="lazy" src="https://static.graphite.art/content/learn/introduction/tutorial-1-vector-art-quickstart-youtube__2.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="7gjUhl_3X10", title="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite") }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -93,9 +93,7 @@ The next big news of August was my formation of [Graphite Labs, LLC](https://www
|
||||
|
||||
I allocated my time at several points throughout the year into growing and evolving this website with a refreshed and more visually-appealing home page, dedicated pages for information [about](/about) the project and its [features](/features), an area providing resources and help for [volunteers](/volunteer) and [code contributors](/volunteer/guide), and just this month— a [user manual](/learn) complete with an introductory tutorial series. The first video went up yesterday:
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="7gjUhl_3X10" src="https://static.graphite.art/content/learn/introduction/tutorial-1-vector-art-quickstart-youtube__2.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="7gjUhl_3X10", title="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite") }}
|
||||
|
||||
The user manual and tutorial series will continue expanding throughout the coming weeks. Additional website features including user accounts, forums, and other community features are being planned.
|
||||
|
||||
|
||||
+1
-3
@@ -119,9 +119,7 @@ The next month in April, Oliver and I went to our second conference of the year:
|
||||
|
||||
I also took to the main stage to present a lightning talk introducing Graphite to the community:
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img src="https://static.graphite.art/content/blog/2025-01-16-year-in-review-2024-highlights-and-a-peek-at-2025/bcon-la-talk-video-cover.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" data-youtube-embed="x3P5eYv11EU" data-youtube-timestamp="1603" alt="BCON LA 2024 - Lightning Talks" />
|
||||
</div>
|
||||
{{ youtube_embed(id="x3P5eYv11EU", timestamp=1603, title="BCON LA 2024 - Lightning Talks") }}
|
||||
|
||||
### Graphite booth at Open Sauce
|
||||
|
||||
|
||||
@@ -24,9 +24,7 @@ Do you love Rust and focus on computer graphics, compiler development, or algori
|
||||
|
||||
Hear from our mentoring team about Graphite's tech stack and engineering vision by listening to last month's episode of the Developer Voices podcast:
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="ZUbcwUC5lxA" src="https://static.graphite.art/content/blog/2025-04-02-internships-for-a-rust-graphics-engine-gsoc-2025/developer-voices-podcast-youtube.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Graphite: Image Editing as a Syntax Tree (with Keavon Chambers & Dennis Kobert)" />
|
||||
</div>
|
||||
{{ youtube_embed(id="ZUbcwUC5lxA", title="Graphite: Image Editing as a Syntax Tree (with Keavon Chambers & Dennis Kobert)") }}
|
||||
|
||||
For GSoC 2025, our priority focus is mentoring projects revolving around advanced graphics techniques and compiler development, meeting our goal of extending Graphite into the domain of raster image manipulation. Demonstrated experience in these areas is highly advantageous.
|
||||
|
||||
|
||||
@@ -21,9 +21,7 @@ The current alpha version of Graphite is a tool for vector art and graphic desig
|
||||
|
||||
<div class="block video-container">
|
||||
<div>
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="ZUbcwUC5lxA" loading="lazy" src="https://static.graphite.art/content/features/podcast-interview-youtube.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Rust-Powered Graphics Editor: How Graphite's Syntax Trees Revolutionize Image Editing" />
|
||||
</div>
|
||||
{{ youtube_embed(id="ZUbcwUC5lxA", title="Rust-Powered Graphics Editor: How Graphite's Syntax Trees Revolutionize Image Editing") }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -25,6 +25,4 @@ If you're ever stuck or confused, ask your questions in the `#🧭user-help` cha
|
||||
|
||||
The fastest way to get started is to watch and follow along steps-by-step in the hands-on quickstart tutorial:
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="7gjUhl_3X10" src="https://static.graphite.art/content/learn/introduction/tutorial-1-vector-art-quickstart-youtube__2.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="7gjUhl_3X10", title="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite") }}
|
||||
@@ -15,8 +15,6 @@ Begin learning Graphite by watching the introductory tutorial video below.
|
||||
|
||||
One is available now, and more will be released on a regular basis throughout early 2026.
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="7gjUhl_3X10" src="https://static.graphite.art/content/learn/introduction/tutorial-1-vector-art-quickstart-youtube__2.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="7gjUhl_3X10", title="Vector Art Quickstart - Graphite, the Open Source 2D Graphics Suite") }}
|
||||
|
||||
*More tutorials coming soon.*
|
||||
@@ -11,9 +11,7 @@ css = ["/component/youtube-embed.css", "/page/contributor-guide/crate-hierarchy.
|
||||
|
||||
The best introduction for getting up-to-speed with Graphite contribution comes from watching this webcast recording. Before asking questions in Discord, please watch the full video because it gives a comprehensive overview of most things you will need to know.
|
||||
|
||||
<div class="youtube-embed aspect-16x9">
|
||||
<img data-youtube-embed="vUzIeg8frh4" src="https://static.graphite.art/content/volunteer/guide/workshop-intro-to-coding-for-graphite-youtube.avif" onerror="this.onerror = null; this.src = this.src.replace('.avif', '.png')" alt="Workshop: Intro to Coding for Graphite" />
|
||||
</div>
|
||||
{{ youtube_embed(id="vUzIeg8frh4", title="Workshop: Intro to Coding for Graphite") }}
|
||||
|
||||
## Codebase structure
|
||||
|
||||
|
||||
@@ -1,21 +1,78 @@
|
||||
.youtube-embed {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
padding-top: calc(100% / (16 / 9));
|
||||
// Lets the overlay chrome scale proportionally with the player's width via `cqw` units
|
||||
container-type: inline-size;
|
||||
|
||||
&.aspect-16x9 {
|
||||
padding-top: calc(100% / (16 / 9));
|
||||
}
|
||||
|
||||
img,
|
||||
.youtube-embed-thumbnail,
|
||||
.youtube-embed-shade,
|
||||
iframe {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
inset: 0;
|
||||
border: none;
|
||||
}
|
||||
|
||||
img {
|
||||
.youtube-embed-thumbnail {
|
||||
cursor: pointer;
|
||||
object-fit: cover;
|
||||
background: #000;
|
||||
}
|
||||
|
||||
.youtube-embed-shade {
|
||||
height: 8.75cqw;
|
||||
background: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.6), transparent);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.youtube-embed-play {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 8.5cqw;
|
||||
height: auto;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.youtube-embed-title {
|
||||
position: absolute;
|
||||
top: 1cqw;
|
||||
left: 3.4cqw;
|
||||
right: 3.4cqw;
|
||||
font-size: 2.5cqw;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-decoration: none;
|
||||
color: #fff;
|
||||
mask-image: linear-gradient(to right, #fff 95%, transparent);
|
||||
}
|
||||
|
||||
.youtube-embed-watch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
position: absolute;
|
||||
border-radius: 3cqw;
|
||||
height: 6cqw;
|
||||
right: 3.6cqw;
|
||||
bottom: 1.5cqw;
|
||||
padding: 0 3cqw;
|
||||
gap: 0.5cqw;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
font-size: 2.25cqw;
|
||||
font-weight: 400;
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
background: rgba(40, 40, 40, 0.6);
|
||||
}
|
||||
|
||||
img {
|
||||
height: 2.3cqw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,28 @@
|
||||
window.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll("[data-youtube-embed]").forEach((placeholder) => {
|
||||
if (!(placeholder instanceof HTMLElement)) return;
|
||||
placeholder.addEventListener("click", () => {
|
||||
|
||||
const loadIframe = () => {
|
||||
const videoId = placeholder.getAttribute("data-youtube-embed") || "";
|
||||
const timestamp = placeholder.getAttribute("data-youtube-timestamp") || "";
|
||||
placeholder.outerHTML = `
|
||||
<iframe \\
|
||||
width="1280" \\
|
||||
height="720" \\
|
||||
src="https://www.youtube.com/embed/${videoId}?${timestamp ? `start=${timestamp}&` : ""}autoplay=1" \\
|
||||
frameborder="0" \\
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" \\
|
||||
allowfullscreen\\
|
||||
>\\
|
||||
</iframe>\\
|
||||
`
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.join("")
|
||||
.replaceAll(`\\`, "");
|
||||
|
||||
const iframe = document.createElement("iframe");
|
||||
iframe.width = "1280";
|
||||
iframe.height = "720";
|
||||
iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1${timestamp ? `&start=${timestamp}` : ""}`;
|
||||
iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
|
||||
iframe.allowFullscreen = true;
|
||||
|
||||
const embed = placeholder.closest("[data-youtube-embed]");
|
||||
embed?.replaceChildren(iframe);
|
||||
};
|
||||
|
||||
placeholder.addEventListener("click", loadIframe);
|
||||
placeholder.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
loadIframe();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{%- set alt = alt | default(value = title) -%}
|
||||
{%- set timestamp = timestamp | default(value = 0) -%}
|
||||
{%- set watch_url = "https://www.youtube.com/watch?v=" ~ id -%}
|
||||
{%- if timestamp %}{% set watch_url = watch_url ~ "&t=" ~ timestamp %}{% endif -%}
|
||||
<div class="youtube-embed" data-youtube-embed="{{ id }}" {% if timestamp %}data-youtube-timestamp="{{ timestamp }}"{% endif %} role="button" tabindex="0">
|
||||
<img class="youtube-embed-thumbnail" loading="lazy" src="https://img.youtube.com/vi/{{ id }}/maxresdefault.jpg" onload="if (this.naturalWidth < 1000 && this.src.includes('maxresdefault')) this.src = 'https://img.youtube.com/vi/{{ id }}/hqdefault.jpg'" onerror="this.onerror = null; this.src = 'https://img.youtube.com/vi/{{ id }}/hqdefault.jpg'" alt="{{ alt }}" />
|
||||
<div class="youtube-embed-shade"></div>
|
||||
<img class="youtube-embed-play" src="https://static.graphite.art/icons/youtube-embed-play.svg" />
|
||||
<a class="youtube-embed-title" href="{{ watch_url }}" target="_blank" rel="noopener">{{ title }}</a>
|
||||
<a class="youtube-embed-watch" href="{{ watch_url }}" target="_blank" rel="noopener">
|
||||
<span>Watch on</span>
|
||||
<img src="https://static.graphite.art/icons/youtube-embed-logo.svg" alt="YouTube" />
|
||||
</a>
|
||||
</div>
|
||||
Reference in new issue
Block a user