Full Code of alacritty/copypasta for AI

master c429615bb13f cached
19 files
31.4 KB
7.8k tokens
42 symbols
1 requests
Download .txt
Repository: alacritty/copypasta
Branch: master
Commit: c429615bb13f
Files: 19
Total size: 31.4 KB

Directory structure:
gitextract_mfabqqir/

├── .builds/
│   ├── freebsd.yml
│   └── linux.yml
├── .github/
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE.apache2
├── LICENSE.mit
├── README.md
├── examples/
│   ├── hello_world.rs
│   └── primary_selection.rs
├── rustfmt.toml
└── src/
    ├── common.rs
    ├── lib.rs
    ├── nop_clipboard.rs
    ├── osx_clipboard.rs
    ├── wayland_clipboard.rs
    ├── windows_clipboard.rs
    └── x11_clipboard.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .builds/freebsd.yml
================================================
image: freebsd/latest

packages:
  - lang/python3
  - lang/gcc
  - x11/libxcb
  - x11/libxkbcommon

sources:
  - https://github.com/alacritty/copypasta

environment:
  PATH: /home/build/.cargo/bin:/bin:/usr/bin:/usr/local/bin
  RUSTFLAGS: -L /usr/local/lib

tasks:
  - rustup: |
      curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain stable --profile minimal
  - test: |
      cd copypasta
      cargo test
  - clippy: |
      cd copypasta
      rustup component add clippy
      cargo clippy --all-targets
  - oldstable: |
      cd copypasta
      rustup toolchain install --profile minimal 1.71.0
      cargo +1.71.0 test


================================================
FILE: .builds/linux.yml
================================================
image: archlinux

packages:
  - libxcb
  - libxkbcommon

sources:
  - https://github.com/alacritty/copypasta

environment:
  PATH: /home/build/.cargo/bin:/usr/bin/

tasks:
  - rustup: |
      curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain stable --profile minimal
  - test: |
      cd copypasta
      cargo test
  - rustfmt: |
      cd copypasta
      rustup toolchain install nightly -c rustfmt
      cargo +nightly fmt -- --check
  - clippy: |
      cd copypasta
      rustup component add clippy
      cargo clippy --all-targets
  - oldstable: |
      cd copypasta
      rustup toolchain install --profile minimal 1.71.0
      cargo +1.71.0 test


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on: [push, pull_request]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    strategy:
      matrix:
        os: [windows-latest, macos-latest]

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v2
      - name: Stable
        run: cargo test
      - name: Clippy
        run: |
          rustup component add clippy
          cargo clippy --all-targets
      - name: Oldstable
        run: |
          rustup default 1.71.0
          cargo clean
          cargo test


================================================
FILE: .gitignore
================================================
/target
Cargo.lock


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 0.10.2

### Packaging

- Minimum Rust version was bumped to `1.71.0`
- Switched from `objc` to `objc2`
- New default `wayland-dlopen` feature, to control `libwayland` linking

## 0.10.1

### Packaging

- Minimum rust version was bumped to `1.66.0`
- `x11_clipboard` was bumped to `0.9.1`

## 0.10.0

### Changed

- Use `String` in `ClipboardProvider::set_contents` for trait to be *object-safe*

## 0.9.0

- Bump minimum supported Rust version to `1.65.0`
- Change `ClipboardProvider::set_contents` parameter type to `AsRef<str>`
- Prefer file's path over text on macOS

## 0.8.2

### Packaging

- Minimum rust version was bumped to `1.60.0`

### Fixed

- `x11_clipboard` was bumped to `0.7.0` droping `quick-xml` from the deps tree


## 0.8.1 

### Fixed

- Crash on use-after-free on macOS

## 0.8.0

### Packaging

- Minimum rust version was bumped to `1.57.0`

### Fixed

- Memory leak on macOS

## 0.7.1

### Changed

- Updated `smithay-clipboard` to 0.6.0

## 0.7.0

### Packaging

- Minimum rust version was bumped to `1.41.0`

### Removed

- Ability to create a Wayland clipboard from Display type directly using `create_clipboard`

## 0.6.3

### Added

- Features `x11` and `wayland` for picking the linux backends

## 0.6.2

### Fixed

- Compilation on iOS, using the no-op clipboard


