Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add iOS support #103

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ winapi = { version = "0.3.9", features = [
clipboard-win = "4.4.2"
log = "0.4"

[target.'cfg(target_os = "macos")'.dependencies]
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
objc = "0.2"
objc_id = "0.1"
objc-foundation = "0.1"
Expand Down
24 changes: 17 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ mod platform;

#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten")),
not(any(
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "emscripten"
)),
))]
pub use platform::{ClearExtLinux, GetExtLinux, LinuxClipboardKind, SetExtLinux};

Expand Down Expand Up @@ -94,7 +99,7 @@ impl Clipboard {
/// Any image data placed on the clipboard with `set_image` will be possible read back, using
/// this function. However it's of not guaranteed that an image placed on the clipboard by any
/// other application will be of a supported format.
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", not(target_os = "ios")))]
pub fn get_image(&mut self) -> Result<ImageData<'static>, Error> {
self.get().image()
}
Expand All @@ -106,7 +111,7 @@ impl Clipboard {
/// - On macOS: `NSImage` object
/// - On Linux: PNG, under the atom `image/png`
/// - On Windows: In order of priority `CF_DIB` and `CF_BITMAP`
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", not(target_os = "ios")))]
pub fn set_image(&mut self, image: ImageData) -> Result<(), Error> {
self.set().image(image)
}
Expand Down Expand Up @@ -151,7 +156,7 @@ impl Get<'_> {
/// Any image data placed on the clipboard with `set_image` will be possible read back, using
/// this function. However it's of not guaranteed that an image placed on the clipboard by any
/// other application will be of a supported format.
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", not(target_os = "ios")))]
pub fn image(self) -> Result<ImageData<'static>, Error> {
self.platform.image()
}
Expand Down Expand Up @@ -192,7 +197,7 @@ impl Set<'_> {
/// - On macOS: `NSImage` object
/// - On Linux: PNG, under the atom `image/png`
/// - On Windows: In order of priority `CF_DIB` and `CF_BITMAP`
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", not(target_os = "ios")))]
pub fn image(self, image: ImageData) -> Result<(), Error> {
self.platform.image(image)
}
Expand Down Expand Up @@ -285,7 +290,7 @@ mod tests {
ctx.set_html(html, Some(alt_text)).unwrap();
assert_eq!(ctx.get_text().unwrap(), alt_text);
}
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", not(target_os = "ios")))]
{
let mut ctx = Clipboard::new().unwrap();
#[rustfmt::skip]
Expand Down Expand Up @@ -327,7 +332,12 @@ mod tests {
}
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten")),
not(any(
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "emscripten"
)),
))]
{
use crate::{LinuxClipboardKind, SetExtLinux};
Expand Down
75 changes: 63 additions & 12 deletions src/platform/osx.rs → src/platform/apple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,24 @@ use once_cell::sync::Lazy;
use std::borrow::Cow;

// Required to bring NSPasteboard into the path of the class-resolver
#[cfg(target_os = "macos")]
#[link(name = "AppKit", kind = "framework")]
extern "C" {
static NSPasteboardTypeHTML: *const Object;
static NSPasteboardTypeString: *const Object;
}

#[cfg(target_os = "macos")]
const PASTEBOARD_CLASS: &str = "NSPasteboard";
#[cfg(target_os = "ios")]
const PASTEBOARD_CLASS: &str = "UIPasteboard";

static NSSTRING_CLASS: Lazy<&Class> = Lazy::new(|| Class::get("NSString").unwrap());
#[cfg(feature = "image-data")]
static NSIMAGE_CLASS: Lazy<&Class> = Lazy::new(|| Class::get("NSImage").unwrap());

/// Returns an NSImage object on success.
#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", target_os = "macos"))]
fn image_from_pixels(
pixels: Vec<u8>,
width: usize,
Expand Down Expand Up @@ -99,7 +105,8 @@ pub(crate) struct Clipboard {

impl Clipboard {
pub(crate) fn new() -> Result<Clipboard, Error> {
let cls = Class::get("NSPasteboard").expect("NSPasteboard not registered");
let cls = Class::get(PASTEBOARD_CLASS)
.unwrap_or_else(|| panic!("{} not registered", PASTEBOARD_CLASS));
let pasteboard: *mut Object = unsafe { msg_send![cls, generalPasteboard] };

if !pasteboard.is_null() {
Expand All @@ -115,7 +122,12 @@ impl Clipboard {
}

fn clear(&mut self) {
#[cfg(target_os = "macos")]
let _: usize = unsafe { msg_send![self.pasteboard, clearContents] };
#[cfg(target_os = "ios")]
let _: () = unsafe {
msg_send![self.pasteboard, setItems: NSArray::from_vec(Vec::<Id<NSString>>::new())]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the right array type to clear any existing content type? The docs seem to say this is essentially an array of [String; Any] but its unclear if this matches. At a glance, this needs an inner dictionary type instead of a plain NSString?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type here doesn't really matter, I just want to send an empty array to the items property.
It is indeed technically wrong, so I'll push a fix.

};
}

// fn get_binary_contents(&mut self) -> Result<Option<ClipboardContent>, Box<dyn std::error::Error>> {
Expand Down Expand Up @@ -178,6 +190,18 @@ impl<'clipboard> Get<'clipboard> {
Self { pasteboard: &*clipboard.pasteboard }
}

#[cfg(target_os = "ios")]
pub(crate) fn text(self) -> Result<String, Error> {
let obj: *mut NSString = unsafe { msg_send![self.pasteboard, string] };
if obj.is_null() {
Err(Error::ContentNotAvailable)
} else {
let id: Id<NSString> = unsafe { Id::from_ptr(obj) };
Ok(id.as_str().to_owned())
}
}

#[cfg(target_os = "macos")]
pub(crate) fn text(self) -> Result<String, Error> {
let string_class = object_class(&NSSTRING_CLASS);
let classes: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(vec![string_class]);
Expand All @@ -200,7 +224,7 @@ impl<'clipboard> Get<'clipboard> {
.ok_or(Error::ContentNotAvailable)
}

#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", target_os = "macos"))]
pub(crate) fn image(self) -> Result<ImageData<'static>, Error> {
use std::io::Cursor;

Expand Down Expand Up @@ -261,13 +285,26 @@ impl<'clipboard> Set<'clipboard> {
pub(crate) fn text(self, data: Cow<'_, str>) -> Result<(), Error> {
self.clipboard.clear();

let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]);
let success: bool =
unsafe { msg_send![self.clipboard.pasteboard, writeObjects: string_array] };
#[cfg(target_os = "macos")]
let success: bool = {
let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]);
unsafe { msg_send![self.clipboard.pasteboard, writeObjects: string_array] }
};
#[cfg(target_os = "ios")]
let success: bool = {
let string = NSString::from_str(&data);
unsafe { msg_send![self.clipboard.pasteboard, setString: string] }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did this (and other callsites) get mixed up? setString appears to be only a method on NSPasteboard.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setString is the objc way of setting a value for the string property, same as setItems.

};

if success {
Ok(())
} else {
Err(Error::Unknown { description: "NSPasteboard#writeObjects: returned false".into() })
Err(Error::Unknown {
description: format!(
"{PASTEBOARD_CLASS}#{}: returned false",
if cfg!(target_os = "ios") { "setString" } else { "writeObjects" }
),
})
}
}

Expand All @@ -284,25 +321,39 @@ impl<'clipboard> Set<'clipboard> {
html
);
let html_nss = NSString::from_str(&html);
#[cfg(target_os = "macos")]
let mut success: bool = unsafe {
msg_send![self.clipboard.pasteboard, setString: html_nss forType:NSPasteboardTypeHTML]
};
#[cfg(target_os = "ios")]
let mut success: bool = unsafe { msg_send![self.clipboard.pasteboard, setString: html_nss] };

if success {
if let Some(alt_text) = alt {
let alt_nss = NSString::from_str(&alt_text);
success = unsafe {
msg_send![self.clipboard.pasteboard, setString: alt_nss forType:NSPasteboardTypeString]
};
#[cfg(target_os = "macos")]
{
success = unsafe {
msg_send![self.clipboard.pasteboard, setString: alt_nss forType:NSPasteboardTypeString]
};
}

#[cfg(target_os = "ios")]
{
success = unsafe { msg_send![self.clipboard.pasteboard, setString: alt_nss] };
}
}
}
if success {
Ok(())
} else {
Err(Error::Unknown { description: "NSPasteboard#writeObjects: returned false".into() })
Err(Error::Unknown {
description: format!("{PASTEBOARD_CLASS}#writeObjects: returned false"),
})
}
}

#[cfg(feature = "image-data")]
#[cfg(all(feature = "image-data", target_os = "macos"))]
pub(crate) fn image(self, data: ImageData) -> Result<(), Error> {
let pixels = data.bytes.into();
let image = image_from_pixels(pixels, data.width, data.height)
Expand Down
25 changes: 19 additions & 6 deletions src/platform/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))))]
#[cfg(all(
unix,
not(any(
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "emscripten"
))
))]
mod linux;
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
not(any(
target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "emscripten"
))
))]
pub use linux::*;

Expand All @@ -11,7 +24,7 @@ mod windows;
#[cfg(windows)]
pub use windows::*;

#[cfg(target_os = "macos")]
mod osx;
#[cfg(target_os = "macos")]
pub(crate) use osx::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod apple;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) use apple::*;