#obtain #text #platform #across #tiny #macos

get-selected-text

A tiny Rust library that allows you to easily obtain selected text across all platforms (macOS, Windows, Linux)

7 releases

0.1.6 May 29, 2024
0.1.5 May 8, 2024

#254 in GUI

Download history 12/week @ 2024-06-11 13/week @ 2024-06-18 10/week @ 2024-06-25 15/week @ 2024-07-02 8/week @ 2024-07-09 41/week @ 2024-07-16 23/week @ 2024-07-23 15/week @ 2024-07-30 26/week @ 2024-08-06 13/week @ 2024-08-13 1/week @ 2024-08-20 10/week @ 2024-08-27 24/week @ 2024-09-03 19/week @ 2024-09-10 7/week @ 2024-09-17 65/week @ 2024-09-24

121 downloads per month

MIT/Apache

14KB
256 lines

get-selected-text

Lint crates.io

A tiny Rust library that allows you to easily obtain selected text across all platforms (macOS, Windows, Linux).

Corresponding Node.js package: node-get-selected-text

Usage

Add:

cargo add get-selected-text

Use:

use get_selected_text::get_selected_text;

fn main() {
    match get_selected_text() {
        Ok(selected_text) => {
            println!("selected text: {}", selected_text);
        },
        Err(()) => {
            println!("error occurred while getting the selected text");
        }
    }
}

How does it work?

macOS

Prioritize using the A11y API to obtain selected text. If the application does not comply with the A11y API, simulate pressing cmd+c to borrow from the clipboard to get the selected text.

To avoid annoying Alert sounds when simulating pressing cmd+c, it will automatically mute the Alert sound (Only the Alert sound is muted, it won't affect the volume of listening to music and watching videos). The volume of the Alert sound will be restored after releasing the key.

Therefore, on macOS, you need to grant accessbility permissions in advance. The sample code is as follows:

fn query_accessibility_permissions() -> bool {
    let trusted = macos_accessibility_client::accessibility::application_is_trusted_with_prompt();
    if trusted {
        print!("Application is totally trusted!");
    } else {
        print!("Application isn't trusted :(");
    }
    trusted
}

Windows + Linux

Simulate pressing ctrl+c to use the clipboard to obtain the selected text.

Dependencies

~2–35MB
~513K SLoC