xgbsel/examples/paste/main.go
2023-06-30 17:23:32 -04:00

75 lines
1.9 KiB
Go

// Example paste shows how to read text data from the CLIPBOARD selection.
package main
import "os"
import "io"
import "log"
import "github.com/jezek/xgbutil"
import "github.com/jezek/xgb/xproto"
import "git.tebibyte.media/tomo/xgbsel"
import "github.com/jezek/xgbutil/xprop"
import "github.com/jezek/xgbutil/xevent"
import "github.com/jezek/xgbutil/xwindow"
type requestor struct {
window *xwindow.Window
}
func (requestor requestor) Window () *xwindow.Window {
return requestor.window
}
func (requestor requestor) Success (target xgbsel.Target, data io.ReadCloser) {
defer data.Close()
text, _ := io.ReadAll(data)
log.Println("Clipboard text:", string(text))
os.Exit(0)
}
func (requestor requestor) Failure (err error) {
log.Fatalln("could not get clipboard:", err)
os.Exit(1)
}
func (requestor requestor) Choose (from []xgbsel.Target) (xgbsel.Target, bool) {
for _, target := range from {
if target == "TEXT" {
return target, true
}
}
return "", false
}
func main () {
X, err := xgbutil.NewConn()
if err != nil {
log.Fatal(err)
}
// create window
window, err := xwindow.Generate(X)
if err != nil {
log.Fatalln("could not generate a new window X id:", err)
}
window.Create(X.RootWin(), 0, 0, 500, 500, xproto.CwBackPixel, 0xffffffff)
// get the atom for the clipboard, and the name of the property we want
// to recieve the selection contents on (which can be anything)
log.Println("creating request")
clipboard, _ := xprop.Atm(X, "CLIPBOARD")
property, _ := xprop.Atm(X, "DESTINATION")
request := xgbsel.NewRequest (
requestor { window: window },
clipboard,
property)
// listen for events
window.Listen(xproto.EventMaskPropertyChange)
xevent.PropertyNotifyFun(request.HandlePropertyNotify).Connect(X, window.Id)
xevent.SelectionNotifyFun(request.HandleSelectionNotify).Connect(X, window.Id)
log.Println("running main event loop")
xevent.Main(X)
}