use std::path::PathBuf;
use objc::runtime::Object;
use objc::{class, msg_send, sel, sel_impl};
use objc_id::ShareId;
use url::Url;
use crate::error::Error;
use crate::foundation::{id, nil, NSArray, NSString, NSURL};
mod types;
pub use types::{PasteboardName, PasteboardType};
#[derive(Debug)]
pub struct Pasteboard(pub ShareId<Object>);
impl Default for Pasteboard {
fn default() -> Self {
Pasteboard(unsafe { ShareId::from_ptr(msg_send![class!(NSPasteboard), generalPasteboard]) })
}
}
impl Pasteboard {
pub(crate) fn with(existing: id) -> Self {
Pasteboard(unsafe { ShareId::from_ptr(existing) })
}
pub fn named(name: PasteboardName) -> Self {
Pasteboard(unsafe {
let name: NSString = name.into();
ShareId::from_ptr(msg_send![class!(NSPasteboard), pasteboardWithName:&*name])
})
}
pub fn unique() -> Self {
Pasteboard(unsafe { ShareId::from_ptr(msg_send![class!(NSPasteboard), pasteboardWithUniqueName]) })
}
pub fn copy_text<S: AsRef<str>>(&self, text: S) {
let contents = NSString::new(text.as_ref());
let ptype: NSString = PasteboardType::String.into();
unsafe {
let _: () = msg_send![&*self.0, setString:&*contents forType:ptype];
}
}
pub fn release_globally(&self) {
unsafe {
let _: () = msg_send![&*self.0, releaseGlobally];
}
}
pub fn clear_contents(&self) {
unsafe {
let _: () = msg_send![&*self.0, clearContents];
}
}
pub fn get_file_urls(&self) -> Result<Vec<NSURL>, Box<dyn std::error::Error>> {
unsafe {
let class: id = msg_send![class!(NSURL), class];
let classes = NSArray::new(&[class]);
let contents: id = msg_send![&*self.0, readObjectsForClasses:classes options:nil];
if contents == nil {
return Err(Box::new(Error {
code: 666,
domain: "com.cacao-rs.pasteboard".to_string(),
description: "Pasteboard server returned no data.".to_string()
}));
}
let urls = NSArray::retain(contents).map(|url| NSURL::retain(url)).into_iter().collect();
Ok(urls)
}
}
}