================================================
FILE: Cargo.toml
================================================
[package]
name = "copypasta"
version = "0.10.2"
authors = ["Christian Duerr <contact@christianduerr.com>"]
description = "copypasta is a cross-platform library for getting and setting the contents of the OS-level clipboard."
repository = "https://github.com/alacritty/copypasta"
documentation = "https://docs.rs/copypasta"
readme = "README.md"
license = "MIT / Apache-2.0"
keywords = ["clipboard"]
exclude = ["/.travis.yml"]
edition = "2021"
rust-version = "1.71.0"

[features]
default = ["x11", "wayland", "wayland-dlopen"]
x11 = ["x11-clipboard"]
wayland = ["smithay-clipboard"]
wayland-dlopen = ["smithay-clipboard/dlopen"]

[target.'cfg(windows)'.dependencies]
clipboard-win = { version = "5.4.0", features = ["std"]}

[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6.1"
objc2-foundation = { version = "0.3.1", default-features = false, features = [
    "std",
    "NSArray",
    "NSString",
    "NSURL",
] }
objc2-app-kit = { version = "0.3.1", default-features = false, features = [
    "std",
    "NSPasteboard",
] }

[target.'cfg(all(unix, not(any(target_os="macos", target_os="android", target_os="ios", target_os="emscripten"))))'.dependencies]
x11-clipboard = { version = "0.9.1", optional = true }
smithay-clipboard = { version = "0.7.0", default-features = false, optional = true }


================================================
FILE: LICENSE.apache2
================================================
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: LICENSE.mit
================================================
Copyright (c) 2017 Avraham Weinstock

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# copypasta

copypasta is a [rust-clipboard](https://github.com/aweinstock314/rust-clipboard) fork, adding support for the Wayland clipboard.

rust-clipboard is a cross-platform library for getting and setting the contents of the OS-level clipboard.  

## Example

```rust
extern crate copypasta;

use copypasta::{ClipboardContext, ClipboardProvider};

fn main() {
    let mut ctx = ClipboardContext::new().unwrap();

    let msg = "Hello, world!";
    ctx.set_contents(msg.to_owned()).unwrap();

    let content = ctx.get_contents().unwrap();

    println!("{}", content);
}
```

## API

The `ClipboardProvider` trait has the following functions:

```rust
fn get_contents(&mut self) -> Result<String, Box<Error>>;
fn set_contents(&mut self, String) -> Result<(), Box<Error>>;
```

`ClipboardContext` is a type alias for one of {`WindowsClipboardContext`, `OSXClipboardContext`, `X11ClipboardContext`, `NopClipboardContext`}, all of which implement `ClipboardProvider`. Which concrete type is chosen for `ClipboardContext` depends on the OS (via conditional compilation).

## License

`rust-clipboard` is dual-licensed under MIT and Apache2.


================================================
FILE: examples/hello_world.rs
================================================
use copypasta::{ClipboardContext, ClipboardProvider};

fn main() {
    let mut ctx = ClipboardContext::new().unwrap();

    let msg = "Hello, world!";
    ctx.set_contents(msg.to_owned()).unwrap();

    let content = ctx.get_contents().unwrap();

    println!("{}", content);
}


================================================
FILE: examples/primary_selection.rs
================================================
#[cfg(target_os = "linux")]
use copypasta::x11_clipboard::{Primary, X11ClipboardContext};
#[cfg(target_os = "linux")]
use copypasta::ClipboardProvider;

#[cfg(target_os = "linux")]
fn main() {
    let mut ctx = X11ClipboardContext::<Primary>::new().unwrap();

    let the_string = "Hello, world!";

    ctx.set_contents(the_string.to_owned()).unwrap();
}

#[cfg(not(target_os = "linux"))]
fn main() {
    println!("Primary selection is only available under linux!");
}


================================================
FILE: rustfmt.toml
================================================
format_code_in_doc_comments = true
match_block_trailing_comma = true
condense_wildcard_suffixes = true
use_field_init_shorthand = true
overflow_delimited_expr = true
use_small_heuristics = "Max"
normalize_comments = true
reorder_impl_items = true
use_try_shorthand = true
newline_style = "Unix"
format_strings = true
wrap_comments = true
comment_width = 100


================================================
FILE: src/common.rs
================================================
// Copyright 2016 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::error::Error;

pub type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync + 'static>>;

// TODO: come up with some platform-agnostic API for richer types
/// Trait for clipboard access
pub trait ClipboardProvider: Send {
    /// Method to get the clipboard contents as a String
    fn get_contents(&mut self) -> Result<String>;
    /// Method to set the clipboard contents as a String
    fn set_contents(&mut self, _: String) -> Result<()>;
}


================================================
FILE: src/lib.rs
================================================
// Copyright 2016 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use)]

mod common;
pub use crate::common::ClipboardProvider;

#[cfg(all(
    unix,
    not(any(
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
        target_os = "emscripten"
    ))
))]
#[cfg(feature = "wayland")]
pub mod wayland_clipboard;
#[cfg(all(
    unix,
    not(any(
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
        target_os = "emscripten"
    ))
))]
#[cfg(feature = "x11")]
pub mod x11_clipboard;

