Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use std::sync::Arc;

use helix_core::syntax;
use helix_view::graphics::{Margin, Rect, Style};
use tui::buffer::Buffer;
use tui::widgets::{BorderType, Paragraph, Widget, Wrap};

use crate::compositor::{Component, Compositor, Context};

use crate::ui::Markdown;

use super::Popup;

pub struct SignatureHelp {
    signature: String,
    signature_doc: Option<String>,
    /// Part of signature text
    active_param_range: Option<(usize, usize)>,

    language: String,
    config_loader: Arc<syntax::Loader>,
}

impl SignatureHelp {
    pub const ID: &'static str = "signature-help";

    pub fn new(signature: String, language: String, config_loader: Arc<syntax::Loader>) -> Self {
        Self {
            signature,
            signature_doc: None,
            active_param_range: None,
            language,
            config_loader,
        }
    }

    pub fn set_signature_doc(&mut self, signature_doc: Option<String>) {
        self.signature_doc = signature_doc;
    }

    pub fn set_active_param_range(&mut self, offset: Option<(usize, usize)>) {
        self.active_param_range = offset;
    }

    pub fn visible_popup(compositor: &mut Compositor) -> Option<&mut Popup<Self>> {
        compositor.find_id::<Popup<Self>>(Self::ID)
    }
}

impl Component for SignatureHelp {
    fn render(&mut self, area: Rect, surface: &mut Buffer, cx: &mut Context) {
        let margin = Margin::horizontal(1);

        let active_param_span = self.active_param_range.map(|(start, end)| {
            vec![(
                cx.editor.theme.find_scope_index("ui.selection").unwrap(),
                start..end,
            )]
        });

        let sig_text = crate::ui::markdown::highlighted_code_block(
            self.signature.clone(),
            &self.language,
            Some(&cx.editor.theme),
            Arc::clone(&self.config_loader),
            active_param_span,
        );

        let (_, sig_text_height) = crate::ui::text::required_size(&sig_text, area.width);
        let sig_text_area = area.clip_top(1).with_height(sig_text_height);
        let sig_text_area = sig_text_area.inner(&margin).intersection(surface.area);
        let sig_text_para = Paragraph::new(sig_text).wrap(Wrap { trim: false });
        sig_text_para.render(sig_text_area, surface);

        if self.signature_doc.is_none() {
            return;
        }

        let sep_style = Style::default();
        let borders = BorderType::line_symbols(BorderType::Plain);
        for x in sig_text_area.left()..sig_text_area.right() {
            if let Some(cell) = surface.get_mut(x, sig_text_area.bottom()) {
                cell.set_symbol(borders.horizontal).set_style(sep_style);
            }
        }

        let sig_doc = match &self.signature_doc {
            None => return,
            Some(doc) => Markdown::new(doc.clone(), Arc::clone(&self.config_loader)),
        };
        let sig_doc = sig_doc.parse(Some(&cx.editor.theme));
        let sig_doc_area = area.clip_top(sig_text_area.height + 2);
        let sig_doc_para = Paragraph::new(sig_doc)
            .wrap(Wrap { trim: false })
            .scroll((cx.scroll.unwrap_or_default() as u16, 0));
        sig_doc_para.render(sig_doc_area.inner(&margin), surface);
    }

    fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
        const PADDING: u16 = 2;
        const SEPARATOR_HEIGHT: u16 = 1;

        if PADDING >= viewport.1 || PADDING >= viewport.0 {
            return None;
        }
        let max_text_width = (viewport.0 - PADDING).min(120);

        let signature_text = crate::ui::markdown::highlighted_code_block(
            self.signature.clone(),
            &self.language,
            None,
            Arc::clone(&self.config_loader),
            None,
        );
        let (sig_width, sig_height) =
            crate::ui::text::required_size(&signature_text, max_text_width);

        let (width, height) = match self.signature_doc {
            Some(ref doc) => {
                let doc_md = Markdown::new(doc.clone(), Arc::clone(&self.config_loader));
                let doc_text = doc_md.parse(None);
                let (doc_width, doc_height) =
                    crate::ui::text::required_size(&doc_text, max_text_width);
                (
                    sig_width.max(doc_width),
                    sig_height + SEPARATOR_HEIGHT + doc_height,
                )
            }
            None => (sig_width, sig_height),
        };

