From 1db7d2d5825f2d4b9ad87a5eb5bea3119a604259 Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Thu, 11 Jul 2024 01:50:16 -0400 Subject: [PATCH] Improve paste example --- examples/paste/main.go | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/examples/paste/main.go b/examples/paste/main.go index 427b3ec..1e019ef 100644 --- a/examples/paste/main.go +++ b/examples/paste/main.go @@ -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,23 +24,41 @@ 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) { - log.Fatalln("could not get clipboard:", err) + 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 } } - return "", false + // if we have any confidence at all, return the result we got + if bestConfidence > xgbsel.ConfidenceNone { + return bestTarget, true + } else { + return "", false + } } func main () {