#[cfg(windows)]
pub mod windows_clipboard;

#[cfg(target_os = "macos")]
pub mod osx_clipboard;

pub mod nop_clipboard;

#[cfg(all(
    unix,
    not(any(
        target_os = "macos",
        target_os = "android",
        target_os = "ios",
        target_os = "emscripten"
    ))
))]
#[cfg(feature = "x11")]
pub type ClipboardContext = x11_clipboard::X11ClipboardContext;
#[cfg(windows)]
pub type ClipboardContext = windows_clipboard::WindowsClipboardContext;
#[cfg(target_os = "macos")]
pub type ClipboardContext = osx_clipboard::OSXClipboardContext;
#[cfg(target_os = "android")]
pub type ClipboardContext = nop_clipboard::NopClipboardContext; // TODO: implement AndroidClipboardContext
#[cfg(target_os = "ios")]
pub type ClipboardContext = nop_clipboard::NopClipboardContext; // TODO: implement IOSClipboardContext
#[cfg(not(any(
    unix,
    windows,
    target_os = "macos",
    target_os = "android",
    target_os = "ios",
    target_os = "emscripten"
)))]
pub type ClipboardContext = nop_clipboard::NopClipboardContext;


================================================
FILE: src/nop_clipboard.rs
================================================
// Copyright 2016 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::common::{ClipboardProvider, Result};

pub struct NopClipboardContext;

impl NopClipboardContext {
    pub fn new() -> Result<NopClipboardContext> {
        Ok(NopClipboardContext)
    }
}

impl ClipboardProvider for NopClipboardContext {
    fn get_contents(&mut self) -> Result<String> {
        println!(
            "Attempting to get the contents of the clipboard, which hasn't yet been implemented \
             on this platform."
        );
        Ok("".to_string())
    }

    fn set_contents(&mut self, _: String) -> Result<()> {
        println!(
            "Attempting to set the contents of the clipboard, which hasn't yet been implemented \
             on this platform."
        );
        Ok(())
    }
}


================================================
FILE: src/osx_clipboard.rs
================================================
// Copyright 2016 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::panic::RefUnwindSafe;
use std::panic::UnwindSafe;

use objc2::rc::{autoreleasepool, Retained};
use objc2::runtime::ProtocolObject;
use objc2::{msg_send, ClassType};
use objc2_app_kit::{NSPasteboard, NSPasteboardTypeFileURL, NSPasteboardTypeString};
use objc2_foundation::{NSArray, NSString, NSURL};

use crate::common::*;

pub struct OSXClipboardContext {
    pasteboard: Retained<NSPasteboard>,
}

unsafe impl Send for OSXClipboardContext {}
unsafe impl Sync for OSXClipboardContext {}
impl UnwindSafe for OSXClipboardContext {}
impl RefUnwindSafe for OSXClipboardContext {}

impl OSXClipboardContext {
    pub fn new() -> Result<OSXClipboardContext> {
        // Use `msg_send_id!` instead of `NSPasteboard::generalPasteboard()`
        // in the off case that it will return NULL (even though it's
        // documented not to).
        let pasteboard: Option<Retained<NSPasteboard>> =
            unsafe { msg_send![NSPasteboard::class(), generalPasteboard] };
        let pasteboard = pasteboard.ok_or("NSPasteboard#generalPasteboard returned null")?;
        Ok(OSXClipboardContext { pasteboard })
    }
}

