Improve paste example

This commit is contained in:
Sasha Koshka 2024-07-11 01:50:16 -04:00
parent dab360de75
commit 1db7d2d582

View File

@ -11,6 +11,8 @@ import "github.com/jezek/xgbutil/xprop"
import "github.com/jezek/xgbutil/xevent"
import "github.com/jezek/xgbutil/xwindow"
// requestor implements xgbsel.Requestor. It asks for text and outputs it to
// os.Stdout, and any logs to the default logging output (os.Stderr).
type requestor struct {
window *xwindow.Window
}
@ -22,24 +24,42 @@ func (requestor requestor) Window () *xwindow.Window {
func (requestor requestor) Success (target xgbsel.Target, data io.ReadCloser) {
defer data.Close()
text, _ := io.ReadAll(data)
log.Println("Clipboard text:", string(text))
log.Println("got clipboard text:")
os.Stdout.Write(text)
os.Exit(0)
}
func (requestor requestor) Failure (err error) {
if err == nil {
log.Fatalln("no available clipboard data")
} else {
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
func (requestor requestor) Choose (available []xgbsel.Target) (xgbsel.Target, bool) {
log.Println("owner supports these targets:", available)
// try to find the closest thing to text/plain by converting each target
// to a MIME type and comparing confidence values
var bestTarget xgbsel.Target
var bestConfidence xgbsel.Confidence
for _, target := range available {
mime, confidence := target.ToMime()
if mime == "text/plain" && confidence > bestConfidence {
bestConfidence = confidence
bestTarget = target
}
}
// if we have any confidence at all, return the result we got
if bestConfidence > xgbsel.ConfidenceNone {
return bestTarget, true
} else {
return "", false
}
}
func main () {
X, err := xgbutil.NewConn()