nativeclipboard

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 9 Imported by: 21 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-nativeclipboard

Go Reference Go Report Card build Latest Release

A cross-platform clipboard library for Go that works without cgo. This is a port of golang.design/x/clipboard that uses purego instead of cgo, enabling clipboard access without a C compiler.

Why?

The original golang.design/x/clipboard is excellent but requires cgo, which complicates cross-compilation and slows down builds. This library provides the same functionality using pure Go with purego for native OS API calls.

Benefits:

  • No C compiler needed
  • Faster builds
  • Easy cross-compilation
  • Smaller binaries
  • Same familiar API

Installation

go get github.com/aymanbagabas/go-nativeclipboard

Quick Start

package main

import (
    "fmt"
    "log"
    "github.com/aymanbagabas/go-nativeclipboard"
)

func main() {
    // Write text to clipboard
    _, err := nativeclipboard.Text.Write([]byte("Hello, clipboard!"))
    if err != nil {
        log.Fatal(err)
    }

    // Read text from clipboard
    data, err := nativeclipboard.Text.Read()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(data))
}

Usage

Reading and Writing
// Text clipboard
data, err := nativeclipboard.Text.Read()
changed, err := nativeclipboard.Text.Write([]byte("hello"))

// Image clipboard (PNG format)
imageData, _ := os.ReadFile("image.png")
changed, err := nativeclipboard.Image.Write(imageData)
data, err := nativeclipboard.Image.Read()
Watching for Changes

Monitor clipboard changes in real-time:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

ch, err := nativeclipboard.Text.Watch(ctx)
if err != nil {
    log.Fatal(err)
}

for data := range ch {
    fmt.Println("Clipboard changed:", string(data))
}
Change Notifications

Get notified when your clipboard data is overwritten:

changed, err := nativeclipboard.Text.Write([]byte("Hello"))
if err != nil {
    log.Fatal(err)
}

select {
case <-changed:
    fmt.Println("Clipboard was overwritten by another application")
case <-time.After(5 * time.Second):
    fmt.Println("Clipboard content still intact")
}

API Reference

The library provides a simple Format type with methods:

type Format int

const (
    Text  Format = iota  // UTF-8 text
    Image                // PNG image
)

// Methods
func (f Format) Read() ([]byte, error)
func (f Format) Write(buf []byte) (<-chan struct{}, error)
func (f Format) Watch(ctx context.Context) (<-chan []byte, error)

Use the pre-defined constants:

  • nativeclipboard.Text for text operations
  • nativeclipboard.Image for image operations

Platform Support

Platform Status Implementation
macOS ✅ Complete NSPasteboard via purego/objc
Linux (X11) ✅ Complete X11 via purego (requires libX11)
Linux (Wayland) 🚧 Planned Not yet implemented
Windows ✅ Complete Win32 API via syscall
FreeBSD ✅ Complete X11 via purego (requires libX11)
Other platforms ❌ Unsupported Returns ErrUnavailable error

Note: On unsupported platforms (OpenBSD, NetBSD, Solaris, iOS, Android, etc.), the package compiles successfully but all clipboard operations return ErrUnavailable.

Linux Requirements

X11 (supported): You need libX11 installed:

# Debian/Ubuntu
sudo apt install libx11-dev

# Fedora/RHEL
sudo dnf install libX11-devel

# For headless environments
sudo apt install xvfb
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
export DISPLAY=:99.0

Wayland (not yet supported): Wayland clipboard support is planned but not yet implemented. If you're using Wayland, you'll need XWayland compatibility layer with X11 libraries installed for the clipboard to work.

FreeBSD Requirements

X11 (supported): You need libX11 installed:

# FreeBSD
sudo pkg install xorg-libraries

# For headless environments
sudo pkg install xorg-vfbserver
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
export DISPLAY=:99.0

Building on FreeBSD: When building with CGO_ENABLED=0 (the default for this library), you need to add special gcflags:

go build -gcflags="github.com/ebitengine/purego/internal/fakecgo=-std" ./...
go test -gcflags="github.com/ebitengine/purego/internal/fakecgo=-std" ./...

