Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
247 changes: 167 additions & 80 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ log = "0.4"
num-traits = "0.2"
portable-atomic = { version = "1.10", features = ["float", "serde"] }
raw-window-handle = "0.6"
slint = { version = "1.12.1", default-features = false, features = ["accessibility", "compat-1-2", "std"] }
slint = { version = "1.13.1", default-features = false, features = ["accessibility", "compat-1-2", "std"] }

# Internal slint crate versions need to be pinned
# since they don't maintain semver compatibility
i-slint-common = "1.12.1"
i-slint-core = "1.12.1"
i-slint-renderer-skia = { version = "1.12.1", features = ["x11"] }
i-slint-common = "1.13.1"
i-slint-core = "1.13.1"
i-slint-renderer-skia = { version = "1.13.1", features = ["x11"] }

[patch.crates-io]
# FIXME: Needed for loading cursors to work, remove once the fix has shipped
Expand Down
4 changes: 2 additions & 2 deletions examples/gain-plugin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ plinth-plugin.workspace = true
plugin-canvas-slint.workspace = true
serde = "1.0"
serde_json = "1.0"
slint = { version = "1.10", default-features = false, features = ["accessibility", "compat-1-2", "std"] }
slint = { version = "1.13", default-features = false, features = ["accessibility", "compat-1-2", "std"] }

[build-dependencies]
slint-build = "1.10"
slint-build = "1.13"
2 changes: 0 additions & 2 deletions plugin-canvas-slint/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ impl SlintEditor {
// It's ok if this fails as it just means it has already been set
slint::platform::set_platform(Box::new(PluginCanvasPlatform)).ok();

// This is Arc only to appease slint
#[expect(clippy::arc_with_non_send_sync)]
let window = Arc::new(window);
WINDOW_TO_SLINT.set(Some(window.clone()));

Expand Down
1 change: 1 addition & 0 deletions plugin-canvas/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod drag_drop;
pub mod error;
pub mod event;
pub mod keyboard;
pub mod thread_bound;
pub mod window;

pub use dimensions::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize};
Expand Down
8 changes: 4 additions & 4 deletions plugin-canvas/src/platform/mac/view.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::{cell::RefCell, ffi::{c_void, CString}, ops::{Deref, DerefMut}, path::PathBuf, rc::Weak, str::FromStr, sync::atomic::{AtomicPtr, AtomicU8, AtomicUsize, Ordering}};
use std::{cell::RefCell, ffi::{c_void, CString}, ops::{Deref, DerefMut}, path::PathBuf, str::FromStr, sync::{atomic::{AtomicPtr, AtomicU8, AtomicUsize, Ordering}, Weak}};

use objc2::{declare::ClassBuilder, msg_send, runtime::{AnyClass, Bool}, sel, ClassType, Encode, Encoding, Message, RefEncode};
use objc2::runtime::{Sel, ProtocolObject};
use objc2_app_kit::{NSDragOperation, NSDraggingInfo, NSEvent, NSEventModifierFlags, NSPasteboardTypeFileURL, NSView};
use objc2_foundation::{NSPoint, NSRect, NSURL};
use uuid::Uuid;

use crate::{drag_drop::{DropData, DropOperation}, event::EventResponse, keyboard::KeyboardModifiers, Event, LogicalPosition, MouseButton};
use crate::{drag_drop::{DropData, DropOperation}, event::EventResponse, keyboard::KeyboardModifiers, thread_bound::ThreadBound, Event, LogicalPosition, MouseButton};

use super::{keyboard::key_event_to_keyboard_type_code, window::OsWindow};

Expand All @@ -15,7 +15,7 @@ pub struct OsWindowView {
}

struct Context {
os_window_ptr: AtomicPtr<OsWindow>,
os_window_ptr: AtomicPtr<ThreadBound<OsWindow>>,
input_focus: AtomicU8,
keyboard_modifiers: RefCell<KeyboardModifiers>,
}
Expand Down Expand Up @@ -81,7 +81,7 @@ impl OsWindowView {
builder.register()
}