impl ClipboardProvider for OSXClipboardContext {
    fn get_contents(&mut self) -> Result<String> {
        autoreleasepool(|_| {
            let types = unsafe { self.pasteboard.types() }.unwrap();
            let has_file = unsafe { types.containsObject(NSPasteboardTypeFileURL) };
            let has_str = unsafe { types.containsObject(NSPasteboardTypeString) };

            if !has_str {
                return Err("NSPasteboard#types doesn't contain NSPasteboardTypeString".into());
            }

            let text = if has_file {
                let file_url_string =
                    unsafe { self.pasteboard.stringForType(NSPasteboardTypeFileURL) }
                        .ok_or("NSPasteboard#stringForType returned null")?;

                let file_url = unsafe { NSURL::URLWithString(&file_url_string) }
                    .ok_or("NSURL#URLWithString returned null")?;
                unsafe { file_url.path() }.ok_or("NSURL#path returned null")?
            } else {
                unsafe { self.pasteboard.stringForType(NSPasteboardTypeString) }
                    .ok_or("NSPasteboard#stringForType returned null")?
            };

            Ok(text.to_string())
        })
    }

    fn set_contents(&mut self, data: String) -> Result<()> {
        let string_array = NSArray::from_retained_slice(&[ProtocolObject::from_retained(
            NSString::from_str(&data),
        )]);
        unsafe { self.pasteboard.clearContents() };
        let success = unsafe { self.pasteboard.writeObjects(&string_array) };
        if success {
            Ok(())
        } else {
            Err("NSPasteboard#writeObjects: returned false".into())
        }
    }
}


================================================
FILE: src/wayland_clipboard.rs
================================================
// Copyright 2017 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::ffi::c_void;
use std::sync::{Arc, Mutex};

use smithay_clipboard::Clipboard as WaylandClipboard;

use crate::common::{ClipboardProvider, Result};

pub struct Clipboard {
    context: Arc<Mutex<WaylandClipboard>>,
}

pub struct Primary {
    context: Arc<Mutex<WaylandClipboard>>,
}

/// Create new clipboard from a raw display pointer.
///
/// # Safety
///
/// Since the type of the display is a raw pointer, it's the responsibility of the callee to make
/// sure that the passed pointer is a valid Wayland display.
pub unsafe fn create_clipboards_from_external(display: *mut c_void) -> (Primary, Clipboard) {
    let context = Arc::new(Mutex::new(WaylandClipboard::new(display)));

    (Primary { context: context.clone() }, Clipboard { context })
}

impl ClipboardProvider for Clipboard {
    fn get_contents(&mut self) -> Result<String> {
        Ok(self.context.lock().unwrap().load()?)
    }

    fn set_contents(&mut self, data: String) -> Result<()> {
        self.context.lock().unwrap().store(data);

        Ok(())
    }
}

impl ClipboardProvider for Primary {
    fn get_contents(&mut self) -> Result<String> {
        Ok(self.context.lock().unwrap().load_primary()?)
    }

    fn set_contents(&mut self, data: String) -> Result<()> {
        self.context.lock().unwrap().store_primary(data);

        Ok(())
    }
}


================================================
FILE: src/windows_clipboard.rs
================================================
// Copyright 2016 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use clipboard_win::{get_clipboard_string, set_clipboard_string};

use crate::common::{ClipboardProvider, Result};

pub struct WindowsClipboardContext;

impl WindowsClipboardContext {
    pub fn new() -> Result<Self> {
        Ok(WindowsClipboardContext)
    }
}

impl ClipboardProvider for WindowsClipboardContext {
    fn get_contents(&mut self) -> Result<String> {
        Ok(get_clipboard_string()?)
    }

    fn set_contents(&mut self, data: String) -> Result<()> {
        Ok(set_clipboard_string(&data)?)
    }
}


================================================
FILE: src/x11_clipboard.rs
================================================
// Copyright 2017 Avraham Weinstock
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::marker::PhantomData;
use std::time::Duration;

use x11_clipboard::Atom;
use x11_clipboard::{Atoms, Clipboard as X11Clipboard};

use crate::common::*;

pub trait Selection: Send {
    fn atom(atoms: &Atoms) -> Atom;
}

pub struct Primary;

impl Selection for Primary {
    fn atom(atoms: &Atoms) -> Atom {
        atoms.primary
    }
}

pub struct Clipboard;

