talc/main.go
2020-03-18 05:16:25 +01:00

131 lines
2.3 KiB
Go

package main
import (
"flag"
"fmt"
"os"
"os/user"
"path/filepath"
"sort"
"talc/pkg/menu"
"talc/pkg/tal"
"github.com/gdamore/tcell"
"github.com/gdamore/tcell/views"
)
var path = flag.String("path", ".", "library path")
var editor = flag.String("editor", os.Getenv("EDITOR"), "editor")
func init() {
flag.Parse()
*path = filepath.FromSlash(*path)
if (*path)[0] == '~' {
user, err := user.Current()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(10)
}
*path = filepath.Join(user.HomeDir, (*path)[1:])
}
*path, _ = filepath.Abs(*path)
}
type Talc struct {
views.BoxLayout
}
func (t *Talc) HandleEvent(ev tcell.Event) bool {
switch ev := ev.(type) {
case *tcell.EventKey:
switch ev.Key() {
case tcell.KeyEscape:
fallthrough
case tcell.KeyCtrlC:
app.Quit()
return true
case tcell.KeyCtrlL:
app.Refresh()
return true
case tcell.KeyRune:
switch ev.Rune() {
case 'q':
app.Quit()
return true
}
}
case *tcell.EventResize:
app.Refresh()
return true
}
return t.BoxLayout.HandleEvent(ev)
}
var app = &views.Application{}
var talc = &Talc{}
func main() {
alib := &tal.Repo{
Path: *path,
}
if err := alib.Scan(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(11)
}
s := tcell.StyleDefault
ss := s.Foreground(tcell.ColorGreen)
meta := alib.GetMeta()
root := menu.Option{
Name: "talc",
}
tags := []menu.Option{}
for tag, vals := range meta {
topt := menu.Option{
Name: tag,
Action: menu.ActionMenu,
}
valopts := []menu.Option{}
for value, books := range vals {
vopt := menu.Option{
Name: value,
Action: menu.ActionMenu,
}
bookopts := []menu.Option{}
for _, book := range books {
bopt := menu.Option{
Name: book.String(),
Action: menu.ActionExec,
Args: []string{*editor, book.Path},
}
bookopts = append(bookopts, bopt)
}
sort.Sort(menu.ByName(bookopts))
vopt.Options = bookopts
valopts = append(valopts, vopt)
}
sort.Sort(menu.ByOptions(valopts))
topt.Options = valopts
tags = append(tags, topt)
}
sort.Sort(menu.ByOptions(tags))
root.Options = tags
mt := menu.NewMenu(app)
mt.SetStyle(s)
mt.SetSelectedStyle(ss)
mt.SetCurrent(root)
talc.AddWidget(mt, 10)
app.SetRootWidget(talc)
if err := app.Run(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}