diff options
Diffstat (limited to 'gui/internal')
| -rw-r--r-- | gui/internal/model/cond.go | 126 | ||||
| -rw-r--r-- | gui/internal/model/cond_test.go | 94 | ||||
| -rw-r--r-- | gui/internal/model/newdir.go | 20 | ||||
| -rw-r--r-- | gui/internal/model/newdir_test.go | 72 | ||||
| -rw-r--r-- | gui/internal/ui/forms.go | 173 | ||||
| -rw-r--r-- | gui/internal/ui/plan.go | 27 | ||||
| -rw-r--r-- | gui/internal/ui/rules.go | 20 | ||||
| -rw-r--r-- | gui/internal/ui/window.go | 62 |
8 files changed, 565 insertions, 29 deletions
diff --git a/gui/internal/model/cond.go b/gui/internal/model/cond.go new file mode 100644 index 0000000..04cc4d1 --- /dev/null +++ b/gui/internal/model/cond.go @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package model + +import ( + "fmt" + "strings" + + "krino/internal/sexp" +) + +// CondOps are the forms that hold other conditions. +var CondOps = map[string]bool{"and": true, "or": true, "not": true} + +// CondTests are the tests a condition can make, in the order a picker +// offers them. +var CondTests = []string{"type", "name", "path", "content", "size", "age", "duplicate", "matched"} + +// Cond is one condition in the tree the forms editor shows: either a test, +// with its arguments as the file writes them, or one of and / or / not +// holding the conditions under it (GUI design §5.1). +type Cond struct { + Kind string + Args string + Children []*Cond +} + +// ParseCond reads a parsed form into the tree. Anything that is not a list +// - which the config parser refuses anyway - comes back as a test with the +// text as its arguments, so nothing is ever silently dropped. +func ParseCond(n *sexp.Node) *Cond { + if n == nil { + return &Cond{Kind: "type"} + } + if n.Kind != sexp.List || len(n.Children) == 0 { + return &Cond{Kind: n.String()} + } + head := n.Head() + if CondOps[head] { + c := &Cond{Kind: head} + for _, child := range n.Args() { + c.Children = append(c.Children, ParseCond(child)) + } + return c + } + var args []string + for _, a := range n.Args() { + args = append(args, a.String()) + } + return &Cond{Kind: head, Args: strings.Join(args, " ")} +} + +// Text writes the condition back as krino reads it. +func (c *Cond) Text() string { + if c == nil { + return "" + } + if CondOps[c.Kind] { + parts := make([]string, 0, len(c.Children)) + for _, child := range c.Children { + if t := child.Text(); t != "" { + parts = append(parts, t) + } + } + if len(parts) == 0 { + return "" + } + return "(" + c.Kind + " " + strings.Join(parts, " ") + ")" + } + args := strings.TrimSpace(c.Args) + if args == "" { + return "(" + c.Kind + ")" + } + return "(" + c.Kind + " " + args + ")" +} + +// Parse checks that a condition is one krino can read, and says where it is +// wrong if it is not. +func (c *Cond) Parse() error { + text := c.Text() + if text == "" { + return fmt.Errorf("%s has nothing under it", c.Kind) + } + nodes, err := sexp.Parse("form", []byte(text)) + if err != nil { + return err + } + if len(nodes) != 1 { + return fmt.Errorf("%s is not one condition", text) + } + return nil +} + +// Add puts a new condition under an operator; a test gets none. +func (c *Cond) Add(kind string) *Cond { + if !CondOps[c.Kind] { + return nil + } + child := &Cond{Kind: kind} + c.Children = append(c.Children, child) + return child +} + +// Remove takes one condition out of the tree, wherever it is, and reports +// whether it found it. The root itself is never removed by this. +func (c *Cond) Remove(target *Cond) bool { + for i, child := range c.Children { + if child == target { + c.Children = append(c.Children[:i], c.Children[i+1:]...) + return true + } + if child.Remove(target) { + return true + } + } + return false +} + +// Walk calls f for every condition in the tree, depth first, with how deep +// it sits and the operator holding it (nil for the roots). +func (c *Cond) Walk(depth int, parent *Cond, f func(node, parent *Cond, depth int)) { + f(c, parent, depth) + for _, child := range c.Children { + child.Walk(depth+1, c, f) + } +} diff --git a/gui/internal/model/cond_test.go b/gui/internal/model/cond_test.go new file mode 100644 index 0000000..7aa4772 --- /dev/null +++ b/gui/internal/model/cond_test.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package model + +import ( + "strings" + "testing" + + "krino/internal/sexp" +) + +// parseOne reads one condition from text, for the tests below. +func parseOne(t *testing.T, text string) *Cond { + t.Helper() + nodes, err := sexp.Parse("test", []byte(text)) + if err != nil || len(nodes) != 1 { + t.Fatalf("%q does not parse: %v", text, err) + } + return ParseCond(nodes[0]) +} + +// TestCondRoundTrip: a condition read into the tree and written back is the +// same condition, however deep it nests. +func TestCondRoundTrip(t *testing.T) { + for _, text := range []string{ + `(type pdf)`, + `(name "^faktura" "^fv")`, + `(duplicate)`, + `(and (type pdf) (content "invoice"))`, + `(or (and (type doc) (age > 90d)) (not (duplicate "~/docs")))`, + `(not (and (name "a;b") (size > 10M)))`, + } { + c := parseOne(t, text) + if got := c.Text(); got != text { + t.Errorf("round trip of %q gave %q", text, got) + } + if err := c.Parse(); err != nil { + t.Errorf("%q does not parse after the round trip: %v", text, err) + } + } +} + +// TestCondTree: an operator holds its conditions, and the tree says how +// deep each one sits. +func TestCondTree(t *testing.T) { + c := parseOne(t, `(and (type pdf) (or (name "a") (name "b")))`) + if c.Kind != "and" || len(c.Children) != 2 { + t.Fatalf("tree = %+v", c) + } + var depths []string + c.Walk(0, nil, func(node, parent *Cond, depth int) { + depths = append(depths, strings.Repeat(" ", depth)+node.Kind) + }) + want := []string{"and", " type", " or", " name", " name"} + if strings.Join(depths, "|") != strings.Join(want, "|") { + t.Errorf("walk = %v, want %v", depths, want) + } +} + +// TestCondAddAndRemove: conditions go under an operator and come out again; +// a test holds none. +func TestCondAddAndRemove(t *testing.T) { + c := parseOne(t, `(and (type pdf))`) + added := c.Add("content") + if added == nil || len(c.Children) != 2 { + t.Fatalf("after adding: %+v", c) + } + added.Args = `"invoice"` + if got := c.Text(); got != `(and (type pdf) (content "invoice"))` { + t.Errorf("text = %q", got) + } + if !c.Remove(added) || len(c.Children) != 1 { + t.Errorf("removing left %+v", c) + } + if c.Children[0].Add("name") != nil { + t.Error("a test took a condition under it") + } + // Removing something that is not there changes nothing. + if c.Remove(&Cond{Kind: "name"}) { + t.Error("removed a condition that is not in the tree") + } +} + +// TestCondEmptyOperator: an operator with nothing under it writes nothing +// rather than "(and)", which krino would refuse, and says so when asked. +func TestCondEmptyOperator(t *testing.T) { + c := &Cond{Kind: "and"} + if got := c.Text(); got != "" { + t.Errorf("text = %q, want nothing", got) + } + if err := c.Parse(); err == nil { + t.Error("an empty operator passed the check") + } +} diff --git a/gui/internal/model/newdir.go b/gui/internal/model/newdir.go new file mode 100644 index 0000000..d0df6db --- /dev/null +++ b/gui/internal/model/newdir.go @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package model + +import ( + "krino/internal/config" + "krino/internal/engine" +) + +// AddDirectory writes dirs/NAME.conf from the template with path filled in +// and adds NAME to krino.conf's include - exactly what `krino new NAME +// PATH` does, through the same code, so a directory made in the window is +// indistinguishable from one made on the command line (his report that the +// window had no way to add one, 2026-09-17). +// +// It returns the new file's path. The caller reloads the engine: until it +// does, the window knows nothing of the new directory. +func AddDirectory(e *engine.Engine, name, path string) (string, error) { + return config.NewDir(e.MainFile, name, path) +} diff --git a/gui/internal/model/newdir_test.go b/gui/internal/model/newdir_test.go new file mode 100644 index 0000000..19957d9 --- /dev/null +++ b/gui/internal/model/newdir_test.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package model + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "krino/internal/engine" +) + +// TestAddDirectory: a directory added in the window is one krino loads, its +// file written from the template and its name in the include. +func TestAddDirectory(t *testing.T) { + conf := "(path \"~/dl\")\n(rule \"all\" (move \"Out\"))\n" + e, h := sandboxDir(t, conf, map[string]string{"a.pdf": "one"}) + target := filepath.Join(h, "papers") + if err := os.MkdirAll(target, 0o755); err != nil { + t.Fatal(err) + } + + file, err := AddDirectory(e, "papers", target) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(file); err != nil { + t.Fatalf("the file was not written: %v", err) + } + main, err := os.ReadFile(e.MainFile) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(main), "papers") { + t.Errorf("the include does not name it:\n%s", main) + } + + fresh, diags := engine.Load(e.MainFile) + if len(diags) > 0 { + t.Fatalf("the configuration no longer loads: %v", diags) + } + found := false + for _, d := range fresh.Dirs { + if d.Name == "papers" && d.Root == target { + found = true + } + } + if !found { + t.Errorf("the new directory is not in the configuration: %+v", fresh.Dirs) + } + // And the window can open its rules straight away. + if _, err := OpenRules(fresh, "papers"); err != nil { + t.Errorf("its rules do not open: %v", err) + } +} + +// TestAddDirectoryRefusals: the checks krino new makes are the checks the +// window makes, because it is the same code. +func TestAddDirectoryRefusals(t *testing.T) { + conf := "(path \"~/dl\")\n(rule \"all\" (move \"Out\"))\n" + e, h := sandboxDir(t, conf, map[string]string{"a.pdf": "one"}) + for _, c := range []struct{ name, path, why string }{ + {"has space", h, "a name with a space"}, + {"check", h, "a krino command"}, + {"dl", h, "a name already taken"}, + } { + if _, err := AddDirectory(e, c.name, c.path); err == nil { + t.Errorf("%s was accepted", c.why) + } + } +} diff --git a/gui/internal/ui/forms.go b/gui/internal/ui/forms.go index 8e1fd33..18a8b13 100644 --- a/gui/internal/ui/forms.go +++ b/gui/internal/ui/forms.go @@ -655,18 +655,18 @@ func hitsText(h *model.RuleHits, root string) string { // formEditor is the widgets of one form, and can write it back. type formEditor struct { - kind model.FormKind - root *gtk.Box - name *gtk.Entry - conds *gtk.Box - rows []*condRow - acts *gtk.Box - arows []*actionRow - stop *gtk.CheckButton - cse *gtk.DropDown - fold *gtk.DropDown - onConf *gtk.DropDown - changed func() + kind model.FormKind + root *gtk.Box + name *gtk.Entry + conds *gtk.Box + conditions []*model.Cond + acts *gtk.Box + arows []*actionRow + stop *gtk.CheckButton + cse *gtk.DropDown + fold *gtk.DropDown + onConf *gtk.DropDown + changed func() } func newFormEditor(form model.Form, changed func()) *formEditor { @@ -685,15 +685,12 @@ func newFormEditor(form model.Form, changed func()) *formEditor { fe.root.Append(field("Name", fe.name)) } - fe.conds = gtk.NewBox(gtk.OrientationVertical, 4) + fe.conds = gtk.NewBox(gtk.OrientationVertical, 2) fe.root.Append(heading("Conditions - all of these must hold")) fe.root.Append(fe.conds) - addCond := gtk.NewButtonWithLabel("+ test") - addCond.ConnectClicked(func() { - fe.addCond(nil) - changed() - }) - fe.root.Append(leftAligned(addCond)) + fe.root.Append(leftAligned(fe.addMenu(func(kind string) { + fe.conditions = append(fe.conditions, &model.Cond{Kind: kind}) + }))) when := form.Rule.When if form.Kind == model.ExcludeForm { @@ -702,8 +699,9 @@ func newFormEditor(form model.Form, changed func()) *formEditor { when = nil } for _, c := range when { - fe.addCond(c) + fe.conditions = append(fe.conditions, model.ParseCond(c)) } + fe.drawConds() if form.Kind == model.RuleForm { fe.acts = gtk.NewBox(gtk.OrientationVertical, 4) @@ -738,11 +736,11 @@ func newFormEditor(form model.Form, changed func()) *formEditor { // text is the form as the printer writes it, from what the widgets hold. func (fe *formEditor) text() (string, error) { var when []*sexp.Node - for _, row := range fe.rows { - if row.gone { - continue + for _, c := range fe.conditions { + text := c.Text() + if text == "" { + return "", fmt.Errorf("(%s ...) has no condition under it", c.Kind) } - text := row.text() nodes, err := sexp.Parse("form", []byte(text)) if err != nil { return "", fmt.Errorf("%s: %v", text, err) @@ -774,11 +772,128 @@ func (fe *formEditor) text() (string, error) { return config.PrintRule(rule), nil } -// addCond adds a condition row, filled in from n when there is one. -func (fe *formEditor) addCond(n *sexp.Node) { - row := newCondRow(n, fe.changed) - fe.rows = append(fe.rows, row) - fe.conds.Append(row.root) +// drawConds rebuilds the condition tree: one row per condition, indented by +// how deep it sits, with the operators holding the conditions under them +// (GUI design §5.1, his choice 2026-09-17). +func (fe *formEditor) drawConds() { + for child := fe.conds.FirstChild(); child != nil; child = fe.conds.FirstChild() { + fe.conds.Remove(child) + } + for _, root := range fe.conditions { + root.Walk(0, nil, func(node, parent *model.Cond, depth int) { + fe.conds.Append(fe.condRow(node, parent, depth)) + }) + } +} + +// addMenu is the "+" that puts a condition somewhere: a test, or one of the +// three operators to hold more conditions under it. +func (fe *formEditor) addMenu(add func(kind string)) *gtk.MenuButton { + box := gtk.NewBox(gtk.OrientationVertical, 0) + pop := gtk.NewPopover() + pop.SetChild(box) + button := gtk.NewMenuButton() + button.SetLabel("+") + button.SetTooltipText("add a test here, or and / or / not to hold more conditions") + button.SetPopover(pop) + for _, item := range []struct{ label, kind string }{ + {"test", "type"}, + {"and (all of these)", "and"}, + {"or (any of these)", "or"}, + {"not (none of these)", "not"}, + } { + b := gtk.NewButtonWithLabel(item.label) + b.SetHasFrame(false) + b.SetHAlign(gtk.AlignFill) + kind := item.kind + b.ConnectClicked(func() { + pop.Popdown() + add(kind) + fe.drawConds() + fe.changed() + }) + box.Append(b) + } + return button +} + +// condRow is one line of the tree. +func (fe *formEditor) condRow(node, parent *model.Cond, depth int) *gtk.Box { + row := gtk.NewBox(gtk.OrientationHorizontal, 6) + row.SetMarginStart(depth * 24) + + kind := gtk.NewDropDownFromStrings(condItems()) + if i := indexOf(condKinds, node.Kind); i >= 0 { + kind.SetSelected(uint(i)) + } + kind.Connect("notify::selected", func() { + next := condKinds[kind.Selected()] + if next == node.Kind { + return + } + node.Kind = next + if !model.CondOps[next] { + node.Children = nil + } + fe.drawConds() + fe.changed() + }) + row.Append(kind) + + if model.CondOps[node.Kind] { + // An operator holds conditions rather than arguments. One button + // puts them under it: four side by side ran off the pane. + row.Append(fe.addMenu(func(kind string) { node.Add(kind) })) + row.Append(gtk.NewLabel("")) + } else { + args := gtk.NewEntry() + args.SetText(node.Args) + args.SetHExpand(true) + hint := condHints[node.Kind] + args.SetPlaceholderText(hint) + args.SetTooltipText(hint) + if isCompare(node.Kind) { + op := gtk.NewDropDownFromStrings(compareOps) + opText, value := splitCompare(node.Args) + if i := indexOf(compareOps, opText); i >= 0 { + op.SetSelected(uint(i)) + } + args.SetText(value) + write := func() { + node.Args = compareOps[op.Selected()] + " " + strings.TrimSpace(args.Text()) + fe.changed() + } + op.Connect("notify::selected", func() { write() }) + args.ConnectChanged(func() { write() }) + row.Append(op) + } else { + args.ConnectChanged(func() { + node.Args = strings.TrimSpace(args.Text()) + fe.changed() + }) + } + row.Append(args) + } + + remove := gtk.NewButtonWithLabel("-") + remove.SetHasFrame(false) + remove.SetTooltipText("take this condition out") + remove.ConnectClicked(func() { + if parent != nil { + parent.Remove(node) + } else { + for i, c := range fe.conditions { + if c == node { + fe.conditions = append(fe.conditions[:i], fe.conditions[i+1:]...) + break + } + } + } + fe.drawConds() + fe.changed() + }) + row.Append(remove) + return row } // addAction adds an action row. diff --git a/gui/internal/ui/plan.go b/gui/internal/ui/plan.go index 0a9b718..0adc6b1 100644 --- a/gui/internal/ui/plan.go +++ b/gui/internal/ui/plan.go @@ -469,6 +469,33 @@ func (p *planView) showPath() { p.path.SetText("no directory is included; add one with: krino new NAME PATH") } +// currentName is the directory the picker names, "" when none. +func (p *planView) currentName() string { + if d := p.currentDir(); d != nil { + return d.Name + } + return "" +} + +// refreshDirs rebuilds the directory picker after the configuration +// changed - a directory added in the Rules tab appears here too. +func (p *planView) refreshDirs(keep string) { + names := make([]string, len(p.w.engine.Dirs)) + for i, d := range p.w.engine.Dirs { + names[i] = d.Name + } + if len(names) == 0 { + names = []string{"none"} + } + p.dirs.SetModel(gtk.NewStringList(names)) + for i, d := range p.w.engine.Dirs { + if d.Name == keep { + p.dirs.SetSelected(uint(i)) + } + } + p.showPath() +} + // currentDir is the directory the picker names. func (p *planView) currentDir() *engine.Dir { i := int(p.dirs.Selected()) diff --git a/gui/internal/ui/rules.go b/gui/internal/ui/rules.go index 3bae8df..5cce276 100644 --- a/gui/internal/ui/rules.go +++ b/gui/internal/ui/rules.go @@ -77,6 +77,10 @@ func newRulesView(w *Window) *rulesView { bar.SetMarginBottom(6) bar.Append(gtk.NewLabel("Rules for")) bar.Append(r.dirs) + add := gtk.NewButtonWithLabel("Add directory...") + add.SetTooltipText("sort another directory: writes dirs/NAME.conf from the template and adds NAME to krino.conf's include, as krino new does") + add.ConnectClicked(func() { r.w.addDirectory() }) + bar.Append(add) r.check = gtk.NewLabel("") r.check.SetXAlign(0) r.check.SetHExpand(true) @@ -269,6 +273,22 @@ func (r *rulesView) textChangedByForm() { r.runCheck() } +// refreshDirs rebuilds the picker after the configuration changed. +func (r *rulesView) refreshDirs(keep string) { + r.names = model.RuleFiles(r.w.engine) + names := r.names + if len(names) == 0 { + names = []string{"none"} + } + r.dirs.SetModel(gtk.NewStringList(names)) + for i, n := range r.names { + if n == keep { + r.dirs.SetSelected(uint(i)) + } + } + r.open(r.selectedName()) +} + // selectedName is the directory the picker names, "" when none is offered. func (r *rulesView) selectedName() string { i := int(r.dirs.Selected()) diff --git a/gui/internal/ui/window.go b/gui/internal/ui/window.go index 12e94a3..ce991d8 100644 --- a/gui/internal/ui/window.go +++ b/gui/internal/ui/window.go @@ -149,6 +149,68 @@ func (w *Window) confirmLeaving() { d.Show() } +// addDirectory asks for a name and a path and makes krino sort that +// directory too - the window had no way to do it (his report, 2026-09-17). +func (w *Window) addDirectory() { + d := gtk.NewWindow() + d.SetTitle("Add a directory") + d.SetTransientFor(&w.win.Window) + d.SetModal(true) + d.SetDefaultSize(520, 200) + + name := gtk.NewEntry() + name.SetPlaceholderText("papers") + name.SetTooltipText("the name krino knows it by: letters, digits, '.', '_' and '-'; its rules go in dirs/NAME.conf") + path := gtk.NewEntry() + path.SetPlaceholderText("~/papers") + path.SetHExpand(true) + path.SetTooltipText("the directory to sort") + + note := gtk.NewLabel("") + note.SetXAlign(0) + note.SetWrap(true) + + box := gtk.NewBox(gtk.OrientationVertical, 8) + box.SetMarginStart(12) + box.SetMarginEnd(12) + box.SetMarginTop(12) + box.SetMarginBottom(12) + box.Append(field("name", name)) + box.Append(field("path", path)) + box.Append(note) + + create := gtk.NewButtonWithLabel("Add") + create.AddCSSClass("suggested-action") + cancel := gtk.NewButtonWithLabel("Cancel") + cancel.ConnectClicked(func() { d.Close() }) + buttons := gtk.NewBox(gtk.OrientationHorizontal, 6) + buttons.SetHAlign(gtk.AlignEnd) + buttons.Append(cancel) + buttons.Append(create) + box.Append(buttons) + + create.ConnectClicked(func() { + file, err := model.AddDirectory(w.engine, strings.TrimSpace(name.Text()), strings.TrimSpace(path.Text())) + if err != nil { + note.SetText(escape(err.Error())) + note.AddCSSClass("error") + return + } + added := strings.TrimSpace(name.Text()) + if err := w.reloadEngine(); err != nil { + note.SetText(escape(err.Error())) + note.AddCSSClass("error") + return + } + w.plan.refreshDirs(w.plan.currentName()) + w.rules.refreshDirs(added) + w.setStatus("added %s; its rules are in %s", escape(added), escape(xdg.Abbrev(file))) + d.Close() + }) + d.SetChild(box) + d.Show() +} + // savePrefsSoon writes the preferences a moment after the last change, so // dragging a divider does not write the file on every pixel. func (w *Window) savePrefsSoon() { |