impl Selection for Clipboard {
    fn atom(atoms: &Atoms) -> Atom {
        atoms.clipboard
    }
}

pub struct X11ClipboardContext<S = Clipboard>(X11Clipboard, PhantomData<S>)
where
    S: Selection;

impl<S> X11ClipboardContext<S>
where
    S: Selection,
{
    pub fn new() -> Result<X11ClipboardContext<S>> {
        Ok(X11ClipboardContext(X11Clipboard::new()?, PhantomData))
    }
}

impl<S> ClipboardProvider for X11ClipboardContext<S>
where
    S: Selection,
{
    fn get_contents(&mut self) -> Result<String> {
        Ok(String::from_utf8(self.0.load(
            S::atom(&self.0.getter.atoms),
            self.0.getter.atoms.utf8_string,
            self.0.getter.atoms.property,
            Duration::from_secs(3),
        )?)?)
    }

    fn set_contents(&mut self, data: String) -> Result<()> {
        Ok(self.0.store(S::atom(&self.0.setter.atoms), self.0.setter.atoms.utf8_string, data)?)
    }
}
Download .txt
gitextract_mfabqqir/

├── .builds/
│   ├── freebsd.yml
│   └── linux.yml
├── .github/
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE.apache2
├── LICENSE.mit
├── README.md
├── examples/
│   ├── hello_world.rs
│   └── primary_selection.rs
├── rustfmt.toml
└── src/
    ├── common.rs
    ├── lib.rs
    ├── nop_clipboard.rs
    ├── osx_clipboard.rs
    ├── wayland_clipboard.rs
    ├── windows_clipboard.rs
    └── x11_clipboard.rs
Download .txt
SYMBOL INDEX (42 symbols across 9 files)

