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

Update clipboard-win to 4.2.1 #11

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[package]
name = "win32yank"
version = "0.1.0"
version = "0.2.0"
authors = ["raf"]
edition = "2018"

[package.metadata.docs.rs]
default-target = "x86_64-pc-windows-gnu"

[dependencies]
docopt = "0.6"
rustc-serialize = "0.3"
clipboard-win = "1.7"
winapi = "0.2"
user32-sys = "0.2"
kernel32-sys = "0.2"
windows-error = "1.0"
docopt = "1.1.1"
serde = { version = "1.0.129", features = ["derive"] }
clipboard-win = "4.2.1"
4 changes: 2 additions & 2 deletions contrib/appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
environment:
rustversion: 1.18.0
rustversion: 1.54.0
install:
# Need Mingw to build C bits
- SET PATH=%PATH%;C:\MinGW\bin
- ps: Start-FileDownload http://static.rust-lang.org/dist/rust-$env:RUSTVERSION-$env:PLATFORM-pc-windows-msvc.exe -FileName rust.exe
- ps: Start-FileDownload http://static.rust-lang.org/dist/rust-$env:RUSTVERSION-$env:PLATFORM-pc-windows-msvc.msi -FileName rust.exe
- rust.exe /VERYSILENT /NORESTART /DIR="C:\Program Files\Rust"
- SET PATH=%PATH%;C:\Program Files\Rust\bin
- rustc -vV
Expand Down
102 changes: 21 additions & 81 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,10 @@
extern crate clipboard_win;
extern crate docopt;
extern crate rustc_serialize;
extern crate winapi;
extern crate user32;
extern crate kernel32;
extern crate windows_error;

use windows_error::WindowsError;
use clipboard_win::wrapper::{get_last_error, open_clipboard, close_clipboard};
use clipboard_win::clipboard_formats::CF_UNICODETEXT;
use clipboard_win::{formats, SysResult};
use docopt::Docopt;
use kernel32::{GlobalLock, GlobalUnlock};
use winapi::winnt::HANDLE;
use user32::{GetClipboardData, EnumClipboardFormats};
use serde::Deserialize;
use std::io;
use std::io::Read;

const USAGE: &'static str = "
const USAGE: &str = "
win32yank

Usage:
Expand All @@ -30,73 +18,26 @@ Options:
--crlf Replace lone LF bytes with CRLF before setting the clipboard
";

#[derive(Debug, RustcDecodable)]
#[derive(Debug, Deserialize)]
struct Args {
flag_o: bool,
flag_i: bool,
flag_lf: bool,
flag_crlf: bool,
}

fn from_wide_ptr(ptr: *const u16) -> String {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

if ptr.is_null() {
return String::new();
}

unsafe {
assert!(!ptr.is_null());
let len = (0..std::isize::MAX).position(|i| *ptr.offset(i) == 0).unwrap();
let slice = std::slice::from_raw_parts(ptr, len);
OsString::from_wide(slice).to_string_lossy().into_owned()
}
}

fn get_clipboard(replace_crlf: bool) -> Result<String, WindowsError> {
let result: Result<String, WindowsError>;
try!(open_clipboard());

// Check clipboard contents, return empty string if unicode text
// is not available
let mut enumfmt = 0;
loop {
match unsafe {EnumClipboardFormats(enumfmt)} {
// Either the call failed or there are no more formats
0 => return Ok(String::new()),
v if v == CF_UNICODETEXT => break,
other => enumfmt = other,
}
}

unsafe {
let text_handler: HANDLE = GetClipboardData(CF_UNICODETEXT as u32);

if text_handler.is_null() {
result = Err(get_last_error());
} else {
let text_p = GlobalLock(text_handler) as *const u16;
result = Ok(from_wide_ptr(text_p));
GlobalUnlock(text_handler);
}
}
try!(close_clipboard());

fn get_clipboard(replace_crlf: bool) -> SysResult<String> {
let content: SysResult<String> = clipboard_win::get_clipboard(formats::Unicode);
if replace_crlf {
result.map(|data| data.replace("\r\n", "\n"))
content.map(|data| data.replace("\r\n", "\n"))
} else {
result
content
}
}

fn set_clipboard(content: &str, replace_lf: bool) -> Result<(), WindowsError> {
// clipboard_win::wrapper::set_clipboard uses CF_UNICODETEXT,
// which is what we want

fn set_clipboard(content: &str, replace_lf: bool) -> SysResult<()> {
if replace_lf {
let chunks = content.split("\r\n")
.map(|item| item.replace("\n", "\r\n"));
let chunks = content.split("\r\n").map(|item| item.replace("\n", "\r\n"));
let mut first = true;
let mut out = String::with_capacity(content.len());
for chunk in chunks {
Expand All @@ -107,32 +48,31 @@ fn set_clipboard(content: &str, replace_lf: bool) -> Result<(), WindowsError> {
}
out.push_str(&chunk);
}
clipboard_win::set_clipboard(&out)
clipboard_win::set_clipboard(formats::Unicode, &out)
} else {
clipboard_win::set_clipboard(content)
clipboard_win::set_clipboard(formats::Unicode, content)
}
}

fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());

if args.flag_o {
let content = get_clipboard(args.flag_lf).unwrap();
let content: String = get_clipboard(args.flag_crlf).unwrap();
print!("{}", content);
} else if args.flag_i {
let mut stdin = io::stdin();
let mut content = String::new();
stdin.read_to_string(&mut content).unwrap();
set_clipboard(&content, args.flag_crlf).unwrap();
set_clipboard(&content, args.flag_lf).unwrap();
}
}

#[test]
fn test() {
// Windows dislikes if we lock the clipboard too long
// sleep for bit
// Windows dislikes if we lock the clipboard too long sleep for bit
use std::thread::sleep;
use std::time::Duration;
let sleep_time = 300;
Expand All @@ -157,8 +97,6 @@ fn test() {
assert_eq!(get_clipboard(false).unwrap(), v);
sleep(Duration::from_millis(sleep_time));

//
// set_clipboard(true)
set_clipboard("", true).unwrap();
assert_eq!(get_clipboard(false).unwrap(), "");
sleep(Duration::from_millis(sleep_time));
Expand All @@ -173,6 +111,8 @@ fn test() {

let v = "\r\nfrom\r\nwin32yank\r\n\n...\\r\n";
set_clipboard(v, true).unwrap();
assert_eq!(get_clipboard(false).unwrap(),
"\r\nfrom\r\nwin32yank\r\n\r\n...\\r\r\n");
assert_eq!(
get_clipboard(false).unwrap(),
"\r\nfrom\r\nwin32yank\r\n\r\n...\\r\r\n"
);
}