rofi-blocks-search/rofi/rofi.go

115 lines
2.9 KiB
Go
Raw Permalink Normal View History

2020-08-08 17:14:21 +00:00
package rofi
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
var (
// InputChangeCallback called when the user types somthing in
InputChangeCallback func(Input)
// CustomKeyCallback idk
CustomKeyCallback func(Input)
// ActivateEntryCallback when the user press enter on an entry
ActivateEntryCallback func(Input)
// SelectEntryCallback when a user selects a entry via arrow keys
SelectEntryCallback func(Input)
// DeleteEntryCallback idk
DeleteEntryCallback func(Input)
// CustomInputCallback idk
CustomInputCallback func(Input)
)
// Output json to send to rofi
type Output struct {
Message string `json:"message,omitempty"` // Sets rofi message, hides it if empty or null
Overlay string `json:"overlay,omitempty"` // Shows overlay with text, hides it if empty or null
Prompt string `json:"prompt,omitempty"` // sets prompt text
Input string `json:"input,omitempty"` // sets input text, to clear use empty string
InputAction string `json:"input action,omitempty"` // "send" or "filter"
EventFormat string `json:"event format,omitempty"` // event format used to send to input
Lines []Line `json:"lines"` // a list of sting or json object to set rofi list content
}
// Line a single entry
type Line struct {
Text string `json:"text,required"`
Urgent bool `json:"urgent,omitempty"`
Highlight bool `json:"highlight,omitempty"`
Markup bool `json:"markup,omitempty"`
Icon string `json:"icon,omitempty"`
}
// Input send when the user types something
type Input struct {
Name string `json:"name"`
Value string `json:"value"`
}
// ConvertStringsToLine converts a string array to Line array with all flags set to false
func ConvertStringsToLine(strings []string) []Line {
lines := make([]Line, len(strings))
for i, v := range strings {
lines[i] = Line{v, false, false, false, ""}
}
return lines
}
// SendOutput sends output to rofi
func SendOutput(output Output) {
res, _ := json.Marshal(output)
fmt.Printf("%s\n", res)
}
// NewOutput helper for a new empty outout
func NewOutput() Output {
return Output{"", "", "", "", "", "", []Line{}}
}
// InputLoop blocking loop to handle incomming json
func InputLoop() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
var input Input
bytes := scanner.Bytes()
json.Unmarshal(bytes, &input)
handleInput(input)
}
}
func handleInput(input Input) {
switch input.Name {
case "input change":
if InputChangeCallback != nil {
InputChangeCallback(input)
}
case "custom key":
if CustomKeyCallback != nil {
CustomKeyCallback(input)
}
case "active entry":
if ActivateEntryCallback != nil {
ActivateEntryCallback(input)
}
case "select entry":
if SelectEntryCallback != nil {
SelectEntryCallback(input)
}
case "delete entry":
if DeleteEntryCallback != nil {
DeleteEntryCallback(input)
}
case "exec custom input":
if CustomInputCallback != nil {
CustomInputCallback(input)
}
}
}