8000 Fix: Daemon clipboard on linux by jooaf · Pull Request #11 · jooaf/thoth · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
555 changes: 232 additions & 323 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
name = "thoth-cli"
version = "0.1.62"
edition = "2021"
authors = ["Joel Afriyie <joel.o.afriyie@gmail.com>", "Joel Afriyie <oren.beani@gmail.com>"]
authors = [
"Joel Afriyie <joel.o.afriyie@gmail.com>",
"Joel Afriyie <oren.beani@gmail.com>",
]
description = "A terminal scratchpad akin to Heynote"
license = "MIT"
repository = "https://github.com/jooaf/thoth"
Expand All @@ -18,7 +21,6 @@ pulldown-cmark-to-cmark = "15.0.1"
ratatui = "0.27.0"
crossterm = { version = "0.27.0", features = ["bracketed-paste"] }
tui-textarea = "0.5.1"
copypasta = "0.10.1"
anyhow = "1.0.86"
clap = { version = "4.3", features = ["derive"] }
dirs = "5.0"
Expand All @@ -28,6 +30,7 @@ syntect-tui = "3.0.2"
unicode-width = "0.1.10"
rand = "0.8.5"
once_cell = "1.19.0"
arboard = "3.4.1"

[[bin]]
name = "thoth"
Expand Down
6 changes: 3 additions & 3 deletions src/cli.rs
8000
Original file line numberDiff line number Diff line change
@@ -1,6 +1,5 @@
use crate::EditorClipboard;
use anyhow::{bail, Result};
use copypasta::{ClipboardContext, ClipboardProvider};

