Skip to content

Commit

Permalink
Fix clipboard on linux
Browse files Browse the repository at this point in the history
  • Loading branch information
evilwaveforms committed Oct 19, 2024
1 parent a7d98da commit 1a10a2a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
20 changes: 20 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ struct Cli {
#[clap(long)]
no_clipboard: bool,

// Used internally for maintaining clipboard on linux.
#[clap(long, hide = true)]
daemon: bool,

// Used internally for maintaining clipboard on linux.
#[clap(long, hide = true)]
clipboard_content: Option<String>,

/// Optional Path to a custom Handlebars template
#[clap(short, long)]
template: Option<PathBuf>,
Expand All @@ -100,6 +108,18 @@ fn main() -> Result<()> {
env_logger::init();
let args = Cli::parse();

if args.daemon {
if let Some(clipboard_content) = args.clipboard_content.as_ref() {
return match copy_to_clipboard(&clipboard_content) {
Ok(_) => Ok(()),
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1)
}
}
}
}

// Handlebars Template Setup
let (template_content, template_name) = get_template(&args)?;
let handlebars = handlebars_setup(&template_content, template_name)?;
Expand Down
31 changes: 24 additions & 7 deletions src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
use anyhow::{Context, Result};
use arboard::Clipboard;
use arboard::SetExtLinux;
use colored::*;
use handlebars::{no_escape, Handlebars};
use inquire::Text;
use regex::Regex;
use std::io::Write;
use std::{env, process};

/// Set up the Handlebars template engine with a template string and a template name.
///
Expand Down Expand Up @@ -116,14 +118,29 @@ pub fn handle_undefined_variables(
///
/// * `Result<()>` - An empty result indicating success or an error.
pub fn copy_to_clipboard(rendered: &str) -> Result<()> {
match Clipboard::new() {
Ok(mut clipboard) => {
clipboard
.set_text(rendered.to_string())
.context("Failed to copy to clipboard")?;
Ok(())
if cfg!(target_os = "linux") {
if env::args().any(|arg| arg == "--daemon") {
let mut clipboard = Clipboard::new().context("Failed to initialize clipboard in daemon")?;
clipboard.set().wait().text(rendered).context("Failed to copy to clipboard in daemon")?;
return Ok(());
}
process::Command::new(env::current_exe()?)
.arg(".") // Path is required arg. Can be set as anything here.
.arg("--daemon")
.arg("--clipboard-content")
.arg(rendered)
.spawn().context("Failed to spawn daemon process")?;
return Ok(())
} else {
match Clipboard::new() {
Ok(mut clipboard) => {
clipboard
.set_text(rendered.to_string())
.context("Failed to copy to clipboard")?;
Ok(())
}
Err(e) => Err(anyhow::anyhow!("Failed to initialize clipboard: {}", e)),
}
Err(e) => Err(anyhow::anyhow!("Failed to initialize clipboard: {}", e)),
}
}

Expand Down

0 comments on commit 1a10a2a

Please sign in to comment.