Skip to content

Commit

Permalink
Prefer the file path of a file on macOS if present
Browse files Browse the repository at this point in the history
This prefers the path of a file URL (NSPasteboardTypeFileURL) over
plain text (NSPasteboardTypeString)
  • Loading branch information
conradev authored Oct 10, 2023
1 parent 10f1137 commit 3d4f8ee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Bump minimum supported Rust version to `1.61.0`
- Change `ClipboardProvider::set_contents` parameter type to `AsRef<str>`
- Prefer file's path over text on macOS

## 0.8.2

Expand Down
22 changes: 17 additions & 5 deletions src/osx_clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
// limitations under the License.

use objc::rc::autoreleasepool;
use objc::runtime::{Class, Object, Sel, BOOL, NO};
use objc::{msg_send, sel, sel_impl};
use objc::runtime::{Class, Object, BOOL, NO, YES};
use objc::{class, msg_send, sel, sel_impl};
use objc_foundation::{INSArray, INSString};
use objc_foundation::{NSArray, NSString};
use objc_id::Id;
Expand All @@ -28,7 +28,8 @@ pub struct OSXClipboardContext {
// required to bring NSPasteboard into the path of the class-resolver
#[link(name = "AppKit", kind = "framework")]
extern "C" {
pub static NSPasteboardTypeString: Sel;
pub static NSPasteboardTypeFileURL: *mut Object;
pub static NSPasteboardTypeString: *mut Object;
}

impl OSXClipboardContext {
Expand All @@ -47,14 +48,25 @@ impl ClipboardProvider for OSXClipboardContext {
fn get_contents(&mut self) -> Result<String> {
autoreleasepool(|| unsafe {
let types: *mut NSArray<*mut NSString> = msg_send![self.pasteboard, types];
let has_file: BOOL = msg_send![types, containsObject: NSPasteboardTypeFileURL];
let has_str: BOOL = msg_send![types, containsObject: NSPasteboardTypeString];

if has_str == NO {
return Err("NSPasteboard#types doesn't contain NSPasteboardTypeString".into());
}

let text: *mut NSString =
msg_send![self.pasteboard, stringForType: NSPasteboardTypeString];
let text = if has_file == YES {
let file_url_string: *mut NSString =
msg_send![self.pasteboard, stringForType: NSPasteboardTypeFileURL];
let file_url: *mut Object =
msg_send![class!(NSURL), URLWithString: file_url_string];
let text: *mut NSString = msg_send![file_url, path];
text
} else {
let text: *mut NSString =
msg_send![self.pasteboard, stringForType: NSPasteboardTypeString];
text
};

if text.is_null() {
return Err(("NSPasteboard#stringForType returned null").into());
Expand Down

0 comments on commit 3d4f8ee

Please sign in to comment.