pub(crate) fn set_os_window_ptr(&self, ptr: *mut OsWindow) {
pub(crate) fn set_os_window_ptr(&self, ptr: *mut ThreadBound<OsWindow>) {
self.with_context(|context| context.os_window_ptr.store(ptr, Ordering::Release));
}

Expand Down
12 changes: 7 additions & 5 deletions plugin-canvas/src/platform/mac/window.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{cell::RefCell, ptr::{null_mut, NonNull}, rc::Rc, sync::atomic::{AtomicBool, Ordering}};
use std::{cell::RefCell, ptr::{null_mut, NonNull}, sync::{atomic::{AtomicBool, Ordering}, Arc}};

use cursor_icon::CursorIcon;
use objc2::{msg_send, rc::{Allocated, Retained}, sel, AllocAnyThread};
Expand All @@ -9,7 +9,7 @@ use objc2_foundation::{MainThreadMarker, NSArray, NSDefaultRunLoopMode, NSPoint,
use objc2_quartz_core::CADisplayLink;
use raw_window_handle::{AppKitWindowHandle, HasDisplayHandle, HasWindowHandle, RawWindowHandle};

use crate::{platform::os_window_handle::OsWindowHandle, Event, LogicalPosition};
use crate::{platform::os_window_handle::OsWindowHandle, thread_bound::ThreadBound, Event, LogicalPosition};
use crate::error::Error;
use crate::event::{EventCallback, EventResponse};
use crate::platform::interface::OsWindowInterface;
Expand Down Expand Up @@ -88,15 +88,17 @@ impl OsWindowInterface for OsWindow {

let main_thread_marker = MainThreadMarker::new().unwrap();

let window = Rc::new(Self {
let window = Self {
window_handle,
display_link: Default::default(),
event_callback,

cursor_hidden: Default::default(),

main_thread_marker,
});
};

let window = Arc::new(ThreadBound::new(window));

let display_link = unsafe { view.displayLinkWithTarget_selector(&view, sel!(drawRect:)) };

Expand All @@ -106,7 +108,7 @@ impl OsWindowInterface for OsWindow {

*window.display_link.borrow_mut() = Some(display_link);

view.set_os_window_ptr(Rc::downgrade(&window).into_raw() as _);
view.set_os_window_ptr(Arc::downgrade(&window).into_raw() as _);

Ok(OsWindowHandle::new(window))
}
Expand Down
9 changes: 6 additions & 3 deletions plugin-canvas/src/platform/os_window_handle.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use std::{ops::Deref, rc::Rc};
use std::sync::Arc;
use std::ops::Deref;

use raw_window_handle::{HasDisplayHandle, HasWindowHandle};

use crate::thread_bound::ThreadBound;

use super::window::OsWindow;

pub(crate) struct OsWindowHandle {
os_window: Rc<OsWindow>,
os_window: Arc<ThreadBound<OsWindow>>,
}

impl OsWindowHandle {
pub(super) fn new(os_window: Rc<OsWindow>) -> Self {
pub(super) fn new(os_window: Arc<ThreadBound<OsWindow>>) -> Self {
Self {
os_window,
}
Expand Down
7 changes: 4 additions & 3 deletions plugin-canvas/src/platform/win32/drop_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::ffi::OsString;
use std::ops::Deref;
use std::os::windows::prelude::OsStringExt;
use std::ptr::null_mut;
use std::rc::Weak;
use std::sync::Weak;

use windows::Win32::Foundation::{POINTL, POINT};
use windows::Win32::Graphics::Gdi::MapWindowPoints;
Expand All @@ -16,18 +16,19 @@ use windows::Win32::UI::WindowsAndMessaging::HWND_DESKTOP;

use crate::event::EventResponse;
use crate::platform::interface::OsWindowInterface;
use crate::thread_bound::ThreadBound;
use crate::{LogicalPosition, PhysicalPosition};
use crate::drag_drop::{DropData, DropOperation};
use super::window::OsWindow;

#[implement(IDropTarget)]
pub(super) struct DropTarget {
window: Weak<OsWindow>,
window: Weak<ThreadBound<OsWindow>>,
drop_data: RefCell<DropData>,
}

impl DropTarget {
pub fn new(window: Weak<OsWindow>) -> Self {
pub fn new(window: Weak<ThreadBound<OsWindow>>) -> Self {
Self {
window,
drop_data: Default::default(),
Expand Down
16 changes: 10 additions & 6 deletions plugin-canvas/src/platform/win32/window.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{cell::RefCell, ffi::OsString, mem::{size_of, transmute}, num::NonZeroIsize, os::windows::prelude::OsStringExt, ptr::{null, null_mut}, rc::{Rc, Weak}, sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Arc}, time::Duration};
use std::sync::Weak;
use std::{cell::RefCell, ffi::OsString, mem::{size_of, transmute}, num::NonZeroIsize, os::windows::prelude::OsStringExt, ptr::{null, null_mut}, sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Arc}, time::Duration};

use cursor_icon::CursorIcon;
use keyboard_types::Code;
Expand All @@ -10,6 +11,7 @@ use windows::Win32::Graphics::{Dwm::{DwmFlush, DwmIsCompositionEnabled}, Dxgi::{
use windows::Win32::System::{Ole::{IDropTarget, OleInitialize, RegisterDragDrop, RevokeDragDrop}, Threading::GetCurrentThreadId};
use windows::Win32::UI::{Controls::WM_MOUSELEAVE, Input::KeyboardAndMouse::{GetAsyncKeyState, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT, VK_CONTROL, VK_MENU, VK_SHIFT}, WindowsAndMessaging::{CallNextHookEx, CreateWindowExW, DefWindowProcW, DestroyWindow, GetWindowLongPtrW, LoadCursorW, MoveWindow, PostMessageW, RegisterClassW, SendMessageW, SetCursor, SetCursorPos, SetWindowLongPtrW, SetWindowsHookExW, ShowCursor, UnhookWindowsHookEx, UnregisterClassW, CS_OWNDC, GWLP_USERDATA, HHOOK, HICON, IDC_ARROW, MOUSEHOOKSTRUCTEX, WH_MOUSE, WINDOW_EX_STYLE, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOVE, WM_RBUTTONDOWN, WM_RBUTTONUP, WNDCLASSW, WS_CHILD, WS_VISIBLE}};

use crate::thread_bound::ThreadBound;
use crate::{dimensions::Size, error::Error, event::{Event, EventCallback, EventResponse, MouseButton}, keyboard::KeyboardModifiers, platform::{interface::OsWindowInterface, os_window_handle::OsWindowHandle}, window::WindowAttributes, LogicalPosition, LogicalSize, PhysicalPosition};

use super::{cursors::Cursors, drop_target::DropTarget, message_window::MessageWindow, to_wstr, version::is_windows10_or_greater, PLUGIN_HINSTANCE, WM_USER_CHAR, WM_USER_FRAME_TIMER, WM_USER_KEY_DOWN, WM_USER_KEY_UP};
Expand Down Expand Up @@ -174,7 +176,7 @@ impl OsWindowInterface for OsWindow {
move || message_window.run(running)
});

let window = Rc::new(Self {
let window = Self {
window_class,
window_handle,
hook_handle,
Expand All @@ -189,9 +191,11 @@ impl OsWindowInterface for OsWindow {
moved,

keyboard_modifiers: Default::default(),
});
};

let window = Arc::new(ThreadBound::new(window));

let drop_target: Box<IDropTarget> = Box::new(DropTarget::new(Rc::downgrade(&window)).into());
let drop_target: Box<IDropTarget> = Box::new(DropTarget::new(Arc::downgrade(&window)).into());

unsafe {
OleInitialize(None)?;
Expand All @@ -200,7 +204,7 @@ impl OsWindowInterface for OsWindow {

*window.drop_target.borrow_mut() = Some(drop_target);

unsafe { SetWindowLongPtrW(hwnd, GWLP_USERDATA, Rc::downgrade(&window).into_raw() as _) };
unsafe { SetWindowLongPtrW(hwnd, GWLP_USERDATA, Arc::downgrade(&window).into_raw() as _) };

Ok(OsWindowHandle::new(window))
}
Expand Down Expand Up @@ -316,7 +320,7 @@ impl HasDisplayHandle for OsWindow {
}

unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
let window_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *mut OsWindow;
let window_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *mut ThreadBound<OsWindow>;
if window_ptr.is_null() {
return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
}
Expand Down
68 changes: 68 additions & 0 deletions plugin-canvas/src/platform/win32/window_handle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::cell::UnsafeCell;
use std::sync::{Arc, Weak};
use std::thread::ThreadId;

use crate::platform::window::OsWindow;

pub(crate) struct OsWindowHandle {
os_window: Arc<UnsafeCell<OsWindow>>,
thread: ThreadId,
}

impl OsWindowHandle {
// OsWindow is not Send + Sync but we are
#[expect(clippy::arc_with_non_send_sync)]
pub(super) fn new(os_window: OsWindow) -> Self {
Self {
os_window: Arc::new(os_window.into()),
thread: std::thread::current().id(),
}
}

pub fn as_window(&self) -> &OsWindow {
assert_eq!(std::thread::current().id(), self.thread);

// SAFETY: It's checked above that we're not on another thread
unsafe { &*self.os_window.get() }
}

pub(super) fn downgrade(&self) -> OsWindowWeak {
OsWindowWeak {
os_window: Arc::downgrade(&self.os_window),
thread: self.thread,
}
}
}

unsafe impl Send for OsWindowHandle {}
unsafe impl Sync for OsWindowHandle {}

#[derive(Clone)]
pub(super) struct OsWindowWeak {
os_window: Weak<UnsafeCell<OsWindow>>,
thread: ThreadId,
}

impl OsWindowWeak {
pub fn upgrade(&self) -> Option<OsWindowHandle> {
let os_window = self.os_window.upgrade()?;

Some(OsWindowHandle {
os_window,
thread: self.thread,
})
}

pub fn into_raw(self) -> *const UnsafeCell<OsWindow> {
Weak::into_raw(self.os_window)
}

/// SAFETY:
/// Must be called from the same thread as into_raw() was called from
pub unsafe fn from_raw(ptr: *const UnsafeCell<OsWindow>) -> Self {
Self {
os_window: unsafe { Weak::from_raw(ptr) },
thread: std::thread::current().id(),
}
}
}
19 changes: 9 additions & 10 deletions plugin-canvas/src/platform/x11/window.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::sync::Arc;
use std::{cell::RefCell, ffi::OsStr, num::NonZeroU32, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}};

use cursor_icon::CursorIcon;
Expand Down Expand Up @@ -97,15 +98,13 @@ impl OsWindow {
for keysym in xkb_state.key_get_syms(x11_keycode) {
xkb_compose_state.feed(*keysym);

if xkb_compose_state.status() == xkb::Status::Composed {
if let Some(text) = xkb_compose_state.utf8() {
self.send_event(Event::KeyDown {
key_code: keycode,
text: Some(text),
});

sent_event_with_text = true;
}
if xkb_compose_state.status() == xkb::Status::Composed && let Some(text) = xkb_compose_state.utf8() {
self.send_event(Event::KeyDown {
key_code: keycode,
text: Some(text),
});

sent_event_with_text = true;
}
}

Expand Down Expand Up @@ -302,7 +301,7 @@ impl OsWindowInterface for OsWindow {
showing_cursor: true.into(),
};

Ok(OsWindowHandle::new(window.into()))
Ok(OsWindowHandle::new(Arc::new(window.into())))
}

fn os_scale(&self) -> f64 {
Expand Down
46 changes: 46 additions & 0 deletions plugin-canvas/src/thread_bound.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::thread::ThreadId;

pub struct ThreadBound<T> {
inner: UnsafeCell<T>,
thread: ThreadId,
}

impl<T> ThreadBound<T> {
pub fn new(inner: T) -> Self {
Self {
inner: inner.into(),
thread: std::thread::current().id(),
}
}

fn assert_thread(&self) {
assert_eq!(std::thread::current().id(), self.thread, "Tried to access inner ThreadBound value from an invalid thread");
}
}

impl<T> Deref for ThreadBound<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
self.assert_thread();
unsafe { &*self.inner.get() }
}
}

impl<T> DerefMut for ThreadBound<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.assert_thread();
self.inner.get_mut()
}
}

impl<T> From<T> for ThreadBound<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}

unsafe impl<T> Send for ThreadBound<T> {}
unsafe impl<T> Sync for ThreadBound<T> {}
Loading