FILE: examples/hello_world.rs
  function main (line 3) | fn main() {

FILE: examples/primary_selection.rs
  function main (line 7) | fn main() {
  function main (line 16) | fn main() {

FILE: src/common.rs
  type Result (line 17) | pub type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync ...
  type ClipboardProvider (line 21) | pub trait ClipboardProvider: Send {
    method get_contents (line 23) | fn get_contents(&mut self) -> Result<String>;
    method set_contents (line 25) | fn set_contents(&mut self, _: String) -> Result<()>;

FILE: src/lib.rs
  type ClipboardContext (line 60) | pub type ClipboardContext = x11_clipboard::X11ClipboardContext;
  type ClipboardContext (line 62) | pub type ClipboardContext = windows_clipboard::WindowsClipboardContext;
  type ClipboardContext (line 64) | pub type ClipboardContext = osx_clipboard::OSXClipboardContext;
  type ClipboardContext (line 66) | pub type ClipboardContext = nop_clipboard::NopClipboardContext;
  type ClipboardContext (line 68) | pub type ClipboardContext = nop_clipboard::NopClipboardContext;
  type ClipboardContext (line 77) | pub type ClipboardContext = nop_clipboard::NopClipboardContext;

FILE: src/nop_clipboard.rs
  type NopClipboardContext (line 17) | pub struct NopClipboardContext;
    method new (line 20) | pub fn new() -> Result<NopClipboardContext> {
  method get_contents (line 26) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 34) | fn set_contents(&mut self, _: String) -> Result<()> {

FILE: src/osx_clipboard.rs
  type OSXClipboardContext (line 26) | pub struct OSXClipboardContext {
    method new (line 36) | pub fn new() -> Result<OSXClipboardContext> {
  method get_contents (line 48) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 75) | fn set_contents(&mut self, data: String) -> Result<()> {

FILE: src/wayland_clipboard.rs
  type Clipboard (line 22) | pub struct Clipboard {
  type Primary (line 26) | pub struct Primary {
  function create_clipboards_from_external (line 36) | pub unsafe fn create_clipboards_from_external(display: *mut c_void) -> (...
  method get_contents (line 43) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 47) | fn set_contents(&mut self, data: String) -> Result<()> {
  method get_contents (line 55) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 59) | fn set_contents(&mut self, data: String) -> Result<()> {

FILE: src/windows_clipboard.rs
  type WindowsClipboardContext (line 19) | pub struct WindowsClipboardContext;
    method new (line 22) | pub fn new() -> Result<Self> {
  method get_contents (line 28) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 32) | fn set_contents(&mut self, data: String) -> Result<()> {

FILE: src/x11_clipboard.rs
  type Selection (line 23) | pub trait Selection: Send {
    method atom (line 24) | fn atom(atoms: &Atoms) -> Atom;
    method atom (line 30) | fn atom(atoms: &Atoms) -> Atom {
    method atom (line 38) | fn atom(atoms: &Atoms) -> Atom {
  type Primary (line 27) | pub struct Primary;
  type Clipboard (line 35) | pub struct Clipboard;
  type X11ClipboardContext (line 43) | pub struct X11ClipboardContext<S = Clipboard>(X11Clipboard, PhantomData<S>)
  function new (line 51) | pub fn new() -> Result<X11ClipboardContext<S>> {
  method get_contents (line 60) | fn get_contents(&mut self) -> Result<String> {
  method set_contents (line 69) | fn set_contents(&mut self, data: String) -> Result<()> {
Condensed preview — 19 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (34K chars).
[
  {
    "path": ".builds/freebsd.yml",
    "chars": 640,
    "preview": "image: freebsd/latest\n\npackages:\n  - lang/python3\n  - lang/gcc\n  - x11/libxcb\n  - x11/libxkbcommon\n\nsources:\n  - https:/"
  },
  {
    "path": ".builds/linux.yml",
    "chars": 667,
    "preview": "image: archlinux\n\npackages:\n  - libxcb\n  - libxkbcommon\n\nsources:\n  - https://github.com/alacritty/copypasta\n\nenvironmen"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 502,
    "preview": "name: CI\n\non: [push, pull_request]\n\nenv:\n  CARGO_TERM_COLOR: always\n\njobs:\n  build:\n    strategy:\n      matrix:\n        "
  },
  {
    "path": ".gitignore",
    "chars": 19,
    "preview": "/target\nCargo.lock\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1550,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
  },
  {
    "path": "Cargo.toml",
    "chars": 1308,
    "preview": "[package]\nname = \"copypasta\"\nversion = \"0.10.2\"\nauthors = [\"Christian Duerr <contact@christianduerr.com>\"]\ndescription ="
  },
  {
    "path": "LICENSE.apache2",
    "chars": 11323,
    "preview": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licens"
  },
  {
    "path": "LICENSE.mit",
    "chars": 1061,
    "preview": "Copyright (c) 2017 Avraham Weinstock\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of th"
  },
  {
    "path": "README.md",
    "chars": 1142,
    "preview": "# copypasta\n\ncopypasta is a [rust-clipboard](https://github.com/aweinstock314/rust-clipboard) fork, adding support for t"
  },
  {
    "path": "examples/hello_world.rs",
    "chars": 278,
    "preview": "use copypasta::{ClipboardContext, ClipboardProvider};\n\nfn main() {\n    let mut ctx = ClipboardContext::new().unwrap();\n\n"
  },
  {
    "path": "examples/primary_selection.rs",
    "chars": 469,
    "preview": "#[cfg(target_os = \"linux\")]\nuse copypasta::x11_clipboard::{Primary, X11ClipboardContext};\n#[cfg(target_os = \"linux\")]\nus"
  },
  {
    "path": "rustfmt.toml",
    "chars": 358,
    "preview": "format_code_in_doc_comments = true\nmatch_block_trailing_comma = true\ncondense_wildcard_suffixes = true\nuse_field_init_sh"
  },
  {
    "path": "src/common.rs",
    "chars": 1057,
    "preview": "// Copyright 2016 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/lib.rs",
    "chars": 2175,
    "preview": "// Copyright 2016 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/nop_clipboard.rs",
    "chars": 1324,
    "preview": "// Copyright 2016 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/osx_clipboard.rs",
    "chars": 3398,
    "preview": "// Copyright 2016 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/wayland_clipboard.rs",
    "chars": 1929,
    "preview": "// Copyright 2017 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/windows_clipboard.rs",
    "chars": 1111,
    "preview": "// Copyright 2016 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  },
  {
    "path": "src/x11_clipboard.rs",
    "chars": 1871,
    "preview": "// Copyright 2017 Avraham Weinstock\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
  }
]

About this extraction

This page contains the full source code of the alacritty/copypasta GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 19 files (31.4 KB), approximately 7.8k tokens, and a symbol index with 42 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!