repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/lib.rs | desktop/src/lib.rs | use clap::Parser;
use std::process::exit;
use tracing_subscriber::EnvFilter;
use winit::event_loop::EventLoop;
pub(crate) mod consts;
mod app;
mod cef;
mod cli;
mod dirs;
mod event;
mod persist;
mod render;
mod window;
mod gpu_context;
pub(crate) use graphite_desktop_wrapper as wrapper;
use app::App;
use cef::CefHandler;
use cli::Cli;
use event::CreateAppEventSchedulerEventLoopExt;
use crate::consts::APP_LOCK_FILE_NAME;
pub fn start() {
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
let cef_context_builder = cef::CefContextBuilder::<CefHandler>::new();
if cef_context_builder.is_sub_process() {
// We are in a CEF subprocess
// This will block until the CEF subprocess quits
let error = cef_context_builder.execute_sub_process();
tracing::warn!("Cef subprocess failed with error: {error}");
return;
}
let mut lock = pidlock::Pidlock::new_validated(dirs::app_data_dir().join(APP_LOCK_FILE_NAME)).unwrap();
match lock.acquire() {
Ok(lock) => {
tracing::info!("Acquired application lock");
lock
}
Err(pidlock::PidlockError::LockExists) => {
tracing::error!("Another instance is already running, Exiting.");
exit(0);
}
Err(err) => {
tracing::error!("Failed to acquire application lock: {err}");
exit(1);
}
};
App::init();
let cli = Cli::parse();
let wgpu_context = futures::executor::block_on(gpu_context::create_wgpu_context());
let event_loop = EventLoop::new().unwrap();
let (app_event_sender, app_event_receiver) = std::sync::mpsc::channel();
let app_event_scheduler = event_loop.create_app_event_scheduler(app_event_sender);
let (cef_view_info_sender, cef_view_info_receiver) = std::sync::mpsc::channel();
let cef_handler = cef::CefHandler::new(wgpu_context.clone(), app_event_scheduler.clone(), cef_view_info_receiver);
let cef_context = match cef_context_builder.initialize(cef_handler, cli.disable_ui_acceleration) {
Ok(c) => {
tracing::info!("CEF initialized successfully");
c
}
Err(cef::InitError::AlreadyRunning) => {
tracing::error!("Another instance is already running, Exiting.");
exit(1);
}
Err(cef::InitError::InitializationFailed(code)) => {
tracing::error!("Cef initialization failed with code: {code}");
exit(1);
}
Err(cef::InitError::BrowserCreationFailed) => {
tracing::error!("Failed to create CEF browser");
exit(1);
}
Err(cef::InitError::RequestContextCreationFailed) => {
tracing::error!("Failed to create CEF request context");
exit(1);
}
};
let mut app = App::new(Box::new(cef_context), cef_view_info_sender, wgpu_context, app_event_receiver, app_event_scheduler, cli.files);
event_loop.run_app(&mut app).unwrap();
}
pub fn start_helper() {
let cef_context_builder = cef::CefContextBuilder::<CefHandler>::new_helper();
assert!(cef_context_builder.is_sub_process());
cef_context_builder.execute_sub_process();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cli.rs | desktop/src/cli.rs | #[derive(clap::Parser)]
#[clap(name = "graphite", version)]
pub struct Cli {
#[arg(help = "Files to open on startup")]
pub files: Vec<std::path::PathBuf>,
#[arg(long, action = clap::ArgAction::SetTrue, help = "Disable hardware accelerated UI rendering")]
pub disable_ui_acceleration: bool,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef.rs | desktop/src/cef.rs | //! CEF (Chromium Embedded Framework) integration for Graphite Desktop
//!
//! This module provides CEF browser integration with hardware-accelerated texture sharing.
//!
//! # Hardware Acceleration
//!
//! The texture import system supports platform-specific hardware acceleration:
//!
//! - **Linux**: DMA-BUF via Vulkan external memory (`accelerated_paint_dmabuf` feature)
//! - **Windows**: D3D11 shared textures via either Vulkan or D3D12 interop (`accelerated_paint_d3d11` feature)
//! - **macOS**: IOSurface via Metal/Vulkan interop (`accelerated_paint_iosurface` feature)
//!
//! The system gracefully falls back to CPU textures when hardware acceleration is unavailable.
use std::fs::File;
use std::io;
use std::io::Read;
use std::path::PathBuf;
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use crate::event::{AppEvent, AppEventScheduler};
use crate::render::FrameBufferRef;
use crate::window::Cursor;
use crate::wrapper::{WgpuContext, deserialize_editor_message};
mod consts;
mod context;
mod dirs;
mod input;
mod internal;
mod ipc;
mod platform;
mod utility;
#[cfg(feature = "accelerated_paint")]
use cef::osr_texture_import::SharedTextureHandle;
pub(crate) use context::{CefContext, CefContextBuilder, InitError};
pub(crate) trait CefEventHandler: Send + Sync + 'static {
fn view_info(&self) -> ViewInfo;
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>);
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle);
fn load_resource(&self, path: PathBuf) -> Option<Resource>;
fn cursor_change(&self, cursor: Cursor);
/// Schedule the main event loop to run the CEF event loop after the timeout.
/// See [`_cef_browser_process_handler_t::on_schedule_message_pump_work`] for more documentation.
fn schedule_cef_message_loop_work(&self, scheduled_time: Instant);
fn initialized_web_communication(&self);
fn receive_web_message(&self, message: &[u8]);
fn duplicate(&self) -> Self
where
Self: Sized;
}
#[derive(Clone, Copy)]
pub(crate) struct ViewInfo {
width: u32,
height: u32,
scale: f64,
}
impl ViewInfo {
pub(crate) fn new() -> Self {
Self { width: 1, height: 1, scale: 1. }
}
pub(crate) fn apply_update(&mut self, update: ViewInfoUpdate) {
match update {
ViewInfoUpdate::Size { width, height } if width > 0 && height > 0 => {
self.width = width;
self.height = height;
}
ViewInfoUpdate::Scale(scale) if scale > 0. => {
self.scale = scale;
}
_ => {}
}
}
pub(crate) fn zoom(&self) -> f64 {
self.scale.ln() / 1.2_f64.ln()
}
pub(crate) fn width(&self) -> u32 {
self.width
}
pub(crate) fn height(&self) -> u32 {
self.height
}
}
impl Default for ViewInfo {
fn default() -> Self {
Self::new()
}
}
pub(crate) enum ViewInfoUpdate {
Size { width: u32, height: u32 },
Scale(f64),
}
#[derive(Clone)]
pub(crate) struct Resource {
pub(crate) reader: ResourceReader,
pub(crate) mimetype: Option<String>,
}
#[expect(dead_code)]
#[derive(Clone)]
pub(crate) enum ResourceReader {
Embedded(io::Cursor<&'static [u8]>),
File(Arc<File>),
}
impl Read for ResourceReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
ResourceReader::Embedded(cursor) => cursor.read(buf),
ResourceReader::File(file) => file.as_ref().read(buf),
}
}
}
pub(crate) struct CefHandler {
wgpu_context: WgpuContext,
app_event_scheduler: AppEventScheduler,
view_info_receiver: Arc<Mutex<ViewInfoReceiver>>,
}
impl CefHandler {
pub(crate) fn new(wgpu_context: WgpuContext, app_event_scheduler: AppEventScheduler, view_info_receiver: Receiver<ViewInfoUpdate>) -> Self {
Self {
wgpu_context,
app_event_scheduler,
view_info_receiver: Arc::new(Mutex::new(ViewInfoReceiver::new(view_info_receiver))),
}
}
}
impl CefEventHandler for CefHandler {
fn view_info(&self) -> ViewInfo {
let Ok(mut guard) = self.view_info_receiver.lock() else {
tracing::error!("Failed to lock view_info_receiver");
return ViewInfo::new();
};
let ViewInfoReceiver { receiver, view_info } = &mut *guard;
for update in receiver.try_iter() {
view_info.apply_update(update);
}
*view_info
}
fn draw<'a>(&self, frame_buffer: FrameBufferRef<'a>) {
let width = frame_buffer.width() as u32;
let height = frame_buffer.height() as u32;
let texture = self.wgpu_context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("CEF Texture"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.wgpu_context.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
frame_buffer.buffer(),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
#[cfg(feature = "accelerated_paint")]
fn draw_gpu(&self, shared_texture: SharedTextureHandle) {
match shared_texture.import_texture(&self.wgpu_context.device) {
Ok(texture) => {
self.app_event_scheduler.schedule(AppEvent::UiUpdate(texture));
}
Err(e) => {
tracing::error!("Failed to import shared texture: {}", e);
}
}
}
fn load_resource(&self, path: PathBuf) -> Option<Resource> {
let path = if path.as_os_str().is_empty() { PathBuf::from("index.html") } else { path };
let mimetype = match path.extension().and_then(|s| s.to_str()).unwrap_or("") {
"html" => Some("text/html".to_string()),
"css" => Some("text/css".to_string()),
"txt" => Some("text/plain".to_string()),
"wasm" => Some("application/wasm".to_string()),
"js" => Some("application/javascript".to_string()),
"png" => Some("image/png".to_string()),
"jpg" | "jpeg" => Some("image/jpeg".to_string()),
"svg" => Some("image/svg+xml".to_string()),
"xml" => Some("application/xml".to_string()),
"json" => Some("application/json".to_string()),
"ico" => Some("image/x-icon".to_string()),
"woff" => Some("font/woff".to_string()),
"woff2" => Some("font/woff2".to_string()),
"ttf" => Some("font/ttf".to_string()),
"otf" => Some("font/otf".to_string()),
"webmanifest" => Some("application/manifest+json".to_string()),
"graphite" => Some("application/graphite+json".to_string()),
_ => None,
};
#[cfg(feature = "embedded_resources")]
{
if let Some(resources) = &graphite_desktop_embedded_resources::EMBEDDED_RESOURCES
&& let Some(file) = resources.get_file(&path)
{
return Some(Resource {
reader: ResourceReader::Embedded(io::Cursor::new(file.contents())),
mimetype,
});
}
}
#[cfg(not(feature = "embedded_resources"))]
{
use std::path::Path;
let asset_path_env = std::env::var("GRAPHITE_RESOURCES").ok()?;
let asset_path = Path::new(&asset_path_env);
let file_path = asset_path.join(path.strip_prefix("/").unwrap_or(&path));
if file_path.exists() && file_path.is_file() {
if let Ok(file) = std::fs::File::open(file_path) {
return Some(Resource {
reader: ResourceReader::File(file.into()),
mimetype,
});
}
}
}
None
}
fn cursor_change(&self, cursor: Cursor) {
self.app_event_scheduler.schedule(AppEvent::CursorChange(cursor));
}
fn schedule_cef_message_loop_work(&self, scheduled_time: std::time::Instant) {
self.app_event_scheduler.schedule(AppEvent::ScheduleBrowserWork(scheduled_time));
}
fn initialized_web_communication(&self) {
self.app_event_scheduler.schedule(AppEvent::WebCommunicationInitialized);
}
fn receive_web_message(&self, message: &[u8]) {
let Some(desktop_wrapper_message) = deserialize_editor_message(message) else {
tracing::error!("Failed to deserialize web message");
return;
};
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(desktop_wrapper_message));
}
fn duplicate(&self) -> Self
where
Self: Sized,
{
Self {
wgpu_context: self.wgpu_context.clone(),
app_event_scheduler: self.app_event_scheduler.clone(),
view_info_receiver: self.view_info_receiver.clone(),
}
}
}
struct ViewInfoReceiver {
view_info: ViewInfo,
receiver: Receiver<ViewInfoUpdate>,
}
impl ViewInfoReceiver {
fn new(receiver: Receiver<ViewInfoUpdate>) -> Self {
Self { view_info: ViewInfo::new(), receiver }
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/render.rs | desktop/src/render.rs | mod frame_buffer_ref;
pub(crate) use frame_buffer_ref::FrameBufferRef;
mod state;
pub(crate) use state::{RenderError, RenderState};
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/gpu_context.rs | desktop/src/gpu_context.rs | use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
pub(super) async fn create_wgpu_context() -> WgpuContext {
let wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::PUSH_CONSTANTS);
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("\nAvailable WGPU adapters:\n{}", wgpu_context_builder.available_adapters_fmt().await);
// TODO: make this configurable via cli flags instead
let wgpu_context = match std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
None => wgpu_context_builder.build().await,
Some(adapter_index) => {
tracing::info!("Overriding WGPU adapter selection with adapter index {adapter_index}");
wgpu_context_builder.build_with_adapter_selection(|_| Some(adapter_index)).await
}
}
.expect("Failed to create WGPU context");
// TODO: add a cli flag to list adapters and exit instead of always printing
println!("Using WGPU adapter: {:?}", wgpu_context.adapter.get_info());
wgpu_context
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window.rs | desktop/src/window.rs | use std::collections::HashMap;
use std::sync::Arc;
use winit::cursor::{CursorIcon, CustomCursor, CustomCursorSource};
use winit::event_loop::ActiveEventLoop;
use winit::window::{Window as WinitWindow, WindowAttributes};
use crate::consts::APP_NAME;
use crate::event::AppEventScheduler;
use crate::wrapper::messages::MenuItem;
pub(crate) trait NativeWindow {
fn init() {}
fn configure(attributes: WindowAttributes, event_loop: &dyn ActiveEventLoop) -> WindowAttributes;
fn new(window: &dyn WinitWindow, app_event_scheduler: AppEventScheduler) -> Self;
fn can_render(&self) -> bool {
true
}
fn update_menu(&self, _entries: Vec<MenuItem>) {}
fn hide(&self) {}
fn hide_others(&self) {}
fn show_all(&self) {}
}
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
use linux as native;
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "macos")]
use mac as native;
#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")]
use win as native;
pub(crate) struct Window {
winit_window: Arc<dyn winit::window::Window>,
#[allow(dead_code)]
native_handle: native::NativeWindowImpl,
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
clipboard: window_clipboard::Clipboard,
}
impl Window {
pub(crate) fn init() {
native::NativeWindowImpl::init();
}
pub(crate) fn new(event_loop: &dyn ActiveEventLoop, app_event_scheduler: AppEventScheduler) -> Self {
let mut attributes = WindowAttributes::default()
.with_title(APP_NAME)
.with_min_surface_size(winit::dpi::LogicalSize::new(400, 300))
.with_surface_size(winit::dpi::LogicalSize::new(1200, 800))
.with_resizable(true)
.with_visible(false)
.with_theme(Some(winit::window::Theme::Dark));
attributes = native::NativeWindowImpl::configure(attributes, event_loop);
let winit_window = event_loop.create_window(attributes).unwrap();
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.expect("failed to create clipboard");
Self {
winit_window: winit_window.into(),
native_handle,
custom_cursors: HashMap::new(),
clipboard,
}
}
pub(crate) fn show(&self) {
self.winit_window.set_visible(true);
self.winit_window.focus_window();
}
pub(crate) fn request_redraw(&self) {
self.winit_window.request_redraw();
}
pub(crate) fn create_surface(&self, instance: Arc<wgpu::Instance>) -> wgpu::Surface<'static> {
instance.create_surface(self.winit_window.clone()).unwrap()
}
pub(crate) fn pre_present_notify(&self) {
self.winit_window.pre_present_notify();
}
pub(crate) fn can_render(&self) -> bool {
self.native_handle.can_render()
}
pub(crate) fn surface_size(&self) -> winit::dpi::PhysicalSize<u32> {
self.winit_window.surface_size()
}
pub(crate) fn scale_factor(&self) -> f64 {
self.winit_window.scale_factor()
}
pub(crate) fn minimize(&self) {
self.winit_window.set_minimized(true);
}
pub(crate) fn toggle_maximize(&self) {
self.winit_window.set_maximized(!self.winit_window.is_maximized());
}
pub(crate) fn is_maximized(&self) -> bool {
self.winit_window.is_maximized()
}
pub(crate) fn is_fullscreen(&self) -> bool {
self.winit_window.fullscreen().is_some()
}
pub(crate) fn start_drag(&self) {
let _ = self.winit_window.drag_window();
}
pub(crate) fn hide(&self) {
self.native_handle.hide();
}
pub(crate) fn hide_others(&self) {
self.native_handle.hide_others();
}
pub(crate) fn show_all(&self) {
self.native_handle.show_all();
}
pub(crate) fn set_cursor(&mut self, event_loop: &dyn ActiveEventLoop, cursor: Cursor) {
let cursor = match cursor {
Cursor::Icon(cursor_icon) => cursor_icon.into(),
Cursor::Custom(custom_cursor_source) => {
let custom_cursor = match self.custom_cursors.get(&custom_cursor_source).cloned() {
Some(cursor) => cursor,
None => {
let Ok(custom_cursor) = event_loop.create_custom_cursor(custom_cursor_source.clone()) else {
tracing::error!("Failed to create custom cursor");
return;
};
self.custom_cursors.insert(custom_cursor_source, custom_cursor.clone());
custom_cursor
}
};
custom_cursor.into()
}
};
self.winit_window.set_cursor(cursor);
}
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
self.native_handle.update_menu(entries);
}
pub(crate) fn clipboard_read(&self) -> Option<String> {
match self.clipboard.read() {
Ok(data) => Some(data),
Err(e) => {
tracing::error!("Failed to read from clipboard: {e}");
None
}
}
}
pub(crate) fn clipboard_write(&mut self, data: String) {
if let Err(e) = self.clipboard.write(data) {
tracing::error!("Failed to write to clipboard: {e}")
}
}
}
pub(crate) enum Cursor {
Icon(CursorIcon),
Custom(CustomCursorSource),
}
impl From<CursorIcon> for Cursor {
fn from(icon: CursorIcon) -> Self {
Cursor::Icon(icon)
}
}
impl From<CustomCursorSource> for Cursor {
fn from(custom: CustomCursorSource) -> Self {
Cursor::Custom(custom)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/dirs.rs | desktop/src/dirs.rs | use std::fs::create_dir_all;
use std::path::PathBuf;
use crate::consts::{APP_DIRECTORY_NAME, APP_DOCUMENTS_DIRECTORY_NAME};
pub(crate) fn ensure_dir_exists(path: &PathBuf) {
if !path.exists() {
create_dir_all(path).unwrap_or_else(|_| panic!("Failed to create directory at {path:?}"));
}
}
pub(crate) fn app_data_dir() -> PathBuf {
let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
pub(crate) fn app_autosave_documents_dir() -> PathBuf {
let path = app_data_dir().join(APP_DOCUMENTS_DIRECTORY_NAME);
ensure_dir_exists(&path);
path
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/main.rs | desktop/src/main.rs | fn main() {
graphite_desktop::start();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/consts.rs | desktop/src/cef/consts.rs | use std::time::Duration;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_X: f32 = 3.0;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_Y: f32 = 3.0;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_X: f32 = 1.0;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_Y: f32 = 1.0;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.0;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal.rs | desktop/src/cef/internal.rs | mod browser_process_app;
mod browser_process_client;
mod browser_process_handler;
mod render_process_app;
mod render_process_handler;
mod render_process_v8_handler;
mod context_menu_handler;
mod display_handler;
mod life_span_handler;
mod load_handler;
mod resource_handler;
mod scheme_handler_factory;
pub(super) mod render_handler;
#[cfg(not(target_os = "macos"))]
pub(super) mod task;
pub(super) use browser_process_app::BrowserProcessAppImpl;
pub(super) use browser_process_client::BrowserProcessClientImpl;
pub(super) use render_process_app::RenderProcessAppImpl;
pub(super) use scheme_handler_factory::SchemeHandlerFactoryImpl;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/platform.rs | desktop/src/cef/platform.rs | #[cfg(feature = "accelerated_paint")]
pub fn should_enable_hardware_acceleration() -> bool {
#[cfg(target_os = "linux")]
{
// Check if running on Wayland or X11
let has_wayland = std::env::var("WAYLAND_DISPLAY")
.ok()
.filter(|var| !var.is_empty())
.or_else(|| std::env::var("WAYLAND_SOCKET").ok())
.filter(|var| !var.is_empty())
.is_some();
let has_x11 = std::env::var("DISPLAY").ok().filter(|var| !var.is_empty()).is_some();
if !has_wayland && !has_x11 {
tracing::warn!("No display server detected, disabling hardware acceleration");
return false;
}
// Check for NVIDIA proprietary driver (known to have issues)
if let Ok(driver_info) = std::fs::read_to_string("/proc/driver/nvidia/version") {
if driver_info.contains("NVIDIA") {
tracing::warn!("NVIDIA proprietary driver detected, hardware acceleration may be unstable");
// Still return true but with warning
}
}
// Check for basic GPU capabilities
if has_wayland {
tracing::info!("Wayland detected, enabling hardware acceleration");
true
} else if has_x11 {
tracing::info!("X11 detected, enabling hardware acceleration");
true
} else {
false
}
}
#[cfg(target_os = "windows")]
{
// Windows generally has good D3D11 support
tracing::info!("Windows detected, enabling hardware acceleration");
true
}
#[cfg(target_os = "macos")]
{
// macOS has good Metal/IOSurface support
tracing::info!("macOS detected, enabling hardware acceleration");
true
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
tracing::warn!("Unsupported platform for hardware acceleration");
false
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/utility.rs | desktop/src/cef/utility.rs | pub unsafe fn pointer_to_string(pointer: *mut cef::sys::_cef_string_utf16_t) -> String {
let str = unsafe { (*pointer).str_ };
let len = unsafe { (*pointer).length };
let slice = unsafe { std::slice::from_raw_parts(str, len) };
String::from_utf16(slice).unwrap()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/dirs.rs | desktop/src/cef/dirs.rs | use std::path::PathBuf;
use crate::dirs::{app_data_dir, ensure_dir_exists};
static CEF_DIR_NAME: &str = "browser";
pub(crate) fn delete_instance_dirs() {
let cef_dir = app_data_dir().join(CEF_DIR_NAME);
if let Ok(entries) = std::fs::read_dir(&cef_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let _ = std::fs::remove_dir_all(&path);
}
}
}
}
pub(crate) fn create_instance_dir() -> PathBuf {
let instance_id: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
let path = app_data_dir().join(CEF_DIR_NAME).join(instance_id);
ensure_dir_exists(&path);
path
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/context.rs | desktop/src/cef/context.rs | #[cfg(not(target_os = "macos"))]
mod multithreaded;
mod singlethreaded;
mod builder;
pub(crate) use builder::{CefContextBuilder, InitError};
pub(crate) trait CefContext {
fn work(&mut self);
fn handle_window_event(&mut self, event: &winit::event::WindowEvent);
fn notify_view_info_changed(&self);
fn send_web_message(&self, message: Vec<u8>);
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/input.rs | desktop/src/cef/input.rs | use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
mod keymap;
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
mod state;
pub(crate) use state::{CefModifiers, InputState};
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
pub(crate) fn handle_window_event(browser: &Browser, input_state: &mut InputState, event: &WindowEvent) {
match event {
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerEntered { position, .. } => {
if !input_state.cursor_move(position) {
return;
}
let Some(host) = browser.host() else { return };
host.send_mouse_move_event(Some(&input_state.into()), 0);
}
WindowEvent::PointerLeft { position, .. } => {
if let Some(position) = position {
let _ = input_state.cursor_move(position);
}
let Some(host) = browser.host() else { return };
host.send_mouse_move_event(Some(&(input_state.into())), 1);
}
WindowEvent::PointerButton { state, button, .. } => {
let mouse_button = match button {
ButtonSource::Mouse(mouse_button) => mouse_button,
_ => {
return; // TODO: Handle touch input
}
};
let cef_click_count = input_state.mouse_input(mouse_button, state).into();
let cef_mouse_up = match state {
ElementState::Pressed => 0,
ElementState::Released => 1,
};
let cef_button = match mouse_button {
MouseButton::Left => cef::MouseButtonType::from(cef_mouse_button_type_t::MBT_LEFT),
MouseButton::Right => cef::MouseButtonType::from(cef_mouse_button_type_t::MBT_RIGHT),
MouseButton::Middle => cef::MouseButtonType::from(cef_mouse_button_type_t::MBT_MIDDLE),
_ => return,
};
let Some(host) = browser.host() else { return };
host.send_mouse_click_event(Some(&input_state.into()), cef_button, cef_mouse_up, cef_click_count);
}
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
let mouse_event = input_state.into();
let (mut delta_x, mut delta_y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
};
delta_x *= SCROLL_SPEED_X;
delta_y *= SCROLL_SPEED_Y;
let Some(host) = browser.host() else { return };
host.send_mouse_wheel_event(Some(&mouse_event), delta_x as i32, delta_y as i32);
}
WindowEvent::ModifiersChanged(modifiers) => {
input_state.modifiers_changed(&modifiers.state());
}
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
let Some(host) = browser.host() else { return };
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
let mut key_event = KeyEvent {
type_: match (event.state, &event.logical_key) {
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => cef_key_event_type_t::KEYEVENT_CHAR,
(ElementState::Pressed, _) => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
(ElementState::Released, _) => cef_key_event_type_t::KEYEVENT_KEYUP,
}
.into(),
..Default::default()
};
key_event.modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
key_event.windows_key_code = match &event.logical_key {
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
key_event.native_key_code = event.physical_key.to_native_keycode();
key_event.character = event.logical_key.to_char_representation() as u16;
if event.state == ElementState::Pressed && key_event.character != 0 {
key_event.type_ = cef_key_event_type_t::KEYEVENT_CHAR.into();
}
// Mitigation for CEF on Mac bug to prevent NSMenu being triggered by this key event.
//
// CEF converts the key event into an `NSEvent` internally and passes that to Chromium.
// In some cases the `NSEvent` gets to the native Cocoa application, is considered "unhandled" and can trigger menus.
//
// Why mitigation works:
// Leaving `key_event.unmodified_character = 0` still leads to CEF forwarding a "unhandled" event to the native application
// but that event is discarded because `key_event.unmodified_character = 0` is considered non-printable and not used for shortcut matching.
//
// See https://github.com/chromiumembedded/cef/issues/3857
//
// TODO: Remove mitigation once bug is fixed or a better solution is found.
#[cfg(not(target_os = "macos"))]
{
key_event.unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
}
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
if key_event.character == 0 && key_event.unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
key_event.character = 1;
}
if key_event.type_ == cef_key_event_type_t::KEYEVENT_CHAR.into() {
let mut key_down_event = key_event.clone();
key_down_event.type_ = cef_key_event_type_t::KEYEVENT_RAWKEYDOWN.into();
host.send_key_event(Some(&key_down_event));
key_event.windows_key_code = event.logical_key.to_char_representation() as i32;
}
host.send_key_event(Some(&key_event));
}
WindowEvent::PinchGesture { delta, .. } => {
if !delta.is_normal() {
return;
}
let Some(host) = browser.host() else { return };
let mouse_event = MouseEvent {
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
..input_state.into()
};
let delta = (delta * PINCH_ZOOM_SPEED).round() as i32;
host.send_mouse_wheel_event(Some(&mouse_event), 0, delta);
}
_ => {}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/ipc.rs | desktop/src/cef/ipc.rs | use cef::{CefString, Frame, ImplBinaryValue, ImplFrame, ImplListValue, ImplProcessMessage, ImplV8Context, ProcessId, V8Context, sys::cef_process_id_t};
pub(crate) enum MessageType {
Initialized,
SendToJS,
SendToNative,
}
impl From<MessageType> for MessageInfo {
fn from(val: MessageType) -> Self {
match val {
MessageType::Initialized => MessageInfo {
name: "initialized".to_string(),
target: cef_process_id_t::PID_BROWSER.into(),
},
MessageType::SendToJS => MessageInfo {
name: "send_to_js".to_string(),
target: cef_process_id_t::PID_RENDERER.into(),
},
MessageType::SendToNative => MessageInfo {
name: "send_to_native".to_string(),
target: cef_process_id_t::PID_BROWSER.into(),
},
}
}
}
impl TryFrom<String> for MessageType {
type Error = ();
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"initialized" => Ok(MessageType::Initialized),
"send_to_js" => Ok(MessageType::SendToJS),
"send_to_native" => Ok(MessageType::SendToNative),
_ => Err(()),
}
}
}
pub(crate) struct MessageInfo {
name: String,
target: ProcessId,
}
pub(crate) trait SendMessage {
fn send_message(&self, message_type: MessageType, message: &[u8]);
}
impl SendMessage for Option<V8Context> {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let Some(context) = self else {
tracing::error!("Current V8 context is not available, cannot send message");
return;
};
context.send_message(message_type, message);
}
}
impl SendMessage for V8Context {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let Some(frame) = self.frame() else {
tracing::error!("Current V8 context does not have a frame, cannot send message");
return;
};
frame.send_message(message_type, message);
}
}
impl SendMessage for Frame {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let MessageInfo { name, target } = message_type.into();
let Some(mut process_message) = cef::process_message_create(Some(&CefString::from(name.as_str()))) else {
tracing::error!("Failed to create process message: {}", name);
return;
};
let Some(arg_list) = process_message.argument_list() else { return };
let mut value = ::cef::binary_value_create(Some(message));
arg_list.set_binary(0, value.as_mut());
self.send_process_message(target, Some(&mut process_message));
}
}
pub(crate) struct UnpackedMessage<'a> {
pub(crate) message_type: MessageType,
pub(crate) data: &'a [u8],
}
trait Sealed {}
impl Sealed for cef::ProcessMessage {}
#[allow(private_bounds)]
pub(crate) trait UnpackMessage: Sealed {
/// # Safety
///
/// The caller must ensure that the message is valid.
/// Message should come from cef.
unsafe fn unpack(&self) -> Option<UnpackedMessage<'_>>;
}
impl UnpackMessage for cef::ProcessMessage {
unsafe fn unpack(&self) -> Option<UnpackedMessage<'_>> {
let pointer: *mut cef::sys::_cef_string_utf16_t = self.name().into();
let message = unsafe { super::utility::pointer_to_string(pointer) };
let Ok(message_type) = message.try_into() else {
tracing::error!("Failed to get message type from process message");
return None;
};
let arglist = self.argument_list()?;
let binary = arglist.binary(0)?;
let size = binary.size();
let ptr = binary.raw_data();
let buffer = unsafe { std::slice::from_raw_parts(ptr as *const u8, size) };
Some(UnpackedMessage { message_type, data: buffer })
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/input/state.rs | desktop/src/cef/input/state.rs | use cef::MouseEvent;
use cef::sys::cef_event_flags_t;
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, MouseButton};
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
use crate::cef::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
#[derive(Default)]
pub(crate) struct InputState {
modifiers: ModifiersState,
mouse_position: MousePosition,
mouse_state: MouseState,
mouse_click_tracker: ClickTracker,
}
impl InputState {
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
self.modifiers = *modifiers;
}
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
let bits = match key {
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
Key::Named(NamedKey::Meta) => ModifiersState::META,
_ => return,
};
let is_pressed = matches!(state, ElementState::Pressed);
self.modifiers.set(bits, is_pressed);
}
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
let new = position.into();
if self.mouse_position == new {
return false;
}
self.mouse_position = new;
true
}
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
self.mouse_state.update(button, state);
self.mouse_click_tracker.input(button, state, self.mouse_position)
}
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
CefModifiers::new(self, location, is_repeat)
}
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
self.cef_modifiers(&KeyLocation::Standard, false)
}
}
impl From<InputState> for CefModifiers {
fn from(val: InputState) -> Self {
CefModifiers::new(&val, &KeyLocation::Standard, false)
}
}
impl From<&InputState> for MouseEvent {
fn from(val: &InputState) -> Self {
MouseEvent {
x: val.mouse_position.x as i32,
y: val.mouse_position.y as i32,
modifiers: val.cef_mouse_modifiers().into(),
}
}
}
impl From<&mut InputState> for MouseEvent {
fn from(val: &mut InputState) -> Self {
MouseEvent {
x: val.mouse_position.x as i32,
y: val.mouse_position.y as i32,
modifiers: val.cef_mouse_modifiers().into(),
}
}
}
#[derive(Default, Clone, Copy, Eq, PartialEq)]
pub(crate) struct MousePosition {
x: usize,
y: usize,
}
impl From<&PhysicalPosition<f64>> for MousePosition {
fn from(position: &PhysicalPosition<f64>) -> Self {
Self {
x: position.x as usize,
y: position.y as usize,
}
}
}
#[derive(Default, Clone)]
pub(crate) struct MouseState {
left: bool,
right: bool,
middle: bool,
}
impl MouseState {
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
match state {
ElementState::Pressed => match button {
MouseButton::Left => self.left = true,
MouseButton::Right => self.right = true,
MouseButton::Middle => self.middle = true,
_ => {}
},
ElementState::Released => match button {
MouseButton::Left => self.left = false,
MouseButton::Right => self.right = false,
MouseButton::Middle => self.middle = false,
_ => {}
},
}
}
}
#[derive(Default)]
struct ClickTracker {
left: Option<ClickRecord>,
middle: Option<ClickRecord>,
right: Option<ClickRecord>,
}
impl ClickTracker {
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
let record = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
_ => return ClickCount::Single,
};
let Some(record) = record else {
*record = Some(ClickRecord { position, ..Default::default() });
return ClickCount::Single;
};
let prev_time = record.time;
let prev_position = record.position;
let now = Instant::now();
record.time = now;
record.position = position;
match state {
ElementState::Pressed if record.down_count == ClickCount::Double => {
*record = ClickRecord {
down_count: ClickCount::Single,
..*record
};
return ClickCount::Single;
}
ElementState::Released if record.up_count == ClickCount::Double => {
*record = ClickRecord {
up_count: ClickCount::Single,
..*record
};
return ClickCount::Single;
}
_ => {}
}
let dx = position.x.abs_diff(prev_position.x);
let dy = position.y.abs_diff(prev_position.y);
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let within_time = now.saturating_duration_since(prev_time) <= MULTICLICK_TIMEOUT;
let count = if within_time && within_dist { ClickCount::Double } else { ClickCount::Single };
*record = match state {
ElementState::Pressed => ClickRecord { down_count: count, ..*record },
ElementState::Released => ClickRecord { up_count: count, ..*record },
};
count
}
}
#[derive(Clone, Copy, PartialEq, Default)]
pub(crate) enum ClickCount {
#[default]
Single,
Double,
}
impl From<ClickCount> for i32 {
fn from(count: ClickCount) -> i32 {
match count {
ClickCount::Single => 1,
ClickCount::Double => 2,
}
}
}
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
}
}
pub(crate) struct CefModifiers(cef_event_flags_t);
impl CefModifiers {
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
if input_state.modifiers.shift_key() {
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
}
if input_state.modifiers.control_key() {
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
}
if input_state.modifiers.alt_key() {
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
}
if input_state.modifiers.meta_key() {
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
}
if input_state.mouse_state.left {
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
}
if input_state.mouse_state.right {
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
}
if input_state.mouse_state.middle {
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
}
if is_repeat {
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
}
inner |= match location {
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
};
Self(inner)
}
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
));
}
impl From<CefModifiers> for u32 {
fn from(val: CefModifiers) -> Self {
#[cfg(not(target_os = "windows"))]
return val.0.0;
#[cfg(target_os = "windows")]
return val.0.0 as u32;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/input/keymap.rs | desktop/src/cef/input/keymap.rs | use winit::keyboard::{Key, NamedKey, PhysicalKey};
pub(crate) trait ToCharRepresentation {
fn to_char_representation(&self) -> char;
}
impl ToCharRepresentation for Key {
fn to_char_representation(&self) -> char {
match self {
Key::Named(named) => match named {
NamedKey::Tab => '\t',
NamedKey::Enter => '\r',
NamedKey::Backspace => '\x08',
NamedKey::Escape => '\x1b',
_ => '\0',
},
Key::Character(char) => char.chars().next().unwrap_or_default(),
_ => '\0',
}
}
}
pub(crate) trait ToNativeKeycode {
fn to_native_keycode(&self) -> i32;
}
impl ToNativeKeycode for PhysicalKey {
fn to_native_keycode(&self) -> i32 {
use winit::platform::scancode::PhysicalKeyExtScancode;
#[cfg(target_os = "linux")]
{
self.to_scancode().map(|evdev| (evdev + 8) as i32).unwrap_or_default()
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
{
self.to_scancode().map(|c| c as i32).unwrap_or_default()
}
}
}
pub(crate) trait ToVKBits {
fn to_vk_bits(&self) -> i32;
}
macro_rules! map_enum {
($target:expr, $enum:ident, $( ($code:expr, $variant:ident), )+ ) => {
match $target {
$(
$enum::$variant => $code,
)+
_ => 0,
}
};
}
impl ToVKBits for winit::keyboard::NamedKey {
fn to_vk_bits(&self) -> i32 {
map_enum!(
self,
NamedKey,
(0x12, Alt),
(0xA5, AltGraph),
(0x14, CapsLock),
(0x11, Control),
(0x90, NumLock),
(0x91, ScrollLock),
(0x10, Shift),
(0x5B, Meta),
(0x0D, Enter),
(0x09, Tab),
(0x25, ArrowLeft),
(0x26, ArrowUp),
(0x27, ArrowRight),
(0x28, ArrowDown),
(0x23, End),
(0x24, Home),
(0x22, PageDown),
(0x21, PageUp),
(0x08, Backspace),
(0x0C, Clear),
(0xF7, CrSel),
(0x2E, Delete),
(0xF9, EraseEof),
(0xF8, ExSel),
(0x2D, Insert),
(0x1E, Accept),
(0xF6, Attn),
(0x03, Cancel),
(0x5D, ContextMenu),
(0x1B, Escape),
(0x2B, Execute),
(0x2F, Help),
(0x13, Pause),
(0xFA, Play),
(0x5D, Props),
(0x29, Select),
(0xFB, ZoomIn),
(0xFB, ZoomOut),
(0x2C, PrintScreen),
(0x5F, Standby),
(0x1C, Convert),
(0x18, FinalMode),
(0x1F, ModeChange),
(0x1D, NonConvert),
(0xE5, Process),
(0x15, HangulMode),
(0x19, HanjaMode),
(0x17, JunjaMode),
(0x15, KanaMode),
(0x19, KanjiMode),
(0xB0, MediaFastForward),
(0xB3, MediaPause),
(0xB3, MediaPlay),
(0xB3, MediaPlayPause),
(0xB1, MediaRewind),
(0xB2, MediaStop),
(0xB0, MediaTrackNext),
(0xB1, MediaTrackPrevious),
(0x2A, Print),
(0xAE, AudioVolumeDown),
(0xAF, AudioVolumeUp),
(0xAD, AudioVolumeMute),
(0xB6, LaunchApplication1),
(0xB7, LaunchApplication2),
(0xB4, LaunchMail),
(0xB5, LaunchMediaPlayer),
(0xB5, LaunchMusicPlayer),
(0xA6, BrowserBack),
(0xAB, BrowserFavorites),
(0xA7, BrowserForward),
(0xAC, BrowserHome),
(0xA8, BrowserRefresh),
(0xAA, BrowserSearch),
(0xA9, BrowserStop),
(0xFB, ZoomToggle),
(0x70, F1),
(0x71, F2),
(0x72, F3),
(0x73, F4),
(0x74, F5),
(0x75, F6),
(0x76, F7),
(0x77, F8),
(0x78, F9),
(0x79, F10),
(0x7A, F11),
(0x7B, F12),
(0x7C, F13),
(0x7D, F14),
(0x7E, F15),
(0x7F, F16),
(0x80, F17),
(0x81, F18),
(0x82, F19),
(0x83, F20),
(0x84, F21),
(0x85, F22),
(0x86, F23),
(0x87, F24),
)
}
}
macro_rules! map {
($target:expr, $( ($code:expr, $variant:literal), )+ ) => {
match $target {
$(
$variant => $code,
)+
_ => 0,
}
};
}
impl ToVKBits for char {
fn to_vk_bits(&self) -> i32 {
map!(
self,
(0x41, 'a'),
(0x42, 'b'),
(0x43, 'c'),
(0x44, 'd'),
(0x45, 'e'),
(0x46, 'f'),
(0x47, 'g'),
(0x48, 'h'),
(0x49, 'i'),
(0x4a, 'j'),
(0x4b, 'k'),
(0x4c, 'l'),
(0x4d, 'm'),
(0x4e, 'n'),
(0x4f, 'o'),
(0x50, 'p'),
(0x51, 'q'),
(0x52, 'r'),
(0x53, 's'),
(0x54, 't'),
(0x55, 'u'),
(0x56, 'v'),
(0x57, 'w'),
(0x58, 'x'),
(0x59, 'y'),
(0x5a, 'z'),
(0x41, 'A'),
(0x42, 'B'),
(0x43, 'C'),
(0x44, 'D'),
(0x45, 'E'),
(0x46, 'F'),
(0x47, 'G'),
(0x48, 'H'),
(0x49, 'I'),
(0x4a, 'J'),
(0x4b, 'K'),
(0x4c, 'L'),
(0x4d, 'M'),
(0x4e, 'N'),
(0x4f, 'O'),
(0x50, 'P'),
(0x51, 'Q'),
(0x52, 'R'),
(0x53, 'S'),
(0x54, 'T'),
(0x55, 'U'),
(0x56, 'V'),
(0x57, 'W'),
(0x58, 'X'),
(0x59, 'Y'),
(0x5a, 'Z'),
(0x31, '1'),
(0x32, '2'),
(0x33, '3'),
(0x34, '4'),
(0x35, '5'),
(0x36, '6'),
(0x37, '7'),
(0x38, '8'),
(0x39, '9'),
(0x30, '0'),
(0x31, '!'),
(0x32, '@'),
(0x33, '#'),
(0x34, '$'),
(0x35, '%'),
(0x36, '^'),
(0x37, '&'),
(0x38, '*'),
(0x39, '('),
(0x30, ')'),
(0xC0, '`'),
(0xC0, '~'),
(0xBD, '-'),
(0xBD, '_'),
(0xBB, '='),
(0xBB, '+'),
(0xDB, '['),
(0xDB, '{'),
(0xDD, ']'),
(0xDD, '}'),
(0xDC, '\\'),
(0xDC, '|'),
(0xBA, ';'),
(0xBA, ':'),
(0xBC, ','),
(0xBC, '<'),
(0xBE, '.'),
(0xBE, '>'),
(0xDE, '\''),
(0xDE, '"'),
(0xBF, '/'),
(0xBF, '?'),
(0x20, ' '),
)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/life_span_handler.rs | desktop/src/cef/internal/life_span_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_life_span_handler_t, cef_base_ref_counted_t};
use cef::{ImplLifeSpanHandler, WrapLifeSpanHandler};
pub(crate) struct LifeSpanHandlerImpl {
object: *mut RcImpl<_cef_life_span_handler_t, Self>,
}
impl LifeSpanHandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplLifeSpanHandler for LifeSpanHandlerImpl {
fn on_before_popup(
&self,
_browser: Option<&mut cef::Browser>,
_frame: Option<&mut cef::Frame>,
_popup_id: std::ffi::c_int,
target_url: Option<&cef::CefString>,
_target_frame_name: Option<&cef::CefString>,
_target_disposition: cef::WindowOpenDisposition,
_user_gesture: std::ffi::c_int,
_popup_features: Option<&cef::PopupFeatures>,
_window_info: Option<&mut cef::WindowInfo>,
_client: Option<&mut Option<cef::Client>>,
_settings: Option<&mut cef::BrowserSettings>,
_extra_info: Option<&mut Option<cef::DictionaryValue>>,
_no_javascript_access: Option<&mut std::ffi::c_int>,
) -> std::ffi::c_int {
let target = target_url.map(|url| url.to_string()).unwrap_or("unknown".to_string());
tracing::error!("Browser tried to open a popup at URL: {}", target);
// Deny any popup by returning 1
1
}
fn get_raw(&self) -> *mut _cef_life_span_handler_t {
self.object.cast()
}
}
impl Clone for LifeSpanHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for LifeSpanHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapLifeSpanHandler for LifeSpanHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_life_span_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/scheme_handler_factory.rs | desktop/src/cef/internal/scheme_handler_factory.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_scheme_handler_factory_t, cef_base_ref_counted_t, cef_scheme_options_t};
use cef::{Browser, CefString, Frame, ImplRequest, ImplSchemeHandlerFactory, ImplSchemeRegistrar, Request, ResourceHandler, SchemeRegistrar, WrapSchemeHandlerFactory};
use super::resource_handler::ResourceHandlerImpl;
use crate::cef::CefEventHandler;
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
pub(crate) struct SchemeHandlerFactoryImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_scheme_handler_factory_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> SchemeHandlerFactoryImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
pub(crate) fn register_schemes(registrar: Option<&mut SchemeRegistrar>) {
if let Some(registrar) = registrar {
let mut scheme_options = 0;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_STANDARD as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_FETCH_ENABLED as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_SECURE as i32;
scheme_options |= cef_scheme_options_t::CEF_SCHEME_OPTION_CORS_ENABLED as i32;
registrar.add_custom_scheme(Some(&CefString::from(RESOURCE_SCHEME)), scheme_options);
}
}
}
impl<H: CefEventHandler> ImplSchemeHandlerFactory for SchemeHandlerFactoryImpl<H> {
fn create(&self, _browser: Option<&mut Browser>, _frame: Option<&mut Frame>, _scheme_name: Option<&CefString>, request: Option<&mut Request>) -> Option<ResourceHandler> {
if let Some(request) = request {
let url = CefString::from(&request.url()).to_string();
let path = url
.strip_prefix(&format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/"))
.expect("CEF should only call this for our custom scheme and domain that we registered this factory for");
let resource = self.event_handler.load_resource(path.to_string().into());
return Some(ResourceHandler::new(ResourceHandlerImpl::new(resource)));
}
None
}
fn get_raw(&self) -> *mut _cef_scheme_handler_factory_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for SchemeHandlerFactoryImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for SchemeHandlerFactoryImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapSchemeHandlerFactory for SchemeHandlerFactoryImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_scheme_handler_factory_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/render_process_v8_handler.rs | desktop/src/cef/internal/render_process_v8_handler.rs | use cef::{ImplV8Handler, ImplV8Value, V8Value, WrapV8Handler, rc::Rc, v8_context_get_current_context};
use crate::cef::ipc::{MessageType, SendMessage};
pub struct RenderProcessV8HandlerImpl {
object: *mut cef::rc::RcImpl<cef::sys::_cef_v8_handler_t, Self>,
}
impl RenderProcessV8HandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplV8Handler for RenderProcessV8HandlerImpl {
fn execute(
&self,
name: Option<&cef::CefString>,
_object: Option<&mut V8Value>,
arguments: Option<&[Option<V8Value>]>,
_retval: Option<&mut Option<V8Value>>,
_exception: Option<&mut cef::CefString>,
) -> std::ffi::c_int {
match name.map(|s| s.to_string()).unwrap_or_default().as_str() {
"initializeNativeCommunication" => {
v8_context_get_current_context().send_message(MessageType::Initialized, vec![0u8].as_slice());
}
"sendNativeMessage" => {
let Some(args) = arguments else {
tracing::error!("No arguments provided to sendNativeMessage");
return 0;
};
let Some(arg1) = args.first() else {
tracing::error!("No arguments provided to sendNativeMessage");
return 0;
};
let Some(arg1) = arg1.as_ref() else {
tracing::error!("First argument to sendNativeMessage is not an ArrayBuffer");
return 0;
};
if arg1.is_array_buffer() == 0 {
tracing::error!("First argument to sendNativeMessage is not an ArrayBuffer");
return 0;
}
let size = arg1.array_buffer_byte_length();
let ptr = arg1.array_buffer_data();
let data = unsafe { std::slice::from_raw_parts_mut(ptr as *mut u8, size) };
v8_context_get_current_context().send_message(MessageType::SendToNative, data);
return 1;
}
name => {
tracing::error!("Unknown V8 function called: {}", name);
}
}
1
}
fn get_raw(&self) -> *mut cef::sys::_cef_v8_handler_t {
self.object.cast()
}
}
impl Clone for RenderProcessV8HandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for RenderProcessV8HandlerImpl {
fn as_base(&self) -> &cef::sys::cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapV8Handler for RenderProcessV8HandlerImpl {
fn wrap_rc(&mut self, object: *mut cef::rc::RcImpl<cef::sys::_cef_v8_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/render_process_app.rs | desktop/src/cef/internal/render_process_app.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_app_t, cef_base_ref_counted_t};
use cef::{App, ImplApp, RenderProcessHandler, SchemeRegistrar, WrapApp};
use super::render_process_handler::RenderProcessHandlerImpl;
use super::scheme_handler_factory::SchemeHandlerFactoryImpl;
use crate::cef::CefEventHandler;
pub(crate) struct RenderProcessAppImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_app_t, Self>,
render_process_handler: RenderProcessHandler,
}
impl<H: CefEventHandler> RenderProcessAppImpl<H> {
pub(crate) fn app() -> App {
App::new(Self {
object: std::ptr::null_mut(),
render_process_handler: RenderProcessHandler::new(RenderProcessHandlerImpl::new()),
})
}
}
impl<H: CefEventHandler> ImplApp for RenderProcessAppImpl<H> {
fn on_register_custom_schemes(&self, registrar: Option<&mut SchemeRegistrar>) {
SchemeHandlerFactoryImpl::<H>::register_schemes(registrar);
}
fn render_process_handler(&self) -> Option<RenderProcessHandler> {
Some(self.render_process_handler.clone())
}
fn get_raw(&self) -> *mut _cef_app_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for RenderProcessAppImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
render_process_handler: self.render_process_handler.clone(),
}
}
}
impl<H: CefEventHandler> Rc for RenderProcessAppImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapApp for RenderProcessAppImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_app_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/display_handler.rs | desktop/src/cef/internal/display_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_display_handler_t, cef_base_ref_counted_t, cef_cursor_type_t::*, cef_log_severity_t::*};
use cef::{CefString, ImplDisplayHandler, Point, Size, WrapDisplayHandler};
use winit::cursor::CursorIcon;
use crate::cef::CefEventHandler;
pub(crate) struct DisplayHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_display_handler_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> DisplayHandlerImpl<H> {
pub fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
}
#[cfg(not(target_os = "macos"))]
type CefCursorHandle = cef::CursorHandle;
#[cfg(target_os = "macos")]
type CefCursorHandle = *mut u8;
impl<H: CefEventHandler> ImplDisplayHandler for DisplayHandlerImpl<H> {
fn on_cursor_change(&self, _browser: Option<&mut cef::Browser>, _cursor: CefCursorHandle, cursor_type: cef::CursorType, custom_cursor_info: Option<&cef::CursorInfo>) -> std::ffi::c_int {
if let Some(custom_cursor_info) = custom_cursor_info {
let Size { width, height } = custom_cursor_info.size;
let Point { x: hotspot_x, y: hotspot_y } = custom_cursor_info.hotspot;
let buffer_size = (width * height * 4) as usize;
let buffer_ptr = custom_cursor_info.buffer as *const u8;
if !buffer_ptr.is_null() && buffer_ptr.align_offset(std::mem::align_of::<u8>()) == 0 {
let buffer = unsafe { std::slice::from_raw_parts(buffer_ptr, buffer_size) }.to_vec();
let cursor = winit::cursor::CustomCursorSource::from_rgba(buffer, width as u16, height as u16, hotspot_x as u16, hotspot_y as u16).unwrap();
self.event_handler.cursor_change(cursor.into());
return 1; // We handled the cursor change.
}
}
let cursor = match cursor_type.into() {
CT_POINTER => CursorIcon::Default,
CT_CROSS => CursorIcon::Crosshair,
CT_HAND => CursorIcon::Pointer,
CT_IBEAM => CursorIcon::Text,
CT_WAIT => CursorIcon::Wait,
CT_HELP => CursorIcon::Help,
CT_EASTRESIZE => CursorIcon::EResize,
CT_NORTHRESIZE => CursorIcon::NResize,
CT_NORTHEASTRESIZE => CursorIcon::NeResize,
CT_NORTHWESTRESIZE => CursorIcon::NwResize,
CT_SOUTHRESIZE => CursorIcon::SResize,
CT_SOUTHEASTRESIZE => CursorIcon::SeResize,
CT_SOUTHWESTRESIZE => CursorIcon::SwResize,
CT_WESTRESIZE => CursorIcon::WResize,
CT_NORTHSOUTHRESIZE => CursorIcon::NsResize,
CT_EASTWESTRESIZE => CursorIcon::EwResize,
CT_NORTHEASTSOUTHWESTRESIZE => CursorIcon::NeswResize,
CT_NORTHWESTSOUTHEASTRESIZE => CursorIcon::NwseResize,
CT_COLUMNRESIZE => CursorIcon::ColResize,
CT_ROWRESIZE => CursorIcon::RowResize,
CT_MIDDLEPANNING => CursorIcon::AllScroll,
CT_EASTPANNING => CursorIcon::AllScroll,
CT_NORTHPANNING => CursorIcon::AllScroll,
CT_NORTHEASTPANNING => CursorIcon::AllScroll,
CT_NORTHWESTPANNING => CursorIcon::AllScroll,
CT_SOUTHPANNING => CursorIcon::AllScroll,
CT_SOUTHEASTPANNING => CursorIcon::AllScroll,
CT_SOUTHWESTPANNING => CursorIcon::AllScroll,
CT_WESTPANNING => CursorIcon::AllScroll,
CT_MOVE => CursorIcon::Move,
CT_VERTICALTEXT => CursorIcon::VerticalText,
CT_CELL => CursorIcon::Cell,
CT_CONTEXTMENU => CursorIcon::ContextMenu,
CT_ALIAS => CursorIcon::Alias,
CT_PROGRESS => CursorIcon::Progress,
CT_NODROP => CursorIcon::NoDrop,
CT_COPY => CursorIcon::Copy,
CT_NONE => CursorIcon::Default,
CT_NOTALLOWED => CursorIcon::NotAllowed,
CT_ZOOMIN => CursorIcon::ZoomIn,
CT_ZOOMOUT => CursorIcon::ZoomOut,
CT_GRAB => CursorIcon::Grab,
CT_GRABBING => CursorIcon::Grabbing,
CT_MIDDLE_PANNING_VERTICAL => CursorIcon::AllScroll,
CT_MIDDLE_PANNING_HORIZONTAL => CursorIcon::AllScroll,
CT_DND_NONE => CursorIcon::Default,
CT_DND_MOVE => CursorIcon::Move,
CT_DND_COPY => CursorIcon::Copy,
CT_DND_LINK => CursorIcon::Alias,
CT_NUM_VALUES => CursorIcon::Default,
_ => CursorIcon::Default,
};
self.event_handler.cursor_change(cursor.into());
1 // We handled the cursor change.
}
fn on_console_message(&self, _browser: Option<&mut cef::Browser>, level: cef::LogSeverity, message: Option<&CefString>, source: Option<&CefString>, line: std::ffi::c_int) -> std::ffi::c_int {
let message = message.map(|m| m.to_string()).unwrap_or_default();
let source = source.map(|s| s.to_string()).unwrap_or_default();
let line = line as i64;
let browser_source = format!("{source}:{line}");
static BROWSER: &str = "browser";
match level.as_ref() {
LOGSEVERITY_FATAL | LOGSEVERITY_ERROR => tracing::error!(target: BROWSER, "{browser_source} {message}"),
LOGSEVERITY_WARNING => tracing::warn!(target: BROWSER, "{browser_source} {message}"),
LOGSEVERITY_INFO => tracing::info!(target: BROWSER, "{browser_source} {message}"),
LOGSEVERITY_DEFAULT | LOGSEVERITY_VERBOSE => tracing::debug!(target: BROWSER, "{browser_source} {message}"),
_ => tracing::trace!(target: BROWSER, "{browser_source} {message}"),
}
0
}
fn get_raw(&self) -> *mut _cef_display_handler_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for DisplayHandlerImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for DisplayHandlerImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapDisplayHandler for DisplayHandlerImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_display_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/load_handler.rs | desktop/src/cef/internal/load_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_load_handler_t, cef_base_ref_counted_t, cef_load_handler_t};
use cef::{ImplBrowser, ImplBrowserHost, ImplLoadHandler, WrapLoadHandler};
use crate::cef::CefEventHandler;
pub(crate) struct LoadHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<cef_load_handler_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> LoadHandlerImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
}
impl<H: CefEventHandler> ImplLoadHandler for LoadHandlerImpl<H> {
fn on_loading_state_change(&self, browser: Option<&mut cef::Browser>, is_loading: std::ffi::c_int, _can_go_back: std::ffi::c_int, _can_go_forward: std::ffi::c_int) {
let view_info = self.event_handler.view_info();
if let Some(browser) = browser
&& is_loading == 0
{
browser.host().unwrap().set_zoom_level(view_info.zoom());
}
}
fn get_raw(&self) -> *mut _cef_load_handler_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for LoadHandlerImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for LoadHandlerImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapLoadHandler for LoadHandlerImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_load_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/render_handler.rs | desktop/src/cef/internal/render_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_render_handler_t, cef_base_ref_counted_t};
use cef::{Browser, ImplRenderHandler, PaintElementType, Rect, WrapRenderHandler};
use crate::cef::CefEventHandler;
use crate::render::FrameBufferRef;
pub(crate) struct RenderHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_render_handler_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> RenderHandlerImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
}
impl<H: CefEventHandler> ImplRenderHandler for RenderHandlerImpl<H> {
fn view_rect(&self, _browser: Option<&mut Browser>, rect: Option<&mut Rect>) {
if let Some(rect) = rect {
let view_info = self.event_handler.view_info();
*rect = Rect {
x: 0,
y: 0,
width: view_info.width() as i32,
height: view_info.height() as i32,
};
}
}
fn on_paint(&self, _browser: Option<&mut Browser>, _type_: PaintElementType, _dirty_rects: Option<&[Rect]>, buffer: *const u8, width: std::ffi::c_int, height: std::ffi::c_int) {
let buffer_size = (width * height * 4) as usize;
let buffer_slice = unsafe { std::slice::from_raw_parts(buffer, buffer_size) };
let frame_buffer = FrameBufferRef::new(buffer_slice, width as usize, height as usize).expect("Failed to create frame buffer");
self.event_handler.draw(frame_buffer)
}
#[cfg(feature = "accelerated_paint")]
fn on_accelerated_paint(&self, _browser: Option<&mut Browser>, type_: PaintElementType, _dirty_rects: Option<&[Rect]>, info: Option<&cef::AcceleratedPaintInfo>) {
use cef::osr_texture_import::SharedTextureHandle;
if type_ != PaintElementType::default() {
return;
}
let shared_handle = SharedTextureHandle::new(info.unwrap());
if let SharedTextureHandle::Unsupported = shared_handle {
tracing::error!("Platform does not support accelerated painting");
return;
}
self.event_handler.draw_gpu(shared_handle);
}
fn get_raw(&self) -> *mut _cef_render_handler_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for RenderHandlerImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for RenderHandlerImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapRenderHandler for RenderHandlerImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_render_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/render_process_handler.rs | desktop/src/cef/internal/render_process_handler.rs | use cef::rc::{ConvertReturnValue, Rc, RcImpl};
use cef::sys::{_cef_render_process_handler_t, cef_base_ref_counted_t, cef_render_process_handler_t, cef_v8_propertyattribute_t, cef_v8_value_create_array_buffer_with_copy};
use cef::{CefString, ImplFrame, ImplRenderProcessHandler, ImplV8Context, ImplV8Value, V8Handler, V8Propertyattribute, V8Value, WrapRenderProcessHandler, v8_value_create_function};
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
use super::render_process_v8_handler::RenderProcessV8HandlerImpl;
pub(crate) struct RenderProcessHandlerImpl {
object: *mut RcImpl<cef_render_process_handler_t, Self>,
}
impl RenderProcessHandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplRenderProcessHandler for RenderProcessHandlerImpl {
fn on_process_message_received(
&self,
_browser: Option<&mut cef::Browser>,
frame: Option<&mut cef::Frame>,
_source_process: cef::ProcessId,
message: Option<&mut cef::ProcessMessage>,
) -> std::ffi::c_int {
let unpacked_message = unsafe { message.and_then(|m| m.unpack()) };
match unpacked_message {
Some(UnpackedMessage {
message_type: MessageType::SendToJS,
data,
}) => {
let Some(frame) = frame else {
tracing::error!("Frame is not available");
return 0;
};
let Some(context) = frame.v8_context() else {
tracing::error!("V8 context is not available");
return 0;
};
if context.enter() == 0 {
tracing::error!("Failed to enter V8 context");
return 0;
}
let mut value: V8Value = unsafe { cef_v8_value_create_array_buffer_with_copy(data.as_ptr() as *mut std::ffi::c_void, data.len()) }.wrap_result();
let Some(global) = context.global() else {
tracing::error!("Global object is not available in V8 context");
return 0;
};
let function_name = "receiveNativeMessage";
let property_name = "receiveNativeMessageData";
let function_call = format!("window.{function_name}(window.{property_name})");
global.set_value_bykey(
Some(&CefString::from(property_name)),
Some(&mut value),
cef_v8_propertyattribute_t::V8_PROPERTY_ATTRIBUTE_READONLY.wrap_result(),
);
if global.value_bykey(Some(&CefString::from(function_name))).is_some() {
frame.execute_java_script(Some(&CefString::from(function_call.as_str())), None, 0);
}
if context.exit() == 0 {
tracing::error!("Failed to exit V8 context");
return 0;
}
}
_ => {
tracing::error!("Unexpected message type received in render process");
return 0;
}
}
1
}
fn on_context_created(&self, _browser: Option<&mut cef::Browser>, _frame: Option<&mut cef::Frame>, context: Option<&mut cef::V8Context>) {
let register_js_function = |context: &mut cef::V8Context, name: &'static str| {
let mut v8_handler = V8Handler::new(RenderProcessV8HandlerImpl::new());
let Some(mut function) = v8_value_create_function(Some(&CefString::from(name)), Some(&mut v8_handler)) else {
tracing::error!("Failed to create V8 function {name}");
return;
};
let Some(global) = context.global() else {
tracing::error!("Global object is not available in V8 context");
return;
};
global.set_value_bykey(Some(&CefString::from(name)), Some(&mut function), V8Propertyattribute::default());
};
let Some(context) = context else {
tracing::error!("V8 context is not available");
return;
};
let initialized_function_name = "initializeNativeCommunication";
let send_function_name = "sendNativeMessage";
register_js_function(context, initialized_function_name);
register_js_function(context, send_function_name);
}
fn get_raw(&self) -> *mut _cef_render_process_handler_t {
self.object.cast()
}
}
impl Clone for RenderProcessHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for RenderProcessHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapRenderProcessHandler for RenderProcessHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_render_process_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/browser_process_app.rs | desktop/src/cef/internal/browser_process_app.rs | #[cfg(target_os = "linux")]
use std::env;
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_app_t, cef_base_ref_counted_t};
use cef::{BrowserProcessHandler, CefString, ImplApp, ImplCommandLine, SchemeRegistrar, WrapApp};
use super::browser_process_handler::BrowserProcessHandlerImpl;
use super::scheme_handler_factory::SchemeHandlerFactoryImpl;
use crate::cef::CefEventHandler;
pub(crate) struct BrowserProcessAppImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_app_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> BrowserProcessAppImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
}
impl<H: CefEventHandler> ImplApp for BrowserProcessAppImpl<H> {
fn browser_process_handler(&self) -> Option<BrowserProcessHandler> {
Some(BrowserProcessHandler::new(BrowserProcessHandlerImpl::new(self.event_handler.duplicate())))
}
fn on_register_custom_schemes(&self, registrar: Option<&mut SchemeRegistrar>) {
SchemeHandlerFactoryImpl::<H>::register_schemes(registrar);
}
fn on_before_command_line_processing(&self, _process_type: Option<&cef::CefString>, command_line: Option<&mut cef::CommandLine>) {
if let Some(cmd) = command_line {
cmd.append_switch_with_value(Some(&CefString::from("renderer-process-limit")), Some(&CefString::from("1")));
cmd.append_switch_with_value(Some(&CefString::from("disk-cache-size")), Some(&CefString::from("0")));
cmd.append_switch(Some(&CefString::from("incognito")));
cmd.append_switch(Some(&CefString::from("no-first-run")));
cmd.append_switch(Some(&CefString::from("disable-file-system")));
cmd.append_switch(Some(&CefString::from("disable-local-storage")));
cmd.append_switch(Some(&CefString::from("disable-background-networking")));
cmd.append_switch(Some(&CefString::from("disable-audio-input")));
cmd.append_switch(Some(&CefString::from("disable-audio-output")));
#[cfg(not(feature = "accelerated_paint"))]
{
// Disable GPU acceleration when accelerated_paint feature is not enabled
cmd.append_switch(Some(&CefString::from("disable-gpu")));
cmd.append_switch(Some(&CefString::from("disable-gpu-compositing")));
}
#[cfg(feature = "accelerated_paint")]
{
// Enable GPU acceleration switches for better performance
cmd.append_switch(Some(&CefString::from("enable-gpu-rasterization")));
cmd.append_switch(Some(&CefString::from("enable-accelerated-2d-canvas")));
}
#[cfg(all(feature = "accelerated_paint", target_os = "linux"))]
{
// Use Vulkan for accelerated painting
cmd.append_switch_with_value(Some(&CefString::from("use-angle")), Some(&CefString::from("vulkan")));
}
// Tell CEF to use Wayland if available
#[cfg(target_os = "linux")]
{
let use_wayland = env::var("WAYLAND_DISPLAY")
.ok()
.filter(|var| !var.is_empty())
.or_else(|| env::var("WAYLAND_SOCKET").ok())
.filter(|var| !var.is_empty())
.is_some();
if use_wayland {
cmd.append_switch_with_value(Some(&CefString::from("ozone-platform")), Some(&CefString::from("wayland")));
}
}
#[cfg(target_os = "macos")]
{
// Hide user prompt asking for keychain access
cmd.append_switch(Some(&CefString::from("use-mock-keychain")));
}
// Enable browser debugging via environment variable
if let Some(env) = std::env::var("GRAPHITE_BROWSER_DEBUG_PORT").ok()
&& let Some(port) = env.parse::<u16>().ok()
{
cmd.append_switch_with_value(Some(&CefString::from("remote-debugging-port")), Some(&CefString::from(port.to_string().as_str())));
cmd.append_switch_with_value(Some(&CefString::from("remote-allow-origins")), Some(&CefString::from("*")));
}
}
}
fn get_raw(&self) -> *mut _cef_app_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for BrowserProcessAppImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for BrowserProcessAppImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapApp for BrowserProcessAppImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_app_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/resource_handler.rs | desktop/src/cef/internal/resource_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_resource_handler_t, cef_base_ref_counted_t};
use cef::{Callback, CefString, ImplResourceHandler, ImplResponse, Request, ResourceReadCallback, Response, WrapResourceHandler};
use std::cell::RefCell;
use std::ffi::c_int;
use std::io::Read;
use crate::cef::{Resource, ResourceReader};
pub(crate) struct ResourceHandlerImpl {
object: *mut RcImpl<_cef_resource_handler_t, Self>,
reader: Option<RefCell<ResourceReader>>,
mimetype: Option<String>,
}
impl ResourceHandlerImpl {
pub fn new(resource: Option<Resource>) -> Self {
if let Some(resource) = resource {
Self {
object: std::ptr::null_mut(),
reader: Some(resource.reader.into()),
mimetype: resource.mimetype,
}
} else {
Self {
object: std::ptr::null_mut(),
reader: None,
mimetype: None,
}
}
}
}
impl ImplResourceHandler for ResourceHandlerImpl {
fn open(&self, _request: Option<&mut Request>, handle_request: Option<&mut c_int>, _callback: Option<&mut Callback>) -> c_int {
if let Some(handle_request) = handle_request {
*handle_request = 1;
}
1
}
fn response_headers(&self, response: Option<&mut Response>, response_length: Option<&mut i64>, _redirect_url: Option<&mut CefString>) {
if let Some(response_length) = response_length {
*response_length = -1; // Indicating that the length is unknown
}
if let Some(response) = response {
if self.reader.is_some() {
if let Some(mimetype) = &self.mimetype {
let cef_mime = CefString::from(mimetype.as_str());
response.set_mime_type(Some(&cef_mime));
} else {
response.set_mime_type(None);
}
response.set_status(200);
} else {
response.set_status(404);
response.set_mime_type(Some(&CefString::from("text/plain")));
}
}
}
fn read(&self, data_out: *mut u8, bytes_to_read: c_int, bytes_read: Option<&mut c_int>, _callback: Option<&mut ResourceReadCallback>) -> c_int {
let Some(bytes_read) = bytes_read else { unreachable!() };
let out = unsafe { std::slice::from_raw_parts_mut(data_out, bytes_to_read as usize) };
if let Some(reader) = &self.reader {
if let Ok(read) = reader.borrow_mut().read(out) {
*bytes_read = read as i32;
if read > 0 {
return 1; // Indicating that data was read
}
} else {
*bytes_read = -2; // Indicating ERR_FAILED
}
}
0 // Indicating no data was read
}
fn get_raw(&self) -> *mut _cef_resource_handler_t {
self.object.cast()
}
}
impl Clone for ResourceHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
reader: self.reader.clone(),
mimetype: self.mimetype.clone(),
}
}
}
impl Rc for ResourceHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapResourceHandler for ResourceHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_resource_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/task.rs | desktop/src/cef/internal/task.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_task_t, cef_base_ref_counted_t};
use cef::{ImplTask, WrapTask};
use std::cell::RefCell;
// Closure-based task wrapper following CEF patterns
pub struct ClosureTask<F> {
pub(crate) object: *mut RcImpl<_cef_task_t, Self>,
pub(crate) closure: RefCell<Option<F>>,
}
impl<F: FnOnce() + Send + 'static> ClosureTask<F> {
pub fn new(closure: F) -> Self {
Self {
object: std::ptr::null_mut(),
closure: RefCell::new(Some(closure)),
}
}
}
impl<F: FnOnce() + Send + 'static> ImplTask for ClosureTask<F> {
fn execute(&self) {
if let Some(closure) = self.closure.borrow_mut().take() {
closure();
}
}
fn get_raw(&self) -> *mut _cef_task_t {
self.object.cast()
}
}
impl<F: FnOnce() + Send + 'static> Clone for ClosureTask<F> {
fn clone(&self) -> Self {
unsafe {
if !self.object.is_null() {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
}
Self {
object: self.object,
closure: RefCell::new(None), // Closure can only be executed once
}
}
}
impl<F: FnOnce() + Send + 'static> Rc for ClosureTask<F> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<F: FnOnce() + Send + 'static> WrapTask for ClosureTask<F> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_task_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/browser_process_handler.rs | desktop/src/cef/internal/browser_process_handler.rs | use std::time::{Duration, Instant};
use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_browser_process_handler_t, cef_base_ref_counted_t, cef_browser_process_handler_t};
use cef::{CefString, ImplBrowserProcessHandler, WrapBrowserProcessHandler};
use crate::cef::CefEventHandler;
pub(crate) struct BrowserProcessHandlerImpl<H: CefEventHandler> {
object: *mut RcImpl<cef_browser_process_handler_t, Self>,
event_handler: H,
}
impl<H: CefEventHandler> BrowserProcessHandlerImpl<H> {
pub(crate) fn new(event_handler: H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler,
}
}
}
impl<H: CefEventHandler> ImplBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
fn on_schedule_message_pump_work(&self, delay_ms: i64) {
self.event_handler.schedule_cef_message_loop_work(Instant::now() + Duration::from_millis(delay_ms as u64));
}
fn on_already_running_app_relaunch(&self, _command_line: Option<&mut cef::CommandLine>, _current_directory: Option<&CefString>) -> std::ffi::c_int {
1 // Return 1 to prevent default behavior of opening a empty browser window
}
fn get_raw(&self) -> *mut _cef_browser_process_handler_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for BrowserProcessHandlerImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
}
}
}
impl<H: CefEventHandler> Rc for BrowserProcessHandlerImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapBrowserProcessHandler for BrowserProcessHandlerImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_browser_process_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/context_menu_handler.rs | desktop/src/cef/internal/context_menu_handler.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_context_menu_handler_t, cef_base_ref_counted_t};
use cef::{ImplContextMenuHandler, WrapContextMenuHandler};
pub(crate) struct ContextMenuHandlerImpl {
object: *mut RcImpl<_cef_context_menu_handler_t, Self>,
}
impl ContextMenuHandlerImpl {
pub(crate) fn new() -> Self {
Self { object: std::ptr::null_mut() }
}
}
impl ImplContextMenuHandler for ContextMenuHandlerImpl {
fn run_context_menu(
&self,
_browser: Option<&mut cef::Browser>,
_frame: Option<&mut cef::Frame>,
_params: Option<&mut cef::ContextMenuParams>,
_model: Option<&mut cef::MenuModel>,
_callback: Option<&mut cef::RunContextMenuCallback>,
) -> std::ffi::c_int {
// Prevent context menu
1
}
fn run_quick_menu(
&self,
_browser: Option<&mut cef::Browser>,
_frame: Option<&mut cef::Frame>,
_location: Option<&cef::Point>,
_size: Option<&cef::Size>,
_edit_state_flags: cef::QuickMenuEditStateFlags,
_callback: Option<&mut cef::RunQuickMenuCallback>,
) -> std::ffi::c_int {
// Prevent quick menu
1
}
fn get_raw(&self) -> *mut _cef_context_menu_handler_t {
self.object.cast()
}
}
impl Clone for ContextMenuHandlerImpl {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self { object: self.object }
}
}
impl Rc for ContextMenuHandlerImpl {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl WrapContextMenuHandler for ContextMenuHandlerImpl {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_context_menu_handler_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/internal/browser_process_client.rs | desktop/src/cef/internal/browser_process_client.rs | use cef::rc::{Rc, RcImpl};
use cef::sys::{_cef_client_t, cef_base_ref_counted_t};
use cef::{ContextMenuHandler, DisplayHandler, ImplClient, LifeSpanHandler, LoadHandler, RenderHandler, WrapClient};
use crate::cef::CefEventHandler;
use crate::cef::ipc::{MessageType, UnpackMessage, UnpackedMessage};
use super::context_menu_handler::ContextMenuHandlerImpl;
use super::display_handler::DisplayHandlerImpl;
use super::life_span_handler::LifeSpanHandlerImpl;
use super::load_handler::LoadHandlerImpl;
use super::render_handler::RenderHandlerImpl;
pub(crate) struct BrowserProcessClientImpl<H: CefEventHandler> {
object: *mut RcImpl<_cef_client_t, Self>,
event_handler: H,
load_handler: LoadHandler,
render_handler: RenderHandler,
display_handler: DisplayHandler,
}
impl<H: CefEventHandler> BrowserProcessClientImpl<H> {
pub(crate) fn new(event_handler: &H) -> Self {
Self {
object: std::ptr::null_mut(),
event_handler: event_handler.duplicate(),
load_handler: LoadHandler::new(LoadHandlerImpl::new(event_handler.duplicate())),
render_handler: RenderHandler::new(RenderHandlerImpl::new(event_handler.duplicate())),
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(event_handler.duplicate())),
}
}
}
impl<H: CefEventHandler> ImplClient for BrowserProcessClientImpl<H> {
fn on_process_message_received(
&self,
_browser: Option<&mut cef::Browser>,
_frame: Option<&mut cef::Frame>,
_source_process: cef::ProcessId,
message: Option<&mut cef::ProcessMessage>,
) -> std::ffi::c_int {
let unpacked_message = unsafe { message.and_then(|m| m.unpack()) };
match unpacked_message {
Some(UnpackedMessage {
message_type: MessageType::Initialized,
data: _,
}) => self.event_handler.initialized_web_communication(),
Some(UnpackedMessage {
message_type: MessageType::SendToNative,
data,
}) => self.event_handler.receive_web_message(data),
_ => {
tracing::error!("Unexpected message type received in browser process");
return 0;
}
}
1
}
fn load_handler(&self) -> Option<cef::LoadHandler> {
Some(self.load_handler.clone())
}
fn render_handler(&self) -> Option<RenderHandler> {
Some(self.render_handler.clone())
}
fn life_span_handler(&self) -> Option<cef::LifeSpanHandler> {
Some(LifeSpanHandler::new(LifeSpanHandlerImpl::new()))
}
fn display_handler(&self) -> Option<cef::DisplayHandler> {
Some(self.display_handler.clone())
}
fn context_menu_handler(&self) -> Option<cef::ContextMenuHandler> {
Some(ContextMenuHandler::new(ContextMenuHandlerImpl::new()))
}
fn get_raw(&self) -> *mut _cef_client_t {
self.object.cast()
}
}
impl<H: CefEventHandler> Clone for BrowserProcessClientImpl<H> {
fn clone(&self) -> Self {
unsafe {
let rc_impl = &mut *self.object;
rc_impl.interface.add_ref();
}
Self {
object: self.object,
event_handler: self.event_handler.duplicate(),
load_handler: self.load_handler.clone(),
render_handler: self.render_handler.clone(),
display_handler: self.display_handler.clone(),
}
}
}
impl<H: CefEventHandler> Rc for BrowserProcessClientImpl<H> {
fn as_base(&self) -> &cef_base_ref_counted_t {
unsafe {
let base = &*self.object;
std::mem::transmute(&base.cef_object)
}
}
}
impl<H: CefEventHandler> WrapClient for BrowserProcessClientImpl<H> {
fn wrap_rc(&mut self, object: *mut RcImpl<_cef_client_t, Self>) {
self.object = object;
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/context/builder.rs | desktop/src/cef/context/builder.rs | use std::path::{Path, PathBuf};
use cef::args::Args;
use cef::sys::{CEF_API_VERSION_LAST, cef_resultcode_t};
use cef::{
App, BrowserSettings, CefString, Client, DictionaryValue, ImplCommandLine, ImplRequestContext, RequestContextSettings, SchemeHandlerFactory, Settings, WindowInfo, api_hash,
browser_host_create_browser_sync, execute_process,
};
use super::CefContext;
use super::singlethreaded::SingleThreadedCefContext;
use crate::cef::CefEventHandler;
use crate::cef::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
use crate::cef::dirs::{create_instance_dir, delete_instance_dirs};
use crate::cef::input::InputState;
use crate::cef::internal::{BrowserProcessAppImpl, BrowserProcessClientImpl, RenderProcessAppImpl, SchemeHandlerFactoryImpl};
pub(crate) struct CefContextBuilder<H: CefEventHandler> {
pub(crate) args: Args,
pub(crate) is_sub_process: bool,
_marker: std::marker::PhantomData<H>,
}
unsafe impl<H: CefEventHandler> Send for CefContextBuilder<H> {}
impl<H: CefEventHandler> CefContextBuilder<H> {
pub(crate) fn new() -> Self {
Self::new_inner(false)
}
pub(crate) fn new_helper() -> Self {
Self::new_inner(true)
}
fn new_inner(helper: bool) -> Self {
#[cfg(target_os = "macos")]
let _loader = {
let loader = cef::library_loader::LibraryLoader::new(&std::env::current_exe().unwrap(), helper);
assert!(loader.load());
loader
};
#[cfg(not(target_os = "macos"))]
let _ = helper;
let _ = api_hash(CEF_API_VERSION_LAST, 0);
let args = Args::new();
let cmd = args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let is_sub_process = cmd.has_switch(Some(&switch)) == 1;
Self {
args,
is_sub_process,
_marker: std::marker::PhantomData,
}
}
pub(crate) fn is_sub_process(&self) -> bool {
self.is_sub_process
}
pub(crate) fn execute_sub_process(&self) -> SetupError {
let cmd = self.args.as_cmd_line().unwrap();
let switch = CefString::from("type");
let process_type = CefString::from(&cmd.switch_value(Some(&switch)));
let mut app = RenderProcessAppImpl::<H>::app();
let ret = execute_process(Some(self.args.as_main_args()), Some(&mut app), std::ptr::null_mut());
if ret >= 0 {
SetupError::SubprocessFailed(process_type.to_string())
} else {
SetupError::Subprocess
}
}
fn common_settings(instance_dir: &Path) -> Settings {
Settings {
windowless_rendering_enabled: 1,
root_cache_path: instance_dir.to_str().map(CefString::from).unwrap(),
cache_path: CefString::from(""),
disable_signal_handlers: 1,
..Default::default()
}
}
#[cfg(target_os = "macos")]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let exe = std::env::current_exe().expect("cannot get current exe path");
let app_root = exe.parent().and_then(|p| p.parent()).expect("bad path structure").parent().expect("bad path structure");
let settings = Settings {
main_bundle_path: CefString::from(app_root.to_str().unwrap()),
multi_threaded_message_loop: 0,
external_message_pump: 1,
no_sandbox: 1, // GPU helper crashes when running with sandbox
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
create_browser(event_handler, instance_dir, disable_gpu_acceleration)
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn initialize(self, event_handler: H, disable_gpu_acceleration: bool) -> Result<impl CefContext, InitError> {
delete_instance_dirs();
let instance_dir = create_instance_dir();
let settings = Settings {
multi_threaded_message_loop: 1,
..Self::common_settings(&instance_dir)
};
self.initialize_inner(&event_handler, settings)?;
super::multithreaded::run_on_ui_thread(move || match create_browser(event_handler, instance_dir, disable_gpu_acceleration) {
Ok(context) => {
super::multithreaded::CONTEXT.with(|b| {
*b.borrow_mut() = Some(context);
});
}
Err(e) => {
tracing::error!("Failed to initialize CEF context: {:?}", e);
std::process::exit(1);
}
});
Ok(super::multithreaded::MultiThreadedCefContextProxy)
}
fn initialize_inner(self, event_handler: &H, settings: Settings) -> Result<(), InitError> {
// Attention! Wrapping this in an extra App is necessary, otherwise the program still compiles but segfaults
let mut cef_app = App::new(BrowserProcessAppImpl::new(event_handler.duplicate()));
let result = cef::initialize(Some(self.args.as_main_args()), Some(&settings), Some(&mut cef_app), std::ptr::null_mut());
if result != 1 {
let cef_exit_code = cef::get_exit_code() as u32;
if cef_exit_code == cef_resultcode_t::CEF_RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED as u32 {
return Err(InitError::AlreadyRunning);
}
return Err(InitError::InitializationFailed(cef_exit_code));
}
Ok(())
}
}
fn create_browser<H: CefEventHandler>(event_handler: H, instance_dir: PathBuf, disable_gpu_acceleration: bool) -> Result<SingleThreadedCefContext, InitError> {
let mut client = Client::new(BrowserProcessClientImpl::new(&event_handler));
#[cfg(feature = "accelerated_paint")]
let use_accelerated_paint = if disable_gpu_acceleration {
false
} else {
crate::cef::platform::should_enable_hardware_acceleration()
};
let window_info = WindowInfo {
windowless_rendering_enabled: 1,
#[cfg(feature = "accelerated_paint")]
shared_texture_enabled: use_accelerated_paint as i32,
..Default::default()
};
let settings = BrowserSettings {
windowless_frame_rate: crate::consts::CEF_WINDOWLESS_FRAME_RATE,
background_color: 0x0,
..Default::default()
};
let Some(mut incognito_request_context) = cef::request_context_create_context(
Some(&RequestContextSettings {
persist_session_cookies: 0,
cache_path: CefString::from(""),
..Default::default()
}),
Option::<&mut cef::RequestContextHandler>::None,
) else {
return Err(InitError::RequestContextCreationFailed);
};
let mut scheme_handler_factory = SchemeHandlerFactory::new(SchemeHandlerFactoryImpl::new(event_handler.duplicate()));
incognito_request_context.clear_scheme_handler_factories();
incognito_request_context.register_scheme_handler_factory(Some(&CefString::from(RESOURCE_SCHEME)), Some(&CefString::from(RESOURCE_DOMAIN)), Some(&mut scheme_handler_factory));
let url = CefString::from(format!("{RESOURCE_SCHEME}://{RESOURCE_DOMAIN}/").as_str());
let browser = browser_host_create_browser_sync(
Some(&window_info),
Some(&mut client),
Some(&url),
Some(&settings),
Option::<&mut DictionaryValue>::None,
Some(&mut incognito_request_context),
);
if let Some(browser) = browser {
Ok(SingleThreadedCefContext {
event_handler: Box::new(event_handler),
browser,
input_state: InputState::default(),
instance_dir,
})
} else {
tracing::error!("Failed to create browser");
Err(InitError::BrowserCreationFailed)
}
}
#[derive(thiserror::Error, Debug)]
pub(crate) enum SetupError {
#[error("This is the sub process should exit immediately")]
Subprocess,
#[error("Subprocess returned non zero exit code")]
SubprocessFailed(String),
}
#[derive(thiserror::Error, Debug)]
pub(crate) enum InitError {
#[error("Initialization failed")]
InitializationFailed(u32),
#[error("Browser creation failed")]
BrowserCreationFailed,
#[error("Request context creation failed")]
RequestContextCreationFailed,
#[error("Another instance is already running")]
AlreadyRunning,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/context/multithreaded.rs | desktop/src/cef/context/multithreaded.rs | use cef::sys::cef_thread_id_t;
use cef::{Task, ThreadId, post_task};
use std::cell::RefCell;
use winit::event::WindowEvent;
use crate::cef::internal::task::ClosureTask;
use super::CefContext;
use super::singlethreaded::SingleThreadedCefContext;
thread_local! {
pub(super) static CONTEXT: RefCell<Option<SingleThreadedCefContext>> = const { RefCell::new(None) };
}
pub(super) struct MultiThreadedCefContextProxy;
impl CefContext for MultiThreadedCefContextProxy {
fn work(&mut self) {
// CEF handles its own message loop in multi-threaded mode
}
fn handle_window_event(&mut self, event: &WindowEvent) {
let event_clone = event.clone();
run_on_ui_thread(move || {
CONTEXT.with(|b| {
if let Some(context) = b.borrow_mut().as_mut() {
context.handle_window_event(&event_clone);
}
});
});
}
fn notify_view_info_changed(&self) {
run_on_ui_thread(move || {
CONTEXT.with(|b| {
if let Some(context) = b.borrow_mut().as_mut() {
context.notify_view_info_changed();
}
});
});
}
fn send_web_message(&self, message: Vec<u8>) {
run_on_ui_thread(move || {
CONTEXT.with(|b| {
if let Some(context) = b.borrow_mut().as_mut() {
context.send_web_message(message);
}
});
});
}
}
impl Drop for MultiThreadedCefContextProxy {
fn drop(&mut self) {
cef::shutdown();
}
}
pub(super) fn run_on_ui_thread<F>(closure: F)
where
F: FnOnce() + Send + 'static,
{
let closure_task = ClosureTask::new(closure);
let mut task = Task::new(closure_task);
post_task(ThreadId::from(cef_thread_id_t::TID_UI), Some(&mut task));
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/cef/context/singlethreaded.rs | desktop/src/cef/context/singlethreaded.rs | use cef::{Browser, ImplBrowser, ImplBrowserHost};
use winit::event::WindowEvent;
use crate::cef::input::InputState;
use crate::cef::ipc::{MessageType, SendMessage};
use crate::cef::{CefEventHandler, input};
use super::CefContext;
pub(super) struct SingleThreadedCefContext {
pub(super) event_handler: Box<dyn CefEventHandler>,
pub(super) browser: Browser,
pub(super) input_state: InputState,
pub(super) instance_dir: std::path::PathBuf,
}
impl CefContext for SingleThreadedCefContext {
fn work(&mut self) {
cef::do_message_loop_work();
}
fn handle_window_event(&mut self, event: &WindowEvent) {
input::handle_window_event(&self.browser, &mut self.input_state, event);
}
fn notify_view_info_changed(&self) {
let view_info = self.event_handler.view_info();
let host = self.browser.host().unwrap();
host.set_zoom_level(view_info.zoom());
host.was_resized();
// Fix for CEF not updating the view after resize on windows and mac
// TODO: remove once https://github.com/chromiumembedded/cef/issues/3822 is fixed
#[cfg(any(target_os = "windows", target_os = "macos"))]
host.invalidate(cef::PaintElementType::default());
}
fn send_web_message(&self, message: Vec<u8>) {
self.send_message(MessageType::SendToJS, &message);
}
}
impl Drop for SingleThreadedCefContext {
fn drop(&mut self) {
cef::shutdown();
// Sometimes some CEF processes still linger at this point and hold file handles to the cache directory.
// To mitigate this, we try to remove the directory multiple times with some delay.
// TODO: find a better solution if possible.
for _ in 0..30 {
match std::fs::remove_dir_all(&self.instance_dir) {
Ok(_) => break,
Err(e) => {
tracing::warn!("Failed to remove CEF cache directory, retrying...: {e}");
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
}
}
impl SendMessage for SingleThreadedCefContext {
fn send_message(&self, message_type: MessageType, message: &[u8]) {
let Some(frame) = self.browser.main_frame() else {
tracing::error!("Main frame is not available, cannot send message");
return;
};
frame.send_message(message_type, message);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/win.rs | desktop/src/window/win.rs | use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
use windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID;
use windows::core::HSTRING;
use winit::event_loop::ActiveEventLoop;
use winit::window::{Window, WindowAttributes};
use crate::consts::APP_ID;
use crate::event::AppEventScheduler;
pub(super) struct NativeWindowImpl {
native_handle: native_handle::NativeWindowHandle,
}
impl super::NativeWindow for NativeWindowImpl {
fn init() {
let app_id = HSTRING::from(APP_ID);
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok();
SetCurrentProcessExplicitAppUserModelID(&app_id).ok();
}
}
fn configure(attributes: WindowAttributes, _event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
attributes
}
fn new(window: &dyn Window, _app_event_scheduler: AppEventScheduler) -> Self {
let native_handle = native_handle::NativeWindowHandle::new(window);
NativeWindowImpl { native_handle }
}
fn can_render(&self) -> bool {
self.native_handle.can_render()
}
}
impl Drop for NativeWindowImpl {
fn drop(&mut self) {
self.native_handle.destroy();
}
}
mod native_handle;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/linux.rs | desktop/src/window/linux.rs | use winit::event_loop::ActiveEventLoop;
use winit::platform::wayland::ActiveEventLoopExtWayland;
use winit::platform::wayland::WindowAttributesWayland;
use winit::platform::x11::WindowAttributesX11;
use winit::window::{Window, WindowAttributes};
use crate::consts::{APP_ID, APP_NAME};
use crate::event::AppEventScheduler;
pub(super) struct NativeWindowImpl {}
impl super::NativeWindow for NativeWindowImpl {
fn configure(attributes: WindowAttributes, event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
if event_loop.is_wayland() {
let wayland_attributes = WindowAttributesWayland::default().with_name(APP_ID, "").with_prefer_csd(true);
attributes.with_platform_attributes(Box::new(wayland_attributes))
} else {
let x11_attributes = WindowAttributesX11::default().with_name(APP_ID, APP_NAME);
attributes.with_platform_attributes(Box::new(x11_attributes))
}
}
fn new(_window: &dyn Window, _app_event_scheduler: AppEventScheduler) -> Self {
NativeWindowImpl {}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/mac.rs | desktop/src/window/mac.rs | use winit::event_loop::ActiveEventLoop;
use winit::platform::macos::WindowAttributesMacOS;
use winit::window::{Window, WindowAttributes};
use crate::event::AppEventScheduler;
use crate::wrapper::messages::MenuItem;
mod app;
mod menu;
pub(super) struct NativeWindowImpl {
menu: menu::Menu,
}
impl super::NativeWindow for NativeWindowImpl {
fn init() {
app::init();
}
fn configure(attributes: WindowAttributes, _event_loop: &dyn ActiveEventLoop) -> WindowAttributes {
let mac_window = WindowAttributesMacOS::default()
.with_titlebar_transparent(true)
.with_fullsize_content_view(true)
.with_title_hidden(true);
attributes.with_platform_attributes(Box::new(mac_window))
}
fn new(_window: &dyn Window, app_event_scheduler: AppEventScheduler) -> Self {
let menu = menu::Menu::new(app_event_scheduler);
NativeWindowImpl { menu }
}
fn update_menu(&self, entries: Vec<MenuItem>) {
self.menu.update(entries);
}
fn hide(&self) {
app::hide();
}
fn hide_others(&self) {
app::hide_others();
}
fn show_all(&self) {
app::show_all();
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/mac/app.rs | desktop/src/window/mac/app.rs | use objc2::{ClassType, define_class, msg_send};
use objc2_app_kit::{NSApplication, NSEvent, NSEventType, NSResponder};
use objc2_foundation::NSObject;
define_class!(
#[unsafe(super(NSApplication, NSResponder, NSObject))]
#[name = "GraphiteApplication"]
pub(super) struct GraphiteApplication;
impl GraphiteApplication {
#[unsafe(method(sendEvent:))]
fn send_event(&self, event: &NSEvent) {
// Route keyDown events straight to the key window to skip native menu shortcut handling.
if event.r#type() == NSEventType::KeyDown && let Some(key_window) = self.keyWindow() {
unsafe { msg_send![&key_window, sendEvent: event] }
} else {
unsafe { msg_send![super(self), sendEvent: event] }
}
}
}
);
fn instance() -> objc2::rc::Retained<NSApplication> {
unsafe { msg_send![GraphiteApplication::class(), sharedApplication] }
}
pub(super) fn init() {
let _ = instance();
}
pub(super) fn hide() {
instance().hide(None);
}
pub(super) fn hide_others() {
instance().hideOtherApplications(None);
}
pub(super) fn show_all() {
instance().unhideAllApplications(None);
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/mac/menu.rs | desktop/src/window/mac/menu.rs | use muda::Menu as MudaMenu;
use muda::accelerator::Accelerator;
use muda::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, MenuItemKind, PredefinedMenuItem, Result, Submenu};
use crate::event::{AppEvent, AppEventScheduler};
use crate::wrapper::messages::MenuItem as WrapperMenuItem;
pub(super) struct Menu {
inner: MudaMenu,
}
impl Menu {
pub(super) fn new(event_scheduler: AppEventScheduler) -> Self {
// TODO: Remove as much app submenu special handling as possible
let app_submenu = Submenu::with_items("", true, &[]).unwrap();
let menu = MudaMenu::new();
menu.prepend(&app_submenu).unwrap();
menu.init_for_nsapp();
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
let mtm = objc2::MainThreadMarker::new().expect("only ever called from main thread");
let is_shortcut_triggered = objc2_app_kit::NSApplication::sharedApplication(mtm)
.mainMenu()
.map(|m| m.highlightedItem().is_some())
.unwrap_or_default();
if is_shortcut_triggered {
tracing::error!("A keyboard input triggered a menu event. This is most likely a bug. Please report!");
return;
}
let id = event.id().0.clone();
event_scheduler.schedule(AppEvent::MenuEvent { id });
}));
Menu { inner: menu }
}
pub(super) fn update(&self, entries: Vec<WrapperMenuItem>) {
let new_entries = menu_items_from_wrapper(entries);
let existing_entries = self.inner.items();
let mut new_entries_iter = new_entries.iter();
let mut existing_entries_iter = existing_entries.iter();
let incremental_update_ok = std::iter::from_fn(move || match (existing_entries_iter.next(), new_entries_iter.next()) {
(Some(MenuItemKind::Submenu(old)), Some(MenuItemKind::Submenu(new))) if old.text() == new.text() => {
replace_children(old, new.items());
Some(true)
}
(None, None) => None,
_ => Some(false),
})
.all(|b| b);
if !incremental_update_ok {
// Fallback to full replace
replace_children(&self.inner, new_entries);
}
}
}
fn menu_items_from_wrapper(entries: Vec<WrapperMenuItem>) -> Vec<MenuItemKind> {
let mut menu_items: Vec<MenuItemKind> = Vec::new();
for entry in entries {
match entry {
WrapperMenuItem::Action { id, text, enabled, shortcut } => {
let accelerator = shortcut.map(|s| Accelerator::new(Some(s.modifiers), s.key));
let item = MenuItem::with_id(id, text, enabled, accelerator);
menu_items.push(MenuItemKind::MenuItem(item));
}
WrapperMenuItem::Checkbox { id, text, enabled, shortcut, checked } => {
let accelerator = shortcut.map(|s| Accelerator::new(Some(s.modifiers), s.key));
let check = CheckMenuItem::with_id(id, text, enabled, checked, accelerator);
menu_items.push(MenuItemKind::Check(check));
}
WrapperMenuItem::SubMenu { text: name, items, .. } => {
let items = menu_items_from_wrapper(items);
let items = items.iter().map(|item| menu_item_kind_to_dyn(item)).collect::<Vec<&dyn IsMenuItem>>();
let submenu = Submenu::with_items(name, true, &items).unwrap();
menu_items.push(MenuItemKind::Submenu(submenu));
}
WrapperMenuItem::Separator => {
let separator = PredefinedMenuItem::separator();
menu_items.push(MenuItemKind::Predefined(separator));
}
}
}
menu_items
}
fn menu_item_kind_to_dyn(item: &MenuItemKind) -> &dyn IsMenuItem {
match item {
MenuItemKind::MenuItem(i) => i,
MenuItemKind::Submenu(i) => i,
MenuItemKind::Predefined(i) => i,
MenuItemKind::Check(i) => i,
MenuItemKind::Icon(i) => i,
}
}
fn replace_children<'a, T: Into<MenuContainer<'a>>>(menu: T, new_items: Vec<MenuItemKind>) {
let menu: MenuContainer = menu.into();
let items = menu.items();
for item in items.iter() {
menu.remove(menu_item_kind_to_dyn(item)).unwrap();
}
let items = new_items.iter().map(|item| menu_item_kind_to_dyn(item)).collect::<Vec<&dyn IsMenuItem>>();
menu.append_items(items.as_ref()).unwrap();
}
enum MenuContainer<'a> {
Menu(&'a MudaMenu),
Submenu(&'a Submenu),
}
impl<'a> MenuContainer<'a> {
fn items(&self) -> Vec<MenuItemKind> {
match self {
MenuContainer::Menu(menu) => menu.items(),
MenuContainer::Submenu(submenu) => submenu.items(),
}
}
fn remove(&self, item: &dyn IsMenuItem) -> Result<()> {
match self {
MenuContainer::Menu(menu) => menu.remove(item),
MenuContainer::Submenu(submenu) => submenu.remove(item),
}
}
fn append_items(&self, items: &[&dyn IsMenuItem]) -> Result<()> {
match self {
MenuContainer::Menu(menu) => menu.append_items(items),
MenuContainer::Submenu(submenu) => submenu.append_items(items),
}
}
}
impl<'a> From<&'a MudaMenu> for MenuContainer<'a> {
fn from(menu: &'a MudaMenu) -> Self {
MenuContainer::Menu(menu)
}
}
impl<'a> From<&'a Submenu> for MenuContainer<'a> {
fn from(submenu: &'a Submenu) -> Self {
MenuContainer::Submenu(submenu)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/window/win/native_handle.rs | desktop/src/window/win/native_handle.rs | //! Implements a Windows-specific custom window frame (no titlebar, but native boarder, shadows and resize).
//! Look and feel should be similar to a standard window.
//!
//! Implementation notes:
//! - Windows that don't use standard decorations don't get native resize handles or shadows by default.
//! - We implement resize handles (outside the main window) by creating an invisible "helper" window that
//! is a little larger than the main window and positioned on top of it. The helper window does hit-testing
//! and triggers native resize operations on the main window when the user clicks and drags a resize area.
//! - The helper window is a invisible window that never activates, so it doesn't steal focus from the main window.
//! - The main window needs to update the helper window's position and size whenever it moves or resizes.
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use wgpu::rwh::{HasWindowHandle, RawWindowHandle};
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Dwm::*;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Controls::MARGINS;
use windows::Win32::UI::HiDpi::*;
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::core::PCWSTR;
use winit::window::Window;
#[derive(Default)]
struct NativeWindowState {
can_render: bool,
can_render_since: Option<Instant>,
}
#[derive(Clone)]
pub(super) struct NativeWindowHandle {
main: HWND,
helper: HWND,
prev_window_message_handler: isize,
state: Arc<Mutex<NativeWindowState>>,
}
impl NativeWindowHandle {
pub(super) fn new(window: &dyn Window) -> NativeWindowHandle {
// Extract Win32 HWND from winit.
let main = match window.window_handle().expect("No window handle").as_raw() {
RawWindowHandle::Win32(h) => HWND(h.hwnd.get() as *mut std::ffi::c_void),
_ => panic!("Not a Win32 window"),
};
// Register the invisible helper (resize ring) window class.
unsafe { ensure_helper_class() };
// Create the helper as a popup tool window that never activates.
// WS_EX_NOACTIVATE keeps focus on the main window; WS_EX_TOOLWINDOW hides it from Alt+Tab.
// https://learn.microsoft.com/windows/win32/winmsg/extended-window-styles
let ex = WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW;
let style = WS_POPUP;
let helper = unsafe {
CreateWindowExW(
ex,
PCWSTR(HELPER_CLASS_NAME.encode_utf16().collect::<Vec<_>>().as_ptr()),
PCWSTR::null(),
style,
0,
0,
0,
0,
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 _),
)
}
.expect("CreateWindowExW failed");
// Subclass the main window.
// https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-setwindowlongptra
let prev_window_message_handler = unsafe { SetWindowLongPtrW(main, GWLP_WNDPROC, main_window_handle_message as isize) };
if prev_window_message_handler == 0 {
let _ = unsafe { DestroyWindow(helper) };
panic!("SetWindowLongPtrW failed");
}
let native_handle = NativeWindowHandle {
main,
helper,
prev_window_message_handler,
state: Arc::new(Mutex::new(NativeWindowState::default())),
};
registry::insert(&native_handle);
// Place the helper over the main window and show it without activation.
unsafe { position_helper(main, helper) };
let _ = unsafe { ShowWindow(helper, SW_SHOWNOACTIVATE) };
// DwmExtendFrameIntoClientArea is needed to keep native window frame (but no titlebar).
// https://learn.microsoft.com/windows/win32/api/dwmapi/nf-dwmapi-dwmextendframeintoclientarea
// https://learn.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
let mut boarder_size: u32 = 1;
let _ = unsafe { DwmGetWindowAttribute(main, DWMWA_VISIBLE_FRAME_BORDER_THICKNESS, &mut boarder_size as *mut _ as *mut _, size_of::<u32>() as u32) };
let margins = MARGINS {
cxLeftWidth: 0,
cxRightWidth: 0,
cyBottomHeight: 0,
cyTopHeight: boarder_size as i32,
};
let _ = unsafe { DwmExtendFrameIntoClientArea(main, &margins) };
let hinst = unsafe { GetModuleHandleW(None) }.unwrap();
// 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) } {
unsafe { SetClassLongPtrW(main, GCLP_HICON, big.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_BIG as usize), 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) } {
unsafe { SetClassLongPtrW(main, GCLP_HICONSM, small.0 as isize) };
unsafe { SendMessageW(main, WM_SETICON, WPARAM(ICON_SMALL as usize), LPARAM(small.0 as isize)) };
}
// Force window update
let _ = unsafe { SetWindowPos(main, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER) };
native_handle
}
pub(super) fn destroy(&self) {
registry::remove_by_main(self.main);
// Undo subclassing and destroy the helper window.
let _ = unsafe { SetWindowLongPtrW(self.main, GWLP_WNDPROC, self.prev_window_message_handler) };
if !self.helper.is_invalid() {
let _ = unsafe { DestroyWindow(self.helper) };
}
}
// Rendering should be disabled when window is minimized
// Rendering also needs to be disabled during minimize and restore animations
// Reenabling rendering is done after a small delay to account for restore animation
// TODO: Find a cleaner solution that doesn't depend on a timeout
pub(super) fn can_render(&self) -> bool {
let can_render = !unsafe { IsIconic(self.main).into() } && unsafe { IsWindowVisible(self.main).into() };
let Ok(mut state) = self.state.lock() else {
tracing::error!("Failed to lock NativeWindowState");
return true;
};
match (can_render, state.can_render, state.can_render_since) {
(true, false, None) => {
state.can_render_since = Some(Instant::now());
}
(true, false, Some(can_render_since)) if can_render_since.elapsed().as_millis() > 50 => {
state.can_render = true;
state.can_render_since = None;
}
(false, true, _) => {
state.can_render = false;
}
_ => {}
}
state.can_render
}
}
mod registry {
use std::cell::RefCell;
use windows::Win32::Foundation::HWND;
use super::NativeWindowHandle;
thread_local! {
static STORE: RefCell<Vec<NativeWindowHandle>> = RefCell::new(Vec::new());
}
pub(super) fn find_by_main(main: HWND) -> Option<NativeWindowHandle> {
STORE.with_borrow(|vec| vec.iter().find(|h| h.main == main).cloned())
}
pub(super) fn remove_by_main(main: HWND) {
STORE.with_borrow_mut(|vec| {
vec.retain(|h| h.main != main);
});
}
pub(super) fn insert(handle: &NativeWindowHandle) {
STORE.with_borrow_mut(|vec| {
vec.push(handle.clone());
});
}
}
const HELPER_CLASS_NAME: &str = "Helper\0";
static HELPER_CLASS_LOCK: OnceLock<u16> = OnceLock::new();
unsafe fn ensure_helper_class() {
// Register a window class for the invisible resize helper.
let _ = *HELPER_CLASS_LOCK.get_or_init(|| {
let class_name: Vec<u16> = HELPER_CLASS_NAME.encode_utf16().collect();
let wc = WNDCLASSW {
style: CS_HREDRAW | CS_VREDRAW,
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() },
// No painting; the ring is invisible.
hbrBackground: HBRUSH::default(),
lpszClassName: PCWSTR(class_name.as_ptr()),
..Default::default()
};
unsafe { RegisterClassW(&wc) }
});
}
// Main window message handler, called on the UI thread for every message the main window receives.
unsafe extern "system" fn main_window_handle_message(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if msg == WM_NCCALCSIZE && wparam.0 != 0 {
// When maximized, shrink to visible frame so content doesn't extend beyond it.
if unsafe { IsZoomed(hwnd).as_bool() } {
let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
let dpi = unsafe { GetDpiForWindow(hwnd) };
let size = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
let pad = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
let inset = (size + pad) as i32;
params.rgrc[0].left += inset;
params.rgrc[0].top += inset;
params.rgrc[0].right -= inset;
params.rgrc[0].bottom -= inset;
}
// Return 0 to to tell Windows to skip the default non-client area calculation and drawing.
return LRESULT(0);
}
let Some(handle) = registry::find_by_main(hwnd) else {
return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
};
match msg {
// Keep the invisible resize helper in sync with moves/resizes/visibility.
WM_MOVE | WM_MOVING | WM_SIZE | WM_SIZING | WM_WINDOWPOSCHANGED | WM_SHOWWINDOW => {
if msg == WM_SHOWWINDOW {
if wparam.0 == 0 {
let _ = unsafe { ShowWindow(handle.helper, SW_HIDE) };
} else {
let _ = unsafe { ShowWindow(handle.helper, SW_SHOWNOACTIVATE) };
}
}
unsafe { position_helper(hwnd, handle.helper) };
}
// If the main window is destroyed, destroy the helper too.
// Should only be needed if windows forcefully destroys the main window.
WM_DESTROY => {
let _ = unsafe { DestroyWindow(handle.helper) };
}
_ => {}
}
// Ensure the previous window message handler is not null.
assert_ne!(handle.prev_window_message_handler, 0);
// Call the previous window message handler, this is a standard subclassing pattern.
let prev_window_message_handler_fn_ptr: *const () = std::ptr::without_provenance(handle.prev_window_message_handler as usize);
let prev_window_message_handler_fn = unsafe { std::mem::transmute::<_, _>(prev_window_message_handler_fn_ptr) };
unsafe { CallWindowProcW(Some(prev_window_message_handler_fn), hwnd, msg, wparam, lparam) }
}
// Helper window message handler, called on the UI thread for every message the helper window receives.
unsafe extern "system" fn helper_window_handle_message(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
match msg {
// Helper window creation, should be the first message that the helper window receives.
WM_NCCREATE => {
// Main window HWND is provided when creating the helper window with `CreateWindowExW`
// Save main window HWND in GWLP_USERDATA so we can extract it later
let crate_struct = lparam.0 as *const CREATESTRUCTW;
let create_param = unsafe { (*crate_struct).lpCreateParams as *const HWND };
unsafe { SetWindowLongPtrW(hwnd, GWLP_USERDATA, (*create_param).0 as isize) };
return LRESULT(1);
}
// Invisible; no background erase.
WM_ERASEBKGND => return LRESULT(1),
// Tell windows what resize areas we are hitting, this is used to decide what cursor to show.
WM_NCHITTEST => {
let ht = unsafe { calculate_hit(hwnd, lparam) };
return LRESULT(ht as isize);
}
// This starts the system's resize loop for the main window if a resize area is hit.
// Helper window button down translates to SC_SIZE | WMSZ_* on the main window.
WM_NCLBUTTONDOWN | WM_NCRBUTTONDOWN | WM_NCMBUTTONDOWN => {
// 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() } {
let Some(wmsz) = (unsafe { calculate_resize_direction(hwnd, lparam) }) else {
return LRESULT(0);
};
// Ensure that the main window can receive WM_SYSCOMMAND.
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) };
}
return LRESULT(0);
}
// Never activate the helper window, allows all inputs that don't hit the resize areas to pass through.
WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE as isize),
_ => {}
}
unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
}
const RESIZE_BAND_THICKNESS: i32 = 8;
// Position the helper window to match the main window's location and size (plus the resize band size).
unsafe fn position_helper(main: HWND, helper: HWND) {
let mut r = RECT::default();
let _ = unsafe { GetWindowRect(main, &mut r) };
let x = r.left - RESIZE_BAND_THICKNESS;
let y = r.top - RESIZE_BAND_THICKNESS;
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_NOZORDER | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING) };
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
let x = (lparam.0 & 0xFFFF) as i16 as u32;
let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as u32;
let mut r = RECT::default();
let _ = unsafe { GetWindowRect(helper, &mut r) };
let on_top = y < (r.top + RESIZE_BAND_THICKNESS) as u32;
let on_right = x >= (r.right - RESIZE_BAND_THICKNESS) as u32;
let on_bottom = y >= (r.bottom - RESIZE_BAND_THICKNESS) as u32;
let on_left = x < (r.left + RESIZE_BAND_THICKNESS) as u32;
match (on_top, on_right, on_bottom, on_left) {
(true, _, _, true) => HTTOPLEFT,
(true, true, _, _) => HTTOPRIGHT,
(_, true, true, _) => HTBOTTOMRIGHT,
(_, _, true, true) => HTBOTTOMLEFT,
(true, _, _, _) => HTTOP,
(_, true, _, _) => HTRIGHT,
(_, _, true, _) => HTBOTTOM,
(_, _, _, true) => HTLEFT,
_ => HTTRANSPARENT as u32,
}
}
unsafe fn calculate_resize_direction(helper: HWND, lparam: LPARAM) -> Option<u32> {
match unsafe { calculate_hit(helper, lparam) } {
HTLEFT => Some(WMSZ_LEFT),
HTRIGHT => Some(WMSZ_RIGHT),
HTTOP => Some(WMSZ_TOP),
HTBOTTOM => Some(WMSZ_BOTTOM),
HTTOPLEFT => Some(WMSZ_TOPLEFT),
HTTOPRIGHT => Some(WMSZ_TOPRIGHT),
HTBOTTOMLEFT => Some(WMSZ_BOTTOMLEFT),
HTBOTTOMRIGHT => Some(WMSZ_BOTTOMRIGHT),
_ => None,
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/render/frame_buffer_ref.rs | desktop/src/render/frame_buffer_ref.rs | use thiserror::Error;
pub(crate) struct FrameBufferRef<'a> {
buffer: &'a [u8],
width: usize,
height: usize,
}
impl<'a> FrameBufferRef<'a> {
pub(crate) fn new(buffer: &'a [u8], width: usize, height: usize) -> Result<Self, FrameBufferError> {
let fb = Self { buffer, width, height };
fb.validate_size()?;
Ok(fb)
}
pub(crate) fn buffer(&self) -> &[u8] {
self.buffer
}
pub(crate) fn width(&self) -> usize {
self.width
}
pub(crate) fn height(&self) -> usize {
self.height
}
fn validate_size(&self) -> Result<(), FrameBufferError> {
if self.buffer.len() != self.width * self.height * 4 {
Err(FrameBufferError::InvalidSize {
buffer_size: self.buffer.len(),
expected_size: self.width * self.height * 4,
width: self.width,
height: self.height,
})
} else {
Ok(())
}
}
}
impl<'a> std::fmt::Debug for FrameBufferRef<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameBuffer")
.field("width", &self.width)
.field("height", &self.height)
.field("len", &self.buffer.len())
.finish()
}
}
#[derive(Error, Debug)]
pub(crate) enum FrameBufferError {
#[error("Invalid buffer size {buffer_size}, expected {expected_size} for width {width} multiplied with height {height} multiplied by 4 channels")]
InvalidSize { buffer_size: usize, expected_size: usize, width: usize, height: usize },
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/src/render/state.rs | desktop/src/render/state.rs | use crate::window::Window;
use crate::wrapper::{Color, WgpuContext, WgpuExecutor};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
pub(crate) struct RenderState {
surface: wgpu::Surface<'static>,
context: WgpuContext,
executor: WgpuExecutor,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
transparent_texture: wgpu::Texture,
sampler: wgpu::Sampler,
desired_width: u32,
desired_height: u32,
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<wgpu::Texture>,
overlays_texture: Option<wgpu::Texture>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
overlays_scene: Option<vello::Scene>,
}
impl RenderState {
pub(crate) fn new(window: &Window, context: WgpuContext) -> Self {
let size = window.surface_size();
let surface = window.create_surface(context.instance.clone());
let surface_caps = surface.get_capabilities(&context.adapter);
let surface_format = surface_caps.formats.iter().find(|f| f.is_srgb()).copied().unwrap_or(surface_caps.formats[0]);
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
#[cfg(not(target_os = "macos"))]
present_mode: surface_caps.present_modes[0],
#[cfg(target_os = "macos")]
present_mode: wgpu::PresentMode::Immediate,
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 1,
};
surface.configure(&context.device, &config);
let transparent_texture = context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Transparent Texture"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
// Create shader module
let shader = context.device.create_shader_module(wgpu::include_wgsl!("composite_shader.wgsl"));
// Create sampler
let sampler = context.device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
let texture_bind_group_layout = context.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
label: Some("texture_bind_group_layout"),
});
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout],
push_constant_ranges: &[wgpu::PushConstantRange {
stages: wgpu::ShaderStages::FRAGMENT,
range: 0..size_of::<Constants>() as u32,
}],
});
let render_pipeline = context.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
});
let wgpu_executor = WgpuExecutor::with_context(context.clone()).expect("Failed to create WgpuExecutor");
Self {
surface,
context,
executor: wgpu_executor,
config,
render_pipeline,
transparent_texture,
sampler,
desired_width: size.width,
desired_height: size.height,
viewport_scale: [1.0, 1.0],
viewport_offset: [0.0, 0.0],
viewport_texture: None,
overlays_texture: None,
ui_texture: None,
bind_group: None,
overlays_scene: None,
}
}
pub(crate) fn resize(&mut self, width: u32, height: u32) {
if width == self.desired_width && height == self.desired_height {
return;
}
self.desired_width = width;
self.desired_height = height;
if width > 0 && height > 0 && (self.config.width != width || self.config.height != height) {
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.context.device, &self.config);
}
}
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: wgpu::Texture) {
self.viewport_texture = Some(viewport_texture);
self.update_bindgroup();
}
pub(crate) fn bind_overlays_texture(&mut self, overlays_texture: wgpu::Texture) {
self.overlays_texture = Some(overlays_texture);
self.update_bindgroup();
}
pub(crate) fn bind_ui_texture(&mut self, bind_ui_texture: wgpu::Texture) {
self.ui_texture = Some(bind_ui_texture);
self.update_bindgroup();
}
pub(crate) fn set_viewport_scale(&mut self, scale: [f32; 2]) {
self.viewport_scale = scale;
}
pub(crate) fn set_viewport_offset(&mut self, offset: [f32; 2]) {
self.viewport_offset = offset;
}
pub(crate) fn set_overlays_scene(&mut self, scene: vello::Scene) {
self.overlays_scene = Some(scene);
}
fn render_overlays(&mut self, scene: vello::Scene) {
let Some(viewport_texture) = self.viewport_texture.as_ref() else {
tracing::warn!("No viewport texture bound, cannot render overlays");
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let texture = futures::executor::block_on(self.executor.render_vello_scene_to_texture(&scene, size, &Default::default(), Color::TRANSPARENT));
let Ok(texture) = texture else {
tracing::error!("Error rendering overlays");
return;
};
self.bind_overlays_texture(texture);
}
pub(crate) fn render(&mut self, window: &Window) -> Result<(), RenderError> {
let ui_scale = if let Some(ui_texture) = &self.ui_texture
&& (self.desired_width != ui_texture.width() || self.desired_height != ui_texture.height())
{
Some([self.desired_width as f32 / ui_texture.width() as f32, self.desired_height as f32 / ui_texture.height() as f32])
} else {
None
};
if let Some(scene) = self.overlays_scene.take() {
self.render_overlays(scene);
}
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self.context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder") });
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Graphite Composition Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.01, g: 0.01, b: 0.01, a: 1. }),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_push_constants(
wgpu::ShaderStages::FRAGMENT,
0,
bytemuck::bytes_of(&Constants {
viewport_scale: self.viewport_scale,
viewport_offset: self.viewport_offset,
ui_scale: ui_scale.unwrap_or([1., 1.]),
_pad: [0., 0.],
background_color: [0x22 as f32 / 0xff as f32, 0x22 as f32 / 0xff as f32, 0x22 as f32 / 0xff as f32, 1.], // #222222
}),
);
if let Some(bind_group) = &self.bind_group {
render_pass.set_bind_group(0, bind_group, &[]);
render_pass.draw(0..3, 0..1); // Draw 3 vertices for fullscreen triangle
} else {
tracing::warn!("No bind group available - showing clear color only");
}
}
self.context.queue.submit(std::iter::once(encoder.finish()));
window.pre_present_notify();
output.present();
if ui_scale.is_some() {
return Err(RenderError::OutdatedUITextureError);
}
Ok(())
}
fn update_bindgroup(&mut self) {
let viewport_texture_view = self.viewport_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let overlays_texture_view = self.overlays_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let ui_texture_view = self.ui_texture.as_ref().unwrap_or(&self.transparent_texture).create_view(&wgpu::TextureViewDescriptor::default());
let bind_group = self.context.device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.render_pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&viewport_texture_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&overlays_texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&ui_texture_view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
],
label: Some("texture_bind_group"),
});
self.bind_group = Some(bind_group);
}
}
pub(crate) enum RenderError {
OutdatedUITextureError,
SurfaceError(wgpu::SurfaceError),
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct Constants {
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
ui_scale: [f32; 2],
_pad: [f32; 2],
background_color: [f32; 4],
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/embedded-resources/build.rs | desktop/embedded-resources/build.rs | const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES";
const DEFAULT_RESOURCES_DIR: &str = "../../frontend/dist";
fn main() {
let mut embedded_resources: Option<String> = None;
println!("cargo:rerun-if-env-changed={EMBEDDED_RESOURCES_ENV}");
if let Ok(embedded_resources_env) = std::env::var(EMBEDDED_RESOURCES_ENV)
&& std::path::PathBuf::from(&embedded_resources_env).exists()
{
embedded_resources = Some(embedded_resources_env);
}
if embedded_resources.is_none() {
// Check if the directory `DEFAULT_RESOURCES_DIR` exists and sets the embedded_resources cfg accordingly
// Absolute path of `DEFAULT_RESOURCES_DIR` available via the `EMBEDDED_RESOURCES` environment variable
let crate_dir = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
println!("cargo:rerun-if-changed={DEFAULT_RESOURCES_DIR}");
if let Ok(resources) = crate_dir.join(DEFAULT_RESOURCES_DIR).canonicalize()
&& resources.exists()
{
embedded_resources = Some(resources.to_string_lossy().to_string());
}
}
if let Some(embedded_resources) = embedded_resources {
println!("cargo:rustc-cfg=embedded_resources");
println!("cargo:rustc-env={EMBEDDED_RESOURCES_ENV}={embedded_resources}");
} else {
println!("cargo:warning=Resource directory does not exist. Resources will not be embedded. Did you forget to build the frontend?");
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/embedded-resources/src/lib.rs | desktop/embedded-resources/src/lib.rs | //! This crate provides `EMBEDDED_RESOURCES` that can be included in the desktop application binary.
//! It is intended to be used by the `embedded_resources` feature of the `graphite-desktop` crate.
//! The build script checks if the specified resources directory exists and sets the `embedded_resources` cfg flag accordingly.
//! If the resources directory does not exist, resources will not be embedded and a warning will be reported during compilation.
#[cfg(embedded_resources)]
pub static EMBEDDED_RESOURCES: Option<include_dir::Dir> = Some(include_dir::include_dir!("$EMBEDDED_RESOURCES"));
#[cfg(not(embedded_resources))]
pub static EMBEDDED_RESOURCES: Option<include_dir::Dir> = None;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/messages.rs | desktop/wrapper/src/messages.rs | use graphite_editor::messages::prelude::FrontendMessage;
use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
pub enum DesktopFrontendMessage {
ToWeb(Vec<FrontendMessage>),
OpenLaunchDocuments,
OpenFileDialog {
title: String,
filters: Vec<FileFilter>,
context: OpenFileDialogContext,
},
SaveFileDialog {
title: String,
default_filename: String,
default_folder: Option<PathBuf>,
filters: Vec<FileFilter>,
context: SaveFileDialogContext,
},
WriteFile {
path: PathBuf,
content: Vec<u8>,
},
OpenUrl(String),
UpdateViewportPhysicalBounds {
x: f64,
y: f64,
width: f64,
height: f64,
},
UpdateUIScale {
scale: f64,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
document: Document,
},
PersistenceDeleteDocument {
id: DocumentId,
},
PersistenceUpdateCurrentDocument {
id: DocumentId,
},
PersistenceLoadCurrentDocument,
PersistenceLoadRemainingDocuments,
PersistenceUpdateDocumentsList {
ids: Vec<DocumentId>,
},
PersistenceWritePreferences {
preferences: Preferences,
},
PersistenceLoadPreferences,
UpdateMenu {
entries: Vec<MenuItem>,
},
ClipboardRead,
ClipboardWrite {
content: String,
},
WindowClose,
WindowMinimize,
WindowMaximize,
WindowDrag,
WindowHide,
WindowHideOthers,
WindowShowAll,
}
pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Input(InputMessage),
OpenFileDialogResult {
path: PathBuf,
content: Vec<u8>,
context: OpenFileDialogContext,
},
SaveFileDialogResult {
path: PathBuf,
context: SaveFileDialogContext,
},
OpenDocument {
path: PathBuf,
content: Vec<u8>,
},
OpenFile {
path: PathBuf,
content: Vec<u8>,
},
ImportFile {
path: PathBuf,
content: Vec<u8>,
},
ImportSvg {
path: PathBuf,
content: Vec<u8>,
},
ImportImage {
path: PathBuf,
content: Vec<u8>,
},
PollNodeGraphEvaluation,
UpdatePlatform(Platform),
UpdateMaximized {
maximized: bool,
},
UpdateFullscreen {
fullscreen: bool,
},
LoadDocument {
id: DocumentId,
document: Document,
to_front: bool,
select_after_open: bool,
},
SelectDocument {
id: DocumentId,
},
LoadPreferences {
preferences: Option<Preferences>,
},
MenuEvent {
id: String,
},
ClipboardReadResult {
content: Option<String>,
},
}
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct Document {
pub content: String,
pub name: String,
pub path: Option<PathBuf>,
pub is_saved: bool,
}
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
pub enum OpenFileDialogContext {
Document,
Import,
}
pub enum SaveFileDialogContext {
Document { document_id: DocumentId, content: Vec<u8> },
File { content: Vec<u8> },
}
pub enum Platform {
Windows,
Mac,
Linux,
}
pub enum MenuItem {
Action {
id: String,
text: String,
enabled: bool,
shortcut: Option<Shortcut>,
},
Checkbox {
id: String,
text: String,
enabled: bool,
shortcut: Option<Shortcut>,
checked: bool,
},
SubMenu {
id: String,
text: String,
enabled: bool,
items: Vec<MenuItem>,
},
Separator,
}
pub use keyboard_types::{Code as KeyCode, Modifiers};
pub struct Shortcut {
pub key: KeyCode,
pub modifiers: Modifiers,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/lib.rs | desktop/wrapper/src/lib.rs | use graph_craft::wasm_application_io::WasmApplicationIo;
use graphite_editor::application::Editor;
use graphite_editor::messages::prelude::{FrontendMessage, Message};
// TODO: Remove usage of this reexport in desktop create and remove this line
pub use graphene_std::Color;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
pub use wgpu_executor::WgpuExecutor;
pub use wgpu_executor::WgpuFeatures;
pub mod messages;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
mod message_dispatcher;
use message_dispatcher::DesktopWrapperMessageDispatcher;
mod handle_desktop_wrapper_message;
mod intercept_editor_message;
mod intercept_frontend_message;
pub(crate) mod utils;
pub struct DesktopWrapper {
editor: Editor,
}
impl DesktopWrapper {
pub fn new() -> Self {
Self { editor: Editor::new() }
}
pub fn init(&self, wgpu_context: WgpuContext) {
let application_io = WasmApplicationIo::new_with_context(wgpu_context);
futures::executor::block_on(graphite_editor::node_graph_executor::replace_application_io(application_io));
}
pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec<DesktopFrontendMessage> {
let mut executor = DesktopWrapperMessageDispatcher::new(&mut self.editor);
executor.queue_desktop_wrapper_message(message);
executor.execute()
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(|t| t.texture)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
}
impl Default for DesktopWrapper {
fn default() -> Self {
Self::new()
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<wgpu::Texture>),
NotRun,
}
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
if let Ok(string) = std::str::from_utf8(data) {
if let Ok(message) = ron::de::from_str::<Message>(string) {
Some(DesktopWrapperMessage::FromWeb(message.into()))
} else {
None
}
} else {
None
}
}
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
if let Ok(serialized) = ron::ser::to_string(&messages) {
Some(serialized.into_bytes())
} else {
None
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/intercept_editor_message.rs | desktop/wrapper/src/intercept_editor_message.rs | use super::DesktopWrapperMessageDispatcher;
use super::messages::EditorMessage;
pub(super) fn intercept_editor_message(_dispatcher: &mut DesktopWrapperMessageDispatcher, message: EditorMessage) -> Option<EditorMessage> {
// TODO: remove if it turns out to be unnecessary
Some(message)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/handle_desktop_wrapper_message.rs | desktop/wrapper/src/handle_desktop_wrapper_message.rs | use graphene_std::Color;
use graphene_std::raster::Image;
use graphite_editor::messages::app_window::app_window_message_handler::AppWindowPlatform;
use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
use graphite_editor::messages::prelude::*;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, Platform, SaveFileDialogContext};
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message {
DesktopWrapperMessage::FromWeb(message) => {
dispatcher.queue_editor_message(*message);
}
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
DesktopWrapperMessage::OpenFileDialogResult { path, content, context } => match context {
OpenFileDialogContext::Document => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenDocument { path, content });
}
OpenFileDialogContext::Import => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
}
},
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
SaveFileDialogContext::Document { document_id, content } => {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
dispatcher.queue_editor_message(EditorMessage::Portfolio(PortfolioMessage::DocumentPassMessage {
document_id,
message: DocumentMessage::SavedDocument { path: Some(path) },
}));
}
SaveFileDialogContext::File { content } => {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
}
},
DesktopWrapperMessage::OpenFile { path, content } => {
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
"graphite" => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenDocument { path, content });
}
_ => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
}
}
}
DesktopWrapperMessage::OpenDocument { path, content } => {
let Ok(content) = String::from_utf8(content) else {
tracing::warn!("Document file is invalid: {}", path.display());
return;
};
let message = PortfolioMessage::OpenDocumentFile {
document_name: None,
document_path: Some(path),
document_serialized_content: content,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportFile { path, content } => {
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
match extension.as_str() {
"svg" => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportSvg { path, content });
}
_ => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportImage { path, content });
}
}
}
DesktopWrapperMessage::ImportSvg { path, content } => {
let Ok(content) = String::from_utf8(content) else {
tracing::warn!("Svg file is invalid: {}", path.display());
return;
};
let message = PortfolioMessage::PasteSvg {
name: path.file_stem().map(|s| s.to_string_lossy().to_string()),
svg: content,
mouse: None,
parent_and_insert_index: None,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportImage { path, content } => {
let name = path.file_stem().and_then(|s| s.to_str()).map(|s| s.to_string());
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or_default().to_lowercase();
let Some(image_format) = image::ImageFormat::from_extension(&extension) else {
tracing::warn!("Unsupported file type: {}", path.display());
return;
};
let reader = image::ImageReader::with_format(std::io::Cursor::new(content), image_format);
let Ok(image) = reader.decode() else {
tracing::error!("Failed to decode image: {}", path.display());
return;
};
let width = image.width();
let height = image.height();
// TODO: Handle Image formats with more than 8 bits per channel
let image_data = image.to_rgba8();
let image = Image::<Color>::from_image_data(image_data.as_raw(), width, height);
let message = PortfolioMessage::PasteImage {
name,
image,
mouse: None,
parent_and_insert_index: None,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
DesktopWrapperMessage::UpdatePlatform(platform) => {
let platform = match platform {
Platform::Windows => AppWindowPlatform::Windows,
Platform::Mac => AppWindowPlatform::Mac,
Platform::Linux => AppWindowPlatform::Linux,
};
let message = AppWindowMessage::UpdatePlatform { platform };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::UpdateMaximized { maximized } => {
let message = FrontendMessage::UpdateMaximized { maximized };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::UpdateFullscreen { fullscreen } => {
let message = FrontendMessage::UpdateFullscreen { fullscreen };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadDocument {
id,
document,
to_front,
select_after_open,
} => {
let message = PortfolioMessage::OpenDocumentFileWithId {
document_id: id,
document_name: Some(document.name),
document_path: document.path,
document_serialized_content: document.content,
document_is_auto_saved: true,
document_is_saved: document.is_saved,
to_front,
select_after_open,
};
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::SelectDocument { id } => {
let message = PortfolioMessage::SelectDocument { document_id: id };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::LoadPreferences { preferences } => {
let message = PreferencesMessage::Load { preferences };
dispatcher.queue_editor_message(message);
}
#[cfg(target_os = "macos")]
DesktopWrapperMessage::MenuEvent { id } => {
if let Some(message) = crate::utils::menu::parse_item_path(id) {
dispatcher.queue_editor_message(message);
} else {
tracing::error!("Received a malformed MenuEvent id");
}
}
#[cfg(not(target_os = "macos"))]
DesktopWrapperMessage::MenuEvent { id: _ } => {}
DesktopWrapperMessage::ClipboardReadResult { content } => {
if let Some(content) = content {
let message = ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(content),
};
dispatcher.queue_editor_message(message);
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/utils.rs | desktop/wrapper/src/utils.rs | #[cfg(target_os = "macos")]
pub(crate) mod menu {
use base64::engine::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
use graphite_editor::messages::layout::LayoutMessage;
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId};
use crate::messages::{EditorMessage, KeyCode, MenuItem, Modifiers, Shortcut};
pub(crate) fn convert_menu_bar_layout_to_menu_items(Layout(layout): &Layout) -> Vec<MenuItem> {
let layout_group = match layout.as_slice() {
[layout_group] => layout_group,
_ => panic!("Menu bar layout is supposed to have exactly one layout group"),
};
let LayoutGroup::Row { widgets } = layout_group else {
panic!("Menu bar layout group is supposed to be a row");
};
widgets
.into_iter()
.map(|widget| {
let text_button = match widget.widget.as_ref() {
Widget::TextButton(text_button) => text_button,
_ => panic!("Menu bar layout top-level widgets are supposed to be text buttons"),
};
MenuItem::SubMenu {
id: widget.widget_id.to_string(),
text: text_button.label.clone(),
enabled: !text_button.disabled,
items: convert_menu_bar_entry_children_to_menu_items(&text_button.menu_list_children, widget.widget_id.0, Vec::new()),
}
})
.collect::<Vec<MenuItem>>()
}
pub(crate) fn parse_item_path(id: String) -> Option<EditorMessage> {
let mut id_parts = id.split(':');
let widget_id = id_parts.next()?.parse::<u64>().ok()?;
let value = id_parts
.map(|part| {
let bytes = BASE64.decode(part).ok()?;
String::from_utf8(bytes).ok()
})
.collect::<Option<Vec<String>>>()?;
let value = serde_json::to_value(value).ok()?;
Some(
LayoutMessage::WidgetValueUpdate {
layout_target: LayoutTarget::MenuBar,
widget_id: WidgetId(widget_id),
value,
}
.into(),
)
}
fn item_path_to_string(widget_id: u64, path: Vec<String>) -> String {
let path = path.into_iter().map(|element| BASE64.encode(element)).collect::<Vec<_>>().join(":");
format!("{widget_id}:{path}")
}
fn convert_menu_bar_layout_to_menu_item(entry: &MenuListEntry, root_widget_id: u64, mut path: Vec<String>) -> MenuItem {
let MenuListEntry {
value,
label,
icon,
disabled,
tooltip_shortcut,
children,
..
}: &MenuListEntry = entry;
path.push(value.clone());
let id = item_path_to_string(root_widget_id, path.clone());
let text = label.clone();
let enabled = !*disabled;
if !children.is_empty() {
let items = convert_menu_bar_entry_children_to_menu_items(&children, root_widget_id, path.clone());
return MenuItem::SubMenu { id, text, enabled, items };
}
let shortcut = match tooltip_shortcut {
Some(ActionShortcut::Shortcut(LabeledShortcut(shortcut))) => convert_labeled_keys_to_shortcut(shortcut),
_ => None,
};
match icon.as_str() {
"CheckboxChecked" => {
return MenuItem::Checkbox {
id,
text,
enabled,
shortcut,
checked: true,
};
}
"CheckboxUnchecked" => {
return MenuItem::Checkbox {
id,
text,
enabled,
shortcut,
checked: false,
};
}
_ => {}
}
MenuItem::Action { id, text, shortcut, enabled }
}
fn convert_menu_bar_entry_children_to_menu_items(children: &[Vec<MenuListEntry>], root_widget_id: u64, path: Vec<String>) -> Vec<MenuItem> {
let mut items = Vec::new();
for (i, section) in children.iter().enumerate() {
for entry in section.iter() {
items.push(convert_menu_bar_layout_to_menu_item(entry, root_widget_id, path.clone()));
}
if i != children.len() - 1 {
items.push(MenuItem::Separator);
}
}
items
}
fn convert_labeled_keys_to_shortcut(labeled_keys: &Vec<LabeledKeyOrMouseMotion>) -> Option<Shortcut> {
let mut key: Option<KeyCode> = None;
let mut modifiers = Modifiers::default();
for labeled_key in labeled_keys {
let LabeledKeyOrMouseMotion::Key(labeled_key) = labeled_key else {
// Return None for shortcuts that include mouse motion because we can't show them in native menu
return None;
};
match labeled_key.key() {
Key::Shift => modifiers |= Modifiers::SHIFT,
Key::Control => modifiers |= Modifiers::CONTROL,
Key::Alt => modifiers |= Modifiers::ALT,
Key::Meta => modifiers |= Modifiers::META,
Key::Command => modifiers |= Modifiers::ALT,
Key::Accel => modifiers |= Modifiers::META,
Key::Digit0 => key = Some(KeyCode::Digit0),
Key::Digit1 => key = Some(KeyCode::Digit1),
Key::Digit2 => key = Some(KeyCode::Digit2),
Key::Digit3 => key = Some(KeyCode::Digit3),
Key::Digit4 => key = Some(KeyCode::Digit4),
Key::Digit5 => key = Some(KeyCode::Digit5),
Key::Digit6 => key = Some(KeyCode::Digit6),
Key::Digit7 => key = Some(KeyCode::Digit7),
Key::Digit8 => key = Some(KeyCode::Digit8),
Key::Digit9 => key = Some(KeyCode::Digit9),
Key::KeyA => key = Some(KeyCode::KeyA),
Key::KeyB => key = Some(KeyCode::KeyB),
Key::KeyC => key = Some(KeyCode::KeyC),
Key::KeyD => key = Some(KeyCode::KeyD),
Key::KeyE => key = Some(KeyCode::KeyE),
Key::KeyF => key = Some(KeyCode::KeyF),
Key::KeyG => key = Some(KeyCode::KeyG),
Key::KeyH => key = Some(KeyCode::KeyH),
Key::KeyI => key = Some(KeyCode::KeyI),
Key::KeyJ => key = Some(KeyCode::KeyJ),
Key::KeyK => key = Some(KeyCode::KeyK),
Key::KeyL => key = Some(KeyCode::KeyL),
Key::KeyM => key = Some(KeyCode::KeyM),
Key::KeyN => key = Some(KeyCode::KeyN),
Key::KeyO => key = Some(KeyCode::KeyO),
Key::KeyP => key = Some(KeyCode::KeyP),
Key::KeyQ => key = Some(KeyCode::KeyQ),
Key::KeyR => key = Some(KeyCode::KeyR),
Key::KeyS => key = Some(KeyCode::KeyS),
Key::KeyT => key = Some(KeyCode::KeyT),
Key::KeyU => key = Some(KeyCode::KeyU),
Key::KeyV => key = Some(KeyCode::KeyV),
Key::KeyW => key = Some(KeyCode::KeyW),
Key::KeyX => key = Some(KeyCode::KeyX),
Key::KeyY => key = Some(KeyCode::KeyY),
Key::KeyZ => key = Some(KeyCode::KeyZ),
Key::Backquote => key = Some(KeyCode::Backquote),
Key::Backslash => key = Some(KeyCode::Backslash),
Key::BracketLeft => key = Some(KeyCode::BracketLeft),
Key::BracketRight => key = Some(KeyCode::BracketRight),
Key::Comma => key = Some(KeyCode::Comma),
Key::Equal => key = Some(KeyCode::Equal),
Key::Minus => key = Some(KeyCode::Minus),
Key::Period => key = Some(KeyCode::Period),
Key::Quote => key = Some(KeyCode::Quote),
Key::Semicolon => key = Some(KeyCode::Semicolon),
Key::Slash => key = Some(KeyCode::Slash),
Key::Backspace => key = Some(KeyCode::Backspace),
Key::CapsLock => key = Some(KeyCode::CapsLock),
Key::ContextMenu => key = Some(KeyCode::ContextMenu),
Key::Enter => key = Some(KeyCode::Enter),
Key::Space => key = Some(KeyCode::Space),
Key::Tab => key = Some(KeyCode::Tab),
Key::Delete => key = Some(KeyCode::Delete),
Key::End => key = Some(KeyCode::End),
Key::Help => key = Some(KeyCode::Help),
Key::Home => key = Some(KeyCode::Home),
Key::Insert => key = Some(KeyCode::Insert),
Key::PageDown => key = Some(KeyCode::PageDown),
Key::PageUp => key = Some(KeyCode::PageUp),
Key::ArrowDown => key = Some(KeyCode::ArrowDown),
Key::ArrowLeft => key = Some(KeyCode::ArrowLeft),
Key::ArrowRight => key = Some(KeyCode::ArrowRight),
Key::ArrowUp => key = Some(KeyCode::ArrowUp),
Key::NumLock => key = Some(KeyCode::NumLock),
Key::NumpadAdd => key = Some(KeyCode::NumpadAdd),
Key::NumpadHash => key = Some(KeyCode::NumpadHash),
Key::NumpadMultiply => key = Some(KeyCode::NumpadMultiply),
Key::NumpadParenLeft => key = Some(KeyCode::NumpadParenLeft),
Key::NumpadParenRight => key = Some(KeyCode::NumpadParenRight),
Key::Escape => key = Some(KeyCode::Escape),
Key::F1 => key = Some(KeyCode::F1),
Key::F2 => key = Some(KeyCode::F2),
Key::F3 => key = Some(KeyCode::F3),
Key::F4 => key = Some(KeyCode::F4),
Key::F5 => key = Some(KeyCode::F5),
Key::F6 => key = Some(KeyCode::F6),
Key::F7 => key = Some(KeyCode::F7),
Key::F8 => key = Some(KeyCode::F8),
Key::F9 => key = Some(KeyCode::F9),
Key::F10 => key = Some(KeyCode::F10),
Key::F11 => key = Some(KeyCode::F11),
Key::F12 => key = Some(KeyCode::F12),
Key::F13 => key = Some(KeyCode::F13),
Key::F14 => key = Some(KeyCode::F14),
Key::F15 => key = Some(KeyCode::F15),
Key::F16 => key = Some(KeyCode::F16),
Key::F17 => key = Some(KeyCode::F17),
Key::F18 => key = Some(KeyCode::F18),
Key::F19 => key = Some(KeyCode::F19),
Key::F20 => key = Some(KeyCode::F20),
Key::F21 => key = Some(KeyCode::F21),
Key::F22 => key = Some(KeyCode::F22),
Key::F23 => key = Some(KeyCode::F23),
Key::F24 => key = Some(KeyCode::F24),
Key::Fn => key = Some(KeyCode::Fn),
Key::FnLock => key = Some(KeyCode::FnLock),
Key::PrintScreen => key = Some(KeyCode::PrintScreen),
Key::ScrollLock => key = Some(KeyCode::ScrollLock),
Key::Pause => key = Some(KeyCode::Pause),
Key::Unidentified => key = Some(KeyCode::Unidentified),
Key::FakeKeyPlus => key = Some(KeyCode::Equal),
_ => key = None,
}
}
key.map(|key| Shortcut { key, modifiers })
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/message_dispatcher.rs | desktop/wrapper/src/message_dispatcher.rs | use graphite_editor::application::Editor;
use std::collections::VecDeque;
use super::handle_desktop_wrapper_message::handle_desktop_wrapper_message;
use super::intercept_editor_message::intercept_editor_message;
use super::intercept_frontend_message::intercept_frontend_message;
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage};
pub(crate) struct DesktopWrapperMessageDispatcher<'a> {
editor: &'a mut Editor,
desktop_wrapper_message_queue: VecDeque<DesktopWrapperMessage>,
editor_message_queue: Vec<EditorMessage>,
responses: Vec<DesktopFrontendMessage>,
}
impl<'a> DesktopWrapperMessageDispatcher<'a> {
pub(crate) fn new(editor: &'a mut Editor) -> Self {
Self {
editor,
desktop_wrapper_message_queue: VecDeque::new(),
editor_message_queue: Vec::new(),
responses: Vec::new(),
}
}
pub(crate) fn execute(mut self) -> Vec<DesktopFrontendMessage> {
self.process_queue();
self.responses
}
pub(crate) fn queue_desktop_wrapper_message(&mut self, message: DesktopWrapperMessage) {
self.desktop_wrapper_message_queue.push_back(message);
}
pub(super) fn queue_editor_message<T: Into<EditorMessage>>(&mut self, message: T) {
if let Some(message) = intercept_editor_message(self, message.into()) {
self.editor_message_queue.push(message);
}
}
pub(super) fn respond(&mut self, response: DesktopFrontendMessage) {
self.responses.push(response);
}
pub(super) fn poll_node_graph_evaluation(&mut self) {
let mut responses = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
if e != "No active document" {
tracing::error!("Error poling node graph: {}", e);
}
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
}
}
fn process_queue(&mut self) {
let mut frontend_messages = Vec::new();
while !self.desktop_wrapper_message_queue.is_empty() || !self.editor_message_queue.is_empty() {
while let Some(message) = self.desktop_wrapper_message_queue.pop_front() {
handle_desktop_wrapper_message(self, message);
}
let current_frontend_messages = self
.editor
.handle_message(EditorMessage::Batched {
messages: std::mem::take(&mut self.editor_message_queue).into_boxed_slice(),
})
.into_iter()
.filter_map(|m| intercept_frontend_message(self, m));
frontend_messages.extend(current_frontend_messages);
}
if !frontend_messages.is_empty() {
self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/wrapper/src/intercept_frontend_message.rs | desktop/wrapper/src/intercept_frontend_message.rs | use std::path::PathBuf;
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, Document, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
FrontendMessage::RenderOverlays { context } => {
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
}
FrontendMessage::TriggerOpenDocument => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Open Document".to_string(),
filters: vec![FileFilter {
name: "Graphite".to_string(),
extensions: vec!["graphite".to_string()],
}],
context: OpenFileDialogContext::Document,
});
}
FrontendMessage::TriggerImport => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![
FileFilter {
name: "Svg".to_string(),
extensions: vec!["svg".to_string()],
},
FileFilter {
name: "Image".to_string(),
extensions: vec!["png".to_string(), "jpg".to_string(), "jpeg".to_string(), "bmp".to_string()],
},
],
context: OpenFileDialogContext::Import,
});
}
FrontendMessage::TriggerSaveDocument { document_id, name, path, content } => {
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: path.and_then(|p| p.parent().map(PathBuf::from)),
filters: vec![FileFilter {
name: "Graphite".to_string(),
extensions: vec!["graphite".to_string()],
}],
context: SaveFileDialogContext::Document { document_id, content },
});
}
}
FrontendMessage::TriggerSaveFile { name, content } => {
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: None,
filters: Vec::new(),
context: SaveFileDialogContext::File { content },
});
}
FrontendMessage::TriggerVisitLink { url } => {
dispatcher.respond(DesktopFrontendMessage::OpenUrl(url));
}
FrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
dispatcher.respond(DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height });
}
FrontendMessage::UpdateUIScale { scale } => {
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
return Some(FrontendMessage::UpdateUIScale { scale });
}
FrontendMessage::TriggerPersistenceWriteDocument { document_id, document, details } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWriteDocument {
id: document_id,
document: Document {
name: details.name,
path: details.path,
content: document,
is_saved: details.is_saved,
},
});
}
FrontendMessage::TriggerPersistenceRemoveDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceDeleteDocument { id: document_id });
}
FrontendMessage::UpdateActiveDocument { document_id } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateCurrentDocument { id: document_id });
// Forward this to update the UI
return Some(FrontendMessage::UpdateActiveDocument { document_id });
}
FrontendMessage::UpdateOpenDocumentsList { open_documents } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdateDocumentsList {
ids: open_documents.iter().map(|document| document.id).collect(),
});
// Forward this to update the UI
return Some(FrontendMessage::UpdateOpenDocumentsList { open_documents });
}
FrontendMessage::TriggerLoadFirstAutoSaveDocument => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadCurrentDocument);
}
FrontendMessage::TriggerLoadRestAutoSaveDocuments => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadRemainingDocuments);
}
FrontendMessage::TriggerOpenLaunchDocuments => {
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
}
FrontendMessage::TriggerSavePreferences { preferences } => {
dispatcher.respond(DesktopFrontendMessage::PersistenceWritePreferences { preferences });
}
FrontendMessage::TriggerLoadPreferences => {
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadPreferences);
}
#[cfg(target_os = "macos")]
FrontendMessage::UpdateMenuBarLayout { diff } => {
use graphite_editor::messages::tool::tool_messages::tool_prelude::{DiffUpdate, WidgetDiff};
match diff.as_slice() {
[
WidgetDiff {
widget_path,
new_value: DiffUpdate::Layout(layout),
},
] if widget_path.is_empty() => {
let entries = crate::utils::menu::convert_menu_bar_layout_to_menu_items(layout);
dispatcher.respond(DesktopFrontendMessage::UpdateMenu { entries });
}
_ => {}
}
}
FrontendMessage::TriggerClipboardRead => {
dispatcher.respond(DesktopFrontendMessage::ClipboardRead);
}
FrontendMessage::TriggerClipboardWrite { content } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
}
FrontendMessage::WindowClose => {
dispatcher.respond(DesktopFrontendMessage::WindowClose);
}
FrontendMessage::WindowMinimize => {
dispatcher.respond(DesktopFrontendMessage::WindowMinimize);
}
FrontendMessage::WindowMaximize => {
dispatcher.respond(DesktopFrontendMessage::WindowMaximize);
}
FrontendMessage::WindowDrag => {
dispatcher.respond(DesktopFrontendMessage::WindowDrag);
}
FrontendMessage::WindowHide => {
dispatcher.respond(DesktopFrontendMessage::WindowHide);
}
FrontendMessage::WindowHideOthers => {
dispatcher.respond(DesktopFrontendMessage::WindowHideOthers);
}
FrontendMessage::WindowShowAll => {
dispatcher.respond(DesktopFrontendMessage::WindowShowAll);
}
m => return Some(m),
}
None
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/build.rs | desktop/bundle/build.rs | fn main() {
println!("cargo:rerun-if-env-changed=CARGO_PROFILE");
println!("cargo:rerun-if-env-changed=PROFILE");
let profile = std::env::var("CARGO_PROFILE").or_else(|_| std::env::var("PROFILE")).unwrap();
println!("cargo:rustc-env=CARGO_PROFILE={profile}");
println!("cargo:rerun-if-env-changed=DEP_CEF_DLL_WRAPPER_CEF_DIR");
let cef_dir = std::env::var("DEP_CEF_DLL_WRAPPER_CEF_DIR").unwrap();
println!("cargo:rustc-env=CEF_PATH={cef_dir}");
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/src/win.rs | desktop/bundle/src/win.rs | use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use crate::common::*;
const EXECUTABLE: &str = "Graphite.exe";
pub fn main() -> Result<(), Box<dyn Error>> {
let app_bin = build_bin("graphite-desktop-platform-win", None)?;
let executable = bundle(&profile_path(), &app_bin);
// TODO: Consider adding more useful cli
if std::env::args().any(|a| a == "open") {
let executable_path = executable.to_string_lossy();
run_command(&executable_path, &[]).expect("failed to open app")
}
Ok(())
}
fn bundle(out_dir: &Path, app_bin: &Path) -> PathBuf {
let app_dir = out_dir.join(APP_NAME);
clean_dir(&app_dir);
copy_dir(&cef_path(), &app_dir);
let bin_path = app_dir.join(EXECUTABLE);
fs::copy(app_bin, &bin_path).unwrap();
bin_path
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/src/linux.rs | desktop/bundle/src/linux.rs | use std::error::Error;
use crate::common::*;
pub fn main() -> Result<(), Box<dyn Error>> {
let app_bin = build_bin("graphite-desktop-platform-linux", None)?;
// TODO: Implement bundling for linux
// TODO: Consider adding more useful cli
if std::env::args().any(|a| a == "open") {
run_command(&app_bin.to_string_lossy(), &[]).expect("failed to open app");
} else {
println!("Binary built and placed at {}", app_bin.to_string_lossy());
eprintln!("Bundling for Linux is not yet implemented.");
eprintln!("You can still start the app with the `open` subcommand. `cargo run -p graphite-desktop-bundle -- open`");
std::process::exit(1);
}
Ok(())
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/src/mac.rs | desktop/bundle/src/mac.rs | use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use crate::common::*;
const APP_ID: &str = "art.graphite.Graphite";
const ICONS_FILE_NAME: &str = "graphite.icns";
const EXEC_PATH: &str = "Contents/MacOS";
const FRAMEWORKS_PATH: &str = "Contents/Frameworks";
const RESOURCES_PATH: &str = "Contents/Resources";
const CEF_FRAMEWORK: &str = "Chromium Embedded Framework.framework";
pub fn main() -> Result<(), Box<dyn Error>> {
let app_bin = build_bin("graphite-desktop-platform-mac", None)?;
let helper_bin = build_bin("graphite-desktop-platform-mac", Some("helper"))?;
let profile_path = profile_path();
let app_dir = bundle(&profile_path, &app_bin, &helper_bin);
// TODO: Consider adding more useful cli
if std::env::args().any(|a| a == "open") {
let executable_path = app_dir.join(EXEC_PATH).join(APP_NAME);
run_command(&executable_path.to_string_lossy(), &[]).expect("failed to open app");
}
Ok(())
}
fn bundle(out_dir: &Path, app_bin: &Path, helper_bin: &Path) -> PathBuf {
let app_dir = out_dir.join(APP_NAME).with_extension("app");
clean_dir(&app_dir);
create_app(&app_dir, APP_ID, APP_NAME, app_bin, false);
for helper_type in [None, Some("GPU"), Some("Renderer")] {
let helper_id_suffix = helper_type.map(|t| format!(".{t}")).unwrap_or_default();
let helper_id = format!("{APP_ID}.helper{helper_id_suffix}");
let helper_name_suffix = helper_type.map(|t| format!(" ({t})")).unwrap_or_default();
let helper_name = format!("{APP_NAME} Helper{helper_name_suffix}");
let helper_app_dir = app_dir.join(FRAMEWORKS_PATH).join(&helper_name).with_extension("app");
create_app(&helper_app_dir, &helper_id, &helper_name, helper_bin, true);
}
copy_dir(&cef_path().join(CEF_FRAMEWORK), &app_dir.join(FRAMEWORKS_PATH).join(CEF_FRAMEWORK));
let resource_dir = app_dir.join(RESOURCES_PATH);
fs::create_dir_all(&resource_dir).expect("failed to create app resource dir");
let icon_file = workspace_path().join("branding/app-icons").join(ICONS_FILE_NAME);
fs::copy(icon_file, resource_dir.join(ICONS_FILE_NAME)).expect("failed to copy icon file");
app_dir
}
fn create_app(app_dir: &Path, id: &str, name: &str, bin: &Path, is_helper: bool) {
fs::create_dir_all(app_dir.join(EXEC_PATH)).unwrap();
let app_contents_dir: &Path = &app_dir.join("Contents");
create_info_plist(app_contents_dir, id, name, is_helper).unwrap();
fs::copy(bin, app_dir.join(EXEC_PATH).join(name)).unwrap();
}
fn create_info_plist(dir: &Path, id: &str, exec_name: &str, is_helper: bool) -> Result<(), Box<dyn std::error::Error>> {
let info = InfoPlist {
cf_bundle_name: exec_name.to_string(),
cf_bundle_identifier: id.to_string(),
cf_bundle_display_name: exec_name.to_string(),
cf_bundle_executable: exec_name.to_string(),
cf_bundle_icon_file: ICONS_FILE_NAME.to_string(),
cf_bundle_info_dictionary_version: "6.0".to_string(),
cf_bundle_package_type: "APPL".to_string(),
cf_bundle_signature: "????".to_string(),
cf_bundle_version: "0.0.0".to_string(),
cf_bundle_short_version_string: "0.0".to_string(),
cf_bundle_development_region: "en".to_string(),
ls_environment: [("MallocNanoZone".to_string(), "0".to_string())].iter().cloned().collect(),
ls_file_quarantine_enabled: true,
ls_minimum_system_version: "11.0".to_string(),
ls_ui_element: if is_helper { Some("1".to_string()) } else { None },
ns_supports_automatic_graphics_switching: true,
};
let plist_file = dir.join("Info.plist");
plist::to_file_xml(plist_file, &info)?;
Ok(())
}
#[derive(serde::Serialize)]
struct InfoPlist {
#[serde(rename = "CFBundleName")]
cf_bundle_name: String,
#[serde(rename = "CFBundleIdentifier")]
cf_bundle_identifier: String,
#[serde(rename = "CFBundleDisplayName")]
cf_bundle_display_name: String,
#[serde(rename = "CFBundleExecutable")]
cf_bundle_executable: String,
#[serde(rename = "CFBundleIconFile")]
cf_bundle_icon_file: String,
#[serde(rename = "CFBundleInfoDictionaryVersion")]
cf_bundle_info_dictionary_version: String,
#[serde(rename = "CFBundlePackageType")]
cf_bundle_package_type: String,
#[serde(rename = "CFBundleSignature")]
cf_bundle_signature: String,
#[serde(rename = "CFBundleVersion")]
cf_bundle_version: String,
#[serde(rename = "CFBundleShortVersionString")]
cf_bundle_short_version_string: String,
#[serde(rename = "CFBundleDevelopmentRegion")]
cf_bundle_development_region: String,
#[serde(rename = "LSEnvironment")]
ls_environment: HashMap<String, String>,
#[serde(rename = "LSFileQuarantineEnabled")]
ls_file_quarantine_enabled: bool,
#[serde(rename = "LSMinimumSystemVersion")]
ls_minimum_system_version: String,
#[serde(rename = "LSUIElement")]
ls_ui_element: Option<String>,
#[serde(rename = "NSSupportsAutomaticGraphicsSwitching")]
ns_supports_automatic_graphics_switching: bool,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/src/main.rs | desktop/bundle/src/main.rs | mod common;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "windows")]
mod win;
fn main() {
#[cfg(target_os = "linux")]
linux::main().unwrap();
#[cfg(target_os = "macos")]
mac::main().unwrap();
#[cfg(target_os = "windows")]
win::main().unwrap();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/bundle/src/common.rs | desktop/bundle/src/common.rs | use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub(crate) const APP_NAME: &str = "Graphite";
pub(crate) const APP_BIN: &str = "graphite";
pub(crate) fn workspace_path() -> PathBuf {
PathBuf::from(env!("CARGO_WORKSPACE_DIR"))
}
fn profile_name() -> &'static str {
let mut profile = env!("CARGO_PROFILE");
if profile == "debug" {
profile = "dev";
}
profile
}
pub(crate) fn profile_path() -> PathBuf {
workspace_path().join(format!("target/{}", env!("CARGO_PROFILE")))
}
pub(crate) fn cef_path() -> PathBuf {
PathBuf::from(env!("CEF_PATH"))
}
pub(crate) fn build_bin(package: &str, bin: Option<&str>) -> Result<PathBuf, Box<dyn Error>> {
let profile = &profile_name();
let mut args = vec!["build", "--package", package, "--profile", profile];
if let Some(bin) = bin {
args.push("--bin");
args.push(bin);
}
run_command("cargo", &args)?;
let profile_path = profile_path();
let mut bin_path = if let Some(bin) = bin { profile_path.join(bin) } else { profile_path.join(APP_BIN) };
if cfg!(target_os = "windows") {
bin_path.set_extension("exe");
}
Ok(bin_path)
}
pub(crate) fn run_command(program: &str, args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
let status = Command::new(program).args(args).stdout(Stdio::inherit()).stderr(Stdio::inherit()).status()?;
if !status.success() {
std::process::exit(1);
}
Ok(())
}
pub(crate) fn clean_dir(dir: &Path) {
if dir.exists() {
fs::remove_dir_all(dir).unwrap();
}
fs::create_dir_all(dir).unwrap();
}
pub(crate) fn copy_dir(src: &Path, dst: &Path) {
fs::create_dir_all(dst).unwrap();
for entry in fs::read_dir(src).unwrap() {
let entry = entry.unwrap();
let dst_path = dst.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_dir(&entry.path(), &dst_path);
} else {
fs::copy(entry.path(), &dst_path).unwrap();
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/platform/mac/src/helper.rs | desktop/platform/mac/src/helper.rs | fn main() {
graphite_desktop::start_helper();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/platform/mac/src/main.rs | desktop/platform/mac/src/main.rs | fn main() {
graphite_desktop::start();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/platform/linux/src/main.rs | desktop/platform/linux/src/main.rs | fn main() {
graphite_desktop::start();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/platform/win/build.rs | desktop/platform/win/build.rs | fn main() {
#[cfg(target_os = "windows")]
{
let mut res = winres::WindowsResource::new();
res.set_icon("../../../branding/app-icons/graphite.ico");
res.set_language(0x0409); // English (US)
// TODO: Replace with actual version
res.set_version_info(winres::VersionInfo::FILEVERSION, {
const MAJOR: u64 = 0;
const MINOR: u64 = 0;
const PATCH: u64 = 0;
const RELEASE: u64 = 0;
(MAJOR << 48) | (MINOR << 32) | (PATCH << 16) | RELEASE
});
res.set("FileVersion", "0.0.0.0");
res.set("ProductVersion", "0.0.0.0");
res.set("OriginalFilename", "Graphite.exe");
res.set("FileDescription", "Graphite");
res.set("ProductName", "Graphite");
res.set("LegalCopyright", "Copyright © 2025 Graphite Labs, LLC");
res.set("CompanyName", "Graphite Labs, LLC");
res.compile().expect("Failed to compile Windows resources");
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/desktop/platform/win/src/main.rs | desktop/platform/win/src/main.rs | #![windows_subsystem = "windows"]
fn main() {
graphite_desktop::start();
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/blending/src/lib.rs | node-graph/nodes/blending/src/lib.rs | use core_types::registry::types::Percentage;
use core_types::table::Table;
use core_types::{BlendMode, Color, Ctx};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, Raster};
use vector_types::GradientStops;
pub(crate) trait MultiplyAlpha {
fn multiply_alpha(&mut self, factor: f64);
}
impl MultiplyAlpha for Color {
fn multiply_alpha(&mut self, factor: f64) {
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
}
}
impl MultiplyAlpha for Table<Vector> {
fn multiply_alpha(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.opacity *= factor as f32;
}
}
}
impl MultiplyAlpha for Table<Graphic> {
fn multiply_alpha(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.opacity *= factor as f32;
}
}
}
impl MultiplyAlpha for Table<Raster<CPU>> {
fn multiply_alpha(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.opacity *= factor as f32;
}
}
}
impl MultiplyAlpha for Table<Color> {
fn multiply_alpha(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.opacity *= factor as f32;
}
}
}
impl MultiplyAlpha for Table<GradientStops> {
fn multiply_alpha(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.opacity *= factor as f32;
}
}
}
pub(crate) trait MultiplyFill {
fn multiply_fill(&mut self, factor: f64);
}
impl MultiplyFill for Color {
fn multiply_fill(&mut self, factor: f64) {
*self = Color::from_rgbaf32_unchecked(self.r(), self.g(), self.b(), (self.a() * factor as f32).clamp(0., 1.))
}
}
impl MultiplyFill for Table<Vector> {
fn multiply_fill(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.fill *= factor as f32;
}
}
}
impl MultiplyFill for Table<Graphic> {
fn multiply_fill(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.fill *= factor as f32;
}
}
}
impl MultiplyFill for Table<Raster<CPU>> {
fn multiply_fill(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.fill *= factor as f32;
}
}
}
impl MultiplyFill for Table<Color> {
fn multiply_fill(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.fill *= factor as f32;
}
}
}
impl MultiplyFill for Table<GradientStops> {
fn multiply_fill(&mut self, factor: f64) {
for row in self.iter_mut() {
row.alpha_blending.fill *= factor as f32;
}
}
}
trait SetBlendMode {
fn set_blend_mode(&mut self, blend_mode: BlendMode);
}
impl SetBlendMode for Table<Vector> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for row in self.iter_mut() {
row.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for Table<Graphic> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for row in self.iter_mut() {
row.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for Table<Raster<CPU>> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for row in self.iter_mut() {
row.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for Table<Color> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for row in self.iter_mut() {
row.alpha_blending.blend_mode = blend_mode;
}
}
}
impl SetBlendMode for Table<GradientStops> {
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
for row in self.iter_mut() {
row.alpha_blending.blend_mode = blend_mode;
}
}
}
trait SetClip {
fn set_clip(&mut self, clip: bool);
}
impl SetClip for Table<Vector> {
fn set_clip(&mut self, clip: bool) {
for row in self.iter_mut() {
row.alpha_blending.clip = clip;
}
}
}
impl SetClip for Table<Graphic> {
fn set_clip(&mut self, clip: bool) {
for row in self.iter_mut() {
row.alpha_blending.clip = clip;
}
}
}
impl SetClip for Table<Raster<CPU>> {
fn set_clip(&mut self, clip: bool) {
for row in self.iter_mut() {
row.alpha_blending.clip = clip;
}
}
}
impl SetClip for Table<Color> {
fn set_clip(&mut self, clip: bool) {
for row in self.iter_mut() {
row.alpha_blending.clip = clip;
}
}
}
impl SetClip for Table<GradientStops> {
fn set_clip(&mut self, clip: bool) {
for row in self.iter_mut() {
row.alpha_blending.clip = clip;
}
}
}
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
#[node_macro::node(category("Style"))]
fn blend_mode<T: SetBlendMode>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
)]
mut content: T,
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
blend_mode: BlendMode,
) -> T {
// TODO: Find a way to make this apply once to the table's parent (i.e. its row in its parent table or TableRow<T>) rather than applying to each row in its own table, which produces the undesired result
content.set_blend_mode(blend_mode);
content
}
/// Modifies the opacity of the input graphics by multiplying the existing opacity by this percentage.
/// This affects the transparency of the content (together with anything above which is clipped to it).
#[node_macro::node(category("Style"))]
fn opacity<T: MultiplyAlpha>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
)]
mut content: T,
/// How visible the content should be, including any content clipped to it.
/// Ranges from the default of 100% (fully opaque) to 0% (fully transparent).
#[default(100.)]
opacity: Percentage,
) -> T {
// TODO: Find a way to make this apply once to the table's parent (i.e. its row in its parent table or TableRow<T>) rather than applying to each row in its own table, which produces the undesired result
content.multiply_alpha(opacity / 100.);
content
}
/// Sets each of the blending properties at once. The blend mode determines how overlapping content is composited together. The opacity affects the transparency of the content (together with anything above which is clipped to it). The fill affects the transparency of the content itself, without affecting that of content clipped to it. The clip property determines whether the content inherits the alpha of the content beneath it.
#[node_macro::node(category("Style"))]
fn blending<T: SetBlendMode + MultiplyAlpha + MultiplyFill + SetClip>(
_: impl Ctx,
/// The layer stack that will be composited when rendering.
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
)]
mut content: T,
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
blend_mode: BlendMode,
/// How visible the content should be, including any content clipped to it.
/// Ranges from the default of 100% (fully opaque) to 0% (fully transparent).
#[default(100.)]
opacity: Percentage,
/// How visible the content should be, independent of any content clipped to it.
/// Ranges from 0% (fully transparent) to 100% (fully opaque).
#[default(100.)]
fill: Percentage,
/// Whether the content inherits the alpha of the content beneath it.
#[default(false)]
clip: bool,
) -> T {
// TODO: Find a way to make this apply once to the table's parent (i.e. its row in its parent table or TableRow<T>) rather than applying to each row in its own table, which produces the undesired result
content.set_blend_mode(blend_mode);
content.multiply_alpha(opacity / 100.);
content.multiply_fill(fill / 100.);
content.set_clip(clip);
content
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/extract_xy.rs | node-graph/nodes/gcore/src/extract_xy.rs | use core_types::Ctx;
use dyn_any::DynAny;
use glam::{DVec2, IVec2, UVec2};
/// Obtains the X or Y component of a vec2.
///
/// The inverse of this node is "Vec2 Value", which can have either or both its X and Y parameters exposed as graph inputs.
#[node_macro::node(name("Extract XY"), category("Math: Vector"))]
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: T, axis: XY) -> f64 {
match axis {
XY::X => vector.into().x,
XY::Y => vector.into().y,
}
}
/// The X or Y component of a vec2.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, DynAny, node_macro::ChoiceType, specta::Type, serde::Serialize, serde::Deserialize)]
#[widget(Radio)]
pub enum XY {
#[default]
X,
Y,
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/lib.rs | node-graph/nodes/gcore/src/lib.rs | pub mod animation;
pub mod context_modification;
pub mod debug;
pub mod extract_xy;
pub mod logic;
pub mod memo;
pub mod ops;
// Re-export all nodes
pub use animation::*;
pub use context_modification::*;
pub use debug::*;
pub use extract_xy::*;
pub use logic::*;
pub use memo::*;
pub use ops::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/animation.rs | node-graph/nodes/gcore/src/animation.rs | use core_types::{Ctx, ExtractAnimationTime, ExtractPointer, ExtractRealTime};
use glam::DVec2;
const DAY: f64 = 1000. * 3600. * 24.;
#[derive(Debug, Clone, Copy, PartialEq, Eq, dyn_any::DynAny, Default, Hash, node_macro::ChoiceType, serde::Serialize, serde::Deserialize)]
pub enum RealTimeMode {
#[label("UTC")]
Utc,
Year,
Hour,
Minute,
#[default]
Second,
Millisecond,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationTimeMode {
AnimationTime,
FrameNumber,
}
/// Produces a chosen representation of the current real time and date (in UTC) based on the system clock.
#[node_macro::node(category("Animation"))]
fn real_time(
ctx: impl Ctx + ExtractRealTime,
_primary: (),
/// The time and date component to be produced as a number.
component: RealTimeMode,
) -> f64 {
let real_time = ctx.try_real_time().unwrap_or_default();
// TODO: Implement proper conversion using and existing time implementation
match component {
RealTimeMode::Utc => real_time,
RealTimeMode::Year => (real_time / DAY / 365.25).floor() + 1970., // TODO: Factor in a chosen timezone
RealTimeMode::Hour => (real_time / 1000. / 3600.).floor() % 24., // TODO: Factor in a chosen timezone
RealTimeMode::Minute => (real_time / 1000. / 60.).floor() % 60., // TODO: Factor in a chosen timezone
RealTimeMode::Second => (real_time / 1000.).floor() % 60.,
RealTimeMode::Millisecond => real_time % 1000.,
}
}
/// Produces the time, in seconds on the timeline, since the beginning of animation playback.
#[node_macro::node(category("Animation"))]
fn animation_time(ctx: impl Ctx + ExtractAnimationTime) -> f64 {
ctx.try_animation_time().unwrap_or_default()
}
/// Produces the current position of the user's pointer within the document canvas.
#[node_macro::node(category("Animation"))]
fn pointer_position(ctx: impl Ctx + ExtractPointer) -> DVec2 {
ctx.try_pointer().unwrap_or_default()
}
// TODO: These nodes require more sophisticated algorithms for giving the correct result
// #[node_macro::node(category("Animation"))]
// fn month(ctx: impl Ctx + ExtractRealTime) -> f64 {
// ((ctx.try_real_time().unwrap_or_default() / DAY / 365.25 % 1.) * 12.).floor()
// }
// #[node_macro::node(category("Animation"))]
// fn day(ctx: impl Ctx + ExtractRealTime) -> f64 {
// (ctx.try_real_time().unwrap_or_default() / DAY
// }
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/debug.rs | node-graph/nodes/gcore/src/debug.rs | use core_types::Ctx;
use core_types::table::Table;
use glam::{DAffine2, DVec2};
use raster_types::{CPU, Raster};
/// Meant for debugging purposes, not general use. Logs the input value to the console and passes it through unchanged.
#[node_macro::node(category("Debug"), name("Log to Console"))]
fn log_to_console<T: std::fmt::Debug>(_: impl Ctx, #[implementations(bool, f64, u32, u64, DVec2, DAffine2, String)] value: T) -> T {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("{value:#?}");
value
}
/// Meant for debugging purposes, not general use. Returns the size of the input type in bytes.
#[node_macro::node(category("Debug"))]
fn size_of(_: impl Ctx, ty: core_types::Type) -> Option<usize> {
ty.size()
}
/// Meant for debugging purposes, not general use. Wraps the input value in the Some variant of an Option.
#[node_macro::node(category("Debug"))]
fn some<T>(_: impl Ctx, #[implementations(f64, f32, u32, u64, String)] input: T) -> Option<T> {
Some(input)
}
/// Meant for debugging purposes, not general use. Unwraps the input value from an Option, returning the default value if the input is None.
#[node_macro::node(category("Debug"))]
fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<u32>, Option<u64>, Option<String>)] input: Option<T>) -> T {
input.unwrap_or_default()
}
/// Meant for debugging purposes, not general use. Clones the input value.
#[node_macro::node(category("Debug"))]
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&Table<Raster<CPU>>)] value: &'i T) -> T {
value.clone()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/memo.rs | node-graph/nodes/gcore/src/memo.rs | use core_types::memo::*;
use core_types::{Node, WasmNotSend};
use dyn_any::DynFuture;
use std::future::Future;
use std::hash::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::sync::Mutex;
/// Caches the output of a given node called with a specific input.
///
/// A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result.
///
/// A cache hit occurs when the Option is Some and has a stored hash matching the hash of the call argument. In this case, the node returns the cached value without re-evaluating the inner node.
///
/// Currently, only one input-output pair is cached. Subsequent calls with different inputs will overwrite the previous cache.
#[derive(Default)]
pub struct MemoNode<T, CachedNode> {
cache: Arc<Mutex<Option<(u64, T)>>>,
node: CachedNode,
}
impl<'i, I: Hash + 'i, T: 'i + Clone + WasmNotSend, CachedNode: 'i> Node<'i, I> for MemoNode<T, CachedNode>
where
CachedNode: for<'any_input> Node<'any_input, I>,
for<'a> <CachedNode as Node<'a, I>>::Output: Future<Output = T> + WasmNotSend,
{
// TODO: This should return a reference to the cached cached_value
// but that requires a lot of lifetime magic <- This was suggested by copilot but is pretty accurate xD
type Output = DynFuture<'i, T>;
fn eval(&'i self, input: I) -> Self::Output {
let mut hasher = DefaultHasher::new();
input.hash(&mut hasher);
let hash = hasher.finish();
if let Some(data) = self.cache.lock().as_ref().unwrap().as_ref().and_then(|data| (data.0 == hash).then_some(data.1.clone())) {
Box::pin(async move { data })
} else {
let fut = self.node.eval(input);
let cache = self.cache.clone();
Box::pin(async move {
let value = fut.await;
*cache.lock().unwrap() = Some((hash, value.clone()));
value
})
}
}
fn reset(&self) {
self.cache.lock().unwrap().take();
}
}
impl<T, CachedNode> MemoNode<T, CachedNode> {
pub fn new(node: CachedNode) -> MemoNode<T, CachedNode> {
MemoNode { cache: Default::default(), node }
}
}
#[allow(clippy::module_inception)]
pub mod memo {
use core_types::ProtoNodeIdentifier;
pub const IDENTIFIER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::memo::MemoNode");
}
/// Caches the output of the last graph evaluation for introspection.
#[derive(Default)]
pub struct MonitorNode<I, T, N> {
#[allow(clippy::type_complexity)]
io: Arc<Mutex<Option<Arc<IORecord<I, T>>>>>,
node: N,
}
impl<'i, T, I, N> Node<'i, I> for MonitorNode<I, T, N>
where
I: Clone + 'static + Send + Sync,
T: Clone + 'static + Send + Sync,
for<'a> N: Node<'a, I, Output: Future<Output = T> + WasmNotSend> + 'i,
{
type Output = DynFuture<'i, T>;
fn eval(&'i self, input: I) -> Self::Output {
let io = self.io.clone();
let output_fut = self.node.eval(input.clone());
Box::pin(async move {
let output = output_fut.await;
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() }));
output
})
}
fn serialize(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
let io = self.io.lock().unwrap();
(io).as_ref().map(|output| output.clone() as Arc<dyn std::any::Any + Send + Sync>)
}
}
impl<I, T, N> MonitorNode<I, T, N> {
pub fn new(node: N) -> MonitorNode<I, T, N> {
MonitorNode { io: Arc::new(Mutex::new(None)), node }
}
}
pub mod monitor {
use core_types::ProtoNodeIdentifier;
pub const IDENTIFIER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode");
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/context_modification.rs | node-graph/nodes/gcore/src/context_modification.rs | use core::f64;
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll};
use core_types::table::Table;
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use core_types::{Color, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::{Artboard, Graphic, Vector, vector_types::GradientStops};
use raster_types::{CPU, GPU, Raster};
/// Filters out what should be unused components of the context based on the specified requirements.
/// This node is inserted by the compiler to "zero out" unused context components.
#[node_macro::node(category("Internal"))]
async fn context_modification<T>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
/// The data to pass through, evaluated with the stripped down context.
#[implementations(
Context -> (),
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> Vec<DVec2>,
Context -> Vec<NodeId>,
Context -> Vec<f64>,
Context -> Vec<f32>,
Context -> Vec<String>,
Context -> Table<Vector>,
Context -> Table<Graphic>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> Table<Artboard>,
Context -> Table<GradientStops>,
Context -> GradientStops,
)]
value: impl Node<Context<'static>, Output = T>,
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
features_to_keep: ContextFeatures,
) -> T {
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep);
value.eval(Some(new_context.into())).await
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::transform::Footprint;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
/// Test that the hash of a nullified context remains stable even when nullified inputs change
#[test]
fn test_nullified_context_hash_stability() {
use core_types::Context;
use std::sync::Arc;
// Create original contexts using the Context type (Option<Arc<OwnedContextImpl>>)
let original_ctx: Context = Some(Arc::new(
OwnedContextImpl::empty()
.with_footprint(Footprint::default())
.with_index(1)
.with_real_time(10.5)
.with_vararg(Box::new("test"))
.with_animation_time(20.25),
));
// Test nullifying different features - hash should remain stable for each nullification
let features_to_keep = ContextFeatures::empty(); // Nullify everything
// Create nullified context - this should only keep features specified in features_to_keep
let nullified_ctx = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), features_to_keep);
// Calculate hash of nullified context
let mut hasher1 = DefaultHasher::new();
nullified_ctx.hash(&mut hasher1);
let hash1 = hasher1.finish();
// Create a different original context with changed values
let changed_ctx: Context = Some(Arc::new(
OwnedContextImpl::empty()
.with_footprint(Footprint::default()) // Same footprint
.with_index(2)
.with_real_time(999.9) // Different real time
.with_vararg(Box::new("test"))
.with_animation_time(888.8), // Different animation time
));
// Create nullified context from the changed original - should have same hash since everything is nullified
let nullified_changed_ctx = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), features_to_keep);
let mut hasher2 = DefaultHasher::new();
nullified_changed_ctx.hash(&mut hasher2);
let hash2 = hasher2.finish();
// Hash should be the same because all features were nullified
assert_eq!(hash1, hash2, "Hash of nullified context should remain stable regardless of input changes when features are nullified");
// Test partial nullification - keep only footprint
let partial_features = ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS;
let partial_nullified1 = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), partial_features);
let partial_nullified2 = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), partial_features);
let mut hasher3 = DefaultHasher::new();
partial_nullified1.hash(&mut hasher3);
let hash3 = hasher3.finish();
let mut hasher4 = DefaultHasher::new();
partial_nullified2.hash(&mut hasher4);
let hash4 = hasher4.finish();
// These should be the same because both have the same footprint (Footprint::default()) and varargs
// and other features are nullified
assert_eq!(hash3, hash4, "Hash should be stable when keeping only footprint and footprint values are the same");
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/ops.rs | node-graph/nodes/gcore/src/ops.rs | use core_types::{Ctx, ExtractFootprint, ops::Convert, transform::Footprint};
use std::marker::PhantomData;
// Re-export TypeNode from core-types for convenience
pub use core_types::ops::TypeNode;
// TODO: Rename to "Passthrough"
/// Passes-through the input value without changing it.
/// This is useful for rerouting wires for organization purposes.
#[node_macro::node(skip_impl)]
fn identity<'i, T: 'i + Send>(value: T) -> T {
value
}
#[node_macro::node(skip_impl)]
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
value.into()
}
#[node_macro::node(skip_impl)]
async fn convert<'i, T: 'i + Send + Convert<O, C>, O: 'i + Send, C: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: T, converter: C, _out_ty: PhantomData<O>) -> O {
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter).await
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn identity_node() {
assert_eq!(identity(&4), &4);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/gcore/src/logic.rs | node-graph/nodes/gcore/src/logic.rs | use core_types::Color;
use core_types::registry::types::TextArea;
use core_types::table::Table;
use core_types::{Context, Ctx};
use glam::{DAffine2, DVec2};
use graphic_types::{Artboard, Graphic, Vector, vector_types::GradientStops};
use raster_types::{CPU, GPU, Raster};
/// Type-asserts a value to be a string.
#[node_macro::node(category("Debug"))]
fn to_string(_: impl Ctx, value: String) -> String {
value
}
/// Converts a value to a JSON string representation.
#[node_macro::node(category("Text"))]
fn serialize<T: serde::Serialize>(
_: impl Ctx,
#[implementations(String, bool, f64, u32, u64, DVec2, DAffine2, /* Table<Artboard>, Table<Graphic>, Table<Vector>, */ Table<Raster<CPU>>, Table<Color> /* , Table<GradientStops> */)] value: T,
) -> String {
serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string())
}
/// Joins two strings together.
#[node_macro::node(category("Text"))]
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: String, second: TextArea) -> String {
first.clone() + &second
}
/// Replaces all occurrences of "From" with "To" in the input string.
#[node_macro::node(category("Text"))]
fn string_replace(_: impl Ctx, string: String, from: TextArea, to: TextArea) -> String {
string.replace(&from, &to)
}
/// Extracts a substring from the input string, starting at "Start" and ending before "End".
/// Negative indices count from the end of the string.
/// If "Start" equals or exceeds "End", the result is an empty string.
#[node_macro::node(category("Text"))]
fn string_slice(_: impl Ctx, string: String, start: f64, end: f64) -> String {
let total_chars = string.chars().count();
let start = if start < 0. {
total_chars.saturating_sub(start.abs() as usize)
} else {
(start as usize).min(total_chars)
};
let end = if end <= 0. {
total_chars.saturating_sub(end.abs() as usize)
} else {
(end as usize).min(total_chars)
};
if start >= end {
return String::new();
}
string.chars().skip(start).take(end - start).collect()
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
/// Counts the number of characters in a string.
#[node_macro::node(category("Text"))]
fn string_length(_: impl Ctx, string: String) -> f64 {
string.chars().count() as f64
}
/// Splits a string into a list of substrings based on the specified delimeter.
/// For example, the delimeter "," will split "a,b,c" into the strings "a", "b", and "c".
#[node_macro::node(category("Text"))]
fn string_split(
_: impl Ctx,
/// The string to split into substrings.
string: String,
/// The character(s) that separate the substrings. These are not included in the outputs.
#[default("\\n")]
delimeter: String,
/// Whether to convert escape sequences found in the delimeter into their corresponding characters:
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
#[default(true)]
delimeter_escaping: bool,
) -> Vec<String> {
let delimeter = if delimeter_escaping {
delimeter.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t").replace("\\0", "\0").replace("\\\\", "\\")
} else {
delimeter
};
string.split(&delimeter).map(str::to_string).collect()
}
/// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false.
#[node_macro::node(category("Math: Logic"))]
async fn switch<T, C: Send + 'n + Clone>(
#[implementations(Context)] ctx: C,
condition: bool,
#[expose]
#[implementations(
Context -> String,
Context -> bool,
Context -> f32,
Context -> f64,
Context -> u32,
Context -> u64,
Context -> DVec2,
Context -> DAffine2,
Context -> Table<Artboard>,
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> GradientStops,
)]
if_true: impl Node<C, Output = T>,
#[expose]
#[implementations(
Context -> String,
Context -> bool,
Context -> f32,
Context -> f64,
Context -> u32,
Context -> u64,
Context -> DVec2,
Context -> DAffine2,
Context -> Table<Artboard>,
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> GradientStops,
)]
if_false: impl Node<C, Output = T>,
) -> T {
if condition { if_true.eval(ctx).await } else { if_false.eval(ctx).await }
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/math/src/lib.rs | node-graph/nodes/math/src/lib.rs | use core_types::registry::types::{Fraction, Percentage, PixelSize, TextArea};
use core_types::table::Table;
use core_types::transform::Footprint;
use core_types::{Color, Ctx, num_traits};
use glam::{DAffine2, DVec2};
use log::warn;
use math_parser::ast;
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
use math_parser::value::{Number, Value};
use num_traits::Pow;
use rand::{Rng, SeedableRng};
use std::ops::{Add, Div, Mul, Rem, Sub};
use vector_types::GradientStops;
/// The struct that stores the context for the maths parser.
/// This is currently just limited to supplying `a` and `b` until we add better node graph support and UI for variadic inputs.
struct MathNodeContext {
a: f64,
b: f64,
}
impl ValueProvider for MathNodeContext {
fn get_value(&self, name: &str) -> Option<Value> {
if name.eq_ignore_ascii_case("a") {
Some(Value::from_f64(self.a))
} else if name.eq_ignore_ascii_case("b") {
Some(Value::from_f64(self.b))
} else {
None
}
}
}
/// Calculates a mathematical expression with input values "A" and "B".
#[node_macro::node(category("Math: Arithmetic"), properties("math_properties"))]
fn math<T: num_traits::float::Float>(
_: impl Ctx,
/// The value of "A" when calculating the expression.
#[implementations(f64, f32)]
operand_a: T,
/// A math expression that may incorporate "A" and/or "B", such as `sqrt(A + B) - B^2`.
#[default(A + B)]
expression: String,
/// The value of "B" when calculating the expression.
#[implementations(f64, f32)]
#[default(1.)]
operand_b: T,
) -> T {
let (node, _unit) = match ast::Node::try_parse_from_str(&expression) {
Ok(expr) => expr,
Err(e) => {
warn!("Invalid expression: `{expression}`\n{e:?}");
return T::from(0.).unwrap();
}
};
let context = EvalContext::new(
MathNodeContext {
a: operand_a.to_f64().unwrap(),
b: operand_b.to_f64().unwrap(),
},
NothingMap,
);
let value = match node.eval(&context) {
Ok(value) => value,
Err(e) => {
warn!("Expression evaluation error: {e:?}");
return T::from(0.).unwrap();
}
};
let Value::Number(num) = value;
match num {
Number::Real(val) => T::from(val).unwrap(),
Number::Complex(c) => T::from(c.re).unwrap(),
}
}
/// The addition operation (`+`) calculates the sum of two scalar numbers or vectors.
#[node_macro::node(category("Math: Arithmetic"))]
fn add<A: Add<B>, B>(
_: impl Ctx,
/// The left-hand side of the addition operation.
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
augend: A,
/// The right-hand side of the addition operation.
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
addend: B,
) -> <A as Add<B>>::Output {
augend + addend
}
/// The subtraction operation (`-`) calculates the difference between two scalar numbers or vectors.
#[node_macro::node(category("Math: Arithmetic"))]
fn subtract<A: Sub<B>, B>(
_: impl Ctx,
/// The left-hand side of the subtraction operation.
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
minuend: A,
/// The right-hand side of the subtraction operation.
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
subtrahend: B,
) -> <A as Sub<B>>::Output {
minuend - subtrahend
}
/// The multiplication operation (`×`) calculates the product of two scalar numbers, vectors, or transforms.
#[node_macro::node(category("Math: Arithmetic"))]
fn multiply<A: Mul<B>, B>(
_: impl Ctx,
/// The left-hand side of the multiplication operation.
#[implementations(f64, f32, u32, DVec2, f64, DVec2, DAffine2)]
multiplier: A,
/// The right-hand side of the multiplication operation.
#[default(1.)]
#[implementations(f64, f32, u32, DVec2, DVec2, f64, DAffine2)]
multiplicand: B,
) -> <A as Mul<B>>::Output {
multiplier * multiplicand
}
/// The division operation (`÷`) calculates the quotient of two scalar numbers or vectors.
///
/// Produces 0 if the denominator is 0.
#[node_macro::node(category("Math: Arithmetic"))]
fn divide<A: Div<B> + Default + PartialEq, B: Default + PartialEq>(
_: impl Ctx,
/// The left-hand side of the division operation.
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
numerator: A,
/// The right-hand side of the division operation.
#[default(1.)]
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
denominator: B,
) -> <A as Div<B>>::Output
where
<A as Div<B>>::Output: Default,
{
if denominator == B::default() {
return <A as Div<B>>::Output::default();
}
numerator / denominator
}
/// The reciprocal operation (`1/x`) calculates the multiplicative inverse of a number.
///
/// Produces 0 if the input is 0.
#[node_macro::node(category("Math: Arithmetic"))]
fn reciprocal<T: num_traits::float::Float>(
_: impl Ctx,
/// The number for which the reciprocal is calculated.
#[implementations(f64, f32)]
value: T,
) -> T {
if value == T::from(0.).unwrap() { T::from(0.).unwrap() } else { T::from(1.).unwrap() / value }
}
/// The modulo operation (`%`) calculates the remainder from the division of two scalar numbers or vectors.
///
/// The sign of the result shares the sign of the numerator unless *Always Positive* is enabled.
#[node_macro::node(category("Math: Arithmetic"))]
fn modulo<A: Rem<B, Output: Add<B, Output: Rem<B, Output = A::Output>>>, B: Copy>(
_: impl Ctx,
/// The left-hand side of the modulo operation.
#[implementations(f64, f32, u32, DVec2, DVec2, f64)]
numerator: A,
/// The right-hand side of the modulo operation.
#[default(2.)]
#[implementations(f64, f32, u32, DVec2, f64, DVec2)]
modulus: B,
/// Ensures the result is always positive, even if the numerator is negative.
#[default(true)]
always_positive: bool,
) -> <A as Rem<B>>::Output {
if always_positive { (numerator % modulus + modulus) % modulus } else { numerator % modulus }
}
/// The exponent operation (`^`) calculates the result of raising a number to a power.
#[node_macro::node(category("Math: Arithmetic"))]
fn exponent<T: Pow<T>>(
_: impl Ctx,
/// The base number that is raised to the power.
#[implementations(f64, f32, u32)]
base: T,
/// The power to which the base number is raised.
#[implementations(f64, f32, u32)]
#[default(2.)]
power: T,
) -> <T as num_traits::Pow<T>>::Output {
base.pow(power)
}
/// The `n`th root operation (`√`) calculates the inverse of exponentiation. Square root inverts squaring, cube root inverts cubing, and so on.
///
/// This is equivalent to raising the number to the power of `1/n`.
#[node_macro::node(category("Math: Arithmetic"))]
fn root<T: num_traits::float::Float>(
_: impl Ctx,
/// The number inside the radical for which the `n`th root is calculated.
#[default(2.)]
#[implementations(f64, f32)]
radicand: T,
/// The degree of the root to be calculated. Square root is 2, cube root is 3, and so on.
/// Degrees 0 or less are invalid and will produce an output of 0.
#[default(2.)]
#[implementations(f64, f32)]
degree: T,
) -> T {
if degree == T::from(2.).unwrap() {
radicand.sqrt()
} else if degree == T::from(3.).unwrap() {
radicand.cbrt()
} else if degree <= T::from(0.).unwrap() {
T::from(0.).unwrap()
} else {
radicand.powf(T::from(1.).unwrap() / degree)
}
}
/// The logarithmic function (`log`) calculates the logarithm of a number with a specified base. If the natural logarithm function (`ln`) is desired, set the base to "e".
#[node_macro::node(category("Math: Arithmetic"))]
fn logarithm<T: num_traits::float::Float>(
_: impl Ctx,
/// The number for which the logarithm is calculated.
#[implementations(f64, f32)]
value: T,
/// The base of the logarithm, such as 2 (binary), 10 (decimal), and e (natural logarithm).
#[default(2.)]
#[implementations(f64, f32)]
base: T,
) -> T {
if base == T::from(2.).unwrap() {
value.log2()
} else if base == T::from(10.).unwrap() {
value.log10()
} else if base - T::from(std::f64::consts::E).unwrap() < T::epsilon() * T::from(1e6).unwrap() {
value.ln()
} else {
value.log(base)
}
}
/// The sine trigonometric function (`sin`) calculates the ratio of the angle's opposite side length to its hypotenuse length.
#[node_macro::node(category("Math: Trig"))]
fn sine<T: num_traits::float::Float>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, f32)]
theta: T,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: bool,
) -> T {
if radians { theta.sin() } else { theta.to_radians().sin() }
}
/// The cosine trigonometric function (`cos`) calculates the ratio of the angle's adjacent side length to its hypotenuse length.
#[node_macro::node(category("Math: Trig"))]
fn cosine<T: num_traits::float::Float>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, f32)]
theta: T,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: bool,
) -> T {
if radians { theta.cos() } else { theta.to_radians().cos() }
}
/// The tangent trigonometric function (`tan`) calculates the ratio of the angle's opposite side length to its adjacent side length.
#[node_macro::node(category("Math: Trig"))]
fn tangent<T: num_traits::float::Float>(
_: impl Ctx,
/// The given angle.
#[implementations(f64, f32)]
theta: T,
/// Whether the given angle should be interpreted as radians instead of degrees.
radians: bool,
) -> T {
if radians { theta.tan() } else { theta.to_radians().tan() }
}
/// The inverse sine trigonometric function (`asin`) calculates the angle whose sine is the input value.
#[node_macro::node(category("Math: Trig"))]
fn sine_inverse<T: num_traits::float::Float>(
_: impl Ctx,
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
#[implementations(f64, f32)]
value: T,
/// Whether the resulting angle should be given in as radians instead of degrees.
radians: bool,
) -> T {
let angle = value.clamp(T::from(-1.).unwrap(), T::from(1.).unwrap()).asin();
if radians { angle } else { angle.to_degrees() }
}
/// The inverse cosine trigonometric function (`acos`) calculates the angle whose cosine is the input value.
#[node_macro::node(category("Math: Trig"))]
fn cosine_inverse<T: num_traits::float::Float>(
_: impl Ctx,
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
#[implementations(f64, f32)]
value: T,
/// Whether the resulting angle should be given in as radians instead of degrees.
radians: bool,
) -> T {
let angle = value.clamp(T::from(-1.).unwrap(), T::from(1.).unwrap()).acos();
if radians { angle } else { angle.to_degrees() }
}
/// The inverse tangent trigonometric function (`atan` or `atan2`, depending on input type) calculates:
/// `atan`: the angle whose tangent is the input scalar number.
/// `atan2`: the angle of a ray from the origin to the input vec2.
///
/// The resulting angle is always in the range `[-90°, 90°]` or, in radians, `[-π/2, π/2]`.
#[node_macro::node(category("Math: Trig"))]
fn tangent_inverse<T: TangentInverse>(
_: impl Ctx,
/// The given value for which the angle is calculated.
#[implementations(f64, f32, DVec2)]
value: T,
/// Whether the resulting angle should be given in as radians instead of degrees.
radians: bool,
) -> T::Output {
value.atan(radians)
}
pub trait TangentInverse {
type Output: num_traits::float::Float;
fn atan(self, radians: bool) -> Self::Output;
}
impl TangentInverse for f32 {
type Output = f32;
fn atan(self, radians: bool) -> Self::Output {
if radians { self.atan() } else { self.atan().to_degrees() }
}
}
impl TangentInverse for f64 {
type Output = f64;
fn atan(self, radians: bool) -> Self::Output {
if radians { self.atan() } else { self.atan().to_degrees() }
}
}
impl TangentInverse for DVec2 {
type Output = f64;
fn atan(self, radians: bool) -> Self::Output {
if radians { self.y.atan2(self.x) } else { self.y.atan2(self.x).to_degrees() }
}
}
/// Linearly maps an input value from one range to another. The ranges may be reversed.
///
/// For example, 0.5 in the input range `[0, 1]` would map to 0 in the output range `[-180, 180]`.
#[node_macro::node(category("Math: Numeric"))]
fn remap<U: num_traits::float::Float>(
_: impl Ctx,
/// The value to be mapped between ranges.
#[implementations(f64, f32)]
value: U,
/// The lower bound of the input range.
#[implementations(f64, f32)]
input_min: U,
/// The upper bound of the input range.
#[implementations(f64, f32)]
#[default(1.)]
input_max: U,
/// The lower bound of the output range.
#[implementations(f64, f32)]
output_min: U,
/// The upper bound of the output range.
#[implementations(f64, f32)]
#[default(1.)]
output_max: U,
/// Whether to constrain the result within the output range instead of extrapolating beyond its bounds.
clamped: bool,
) -> U {
let input_range = input_max - input_min;
// Handle division by zero
if input_range.abs() < U::epsilon() {
return output_min;
}
let normalized = (value - input_min) / input_range;
let output_range = output_max - output_min;
let result = output_min + normalized * output_range;
if clamped {
// Handle both normal and inverted ranges, since we want to allow the user to use this node to also reverse a range.
if output_min <= output_max {
result.clamp(output_min, output_max)
} else {
result.clamp(output_max, output_min)
}
} else {
result
}
}
/// The random function (`rand`) converts a seed into a random number within the specified range, inclusive of the minimum and exclusive of the maximum. The minimum and maximum values are automatically swapped if they are reversed.
#[node_macro::node(category("Math: Numeric"))]
fn random(
_: impl Ctx,
_primary: (),
/// Seed to determine the unique variation of which number is generated.
seed: u64,
/// The smaller end of the range within which the random number is generated.
#[default(0.)]
min: f64,
/// The larger end of the range within which the random number is generated.
#[default(1.)]
max: f64,
) -> f64 {
let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
let result = rng.random::<f64>();
let (min, max) = if min < max { (min, max) } else { (max, min) };
result * (max - min) + min
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Convert a number to an integer of the type u32, which may be the required type for certain node inputs.
#[node_macro::node(name("To u32"), category("Debug"))]
fn to_u32(_: impl Ctx, value: u32) -> u32 {
value
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Convert a number to an integer of the type u64, which may be the required type for certain node inputs.
#[node_macro::node(name("To u64"), category("Debug"))]
fn to_u64(_: impl Ctx, value: u64) -> u64 {
value
}
// TODO: Test that these are no longer needed in all circumstances, then remove them and add a migration to convert these into Passthrough nodes. Note: these act more as type annotations than as identity functions.
/// Convert an integer to a decimal number of the type f64, which may be the required type for certain node inputs.
#[node_macro::node(name("To f64"), category("Debug"))]
fn to_f64(_: impl Ctx, value: f64) -> f64 {
value
}
/// The rounding function (`round`) maps an input value to its nearest whole number. Halfway values are rounded away from zero.
#[node_macro::node(category("Math: Numeric"))]
fn round<T: num_traits::float::Float>(
_: impl Ctx,
/// The number to be rounded to the nearest whole number.
#[implementations(f64, f32)]
value: T,
) -> T {
value.round()
}
/// The floor function (`floor`) rounds down an input value to the nearest whole number, unless the input number is already whole.
#[node_macro::node(category("Math: Numeric"))]
fn floor<T: num_traits::float::Float>(
_: impl Ctx,
/// The number to be rounded down.
#[implementations(f64, f32)]
value: T,
) -> T {
value.floor()
}
/// The ceiling function (`ceil`) rounds up an input value to the nearest whole number, unless the input number is already whole.
#[node_macro::node(category("Math: Numeric"))]
fn ceiling<T: num_traits::float::Float>(
_: impl Ctx,
/// The number to be rounded up.
#[implementations(f64, f32)]
value: T,
) -> T {
value.ceil()
}
trait AbsoluteValue {
fn abs(self) -> Self;
}
impl AbsoluteValue for DVec2 {
fn abs(self) -> Self {
DVec2::new(self.x.abs(), self.y.abs())
}
}
impl AbsoluteValue for f32 {
fn abs(self) -> Self {
self.abs()
}
}
impl AbsoluteValue for f64 {
fn abs(self) -> Self {
self.abs()
}
}
impl AbsoluteValue for i32 {
fn abs(self) -> Self {
self.abs()
}
}
impl AbsoluteValue for i64 {
fn abs(self) -> Self {
self.abs()
}
}
/// The absolute value function (`abs`) removes the negative sign from an input value, if present.
#[node_macro::node(category("Math: Numeric"))]
fn absolute_value<T: AbsoluteValue>(
_: impl Ctx,
/// The number to be made positive.
#[implementations(f64, f32, i32, i64, DVec2)]
value: T,
) -> T {
value.abs()
}
/// The minimum function (`min`) picks the smaller of two numbers.
#[node_macro::node(category("Math: Numeric"))]
fn min<T: std::cmp::PartialOrd>(
_: impl Ctx,
/// One of the two numbers, of which the lesser is returned.
#[implementations(f64, f32, u32, &str)]
value: T,
/// The other of the two numbers, of which the lesser is returned.
#[implementations(f64, f32, u32, &str)]
other_value: T,
) -> T {
if value < other_value { value } else { other_value }
}
/// The maximum function (`max`) picks the larger of two numbers.
#[node_macro::node(category("Math: Numeric"))]
fn max<T: std::cmp::PartialOrd>(
_: impl Ctx,
/// One of the two numbers, of which the greater is returned.
#[implementations(f64, f32, u32, &str)]
value: T,
/// The other of the two numbers, of which the greater is returned.
#[implementations(f64, f32, u32, &str)]
other_value: T,
) -> T {
if value > other_value { value } else { other_value }
}
/// The clamp function (`clamp`) restricts a number to a specified range between a minimum and maximum value. The minimum and maximum values are automatically swapped if they are reversed.
#[node_macro::node(category("Math: Numeric"))]
fn clamp<T: std::cmp::PartialOrd>(
_: impl Ctx,
/// The number to be clamped, which is restricted to the range between the minimum and maximum values.
#[implementations(f64, f32, u32, &str)]
value: T,
/// The left (smaller) side of the range. The output is never less than this number.
#[implementations(f64, f32, u32, &str)]
min: T,
/// The right (greater) side of the range. The output is never greater than this number.
#[implementations(f64, f32, u32, &str)]
max: T,
) -> T {
let (min, max) = if min < max { (min, max) } else { (max, min) };
if value < min {
min
} else if value > max {
max
} else {
value
}
}
/// The greatest common divisor (GCD) calculates the largest positive integer that divides both of the two input numbers without leaving a remainder.
#[node_macro::node(category("Math: Numeric"))]
fn greatest_common_divisor<T: num_traits::int::PrimInt + std::ops::ShrAssign<i32> + std::ops::SubAssign>(
_: impl Ctx,
/// One of the two numbers for which the GCD is calculated.
#[implementations(u32, u64, i32)]
value: T,
/// The other of the two numbers for which the GCD is calculated.
#[implementations(u32, u64, i32)]
other_value: T,
) -> T {
if value == T::zero() {
return other_value;
}
if other_value == T::zero() {
return value;
}
binary_gcd(value, other_value)
}
/// The least common multiple (LCM) calculates the smallest positive integer that is a multiple of both of the two input numbers.
#[node_macro::node(category("Math: Numeric"))]
fn least_common_multiple<T: num_traits::ToPrimitive + num_traits::FromPrimitive + num_traits::identities::Zero>(
_: impl Ctx,
/// One of the two numbers for which the LCM is calculated.
#[implementations(u32, u64, i32)]
value: T,
/// The other of the two numbers for which the LCM is calculated.
#[implementations(u32, u64, i32)]
other_value: T,
) -> T {
let value = value.to_i128().unwrap();
let other_value = other_value.to_i128().unwrap();
if value == 0 || other_value == 0 {
return T::zero();
}
let gcd = binary_gcd(value, other_value);
T::from_i128((value * other_value).abs() / gcd).unwrap()
}
fn binary_gcd<T: num_traits::int::PrimInt + std::ops::ShrAssign<i32> + std::ops::SubAssign>(mut a: T, mut b: T) -> T {
if a == T::zero() {
return b;
}
if b == T::zero() {
return a;
}
let mut shift = 0;
while (a | b) & T::one() == T::zero() {
a >>= 1;
b >>= 1;
shift += 1;
}
while a & T::one() == T::zero() {
a >>= 1;
}
while b != T::zero() {
while b & T::one() == T::zero() {
b >>= 1;
}
if a > b {
std::mem::swap(&mut a, &mut b);
}
b -= a;
}
a << shift
}
/// The less-than operation (`<`) compares two values and returns true if the first value is less than the second, or false if it is not.
/// If enabled with *Or Equal*, the less-than-or-equal operation (`<=`) is used instead.
#[node_macro::node(category("Math: Logic"))]
fn less_than<T: std::cmp::PartialOrd<T>>(
_: impl Ctx,
/// The number on the left-hand side of the comparison.
#[implementations(f64, f32, u32)]
value: T,
/// The number on the right-hand side of the comparison.
#[implementations(f64, f32, u32)]
other_value: T,
/// Uses the less-than-or-equal operation (`<=`) instead of the less-than operation (`<`).
or_equal: bool,
) -> bool {
if or_equal { value <= other_value } else { value < other_value }
}
/// The greater-than operation (`>`) compares two values and returns true if the first value is greater than the second, or false if it is not.
/// If enabled with *Or Equal*, the greater-than-or-equal operation (`>=`) is used instead.
#[node_macro::node(category("Math: Logic"))]
fn greater_than<T: std::cmp::PartialOrd<T>>(
_: impl Ctx,
/// The number on the left-hand side of the comparison.
#[implementations(f64, f32, u32)]
value: T,
/// The number on the right-hand side of the comparison.
#[implementations(f64, f32, u32)]
other_value: T,
/// Uses the greater-than-or-equal operation (`>=`) instead of the greater-than operation (`>`).
or_equal: bool,
) -> bool {
if or_equal { value >= other_value } else { value > other_value }
}
/// The equality operation (`==`, `XNOR`) compares two values and returns true if they are equal, or false if they are not.
#[node_macro::node(category("Math: Logic"))]
fn equals<T: std::cmp::PartialEq<T>>(
_: impl Ctx,
/// One of the two values to compare for equality.
#[implementations(f64, f32, u32, DVec2, bool, &str, String)]
value: T,
/// The other of the two values to compare for equality.
#[implementations(f64, f32, u32, DVec2, bool, &str, String)]
other_value: T,
) -> bool {
other_value == value
}
/// The inequality operation (`!=`, `XOR`) compares two values and returns true if they are not equal, or false if they are.
#[node_macro::node(category("Math: Logic"))]
fn not_equals<T: std::cmp::PartialEq<T>>(
_: impl Ctx,
/// One of the two values to compare for inequality.
#[implementations(f64, f32, u32, DVec2, bool, &str)]
value: T,
/// The other of the two values to compare for inequality.
#[implementations(f64, f32, u32, DVec2, bool, &str)]
other_value: T,
) -> bool {
other_value != value
}
/// The logical OR operation (`||`) returns true if either of the two inputs are true, or false if both are false.
#[node_macro::node(category("Math: Logic"))]
fn logical_or(
_: impl Ctx,
/// One of the two boolean values, either of which may be true for the node to output true.
value: bool,
/// The other of the two boolean values, either of which may be true for the node to output true.
other_value: bool,
) -> bool {
value || other_value
}
/// The logical AND operation (`&&`) returns true if both of the two inputs are true, or false if any are false.
#[node_macro::node(category("Math: Logic"))]
fn logical_and(
_: impl Ctx,
/// One of the two boolean values, both of which must be true for the node to output true.
value: bool,
/// The other of the two boolean values, both of which must be true for the node to output true.
other_value: bool,
) -> bool {
value && other_value
}
/// The logical NOT operation (`!`) reverses true and false value of the input.
#[node_macro::node(category("Math: Logic"))]
fn logical_not(
_: impl Ctx,
/// The boolean value to be reversed.
input: bool,
) -> bool {
!input
}
/// Constructs a bool value which may be set to true or false.
#[node_macro::node(category("Value"))]
fn bool_value(_: impl Ctx, _primary: (), #[name("Bool")] bool_value: bool) -> bool {
bool_value
}
/// Constructs a number value which may be set to any real number.
#[node_macro::node(category("Value"))]
fn number_value(_: impl Ctx, _primary: (), number: f64) -> f64 {
number
}
/// Constructs a number value which may be set to any value from 0% to 100% by dragging the slider.
#[node_macro::node(category("Value"))]
fn percentage_value(_: impl Ctx, _primary: (), percentage: Percentage) -> f64 {
percentage
}
/// Constructs a two-dimensional vector value which may be set to any XY pair.
#[node_macro::node(category("Value"), name("Vec2 Value"))]
fn vec2_value(_: impl Ctx, _primary: (), x: f64, y: f64) -> DVec2 {
DVec2::new(x, y)
}
/// Constructs a color value which may be set to any color, or no color.
#[node_macro::node(category("Value"))]
fn color_value(_: impl Ctx, _primary: (), #[default(Color::RED)] color: Table<Color>) -> Table<Color> {
color
}
/// Constructs a gradient value which may be set to any sequence of color stops to represent the transition between colors.
#[node_macro::node(category("Value"))]
fn gradient_value(_: impl Ctx, _primary: (), gradient: GradientStops) -> GradientStops {
gradient
}
/// Constructs a gradient value which may be set to any sequence of color stops to represent the transition between colors.
#[node_macro::node(category("Value"))]
fn gradient_table_value(_: impl Ctx, _primary: (), gradient: GradientStops) -> Table<GradientStops> {
Table::new_from_element(gradient)
}
/// Gets the color at the specified position along the gradient, given a position from 0 (left) to 1 (right).
#[node_macro::node(category("Color"))]
fn sample_gradient(_: impl Ctx, _primary: (), gradient: GradientStops, position: Fraction) -> Table<Color> {
let position = position.clamp(0., 1.);
let color = gradient.evaluate(position);
Table::new_from_element(color)
}
/// Constructs a string value which may be set to any plain text.
#[node_macro::node(category("Value"))]
fn string_value(_: impl Ctx, _primary: (), string: TextArea) -> String {
string
}
/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels.
#[node_macro::node(category("Value"))]
fn footprint_value(_: impl Ctx, _primary: (), transform: DAffine2, #[default(100., 100.)] resolution: PixelSize) -> Footprint {
Footprint {
transform,
resolution: resolution.max(DVec2::ONE).as_uvec2(),
..Default::default()
}
}
/// The dot product operation (`·`) calculates the degree of similarity of a vec2 pair based on their angles and lengths.
///
/// Calculated as `‖a‖‖b‖cos(θ)`, it represents the product of their lengths (`‖a‖‖b‖`) scaled by the alignment of their directions (`cos(θ)`).
/// The output ranges from the positive to negative product of their lengths based on when they are pointing in the same or opposite directions.
/// If any vector has zero length, the output is 0.
#[node_macro::node(category("Math: Vector"))]
fn dot_product(
_: impl Ctx,
/// An operand of the dot product operation.
vector_a: DVec2,
/// The other operand of the dot product operation.
#[default((1., 0.))]
vector_b: DVec2,
/// Whether to normalize both input vectors so the calculation ranges in `[-1, 1]` by considering only their degree of directional alignment.
normalize: bool,
) -> f64 {
if normalize {
vector_a.normalize_or_zero().dot(vector_b.normalize_or_zero())
} else {
vector_a.dot(vector_b)
}
}
/// Calculates the angle swept between two vectors.
///
/// The value is always positive and ranges from 0° (both vectors point the same direction) to 180° (both vectors point opposite directions).
#[node_macro::node(category("Math: Vector"))]
fn angle_between(_: impl Ctx, vector_a: DVec2, vector_b: DVec2, radians: bool) -> f64 {
let dot_product = vector_a.normalize_or_zero().dot(vector_b.normalize_or_zero());
let angle = dot_product.acos();
if radians { angle } else { angle.to_degrees() }
}
pub trait ToPosition {
fn to_position(self) -> DVec2;
}
impl ToPosition for DVec2 {
fn to_position(self) -> DVec2 {
self
}
}
impl ToPosition for DAffine2 {
fn to_position(self) -> DVec2 {
self.translation
}
}
/// Calculates the angle needed for a rightward-facing object placed at the observer position to turn so it points toward the target position.
#[node_macro::node(category("Math: Vector"))]
fn angle_to<T: ToPosition, U: ToPosition>(
_: impl Ctx,
/// The position from which the angle is measured.
#[implementations(DVec2, DAffine2, DVec2, DAffine2)]
observer: T,
/// The position toward which the angle is measured.
#[expose]
#[implementations(DVec2, DVec2, DAffine2, DAffine2)]
target: U,
/// Whether the resulting angle should be given in as radians instead of degrees.
radians: bool,
) -> f64 {
let from = observer.to_position();
let to = target.to_position();
let delta = to - from;
let angle = delta.y.atan2(delta.x);
if radians { angle } else { angle.to_degrees() }
}
// TODO: Rename to "Magnitude"
/// The magnitude operator (`‖x‖`) calculates the length of a vec2, which is the distance from the base to the tip of the arrow represented by the vector.
#[node_macro::node(category("Math: Vector"))]
fn length(_: impl Ctx, vector: DVec2) -> f64 {
vector.length()
}
/// Scales the input vector to unit length while preserving its direction. This is equivalent to dividing the input vector by its own magnitude.
///
/// Returns 0 when the input vector has zero length.
#[node_macro::node(category("Math: Vector"))]
fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
vector.normalize_or_zero()
}
#[cfg(test)]
mod test {
use super::*;
use core_types::Node;
use core_types::generic::FnNode;
#[test]
pub fn dot_product_function() {
let vector_a = DVec2::new(1., 2.);
let vector_b = DVec2::new(3., 4.);
assert_eq!(dot_product((), vector_a, vector_b, false), 11.);
}
#[test]
pub fn length_function() {
let vector = DVec2::new(3., 4.);
assert_eq!(length((), vector), 5.);
}
#[test]
fn test_basic_expression() {
let result = math((), 0., "2 + 2".to_string(), 0.);
assert_eq!(result, 4.);
}
#[test]
fn test_complex_expression() {
let result = math((), 0., "(5 * 3) + (10 / 2)".to_string(), 0.);
assert_eq!(result, 20.);
}
#[test]
fn test_default_expression() {
let result = math((), 0., "0".to_string(), 0.);
assert_eq!(result, 0.);
}
#[test]
fn test_invalid_expression() {
let result = math((), 0., "invalid".to_string(), 0.);
assert_eq!(result, 0.);
}
#[test]
pub fn foo() {
let fnn = FnNode::new(|(a, b)| (b, a));
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
}
#[test]
pub fn add_vectors() {
assert_eq!(super::add((), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.);
}
#[test]
pub fn subtract_f64() {
assert_eq!(super::subtract((), 5_f64, 3_f64), 2.);
}
#[test]
pub fn divide_vectors() {
assert_eq!(super::divide((), DVec2::ONE, 2_f64), DVec2::ONE / 2.);
}
#[test]
pub fn modulo_positive() {
assert_eq!(super::modulo((), -5_f64, 2_f64, true), 1_f64);
}
#[test]
pub fn modulo_negative() {
assert_eq!(super::modulo((), -5_f64, 2_f64, false), -1_f64);
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/graphic/src/lib.rs | node-graph/nodes/graphic/src/lib.rs | pub mod artboard;
pub mod graphic;
// Re-export all nodes
pub use artboard::*;
pub use graphic::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/graphic/src/artboard.rs | node-graph/nodes/graphic/src/artboard.rs | use core_types::{CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl, table::Table, transform::TransformMut};
use glam::{DAffine2, DVec2, IVec2};
use graphic_types::{
Artboard, Vector,
graphic::{Graphic, IntoGraphicTable},
};
use raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
/// Constructs a new single artboard table with the chosen properties.
#[node_macro::node(category(""))]
pub async fn create_artboard<T: IntoGraphicTable + 'n>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
/// Graphics to include within the artboard.
#[implementations(
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> Table<GradientStops>,
Context -> DAffine2,
)]
content: impl Node<Context<'static>, Output = T>,
/// Name of the artboard, shown in parts of the editor.
label: String,
/// Coordinate of the top-left corner of the artboard within the document.
location: DVec2,
/// Width and height of the artboard within the document. Only integers are valid.
dimensions: DVec2,
/// Color of the artboard background. Only positive integers are valid.
background: Table<Color>,
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
clip: bool,
) -> Table<Artboard> {
let location = location.as_ivec2();
let footprint = ctx.try_footprint().copied();
let mut new_ctx = OwnedContextImpl::from(ctx);
if let Some(mut footprint) = footprint {
footprint.translate(location.as_dvec2());
new_ctx = new_ctx.with_footprint(footprint);
}
let content = content.eval(new_ctx.into_context()).await.into_graphic_table();
let dimensions = dimensions.as_ivec2().max(IVec2::ONE);
let location = location.min(location + dimensions);
let dimensions = dimensions.abs();
let background: Option<Color> = background.into();
let background = background.unwrap_or(Color::WHITE);
Table::new_from_element(Artboard {
content,
label,
location,
dimensions,
background,
clip,
})
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/graphic/src/graphic.rs | node-graph/nodes/graphic/src/graphic.rs | use core_types::Color;
use core_types::Ctx;
use core_types::registry::types::SignedInteger;
use core_types::table::{Table, TableRow};
use core_types::uuid::NodeId;
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicTable};
use graphic_types::{Artboard, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
/// Performs internal editor record-keeping that enables tools to target this network's layer.
/// This node associates the ID of the network's parent layer to every element of output data.
/// This technical detail may be ignored by users, and will be phased out in the future.
#[node_macro::node(category(""))]
pub async fn source_node_id<I: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(
Table<Artboard>,
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
content: Table<I>,
node_path: Vec<NodeId>,
) -> Table<I> {
// Get the penultimate element of the node path, or None if the path is too short
// This is used to get the ID of the user-facing parent layer node (whose network contains this internal node).
let source_node_id = node_path.get(node_path.len().wrapping_sub(2)).copied();
let mut content = content;
for row in content.iter_mut() {
*row.source_node_id = source_node_id;
}
content
}
/// Joins two tables of the same type, extending the base table with the rows of the new table.
#[node_macro::node(category("General"))]
pub async fn extend<I: 'n + Send + Clone>(
_: impl Ctx,
/// The table whose rows will appear at the start of the extended table.
#[implementations(Table<Artboard>, Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Raster<GPU>>, Table<Color>, Table<GradientStops>)]
base: Table<I>,
/// The table whose rows will appear at the end of the extended table.
#[expose]
#[implementations(Table<Artboard>, Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Raster<GPU>>, Table<Color>, Table<GradientStops>)]
new: Table<I>,
) -> Table<I> {
let mut base = base;
base.extend(new);
base
}
// TODO: Eventually remove this document upgrade code
/// Performs an obsolete function as part of a migration from an older document format.
/// Users are advised to delete this node and replace it with a new one.
#[node_macro::node(category(""))]
pub async fn legacy_layer_extend<I: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(Table<Artboard>, Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Raster<GPU>>, Table<Color>, Table<GradientStops>)] base: Table<I>,
#[expose]
#[implementations(Table<Artboard>, Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Raster<GPU>>, Table<Color>, Table<GradientStops>)]
new: Table<I>,
nested_node_path: Vec<NodeId>,
) -> Table<I> {
// Get the penultimate element of the node path, or None if the path is too short
// This is used to get the ID of the user-facing parent layer-style node (which encapsulates this internal node).
let source_node_id = nested_node_path.get(nested_node_path.len().wrapping_sub(2)).copied();
let mut base = base;
for row in new.into_iter() {
base.push(TableRow { source_node_id, ..row });
}
base
}
/// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input.
/// The inverse of this node is 'Flatten Graphic'.
#[node_macro::node(category("General"))]
pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
_: impl Ctx,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
DAffine2,
)]
content: T,
) -> Table<Graphic> {
Table::new_from_element(content.into())
}
/// Converts a table of graphical content into a graphic table by placing it into an element of a new wrapper graphic table.
/// If it is already a graphic table, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
#[node_macro::node(category("General"))]
pub async fn to_graphic<T: IntoGraphicTable + 'n>(
_: impl Ctx,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
content: T,
) -> Table<Graphic> {
content.into_graphic_table()
}
/// Removes a level of nesting from a graphic table, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("General"))]
pub async fn flatten_graphic(_: impl Ctx, content: Table<Graphic>, fully_flatten: bool) -> Table<Graphic> {
// TODO: Avoid mutable reference, instead return a new Table<Graphic>?
fn flatten_table(output_graphic_table: &mut Table<Graphic>, current_graphic_table: Table<Graphic>, fully_flatten: bool, recursion_depth: usize) {
for current_row in current_graphic_table.iter() {
let current_element = current_row.element.clone();
let reference = *current_row.source_node_id;
let recurse = fully_flatten || recursion_depth == 0;
match current_element {
// If we're allowed to recurse, flatten any graphics we encounter
Graphic::Graphic(mut current_element) if recurse => {
// Apply the parent graphic's transform to all child elements
for graphic in current_element.iter_mut() {
*graphic.transform = *current_row.transform * *graphic.transform;
}
flatten_table(output_graphic_table, current_element, fully_flatten, recursion_depth + 1);
}
// Push any leaf Graphic elements we encounter, which can be either Graphic table elements beyond the recursion depth, or table elements other than Graphic tables
_ => {
output_graphic_table.push(TableRow {
element: current_element,
transform: *current_row.transform,
alpha_blending: *current_row.alpha_blending,
source_node_id: reference,
});
}
}
}
}
let mut output = Table::new();
flatten_table(&mut output, content, fully_flatten, 0);
output
}
/// Converts a graphic table into a vector table by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Vector"))]
pub async fn flatten_vector<I: IntoGraphicTable + 'n + Send + Clone>(_: impl Ctx, #[implementations(Table<Graphic>, Table<Vector>)] content: I) -> Table<Vector> {
content.into_flattened_vector_table()
}
/// Returns the value at the specified index in the collection.
/// If no value exists at that index, the type's default value is returned.
#[node_macro::node(category("General"))]
pub fn index_elements<T: graphic_types::graphic::AtIndex + Clone + Default>(
_: impl Ctx,
/// The collection of data, such as a list or table.
#[implementations(
Vec<f64>,
Vec<u32>,
Vec<u64>,
Vec<DVec2>,
Vec<String>,
Table<Artboard>,
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
collection: T,
/// The index of the item to retrieve, starting from 0 for the first item. Negative indices count backwards from the end of the collection, starting from -1 for the last item.
index: SignedInteger,
) -> T::Output
where
T::Output: Clone + Default,
{
let index = index as i32;
if index < 0 {
collection.at_index_from_end(-index as usize)
} else {
collection.at_index(index as usize)
}
.unwrap_or_default()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/gradient_map.rs | node-graph/nodes/raster/src/gradient_map.rs | //! Not immediately shader compatible due to needing [`GradientStops`] as a param, which needs [`Vec`]
use crate::adjust::Adjust;
use core_types::table::Table;
use core_types::{Color, Ctx};
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27grdm%27%20%3D%20Gradient%20Map
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Gradient%20settings%20(Photoshop%206.0)
#[node_macro::node(category("Raster: Adjustment"))]
async fn gradient_map<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
mut image: T,
gradient: GradientStops,
reverse: bool,
) -> T {
image.adjust(|color| {
let intensity = color.luminance_srgb();
let intensity = if reverse { 1. - intensity } else { intensity };
gradient.evaluate(intensity as f64).to_linear_srgb()
});
image
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/lib.rs | node-graph/nodes/raster/src/lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
pub mod adjust;
pub mod adjustments;
pub mod blending_nodes;
pub mod cubic_spline;
pub mod fullscreen_vertex;
/// required by shader macro
#[cfg(feature = "shader-nodes")]
pub use raster_nodes_shaders::WGSL_SHADER;
#[cfg(feature = "std")]
pub mod curve;
#[cfg(feature = "std")]
pub mod dehaze;
#[cfg(feature = "std")]
pub mod filter;
#[cfg(feature = "std")]
pub mod generate_curves;
#[cfg(feature = "std")]
pub mod gradient_map;
#[cfg(feature = "std")]
pub mod image_color_palette;
#[cfg(feature = "std")]
pub mod std_nodes;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/filter.rs | node-graph/nodes/raster/src/filter.rs | use core_types::color::Color;
use core_types::context::Ctx;
use core_types::registry::types::PixelLength;
use core_types::table::Table;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, Raster};
/// Blurs the image with a Gaussian or blur kernel filter.
#[node_macro::node(category("Raster: Filter"))]
async fn blur(
_: impl Ctx,
/// The image to be blurred.
image_frame: Table<Raster<CPU>>,
/// The radius of the blur kernel.
#[range((0., 100.))]
#[hard_min(0.)]
radius: PixelLength,
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
box_blur: bool,
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
gamma: bool,
) -> Table<Raster<CPU>> {
image_frame
.into_iter()
.map(|mut row| {
let image = row.element.clone();
// Run blur algorithm
let blurred_image = if radius < 0.1 {
// Minimum blur radius
image.clone()
} else if box_blur {
Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma))
} else {
Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma))
};
row.element = blurred_image;
row
})
.collect()
}
// 1D gaussian kernel
fn gaussian_kernel(radius: f64) -> Vec<f64> {
// Given radius, compute the size of the kernel that's approximately three times the radius
let kernel_radius = (3. * radius).ceil() as usize;
let kernel_size = 2 * kernel_radius + 1;
let mut gaussian_kernel: Vec<f64> = vec![0.; kernel_size];
// Kernel values
let two_radius_squared = 2. * radius * radius;
let sum = gaussian_kernel
.iter_mut()
.enumerate()
.map(|(i, value_at_index)| {
let x = i as f64 - kernel_radius as f64;
let exponent = -(x * x) / two_radius_squared;
*value_at_index = exponent.exp();
*value_at_index
})
.sum::<f64>();
// Normalize
gaussian_kernel.iter_mut().for_each(|value_at_index| *value_at_index /= sum);
gaussian_kernel
}
fn gaussian_blur_algorithm(mut original_buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
if gamma {
original_buffer.map_pixels(|px| px.to_gamma_srgb().to_associated_alpha(px.a()));
} else {
original_buffer.map_pixels(|px| px.to_associated_alpha(px.a()));
}
let (width, height) = original_buffer.dimensions();
// Create 1D gaussian kernel
let kernel = gaussian_kernel(radius);
let half_kernel = kernel.len() / 2;
// Intermediate buffer for horizontal and vertical passes
let mut x_axis = Image::new(width, height, Color::TRANSPARENT);
let mut y_axis = Image::new(width, height, Color::TRANSPARENT);
for pass in [false, true] {
let (max, old_buffer, current_buffer) = match pass {
false => (width, &original_buffer, &mut x_axis),
true => (height, &x_axis, &mut y_axis),
};
let pass = pass as usize;
for y in 0..height {
for x in 0..width {
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
for (i, &weight) in kernel.iter().enumerate() {
let p = [x, y][pass] as i32 + (i as i32 - half_kernel as i32);
if p >= 0
&& p < max as i32 && let Some(px) = old_buffer.get_pixel([p as u32, x][pass], [y, p as u32][pass])
{
r_sum += px.r() as f64 * weight;
g_sum += px.g() as f64 * weight;
b_sum += px.b() as f64 * weight;
a_sum += px.a() as f64 * weight;
weight_sum += weight;
}
}
// Normalize
let (r, g, b, a) = if weight_sum > 0. {
((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32)
} else {
let px = old_buffer.get_pixel(x, y).unwrap();
(px.r(), px.g(), px.b(), px.a())
};
current_buffer.set_pixel(x, y, Color::from_rgbaf32_unchecked(r, g, b, a));
}
}
}
if gamma {
y_axis.map_pixels(|px| px.to_linear_srgb().to_unassociated_alpha());
} else {
y_axis.map_pixels(|px| px.to_unassociated_alpha());
}
y_axis
}
fn box_blur_algorithm(mut original_buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
if gamma {
original_buffer.map_pixels(|px| px.to_gamma_srgb().to_associated_alpha(px.a()));
} else {
original_buffer.map_pixels(|px| px.to_associated_alpha(px.a()));
}
let (width, height) = original_buffer.dimensions();
let mut x_axis = Image::new(width, height, Color::TRANSPARENT);
let mut y_axis = Image::new(width, height, Color::TRANSPARENT);
for pass in [false, true] {
let (max, old_buffer, current_buffer) = match pass {
false => (width, &original_buffer, &mut x_axis),
true => (height, &x_axis, &mut y_axis),
};
let pass = pass as usize;
for y in 0..height {
for x in 0..width {
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
let i = [x, y][pass];
for d in (i as i32 - radius as i32).max(0)..=(i as i32 + radius as i32).min(max as i32 - 1) {
if let Some(px) = old_buffer.get_pixel([d as u32, x][pass], [y, d as u32][pass]) {
let weight = 1.;
r_sum += px.r() as f64 * weight;
g_sum += px.g() as f64 * weight;
b_sum += px.b() as f64 * weight;
a_sum += px.a() as f64 * weight;
weight_sum += weight;
}
}
let (r, g, b, a) = ((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32);
current_buffer.set_pixel(x, y, Color::from_rgbaf32_unchecked(r, g, b, a));
}
}
}
if gamma {
y_axis.map_pixels(|px| px.to_linear_srgb().to_unassociated_alpha());
} else {
y_axis.map_pixels(|px| px.to_unassociated_alpha());
}
y_axis
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/dehaze.rs | node-graph/nodes/raster/src/dehaze.rs | use core_types::context::Ctx;
use core_types::registry::types::Percentage;
use core_types::table::Table;
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
use raster_types::Image;
use raster_types::{CPU, Raster};
use std::cmp::{max, min};
#[node_macro::node(category("Raster: Filter"))]
async fn dehaze(_: impl Ctx, image_frame: Table<Raster<CPU>>, strength: Percentage) -> Table<Raster<CPU>> {
image_frame
.into_iter()
.map(|mut row| {
let image = row.element;
// Prepare the image data for processing
let image_data = bytemuck::cast_vec(image.data.clone());
let image_buffer = image::Rgba32FImage::from_raw(image.width, image.height, image_data).expect("Failed to convert internal image format into image-rs data type.");
let dynamic_image: DynamicImage = image_buffer.into();
// Run the dehaze algorithm
let dehazed_dynamic_image = dehaze_image(dynamic_image, strength / 100.);
// Prepare the image data for returning
let buffer = dehazed_dynamic_image.to_rgba32f().into_raw();
let color_vec = bytemuck::cast_vec(buffer);
let dehazed_image = Image {
width: image.width,
height: image.height,
data: color_vec,
base64_string: None,
};
row.element = Raster::new_cpu(dehazed_image);
row
})
.collect()
}
// There is no real point in modifying these values because they do not change the final result all that much.
// The authors of the paper recommended using these values to get a reasonable balance of performance and quality.
const PATCH_SIZE: u32 = 15;
const TOP_PERCENT: f64 = 0.001;
const RADIUS: u32 = 60;
const EPSILON: f64 = 0.0001;
const TX: f32 = 0.1;
// Dehazing algorithm based on "Single Image Haze Removal Using Dark Channel Prior"
// Paper: <https://www.researchgate.net/publication/220182411_Single_Image_Haze_Removal_Using_Dark_Channel_Prior>
// TODO: Make this algorithm work with negative strength values
fn dehaze_image(image: DynamicImage, strength: f64) -> DynamicImage {
// TODO: Break out this pair of steps into its own node, with a memoize node which caches the pair of outputs, so the strength can be adjusted without recomputing these two steps.
let dark_channel = compute_dark_channel(&image);
let atmospheric_light = estimate_atmospheric_light(&image, &dark_channel);
let transmission_map = estimate_transmission_map(&image, &dark_channel, strength);
let refined_transmission_map = refine_transmission_map(&image, &transmission_map);
recover(&image, &refined_transmission_map, atmospheric_light)
}
fn compute_dark_channel(image: &DynamicImage) -> DynamicImage {
let (width, height) = image.dimensions();
let mut dark_channel = GrayImage::new(width, height);
let half_patch = PATCH_SIZE / 2;
for y in 0..height {
for x in 0..width {
let pixel = image.get_pixel(x, y);
let min_intensity = min(min(pixel[0], pixel[1]), pixel[2]);
dark_channel.put_pixel(x, y, Luma([min_intensity]));
}
}
let mut eroded_channel = RgbaImage::new(width, height);
for y in 0..height {
for x in 0..width {
let mut local_min = u8::MAX;
for dy in 0..PATCH_SIZE {
for dx in 0..PATCH_SIZE {
let nx = x as i32 + dx as i32 - half_patch as i32;
let ny = y as i32 + dy as i32 - half_patch as i32;
if nx >= 0 && nx < width as i32 && ny >= 0 && ny < height as i32 {
let intensity = dark_channel.get_pixel(nx as u32, ny as u32)[0];
if intensity < local_min {
local_min = intensity;
}
}
}
}
let alpha = image.get_pixel(x, y)[3];
eroded_channel.put_pixel(x, y, Rgba([local_min, local_min, local_min, alpha]));
}
}
DynamicImage::ImageRgba8(eroded_channel)
}
fn estimate_atmospheric_light(hazy: &DynamicImage, dark_channel: &DynamicImage) -> Rgba<u8> {
let (width, height) = hazy.dimensions();
let dark = dark_channel.to_luma_alpha8();
let total_pixels = (width * height) as usize;
let num_pixels = ((TOP_PERCENT / 100.) * total_pixels as f64).ceil() as usize;
let mut intensities: Vec<(u32, u32, f64)> = Vec::with_capacity(total_pixels);
for y in 0..height {
for x in 0..width {
let pixel = dark.get_pixel(x, y);
let intensity = pixel.0[0] as f64;
intensities.push((x, y, intensity))
}
}
intensities.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap());
let top_intensities = &intensities[..num_pixels];
let mut atm_sum = [0., 0., 0.];
for (x, y, _) in top_intensities {
let pixel = hazy.get_pixel(*x, *y);
atm_sum[0] += pixel[0] as f64;
atm_sum[1] += pixel[1] as f64;
atm_sum[2] += pixel[2] as f64;
}
let num_pixels = num_pixels as f64;
Rgba([(atm_sum[0] / num_pixels) as u8, (atm_sum[1] / num_pixels) as u8, (atm_sum[2] / num_pixels) as u8, 255])
}
fn estimate_transmission_map(image: &DynamicImage, dark_channel: &DynamicImage, omega: f64) -> DynamicImage {
let (width, height) = image.dimensions();
let mut transmission_map = RgbaImage::new(width, height);
for y in 0..height {
for x in 0..width {
let min_intensity = dark_channel.get_pixel(x, y).0[0] as f32 / 255.;
let transmission_value = 1. - omega * min_intensity as f64;
let alpha = image.get_pixel(x, y)[3];
transmission_map.put_pixel(
x,
y,
Rgba([(transmission_value * 255.) as u8, (transmission_value * 255.) as u8, (transmission_value * 255.) as u8, alpha]),
);
}
}
DynamicImage::ImageRgba8(transmission_map)
}
fn refine_transmission_map(img: &DynamicImage, transmission_map: &DynamicImage) -> DynamicImage {
let gray_image = img.to_luma8();
let normalized_gray_image: GrayImage = ImageBuffer::from_fn(gray_image.width(), gray_image.height(), |x, y| {
let pixel = gray_image.get_pixel(x, y);
let normalized_value = (pixel[0] as f64 / 255.) * 255.;
Luma([normalized_value as u8])
});
let normalized_gray_image = DynamicImage::ImageLuma8(normalized_gray_image);
guided_filter(&normalized_gray_image, transmission_map, RADIUS, EPSILON)
}
fn recover(im: &DynamicImage, t: &DynamicImage, a: Rgba<u8>) -> DynamicImage {
let (width, height) = im.dimensions();
let mut res = DynamicImage::new_rgba8(width, height);
let a = [a[0] as f32 / 255., a[1] as f32 / 255., a[2] as f32 / 255.];
for y in 0..height {
for x in 0..width {
let im_pixel = im.get_pixel(x, y).0;
let t_pixel = t.get_pixel(x, y).0;
let t_val = f32::max(t_pixel[0] as f32 / 255., TX);
let mut res_pixel = [0; 4];
for ind in 0..3 {
res_pixel[ind] = ((((im_pixel[ind] as f32 / 255. - a[ind]) / t_val) + a[ind]).clamp(0., 1.) * 255.) as u8;
}
res_pixel[3] = im_pixel[3];
res.put_pixel(x, y, Rgba(res_pixel));
}
}
res
}
fn guided_filter(guidance_img: &DynamicImage, input_img: &DynamicImage, r: u32, epsilon: f64) -> DynamicImage {
let (width, height) = guidance_img.dimensions();
let radius = r as i32;
let guidance_nd = image_to_ndarray(guidance_img);
let input_nd = image_to_ndarray(input_img);
let mean_guidance = box_filter(&guidance_nd, radius);
let mean_input = box_filter(&input_nd, radius);
let corr_guidance = box_filter(&(guidance_nd.clone() * guidance_nd.clone()), radius);
let corr_guidance_input = box_filter(&(guidance_nd.clone() * input_nd.clone()), radius);
let var_guidance = &corr_guidance - &(mean_guidance.clone() * mean_guidance.clone());
let cov_guidance_input = &corr_guidance_input - &(mean_guidance.clone() * mean_input.clone());
let a = &cov_guidance_input / &(var_guidance.clone() + epsilon);
let b = mean_input - &(a.clone() * mean_guidance);
let mean_a = box_filter(&a, radius);
let mean_b = box_filter(&b, radius);
let q = &mean_a * &guidance_nd + mean_b;
ndarray_to_image(&q, width, height)
}
fn box_filter(img: &Array2<f64>, radius: i32) -> Array2<f64> {
let (height, width) = img.dim();
let mut result = Array2::zeros((height, width));
let mut integral_image: ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>> = Array2::zeros((height + 1, width + 1));
// Compute integral image
for y in 0..height {
for x in 0..width {
integral_image[(y + 1, x + 1)] = img[(y, x)] + integral_image[(y, x + 1)] + integral_image[(y + 1, x)] - integral_image[(y, x)];
}
}
for y in 0..height {
for x in 0..width {
let y1 = max(0, y as i32 - radius) as usize;
let y2 = min(height as i32 - 1, y as i32 + radius) as usize;
let x1 = max(0, x as i32 - radius) as usize;
let x2 = min(width as i32 - 1, x as i32 + radius) as usize;
let area = (y2 - y1 + 1) as f64 * (x2 - x1 + 1) as f64;
result[(y, x)] = (integral_image[(y2 + 1, x2 + 1)] - integral_image[(y1, x2 + 1)] - integral_image[(y2 + 1, x1)] + integral_image[(y1, x1)]) / area;
}
}
result
}
fn image_to_ndarray(img: &DynamicImage) -> Array2<f64> {
let (width, height) = img.dimensions();
let mut array = Array2::zeros((height as usize, width as usize));
for (x, y, pixel) in img.pixels() {
let luminance = pixel.0[0] as f64 / 255.;
array[(y as usize, x as usize)] = luminance;
}
array
}
fn ndarray_to_image(array: &Array2<f64>, width: u32, height: u32) -> DynamicImage {
let mut img = DynamicImage::new_rgba8(width, height);
for ((y, x), &value) in array.indexed_iter() {
let clamped_value = (value * 255.).clamp(0., 255.) as u8;
img.put_pixel(x as u32, y as u32, Rgba([clamped_value, clamped_value, clamped_value, 255]));
}
img
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/std_nodes.rs | node-graph/nodes/raster/src/std_nodes.rs | use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use core_types::blending::AlphaBlending;
use core_types::color::Color;
use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut};
use core_types::context::{Ctx, ExtractFootprint};
use core_types::math::bbox::Bbox;
use core_types::table::{Table, TableRow};
use core_types::transform::Transform;
use dyn_any::DynAny;
use fastnoise_lite;
use glam::{DAffine2, DVec2, Vec2};
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use raster_types::Image;
use raster_types::{Bitmap, BitmapMut};
use raster_types::{CPU, Raster};
use std::fmt::Debug;
use std::hash::Hash;
#[derive(Debug, DynAny)]
pub enum Error {
IO(std::io::Error),
Image(::image::ImageError),
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IO(e)
}
}
#[node_macro::node(category("Debug: Raster"))]
pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Table<Raster<CPU>>) -> Table<Raster<CPU>> {
image_frame
.into_iter()
.filter_map(|mut row| {
let image_frame_transform = row.transform;
let image = row.element;
// Resize the image using the image crate
let data = bytemuck::cast_vec(image.data.clone());
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = Bbox::from_transform(image_frame_transform).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
let image_size = DAffine2::from_scale(DVec2::new(image.width as f64, image.height as f64));
let size = intersection.size();
let size_px = image_size.transform_vector2(size).as_uvec2();
// If the image would not be visible, add nothing.
if size.x <= 0. || size.y <= 0. {
return None;
}
let image_buffer = ::image::Rgba32FImage::from_raw(image.width, image.height, data).expect("Failed to convert internal image format into image-rs data type.");
let dynamic_image: ::image::DynamicImage = image_buffer.into();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
let offset_px = image_size.transform_vector2(offset).as_uvec2();
let cropped = dynamic_image.crop_imm(offset_px.x, offset_px.y, size_px.x, size_px.y);
let viewport_resolution_x = footprint.transform.transform_vector2(DVec2::X * size.x).length();
let viewport_resolution_y = footprint.transform.transform_vector2(DVec2::Y * size.y).length();
let mut new_width = size_px.x;
let mut new_height = size_px.y;
// Only downscale the image for now
let resized = if new_width < image.width || new_height < image.height {
new_width = viewport_resolution_x as u32;
new_height = viewport_resolution_y as u32;
// TODO: choose filter based on quality requirements
cropped.resize_exact(new_width, new_height, ::image::imageops::Triangle)
} else {
cropped
};
let buffer = resized.to_rgba32f();
let buffer = buffer.into_raw();
let vec = bytemuck::cast_vec(buffer);
let image = Image {
width: new_width,
height: new_height,
data: vec,
base64_string: None,
};
// we need to adjust the offset if we truncate the offset calculation
let new_transform = image_frame_transform * DAffine2::from_translation(offset) * DAffine2::from_scale(size);
row.transform = new_transform;
row.element = Raster::new_cpu(image);
Some(row)
})
.collect()
}
#[node_macro::node(category("Raster: Channels"))]
pub fn combine_channels(
_: impl Ctx,
_primary: (),
#[expose] red: Table<Raster<CPU>>,
#[expose] green: Table<Raster<CPU>>,
#[expose] blue: Table<Raster<CPU>>,
#[expose] alpha: Table<Raster<CPU>>,
) -> Table<Raster<CPU>> {
let max_len = red.len().max(green.len()).max(blue.len()).max(alpha.len());
let red = red.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let green = green.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let blue = blue.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
let alpha = alpha.into_iter().map(Some).chain(std::iter::repeat(None)).take(max_len);
red.zip(green)
.zip(blue)
.zip(alpha)
.filter_map(|(((red, green), blue), alpha)| {
// Turn any default zero-sized image rows into None
let red = red.filter(|i| i.element.width > 0 && i.element.height > 0);
let green = green.filter(|i| i.element.width > 0 && i.element.height > 0);
let blue = blue.filter(|i| i.element.width > 0 && i.element.height > 0);
let alpha = alpha.filter(|i| i.element.width > 0 && i.element.height > 0);
// Get this row's transform and alpha blending mode from the first non-empty channel
let (transform, alpha_blending, source_node_id) = [&red, &green, &blue, &alpha]
.iter()
.find_map(|i| i.as_ref())
.map(|i| (i.transform, i.alpha_blending, i.source_node_id))?;
// Get the common width and height of the channels, which must have equal dimensions
let channel_dimensions = [
red.as_ref().map(|r| (r.element.width, r.element.height)),
green.as_ref().map(|g| (g.element.width, g.element.height)),
blue.as_ref().map(|b| (b.element.width, b.element.height)),
alpha.as_ref().map(|a| (a.element.width, a.element.height)),
];
if channel_dimensions.iter().all(Option::is_none)
|| channel_dimensions
.iter()
.flatten()
.any(|&(x, y)| channel_dimensions.iter().flatten().any(|&(other_x, other_y)| x != other_x || y != other_y))
{
return None;
}
let &(width, height) = channel_dimensions.iter().flatten().next()?;
// Create a new image for the output element
let mut image = Image::new(width, height, Color::TRANSPARENT);
// Iterate over all pixels in the image and set the color channels
for y in 0..image.height() {
for x in 0..image.width() {
let image_pixel = image.get_pixel_mut(x, y).unwrap();
if let Some(r) = red.as_ref().and_then(|r| r.element.get_pixel(x, y)) {
image_pixel.set_red(r.l().cast_linear_channel());
} else {
image_pixel.set_red(Channel::from_linear(0.));
}
if let Some(g) = green.as_ref().and_then(|g| g.element.get_pixel(x, y)) {
image_pixel.set_green(g.l().cast_linear_channel());
} else {
image_pixel.set_green(Channel::from_linear(0.));
}
if let Some(b) = blue.as_ref().and_then(|b| b.element.get_pixel(x, y)) {
image_pixel.set_blue(b.l().cast_linear_channel());
} else {
image_pixel.set_blue(Channel::from_linear(0.));
}
if let Some(a) = alpha.as_ref().and_then(|a| a.element.get_pixel(x, y)) {
image_pixel.set_alpha(a.l().cast_linear_channel());
} else {
image_pixel.set_alpha(Channel::from_linear(1.));
}
}
}
Some(TableRow {
element: Raster::new_cpu(image),
transform,
alpha_blending,
source_node_id,
})
})
.collect()
}
#[node_macro::node(category("Raster"))]
pub fn mask(
_: impl Ctx,
/// The image to be masked.
image: Table<Raster<CPU>>,
/// The stencil to be used for masking.
#[expose]
stencil: Table<Raster<CPU>>,
) -> Table<Raster<CPU>> {
// TODO: Figure out what it means to support multiple stencil rows?
let Some(stencil) = stencil.into_iter().next() else {
// No stencil provided so we return the original image
return image;
};
let stencil_size = DVec2::new(stencil.element.width as f64, stencil.element.height as f64);
image
.into_iter()
.filter_map(|mut row| {
let image_size = DVec2::new(row.element.width as f64, row.element.height as f64);
let mask_size = stencil.transform.decompose_scale();
if mask_size == DVec2::ZERO {
return None;
}
// Transforms a point from the background image to the foreground image
let bg_to_fg = row.transform * DAffine2::from_scale(1. / image_size);
let stencil_transform_inverse = stencil.transform.inverse();
for y in 0..row.element.height {
for x in 0..row.element.width {
let image_point = DVec2::new(x as f64, y as f64);
let mask_point = bg_to_fg.transform_point2(image_point);
let local_mask_point = stencil_transform_inverse.transform_point2(mask_point);
let mask_point = stencil.transform.transform_point2(local_mask_point.clamp(DVec2::ZERO, DVec2::ONE));
let mask_point = (DAffine2::from_scale(stencil_size) * stencil.transform.inverse()).transform_point2(mask_point);
let image_pixel = row.element.data_mut().get_pixel_mut(x, y).unwrap();
let mask_pixel = stencil.element.sample(mask_point);
*image_pixel = image_pixel.multiplied_alpha(mask_pixel.l().cast_linear_channel());
}
}
Some(row)
})
.collect()
}
#[node_macro::node(category(""))]
pub fn extend_image_to_bounds(_: impl Ctx, image: Table<Raster<CPU>>, bounds: DAffine2) -> Table<Raster<CPU>> {
image
.into_iter()
.map(|mut row| {
let image_aabb = Bbox::unit().affine_transform(row.transform).to_axis_aligned_bbox();
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
return row;
}
let image_data = &row.element.data;
let (image_width, image_height) = (row.element.width, row.element.height);
if image_width == 0 || image_height == 0 {
return empty_image((), bounds, Table::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap();
}
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * row.transform.inverse();
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
let new_scale = new_end - new_start;
// Copy over original image into enlarged image.
let mut new_image = Image::new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT);
let offset_in_new_image = (-new_start).as_uvec2();
for y in 0..image_height {
let old_start = y * image_width;
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
let old_row = &image_data[old_start as usize..(old_start + image_width) as usize];
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
new_row.copy_from_slice(old_row);
}
// Compute new transform.
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
let new_texture_to_layer_space = row.transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
row.element = Raster::new_cpu(new_image);
row.transform = new_texture_to_layer_space;
row
})
.collect()
}
#[node_macro::node(category("Debug: Raster"))]
pub fn empty_image(_: impl Ctx, transform: DAffine2, color: Table<Color>) -> Table<Raster<CPU>> {
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
let color: Option<Color> = color.into();
let image = Image::new(width, height, color.unwrap_or(Color::WHITE));
let mut result_table = Table::new_from_element(Raster::new_cpu(image));
let row = result_table.get_mut(0).unwrap();
*row.transform = transform;
*row.alpha_blending = AlphaBlending::default();
// Callers of empty_image can safely unwrap on returned table
result_table
}
#[node_macro::node(category(""))]
pub fn image_value(_: impl Ctx, _primary: (), image: Table<Raster<CPU>>) -> Table<Raster<CPU>> {
image
}
#[node_macro::node(category("Raster: Pattern"))]
#[allow(clippy::too_many_arguments)]
pub fn noise_pattern(
ctx: impl ExtractFootprint + Ctx,
_primary: (),
clip: bool,
seed: u32,
scale: f64,
noise_type: NoiseType,
domain_warp_type: DomainWarpType,
domain_warp_amplitude: f64,
fractal_type: FractalType,
fractal_octaves: u32,
fractal_lacunarity: f64,
fractal_gain: f64,
fractal_weighted_strength: f64,
fractal_ping_pong_strength: f64,
cellular_distance_function: CellularDistanceFunction,
cellular_return_type: CellularReturnType,
cellular_jitter: f64,
) -> Table<Raster<CPU>> {
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let mut size = viewport_bounds.size();
let mut offset = viewport_bounds.start;
if clip {
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
const CLIPPING_SQUARE_SIZE: f64 = 100.;
let image_bounds = Bbox::from_transform(DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE))).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
size = intersection.size();
}
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Table::new();
}
let footprint_scale = footprint.scale();
let width = (size.x * footprint_scale.x) as u32;
let height = (size.y * footprint_scale.y) as u32;
// All
let mut image = Image::new(width, height, Color::from_luminance(0.5));
let mut noise = fastnoise_lite::FastNoiseLite::with_seed(seed as i32);
noise.set_frequency(Some(1. / (scale as f32).max(f32::EPSILON)));
// Domain Warp
let domain_warp_type = match domain_warp_type {
DomainWarpType::None => None,
DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2),
DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced),
DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid),
};
let domain_warp_active = domain_warp_type.is_some();
noise.set_domain_warp_type(domain_warp_type);
noise.set_domain_warp_amp(Some(domain_warp_amplitude as f32));
// Fractal
let noise_type = match noise_type {
NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin,
NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2,
NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S,
NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular,
NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic,
NoiseType::Value => fastnoise_lite::NoiseType::Value,
NoiseType::WhiteNoise => {
// TODO: Generate in layer space, not viewport space
let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
for y in 0..height {
for x in 0..width {
let pixel = image.get_pixel_mut(x, y).unwrap();
let luminance = rng.random_range(0.0..1.) as f32;
*pixel = Color::from_luminance(luminance);
}
}
return Table::new_from_row(TableRow {
element: Raster::new_cpu(image),
transform: DAffine2::from_translation(offset) * DAffine2::from_scale(size),
..Default::default()
});
}
};
noise.set_noise_type(Some(noise_type));
let fractal_type = match fractal_type {
FractalType::None => fastnoise_lite::FractalType::None,
FractalType::FBm => fastnoise_lite::FractalType::FBm,
FractalType::Ridged => fastnoise_lite::FractalType::Ridged,
FractalType::PingPong => fastnoise_lite::FractalType::PingPong,
FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive,
FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent,
};
noise.set_fractal_type(Some(fractal_type));
noise.set_fractal_octaves(Some(fractal_octaves as i32));
noise.set_fractal_lacunarity(Some(fractal_lacunarity as f32));
noise.set_fractal_gain(Some(fractal_gain as f32));
noise.set_fractal_weighted_strength(Some(fractal_weighted_strength as f32));
noise.set_fractal_ping_pong_strength(Some(fractal_ping_pong_strength as f32));
// Cellular
let cellular_distance_function = match cellular_distance_function {
CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean,
CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq,
CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan,
CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid,
};
let cellular_return_type = match cellular_return_type {
CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue,
CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance,
CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2,
CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add,
CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub,
CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul,
CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div,
};
noise.set_cellular_distance_function(Some(cellular_distance_function));
noise.set_cellular_return_type(Some(cellular_return_type));
noise.set_cellular_jitter(Some(cellular_jitter as f32));
let coordinate_offset = offset.as_vec2();
let scale = size.as_vec2() / Vec2::new(width as f32, height as f32);
// Calculate the noise for every pixel
for y in 0..height {
for x in 0..width {
let pixel = image.get_pixel_mut(x, y).unwrap();
let pos = Vec2::new(x as f32, y as f32);
let vec = pos * scale + coordinate_offset;
let (mut x, mut y) = (vec.x, vec.y);
if domain_warp_active && domain_warp_amplitude > 0. {
(x, y) = noise.domain_warp_2d(x, y);
}
let luminance = (noise.get_noise_2d(x, y) + 1.) * 0.5;
*pixel = Color::from_luminance(luminance);
}
}
Table::new_from_row(TableRow {
element: Raster::new_cpu(image),
transform: DAffine2::from_translation(offset) * DAffine2::from_scale(size),
..Default::default()
})
}
#[node_macro::node(category("Raster: Pattern"))]
pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Table<Raster<CPU>> {
let footprint = ctx.footprint();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
let intersection = viewport_bounds.intersect(&image_bounds);
let size = intersection.size();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Table::new();
}
let scale = footprint.scale();
let width = (size.x * scale.x) as u32;
let height = (size.y * scale.y) as u32;
let mut data = Vec::with_capacity(width as usize * height as usize);
let max_iter = 255;
let scale = 3. * size.as_vec2() / Vec2::new(width as f32, height as f32);
let coordinate_offset = offset.as_vec2() * 3. - Vec2::new(2., 1.5);
for y in 0..height {
for x in 0..width {
let pos = Vec2::new(x as f32, y as f32);
let c = pos * scale + coordinate_offset;
let iter = mandelbrot_impl(c, max_iter);
data.push(map_color(iter, max_iter));
}
}
Table::new_from_row(TableRow {
element: Raster::new_cpu(Image {
width,
height,
data,
..Default::default()
}),
transform: DAffine2::from_translation(offset) * DAffine2::from_scale(size),
..Default::default()
})
}
#[inline(always)]
fn mandelbrot_impl(c: Vec2, max_iter: usize) -> usize {
let mut z = Vec2::new(0., 0.);
for i in 0..max_iter {
z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
if z.length_squared() > 4. {
return i;
}
}
max_iter
}
fn map_color(iter: usize, max_iter: usize) -> Color {
let v = iter as f32 / max_iter as f32;
Color::from_rgbaf32_unchecked(v, v, v, 1.)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/curve.rs | node-graph/nodes/raster/src/curve.rs | use core_types::Node;
use core_types::color::{Channel, Linear, LuminanceMut};
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use std::hash::{Hash, Hasher};
use std::ops::{Add, Mul, Sub};
#[derive(Debug, Clone, PartialEq, DynAny, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct Curve {
#[serde(rename = "manipulatorGroups")]
pub manipulator_groups: Vec<CurveManipulatorGroup>,
#[serde(rename = "firstHandle")]
pub first_handle: [f32; 2],
#[serde(rename = "lastHandle")]
pub last_handle: [f32; 2],
}
impl Default for Curve {
fn default() -> Self {
Self {
manipulator_groups: vec![],
first_handle: [0.2; 2],
last_handle: [0.8; 2],
}
}
}
impl Hash for Curve {
fn hash<H: Hasher>(&self, state: &mut H) {
self.manipulator_groups.hash(state);
[self.first_handle, self.last_handle].iter().flatten().for_each(|f| f.to_bits().hash(state));
}
}
#[derive(Debug, Clone, Copy, PartialEq, DynAny, specta::Type, serde::Serialize, serde::Deserialize)]
pub struct CurveManipulatorGroup {
pub anchor: [f32; 2],
pub handles: [[f32; 2]; 2],
}
impl Hash for CurveManipulatorGroup {
fn hash<H: Hasher>(&self, state: &mut H) {
for c in self.handles.iter().chain([&self.anchor]).flatten() {
c.to_bits().hash(state);
}
}
}
pub struct ValueMapperNode<C> {
lut: Vec<C>,
}
unsafe impl<C: StaticTypeSized> StaticType for ValueMapperNode<C> {
type Static = ValueMapperNode<C::Static>;
}
impl<C> ValueMapperNode<C> {
pub const fn new(lut: Vec<C>) -> Self {
Self { lut }
}
}
impl<'i, L: LuminanceMut + 'i> Node<'i, L> for ValueMapperNode<L::LuminanceChannel>
where
L::LuminanceChannel: Linear + Copy,
L::LuminanceChannel: Add<Output = L::LuminanceChannel>,
L::LuminanceChannel: Sub<Output = L::LuminanceChannel>,
L::LuminanceChannel: Mul<Output = L::LuminanceChannel>,
{
type Output = L;
fn eval(&'i self, mut val: L) -> L {
let luminance: f32 = val.luminance().to_linear();
let floating_sample_index = luminance * (self.lut.len() - 1) as f32;
let index_in_lut = floating_sample_index.floor() as usize;
let a = self.lut[index_in_lut];
let b = self.lut[(index_in_lut + 1).clamp(0, self.lut.len() - 1)];
let result = a.lerp(b, L::LuminanceChannel::from_linear(floating_sample_index.fract()));
val.set_luminance(result);
val
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/fullscreen_vertex.rs | node-graph/nodes/raster/src/fullscreen_vertex.rs | use glam::{Vec2, Vec4};
use spirv_std::spirv;
/// webgpu NDC is like OpenGL: (-1.0 .. 1.0, -1.0 .. 1.0, 0.0 .. 1.0)
/// https://www.w3.org/TR/webgpu/#coordinate-systems
///
/// So to make a fullscreen triangle around a box at (-1..1):
///
/// ```text
/// 3 +
/// |\
/// 2 | \
/// | \
/// 1 +-----+
/// | |\
/// 0 | 0 | \
/// | | \
/// -1 +-----+-----+
/// -1 0 1 2 3
/// ```
const FULLSCREEN_VERTICES: [Vec2; 3] = [Vec2::new(-1., -1.), Vec2::new(-1., 3.), Vec2::new(3., -1.)];
#[spirv(vertex)]
pub fn fullscreen_vertex(#[spirv(vertex_index)] vertex_index: u32, #[spirv(position)] gl_position: &mut Vec4) {
// broken on edition 2024 branch
// let vertex = unsafe { *FULLSCREEN_VERTICES.index_unchecked(vertex_index as usize) };
let vertex = FULLSCREEN_VERTICES[vertex_index as usize];
*gl_position = Vec4::from((vertex, 0., 1.));
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/cubic_spline.rs | node-graph/nodes/raster/src/cubic_spline.rs | #[derive(Debug)]
pub struct CubicSplines {
pub x: [f32; 4],
pub y: [f32; 4],
}
impl CubicSplines {
pub fn solve(&self) -> [f32; 4] {
let (x, y) = (&self.x, &self.y);
// Build an augmented matrix to solve the system of equations using Gaussian elimination
let mut augmented_matrix = [
[
2. / (x[1] - x[0]),
1. / (x[1] - x[0]),
0.,
0.,
// |
3. * (y[1] - y[0]) / ((x[1] - x[0]) * (x[1] - x[0])),
],
[
1. / (x[1] - x[0]),
2. * (1. / (x[1] - x[0]) + 1. / (x[2] - x[1])),
1. / (x[2] - x[1]),
0.,
// |
3. * ((y[1] - y[0]) / ((x[1] - x[0]) * (x[1] - x[0])) + (y[2] - y[1]) / ((x[2] - x[1]) * (x[2] - x[1]))),
],
[
0.,
1. / (x[2] - x[1]),
2. * (1. / (x[2] - x[1]) + 1. / (x[3] - x[2])),
1. / (x[3] - x[2]),
// |
3. * ((y[2] - y[1]) / ((x[2] - x[1]) * (x[2] - x[1])) + (y[3] - y[2]) / ((x[3] - x[2]) * (x[3] - x[2]))),
],
[
0.,
0.,
1. / (x[3] - x[2]),
2. / (x[3] - x[2]),
// |
3. * (y[3] - y[2]) / ((x[3] - x[2]) * (x[3] - x[2])),
],
];
// Gaussian elimination: forward elimination
for row in 0..4 {
let pivot_row_index = (row..4)
.max_by(|&a_row, &b_row| {
augmented_matrix[a_row][row]
.abs()
.partial_cmp(&augmented_matrix[b_row][row].abs())
.unwrap_or(core::cmp::Ordering::Equal)
})
.unwrap();
// Swap the current row with the row that has the largest pivot element
augmented_matrix.swap(row, pivot_row_index);
// Eliminate the current column in all rows below the current one
for row_below_current in row + 1..4 {
assert!(augmented_matrix[row][row].abs() > f32::EPSILON);
let scale_factor = augmented_matrix[row_below_current][row] / augmented_matrix[row][row];
for col in row..5 {
augmented_matrix[row_below_current][col] -= augmented_matrix[row][col] * scale_factor
}
}
}
// Gaussian elimination: back substitution
let mut solutions = [0.; 4];
for col in (0..4).rev() {
assert!(augmented_matrix[col][col].abs() > f32::EPSILON);
solutions[col] = augmented_matrix[col][4] / augmented_matrix[col][col];
for row in (0..col).rev() {
augmented_matrix[row][4] -= augmented_matrix[row][col] * solutions[col];
augmented_matrix[row][col] = 0.;
}
}
solutions
}
pub fn interpolate(&self, input: f32, solutions: &[f32]) -> f32 {
if input <= self.x[0] {
return self.y[0];
}
if input >= self.x[self.x.len() - 1] {
return self.y[self.x.len() - 1];
}
// Find the segment that the input falls between
let mut segment = 1;
while self.x[segment] < input {
segment += 1;
}
let segment_start = segment - 1;
let segment_end = segment;
// Calculate the output value using quadratic interpolation
let input_value = self.x[segment_start];
let input_value_prev = self.x[segment_end];
let output_value = self.y[segment_start];
let output_value_prev = self.y[segment_end];
let solutions_value = solutions[segment_start];
let solutions_value_prev = solutions[segment_end];
let output_delta = solutions_value_prev * (input_value - input_value_prev) - (output_value - output_value_prev);
let solution_delta = (output_value - output_value_prev) - solutions_value * (input_value - input_value_prev);
let input_ratio = (input - input_value_prev) / (input_value - input_value_prev);
let prev_output_ratio = (1. - input_ratio) * output_value_prev;
let output_ratio = input_ratio * output_value;
let quadratic_ratio = input_ratio * (1. - input_ratio) * (output_delta * (1. - input_ratio) + solution_delta * input_ratio);
let result = prev_output_ratio + output_ratio + quadratic_ratio;
result.clamp(0., 1.)
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/adjustments.rs | node-graph/nodes/raster/src/adjustments.rs | #![allow(clippy::too_many_arguments)]
use crate::adjust::Adjust;
use crate::cubic_spline::CubicSplines;
use core::fmt::Debug;
#[cfg(feature = "std")]
use core_types::table::Table;
use glam::{Vec3, Vec4};
use no_std_types::color::Color;
use no_std_types::context::Ctx;
use no_std_types::registry::types::{AngleF32, PercentageF32, SignedPercentageF32};
use node_macro::BufferStruct;
use num_enum::{FromPrimitive, IntoPrimitive};
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::GradientStops;
// TODO: Implement the following:
// Color Balance
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27blnc%27%20%3D%20Color%20Balance
//
// Photo Filter
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27phfl%27%20%3D%20Photo%20Filter
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=of%20the%20file.-,Photo%20Filter,-Key%20is%20%27phfl
//
// Color Lookup
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27clrL%27%20%3D%20Color%20Lookup
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Color%20Lookup%20(Photoshop%20CS6
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, node_macro::ChoiceType, bytemuck::NoUninit, BufferStruct, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Dropdown)]
#[repr(u32)]
pub enum LuminanceCalculation {
#[default]
#[label("sRGB")]
SRGB,
Perceptual,
AverageChannels,
MinimumChannels,
MaximumChannels,
}
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn luminance<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
luminance_calc: LuminanceCalculation,
) -> T {
input.adjust(|color| {
let luminance = match luminance_calc {
LuminanceCalculation::SRGB => color.luminance_srgb(),
LuminanceCalculation::Perceptual => color.luminance_perceptual(),
LuminanceCalculation::AverageChannels => color.average_rgb_channels(),
LuminanceCalculation::MinimumChannels => color.minimum_rgb_channels(),
LuminanceCalculation::MaximumChannels => color.maximum_rgb_channels(),
};
color.map_rgb(|_| luminance)
});
input
}
#[node_macro::node(category("Raster"), shader_node(PerPixelAdjust))]
fn gamma_correction<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
#[default(2.2)]
#[range((0.01, 10.))]
#[hard_min(0.0001)]
gamma: f32,
inverse: bool,
) -> T {
let exponent = if inverse { 1. / gamma } else { gamma };
input.adjust(|color| color.gamma(exponent));
input
}
#[node_macro::node(category("Raster: Channels"), shader_node(PerPixelAdjust))]
fn extract_channel<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
channel: RedGreenBlueAlpha,
) -> T {
input.adjust(|color| {
let extracted_value = match channel {
RedGreenBlueAlpha::Red => color.r(),
RedGreenBlueAlpha::Green => color.g(),
RedGreenBlueAlpha::Blue => color.b(),
RedGreenBlueAlpha::Alpha => color.a(),
};
color.map_rgb(|_| extracted_value).with_alpha(1.)
});
input
}
#[node_macro::node(category("Raster: Channels"), shader_node(PerPixelAdjust))]
fn make_opaque<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
if color.a() == 0. {
return color.with_alpha(1.);
}
Color::from_rgbaf32_unchecked(color.r() / color.a(), color.g() / color.a(), color.b() / color.a(), 1.)
});
input
}
// TODO: Remove this once GPU shader nodes are able to support the non-classic algorithm
#[node_macro::node(
name("Brightness/Contrast Classic"),
category("Raster: Adjustment"),
properties("brightness_contrast_properties"),
shader_node(PerPixelAdjust)
)]
fn brightness_contrast_classic<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
) -> T {
let brightness = brightness / 255.;
let contrast = contrast / 100.;
let contrast = if contrast > 0. { (contrast * core::f32::consts::FRAC_PI_2 - 0.01).tan() } else { contrast };
let offset = brightness * contrast + brightness - contrast / 2.;
input.adjust(|color| color.to_gamma_srgb().map_rgb(|c| (c + c * contrast + offset).clamp(0., 1.)).to_linear_srgb());
input
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27brit%27%20%3D%20Brightness/Contrast
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Padding-,Brightness%20and%20Contrast,-Key%20is%20%27brit
//
// Some further analysis available at:
// https://geraldbakker.nl/psnumbers/brightness-contrast.html
#[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), properties("brightness_contrast_properties"), cfg(feature = "std"))]
fn brightness_contrast<T: Adjust<Color>>(
_ctx: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
brightness: SignedPercentageF32,
contrast: SignedPercentageF32,
use_classic: bool,
) -> T {
if use_classic {
return brightness_contrast_classic(_ctx, input, brightness, contrast);
}
const WINDOW_SIZE: usize = 1024;
// Brightness LUT
let brightness_is_negative = brightness < 0.;
// We clamp the brightness before the two curve X-axis points `130 - brightness * 26` and `233 - brightness * 48` intersect.
// Beyond the point of intersection, the cubic spline fitting becomes invalid and fails an assertion, which we need to avoid.
// See the intersection of the red lines at x = 103/22*100 = 468.18182 in the graph: https://www.desmos.com/calculator/ekvz4zyd9c
let brightness = (brightness.abs() / 100.).min(103. / 22. - 0.00001);
let brightness_curve_points = CubicSplines {
x: [0., 130. - brightness * 26., 233. - brightness * 48., 255.].map(|x| x / 255.),
y: [0., 130. + brightness * 51., 233. + brightness * 10., 255.].map(|x| x / 255.),
};
let brightness_curve_solutions = brightness_curve_points.solve();
let mut brightness_lut: [f32; WINDOW_SIZE] = core::array::from_fn(|i| {
let x = i as f32 / (WINDOW_SIZE as f32 - 1.);
brightness_curve_points.interpolate(x, &brightness_curve_solutions)
});
// Special handling for when brightness is negative
if brightness_is_negative {
brightness_lut = core::array::from_fn(|i| {
let mut x = i;
while x > 1 && brightness_lut[x] > i as f32 / WINDOW_SIZE as f32 {
x -= 1;
}
x as f32 / WINDOW_SIZE as f32
});
}
// Contrast LUT
// Unlike with brightness, the X-axis points `64` and `192` don't intersect at any contrast value, because they are constants.
// So we don't have to worry about clamping the contrast value to avoid invalid cubic spline fitting.
// See the graph: https://www.desmos.com/calculator/iql9vsca56
let contrast = contrast / 100.;
let contrast_curve_points = CubicSplines {
x: [0., 64., 192., 255.].map(|x| x / 255.),
y: [0., 64. - contrast * 30., 192. + contrast * 30., 255.].map(|x| x / 255.),
};
let contrast_curve_solutions = contrast_curve_points.solve();
let contrast_lut: [f32; WINDOW_SIZE] = core::array::from_fn(|i| {
let x = i as f32 / (WINDOW_SIZE as f32 - 1.);
contrast_curve_points.interpolate(x, &contrast_curve_solutions)
});
// Composed brightness and contrast LUTs
let combined_lut = brightness_lut.map(|brightness| {
let index_in_contrast_lut = (brightness * (contrast_lut.len() - 1) as f32).round() as usize;
contrast_lut[index_in_contrast_lut]
});
let lut_max = (combined_lut.len() - 1) as f32;
input.adjust(|color| color.to_gamma_srgb().map_rgb(|c| combined_lut[(c * lut_max).round() as usize]).to_linear_srgb());
input
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=levl%27%20%3D%20Levels
//
// Algorithm from:
// https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
//
// Some further analysis available at:
// https://geraldbakker.nl/psnumbers/levels.html
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn levels<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
#[default(0.)] shadows: PercentageF32,
#[default(50.)] midtones: PercentageF32,
#[default(100.)] highlights: PercentageF32,
#[default(0.)] output_minimums: PercentageF32,
#[default(100.)] output_maximums: PercentageF32,
) -> T {
image.adjust(|color| {
let color = color.to_gamma_srgb();
// Input Range (Range: 0-1)
let input_shadows = shadows / 100.;
let input_midtones = midtones / 100.;
let input_highlights = highlights / 100.;
// Output Range (Range: 0-1)
let output_minimums = output_minimums / 100.;
let output_maximums = output_maximums / 100.;
// Midtones interpolation factor between minimums and maximums (Range: 0-1)
let midtones = output_minimums + (output_maximums - output_minimums) * input_midtones;
// Gamma correction (Range: 0.01-10)
let gamma = if midtones < 0.5 {
// Range: 0-1
let x = 1. - midtones * 2.;
// Range: 1-10
1. + 9. * x
} else {
// Range: 0-0.5
let x = 1. - midtones;
// Range: 0-1
let x = x * 2.;
// Range: 0.01-1
x.max(0.01)
};
// Input levels (Range: 0-1)
let highlights_minus_shadows = (input_highlights - input_shadows).clamp(f32::EPSILON, 1.);
let color = color.map_rgb(|c| ((c - input_shadows).max(0.) / highlights_minus_shadows).min(1.));
// Midtones (Range: 0-1)
let color = color.gamma(gamma);
// Output levels (Range: 0-1)
let color = color.map_rgb(|c| c * (output_maximums - output_minimums) + output_minimums);
color.to_linear_srgb()
});
image
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27blwh%27%20%3D%20Black%20and%20White
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Black%20White%20(Photoshop%20CS3)
//
// Algorithm from:
// https://stackoverflow.com/a/55233732/775283
// Works the same for gamma and linear color
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn black_and_white<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] tint: Color,
#[default(40.)]
#[range((-200., 300.))]
reds: PercentageF32,
#[default(60.)]
#[range((-200., 300.))]
yellows: PercentageF32,
#[default(40.)]
#[range((-200., 300.))]
greens: PercentageF32,
#[default(60.)]
#[range((-200., 300.))]
cyans: PercentageF32,
#[default(20.)]
#[range((-200., 300.))]
blues: PercentageF32,
#[default(80.)]
#[range((-200., 300.))]
magentas: PercentageF32,
) -> T {
image.adjust(|color| {
let color = color.to_gamma_srgb();
let reds = reds / 100.;
let yellows = yellows / 100.;
let greens = greens / 100.;
let cyans = cyans / 100.;
let blues = blues / 100.;
let magentas = magentas / 100.;
let gray_base = color.r().min(color.g()).min(color.b());
let red_part = color.r() - gray_base;
let green_part = color.g() - gray_base;
let blue_part = color.b() - gray_base;
let alpha_part = color.a();
let additional = if red_part == 0. {
let cyan_part = green_part.min(blue_part);
cyan_part * cyans + (green_part - cyan_part) * greens + (blue_part - cyan_part) * blues
} else if green_part == 0. {
let magenta_part = red_part.min(blue_part);
magenta_part * magentas + (red_part - magenta_part) * reds + (blue_part - magenta_part) * blues
} else {
let yellow_part = red_part.min(green_part);
yellow_part * yellows + (red_part - yellow_part) * reds + (green_part - yellow_part) * greens
};
let luminance = gray_base + additional;
// TODO: Fix "Color" blend mode implementation so it matches the expected behavior perfectly (it's currently close)
let color = tint.with_luminance(luminance);
let color = Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), alpha_part);
color.to_linear_srgb()
});
image
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27hue%20%27%20%3D%20Old,saturation%2C%20Photoshop%205.0
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=0%20%3D%20Use%20other.-,Hue/Saturation,-Hue/Saturation%20settings
#[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn hue_saturation<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
hue_shift: AngleF32,
saturation_shift: SignedPercentageF32,
lightness_shift: SignedPercentageF32,
) -> T {
input.adjust(|color| {
let color = color.to_gamma_srgb();
let [hue, saturation, lightness, alpha] = color.to_hsla();
let color = Color::from_hsla(
(hue + hue_shift / 360.) % 1.,
// TODO: Improve the way saturation works (it's slightly off)
(saturation + saturation_shift / 100.).clamp(0., 1.),
// TODO: Fix the way lightness works (it's very off)
(lightness + lightness_shift / 100.).clamp(0., 1.),
alpha,
);
color.to_linear_srgb()
});
input
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27%20%3D%20Color%20Lookup-,%27nvrt%27%20%3D%20Invert,-%27post%27%20%3D%20Posterize
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn invert<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
) -> T {
input.adjust(|color| {
let color = color.to_gamma_srgb();
let color = color.map_rgb(|c| color.a() - c);
color.to_linear_srgb()
});
input
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=post%27%20%3D%20Posterize-,%27thrs%27%20%3D%20Threshold,-%27grdm%27%20%3D%20Gradient
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn threshold<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
#[default(50.)] min_luminance: PercentageF32,
#[default(100.)] max_luminance: PercentageF32,
luminance_calc: LuminanceCalculation,
) -> T {
image.adjust(|color| {
let min_luminance = Color::srgb_to_linear(min_luminance / 100.);
let max_luminance = Color::srgb_to_linear(max_luminance / 100.);
let luminance = match luminance_calc {
LuminanceCalculation::SRGB => color.luminance_srgb(),
LuminanceCalculation::Perceptual => color.luminance_perceptual(),
LuminanceCalculation::AverageChannels => color.average_rgb_channels(),
LuminanceCalculation::MinimumChannels => color.minimum_rgb_channels(),
LuminanceCalculation::MaximumChannels => color.maximum_rgb_channels(),
};
if luminance >= min_luminance && luminance <= max_luminance { Color::WHITE } else { Color::BLACK }
});
image
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27-,vibA%27%20%3D%20Vibrance,-%27hue%20%27%20%3D%20Old
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Vibrance%20(Photoshop%20CS3)
//
// Algorithm based on:
// https://stackoverflow.com/questions/33966121/what-is-the-algorithm-for-vibrance-filters
// The results of this implementation are very close to correct, but not quite perfect.
//
// Some further analysis available at:
// https://www.photo-mark.com/notes/analyzing-photoshop-vibrance-and-saturation/
//
// This algorithm is currently lacking a "Saturation" parameter which is needed for interoperability.
// It's not the same as the saturation component of Hue/Saturation/Value. Vibrance and Saturation are both separable.
// When both parameters are set, it is equivalent to running this adjustment twice, with only vibrance set and then only saturation set.
// (Except for some noise probably due to rounding error.)
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn vibrance<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
vibrance: SignedPercentageF32,
) -> T {
image.adjust(|color| {
let vibrance = vibrance / 100.;
// Slow the effect down by half when it's negative, since artifacts begin appearing past -50%.
// So this scales the 0% to -50% range to 0% to -100%.
let slowed_vibrance = if vibrance >= 0. { vibrance } else { vibrance * 0.5 };
let channel_max = color.r().max(color.g()).max(color.b());
let channel_min = color.r().min(color.g()).min(color.b());
let channel_difference = channel_max - channel_min;
let scale_multiplier = if channel_max == color.r() {
let green_blue_difference = (color.g() - color.b()).abs();
let t = (green_blue_difference / channel_difference).min(1.);
t * 0.5 + 0.5
} else {
1.
};
let scale = slowed_vibrance * scale_multiplier * (2. - channel_difference);
let channel_reduction = channel_min * scale;
let scale = 1. + scale * (1. - channel_difference);
let luminance_initial = color.to_linear_srgb().luminance_srgb();
let altered_color = color.map_rgb(|c| c * scale - channel_reduction).to_linear_srgb();
let luminance = altered_color.luminance_srgb();
let altered_color = altered_color.map_rgb(|c| c * luminance_initial / luminance);
let channel_max = altered_color.r().max(altered_color.g()).max(altered_color.b());
let altered_color = if Color::linear_to_srgb(channel_max) > 1. {
let scale = (1. - luminance) / (channel_max - luminance);
altered_color.map_rgb(|c| (c - luminance) * scale + luminance)
} else {
altered_color
};
let altered_color = altered_color.to_gamma_srgb();
if vibrance >= 0. {
altered_color
} else {
// TODO: The result ends up a bit darker than it should be, further investigation is needed
let luminance = color.luminance_rec_601();
// Near -0% vibrance we mostly use `altered_color`.
// Near -100% vibrance, we mostly use half the desaturated luminance color and half `altered_color`.
let factor = -slowed_vibrance;
altered_color.map_rgb(|c| c * (1. - factor) + luminance * factor)
}
});
image
}
#[repr(u32)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType, BufferStruct, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum RedGreenBlue {
#[default]
Red,
Green,
Blue,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType, bytemuck::NoUninit, BufferStruct, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
#[repr(u32)]
pub enum RedGreenBlueAlpha {
#[default]
Red,
Green,
Blue,
Alpha,
}
/// Style of noise pattern.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Dropdown)]
pub enum NoiseType {
#[default]
Perlin,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2S")]
OpenSimplex2S,
Cellular,
ValueCubic,
Value,
WhiteNoise,
}
/// Style of layered levels of the noise pattern.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
pub enum FractalType {
#[default]
None,
#[label("Fractional Brownian Motion")]
FBm,
Ridged,
PingPong,
#[label("Progressive (Domain Warp Only)")]
DomainWarpProgressive,
#[label("Independent (Domain Warp Only)")]
DomainWarpIndependent,
}
/// Distance function used by the cellular noise.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
pub enum CellularDistanceFunction {
#[default]
Euclidean,
#[label("Euclidean Squared (Faster)")]
EuclideanSq,
Manhattan,
Hybrid,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
pub enum CellularReturnType {
CellValue,
#[default]
#[label("Nearest (F1)")]
Nearest,
#[label("Next Nearest (F2)")]
NextNearest,
#[label("Average (F1 / 2 + F2 / 2)")]
Average,
#[label("Difference (F2 - F1)")]
Difference,
#[label("Product (F2 * F1 / 2)")]
Product,
#[label("Division (F1 / F2)")]
Division,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Dropdown)]
pub enum DomainWarpType {
#[default]
None,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2 Reduced")]
OpenSimplex2Reduced,
BasicGrid,
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27mixr%27%20%3D%20Channel%20Mixer
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Lab%20color%20only-,Channel%20Mixer,-Key%20is%20%27mixr
#[node_macro::node(category("Raster: Adjustment"), properties("channel_mixer_properties"), shader_node(PerPixelAdjust))]
fn channel_mixer<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
monochrome: bool,
#[default(40.)]
#[name("Red")]
monochrome_r: f32,
#[default(40.)]
#[name("Green")]
monochrome_g: f32,
#[default(20.)]
#[name("Blue")]
monochrome_b: f32,
#[default(0.)]
#[name("Constant")]
monochrome_c: f32,
#[default(100.)]
#[name("(Red) Red")]
red_r: f32,
#[default(0.)]
#[name("(Red) Green")]
red_g: f32,
#[default(0.)]
#[name("(Red) Blue")]
red_b: f32,
#[default(0.)]
#[name("(Red) Constant")]
red_c: f32,
#[default(0.)]
#[name("(Green) Red")]
green_r: f32,
#[default(100.)]
#[name("(Green) Green")]
green_g: f32,
#[default(0.)]
#[name("(Green) Blue")]
green_b: f32,
#[default(0.)]
#[name("(Green) Constant")]
green_c: f32,
#[default(0.)]
#[name("(Blue) Red")]
blue_r: f32,
#[default(0.)]
#[name("(Blue) Green")]
blue_g: f32,
#[default(100.)]
#[name("(Blue) Blue")]
blue_b: f32,
#[default(0.)]
#[name("(Blue) Constant")]
blue_c: f32,
// Display-only properties (not used within the node)
_output_channel: RedGreenBlue,
) -> T {
image.adjust(|color| {
let color = color.to_gamma_srgb();
let (r, g, b, a) = color.components();
let color = if monochrome {
let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = (monochrome_r / 100., monochrome_g / 100., monochrome_b / 100., monochrome_c / 100.);
let gray = (r * monochrome_r + g * monochrome_g + b * monochrome_b + monochrome_c).clamp(0., 1.);
Color::from_rgbaf32_unchecked(gray, gray, gray, a)
} else {
let (red_r, red_g, red_b, red_c) = (red_r / 100., red_g / 100., red_b / 100., red_c / 100.);
let (green_r, green_g, green_b, green_c) = (green_r / 100., green_g / 100., green_b / 100., green_c / 100.);
let (blue_r, blue_g, blue_b, blue_c) = (blue_r / 100., blue_g / 100., blue_b / 100., blue_c / 100.);
let red = (r * red_r + g * red_g + b * red_b + red_c).clamp(0., 1.);
let green = (r * green_r + g * green_g + b * green_b + green_c).clamp(0., 1.);
let blue = (r * blue_r + g * blue_g + b * blue_b + blue_c).clamp(0., 1.);
Color::from_rgbaf32_unchecked(red, green, blue, a)
};
color.to_linear_srgb()
});
image
}
#[repr(u32)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType, BufferStruct, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum RelativeAbsolute {
#[default]
Relative,
Absolute,
}
#[repr(u32)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, node_macro::ChoiceType, BufferStruct, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, specta::Type, serde::Serialize, serde::Deserialize))]
pub enum SelectiveColorChoice {
#[default]
Reds,
Yellows,
Greens,
Cyans,
Blues,
Magentas,
#[menu_separator]
Whites,
Neutrals,
Blacks,
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27selc%27%20%3D%20Selective%20color
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=from%20%2D100...100.%20.-,Selective%20Color,-Selective%20Color%20settings
//
// Algorithm based on:
// https://blog.pkh.me/p/22-understanding-selective-coloring-in-adobe-photoshop.html
#[node_macro::node(category("Raster: Adjustment"), properties("selective_color_properties"), shader_node(PerPixelAdjust))]
fn selective_color<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
mode: RelativeAbsolute,
#[name("(Reds) Cyan")] r_c: f32,
#[name("(Reds) Magenta")] r_m: f32,
#[name("(Reds) Yellow")] r_y: f32,
#[name("(Reds) Black")] r_k: f32,
#[name("(Yellows) Cyan")] y_c: f32,
#[name("(Yellows) Magenta")] y_m: f32,
#[name("(Yellows) Yellow")] y_y: f32,
#[name("(Yellows) Black")] y_k: f32,
#[name("(Greens) Cyan")] g_c: f32,
#[name("(Greens) Magenta")] g_m: f32,
#[name("(Greens) Yellow")] g_y: f32,
#[name("(Greens) Black")] g_k: f32,
#[name("(Cyans) Cyan")] c_c: f32,
#[name("(Cyans) Magenta")] c_m: f32,
#[name("(Cyans) Yellow")] c_y: f32,
#[name("(Cyans) Black")] c_k: f32,
#[name("(Blues) Cyan")] b_c: f32,
#[name("(Blues) Magenta")] b_m: f32,
#[name("(Blues) Yellow")] b_y: f32,
#[name("(Blues) Black")] b_k: f32,
#[name("(Magentas) Cyan")] m_c: f32,
#[name("(Magentas) Magenta")] m_m: f32,
#[name("(Magentas) Yellow")] m_y: f32,
#[name("(Magentas) Black")] m_k: f32,
#[name("(Whites) Cyan")] w_c: f32,
#[name("(Whites) Magenta")] w_m: f32,
#[name("(Whites) Yellow")] w_y: f32,
#[name("(Whites) Black")] w_k: f32,
#[name("(Neutrals) Cyan")] n_c: f32,
#[name("(Neutrals) Magenta")] n_m: f32,
#[name("(Neutrals) Yellow")] n_y: f32,
#[name("(Neutrals) Black")] n_k: f32,
#[name("(Blacks) Cyan")] k_c: f32,
#[name("(Blacks) Magenta")] k_m: f32,
#[name("(Blacks) Yellow")] k_y: f32,
#[name("(Blacks) Black")] k_k: f32,
_colors: SelectiveColorChoice,
) -> T {
image.adjust(|color| {
let color = color.to_gamma_srgb();
let (r, g, b, a) = color.components();
let min = |a: f32, b: f32, c: f32| a.min(b).min(c);
let max = |a: f32, b: f32, c: f32| a.max(b).max(c);
let med = |a: f32, b: f32, c: f32| a + b + c - min(a, b, c) - max(a, b, c);
let max_channel = max(r, g, b);
let min_channel = min(r, g, b);
let pixel_color_range = |choice| match choice {
SelectiveColorChoice::Reds => max_channel == r,
SelectiveColorChoice::Yellows => min_channel == b,
SelectiveColorChoice::Greens => max_channel == g,
SelectiveColorChoice::Cyans => min_channel == r,
SelectiveColorChoice::Blues => max_channel == b,
SelectiveColorChoice::Magentas => min_channel == g,
SelectiveColorChoice::Whites => r > 0.5 && g > 0.5 && b > 0.5,
SelectiveColorChoice::Neutrals => r > 0. && g > 0. && b > 0. && r < 1. && g < 1. && b < 1.,
SelectiveColorChoice::Blacks => r < 0.5 && g < 0.5 && b < 0.5,
};
let color_parameter_group_scale_factor_rgb = max(r, g, b) - med(r, g, b);
let color_parameter_group_scale_factor_cmy = med(r, g, b) - min(r, g, b);
// Used to apply the r, g, or b channel slope (by multiplying it by 1) in relative mode, or no slope (by multiplying it by 0) in absolute mode
let (slope_r, slope_g, slope_b) = match mode {
RelativeAbsolute::Relative => (r - 1., g - 1., b - 1.),
RelativeAbsolute::Absolute => (-1., -1., -1.),
};
let array = [
(SelectiveColorChoice::Reds, (r_c, r_m, r_y, r_k)),
(SelectiveColorChoice::Yellows, (y_c, y_m, y_y, y_k)),
(SelectiveColorChoice::Greens, (g_c, g_m, g_y, g_k)),
(SelectiveColorChoice::Cyans, (c_c, c_m, c_y, c_k)),
(SelectiveColorChoice::Blues, (b_c, b_m, b_y, b_k)),
(SelectiveColorChoice::Magentas, (m_c, m_m, m_y, m_k)),
(SelectiveColorChoice::Whites, (w_c, w_m, w_y, w_k)),
(SelectiveColorChoice::Neutrals, (n_c, n_m, n_y, n_k)),
(SelectiveColorChoice::Blacks, (k_c, k_m, k_y, k_k)),
];
let mut sum = Vec3::ZERO;
for i in 0..array.len() {
let (color_parameter_group, (c, m, y, k)) = array[i];
// Skip this color parameter group...
// ...if it's unchanged from the default of zero offset on all CMYK parameters, or...
// ...if this pixel's color isn't in the range affected by this color parameter group
if (c < f32::EPSILON && m < f32::EPSILON && y < f32::EPSILON && k < f32::EPSILON) || (!pixel_color_range(color_parameter_group)) {
continue;
}
let (c, m, y, k) = (c / 100., m / 100., y / 100., k / 100.);
let color_parameter_group_scale_factor = match color_parameter_group {
SelectiveColorChoice::Reds | SelectiveColorChoice::Greens | SelectiveColorChoice::Blues => color_parameter_group_scale_factor_rgb,
SelectiveColorChoice::Cyans | SelectiveColorChoice::Magentas | SelectiveColorChoice::Yellows => color_parameter_group_scale_factor_cmy,
SelectiveColorChoice::Whites => min(r, g, b) * 2. - 1.,
SelectiveColorChoice::Neutrals => 1. - ((max(r, g, b) - 0.5).abs() + (min(r, g, b) - 0.5).abs()),
SelectiveColorChoice::Blacks => 1. - max(r, g, b) * 2.,
};
let offset_r = f32::clamp((c + k * (c + 1.)) * slope_r, -r, -r + 1.) * color_parameter_group_scale_factor;
let offset_g = f32::clamp((m + k * (m + 1.)) * slope_g, -g, -g + 1.) * color_parameter_group_scale_factor;
let offset_b = f32::clamp((y + k * (y + 1.)) * slope_b, -b, -b + 1.) * color_parameter_group_scale_factor;
sum += Vec3::new(offset_r, offset_g, offset_b);
}
let rgb = Vec3::new(r, g, b);
let color = Color::from_vec4(Vec4::from(((sum + rgb).clamp(Vec3::ZERO, Vec3::ONE), a)));
color.to_linear_srgb()
});
image
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=nvrt%27%20%3D%20Invert-,%27post%27%20%3D%20Posterize,-%27thrs%27%20%3D%20Threshold
//
// Algorithm based on:
// https://www.axiomx.com/posterize.htm
// This algorithm produces fully accurate output in relation to the industry standard.
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn posterize<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut input: T,
#[default(4)]
#[hard_min(2.)]
levels: u32,
) -> T {
input.adjust(|color| {
let color = color.to_gamma_srgb();
let levels = levels as f32;
let number_of_areas = levels.recip();
let size_of_areas = (levels - 1.).recip();
let channel = |channel: f32| (channel / number_of_areas).floor() * size_of_areas;
let color = color.map_rgb(channel);
color.to_linear_srgb()
});
input
}
// Aims for interoperable compatibility with:
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=curv%27%20%3D%20Curves-,%27expA%27%20%3D%20Exposure,-%27vibA%27%20%3D%20Vibrance
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Flag%20(%20%3D%20128%20)-,Exposure,-Key%20is%20%27expA
//
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/blending_nodes.rs | node-graph/nodes/raster/src/blending_nodes.rs | use crate::adjust::Adjust;
#[cfg(feature = "std")]
use core_types::table::Table;
use no_std_types::Ctx;
use no_std_types::blending::BlendMode;
use no_std_types::color::{Color, Pixel};
use no_std_types::registry::types::PercentageF32;
#[cfg(feature = "std")]
use raster_types::{CPU, Raster};
#[cfg(feature = "std")]
use vector_types::GradientStops;
pub trait Blend<P: Pixel> {
fn blend(&self, under: &Self, blend_fn: impl Fn(P, P) -> P) -> Self;
}
impl Blend<Color> for Color {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
blend_fn(*self, *under)
}
}
#[cfg(feature = "std")]
mod blend_std {
use super::*;
use core::cmp::Ordering;
use core_types::table::Table;
use raster_types::Image;
use raster_types::Raster;
impl Blend<Color> for Table<Raster<CPU>> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_table = self.clone();
for (over, under) in result_table.iter_mut().zip(under.iter()) {
let data = over.element.data.iter().zip(under.element.data.iter()).map(|(a, b)| blend_fn(*a, *b)).collect();
*over.element = Raster::new_cpu(Image {
data,
width: over.element.width,
height: over.element.height,
base64_string: None,
});
}
result_table
}
}
impl Blend<Color> for Table<Color> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_table = self.clone();
for (over, under) in result_table.iter_mut().zip(under.iter()) {
*over.element = blend_fn(*over.element, *under.element);
}
result_table
}
}
impl Blend<Color> for Table<GradientStops> {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut result_table = self.clone();
for (over, under) in result_table.iter_mut().zip(under.iter()) {
*over.element = over.element.blend(under.element, &blend_fn);
}
result_table
}
}
impl Blend<Color> for GradientStops {
fn blend(&self, under: &Self, blend_fn: impl Fn(Color, Color) -> Color) -> Self {
let mut combined_stops = self.iter().map(|(position, _)| position).chain(under.iter().map(|(position, _)| position)).collect::<Vec<_>>();
combined_stops.dedup_by(|&mut a, &mut b| (a - b).abs() < 1e-6);
combined_stops.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
let stops = combined_stops
.into_iter()
.map(|&position| {
let over_color = self.evaluate(position);
let under_color = under.evaluate(position);
let color = blend_fn(over_color, under_color);
(position, color)
})
.collect::<Vec<_>>();
GradientStops::new(stops)
}
}
}
#[inline(always)]
pub fn blend_colors(foreground: Color, background: Color, blend_mode: BlendMode, opacity: f32) -> Color {
let target_color = match blend_mode {
// Other utility blend modes (hidden from the normal list) - do not have alpha blend
BlendMode::Erase => return background.alpha_subtract(foreground),
BlendMode::Restore => return background.alpha_add(foreground),
BlendMode::MultiplyAlpha => return background.alpha_multiply(foreground),
blend_mode => apply_blend_mode(foreground, background, blend_mode),
};
background.alpha_blend(target_color.to_associated_alpha(opacity))
}
pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendMode) -> Color {
match blend_mode {
// Normal group
BlendMode::Normal => background.blend_rgb(foreground, Color::blend_normal),
// Darken group
BlendMode::Darken => background.blend_rgb(foreground, Color::blend_darken),
BlendMode::Multiply => background.blend_rgb(foreground, Color::blend_multiply),
BlendMode::ColorBurn => background.blend_rgb(foreground, Color::blend_color_burn),
BlendMode::LinearBurn => background.blend_rgb(foreground, Color::blend_linear_burn),
BlendMode::DarkerColor => background.blend_darker_color(foreground),
// Lighten group
BlendMode::Lighten => background.blend_rgb(foreground, Color::blend_lighten),
BlendMode::Screen => background.blend_rgb(foreground, Color::blend_screen),
BlendMode::ColorDodge => background.blend_rgb(foreground, Color::blend_color_dodge),
BlendMode::LinearDodge => background.blend_rgb(foreground, Color::blend_linear_dodge),
BlendMode::LighterColor => background.blend_lighter_color(foreground),
// Contrast group
BlendMode::Overlay => foreground.blend_rgb(background, Color::blend_hardlight),
BlendMode::SoftLight => background.blend_rgb(foreground, Color::blend_softlight),
BlendMode::HardLight => background.blend_rgb(foreground, Color::blend_hardlight),
BlendMode::VividLight => background.blend_rgb(foreground, Color::blend_vivid_light),
BlendMode::LinearLight => background.blend_rgb(foreground, Color::blend_linear_light),
BlendMode::PinLight => background.blend_rgb(foreground, Color::blend_pin_light),
BlendMode::HardMix => background.blend_rgb(foreground, Color::blend_hard_mix),
// Inversion group
BlendMode::Difference => background.blend_rgb(foreground, Color::blend_difference),
BlendMode::Exclusion => background.blend_rgb(foreground, Color::blend_exclusion),
BlendMode::Subtract => background.blend_rgb(foreground, Color::blend_subtract),
BlendMode::Divide => background.blend_rgb(foreground, Color::blend_divide),
// Component group
BlendMode::Hue => background.blend_hue(foreground),
BlendMode::Saturation => background.blend_saturation(foreground),
BlendMode::Color => background.blend_color(foreground),
BlendMode::Luminosity => background.blend_luminosity(foreground),
// Other utility blend modes (hidden from the normal list) - do not have alpha blend
_ => panic!("Used blend mode without alpha blend"),
}
}
#[node_macro::node(category("Raster"), cfg(feature = "std"))]
fn blend<T: Blend<Color> + Send>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
over: T,
#[expose]
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
under: T,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
over.blend(&under, |a, b| blend_colors(a, b, blend_mode, opacity / 100.))
}
#[node_macro::node(category("Raster: Adjustment"), shader_node(PerPixelAdjust))]
fn color_overlay<T: Adjust<Color>>(
_: impl Ctx,
#[implementations(
Table<Raster<CPU>>,
Table<Color>,
Table<GradientStops>,
GradientStops,
)]
#[gpu_image]
mut image: T,
#[default(Color::BLACK)] color: Color,
blend_mode: BlendMode,
#[default(100.)] opacity: PercentageF32,
) -> T {
let opacity = (opacity / 100.).clamp(0., 1.);
image.adjust(|pixel| {
let image = pixel.map_rgb(|channel| channel * (1. - opacity));
// The apply blend mode function divides rgb by the alpha channel for the background. This undoes that.
let associated_pixel = Color::from_rgbaf32_unchecked(pixel.r() * pixel.a(), pixel.g() * pixel.a(), pixel.b() * pixel.a(), pixel.a());
let overlay = apply_blend_mode(color, associated_pixel, blend_mode).map_rgb(|channel| channel * opacity);
Color::from_rgbaf32_unchecked(image.r() + overlay.r(), image.g() + overlay.g(), image.b() + overlay.b(), pixel.a())
});
image
}
#[cfg(all(feature = "std", test))]
mod test {
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::table::Table;
use raster_types::Image;
use raster_types::Raster;
#[tokio::test]
async fn color_overlay_multiply() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
let image = Image::new(1, 1, image_color);
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
let overlay_color = Color::GREEN;
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay((), Table::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = result.iter().next().unwrap().element;
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/adjust.rs | node-graph/nodes/raster/src/adjust.rs | use no_std_types::color::Color;
pub trait Adjust<P> {
fn adjust(&mut self, map_fn: impl Fn(&P) -> P);
}
impl Adjust<Color> for Color {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
*self = map_fn(self);
}
}
#[cfg(feature = "std")]
mod adjust_std {
use super::*;
use core_types::table::Table;
use raster_types::{CPU, Raster};
use vector_types::GradientStops;
impl Adjust<Color> for Table<Raster<CPU>> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for row in self.iter_mut() {
for color in row.element.data_mut().data.iter_mut() {
*color = map_fn(color);
}
}
}
}
impl Adjust<Color> for Table<Color> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for row in self.iter_mut() {
*row.element = map_fn(row.element);
}
}
}
impl Adjust<Color> for Table<GradientStops> {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for row in self.iter_mut() {
row.element.adjust(&map_fn);
}
}
}
impl Adjust<Color> for GradientStops {
fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) {
for (_, color) in self.iter_mut() {
*color = map_fn(color);
}
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/generate_curves.rs | node-graph/nodes/raster/src/generate_curves.rs | use crate::curve::{Curve, CurveManipulatorGroup, ValueMapperNode};
use core_types::color::{Channel, Linear};
use core_types::context::Ctx;
use kurbo::{CubicBez, ParamCurve, PathSeg, Point};
use vector_types::vector::algorithms::bezpath_algorithms::pathseg_find_tvalues_for_x;
const WINDOW_SIZE: usize = 1024;
#[node_macro::node(category(""))]
fn generate_curves<C: Channel + Linear>(_: impl Ctx, curve: Curve, #[implementations(f32, f64)] _target_format: C) -> ValueMapperNode<C> {
let [mut pos, mut param]: [[f32; 2]; 2] = [[0.; 2], curve.first_handle];
let mut lut = vec![C::from_f64(0.); WINDOW_SIZE];
let end = CurveManipulatorGroup {
anchor: [1.; 2],
handles: [curve.last_handle, [0.; 2]],
};
for sample in curve.manipulator_groups.iter().chain(std::iter::once(&end)) {
let [x0, y0, x1, y1, x2, y2, x3, y3] = [pos[0], pos[1], param[0], param[1], sample.handles[0][0], sample.handles[0][1], sample.anchor[0], sample.anchor[1]].map(f64::from);
let segment = PathSeg::Cubic(CubicBez::new(Point::new(x0, y0), Point::new(x1, y1), Point::new(x2, y2), Point::new(x3, y3)));
let [left, right] = [pos[0], sample.anchor[0]].map(|c| c.clamp(0., 1.));
let lut_index_left: usize = (left * (lut.len() - 1) as f32).floor() as _;
let lut_index_right: usize = (right * (lut.len() - 1) as f32).ceil() as _;
for index in lut_index_left..=lut_index_right {
let x = index as f64 / (lut.len() - 1) as f64;
let y = if x <= x0 {
y0
} else if x >= x3 {
y3
} else {
pathseg_find_tvalues_for_x(segment, x)
.next()
.map(|t| segment.eval(t.clamp(0., 1.)).y)
// Fall back to a very bad approximation if the above fails
.unwrap_or_else(|| (x - x0) / (x3 - x0) * (y3 - y0) + y0)
};
lut[index] = C::from_f64(y);
}
pos = sample.anchor;
param = sample.handles[1];
}
ValueMapperNode::new(lut)
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/src/image_color_palette.rs | node-graph/nodes/raster/src/image_color_palette.rs | use core_types::color::Color;
use core_types::context::Ctx;
use core_types::table::{Table, TableRow};
use raster_types::{CPU, Raster};
#[node_macro::node(category("Color"))]
async fn image_color_palette(
_: impl Ctx,
image: Table<Raster<CPU>>,
#[hard_min(1.)]
#[soft_max(28.)]
max_size: u32,
) -> Table<Color> {
const GRID: f32 = 3.;
let bins = GRID * GRID * GRID;
let mut histogram = vec![0; (bins + 1.) as usize];
let mut color_bins = vec![Vec::new(); (bins + 1.) as usize];
for row in image.iter() {
for pixel in row.element.data.iter() {
let r = pixel.r() * GRID;
let g = pixel.g() * GRID;
let b = pixel.b() * GRID;
let bin = (r * GRID + g * GRID + b * GRID) as usize;
histogram[bin] += 1;
color_bins[bin].push(pixel.to_gamma_srgb());
}
}
let shorted = histogram.iter().enumerate().filter(|&(_, &count)| count > 0).map(|(i, _)| i).collect::<Vec<usize>>();
shorted
.iter()
.take(max_size as usize)
.flat_map(|&i| {
let list = &color_bins[i];
let mut r = 0.;
let mut g = 0.;
let mut b = 0.;
let mut a = 0.;
for color in list.iter() {
r += color.r();
g += color.g();
b += color.b();
a += color.a();
}
r /= list.len() as f32;
g /= list.len() as f32;
b /= list.len() as f32;
a /= list.len() as f32;
Color::from_rgbaf32(r, g, b, a).map(TableRow::new_from_element).into_iter()
})
.collect()
}
#[cfg(test)]
mod test {
use super::*;
use raster_types::Image;
use raster_types::Raster;
#[test]
fn test_image_color_palette() {
let result = image_color_palette(
(),
Table::new_from_element(Raster::new_cpu(Image {
width: 100,
height: 100,
data: vec![Color::from_rgbaf32(0., 0., 0., 1.).unwrap(); 10000],
base64_string: None,
})),
1,
);
assert_eq!(futures::executor::block_on(result), Table::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/shaders/build.rs | node-graph/nodes/raster/shaders/build.rs | use cargo_gpu::InstalledBackend;
use cargo_gpu::spirv_builder::{MetadataPrintout, SpirvMetadata};
use std::path::PathBuf;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::builder().filter_level(log::LevelFilter::Debug).init();
// Skip building the shader if they are provided externally
println!("cargo:rerun-if-env-changed=RASTER_NODES_SHADER_PATH");
if !std::env::var("RASTER_NODES_SHADER_PATH").unwrap_or_default().is_empty() {
return Ok(());
}
// Allows overriding the PATH to inject the rust-gpu rust toolchain when building the rest of the project with stable rustc.
// Used in nix shell. Do not remove without checking with developers using nix.
println!("cargo:rerun-if-env-changed=RUST_GPU_PATH_OVERRIDE");
if let Ok(path_override) = std::env::var("RUST_GPU_PATH_OVERRIDE") {
let current_path = std::env::var("PATH").unwrap_or_default();
let new_path = format!("{path_override}:{current_path}");
// SAFETY: Build script is single-threaded therefore this cannot lead to undefined behavior.
unsafe {
std::env::set_var("PATH", &new_path);
}
}
let shader_crate = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/entrypoint"));
println!("cargo:rerun-if-env-changed=RUSTC_CODEGEN_SPIRV_PATH");
let rustc_codegen_spirv_path = std::env::var("RUSTC_CODEGEN_SPIRV_PATH").unwrap_or_default();
let backend = if rustc_codegen_spirv_path.is_empty() {
// install the toolchain and build the `rustc_codegen_spirv` codegen backend with it
cargo_gpu::Install::from_shader_crate(shader_crate.clone()).run()?
} else {
// use the `RUSTC_CODEGEN_SPIRV` environment variable to find the codegen backend
let mut backend = InstalledBackend::default();
backend.rustc_codegen_spirv_location = PathBuf::from(rustc_codegen_spirv_path);
backend.toolchain_channel = "nightly".to_string();
backend.target_spec_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
backend
};
// build the shader crate
let mut builder = backend.to_spirv_builder(shader_crate, "spirv-unknown-naga-wgsl");
builder.print_metadata = MetadataPrintout::DependencyOnly;
builder.spirv_metadata = SpirvMetadata::Full;
let wgsl_result = builder.build()?;
let path_to_spv = wgsl_result.module.unwrap_single();
// needs to be fixed upstream
let path_to_wgsl = path_to_spv.with_extension("wgsl");
println!("cargo::rustc-env=RASTER_NODES_SHADER_PATH={}", path_to_wgsl.display());
Ok(())
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/shaders/src/lib.rs | node-graph/nodes/raster/shaders/src/lib.rs | pub const WGSL_SHADER: &str = include_str!(env!("RASTER_NODES_SHADER_PATH"));
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/raster/shaders/entrypoint/src/lib.rs | node-graph/nodes/raster/shaders/entrypoint/src/lib.rs | #![no_std]
pub use raster_nodes::*;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/transform/src/lib.rs | node-graph/nodes/transform/src/lib.rs | pub mod transform_nodes;
// Re-export for convenience
pub use core_types as gcore;
pub use graphic_types;
pub use transform_nodes::*;
pub use vector_types;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/transform/src/transform_nodes.rs | node-graph/nodes/transform/src/transform_nodes.rs | use core::f64;
use core_types::color::Color;
use core_types::table::Table;
use core_types::transform::{ApplyTransform, Transform};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use vector_types::GradientStops;
/// Applies the specified transform to the input value, which may be a graphic type or another transform.
#[node_macro::node(category(""))]
async fn transform<T: ApplyTransform + 'n + 'static>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
#[implementations(
Context -> DAffine2,
Context -> DVec2,
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> Table<GradientStops>,
)]
content: impl Node<Context<'static>, Output = T>,
translation: DVec2,
rotation: f64,
scale: DVec2,
skew: DVec2,
) -> T {
let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation);
let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
let matrix = trs * skew;
let footprint = ctx.try_footprint().copied();
let mut ctx = OwnedContextImpl::from(ctx);
if let Some(mut footprint) = footprint {
footprint.apply_transform(&matrix);
ctx = ctx.with_footprint(footprint);
}
let mut transform_target = content.eval(ctx.into_context()).await;
transform_target.left_apply_transform(&matrix);
transform_target
}
/// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform.
/// Shear is represented jointly by rotation and scale, so resetting both will also remove any shear.
#[node_macro::node(category("Math: Transform"))]
fn reset_transform<T>(
_: impl Ctx,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
mut content: Table<T>,
#[default(true)] reset_translation: bool,
reset_rotation: bool,
reset_scale: bool,
) -> Table<T> {
for row in content.iter_mut() {
// Translation
if reset_translation {
row.transform.translation = DVec2::ZERO;
}
// (Rotation, Scale)
match (reset_rotation, reset_scale) {
(true, true) => {
row.transform.matrix2 = DMat2::IDENTITY;
}
(true, false) => {
let scale = row.transform.decompose_scale();
row.transform.matrix2 = DMat2::from_diagonal(scale);
}
(false, true) => {
let rotation = row.transform.decompose_rotation();
let rotation_matrix = DMat2::from_angle(rotation);
row.transform.matrix2 = rotation_matrix;
}
(false, false) => {}
}
}
content
}
/// Overwrites the transform of each element in the input table with the specified transform.
#[node_macro::node(category("Math: Transform"))]
fn replace_transform<T>(
_: impl Ctx + InjectFootprint,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
mut content: Table<T>,
transform: DAffine2,
) -> Table<T> {
for row in content.iter_mut() {
*row.transform = transform.transform();
}
content
}
// TODO: Figure out how this node should behave once #2982 is implemented.
/// Obtains the transform of the first element in the input table, if present.
#[node_macro::node(category("Math: Transform"), path(core_types::vector))]
async fn extract_transform<T>(
_: impl Ctx,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
Table<Color>,
Table<GradientStops>,
)]
content: Table<T>,
) -> DAffine2 {
content.iter().next().map(|row| *row.transform).unwrap_or_default()
}
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
#[node_macro::node(category("Math: Transform"))]
fn invert_transform(_: impl Ctx, transform: DAffine2) -> DAffine2 {
transform.inverse()
}
/// Extracts the translation component from the input transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_translation(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.translation
}
/// Extracts the rotation component (in degrees) from the input transform.
/// This, together with the "Decompose Scale" node, also may jointly represent any shear component in the original transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_rotation(_: impl Ctx, transform: DAffine2) -> f64 {
transform.decompose_rotation().to_degrees()
}
/// Extracts the scale component from the input transform.
/// This, together with the "Decompose Rotation" node, also may jointly represent any shear component in the original transform.
#[node_macro::node(category("Math: Transform"))]
fn decompose_scale(_: impl Ctx, transform: DAffine2) -> DVec2 {
transform.decompose_scale()
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/vector/src/vector_nodes.rs | node-graph/nodes/vector/src/vector_nodes.rs | use core::f64::consts::PI;
use core::hash::{Hash, Hasher};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::registry::types::{Angle, IntegerCount, Length, Multiplier, Percentage, PixelLength, PixelSize, Progression, SeedValue};
use core_types::table::{Table, TableRow, TableRowMut};
use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Graphic, IntoGraphicTable};
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, PathEl, PathSeg, Shape};
use rand::{Rng, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use std::f64::consts::TAU;
use vector_types::subpath::{BezierHandles, ManipulatorGroup};
use vector_types::vector::PointDomain;
use vector_types::vector::ReferencePoint;
use vector_types::vector::algorithms::bezpath_algorithms::eval_pathseg_euclidean;
use vector_types::vector::algorithms::bezpath_algorithms::{self, TValue, evaluate_bezpath, sample_polyline_on_bezpath, split_bezpath, tangent_on_bezpath};
use vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
use vector_types::vector::algorithms::offset_subpath::offset_bezpath;
use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open};
use vector_types::vector::misc::{CentroidType, ExtrudeJoiningAlgorithm, bezpath_from_manipulator_groups, bezpath_to_manipulator_groups, point_to_dvec2};
use vector_types::vector::misc::{MergeByDistanceAlgorithm, PointSpacingType, is_linear};
use vector_types::vector::misc::{handles_to_segment, segment_to_handles};
use vector_types::vector::style::{Fill, Gradient, GradientStops, Stroke};
use vector_types::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::{FillId, RegionId};
use vector_types::vector::{PointId, SegmentDomain, SegmentId, StrokeId, VectorExt};
/// Implemented for types that can be converted to an iterator of vector rows.
/// Used for the fill and stroke node so they can be used on `Table<Graphic>` or `Table<Vector>`.
trait VectorTableIterMut {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>>;
}
impl VectorTableIterMut for Table<Graphic> {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>> {
// Grab only the direct children
self.iter_mut().filter_map(|element| element.element.as_vector_mut()).flat_map(move |vector| vector.iter_mut())
}
}
impl VectorTableIterMut for Table<Vector> {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>> {
self.iter_mut()
}
}
/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector))]
async fn assign_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the fill and/or stroke style to.
#[implementations(Table<Graphic>, Table<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
mut content: T,
/// Whether to style the fill.
#[default(true)]
fill: bool,
/// Whether to style the stroke.
stroke: bool,
/// The range of colors to select from.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_gradient")]
gradient: GradientStops,
/// Whether to reverse the gradient.
reverse: bool,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: bool,
/// The seed used for randomization.
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_seed")]
seed: SeedValue,
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_repeat_every")]
repeat_every: u32,
) -> T
where
T: VectorTableIterMut + 'n + Send,
{
let length = content.vector_iter_mut().count();
let gradient = if reverse { gradient.reversed() } else { gradient };
let mut rng = rand::rngs::StdRng::seed_from_u64(seed.into());
for (i, vector) in content.vector_iter_mut().enumerate() {
let factor = match randomize {
true => rng.random::<f64>(),
false => match repeat_every {
0 => i as f64 / (length - 1).max(1) as f64,
1 => 0.,
_ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let color = gradient.evaluate(factor);
if fill {
vector.element.style.set_fill(Fill::Solid(color));
}
if stroke && let Some(stroke) = vector.element.style.stroke().and_then(|stroke| stroke.with_color(&Some(color))) {
vector.element.style.set_stroke(stroke);
}
}
content
}
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
async fn fill<F: Into<Fill> + 'n + Send, V: VectorTableIterMut + 'n + Send>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
#[implementations(
Table<Vector>,
Table<Vector>,
Table<Vector>,
Table<Vector>,
Table<Graphic>,
Table<Graphic>,
Table<Graphic>,
Table<Graphic>,
)]
mut content: V,
/// The fill to paint the path with.
#[default(Color::BLACK)]
#[implementations(
Fill,
Table<Color>,
Table<GradientStops>,
Gradient,
Fill,
Table<Color>,
Table<GradientStops>,
Gradient,
)]
fill: F,
_backup_color: Table<Color>,
_backup_gradient: Gradient,
) -> V {
let fill: Fill = fill.into();
for vector in content.vector_iter_mut() {
vector.element.style.set_fill(fill.clone());
}
content
}
trait IntoF64Vec {
fn into_vec(self) -> Vec<f64>;
}
impl IntoF64Vec for f64 {
fn into_vec(self) -> Vec<f64> {
vec![self]
}
}
impl IntoF64Vec for Vec<f64> {
fn into_vec(self) -> Vec<f64> {
self
}
}
impl IntoF64Vec for String {
fn into_vec(self) -> Vec<f64> {
self.split(&[',', ' ']).filter(|s| !s.is_empty()).filter_map(|s| s.parse::<f64>().ok()).collect()
}
}
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
async fn stroke<V, L: IntoF64Vec>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(Table<Vector>, Table<Vector>, Table<Vector>, Table<Graphic>, Table<Graphic>, Table<Graphic>)]
mut content: Table<V>,
/// The stroke color.
#[default(Color::BLACK)]
color: Table<Color>,
/// The stroke weight.
#[unit(" px")]
#[default(2.)]
weight: f64,
/// The alignment of stroke to the path's centerline or (for closed shapes) the inside or outside of the shape.
align: StrokeAlign,
/// The shape of the stroke at open endpoints.
cap: StrokeCap,
/// The curvature of the bent stroke at sharp corners.
join: StrokeJoin,
/// The threshold for when a miter-joined stroke is converted to a bevel-joined stroke when a sharp angle becomes pointier than this ratio.
#[default(4.)]
miter_limit: f64,
// <https://svgwg.org/svg2-draft/painting.html#PaintOrderProperty>
/// The order to paint the stroke on top of the fill, or the fill on top of the stroke.
paint_order: PaintOrder,
/// The stroke dash lengths. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
#[implementations(Vec<f64>, f64, String, Vec<f64>, f64, String)]
dash_lengths: L,
/// The phase offset distance from the starting point of the dash pattern.
#[unit(" px")]
dash_offset: f64,
) -> Table<V>
where
Table<V>: VectorTableIterMut + 'n + Send,
{
let stroke = Stroke {
color: color.into(),
weight,
dash_lengths: dash_lengths.into_vec(),
dash_offset,
cap,
join,
join_miter_limit: miter_limit,
align,
transform: DAffine2::IDENTITY,
non_scaling: false,
paint_order,
};
for vector in content.vector_iter_mut() {
let mut stroke = stroke.clone();
stroke.transform *= *vector.transform;
vector.element.style.set_stroke(stroke);
}
content
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn repeat<I: 'n + Send + Clone>(
_: impl Ctx,
// TODO: Implement other graphical types.
#[implementations(Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Color>, Table<GradientStops>)] instance: Table<I>,
#[default(100., 100.)]
// TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed.
direction: PixelSize,
angle: Angle,
#[default(5)] count: IntegerCount,
) -> Table<I> {
let angle = angle.to_radians();
let count = count.max(1);
let total = (count - 1) as f64;
let mut result_table = Table::new();
for index in 0..count {
let angle = index as f64 * angle / total;
let translation = index as f64 * direction / total;
let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation);
for row in instance.iter() {
let mut row = row.into_cloned();
let local_translation = DAffine2::from_translation(row.transform.translation);
let local_matrix = DAffine2::from_mat2(row.transform.matrix2);
row.transform = local_translation * transform * local_matrix;
result_table.push(row);
}
}
result_table
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn circular_repeat<I: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Color>, Table<GradientStops>)] instance: Table<I>,
start_angle: Angle,
#[unit(" px")]
#[default(5)]
radius: f64,
#[default(5)] count: IntegerCount,
) -> Table<I> {
let count = count.max(1);
let mut result_table = Table::new();
for index in 0..count {
let angle = DAffine2::from_angle((TAU / count as f64) * index as f64 + start_angle.to_radians());
let translation = DAffine2::from_translation(radius * DVec2::Y);
let transform = angle * translation;
for row in instance.iter() {
let mut row = row.into_cloned();
let local_translation = DAffine2::from_translation(row.transform.translation);
let local_matrix = DAffine2::from_mat2(row.transform.matrix2);
row.transform = local_translation * transform * local_matrix;
result_table.push(row);
}
}
result_table
}
#[node_macro::node(name("Copy to Points"), category("Instancing"), path(core_types::vector))]
async fn copy_to_points<I: 'n + Send + Clone>(
_: impl Ctx,
points: Table<Vector>,
/// Artwork to be copied and placed at each point.
#[expose]
#[implementations(Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Color>, Table<GradientStops>)]
instance: Table<I>,
/// Minimum range of randomized sizes given to each instance.
#[default(1)]
#[range((0., 2.))]
#[unit("x")]
random_scale_min: Multiplier,
/// Maximum range of randomized sizes given to each instance.
#[default(1)]
#[range((0., 2.))]
#[unit("x")]
random_scale_max: Multiplier,
/// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes).
#[range((-50., 50.))]
random_scale_bias: f64,
/// Seed to determine unique variations on all the randomized instance sizes.
random_scale_seed: SeedValue,
/// Range of randomized angles given to each instance, in degrees ranging from furthest clockwise to counterclockwise.
#[range((0., 360.))]
random_rotation: Angle,
/// Seed to determine unique variations on all the randomized instance angles.
random_rotation_seed: SeedValue,
) -> Table<I> {
let mut result_table = Table::new();
let random_scale_difference = random_scale_max - random_scale_min;
for row in points.into_iter() {
let mut scale_rng = rand::rngs::StdRng::seed_from_u64(random_scale_seed.into());
let mut rotation_rng = rand::rngs::StdRng::seed_from_u64(random_rotation_seed.into());
let do_scale = random_scale_difference.abs() > 1e-6;
let do_rotation = random_rotation.abs() > 1e-6;
let points_transform = row.transform;
for &point in row.element.point_domain.positions() {
let translation = points_transform.transform_point2(point);
let rotation = if do_rotation {
let degrees = (rotation_rng.random::<f64>() - 0.5) * random_rotation;
degrees / 360. * TAU
} else {
0.
};
let scale = if do_scale {
if random_scale_bias.abs() < 1e-6 {
// Linear
random_scale_min + scale_rng.random::<f64>() * random_scale_difference
} else {
// Weighted (see <https://www.desmos.com/calculator/gmavd3m9bd>)
let horizontal_scale_factor = 1. - 2_f64.powf(random_scale_bias);
let scale_factor = (1. - scale_rng.random::<f64>() * horizontal_scale_factor).log2() / random_scale_bias;
random_scale_min + scale_factor * random_scale_difference
}
} else {
random_scale_min
};
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(scale), rotation, translation);
for mut row in instance.iter().map(|row| row.into_cloned()) {
row.transform = transform * row.transform;
result_table.push(row);
}
}
}
result_table
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn mirror<I: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Color>, Table<GradientStops>)] content: Table<I>,
#[default(ReferencePoint::Center)] relative_to_bounds: ReferencePoint,
#[unit(" px")] offset: f64,
#[range((-90., 90.))] angle: Angle,
#[default(true)] keep_original: bool,
) -> Table<I>
where
Table<I>: BoundingBox,
{
// Normalize the direction vector
let normal = DVec2::from_angle(angle.to_radians());
// The mirror reference may be based on the bounding box if an explicit reference point is chosen
let RenderBoundingBox::Rectangle(bounding_box) = content.bounding_box(DAffine2::IDENTITY, false) else {
return content;
};
let reference_point_location = relative_to_bounds.point_in_bounding_box((bounding_box[0], bounding_box[1]).into());
let mirror_reference_point = reference_point_location.map(|point| point + normal * offset);
// Create the reflection matrix
let reflection = DAffine2::from_mat2_translation(
glam::DMat2::from_cols(
DVec2::new(1. - 2. * normal.x * normal.x, -2. * normal.y * normal.x),
DVec2::new(-2. * normal.x * normal.y, 1. - 2. * normal.y * normal.y),
),
DVec2::ZERO,
);
// Apply reflection around the reference point
let reflected_transform = if let Some(mirror_reference_point) = mirror_reference_point {
DAffine2::from_translation(mirror_reference_point) * reflection * DAffine2::from_translation(-mirror_reference_point)
} else {
reflection * DAffine2::from_translation(DVec2::from_angle(angle.to_radians()) * DVec2::splat(-offset))
};
let mut result_table = Table::new();
// Add original instance depending on the keep_original flag
if keep_original {
for instance in content.clone().into_iter() {
result_table.push(instance);
}
}
// Create and add mirrored instance
for mut row in content.into_iter() {
row.transform = reflected_transform * row.transform;
result_table.push(row);
}
result_table
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn round_corners(
_: impl Ctx,
source: Table<Vector>,
#[hard_min(0.)]
#[default(10.)]
radius: PixelLength,
#[range((0., 1.))]
#[hard_min(0.)]
#[hard_max(1.)]
#[default(0.5)]
roundness: f64,
#[default(100.)] edge_length_limit: Percentage,
#[range((0., 180.))]
#[hard_min(0.)]
#[hard_max(180.)]
#[default(5.)]
min_angle_threshold: Angle,
) -> Table<Vector> {
source
.iter()
.map(|source| {
let source_transform = *source.transform;
let source_transform_inverse = source_transform.inverse();
let source_node_id = source.source_node_id;
let source = source.element;
let upstream_nested_layers = source.upstream_data.clone();
// Flip the roundness to help with user intuition
let roundness = 1. - roundness;
// Convert 0-100 to 0-0.5
let edge_length_limit = edge_length_limit * 0.005;
let mut result = Vector {
style: source.style.clone(),
..Default::default()
};
// Grab the initial point ID as a stable starting point
let mut initial_point_id = source.point_domain.ids().first().copied().unwrap_or(PointId::generate());
for mut bezpath in source.stroke_bezpath_iter() {
bezpath.apply_affine(Affine::new(source_transform.to_cols_array()));
let (manipulator_groups, is_closed) = bezpath_to_manipulator_groups(&bezpath);
// End if not enough points for corner rounding
if manipulator_groups.len() < 3 {
result.append_bezpath(bezpath);
continue;
}
let mut new_manipulator_groups = Vec::new();
for i in 0..manipulator_groups.len() {
// Skip first and last points for open paths
if !is_closed && (i == 0 || i == manipulator_groups.len() - 1) {
new_manipulator_groups.push(manipulator_groups[i]);
continue;
}
// Not the prettiest, but it makes the rest of the logic more readable
let prev_idx = if i == 0 { if is_closed { manipulator_groups.len() - 1 } else { 0 } } else { i - 1 };
let curr_idx = i;
let next_idx = if i == manipulator_groups.len() - 1 { if is_closed { 0 } else { i } } else { i + 1 };
let prev = manipulator_groups[prev_idx].anchor;
let curr = manipulator_groups[curr_idx].anchor;
let next = manipulator_groups[next_idx].anchor;
let dir1 = (curr - prev).normalize_or(DVec2::X);
let dir2 = (next - curr).normalize_or(DVec2::X);
let theta = PI - dir1.angle_to(dir2).abs();
// Skip near-straight corners
if theta > PI - min_angle_threshold.to_radians() {
new_manipulator_groups.push(manipulator_groups[curr_idx]);
continue;
}
// Calculate L, with limits to avoid extreme values
let distance_along_edge = radius / (theta / 2.).sin();
let distance_along_edge = distance_along_edge.min(edge_length_limit * (curr - prev).length().min((next - curr).length())).max(0.01);
// Find points on each edge at distance L from corner
let p1 = curr - dir1 * distance_along_edge;
let p2 = curr + dir2 * distance_along_edge;
// Add first point (coming into the rounded corner)
new_manipulator_groups.push(ManipulatorGroup {
anchor: p1,
in_handle: None,
out_handle: Some(curr - dir1 * distance_along_edge * roundness),
id: initial_point_id.next_id(),
});
// Add second point (coming out of the rounded corner)
new_manipulator_groups.push(ManipulatorGroup {
anchor: p2,
in_handle: Some(curr + dir2 * distance_along_edge * roundness),
out_handle: None,
id: initial_point_id.next_id(),
});
}
// One subpath for each shape
let mut rounded_subpath = bezpath_from_manipulator_groups(&new_manipulator_groups, is_closed);
rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array()));
result.append_bezpath(rounded_subpath);
}
result.upstream_data = upstream_nested_layers;
TableRow {
element: result,
transform: source_transform,
alpha_blending: Default::default(),
source_node_id: *source_node_id,
}
})
.collect()
}
#[node_macro::node(name("Merge by Distance"), category("Vector: Modifier"), path(core_types::vector))]
pub fn merge_by_distance(
_: impl Ctx,
content: Table<Vector>,
#[default(0.1)]
#[hard_min(0.0001)]
distance: PixelLength,
algorithm: MergeByDistanceAlgorithm,
) -> Table<Vector> {
match algorithm {
MergeByDistanceAlgorithm::Spatial => content
.into_iter()
.map(|mut row| {
row.element.merge_by_distance_spatial(row.transform, distance);
row
})
.collect(),
MergeByDistanceAlgorithm::Topological => content
.into_iter()
.map(|mut row| {
row.element.merge_by_distance_topological(distance);
row
})
.collect(),
}
}
pub mod extrude_algorithms {
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
use vector_types::subpath::BezierHandles;
use vector_types::vector::StrokeId;
use vector_types::vector::misc::ExtrudeJoiningAlgorithm;
/// Convert [`vector_types::subpath::Bezier`] to [`kurbo::PathSeg`].
fn bezier_to_path_seg(bezier: vector_types::subpath::Bezier) -> kurbo::PathSeg {
let [start, end] = [(bezier.start().x, bezier.start().y), (bezier.end().x, bezier.end().y)];
match bezier.handles {
BezierHandles::Linear => kurbo::Line::new(start, end).into(),
BezierHandles::Quadratic { handle } => kurbo::QuadBez::new(start, (handle.x, handle.y), end).into(),
BezierHandles::Cubic { handle_start, handle_end } => kurbo::CubicBez::new(start, (handle_start.x, handle_start.y), (handle_end.x, handle_end.y), end).into(),
}
}
/// Convert [`kurbo::CubicBez`] to [`vector_types::subpath::BezierHandles`].
fn cubic_to_handles(cubic_bez: kurbo::CubicBez) -> BezierHandles {
BezierHandles::Cubic {
handle_start: DVec2::new(cubic_bez.p1.x, cubic_bez.p1.y),
handle_end: DVec2::new(cubic_bez.p2.x, cubic_bez.p2.y),
}
}
/// Find the `t` values to split (where the tangent changes to be on the other side of the direction).
fn find_splits(cubic_segment: kurbo::CubicBez, direction: DVec2) -> impl Iterator<Item = f64> {
let derivative = cubic_segment.deriv();
let convert = |x: kurbo::Point| DVec2::new(x.x, x.y);
let derivative_points = [derivative.p0, derivative.p1, derivative.p2].map(convert);
let t_squared = derivative_points[0] - 2. * derivative_points[1] + derivative_points[2];
let t_scalar = -2. * derivative_points[0] + 2. * derivative_points[1];
let constant = derivative_points[0];
kurbo::common::solve_quadratic(constant.perp_dot(direction), t_scalar.perp_dot(direction), t_squared.perp_dot(direction))
.into_iter()
.filter(|&t| t > 1e-6 && t < 1. - 1e-6)
}
/// Split so segments no longer have tangents on both sides of the direction vector.
fn split(vector: &mut graphic_types::Vector, direction: DVec2) {
let segment_count = vector.segment_domain.ids().len();
let mut next_point = vector.point_domain.next_id();
let mut next_segment = vector.segment_domain.next_id();
for segment_index in 0..segment_count {
let (_, _, bezier) = vector.segment_points_from_index(segment_index);
let mut start_index = vector.segment_domain.start_point()[segment_index];
let pathseg = bezier_to_path_seg(bezier).to_cubic();
let mut start_t = 0.;
for split_t in find_splits(pathseg, direction) {
let [first, second] = [pathseg.subsegment(start_t..split_t), pathseg.subsegment(split_t..1.)];
let [first_handles, second_handles] = [first, second].map(cubic_to_handles);
let middle_point = next_point.next_id();
let start_segment = next_segment.next_id();
let middle_point_index = vector.point_domain.len();
vector.point_domain.push(middle_point, DVec2::new(first.end().x, first.end().y));
vector.segment_domain.push(start_segment, start_index, middle_point_index, first_handles, StrokeId::ZERO);
vector.segment_domain.set_start_point(segment_index, middle_point_index);
vector.segment_domain.set_handles(segment_index, second_handles);
start_t = split_t;
start_index = middle_point_index;
}
}
}
/// Copy all segments with the offset of `direction`.
fn offset_copy_all_segments(vector: &mut graphic_types::Vector, direction: DVec2) {
let points_count = vector.point_domain.ids().len();
let mut next_point = vector.point_domain.next_id();
for index in 0..points_count {
vector.point_domain.push(next_point.next_id(), vector.point_domain.positions()[index] + direction);
}
let segment_count = vector.segment_domain.ids().len();
let mut next_segment = vector.segment_domain.next_id();
for index in 0..segment_count {
vector.segment_domain.push(
next_segment.next_id(),
vector.segment_domain.start_point()[index] + points_count,
vector.segment_domain.end_point()[index] + points_count,
vector.segment_domain.handles()[index].apply_transformation(|x| x + direction),
vector.segment_domain.stroke()[index],
);
}
}
/// Join points from the original to the copied that are on opposite sides of the direction.
fn join_extrema_edges(vector: &mut graphic_types::Vector, direction: DVec2) {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Found {
#[default]
None,
Positive,
Negative,
Both,
Invalid,
}
impl Found {
fn update(&mut self, value: f64) {
*self = match (*self, value > 0.) {
(Found::None, true) => Found::Positive,
(Found::None, false) => Found::Negative,
(Found::Positive, true) | (Found::Negative, false) => Found::Both,
_ => Found::Invalid,
};
}
}
let first_half_points = vector.point_domain.len() / 2;
let mut points = vec![Found::None; first_half_points];
let first_half_segments = vector.segment_domain.ids().len() / 2;
for segment_id in 0..first_half_segments {
let index = [vector.segment_domain.start_point()[segment_id], vector.segment_domain.end_point()[segment_id]];
let position = index.map(|index| vector.point_domain.positions()[index]);
if position[0].abs_diff_eq(position[1], 1e-6) {
continue; // Skip zero length segments
}
points[index[0]].update(direction.perp_dot(position[1] - position[0]));
points[index[1]].update(direction.perp_dot(position[0] - position[1]));
}
let mut next_segment = vector.segment_domain.next_id();
for (index, &point) in points.iter().enumerate().take(first_half_points) {
if point != Found::Both {
continue;
}
vector
.segment_domain
.push(next_segment.next_id(), index, index + first_half_points, BezierHandles::Linear, StrokeId::ZERO);
}
}
/// Join all points from the original to the copied.
fn join_all(vector: &mut graphic_types::Vector) {
let mut next_segment = vector.segment_domain.next_id();
let first_half = vector.point_domain.len() / 2;
for index in 0..first_half {
vector.segment_domain.push(next_segment.next_id(), index, index + first_half, BezierHandles::Linear, StrokeId::ZERO);
}
}
pub fn extrude(vector: &mut graphic_types::Vector, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) {
split(vector, direction);
offset_copy_all_segments(vector, direction);
match joining_algorithm {
ExtrudeJoiningAlgorithm::Extrema => join_extrema_edges(vector, direction),
ExtrudeJoiningAlgorithm::All => join_all(vector),
ExtrudeJoiningAlgorithm::None => {}
}
}
#[cfg(test)]
mod extrude_tests {
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
#[test]
fn split_cubic() {
let l1 = kurbo::CubicBez::new((0., 0.), (100., 0.), (100., 100.), (0., 100.));
assert_eq!(super::find_splits(l1, DVec2::Y).collect::<Vec<f64>>(), vec![0.5]);
assert!(super::find_splits(l1, DVec2::X).collect::<Vec<f64>>().is_empty());
let l2 = kurbo::CubicBez::new((0., 0.), (0., 0.), (100., 0.), (100., 0.));
assert!(super::find_splits(l2, DVec2::X).collect::<Vec<f64>>().is_empty());
let l3 = kurbo::PathSeg::Line(kurbo::Line::new((0., 0.), (100., 0.)));
assert!(super::find_splits(l3.to_cubic(), DVec2::X).collect::<Vec<f64>>().is_empty());
let l4 = kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.));
let splits = super::find_splits(l4, DVec2::X).map(|t| l4.deriv().eval(t)).collect::<Vec<_>>();
assert_eq!(splits.len(), 2);
assert!(splits.iter().all(|&deriv| deriv.y.abs() < 1e-8), "{splits:?}");
}
#[test]
fn split_vector() {
let curve = kurbo::PathSeg::Cubic(kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.)));
let mut vector = graphic_types::Vector::from_bezpath(kurbo::BezPath::from_path_segments([curve].into_iter()));
super::split(&mut vector, DVec2::X);
assert_eq!(vector.segment_ids().len(), 3);
assert_eq!(vector.point_domain.ids().len(), 4);
}
}
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn extrude(_: impl Ctx, mut source: Table<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> Table<Vector> {
for TableRowMut { element: source, .. } in source.iter_mut() {
extrude_algorithms::extrude(source, direction, joining_algorithm);
}
source
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn box_warp(_: impl Ctx, content: Table<Vector>, #[expose] rectangle: Table<Vector>) -> Table<Vector> {
let Some((target, target_transform)) = rectangle.get(0).map(|rect| (rect.element, rect.transform)) else {
return content;
};
content
.into_iter()
.map(|mut row| {
let transform = row.transform;
let vector = row.element;
// Get the bounding box of the source vector geometry
let source_bbox = vector.bounding_box_with_transform(transform).unwrap_or([DVec2::ZERO, DVec2::ONE]);
// Extract first 4 points from target shape to form the quadrilateral
// Apply the target's transform to get points in world space
let target_points: Vec<DVec2> = target.point_domain.positions().iter().map(|&p| target_transform.transform_point2(p)).take(4).collect();
// If we have fewer than 4 points, use the corners of the source bounding box
// This handles the degenerative case
let dst_corners = if target_points.len() >= 4 {
[target_points[0], target_points[1], target_points[2], target_points[3]]
} else {
warn!("Target shape has fewer than 4 points. Using source bounding box instead.");
[
source_bbox[0],
DVec2::new(source_bbox[1].x, source_bbox[0].y),
source_bbox[1],
DVec2::new(source_bbox[0].x, source_bbox[1].y),
]
};
// Apply the warp
let mut result = vector.clone();
// Precompute source bounding box size for normalization
let source_size = source_bbox[1] - source_bbox[0];
// Transform points
for (_, position) in result.point_domain.positions_mut() {
// Get the point in world space
let world_pos = transform.transform_point2(*position);
// Normalize coordinates within the source bounding box
let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE);
// Apply bilinear interpolation
*position = bilinear_interpolate(t, &dst_corners);
}
// Transform handles in bezier curves
for (_, handles, _, _) in result.handles_mut() {
*handles = handles.apply_transformation(|pos| {
// Get the handle in world space
let world_pos = transform.transform_point2(pos);
// Normalize coordinates within the source bounding box
let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE);
// Apply bilinear interpolation
bilinear_interpolate(t, &dst_corners)
});
}
result.style.set_stroke_transform(DAffine2::IDENTITY);
// Add this to the table and reset the transform since we've applied it directly to the points
row.element = result;
row.transform = DAffine2::IDENTITY;
row
})
.collect()
}
// Interpolate within a quadrilateral using normalized coordinates (0-1)
fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
let tl = quad[0]; // Top-left
let tr = quad[1]; // Top-right
let br = quad[2]; // Bottom-right
let bl = quad[3]; // Bottom-left
// Bilinear interpolation
tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y
}
/// Automatically constructs tangents (Bézier handles) for anchor points in a vector path.
#[node_macro::node(category("Vector: Modifier"), name("Auto-Tangents"), path(core_types::vector))]
async fn auto_tangents(
_: impl Ctx,
source: Table<Vector>,
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
#[default(0.5)]
// TODO: Make this a soft range to allow any value to be typed in outside the slider range of 0 to 1
#[range((0., 1.))]
spread: f64,
/// If active, existing non-zero handles won't be affected.
#[default(true)]
preserve_existing: bool,
) -> Table<Vector> {
source
.iter()
.map(|source| {
let transform = *source.transform;
let alpha_blending = *source.alpha_blending;
let source_node_id = *source.source_node_id;
let source = source.element;
let mut result = Vector {
style: source.style.clone(),
..Default::default()
};
for mut subpath in source.stroke_bezier_paths() {
subpath.apply_transform(transform);
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | true |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/vector/src/lib.rs | node-graph/nodes/vector/src/lib.rs | pub mod generator_nodes;
pub mod instance;
pub mod vector_modification_nodes;
mod vector_nodes;
#[macro_use]
extern crate log;
// Re-export for convenience
pub use core_types as gcore;
pub use generator_nodes::*;
pub use graphic_types;
pub use instance::*;
pub use vector_modification_nodes::*;
pub use vector_nodes::*;
pub use vector_types;
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/vector/src/vector_modification_nodes.rs | node-graph/nodes/vector/src/vector_modification_nodes.rs | use core_types::Ctx;
use core_types::table::Table;
use core_types::uuid::NodeId;
use glam::DAffine2;
use graphic_types::Vector;
use vector_types::vector::VectorModification;
/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments.
#[node_macro::node(category(""))]
async fn path_modify(_ctx: impl Ctx, mut vector: Table<Vector>, modification: Box<VectorModification>, node_path: Vec<NodeId>) -> Table<Vector> {
use core_types::table::TableRow;
if vector.is_empty() {
vector.push(TableRow::default());
}
let row = vector.get_mut(0).expect("push should give one item");
modification.apply(row.element);
// Update the source node id
let this_node_path = node_path.iter().rev().nth(1).copied();
*row.source_node_id = row.source_node_id.or(this_node_path);
if vector.len() > 1 {
warn!("The path modify ran on {} vector rows. Only the first can be modified.", vector.len());
}
vector
}
/// Applies the vector path's local transformation to its geometry and resets the transform to the identity.
#[node_macro::node(category("Vector"))]
async fn apply_transform(_ctx: impl Ctx, mut vector: Table<Vector>) -> Table<Vector> {
for row in vector.iter_mut() {
let vector = row.element;
let transform = *row.transform;
for (_, point) in vector.point_domain.positions_mut() {
*point = transform.transform_point2(*point);
}
*row.transform = DAffine2::IDENTITY;
}
vector
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/vector/src/generator_nodes.rs | node-graph/nodes/vector/src/generator_nodes.rs | use core_types::Ctx;
use core_types::registry::types::{Angle, PixelSize};
use core_types::table::Table;
use glam::DVec2;
use graphic_types::Vector;
use vector_types::subpath;
use vector_types::vector::misc::{ArcType, AsU64, GridType};
use vector_types::vector::misc::{HandleId, SpiralType};
use vector_types::vector::{PointId, SegmentId, StrokeId};
trait CornerRadius {
fn generate(self, size: DVec2, clamped: bool) -> Table<Vector>;
}
impl CornerRadius for f64 {
fn generate(self, size: DVec2, clamped: bool) -> Table<Vector> {
let clamped_radius = if clamped { self.clamp(0., size.x.min(size.y).max(0.) / 2.) } else { self };
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_rounded_rect(size / -2., size / 2., [clamped_radius; 4])))
}
}
impl CornerRadius for [f64; 4] {
fn generate(self, size: DVec2, clamped: bool) -> Table<Vector> {
let clamped_radius = if clamped {
// Algorithm follows the CSS spec: <https://drafts.csswg.org/css-backgrounds/#corner-overlap>
let mut scale_factor: f64 = 1.;
for i in 0..4 {
let side_length = if i % 2 == 0 { size.x } else { size.y };
let adjacent_corner_radius_sum = self[i] + self[(i + 1) % 4];
if side_length < adjacent_corner_radius_sum {
scale_factor = scale_factor.min(side_length / adjacent_corner_radius_sum);
}
}
self.map(|x| x * scale_factor)
} else {
self
};
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_rounded_rect(size / -2., size / 2., clamped_radius)))
}
}
/// Generates a circle shape with a chosen radius.
#[node_macro::node(category("Vector: Shape"))]
fn circle(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(50.)]
radius: f64,
) -> Table<Vector> {
let radius = radius.abs();
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_ellipse(DVec2::splat(-radius), DVec2::splat(radius))))
}
/// Generates an arc shape forming a portion of a circle which may be open, closed, or a pie slice.
#[node_macro::node(category("Vector: Shape"))]
fn arc(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(50.)]
radius: f64,
start_angle: Angle,
#[default(270.)]
#[range((0., 360.))]
sweep_angle: Angle,
arc_type: ArcType,
) -> Table<Vector> {
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_arc(
radius,
start_angle / 360. * std::f64::consts::TAU,
sweep_angle / 360. * std::f64::consts::TAU,
match arc_type {
ArcType::Open => subpath::ArcType::Open,
ArcType::Closed => subpath::ArcType::Closed,
ArcType::PieSlice => subpath::ArcType::PieSlice,
},
)))
}
/// Generates a spiral shape that winds from an inner to an outer radius.
#[node_macro::node(category("Vector: Shape"), properties("spiral_properties"))]
fn spiral(
_: impl Ctx,
_primary: (),
spiral_type: SpiralType,
#[default(5.)] turns: f64,
#[default(0.)] start_angle: f64,
#[default(0.)] inner_radius: f64,
#[default(25)] outer_radius: f64,
#[default(90.)] angular_resolution: f64,
) -> Table<Vector> {
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_spiral(
inner_radius,
outer_radius,
turns,
start_angle.to_radians(),
angular_resolution.to_radians(),
spiral_type,
)))
}
/// Generates an ellipse shape (an oval or stretched circle) with the chosen radii.
#[node_macro::node(category("Vector: Shape"))]
fn ellipse(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(50)]
radius_x: f64,
#[unit(" px")]
#[default(25)]
radius_y: f64,
) -> Table<Vector> {
let radius = DVec2::new(radius_x, radius_y);
let corner1 = -radius;
let corner2 = radius;
let mut ellipse = Vector::from_subpath(subpath::Subpath::new_ellipse(corner1, corner2));
let len = ellipse.segment_domain.ids().len();
for i in 0..len {
ellipse
.colinear_manipulators
.push([HandleId::end(ellipse.segment_domain.ids()[i]), HandleId::primary(ellipse.segment_domain.ids()[(i + 1) % len])]);
}
Table::new_from_element(ellipse)
}
/// Generates a rectangle shape with the chosen width and height. It may also have rounded corners if desired.
#[node_macro::node(category("Vector: Shape"), properties("rectangle_properties"))]
fn rectangle<T: CornerRadius>(
_: impl Ctx,
_primary: (),
#[unit(" px")]
#[default(100)]
width: f64,
#[unit(" px")]
#[default(100)]
height: f64,
_individual_corner_radii: bool, // TODO: Move this to the bottom once we have a migration capability
#[implementations(f64, [f64; 4])] corner_radius: T,
#[default(true)] clamped: bool,
) -> Table<Vector> {
corner_radius.generate(DVec2::new(width, height), clamped)
}
/// Generates an regular polygon shape like a triangle, square, pentagon, hexagon, heptagon, octagon, or any higher n-gon.
#[node_macro::node(category("Vector: Shape"))]
fn regular_polygon<T: AsU64>(
_: impl Ctx,
_primary: (),
#[default(6)]
#[hard_min(3.)]
#[implementations(u32, u64, f64)]
sides: T,
#[unit(" px")]
#[default(50)]
radius: f64,
) -> Table<Vector> {
let points = sides.as_u64();
let radius: f64 = radius * 2.;
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_regular_polygon(DVec2::splat(-radius), points, radius)))
}
/// Generates an n-pointed star shape with inner and outer points at chosen radii from the center.
#[node_macro::node(category("Vector: Shape"))]
fn star<T: AsU64>(
_: impl Ctx,
_primary: (),
#[default(5)]
#[hard_min(2.)]
#[implementations(u32, u64, f64)]
sides: T,
#[unit(" px")]
#[default(50)]
radius_1: f64,
#[unit(" px")]
#[default(25)]
radius_2: f64,
) -> Table<Vector> {
let points = sides.as_u64();
let diameter: f64 = radius_1 * 2.;
let inner_diameter = radius_2 * 2.;
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_star_polygon(DVec2::splat(-diameter), points, diameter, inner_diameter)))
}
/// Generates a line with endpoints at the two chosen coordinates.
#[node_macro::node(category("Vector: Shape"))]
fn line(
_: impl Ctx,
_primary: (),
/// Coordinate of the line's initial endpoint.
#[default(0., 0.)]
start: PixelSize,
/// Coordinate of the line's terminal endpoint.
#[default(100., 100.)]
end: PixelSize,
) -> Table<Vector> {
Table::new_from_element(Vector::from_subpath(subpath::Subpath::new_line(start, end)))
}
trait GridSpacing {
fn as_dvec2(&self) -> DVec2;
}
impl GridSpacing for f64 {
fn as_dvec2(&self) -> DVec2 {
DVec2::splat(*self)
}
}
impl GridSpacing for DVec2 {
fn as_dvec2(&self) -> DVec2 {
*self
}
}
/// Generates a rectangular or isometric grid with the chosen number of columns and rows. Line segments connect the points, forming a vector mesh.
#[node_macro::node(category("Vector: Shape"), properties("grid_properties"))]
fn grid<T: GridSpacing>(
_: impl Ctx,
_primary: (),
grid_type: GridType,
#[unit(" px")]
#[hard_min(0.)]
#[default(10)]
#[implementations(f64, DVec2)]
spacing: T,
#[default(10)] columns: u32,
#[default(10)] rows: u32,
#[default(30., 30.)] angles: DVec2,
) -> Table<Vector> {
let (x_spacing, y_spacing) = spacing.as_dvec2().into();
let (angle_a, angle_b) = angles.into();
let mut vector = Vector::default();
let mut segment_id = SegmentId::ZERO;
let mut point_id = PointId::ZERO;
match grid_type {
GridType::Rectangular => {
// Create rectangular grid points and connect them with line segments
for y in 0..rows {
for x in 0..columns {
// Add current point to the grid
let current_index = vector.point_domain.ids().len();
vector.point_domain.push(point_id.next_id(), DVec2::new(x_spacing * x as f64, y_spacing * y as f64));
// Helper function to connect points with line segments
let mut push_segment = |to_index: Option<usize>| {
if let Some(other_index) = to_index {
vector
.segment_domain
.push(segment_id.next_id(), other_index, current_index, subpath::BezierHandles::Linear, StrokeId::ZERO);
}
};
// Connect to the point to the left (horizontal connection)
push_segment((x > 0).then(|| current_index - 1));
// Connect to the point above (vertical connection)
push_segment(current_index.checked_sub(columns as usize));
}
}
}
GridType::Isometric => {
// Calculate isometric grid spacing based on angles
let tan_a = angle_a.to_radians().tan();
let tan_b = angle_b.to_radians().tan();
let spacing = DVec2::new(y_spacing / (tan_a + tan_b), y_spacing);
// Create isometric grid points and connect them with line segments
for y in 0..rows {
for x in 0..columns {
// Add current point to the grid with offset for odd columns
let current_index = vector.point_domain.ids().len();
let a_angles_eaten = x.div_ceil(2) as f64;
let b_angles_eaten = (x / 2) as f64;
let offset_y_fraction = b_angles_eaten * tan_b - a_angles_eaten * tan_a;
let position = DVec2::new(spacing.x * x as f64, spacing.y * y as f64 + offset_y_fraction * spacing.x);
vector.point_domain.push(point_id.next_id(), position);
// Helper function to connect points with line segments
let mut push_segment = |to_index: Option<usize>| {
if let Some(other_index) = to_index {
vector
.segment_domain
.push(segment_id.next_id(), other_index, current_index, subpath::BezierHandles::Linear, StrokeId::ZERO);
}
};
// Connect to the point to the left
push_segment((x > 0).then(|| current_index - 1));
// Connect to the point directly above
push_segment(current_index.checked_sub(columns as usize));
// Additional diagonal connections for odd columns (creates hexagonal pattern)
if x % 2 == 1 {
// Connect to the point diagonally up-right (if not at right edge)
push_segment(current_index.checked_sub(columns as usize - 1).filter(|_| x + 1 < columns));
// Connect to the point diagonally up-left
push_segment(current_index.checked_sub(columns as usize + 1));
}
}
}
}
}
Table::new_from_element(vector)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn isometric_grid_test() {
// Doesn't crash with weird angles
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
// Works properly
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
assert_eq!(grid.iter().next().unwrap().element.point_domain.ids().len(), 5 * 5);
assert_eq!(grid.iter().next().unwrap().element.segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.iter().next().unwrap().element.segment_bezier_iter() {
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
assert!(
((bezier.start - bezier.end).length() - 10.).abs() < 1e-5,
"Length of {} should be 10",
(bezier.start - bezier.end).length()
);
}
}
#[test]
fn skew_isometric_grid_test() {
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
assert_eq!(grid.iter().next().unwrap().element.point_domain.ids().len(), 5 * 5);
assert_eq!(grid.iter().next().unwrap().element.segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.iter().next().unwrap().element.segment_bezier_iter() {
assert_eq!(bezier.handles, subpath::BezierHandles::Linear);
let vector = bezier.start - bezier.end;
let angle = (vector.angle_to(DVec2::X).to_degrees() + 180.) % 180.;
assert!([90., 150., 40.].into_iter().any(|target| (target - angle).abs() < 1e-10), "unexpected angle of {angle}")
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/vector/src/instance.rs | node-graph/nodes/vector/src/instance.rs | use core_types::Color;
use core_types::table::{Table, TableRowRef};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractIndex, ExtractVarArgs, InjectVarArgs, OwnedContextImpl};
use glam::DVec2;
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, Raster};
use vector_types::GradientStops;
use log::*;
#[repr(transparent)]
#[derive(dyn_any::DynAny)]
struct HashableDVec2(DVec2);
impl std::hash::Hash for HashableDVec2 {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.x.to_bits().hash(state);
self.0.y.to_bits().hash(state);
}
}
#[node_macro::node(name("Instance on Points"), category("Instancing"), path(core_types::vector))]
async fn instance_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
points: Table<Vector>,
#[implementations(
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Color>,
Context -> Table<GradientStops>,
)]
instance: impl Node<'n, Context<'static>, Output = Table<T>>,
reverse: bool,
) -> Table<T> {
let mut result_table = Table::new();
for TableRowRef { element: points, transform, .. } in points.iter() {
let mut iteration = async |index, point| {
let transformed_point = transform.transform_point2(point);
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_vararg(Box::new(HashableDVec2(transformed_point)));
let generated_instance = instance.eval(new_ctx.into_context()).await;
for mut generated_row in generated_instance.into_iter() {
generated_row.transform.translation = transformed_point;
result_table.push(generated_row);
}
};
let range = points.point_domain.positions().iter().enumerate();
if reverse {
for (index, &point) in range.rev() {
iteration(index, point).await;
}
} else {
for (index, &point) in range {
iteration(index, point).await;
}
}
}
result_table
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn instance_repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
#[implementations(
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Color>,
Context -> Table<GradientStops>,
)]
instance: impl Node<'n, Context<'static>, Output = Table<T>>,
#[default(1)] count: u64,
reverse: bool,
) -> Table<T> {
let count = count.max(1) as usize;
let mut result_table = Table::new();
for index in 0..count {
let index = if reverse { count - index - 1 } else { index };
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index);
let generated_instance = instance.eval(new_ctx.into_context()).await;
for generated_row in generated_instance.into_iter() {
result_table.push(generated_row);
}
}
result_table
}
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn instance_position(ctx: impl Ctx + ExtractVarArgs) -> DVec2 {
match ctx.vararg(0).map(|dynamic| dynamic.downcast_ref::<HashableDVec2>()) {
Ok(Some(position)) => return position.0,
Ok(_) => warn!("Extracted value of incorrect type"),
Err(e) => warn!("Cannot extract position vararg: {e:?}"),
}
Default::default()
}
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
#[node_macro::node(category("Instancing"), path(core_types::vector))]
async fn instance_index(ctx: impl Ctx + ExtractIndex, _primary: (), loop_level: u32) -> f64 {
let Some(index_iter) = ctx.try_index() else { return 0. };
let mut last = 0;
for (i, index) in index_iter.enumerate() {
if i == loop_level as usize {
return index as f64;
}
last = index;
}
last as f64
}
#[cfg(test)]
mod test {
use super::*;
use crate::generator_nodes::RectangleNode;
use core_types::Ctx;
use core_types::Node;
use glam::DVec2;
use graphene_core::extract_xy::{ExtractXyNode, XY};
use graphic_types::Vector;
use std::future::Future;
use std::pin::Pin;
use vector_types::subpath::Subpath;
#[derive(Clone)]
pub struct FutureWrapperNode<T: Clone>(T);
impl<'i, I: Ctx, T: 'i + Clone + Send> Node<'i, I> for FutureWrapperNode<T> {
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
fn eval(&'i self, _input: I) -> Self::Output {
let value = self.0.clone();
Box::pin(async move { value })
}
}
#[tokio::test]
async fn instance_on_points_test() {
let owned = OwnedContextImpl::default().into_context();
let rect = RectangleNode::new(
FutureWrapperNode(()),
ExtractXyNode::new(InstancePositionNode {}, FutureWrapperNode(XY::Y)),
FutureWrapperNode(2_f64),
FutureWrapperNode(false),
FutureWrapperNode(0_f64),
FutureWrapperNode(false),
);
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
let points = Table::new_from_element(Vector::from_subpath(Subpath::from_anchors_linear(positions, false)));
let generated = super::instance_on_points(owned, points, &rect, false).await;
assert_eq!(generated.len(), positions.len());
for (position, generated_row) in positions.into_iter().zip(generated.iter()) {
let bounds = generated_row.element.bounding_box_with_transform(*generated_row.transform).unwrap();
assert!(position.abs_diff_eq((bounds[0] + bounds[1]) / 2., 1e-10));
assert_eq!((bounds[1] - bounds[0]).x, position.y);
}
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
GraphiteEditor/Graphite | https://github.com/GraphiteEditor/Graphite/blob/42440c0d0bcf5735b05d8a9e5bd27187f74b1589/node-graph/nodes/brush/src/brush_stroke.rs | node-graph/nodes/brush/src/brush_stroke.rs | use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::math::bbox::AxisAlignedBbox;
use dyn_any::DynAny;
use glam::DVec2;
use std::hash::{Hash, Hasher};
/// The style of a brush.
#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)]
pub struct BrushStyle {
pub color: Color,
pub diameter: f64,
pub hardness: f64,
pub flow: f64,
pub spacing: f64, // Spacing as a fraction of the diameter.
pub blend_mode: BlendMode,
}
impl Default for BrushStyle {
fn default() -> Self {
Self {
color: Color::BLACK,
diameter: 40.,
hardness: 50.,
flow: 100.,
spacing: 50., // Percentage of diameter.
blend_mode: BlendMode::Normal,
}
}
}
impl Hash for BrushStyle {
fn hash<H: Hasher>(&self, state: &mut H) {
self.color.hash(state);
self.diameter.to_bits().hash(state);
self.hardness.to_bits().hash(state);
self.flow.to_bits().hash(state);
self.spacing.to_bits().hash(state);
self.blend_mode.hash(state);
}
}
impl Eq for BrushStyle {}
impl PartialEq for BrushStyle {
fn eq(&self, other: &Self) -> bool {
self.color == other.color
&& self.diameter.to_bits() == other.diameter.to_bits()
&& self.hardness.to_bits() == other.hardness.to_bits()
&& self.flow.to_bits() == other.flow.to_bits()
&& self.spacing.to_bits() == other.spacing.to_bits()
&& self.blend_mode == other.blend_mode
}
}
/// A single sample of brush parameters across the brush stroke.
#[derive(Clone, Debug, PartialEq, DynAny, serde::Serialize, serde::Deserialize)]
pub struct BrushInputSample {
// The position of the sample in layer space, in pixels.
// The origin of layer space is not specified.
pub position: DVec2,
// Future work: pressure, stylus angle, etc.
}
impl Hash for BrushInputSample {
fn hash<H: Hasher>(&self, state: &mut H) {
self.position.x.to_bits().hash(state);
self.position.y.to_bits().hash(state);
}
}
/// The parameters for a single stroke brush.
#[derive(Clone, Debug, PartialEq, Hash, Default, DynAny, serde::Serialize, serde::Deserialize)]
pub struct BrushStroke {
pub style: BrushStyle,
pub trace: Vec<BrushInputSample>,
}
impl BrushStroke {
pub fn bounding_box(&self) -> AxisAlignedBbox {
let radius = self.style.diameter / 2.;
self.compute_blit_points()
.iter()
.map(|pos| AxisAlignedBbox {
start: *pos + DVec2::new(-radius, -radius),
end: *pos + DVec2::new(radius, radius),
})
.reduce(|a, b| a.union(&b))
.unwrap_or(AxisAlignedBbox::ZERO)
}
pub fn compute_blit_points(&self) -> Vec<DVec2> {
// We always travel in a straight line towards the next user input,
// placing a blit point every time we travelled our spacing distance.
let spacing_dist = self.style.spacing / 100. * self.style.diameter;
let Some(first_sample) = self.trace.first() else {
return Vec::new();
};
let mut cur_pos = first_sample.position;
let mut result = vec![cur_pos];
let mut dist_until_next_blit = spacing_dist;
for sample in &self.trace[1..] {
// Travel to the next sample.
let delta = sample.position - cur_pos;
let mut dist_left = delta.length();
let unit_step = delta / dist_left;
while dist_left >= dist_until_next_blit {
// Take a step to the next blit point.
cur_pos += dist_until_next_blit * unit_step;
dist_left -= dist_until_next_blit;
// Blit.
result.push(cur_pos);
dist_until_next_blit = spacing_dist;
}
// Take the partial step to land at the sample.
dist_until_next_blit -= dist_left;
cur_pos = sample.position;
}
result
}
}
| rust | Apache-2.0 | 42440c0d0bcf5735b05d8a9e5bd27187f74b1589 | 2026-01-04T15:38:29.103662Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.