Note: FreeBSD typically installs X11 libraries to /usr/local/lib or /usr/X11R6/lib. The library will automatically search these common FreeBSD locations.

How It Works

This library uses different approaches per platform:

  • macOS: Calls Objective-C runtime and AppKit (NSPasteboard) using purego/objc
  • Linux (X11): Dynamically loads libX11.so and calls X11 clipboard functions via purego
  • FreeBSD: Same X11 implementation as Linux, with automatic detection of FreeBSD-specific library paths
  • Linux (Wayland): Not yet implemented - planned for future release
  • Windows: Uses Win32 clipboard API (user32.dll, kernel32.dll) via Go's syscall package
  • Other platforms: Stub implementation that returns ErrUnavailable for all operations

All approaches avoid cgo entirely, resulting in faster builds and easier cross-compilation.

Testing

# Run tests
go test -v

# Cross-compile (no C compiler needed!)
CGO_ENABLED=0 GOOS=linux go build
CGO_ENABLED=0 GOOS=windows go build

Contributing

Contributions welcome! Some ideas:

  • Wayland clipboard support for Linux
  • Additional clipboard formats (HTML, RTF, files)
  • Performance optimizations
  • Better error messages

License

MIT License - see LICENSE file for details.

Credits

  • This is a port of golang.design/x/clipboard by Changkun Ou
  • Built with purego by Ebitengine
  • Thanks to the Go community for making cgo-free native calls possible

See Also

Documentation

Overview

Package nativeclipboard provides cross-platform clipboard access using purego instead of cgo. It supports text and image data on macOS, Linux, and Windows.

The package initializes automatically and returns errors from individual operations.

Read and write clipboard data:

// Write text to clipboard
changed, err := nativeclipboard.Text.Write([]byte("hello world"))
if err != nil {
	log.Fatal(err)
}

// Read text from clipboard
data, err := nativeclipboard.Text.Read()
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(data))

The package supports text (UTF-8) and images (PNG).

Index

Constants

View Source
const (
	None             = 0
	CurrentTime      = 0
	AnyPropertyType  = 0
	PropModeReplace  = 0
	Success          = 0
	SelectionNotify  = 31
	SelectionClear   = 29
	SelectionRequest = 30
)

X11 constants

Variables

View Source
var (
	// ErrUnavailable indicates the clipboard is not available
	ErrUnavailable = errors.New("clipboard unavailable")
	// ErrUnsupported indicates the requested format is not supported
	ErrUnsupported = errors.New("unsupported format")
)

Functions

This section is empty.

Types

type Atom

type Atom uintptr

X11 types

type Bool

type Bool int

X11 types

type Display

type Display uintptr

X11 types

type Format

type Format int

Format represents a clipboard data format.

const (
	// Text provides access to text clipboard operations.
	Text Format = iota
	// Image provides access to image (PNG) clipboard operations.
	Image
)

Supported clipboard formats

func (Format) Read

func (f Format) Read() ([]byte, error)

Read reads clipboard data in this format. Returns an error if the clipboard is unavailable or initialization failed.

func (Format) Watch

func (f Format) Watch(ctx context.Context) (<-chan []byte, error)

Watch returns a channel that receives clipboard data whenever it changes. The channel will be closed when the provided context is canceled. Returns an error if the clipboard is unavailable or initialization failed.

func (Format) Write

func (f Format) Write(buf []byte) (<-chan struct{}, error)

Write writes data to the clipboard in this format. Returns a channel that receives a signal when the clipboard content has been overwritten by another application, and an error if the operation fails.

type Time

type Time uintptr

X11 types

type Window

type Window uintptr

X11 types

type XEvent

type XEvent struct {
	// contains filtered or unexported fields
}

XEvent is a union in C, we need the largest variant

type XSelectionEvent

type XSelectionEvent struct {
	// contains filtered or unexported fields
}

type XSelectionRequestEvent

type XSelectionRequestEvent struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
examples
readImage command
readText command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址