fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: allow scanning multiple directories (#653)34f3996

master
13.6 KiB618 linesraw
1package tui
2
3import (
4	"fmt"
5	"path/filepath"
6	"time"
7
8	"github.com/dundee/gdu/v5/pkg/fs"
9	"github.com/gdamore/tcell/v2"
10	"github.com/rivo/tview"
11)
12
13var analyzeParentPath = func(ui *UI, path string, parentDir fs.Item) error {
14	return ui.AnalyzePath(path, parentDir)
15}
16
17func (ui *UI) keyPressed(key *tcell.EventKey) *tcell.EventKey {
18	if key.Key() == tcell.KeyExit {
19		ui.handleSignalEvent(key)
20		return nil
21	}
22
23	if ui.handleCtrlZ(key) == nil {
24		return nil
25	}
26
27	if ui.pages.HasPage("file") || ui.pages.HasPage("export") {
28		return key // send event to primitive
29	}
30	if ui.filtering || ui.typeFiltering {
31		return key
32	}
33
34	key = ui.handleClosingModals(key)
35	if key == nil {
36		return nil
37	}
38	key = ui.handleInfoPageEvents(key)
39	if key == nil {
40		return nil
41	}
42	key = ui.handleQuit(key)
43	if key == nil {
44		return nil
45	}
46
47	if ui.pages.HasPage("confirm") {
48		return ui.handleConfirmation(key)
49	}
50
51	if key.Key() == tcell.KeyCtrlC && ui.cancelScan() {
52		return nil
53	}
54
55	if ui.previewing {
56		return ui.handlePreviewKeys(key)
57	}
58
59	if ui.pages.HasPage("progress") ||
60		ui.pages.HasPage("deleting") ||
61		ui.pages.HasPage("emptying") ||
62		ui.pages.HasPage("moving to trash") {
63		// allow peeking at the results found so far during a scan
64		if key.Key() == tcell.KeyTab && ui.pages.HasPage("progress") {
65			ui.enterPreview()
66			return nil
67		}
68		return key
69	}
70
71	key = ui.handleHelp(key)
72	if key == nil {
73		return nil
74	}
75
76	if ui.pages.HasPage("help") {
77		return key
78	}
79
80	key = ui.handleShell(key)
81	if key == nil {
82		return nil
83	}
84
85	key = ui.handleLeftRight(key)
86	if key == nil {
87		return nil
88	}
89
90	key = ui.handleFiltering(key)
91	if key == nil {
92		return nil
93	}
94
95	return ui.handleMainActions(key)
96}
97
98func (ui *UI) handleClosingModals(key *tcell.EventKey) *tcell.EventKey {
99	if key.Key() == tcell.KeyEsc || key.Rune() == 'q' {
100		if ui.pages.HasPage("help") {
101			ui.pages.RemovePage("help")
102			ui.app.SetFocus(ui.table)
103			return nil
104		}
105		if ui.pages.HasPage("info") {
106			ui.pages.RemovePage("info")
107			ui.app.SetFocus(ui.table)
108			return nil
109		}
110	}
111	return key
112}
113
114func (ui *UI) handleConfirmation(key *tcell.EventKey) *tcell.EventKey {
115	if key.Rune() == 'h' {
116		return tcell.NewEventKey(tcell.KeyLeft, 0, 0)
117	}
118	if key.Rune() == 'l' {
119		return tcell.NewEventKey(tcell.KeyRight, 0, 0)
120	}
121	return key
122}
123
124func (ui *UI) handleInfoPageEvents(key *tcell.EventKey) *tcell.EventKey {
125	if ui.pages.HasPage("info") {
126		switch key.Rune() {
127		case 'i':
128			ui.pages.RemovePage("info")
129			ui.app.SetFocus(ui.table)
130			return nil
131		case '?':
132			return nil
133		}
134
135		if key.Key() == tcell.KeyUp ||
136			key.Key() == tcell.KeyDown ||
137			key.Rune() == 'j' ||
138			key.Rune() == 'k' {
139			row, column := ui.table.GetSelection()
140			if (key.Key() == tcell.KeyUp || key.Rune() == 'k') && row > 0 {
141				row--
142			} else if (key.Key() == tcell.KeyDown || key.Rune() == 'j') &&
143				row+1 < ui.table.GetRowCount() {
144				row++
145			}
146			ui.table.Select(row, column)
147		}
148		ui.showInfo() // refresh file info after any change
149	}
150	return key
151}
152
153// handle ctrl+z job control
154func (ui *UI) handleCtrlZ(key *tcell.EventKey) *tcell.EventKey {
155	if key.Key() == tcell.KeyCtrlZ {
156		ui.app.Suspend(func() {
157			termApp := ui.app.(*tview.Application)
158			termApp.Lock()
159			defer termApp.Unlock()
160
161			err := stopProcess()
162			if err != nil {
163				ui.showErr("Error sending STOP signal", err)
164			}
165		})
166		return nil
167	}
168
169	return key
170}
171
172// confirmQuitMinScanDuration is the scan time above which quitting asks for
173// confirmation, so a long scan is not lost by an accidental key press.
174const confirmQuitMinScanDuration = 3 * time.Second
175
176func (ui *UI) handleQuit(key *tcell.EventKey) *tcell.EventKey {
177	clearTerminalProgress()
178
179	// do not re-trigger quitting while a confirmation dialog is open
180	if ui.pages.HasPage("confirm") {
181		return key
182	}
183
184	switch key.Rune() {
185	case 'Q':
186		ui.quit(true)
187		return nil
188	case 'q':
189		ui.quit(false)
190		return nil
191	}
192	return key
193}
194
195// quit asks for confirmation when there are scan results worth protecting,
196// otherwise it quits immediately.
197func (ui *UI) quit(printCurrentDirPath bool) {
198	if ui.shouldConfirmQuit() {
199		ui.confirmQuitDialog(printCurrentDirPath)
200		return
201	}
202	ui.doQuit(printCurrentDirPath)
203}
204
205// shouldConfirmQuit returns true when quitting would discard the work of a scan
206// that took a noticeable amount of time, whether it is still running or already
207// finished.
208func (ui *UI) shouldConfirmQuit() bool {
209	if !ui.confirmQuit {
210		return false
211	}
212	if ui.scanning {
213		return time.Since(ui.scanStart) >= confirmQuitMinScanDuration
214	}
215	return ui.currentDir != nil && ui.scanDuration >= confirmQuitMinScanDuration
216}
217
218func (ui *UI) doQuit(printCurrentDirPath bool) {
219	ui.app.Stop()
220	ui.printMarkedPaths()
221	if printCurrentDirPath {
222		fmt.Fprintf(ui.output, "%s\n", sanitizePathForDisplay(ui.currentDirPath))
223	}
224}
225
226func (ui *UI) confirmQuitDialog(printCurrentDirPath bool) {
227	var text string
228	if ui.scanning {
229		text = "A scan has been running for " +
230			time.Since(ui.scanStart).Round(time.Second).String() + ".\n\n" +
231			"Do you really want to quit gdu and abandon it?"
232	} else {
233		text = "Do you really want to quit gdu?\n\n" +
234			"This scan took " + ui.scanDuration.Round(time.Second).String() +
235			" and the results are not saved.\n" +
236			"Choose \"no\" and press E to export them first."
237	}
238	modal := tview.NewModal().
239		SetText(text).
240		AddButtons([]string{No, Yes, DontAskAgain}).
241		SetDoneFunc(func(buttonIndex int, buttonLabel string) {
242			ui.pages.RemovePage("confirm")
243			ui.app.SetFocus(ui.table)
244			switch buttonIndex {
245			case 2:
246				ui.confirmQuit = false
247				fallthrough
248			case 1:
249				ui.doQuit(printCurrentDirPath)
250			}
251		})
252
253	if !ui.UseColors {
254		modal.SetBackgroundColor(tcell.ColorGray)
255	} else {
256		modal.SetBackgroundColor(tcell.ColorBlack)
257	}
258	modal.SetBorderColor(tcell.ColorDefault)
259
260	ui.pages.AddPage("confirm", modal, true, true)
261}
262
263// enterPreview switches from the scanning progress modal to a read-only,
264// point-in-time view of the directory tree discovered so far. The view does not
265// auto-refresh: pressing Tab again returns to the progress modal, and entering
266// the preview once more takes a fresh snapshot.
267func (ui *UI) enterPreview() {
268	analyzer, ok := ui.Analyzer.(interface{ GetCurrentDir() fs.Item })
269	if !ok {
270		return
271	}
272	root := analyzer.GetCurrentDir()
273	if root == nil {
274		return // nothing scanned yet
275	}
276
277	// compute aggregated sizes on the partial tree using a throwaway hard-link
278	// map so the running scan's accounting is left untouched
279	root.UpdateStats(make(fs.HardLinkedItems))
280
281	ui.previewing = true
282	ui.previewSavedDir = ui.currentDir
283	ui.currentDir = root
284	ui.markedRows = make(map[int]struct{})
285	ui.ignoredRows = make(map[int]struct{})
286	ui.pages.RemovePage("progress")
287	ui.showDir()
288	ui.table.Select(0, 0)
289	ui.app.SetFocus(ui.table)
290}
291
292// exitPreview leaves the mid-scan preview and restores the scanning progress modal.
293func (ui *UI) exitPreview() {
294	ui.previewing = false
295	ui.currentDir = ui.previewSavedDir
296	ui.previewSavedDir = nil
297	if ui.progressFlex != nil {
298		ui.pages.AddPage("progress", ui.progressFlex, true, true)
299	}
300	ui.app.SetFocus(ui.table)
301}
302
303// handlePreviewKeys handles input while a mid-scan preview is shown. Navigation
304// and sorting are allowed; destructive or external actions are intentionally
305// ignored because the tree is still being built.
306func (ui *UI) handlePreviewKeys(key *tcell.EventKey) *tcell.EventKey {
307	if ui.pages.HasPage("help") {
308		return key
309	}
310
311	if key.Key() == tcell.KeyTab || key.Key() == tcell.KeyEsc {
312		ui.exitPreview()
313		return nil
314	}
315	if key.Key() == tcell.KeyLeft {
316		ui.previewLeft()
317		return nil
318	}
319	if key.Key() == tcell.KeyRight {
320		ui.handleRight()
321		return nil
322	}
323
324	switch key.Rune() {
325	case '?':
326		ui.showHelp()
327		return nil
328	case 'h':
329		ui.previewLeft()
330		return nil
331	case 'l':
332		ui.handleRight()
333		return nil
334	case 's', 'C', 'n', 'M':
335		ui.handleSorting(key)
336		return nil
337	case 'a', 'B', 'c', 'm':
338		ui.handleToggles(key)
339		return nil
340	}
341
342	// up/down/pgup/pgdn and Enter are handled by the table itself
343	return key
344}
345
346// previewLeft navigates to the parent dir within the preview, or leaves the
347// preview when already at its root.
348func (ui *UI) previewLeft() {
349	if ui.currentDir == nil || ui.currentDir.GetParent() == nil {
350		ui.exitPreview()
351		return
352	}
353	ui.fileItemSelected(0, 0)
354}
355
356func (ui *UI) handleHelp(key *tcell.EventKey) *tcell.EventKey {
357	if key.Rune() == '?' {
358		if ui.pages.HasPage("help") {
359			ui.pages.RemovePage("help")
360			ui.app.SetFocus(ui.table)
361			return nil
362		}
363		ui.showHelp()
364		return nil
365	}
366	return key
367}
368
369func (ui *UI) handleShell(key *tcell.EventKey) *tcell.EventKey {
370	if key.Rune() == 'b' {
371		if ui.isInArchive() {
372			ui.showErr("Spawning shell is not supported in archives", nil)
373			return nil
374		}
375		if ui.noSpawnShell {
376			ui.showMessage(" Shell spawning is disabled!")
377			return nil
378		}
379		ui.spawnShell()
380		return nil
381	}
382	return key
383}
384
385func (ui *UI) handleLeftRight(key *tcell.EventKey) *tcell.EventKey {
386	if key.Rune() == 'h' || key.Key() == tcell.KeyLeft {
387		ui.handleLeft()
388		return nil
389	}
390
391	if key.Rune() == 'l' || key.Key() == tcell.KeyRight {
392		ui.handleRight()
393		return nil
394	}
395	return key
396}
397
398func (ui *UI) handleFiltering(key *tcell.EventKey) *tcell.EventKey {
399	if key.Key() != tcell.KeyTab {
400		return key
401	}
402	if ui.filteringInput != nil {
403		ui.filtering = true
404		ui.app.SetFocus(ui.filteringInput)
405		return nil
406	}
407	if ui.typeFilteringInput != nil {
408		ui.typeFiltering = true
409		ui.app.SetFocus(ui.typeFilteringInput)
410		return nil
411	}
412	return key
413}
414
415// nolint: funlen // Why: there's a lot of options to handle
416func (ui *UI) handleMainActions(key *tcell.EventKey) *tcell.EventKey {
417	switch key.Rune() {
418	case 'd':
419		if ui.isInArchive() {
420			ui.showErr("Deletion is not supported in archives", nil)
421			return nil
422		}
423		ui.handleDelete(ActionDelete)
424	case 'e':
425		if ui.isInArchive() {
426			ui.showErr("Deletion is not supported in archives", nil)
427			return nil
428		}
429		ui.handleDelete(ActionEmpty)
430	case 'D':
431		if ui.isInArchive() {
432			ui.showErr("Deletion is not supported in archives", nil)
433			return nil
434		}
435		ui.handleDelete(ActionMoveToTrash)
436	case 'v':
437		if ui.isInArchive() {
438			ui.showErr("Viewing content is not supported in archives", nil)
439			return nil
440		}
441		if ui.noViewFile {
442			ui.showMessage(" Viewing files is disabled!")
443			return nil
444		}
445		ui.showFile()
446	case 'o':
447		if ui.noSpawnShell {
448			ui.showMessage(" Opening items is disabled!")
449			return nil
450		}
451		ui.openItem()
452	case 'i':
453		ui.showInfo()
454	case 'a', 'B', 'c', 'm':
455		ui.handleToggles(key)
456	case 'r':
457		if ui.currentDir != nil {
458			ui.rescanDir()
459		}
460	case 'E':
461		ui.confirmExport()
462		return nil
463	case 's', 'C', 'n', 'M':
464		ui.handleSorting(key)
465	case '/':
466		ui.showFilterInput()
467		return nil
468	case 'T':
469		ui.showTypeFilterInput()
470		return nil
471	case ' ':
472		ui.handleMark()
473	case 'p':
474		ui.printMarked()
475		return nil
476	case 'y':
477		ui.copySelectedPath()
478		return nil
479	case 'I':
480		ui.ignoreItem()
481	}
482	return key
483}
484
485func (ui *UI) handleToggles(key *tcell.EventKey) {
486	switch key.Rune() {
487	case 'a':
488		ui.ShowApparentSize = !ui.ShowApparentSize
489	case 'B':
490		ui.ShowRelativeSize = !ui.ShowRelativeSize
491	case 'c':
492		ui.showItemCount = !ui.showItemCount
493	case 'm':
494		ui.showMtime = !ui.showMtime
495	}
496	if ui.currentDir != nil {
497		row, column := ui.table.GetSelection()
498		ui.showDir()
499		ui.table.Select(row, column)
500	}
501}
502
503func (ui *UI) handleSorting(key *tcell.EventKey) {
504	switch key.Rune() {
505	case 's':
506		ui.setSorting("size")
507	case 'C':
508		ui.setSorting("itemCount")
509	case 'n':
510		ui.setSorting("name")
511	case 'M':
512		ui.setSorting("mtime")
513	}
514}
515
516func (ui *UI) handleLeft() {
517	if ui.currentDirPath == ui.topDirPath {
518		if ui.devices != nil {
519			ui.currentDir = nil
520			err := ui.ListDevices(ui.getter)
521			if err != nil {
522				ui.showErr("Error listing devices", err)
523			}
524		} else if ui.browseParentDirs {
525			ui.analyzeParentOfTopDir()
526		}
527		return
528	}
529	if ui.currentDir != nil {
530		ui.fileItemSelected(0, 0)
531	}
532}
533
534func (ui *UI) analyzeParentOfTopDir() {
535	// the virtual root has no parent on disk to browse up into
536	if ui.currentDir == nil || ui.isInArchive() || ui.atVirtualRoot() {
537		return
538	}
539
540	currentPath := ui.currentDir.GetPath()
541	parentPath := filepath.Dir(currentPath)
542	if parentPath == currentPath {
543		return
544	}
545
546	ui.Analyzer.ResetProgress()
547	ui.linkedItems = make(fs.HardLinkedItems)
548
549	if err := analyzeParentPath(ui, parentPath, nil); err != nil {
550		ui.showErr("Error analyzing parent directory", err)
551	}
552}
553
554func (ui *UI) handleRight() {
555	row, column := ui.table.GetSelection()
556	if ui.currentDirPath != ui.topDirPath && row == 0 { // do not select /..
557		return
558	}
559
560	if ui.currentDir != nil {
561		ui.fileItemSelected(row, column)
562	} else {
563		ui.deviceItemSelected(row, column)
564	}
565}
566
567func (ui *UI) handleDelete(action DeleteAction) {
568	if ui.currentDir == nil {
569		return
570	}
571	// do not allow deleting parent dir
572	row, column := ui.table.GetSelection()
573	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
574	if !ok || selectedFile == ui.currentDir.GetParent() {
575		return
576	}
577
578	if ui.askBeforeDelete {
579		ui.confirmDeletion(action)
580	} else {
581		ui.delete(action)
582	}
583}
584
585func (ui *UI) handleMark() {
586	if ui.currentDir == nil {
587		return
588	}
589	// do not allow deleting parent dir
590	row, column := ui.table.GetSelection()
591	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
592	if !ok || selectedFile == ui.currentDir.GetParent() {
593		return
594	}
595
596	ui.fileItemMarked(row)
597}
598
599func (ui *UI) ignoreItem() {
600	if ui.currentDir == nil {
601		return
602	}
603	// do not allow ignoring parent dir
604	row, column := ui.table.GetSelection()
605	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
606	if !ok || selectedFile == ui.currentDir.GetParent() {
607		return
608	}
609
610	if _, ok := ui.ignoredRows[row]; ok {
611		delete(ui.ignoredRows, row)
612	} else {
613		ui.ignoredRows[row] = struct{}{}
614	}
615	ui.showDir()
616	// select next row if possible
617	ui.table.Select(min(row+1, ui.table.GetRowCount()-1), 0)
618}