2019-03-22 16:25:09 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
2019-04-18 16:15:35 +02:00
|
|
|
"log"
|
2019-03-22 16:25:09 +01:00
|
|
|
"os/exec"
|
|
|
|
)
|
|
|
|
|
2019-09-16 20:38:39 +02:00
|
|
|
func store(text string, history []string, histfile string, max int, persist bool) {
|
|
|
|
if text == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
l := len(history)
|
|
|
|
if l > 0 {
|
|
|
|
if history[l-1] == text {
|
2019-09-16 20:38:39 +02:00
|
|
|
return
|
2019-04-16 14:21:36 +02:00
|
|
|
}
|
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
if l >= max {
|
|
|
|
// usually just one item, but more if we reduce our --max-items value
|
|
|
|
history = history[l-max+1:]
|
2019-03-22 16:25:09 +01:00
|
|
|
}
|
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
// remove duplicates
|
|
|
|
history = filter(history, text)
|
|
|
|
}
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
history = append(history, text)
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
// dump history to file so that other apps can query it
|
|
|
|
if err := write(history, histfile); err != nil {
|
|
|
|
log.Fatalf("Fatal error writing history: %s", err)
|
|
|
|
}
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-10 16:20:27 +02:00
|
|
|
if persist {
|
|
|
|
// make the copy buffer available to all applications,
|
|
|
|
// even when the source has disappeared
|
|
|
|
if err := exec.Command("wl-copy", []string{"--", text}...).Run(); err != nil {
|
|
|
|
log.Printf("Error running wl-copy: %s", err)
|
2019-03-22 16:25:09 +01:00
|
|
|
}
|
2019-09-10 16:20:27 +02:00
|
|
|
}
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-16 20:38:39 +02:00
|
|
|
return
|
2019-09-10 16:20:27 +02:00
|
|
|
}
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-16 19:39:53 +02:00
|
|
|
func filter(history []string, text string) []string {
|
|
|
|
var (
|
|
|
|
found bool
|
|
|
|
idx int
|
|
|
|
)
|
|
|
|
|
|
|
|
for i, el := range history {
|
|
|
|
if el == text {
|
|
|
|
found = true
|
|
|
|
idx = i
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2019-03-22 16:25:09 +01:00
|
|
|
|
2019-09-16 19:39:53 +02:00
|
|
|
if found {
|
|
|
|
// we know that idx can't be the last element, because
|
|
|
|
// we never get to call this function if that's the case
|
|
|
|
history = append(history[:idx], history[idx+1:]...)
|
2019-09-10 16:20:27 +02:00
|
|
|
}
|
|
|
|
|
2019-09-16 19:39:53 +02:00
|
|
|
return history
|
|
|
|
}
|
|
|
|
|
|
|
|
func write(history []string, histfile string) error {
|
|
|
|
histlog, err := json.Marshal(history)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-03-22 16:25:09 +01:00
|
|
|
}
|
2019-09-16 19:39:53 +02:00
|
|
|
err = ioutil.WriteFile(histfile, histlog, 0644)
|
|
|
|
|
|
|
|
return err
|
2019-03-22 16:25:09 +01:00
|
|
|
}
|