Add macOS support for rich text

This commit is contained in:
Federico Terzi 2020-10-23 21:28:05 +02:00
parent c43774a59f
commit 37bd79039f
4 changed files with 37 additions and 0 deletions

View File

@ -170,6 +170,11 @@ int32_t set_clipboard(char * text);
*/
int32_t set_clipboard_image(char * path);
/*
* Set the clipboard html
*/
int32_t set_clipboard_html(char * html, char * fallback);
/*
* If a process is currently holding SecureInput, then return 1 and set the pid pointer to the corresponding PID.
*/

View File

@ -324,6 +324,24 @@ int32_t set_clipboard_image(char *path) {
return result;
}
int32_t set_clipboard_html(char * html, char * fallback_text) {
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSArray *array = @[NSRTFPboardType, NSPasteboardTypeString];
[pasteboard declareTypes:array owner:nil];
NSString *nsHtml = [NSString stringWithUTF8String:html];
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute,[NSNumber numberWithInt:NSUTF8StringEncoding], nil];
NSAttributedString* atr = [[NSAttributedString alloc] initWithData:[nsHtml dataUsingEncoding:NSUTF8StringEncoding] options:documentAttributes documentAttributes:nil error:nil];
NSData *rtf = [atr RTFFromRange:NSMakeRange(0, [atr length])
documentAttributes:nil];
[pasteboard setData:rtf forType:NSRTFPboardType];
NSString *nsText = [NSString stringWithUTF8String:fallback_text];
[pasteboard setString:nsText forType:NSPasteboardTypeString];
}
// CONTEXT MENU

View File

@ -51,6 +51,7 @@ extern "C" {
pub fn get_clipboard(buffer: *mut c_char, size: i32) -> i32;
pub fn set_clipboard(text: *const c_char) -> i32;
pub fn set_clipboard_image(path: *const c_char) -> i32;
pub fn set_clipboard_html(html: *const c_char, text_fallback: *const c_char) -> i32;
// UI
pub fn register_icon_click_callback(cb: extern "C" fn(_self: *mut c_void));

View File

@ -65,6 +65,19 @@ impl super::ClipboardManager for MacClipboardManager {
}
}
}
fn set_clipboard_html(&self, html: &str) {
// Render the text fallback for those applications that don't support HTML clipboard
let decorator = html2text::render::text_renderer::TrivialDecorator::new();
let text_fallback =
html2text::from_read_with_decorator(html.as_bytes(), 1000000, decorator);
unsafe {
let payload_c =
CString::new(html).expect("unable to create CString for html content");
let payload_fallback_c = CString::new(text_fallback).unwrap();
set_clipboard_html(payload_c.as_ptr(), payload_fallback_c.as_ptr());
}
}
}
impl MacClipboardManager {