        Some((width + PADDING, height + PADDING))
    }
}
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
// Implementation reference: https://github.com/neovim/neovim/blob/f2906a4669a2eef6d7bf86a29648793d63c98949/runtime/autoload/provider/clipboard.vim#L68-L152

use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use thiserror::Error;

#[derive(Clone, Copy)]
pub enum ClipboardType {
    Clipboard,
    Selection,
}

#[derive(Debug, Error)]
pub enum ClipboardError {
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    #[error("could not convert terminal output to UTF-8: {0}")]
    FromUtf8Error(#[from] std::string::FromUtf8Error),
    #[cfg(windows)]
    #[error("Windows API error: {0}")]
    WinAPI(#[from] clipboard_win::ErrorCode),
    #[error("clipboard provider command failed")]
    CommandFailed,
    #[error("failed to write to clipboard provider's stdin")]
    StdinWriteFailed,
    #[error("clipboard provider did not return any contents")]
    MissingStdout,
    #[error("This clipboard provider does not support reading")]
    ReadingNotSupported,
}

type Result<T> = std::result::Result<T, ClipboardError>;

#[cfg(not(target_arch = "wasm32"))]
pub use external::ClipboardProvider;
#[cfg(target_arch = "wasm32")]
pub use noop::ClipboardProvider;

// Clipboard not supported for wasm
#[cfg(target_arch = "wasm32")]
mod noop {
    use super::*;

    #[derive(Debug, Clone)]
    pub enum ClipboardProvider {}

    impl ClipboardProvider {
        pub fn detect() -> Self {
            Self
        }

        pub fn name(&self) -> Cow<str> {
            "none".into()
        }

        pub fn get_contents(&self, _clipboard_type: ClipboardType) -> Result<String> {
            Err(ClipboardError::ReadingNotSupported)
        }

        pub fn set_contents(&self, _content: &str, _clipboard_type: ClipboardType) -> Result<()> {
            Ok(())
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
mod external {
    use super::*;

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct Command {
        command: Cow<'static, str>,
        #[serde(default)]
        args: Cow<'static, [Cow<'static, str>]>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    #[serde(rename_all = "kebab-case")]
    pub struct CommandProvider {
        yank: Command,
        paste: Command,
        yank_primary: Option<Command>,
        paste_primary: Option<Command>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    #[serde(rename_all = "kebab-case")]
    #[allow(clippy::large_enum_variant)]
    pub enum ClipboardProvider {
        Pasteboard,
        Wayland,
        XClip,
        XSel,
        Win32Yank,
        Tmux,
        #[cfg(windows)]
        Windows,
        Termux,
        #[cfg(feature = "term")]
        Termcode,
        Custom(CommandProvider),
        None,
    }

    impl Default for ClipboardProvider {
        #[cfg(windows)]
        fn default() -> Self {
            use helix_stdx::env::binary_exists;

            if binary_exists("win32yank.exe") {
                Self::Win32Yank
            } else {
                Self::Windows
            }
        }

        #[cfg(target_os = "macos")]
        fn default() -> Self {
            use helix_stdx::env::{binary_exists, env_var_is_set};

            if env_var_is_set("TMUX") && binary_exists("tmux") {
                Self::Tmux
            } else if binary_exists("pbcopy") && binary_exists("pbpaste") {
                Self::Pasteboard
            } else {
                #[cfg(feature = "term")]
                return Self::Termcode;
                #[cfg(not(feature = "term"))]
                return Self::None;
            }
        }

        #[cfg(not(any(windows, target_os = "macos")))]
        fn default() -> Self {
            use helix_stdx::env::{binary_exists, env_var_is_set};

            fn is_exit_success(program: &str, args: &[&str]) -> bool {
                std::process::Command::new(program)
                    .args(args)
                    .output()
                    .ok()
                    .and_then(|out| out.status.success().then_some(()))
                    .is_some()
            }

            if env_var_is_set("WAYLAND_DISPLAY")
                && binary_exists("wl-copy")
                && binary_exists("wl-paste")
            {
                Self::Wayland
            } else if env_var_is_set("DISPLAY") && binary_exists("xclip") {
                Self::XClip
            } else if env_var_is_set("DISPLAY")
                && binary_exists("xsel")
                // FIXME: check performance of is_exit_success
                && is_exit_success("xsel", &["-o", "-b"])
            {
                Self::XSel
            } else if binary_exists("termux-clipboard-set") && binary_exists("termux-clipboard-get")
            {
                Self::Termux
            } else if env_var_is_set("TMUX") && binary_exists("tmux") {
                Self::Tmux
            } else if binary_exists("win32yank.exe") {
                Self::Win32Yank
            } else if cfg!(feature = "term") {
                Self::Termcode
            } else {
                Self::None
            }
        }
    }

    impl ClipboardProvider {
        pub fn name(&self) -> Cow<'_, str> {
            fn builtin_name<'a>(
                name: &'static str,
                provider: &'static CommandProvider,
            ) -> Cow<'a, str> {
                if provider.yank.command != provider.paste.command {
                    Cow::Owned(format!(
                        "{} ({}+{})",
                        name, provider.yank.command, provider.paste.command
                    ))
                } else {
                    Cow::Owned(format!("{} ({})", name, provider.yank.command))
                }
            }

            match self {
                // These names should match the config option names from Serde
                Self::Pasteboard => builtin_name("pasteboard", &PASTEBOARD),
                Self::Wayland => builtin_name("wayland", &WL_CLIPBOARD),
                Self::XClip => builtin_name("x-clip", &XCLIP),
                Self::XSel => builtin_name("x-sel", &XSEL),
                Self::Win32Yank => builtin_name("win-32-yank", &WIN32),
                Self::Tmux => builtin_name("tmux", &TMUX),
                Self::Termux => builtin_name("termux", &TERMUX),
                #[cfg(windows)]
                Self::Windows => "windows".into(),
                #[cfg(feature = "term")]
                Self::Termcode => "termcode".into(),
                Self::Custom(command_provider) => Cow::Owned(format!(
                    "custom ({}+{})",
                    command_provider.yank.command, command_provider.paste.command
                )),
                Self::None => "none".into(),
            }
        }

        pub fn get_contents(&self, clipboard_type: &ClipboardType) -> Result<String> {
            fn yank_from_builtin(
                provider: CommandProvider,
                clipboard_type: &ClipboardType,
            ) -> Result<String> {
                match clipboard_type {
                    ClipboardType::Clipboard => execute_command(&provider.yank, None, true)?
                        .ok_or(ClipboardError::MissingStdout),
                    ClipboardType::Selection => {
                        if let Some(cmd) = provider.yank_primary.as_ref() {
                            return execute_command(cmd, None, true)?
                                .ok_or(ClipboardError::MissingStdout);
                        }

                        Ok(String::new())
                    }
                }
            }

            match self {
                Self::Pasteboard => yank_from_builtin(PASTEBOARD, clipboard_type),
                Self::Wayland => yank_from_builtin(WL_CLIPBOARD, clipboard_type),
                Self::XClip => yank_from_builtin(XCLIP, clipboard_type),
                Self::XSel => yank_from_builtin(XSEL, clipboard_type),
                Self::Win32Yank => yank_from_builtin(WIN32, clipboard_type),
                Self::Tmux => yank_from_builtin(TMUX, clipboard_type),
                Self::Termux => yank_from_builtin(TERMUX, clipboard_type),
                #[cfg(target_os = "windows")]
                Self::Windows => match clipboard_type {
                    ClipboardType::Clipboard => {
                        let contents =
                            clipboard_win::get_clipboard(clipboard_win::formats::Unicode)?;
                        Ok(contents)
                    }
                    ClipboardType::Selection => Ok(String::new()),
                },
                #[cfg(feature = "term")]
                Self::Termcode => Err(ClipboardError::ReadingNotSupported),
                Self::Custom(command_provider) => {
                    execute_command(&command_provider.yank, None, true)?
                        .ok_or(ClipboardError::MissingStdout)
                }
                Self::None => Err(ClipboardError::ReadingNotSupported),
            }
        }

        pub fn set_contents(&self, content: &str, clipboard_type: ClipboardType) -> Result<()> {
            fn paste_to_builtin(
                provider: CommandProvider,
                content: &str,
                clipboard_type: ClipboardType,
            ) -> Result<()> {
                let cmd = match clipboard_type {
                    ClipboardType::Clipboard => &provider.paste,
                    ClipboardType::Selection => {
                        if let Some(cmd) = provider.paste_primary.as_ref() {
                            cmd
                        } else {
                            return Ok(());
                        }
                    }
                };

                execute_command(cmd, Some(content), false).map(|_| ())
            }

            match self {
                Self::Pasteboard => paste_to_builtin(PASTEBOARD, content, clipboard_type),
                Self::Wayland => paste_to_builtin(WL_CLIPBOARD, content, clipboard_type),
                Self::XClip => paste_to_builtin(XCLIP, content, clipboard_type),
                Self::XSel => paste_to_builtin(XSEL, content, clipboard_type),
                Self::Win32Yank => paste_to_builtin(WIN32, content, clipboard_type),
                Self::Tmux => paste_to_builtin(TMUX, content, clipboard_type),
                Self::Termux => paste_to_builtin(TERMUX, content, clipboard_type),
                #[cfg(target_os = "windows")]
                Self::Windows => match clipboard_type {
                    ClipboardType::Clipboard => {
                        clipboard_win::set_clipboard(clipboard_win::formats::Unicode, content)?;
                        Ok(())
                    }
                    ClipboardType::Selection => Ok(()),
                },
                #[cfg(feature = "term")]
                Self::Termcode => {
                    crossterm::queue!(
                        std::io::stdout(),
                        osc52::SetClipboardCommand::new(content, clipboard_type)
                    )?;
                    Ok(())
                }
                Self::Custom(command_provider) => match clipboard_type {
                    ClipboardType::Clipboard => {
                        execute_command(&command_provider.paste, Some(content), false).map(|_| ())
                    }
                    ClipboardType::Selection => {
                        if let Some(cmd) = &command_provider.paste_primary {
                            execute_command(cmd, Some(content), false).map(|_| ())
                        } else {
                            Ok(())
                        }
                    }
                },
                Self::None => Ok(()),
            }
        }
    }

    macro_rules! command_provider {
        ($name:ident,
         yank => $yank_cmd:literal $( , $yank_arg:literal )* ;
         paste => $paste_cmd:literal $( , $paste_arg:literal )* ; ) => {
            const $name: CommandProvider = CommandProvider {
                yank: Command {
                    command: Cow::Borrowed($yank_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_arg) ),* ])
                },
                paste: Command {
                    command: Cow::Borrowed($paste_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_arg) ),* ])
                },
                yank_primary: None,
                paste_primary: None,
            };
        };
        ($name:ident,
         yank => $yank_cmd:literal $( , $yank_arg:literal )* ;
         paste => $paste_cmd:literal $( , $paste_arg:literal )* ;
         yank_primary => $yank_primary_cmd:literal $( , $yank_primary_arg:literal )* ;
         paste_primary => $paste_primary_cmd:literal $( , $paste_primary_arg:literal )* ; ) => {
            const $name: CommandProvider = CommandProvider {
                yank: Command {
                    command: Cow::Borrowed($yank_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_arg) ),* ])
                },
                paste: Command {
                    command: Cow::Borrowed($paste_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_arg) ),* ])
                },
                yank_primary: Some(Command {
                    command: Cow::Borrowed($yank_primary_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_primary_arg) ),* ])
                }),
                paste_primary: Some(Command {
                    command: Cow::Borrowed($paste_primary_cmd),
                    args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_primary_arg) ),* ])
                }),
            };
        };
    }

    command_provider! {
        TMUX,
        yank => "tmux", "save-buffer", "-";
        paste => "tmux", "load-buffer", "-w", "-";
    }
    command_provider! {
        PASTEBOARD,
        yank => "pbpaste";
        paste => "pbcopy";
    }
    command_provider! {
        WL_CLIPBOARD,
        yank => "wl-paste", "--no-newline";
        paste => "wl-copy", "--type", "text/plain";
        yank_primary => "wl-paste", "-p", "--no-newline";
        paste_primary => "wl-copy", "-p", "--type", "text/plain";
    }
    command_provider! {
        XCLIP,
        yank => "xclip", "-o", "-selection", "clipboard";
        paste => "xclip", "-i", "-selection", "clipboard";
        yank_primary => "xclip", "-o";
        paste_primary => "xclip", "-i";
    }
    command_provider! {
        XSEL,
        yank => "xsel", "-o", "-b";
        paste => "xsel", "-i", "-b";
        yank_primary => "xsel", "-o";
        paste_primary => "xsel", "-i";
    }
    command_provider! {
        WIN32,
        yank => "win32yank.exe", "-o", "--lf";
        paste => "win32yank.exe", "-i", "--crlf";
    }
    command_provider! {
        TERMUX,
        yank => "termux-clipboard-get";
        paste => "termux-clipboard-set";
    }

    #[cfg(feature = "term")]
    mod osc52 {
        use {super::ClipboardType, crate::base64};

        pub struct SetClipboardCommand {
            encoded_content: String,
            clipboard_type: ClipboardType,
        }

        impl SetClipboardCommand {
            pub fn new(content: &str, clipboard_type: ClipboardType) -> Self {
                Self {
                    encoded_content: base64::encode(content.as_bytes()),
                    clipboard_type,
                }
            }
        }

        impl crossterm::Command for SetClipboardCommand {
            fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result {
                let kind = match &self.clipboard_type {
                    ClipboardType::Clipboard => "c",
                    ClipboardType::Selection => "p",
                };
                // Send an OSC 52 set command: https://terminalguide.namepad.de/seq/osc-52/
                write!(f, "\x1b]52;{};{}\x1b\\", kind, &self.encoded_content)
            }
            #[cfg(windows)]
            fn execute_winapi(&self) -> std::result::Result<(), std::io::Error> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "OSC clipboard codes not supported by winapi.",
                ))
            }
        }
    }

    fn execute_command(
        cmd: &Command,
        input: Option<&str>,
        pipe_output: bool,
    ) -> Result<Option<String>> {
        use std::io::Write;
        use std::process::{Command, Stdio};

        let stdin = input.map(|_| Stdio::piped()).unwrap_or_else(Stdio::null);
        let stdout = pipe_output.then(Stdio::piped).unwrap_or_else(Stdio::null);

        let mut command: Command = Command::new(cmd.command.as_ref());

        #[allow(unused_mut)]
        let mut command_mut: &mut Command = command
            .args(cmd.args.iter().map(AsRef::as_ref))
            .stdin(stdin)
            .stdout(stdout)
            .stderr(Stdio::null());

        // Fix for https://github.com/helix-editor/helix/issues/5424
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;

            unsafe {
                command_mut = command_mut.pre_exec(|| match libc::setsid() {
                    -1 => Err(std::io::Error::last_os_error()),
                    _ => Ok(()),
                });
            }
        }

        let mut child = command_mut.spawn()?;

        if let Some(input) = input {
            let mut stdin = child.stdin.take().ok_or(ClipboardError::StdinWriteFailed)?;
            stdin
                .write_all(input.as_bytes())
                .map_err(|_| ClipboardError::StdinWriteFailed)?;
        }

        // TODO: add timer?
        let output = child.wait_with_output()?;

        if !output.status.success() {
            log::error!(
                "clipboard provider {} failed with stderr: \"{}\"",
                cmd.command,
                String::from_utf8_lossy(&output.stderr)
            );
            return Err(ClipboardError::CommandFailed);
        }

        if pipe_output {
            Ok(Some(String::from_utf8(output.stdout)?))
        } else {
            Ok(None)
        }
    }
}