aboutsummaryrefslogtreecommitdiff
path: root/gui/internal/ui/plan.go
blob: fd2f563bd86ce99192bcdf0acf7a6dfec7e423ba (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// SPDX-License-Identifier: GPL-3.0-or-later

package ui

import (
	"context"
	"fmt"
	"strings"

	"github.com/diamondburned/gotk4/pkg/gdk/v4"
	"github.com/diamondburned/gotk4/pkg/pango"

	"github.com/diamondburned/gotk4/pkg/gtk/v4"

	"krino/gui/internal/model"
	"krino/internal/engine"
	"krino/internal/plan"
	"krino/internal/xdg"
)

// planView is the Plan tab: a directory picker and Scan, the plan as a list
// with a checkbox per file, the selected file's explanation beside it, and
// Apply (GUI design §3).
type planView struct {
	w    *Window
	root *gtk.Box

	dirs    *gtk.DropDown
	path    *gtk.Label
	scan    *gtk.Button
	apply   *gtk.Button
	cancel  *gtk.Button
	selAll  *gtk.Button
	selNone *gtk.Button

	list    *gtk.ListBox
	details *gtk.TextView
	menu    *gtk.Popover
	menuRow int

	tab      *model.PlanTab
	cancelOp context.CancelFunc
}

func newPlanView(w *Window) *planView {
	p := &planView{w: w}
	p.root = gtk.NewBox(gtk.OrientationVertical, 0)

	// The picker holds names only: a long path in it would widen the
	// window past the screen, so the path goes in a label that ellipsizes.
	names := make([]string, len(w.engine.Dirs))
	for i, d := range w.engine.Dirs {
		names[i] = d.Name
	}
	if len(names) == 0 {
		names = []string{"none"}
	}
	p.dirs = gtk.NewDropDownFromStrings(names)
	p.path = gtk.NewLabel("")
	p.path.SetXAlign(0)
	p.path.SetHExpand(true)
	p.path.SetEllipsize(pango.EllipsizeMiddle)
	p.path.SetMaxWidthChars(20)
	p.dirs.Connect("notify::selected", p.showPath)
	p.scan = gtk.NewButtonWithLabel("Scan")
	p.selAll = gtk.NewButtonWithLabel("Select all")
	p.selNone = gtk.NewButtonWithLabel("None")
	p.apply = gtk.NewButtonWithLabel("Apply")
	p.apply.AddCSSClass("suggested-action")
	p.cancel = gtk.NewButtonWithLabel("Cancel")
	p.cancel.SetSensitive(false)

	bar := gtk.NewBox(gtk.OrientationHorizontal, 6)
	bar.SetMarginTop(6)
	bar.SetMarginStart(6)
	bar.SetMarginEnd(6)
	bar.SetMarginBottom(6)
	bar.Append(gtk.NewLabel("Directory"))
	bar.Append(p.dirs)
	bar.Append(p.scan)
	bar.Append(p.path)
	bar.Append(p.selAll)
	bar.Append(p.selNone)
	bar.Append(p.cancel)
	bar.Append(p.apply)

	p.list = gtk.NewListBox()
	p.list.SetSelectionMode(gtk.SelectionSingle)
	listScroll := gtk.NewScrolledWindow()
	listScroll.SetChild(p.list)
	listScroll.SetHExpand(true)
	listScroll.SetVExpand(true)

	p.details = gtk.NewTextView()
	p.details.Buffer().SetText("Select a file to see what would happen to it, and why.")
	p.details.SetEditable(false)
	p.details.SetMonospace(true)
	p.details.SetWrapMode(gtk.WrapWord)
	p.details.SetLeftMargin(8)
	p.details.SetRightMargin(8)
	p.details.SetTopMargin(6)
	p.details.SetBottomMargin(6)
	detailScroll := gtk.NewScrolledWindow()
	detailScroll.SetChild(p.details)
	detailScroll.SetSizeRequest(320, -1)

	// A pane the user can drag: on a narrow window the list needs the room,
	// on a wide one the explanation does.
	panes := gtk.NewPaned(gtk.OrientationHorizontal)
	panes.SetStartChild(listScroll)
	panes.SetEndChild(detailScroll)
	panes.SetResizeStartChild(true)
	panes.SetResizeEndChild(false)
	panes.SetShrinkEndChild(false)
	panes.SetPosition(640)
	panes.SetVExpand(true)

	p.root.Append(bar)
	p.root.Append(gtk.NewSeparator(gtk.OrientationHorizontal))
	p.root.Append(panes)

	p.scan.ConnectClicked(p.onScan)
	p.apply.ConnectClicked(p.onApply)
	p.cancel.ConnectClicked(func() {
		if p.cancelOp != nil {
			p.cancelOp()
		}
	})
	p.selAll.ConnectClicked(func() { p.selectAll(true) })
	p.selNone.ConnectClicked(func() { p.selectAll(false) })
	p.list.ConnectRowSelected(func(row *gtk.ListBoxRow) {
		if row != nil {
			p.showDetails(row.Index())
		}
	})
	// The right button on a row offers the two overrides the terminal
	// review has on t and d (GUI design §3).
	p.menu = p.newMenu()
	click := gtk.NewGestureClick()
	click.SetButton(3)
	click.ConnectPressed(func(_ int, x, y float64) { p.onRightClick(x, y) })
	p.list.AddController(click)

	p.showPath()
	p.setBusy(false)
	return p
}

// newMenu builds the row menu: what to do with a file instead of what the
// rules decided.
func (p *planView) newMenu() *gtk.Popover {
	box := gtk.NewBox(gtk.OrientationVertical, 0)
	trash := gtk.NewButtonWithLabel("Trash instead")
	perm := gtk.NewButtonWithLabel("Delete permanently instead...")
	for _, b := range []*gtk.Button{trash, perm} {
		b.SetHasFrame(false)
		b.SetHAlign(gtk.AlignFill)
		box.Append(b)
	}
	pop := gtk.NewPopover()
	pop.SetChild(box)
	pop.SetParent(p.list)
	pop.SetHasArrow(false)
	trash.ConnectClicked(func() {
		pop.Popdown()
		p.replace(plan.Trash)
	})
	perm.ConnectClicked(func() {
		pop.Popdown()
		p.confirmDeletePermanent()
	})
	return pop
}

// onRightClick opens the menu on the row under the pointer. A plan that has
// been applied is history and cannot be changed.
func (p *planView) onRightClick(x, y float64) {
	if p.tab == nil || p.tab.Applied {
		return
	}
	row := p.list.RowAtY(int(y))
	if row == nil {
		return
	}
	p.list.SelectRow(row)
	p.menuRow = row.Index()
	at := gdk.NewRectangle(int(x), int(y), 1, 1)
	p.menu.SetPointingTo(&at)
	p.menu.Popup()
}

// replace swaps the menu row's steps for the one the user chose.
func (p *planView) replace(kind plan.Kind) {
	if p.tab == nil {
		return
	}
	if err := p.tab.Replace(p.menuRow, kind); err != nil {
		p.w.setStatus("%v", err)
		return
	}
	rel := p.tab.Rows[p.menuRow].Rel
	p.fillList()
	p.showDetails(p.menuRow)
	p.w.setStatus("%s: %s instead", escape(rel), kind)
}

// confirmDeletePermanent asks before a step nothing can undo, naming the
// file (GUI design §3).
func (p *planView) confirmDeletePermanent() {
	if p.tab == nil || p.menuRow < 0 || p.menuRow >= len(p.tab.Rows) {
		return
	}
	rel := p.tab.Rows[p.menuRow].Rel
	d := gtk.NewMessageDialog(&p.w.win.Window, gtk.DialogModal|gtk.DialogDestroyWithParent,
		gtk.MessageWarning, gtk.ButtonsNone)
	d.SetObjectProperty("text", "Delete "+escape(rel)+" permanently?")
	d.SetObjectProperty("secondary-text",
		"It is not moved to the Trash and undo cannot bring it back.")
	d.AddButton("Cancel", int(gtk.ResponseCancel))
	del := d.AddButton("Delete permanently", int(gtk.ResponseAccept))
	if b, ok := del.(*gtk.Button); ok {
		b.AddCSSClass("destructive-action")
	}
	d.ConnectResponse(func(response int) {
		d.Destroy()
		if response == int(gtk.ResponseAccept) {
			p.replace(plan.DeletePermanent)
		}
	})
	d.Show()
}

// showPath writes the chosen directory's path beside the picker.
func (p *planView) showPath() {
	if d := p.currentDir(); d != nil {
		p.path.SetText(escape(xdg.Abbrev(d.Root)))
		return
	}
	p.path.SetText("no directory is included; add one with: krino new NAME PATH")
}

// currentDir is the directory the picker names.
func (p *planView) currentDir() *engine.Dir {
	i := int(p.dirs.Selected())
	if i < 0 || i >= len(p.w.engine.Dirs) {
		return nil
	}
	return p.w.engine.Dirs[i]
}

// onScan plans the chosen directory, off the main loop.
func (p *planView) onScan() {
	d := p.currentDir()
	if d == nil {
		p.w.setStatus("no directory is included; add one with: krino new NAME PATH")
		return
	}
	// One plan at a time: the open one holds its directory's lock, and
	// scanning again - the same directory or another - replaces it.
	p.closeTab()
	p.setBusy(true)
	p.w.setStatus("scanning %s...", escape(d.Name))
	var tab *model.PlanTab
	p.cancelOp = runInBackground(func(ctx context.Context) error {
		var err error
		tab, err = model.Plan(ctx, p.w.engine, d)
		return err
	}, func(err error) {
		p.setBusy(false)
		if err != nil {
			p.w.setStatus("%s: %v", escape(d.Name), err)
			return
		}
		p.tab = tab
		p.fillList()
		c := tab.Counts
		p.w.setStatus("%d scanned, %d to act on, %d excluded, %d skipped, %d with warnings",
			c.Scanned, c.Acting, c.Excluded, c.Skipped, c.Warned)
	})
}

// onApply acts on the checked files, off the main loop.
func (p *planView) onApply() {
	if p.tab == nil {
		return
	}
	n := p.tab.SelectedCount()
	p.setBusy(true)
	p.w.setStatus("applying %d file(s)...", n)
	var res *engine.ApplyResult
	p.cancelOp = runInBackground(func(ctx context.Context) error {
		var err error
		res, err = p.tab.Apply(ctx)
		return err
	}, func(err error) {
		p.setBusy(false)
		p.apply.SetSensitive(false)
		p.fillList()
		if err != nil {
			p.w.setStatus("apply: %v", err)
			return
		}
		p.w.setStatus("%d applied, %d failed, %d declined", res.Applied, res.Failed, res.Declined)
	})
}

// closeTab drops the open plan and releases the directory's lock.
func (p *planView) closeTab() {
	if p.tab == nil {
		return
	}
	if err := p.tab.Close(); err != nil {
		p.w.setStatus("%s: %v", escape(p.tab.Dir.Name), err)
	}
	p.tab = nil
	p.fillList()
}

// setBusy turns the buttons on or off around a background operation.
func (p *planView) setBusy(busy bool) {
	p.scan.SetSensitive(!busy)
	p.dirs.SetSensitive(!busy)
	p.selAll.SetSensitive(!busy)
	p.selNone.SetSensitive(!busy)
	p.apply.SetSensitive(!busy && p.tab != nil && !p.tab.Applied)
	p.cancel.SetSensitive(busy)
}

// selectAll checks or unchecks every file that can be applied.
func (p *planView) selectAll(on bool) {
	if p.tab == nil {
		return
	}
	if on {
		p.tab.SelectAll()
	} else {
		p.tab.SelectNone()
	}
	p.fillList()
}

// fillList renders the rows: a checkbox, the file, what would happen, the
// rule, and the outcome once applied.
func (p *planView) fillList() {
	clearList(p.list)
	if p.tab == nil {
		return
	}
	for i, r := range p.tab.Rows {
		p.list.Append(p.rowWidget(i, r))
	}
	p.apply.SetLabel(fmt.Sprintf("Apply %d selected", p.tab.SelectedCount()))
	p.apply.SetSensitive(!p.tab.Applied && p.tab.SelectedCount() > 0)
}

// rowWidget is one line of the list.
func (p *planView) rowWidget(i int, r model.Row) *gtk.ListBoxRow {
	box := gtk.NewBox(gtk.OrientationHorizontal, 8)
	box.SetMarginStart(6)
	box.SetMarginEnd(6)
	box.SetMarginTop(2)
	box.SetMarginBottom(2)

	check := gtk.NewCheckButton()
	check.SetActive(r.Selected)
	check.SetSensitive(r.Actable && (p.tab == nil || !p.tab.Applied))
	check.ConnectToggled(func() {
		if p.tab != nil && p.tab.Rows[i].Selected != check.Active() {
			p.tab.Toggle(i)
			p.apply.SetLabel(fmt.Sprintf("Apply %d selected", p.tab.SelectedCount()))
			p.apply.SetSensitive(!p.tab.Applied && p.tab.SelectedCount() > 0)
		}
	})
	box.Append(check)

	box.Append(column(escape(r.Rel), 24, true))
	box.Append(column(escape(rowLabel(r, p.dirRoot())), 30, false))
	box.Append(column(escape(r.Rule), 12, false))
	if r.Outcome != "" {
		box.Append(column(escape(r.Outcome), 12, false))
	}
	row := gtk.NewListBoxRow()
	row.SetChild(box)
	return row
}

// dirRoot is the directory the list belongs to, for shortening destinations.
func (p *planView) dirRoot() string {
	if p.tab != nil {
		return p.tab.Dir.Root
	}
	return ""
}

// column is one cell of a row: left-aligned, and ellipsized to chars so
// that a long name or warning cannot widen the window past the screen. The
// whole text is in the details pane beside the list.
func column(text string, chars int, expand bool) *gtk.Label {
	l := gtk.NewLabel(text)
	l.SetXAlign(0)
	l.SetEllipsize(pango.EllipsizeEnd)
	l.SetWidthChars(chars)
	l.SetMaxWidthChars(chars)
	l.SetHExpand(expand)
	l.SetTooltipText(text)
	return l
}

// showDetails writes the selected file's steps and warnings into the pane.
func (p *planView) showDetails(i int) {
	if p.tab == nil || i < 0 || i >= len(p.tab.Rows) {
		return
	}
	r := p.tab.Rows[i]
	var b strings.Builder
	b.WriteString(escape(r.Rel) + "\n\n")
	for _, s := range r.Steps {
		switch {
		case s.Skip != "":
			fmt.Fprintf(&b, "%s skipped: %s\n", s.Kind, escape(s.Skip))
		case s.Kind == plan.Trash || s.Kind == plan.DeletePermanent:
			fmt.Fprintf(&b, "%s\n", s.Kind)
		default:
			fmt.Fprintf(&b, "%s -> %s\n", s.Kind, escape(shorten(s.Dst, p.dirRoot())))
		}
		if s.Rule != "" {
			fmt.Fprintf(&b, "  rule %s\n", escape(s.Rule))
		}
		if s.Reason != "" {
			fmt.Fprintf(&b, "  because %s\n", escape(s.Reason))
		}
	}
	for _, warn := range r.Warnings {
		b.WriteString("\n" + escape(warn) + "\n")
	}
	if r.Outcome != "" {
		b.WriteString("\n" + escape(r.Outcome) + "\n")
	}
	p.details.Buffer().SetText(b.String())
}