pax_global_header00006660000000000000000000000064143316030770014516gustar00rootroot0000000000000052 comment=17a3fa8e4014e3747e13bbadd8b780b55a8f8b61 clipper-0.1.1/000077500000000000000000000000001433160307700131535ustar00rootroot00000000000000clipper-0.1.1/LICENSE000066400000000000000000000020621433160307700141600ustar00rootroot00000000000000MIT License Copyright (c) 2022: Zachary Yedidia. 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. clipper-0.1.1/LICENSE-EXTRA000066400000000000000000000026771433160307700150550ustar00rootroot00000000000000Copyright (c) 2013 Ato Araki. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of @atotto. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. clipper-0.1.1/README.md000066400000000000000000000021511433160307700144310ustar00rootroot00000000000000# Clipper: cross-platform clipboard library [![Go Reference](https://pkg.go.dev/badge/github.com/zyedidia/clipper.svg)](https://pkg.go.dev/github.com/zyedidia/clipper) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/zyedidia/clipper/blob/master/LICENSE) Platforms supported: * Linux (via `xclip` or `xsel` or `wl-copy`/`wl-paste`) * MacOS (via `pbcopy`/`pbpaste`) * Windows (via the Windows clipboard API) * WSL (via `clip.exe`/`powershell.exe`) * Android Termux (via `termux-clipboard-set`/`termux-clipboard-get`) * Plan9 (via `/dev/snarf`) * Anything else (via a user-defined script) Fallback methods: * Internal in-memory clipboard * File-based clipboard # Example ``` func main() { clip, err := clipper.GetClipboard(clipper.Clipboards...) must(err) // copy from stdin data, err := io.ReadAll(os.Stdin) must(err) err = clip.WriteAll(clipper.RegClipboard, data) must(err) // paste to stdout data, err := clip.ReadAll(clipper.RegClipboard) must(err) fmt.Print(string(data)) } ``` A CLI tool is provided as an example in `cmd/clipper`. clipper-0.1.1/clipboard.go000066400000000000000000000023401433160307700154400ustar00rootroot00000000000000package clipper import ( "fmt" "os/exec" ) type Clipboard interface { // Init initializes the clipboard and returns an error if it is not // accessible Init() error // ReadAll returns the contents of the clipboard register 'reg' ReadAll(reg string) ([]byte, error) // WriteAll writes 'p' to the clipboard register 'reg' WriteAll(reg string, p []byte) error } const ( RegClipboard = "clipboard" RegPrimary = "primary" ) type ErrInvalidReg struct { Reg string } func (e *ErrInvalidReg) Error() string { return fmt.Sprintf("invalid register: %s", e.Reg) } func verify(clip Clipboard, cmds ...string) error { for _, cmd := range cmds { if _, err := exec.LookPath(cmd); err != nil { // command not installed return err } } _, err := clip.ReadAll(RegClipboard) if err == nil { // reading clipboard worked return nil } // reading could fail if the clipboard has no contents, so check if writing // works in that case return clip.WriteAll(RegClipboard, []byte{}) } func write(cmd *exec.Cmd, p []byte) error { in, err := cmd.StdinPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } if _, err := in.Write(p); err != nil { return err } in.Close() return cmd.Wait() } clipper-0.1.1/clipboards_darwin.go000066400000000000000000000001141433160307700171640ustar00rootroot00000000000000//go:build darwin package clipper var Clipboards = []Clipboard{ &Pb{}, } clipper-0.1.1/clipboards_other.go000066400000000000000000000002221433160307700170210ustar00rootroot00000000000000//go:build !windows && !darwin && !plan9 package clipper var Clipboards = []Clipboard{ &Wayland{}, &Xclip{}, &Xsel{}, &Wsl{}, &Termux{}, } clipper-0.1.1/clipboards_plan9.go000066400000000000000000000001161433160307700167250ustar00rootroot00000000000000//go:build plan9 package clipper var Clipboards = []Clipboard{ &Snarf{}, } clipper-0.1.1/clipboards_windows.go000066400000000000000000000001211433160307700173700ustar00rootroot00000000000000//go:build windows package clipper var Clipboards = []Clipboard{ &WinApi{}, } clipper-0.1.1/cmd/000077500000000000000000000000001433160307700137165ustar00rootroot00000000000000clipper-0.1.1/cmd/clipper/000077500000000000000000000000001433160307700153545ustar00rootroot00000000000000clipper-0.1.1/cmd/clipper/clipper.go000066400000000000000000000014561433160307700173470ustar00rootroot00000000000000package main import ( "flag" "fmt" "io" "os" "github.com/zyedidia/clipper" ) func must(err error) { if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } var paste = flag.Bool("paste", false, "paste clipboard contents") var cpy = flag.Bool("copy", false, "copy into clipboard") var reg = flag.String("reg", "clipboard", "clipboard register to use") func prepend[T any](c T, cs []T) []T { return append([]T{c}, cs...) } func main() { flag.Parse() clip, err := clipper.GetClipboard(prepend[clipper.Clipboard](&clipper.Custom{ Name: "clipper-clip", }, clipper.Clipboards)...) must(err) if *cpy { data, err := io.ReadAll(os.Stdin) must(err) err = clip.WriteAll(*reg, data) must(err) } if *paste { data, err := clip.ReadAll(*reg) must(err) fmt.Print(string(data)) } } clipper-0.1.1/custom.go000066400000000000000000000005711433160307700150170ustar00rootroot00000000000000package clipper import ( "os/exec" ) type Custom struct { Name string } func (c *Custom) Init() error { return verify(c, c.Name) } func (c *Custom) ReadAll(reg string) ([]byte, error) { cmd := exec.Command(c.Name, "-o", reg) return cmd.Output() } func (c *Custom) WriteAll(reg string, p []byte) error { cmd := exec.Command(c.Name, "-i", reg) return write(cmd, p) } clipper-0.1.1/detect.go000066400000000000000000000010221433160307700147450ustar00rootroot00000000000000package clipper import "bytes" type MultiErr []error func (me MultiErr) Error() string { b := &bytes.Buffer{} for _, e := range me { b.WriteString(e.Error()) b.WriteByte(';') } return b.String() } // GetClipboard iterates through the given clipboards and returns the first one that works. func GetClipboard(clips ...Clipboard) (clip Clipboard, err error) { var errs MultiErr for _, clip := range clips { if err = clip.Init(); err == nil { return clip, nil } errs = append(errs, err) } return nil, errs } clipper-0.1.1/file.go000066400000000000000000000006221433160307700144210ustar00rootroot00000000000000package clipper import ( "io/ioutil" "os" "path/filepath" ) type File struct { Dir string } func (fb *File) Init() error { return os.MkdirAll(fb.Dir, os.ModePerm) } func (fb *File) ReadAll(reg string) ([]byte, error) { return ioutil.ReadFile(filepath.Join(fb.Dir, reg)) } func (fb *File) WriteAll(reg string, p []byte) error { return ioutil.WriteFile(filepath.Join(fb.Dir, reg), p, 0666) } clipper-0.1.1/go.mod000066400000000000000000000000541433160307700142600ustar00rootroot00000000000000module github.com/zyedidia/clipper go 1.18 clipper-0.1.1/internal.go000066400000000000000000000010321433160307700153120ustar00rootroot00000000000000package clipper type Internal struct { regs map[string][]byte } func (i *Internal) Init() error { i.regs = map[string][]byte{ RegClipboard: []byte{}, RegPrimary: []byte{}, } return nil } func (i *Internal) ReadAll(reg string) ([]byte, error) { if p, ok := i.regs[reg]; ok { b := make([]byte, len(p)) copy(b, p) return b, nil } else { return nil, &ErrInvalidReg{ Reg: reg, } } } func (i *Internal) WriteAll(reg string, p []byte) error { i.regs[reg] = make([]byte, len(p)) copy(i.regs[reg], p) return nil } clipper-0.1.1/multi.go000066400000000000000000000022411433160307700146330ustar00rootroot00000000000000package clipper import "bytes" type Multi struct { Clip Clipboard data map[string][][]byte } func (m *Multi) Init() { m.data = map[string][][]byte{ "clipboard": [][]byte{}, "primary": [][]byte{}, } } func (m *Multi) full(reg string) []byte { content := m.data[reg] buf := &bytes.Buffer{} for _, s := range content { buf.Write(s) } return buf.Bytes() } func (m *Multi) text(reg string, num int) []byte { content := m.data[reg] if len(content) <= num { return nil } return content[num] } func (m *Multi) ReadCursor(reg string, num, ncursors int) ([]byte, error) { clip, err := m.Clip.ReadAll(reg) if err != nil { return nil, err } if m.IsValid(reg, clip, ncursors) { return m.text(reg, num), nil } return clip, nil } func (m *Multi) WriteCursor(reg string, p []byte, num, ncursors int) error { if len(m.data[reg]) != ncursors { m.data[reg] = make([][]byte, ncursors) } if num >= ncursors { return nil } m.data[reg][num] = p return m.Clip.WriteAll(reg, m.full(reg)) } func (m *Multi) IsValid(reg string, system []byte, ncursors int) bool { if len(m.data[reg]) != ncursors { return false } return bytes.Equal(system, m.full(reg)) } clipper-0.1.1/pb.go000066400000000000000000000010111433160307700140740ustar00rootroot00000000000000package clipper import ( "os/exec" ) // pbpaste/pbcopy for macos type Pb struct{} func (pb *Pb) Init() error { return verify(pb, "pbpaste", "pbcopy") } func (pb *Pb) ReadAll(reg string) ([]byte, error) { if reg != RegClipboard { return nil, &ErrInvalidReg{ Reg: reg, } } cmd := exec.Command("pbpaste") return cmd.Output() } func (pb *Pb) WriteAll(reg string, p []byte) error { if reg != RegClipboard { return &ErrInvalidReg{ Reg: reg, } } cmd := exec.Command("pbcopy") return write(cmd, p) } clipper-0.1.1/snarf.go000066400000000000000000000010021433160307700146040ustar00rootroot00000000000000package clipper import ( "io/ioutil" "os" ) // snarf for plan9 type Snarf struct{} func (s *Snarf) Init() error { _, err := os.Stat("/dev/snarf") return err } func (s *Snarf) ReadAll(reg string) ([]byte, error) { if reg != RegClipboard { return nil, &ErrInvalidReg{ Reg: reg, } } return ioutil.ReadFile("/dev/snarf") } func (s *Snarf) WriteAll(reg string, p []byte) error { if reg != RegClipboard { return &ErrInvalidReg{ Reg: reg, } } return ioutil.WriteFile("/dev/snarf", p, 0666) } clipper-0.1.1/termux.go000066400000000000000000000012401433160307700150230ustar00rootroot00000000000000package clipper import ( "os/exec" ) // termux-clipboard for Android Termux type Termux struct{} func (t *Termux) Init() error { return verify(t, "termux-clipboard-get", "termux-clipboard-set") } func (t *Termux) ReadAll(reg string) ([]byte, error) { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("termux-clipboard-get") default: return nil, &ErrInvalidReg{ Reg: reg, } } return cmd.Output() } func (t *Termux) WriteAll(reg string, p []byte) error { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("termux-clipboard-set") default: return &ErrInvalidReg{ Reg: reg, } } return write(cmd, p) } clipper-0.1.1/wayland.go000066400000000000000000000015761433160307700151520ustar00rootroot00000000000000package clipper import ( "fmt" "os" "os/exec" ) // wl-paste/wl-copy for linux Wayland type Wayland struct{} func (wl *Wayland) Init() error { if os.Getenv("WAYLAND_DISPLAY") != "" { return verify(wl, "wl-paste", "wl-copy") } return fmt.Errorf("Wayland display not found") } func (wl *Wayland) ReadAll(reg string) ([]byte, error) { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("wl-paste", "--no-newline") case RegPrimary: cmd = exec.Command("wl-paste", "--no-newline", "--primary") default: return nil, &ErrInvalidReg{ Reg: reg, } } return cmd.Output() } func (wl *Wayland) WriteAll(reg string, p []byte) error { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("wl-copy") case RegPrimary: cmd = exec.Command("wl-copy", "--primary") default: return &ErrInvalidReg{ Reg: reg, } } return write(cmd, p) } clipper-0.1.1/winapi.go000066400000000000000000000106001433160307700147660ustar00rootroot00000000000000// Copyright 2013 @atotto. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE-EXTRA file. //go:build windows package clipper import ( "runtime" "syscall" "time" "unsafe" ) type WinApi struct{} const ( cfUnicodetext = 13 gmemMoveable = 0x0002 ) var ( user32 = syscall.MustLoadDLL("user32") isClipboardFormatAvailable = user32.MustFindProc("IsClipboardFormatAvailable") openClipboard = user32.MustFindProc("OpenClipboard") closeClipboard = user32.MustFindProc("CloseClipboard") emptyClipboard = user32.MustFindProc("EmptyClipboard") getClipboardData = user32.MustFindProc("GetClipboardData") setClipboardData = user32.MustFindProc("SetClipboardData") kernel32 = syscall.NewLazyDLL("kernel32") globalAlloc = kernel32.NewProc("GlobalAlloc") globalFree = kernel32.NewProc("GlobalFree") globalLock = kernel32.NewProc("GlobalLock") globalUnlock = kernel32.NewProc("GlobalUnlock") lstrcpy = kernel32.NewProc("lstrcpyW") ) // waitOpenClipboard opens the clipboard, waiting for up to a second to do so. func waitOpenClipboard() error { started := time.Now() limit := started.Add(time.Second) var r uintptr var err error for time.Now().Before(limit) { r, _, err = openClipboard.Call(0) if r != 0 { return nil } time.Sleep(time.Millisecond) } return err } func (w *WinApi) Init() error { return nil } func (w *WinApi) ReadAll(reg string) ([]byte, error) { // LockOSThread ensure that the whole method will keep executing on the same thread from begin to end (it actually locks the goroutine thread attribution). // Otherwise if the goroutine switch thread during execution (which is a common practice), the OpenClipboard and CloseClipboard will happen on two different threads, and it will result in a clipboard deadlock. runtime.LockOSThread() defer runtime.UnlockOSThread() if formatAvailable, _, err := isClipboardFormatAvailable.Call(cfUnicodetext); formatAvailable == 0 { return nil, err } if reg != RegClipboard { return nil, &ErrInvalidReg{ Reg: reg, } } err := waitOpenClipboard() if err != nil { return nil, err } h, _, err := getClipboardData.Call(cfUnicodetext) if h == 0 { _, _, _ = closeClipboard.Call() return nil, err } l, _, err := globalLock.Call(h) if l == 0 { _, _, _ = closeClipboard.Call() return nil, err } text := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(l))[:]) r, _, err := globalUnlock.Call(h) if r == 0 { _, _, _ = closeClipboard.Call() return nil, err } closed, _, err := closeClipboard.Call() if closed == 0 { return nil, err } return []byte(text), nil } func (w *WinApi) WriteAll(reg string, text []byte) error { // LockOSThread ensure that the whole method will keep executing on the same thread from begin to end (it actually locks the goroutine thread attribution). // Otherwise if the goroutine switch thread during execution (which is a common practice), the OpenClipboard and CloseClipboard will happen on two different threads, and it will result in a clipboard deadlock. runtime.LockOSThread() defer runtime.UnlockOSThread() if reg != RegClipboard { return &ErrInvalidReg{ Reg: reg, } } err := waitOpenClipboard() if err != nil { return err } r, _, err := emptyClipboard.Call(0) if r == 0 { _, _, _ = closeClipboard.Call() return err } data := syscall.StringToUTF16(string(text)) // "If the hMem parameter identifies a memory object, the object must have // been allocated using the function with the GMEM_MOVEABLE flag." h, _, err := globalAlloc.Call(gmemMoveable, uintptr(len(data)*int(unsafe.Sizeof(data[0])))) if h == 0 { _, _, _ = closeClipboard.Call() return err } defer func() { if h != 0 { globalFree.Call(h) } }() l, _, err := globalLock.Call(h) if l == 0 { _, _, _ = closeClipboard.Call() return err } r, _, err = lstrcpy.Call(l, uintptr(unsafe.Pointer(&data[0]))) if r == 0 { _, _, _ = closeClipboard.Call() return err } r, _, err = globalUnlock.Call(h) if r == 0 { if err.(syscall.Errno) != 0 { _, _, _ = closeClipboard.Call() return err } } r, _, err = setClipboardData.Call(cfUnicodetext, h) if r == 0 { _, _, _ = closeClipboard.Call() return err } h = 0 // suppress deferred cleanup closed, _, err := closeClipboard.Call() if closed == 0 { return err } return nil } clipper-0.1.1/wsl.go000066400000000000000000000013501433160307700143060ustar00rootroot00000000000000package clipper import ( "os/exec" ) // powershell.exe/clip.exe for WSL type Wsl struct{} func (w *Wsl) Init() error { return verify(w, "powershell.exe", "clip.exe") } func (w *Wsl) ReadAll(reg string) ([]byte, error) { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("powershell.exe", "Get-Clipboard") default: return nil, &ErrInvalidReg{ Reg: reg, } } out, err := cmd.Output() if err != nil { return nil, err } if len(out) > 1 { out = out[:len(out)-2] } return out, nil } func (w *Wsl) WriteAll(reg string, p []byte) error { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("clip.exe") default: return &ErrInvalidReg{ Reg: reg, } } return write(cmd, p) } clipper-0.1.1/xclip.go000066400000000000000000000013711433160307700146230ustar00rootroot00000000000000package clipper import ( "os/exec" ) // xclip for linux X type Xclip struct{} func (x *Xclip) Init() error { return verify(x, "xclip") } func (x *Xclip) ReadAll(reg string) ([]byte, error) { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("xclip", "-out", "-selection", "clipboard") case RegPrimary: cmd = exec.Command("xclip", "-out") default: return nil, &ErrInvalidReg{ Reg: reg, } } return cmd.Output() } func (x *Xclip) WriteAll(reg string, p []byte) error { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("xclip", "-in", "-selection", "clipboard") case RegPrimary: cmd = exec.Command("xclip", "-in") default: return &ErrInvalidReg{ Reg: reg, } } return write(cmd, p) } clipper-0.1.1/xsel.go000066400000000000000000000013471433160307700144620ustar00rootroot00000000000000package clipper import ( "os/exec" ) // xsel for linux X type Xsel struct{} func (x *Xsel) Init() error { return verify(x, "xsel") } func (x *Xsel) ReadAll(reg string) ([]byte, error) { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("xsel", "--output", "--clipboard") case RegPrimary: cmd = exec.Command("xsel", "--output") default: return nil, &ErrInvalidReg{ Reg: reg, } } return cmd.Output() } func (x *Xsel) WriteAll(reg string, p []byte) error { var cmd *exec.Cmd switch reg { case RegClipboard: cmd = exec.Command("xsel", "--input", "--clipboard") case RegPrimary: cmd = exec.Command("xsel", "--input") default: return &ErrInvalidReg{ Reg: reg, } } return write(cmd, p) }