use std::{marker::PhantomData, rc::Rc};
use ::windows::{
Win32::{
Foundation::{HANDLE, HWND},
System::DataExchange::{CloseClipboard, EmptyClipboard, OpenClipboard, SetClipboardData},
UI::WindowsAndMessaging::{CreateWindowExW, DestroyWindow, HWND_MESSAGE, IsWindow, WINDOW_EX_STYLE, WINDOW_STYLE},
},
core::w,
};
use super::{Platform, Session, memory::Data};
pub(super) struct Native;
pub(super) struct Owner {
hwnd: HWND,
_thread: PhantomData<Rc<()>>,
}
pub(super) struct Open {
opened: bool,
_thread: PhantomData<Rc<()>>,
}
impl Platform for Native {
type Owner = Owner;
type Data = Data;
type Session = Open;
fn prepare(&self, text: &str) -> Option<Data> {
Data::prepare(text)
}
fn owner(&self) -> Option<Owner> {
let hwnd = unsafe {
CreateWindowExW(
WINDOW_EX_STYLE::default(),
w!("STATIC"),
w!("LurqClipboardOwner"),
WINDOW_STYLE::default(),
0,
0,
0,
0,
Some(HWND_MESSAGE),
None,
None,
None,
)
}
.ok()?;
Some(Owner {
hwnd,
_thread: PhantomData,
})
}
fn open(&self, owner: &Owner) -> Option<Open> {
if !unsafe { IsWindow(Some(owner.hwnd)) }.as_bool() {
return None;
}
unsafe { OpenClipboard(Some(owner.hwnd)) }.ok()?;
Some(Open {
opened: true,
_thread: PhantomData,
})
}
}
impl Session for Open {
type Data = Data;
fn empty(&mut self) -> bool {
self.opened && unsafe { EmptyClipboard() }.is_ok()
}
fn put(&mut self, data: Data) -> bool {
if !self.opened {
return false;
}
if unsafe { SetClipboardData(13, Some(HANDLE(data.handle().0))) }.is_err() {
return false;
}
data.transfer(); true
}
fn close(&mut self) -> bool {
if !self.opened {
return true;
}
self.opened = false;
unsafe { CloseClipboard() }.is_ok()
}
}
impl Drop for Open {
fn drop(&mut self) {
if self.opened && !self.close() {
tracing::warn!("clipboard session could not be closed");
}
}
}
impl Drop for Owner {
fn drop(&mut self) {
if unsafe { DestroyWindow(self.hwnd) }.is_err() {
tracing::warn!("clipboard owner window could not be destroyed");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ::windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;
#[test]
fn windows_clipboard_real_owner_is_process_owned_until_drop() {
let owner = Native.owner().expect("own message-only test window");
let hwnd = owner.hwnd;
let mut pid = 0;
assert_ne!(unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) }, 0);
assert_eq!(pid, std::process::id());
assert!(unsafe { IsWindow(Some(hwnd)) }.as_bool());
drop(owner);
assert!(!unsafe { IsWindow(Some(hwnd)) }.as_bool());
}
}