clipman/selector.go

87 lines
2 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
)
func selector(history []string, max int, tool string) error {
// reverse the history
for i, j := 0, len(history)-1; i < j; i, j = i+1, j-1 {
history[i], history[j] = history[j], history[i]
}
selected, err := dmenu(history, max, tool)
if err != nil {
2019-05-09 18:46:16 +02:00
if err.Error() == "exit status 1" {
// dmenu exits with this error when no selection done
return nil
}
return err
}
2019-03-25 19:13:19 +01:00
// serve selection to the OS
2019-04-18 23:07:34 +02:00
err = exec.Command("wl-copy", []string{"--", selected}...).Run()
2019-04-18 23:07:34 +02:00
return err
}
func dmenu(list []string, max int, tool string) (string, error) {
2019-04-04 10:21:20 +02:00
if len(list) == 0 {
return "", nil
}
2019-05-09 18:46:16 +02:00
bin, err := exec.LookPath("/usr/bin/" + tool)
if err != nil {
return "", fmt.Errorf("%s is not installed", tool)
}
2019-05-09 08:42:43 +02:00
var args []string
if tool == "dmenu" {
args = []string{"dmenu", "-b",
"-fn",
"-misc-dejavu sans mono-medium-r-normal--17-120-100-100-m-0-iso8859-16",
"-l",
strconv.Itoa(max)}
} else {
args = []string{"rofi", "-dmenu",
"-lines",
strconv.Itoa(max)}
}
// dmenu will break if items contain newlines, so we must pass them as literals.
// however, when it sends them back, we need a way to restore them to non literals
2019-03-22 22:05:37 +01:00
guide := make(map[string]string)
reprList := []string{}
2019-03-22 22:08:54 +01:00
for _, original := range list {
repr := fmt.Sprintf("%#v", original)
2019-04-04 09:04:57 +02:00
max := len(repr) - 1 // drop right quote
2019-04-04 10:50:15 +02:00
maxChars := 400
// dmenu will split lines longer than 1200 something; we cut at 400 to spare memory
if max > maxChars {
max = maxChars
2019-04-04 09:04:57 +02:00
}
repr = repr[1:max] // drop left quote
2019-03-22 22:08:54 +01:00
guide[repr] = original
reprList = append(reprList, repr)
}
input := strings.NewReader(strings.Join(reprList, "\n"))
2019-05-09 18:46:16 +02:00
cmd := exec.Cmd{Path: bin, Args: args, Stdin: input}
selected, err := cmd.Output()
if err != nil {
return "", err
}
trimmed := selected[:len(selected)-1] // drop newline
2019-04-04 09:04:57 +02:00
sel, ok := guide[string(trimmed)]
if !ok {
return "", fmt.Errorf("couldn't recover original string; please report this bug along with a copy of your clipman.json")
}
return sel, nil
}