use std::{
fs::File,
io::{BufRead, BufReader, Write},
Expand Down Expand Up @@ -136,7 +135,7 @@ pub fn copy_block(name: &str) -> Result<()> {

for (block_name, block_content) in blocks {
if block_name == name {
let result_ctx = ClipboardContext::new();
let result_ctx = EditorClipboard::new();

if result_ctx.is_err() {
bail!("Failed to create clipboard context for copy block");
Expand All @@ -153,6 +152,7 @@ pub fn copy_block(name: &str) -> Result<()> {
));
}
matched_name = Some(block_name);
break;
}
}
match matched_name {
Expand Down
74 changes: 74 additions & 0 deletions src/clipboard.rs
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use anyhow::Result;
use arboard::{Clipboard, Error};
use std::env;
use std::process;
use std::sync::{Arc, Mutex};

#[cfg(target_os = "linux")]
use arboard::SetExtLinux;

use crate::DAEMONIZE_ARG;

pub struct EditorClipboard {
clipboard: Arc<Mutex<Clipboard>>,
}

impl EditorClipboard {
pub fn new() -> Result<EditorClipboard, Error> {
Clipboard::new().map(|c| EditorClipboard {
clipboard: Arc::new(Mutex::new(c)),
})
}

pub fn try_new() -> Option<EditorClipboard> {
Self::new().ok()
}

pub fn set_contents(&mut self, content: String) -> Result<(), Error> {
#[cfg(target_os = "linux")]
{
if env::args().nth(1).as_deref() == Some(DAEMONIZE_ARG) {
let mut clipboard = self
.clipboard
.lock()
.map_err(|_e| arboard::Error::ContentNotAvailable)?;
clipboard.set().wait().text(content)?;
} else {
process::Command::new(env::current_exe().unwrap())
.arg(DAEMONIZE_ARG)
.arg(content)
.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null())
.current_dir("/")
.spawn()
.map_err(|_e| arboard::Error::ContentNotAvailable)?;
}
}

#[cfg(not(target_os = "linux"))]
{
let mut clipboard = self.clipboard.lock().unwrap();
clipboard.set_text(content)?;
}

Ok(())
}

pub fn get_content(&mut self) -> Result<String, Error> {
let mut clipboard = self.clipboard.lock().unwrap();
clipboard.get_text()
}

#[cfg(target_os = "linux")]
pub fn handle_daemon_args() -> Result<(), Error> {
if let Some(content) = env::args().nth(2) {
if env::args().nth(1).as_deref() == Some(DAEMONIZE_ARG) {
let mut clipboard = Self::new()?;
clipboard.set_contents(content)?;
std::process::exit(0);
}
}
Ok(())
}
}
8 changes: 5 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod cli;
pub mod clipboard;
pub mod formatter;
pub mod markdown_renderer;
pub mod scrollable_textarea;
Expand All @@ -8,18 +9,19 @@ pub mod ui;
pub mod ui_handler;
pub mod utils;

pub use clipboard::EditorClipboard;
use dirs::home_dir;
pub use formatter::{format_json, format_markdown};
pub use markdown_renderer::MarkdownRenderer;
pub use scrollable_textarea::ScrollableTextArea;
use std::path::PathBuf;
pub use title_popup::TitlePopup;
pub use title_select_popup::TitleSelectPopup;
pub use utils::{load_textareas, save_textareas};

use dirs::home_dir;
use std::path::PathBuf;

pub fn get_save_file_path() -> PathBuf {
home_dir().unwrap_or_default().join("thoth_notes.md")
}

pub const ORANGE: ratatui::style::Color = ratatui::style::Color::Rgb(255, 165, 0);
pub const DAEMONIZE_ARG: &str = "__thoth_copy_daemonize";
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ use crossterm::{
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{self, Read};
use thoth_cli::cli::{add_block, copy_block, delete_block, list_blocks, view_block};
use thoth_cli::{
cli::{add_block, copy_block, delete_block, list_blocks, view_block},
EditorClipboard,
};
use thoth_cli::{
cli::{Cli, Commands},
ui_handler::{draw_ui, handle_input, UIState},
Expand All @@ -16,6 +19,8 @@ use thoth_cli::{
use std::time::Duration;

fn main() -> Result<()> {
#[cfg(target_os = "linux")]
EditorClipboard::handle_daemon_args()?;
let cli = Cli::parse();

match &cli.command {
Expand Down
8 changes: 4 additions & 4 deletions src/scrollable_textarea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use std::{
rc::Rc,
};

use crate::EditorClipboard;
use crate::{MarkdownRenderer, ORANGE};
use anyhow;
use anyhow::Result;
use copypasta::{ClipboardContext, ClipboardProvider};
use rand::Rng;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
Expand Down Expand Up @@ -144,7 +144,7 @@ impl ScrollableTextArea {
pub fn copy_textarea_contents(&self) -> Result<()> {
if let Some(textarea) = self.textareas.get(self.focused_index) {
let content = textarea.lines().join("\n");
let mut ctx = ClipboardContext::new()
let mut ctx = EditorClipboard::new()
.map_err(|e| anyhow::anyhow!("Failed to create clipboard context: {}", e))?;
ctx.set_contents(content)
.map_err(|e| anyhow::anyhow!("Failed to set clipboard contents: {}", e))?;
Expand Down Expand Up @@ -216,7 +216,7 @@ impl ScrollableTextArea {
pub fn copy_focused_textarea_contents(&self) -> anyhow::Result<()> {
if let Some(textarea) = self.textareas.get(self.focused_index) {
let content = textarea.lines().join("\n");
let mut ctx = ClipboardContext::new().unwrap();
let mut ctx = EditorClipboard::new().unwrap();
ctx.set_contents(content).unwrap();
}
Ok(())
Expand All @@ -231,7 +231,7 @@ impl ScrollableTextArea {

if max_row <= all_lines.len() {
let content = all_lines[min_row..max_row].join("\n");
let mut ctx = ClipboardContext::new().unwrap();
let mut ctx = EditorClipboard::new().unwrap();
ctx.set_contents(content).unwrap();
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/ui_handler.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::EditorClipboard;
use anyhow::{bail, Result};
use copypasta::{ClipboardContext, ClipboardProvider};
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, KeyCode, KeyModifiers},
execute,
Expand Down Expand Up @@ -32,7 +32,7 @@ pub struct UIState {
pub title_select_popup: TitleSelectPopup,
pub error_popup: ErrorPopup,
pub edit_commands_popup: EditCommandsPopup,
pub clipboard: Option<ClipboardContext>,
pub clipboard: Option<EditorClipboard>,
pub last_draw: Instant,
}

Expand All @@ -55,7 +55,7 @@ impl UIState {
title_select_popup: TitleSelectPopup::new(),
error_popup: ErrorPopup::new(),
edit_commands_popup: EditCommandsPopup::new(),
clipboard: ClipboardContext::new().ok(),
clipboard: EditorClipboard::try_new(),
last_draw: Instant::now(),
})
}
Expand Down Expand Up @@ -476,7 +476,7 @@ fn handle_paste(state: &mut UIState) -> Result<()> {
if state.scrollable_textarea.edit_mode {
match &mut state.clipboard {
Some(clip) => {
if let Ok(content) = clip.get_contents() {
if let Ok(content) = clip.get_content() {
let textarea = &mut state.scrollable_textarea.textareas
[state.scrollable_textarea.focused_index];
for line in content.lines() {
Expand Down
0