fork/gdu

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

Julia RyanDan's preferred ignore behavior04c9958

ignore
14.0 KiB641 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", "don't ask me again"}).
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.pages.RemovePage("progress")
286	ui.showDir()
287	ui.table.Select(0, 0)
288	ui.app.SetFocus(ui.table)
289}
290
291// exitPreview leaves the mid-scan preview and restores the scanning progress modal.
292func (ui *UI) exitPreview() {
293	ui.previewing = false
294	ui.currentDir = ui.previewSavedDir
295	ui.previewSavedDir = nil
296	if ui.progressFlex != nil {
297		ui.pages.AddPage("progress", ui.progressFlex, true, true)
298	}
299	ui.app.SetFocus(ui.table)
300}
301
302// handlePreviewKeys handles input while a mid-scan preview is shown. Navigation
303// and sorting are allowed; destructive or external actions are intentionally
304// ignored because the tree is still being built.
305func (ui *UI) handlePreviewKeys(key *tcell.EventKey) *tcell.EventKey {
306	if ui.pages.HasPage("help") {
307		return key
308	}
309
310	if key.Key() == tcell.KeyTab || key.Key() == tcell.KeyEsc {
311		ui.exitPreview()
312		return nil
313	}
314	if key.Key() == tcell.KeyLeft {
315		ui.previewLeft()
316		return nil
317	}
318	if key.Key() == tcell.KeyRight {
319		ui.handleRight()
320		return nil
321	}
322
323	switch key.Rune() {
324	case '?':
325		ui.showHelp()
326		return nil
327	case 'h':
328		ui.previewLeft()
329		return nil
330	case 'l':
331		ui.handleRight()
332		return nil
333	case 's', 'C', 'n', 'M':
334		ui.handleSorting(key)
335		return nil
336	case 'a', 'B', 'c', 'm':
337		ui.handleToggles(key)
338		return nil
339	}
340
341	// up/down/pgup/pgdn and Enter are handled by the table itself
342	return key
343}
344
345// previewLeft navigates to the parent dir within the preview, or leaves the
346// preview when already at its root.
347func (ui *UI) previewLeft() {
348	if ui.currentDir == nil || ui.currentDir.GetParent() == nil {
349		ui.exitPreview()
350		return
351	}
352	ui.fileItemSelected(0, 0)
353}
354
355func (ui *UI) handleHelp(key *tcell.EventKey) *tcell.EventKey {
356	if key.Rune() == '?' {
357		if ui.pages.HasPage("help") {
358			ui.pages.RemovePage("help")
359			ui.app.SetFocus(ui.table)
360			return nil
361		}
362		ui.showHelp()
363		return nil
364	}
365	return key
366}
367
368func (ui *UI) handleShell(key *tcell.EventKey) *tcell.EventKey {
369	if key.Rune() == 'b' {
370		if ui.isInArchive() {
371			ui.showErr("Spawning shell is not supported in archives", nil)
372			return nil
373		}
374		if ui.noSpawnShell {
375			previousHeaderText := ui.header.GetText(false)
376
377			// show feedback to user
378			ui.header.SetText(" Shell spawning is disabled!")
379
380			go func() {
381				time.Sleep(2 * time.Second)
382				ui.app.QueueUpdateDraw(func() {
383					ui.header.Clear()
384					ui.header.SetText(previousHeaderText)
385				})
386			}()
387
388			return nil
389		}
390		ui.spawnShell()
391		return nil
392	}
393	return key
394}
395
396func (ui *UI) handleLeftRight(key *tcell.EventKey) *tcell.EventKey {
397	if key.Rune() == 'h' || key.Key() == tcell.KeyLeft {
398		ui.handleLeft()
399		return nil
400	}
401
402	if key.Rune() == 'l' || key.Key() == tcell.KeyRight {
403		ui.handleRight()
404		return nil
405	}
406	return key
407}
408
409func (ui *UI) handleFiltering(key *tcell.EventKey) *tcell.EventKey {
410	if key.Key() != tcell.KeyTab {
411		return key
412	}
413	if ui.filteringInput != nil {
414		ui.filtering = true
415		ui.app.SetFocus(ui.filteringInput)
416		return nil
417	}
418	if ui.typeFilteringInput != nil {
419		ui.typeFiltering = true
420		ui.app.SetFocus(ui.typeFilteringInput)
421		return nil
422	}
423	return key
424}
425
426// nolint: funlen // Why: there's a lot of options to handle
427func (ui *UI) handleMainActions(key *tcell.EventKey) *tcell.EventKey {
428	switch key.Rune() {
429	case 'd':
430		if ui.isInArchive() {
431			ui.showErr("Deletion is not supported in archives", nil)
432			return nil
433		}
434		ui.handleDelete(ActionDelete)
435	case 'e':
436		if ui.isInArchive() {
437			ui.showErr("Deletion is not supported in archives", nil)
438			return nil
439		}
440		ui.handleDelete(ActionEmpty)
441	case 'D':
442		if ui.isInArchive() {
443			ui.showErr("Deletion is not supported in archives", nil)
444			return nil
445		}
446		ui.handleDelete(ActionMoveToTrash)
447	case 'v':
448		if ui.isInArchive() {
449			ui.showErr("Viewing content is not supported in archives", nil)
450			return nil
451		}
452		if ui.noViewFile {
453			previousHeaderText := ui.header.GetText(false)
454
455			ui.header.SetText(" Viewing files is disabled!")
456
457			go func() {
458				time.Sleep(2 * time.Second)
459				ui.app.QueueUpdateDraw(func() {
460					ui.header.Clear()
461					ui.header.SetText(previousHeaderText)
462				})
463			}()
464
465			return nil
466		}
467		ui.showFile()
468	case 'o':
469		if ui.noSpawnShell {
470			previousHeaderText := ui.header.GetText(false)
471
472			// show feedback to user
473			ui.header.SetText(" Opening items is disabled!")
474
475			go func() {
476				time.Sleep(2 * time.Second)
477				ui.app.QueueUpdateDraw(func() {
478					ui.header.Clear()
479					ui.header.SetText(previousHeaderText)
480				})
481			}()
482			return nil
483		}
484		ui.openItem()
485	case 'i':
486		ui.showInfo()
487	case 'a', 'B', 'c', 'm':
488		ui.handleToggles(key)
489	case 'r':
490		if ui.currentDir != nil {
491			ui.rescanDir()
492		}
493	case 'E':
494		ui.confirmExport()
495		return nil
496	case 's', 'C', 'n', 'M':
497		ui.handleSorting(key)
498	case '/':
499		ui.showFilterInput()
500		return nil
501	case 'T':
502		ui.showTypeFilterInput()
503		return nil
504	case ' ':
505		ui.handleMark()
506	case 'p':
507		ui.printMarked()
508		return nil
509	case 'I':
510		ui.ignoreItem()
511	}
512	return key
513}
514
515func (ui *UI) handleToggles(key *tcell.EventKey) {
516	switch key.Rune() {
517	case 'a':
518		ui.ShowApparentSize = !ui.ShowApparentSize
519	case 'B':
520		ui.ShowRelativeSize = !ui.ShowRelativeSize
521	case 'c':
522		ui.showItemCount = !ui.showItemCount
523	case 'm':
524		ui.showMtime = !ui.showMtime
525	}
526	if ui.currentDir != nil {
527		row, column := ui.table.GetSelection()
528		ui.showDir()
529		ui.table.Select(row, column)
530	}
531}
532
533func (ui *UI) handleSorting(key *tcell.EventKey) {
534	switch key.Rune() {
535	case 's':
536		ui.setSorting("size")
537	case 'C':
538		ui.setSorting("itemCount")
539	case 'n':
540		ui.setSorting("name")
541	case 'M':
542		ui.setSorting("mtime")
543	}
544}
545
546func (ui *UI) handleLeft() {
547	if ui.currentDirPath == ui.topDirPath {
548		if ui.devices != nil {
549			ui.currentDir = nil
550			err := ui.ListDevices(ui.getter)
551			if err != nil {
552				ui.showErr("Error listing devices", err)
553			}
554		} else if ui.browseParentDirs {
555			ui.analyzeParentOfTopDir()
556		}
557		return
558	}
559	if ui.currentDir != nil {
560		ui.fileItemSelected(0, 0)
561	}
562}
563
564func (ui *UI) analyzeParentOfTopDir() {
565	if ui.currentDir == nil || ui.isInArchive() {
566		return
567	}
568
569	currentPath := ui.currentDir.GetPath()
570	parentPath := filepath.Dir(currentPath)
571	if parentPath == currentPath {
572		return
573	}
574
575	ui.Analyzer.ResetProgress()
576	ui.linkedItems = make(fs.HardLinkedItems)
577
578	if err := analyzeParentPath(ui, parentPath, nil); err != nil {
579		ui.showErr("Error analyzing parent directory", err)
580	}
581}
582
583func (ui *UI) handleRight() {
584	row, column := ui.table.GetSelection()
585	if ui.currentDirPath != ui.topDirPath && row == 0 { // do not select /..
586		return
587	}
588
589	if ui.currentDir != nil {
590		ui.fileItemSelected(row, column)
591	} else {
592		ui.deviceItemSelected(row, column)
593	}
594}
595
596func (ui *UI) handleDelete(action DeleteAction) {
597	if ui.currentDir == nil {
598		return
599	}
600	// do not allow deleting parent dir
601	row, column := ui.table.GetSelection()
602	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
603	if !ok || selectedFile == ui.currentDir.GetParent() {
604		return
605	}
606
607	if ui.askBeforeDelete {
608		ui.confirmDeletion(action)
609	} else {
610		ui.delete(action)
611	}
612}
613
614func (ui *UI) handleMark() {
615	if ui.currentDir == nil {
616		return
617	}
618	// do not allow deleting parent dir
619	row, column := ui.table.GetSelection()
620	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
621	if !ok || selectedFile == ui.currentDir.GetParent() {
622		return
623	}
624
625	ui.fileItemMarked(row)
626}
627
628func (ui *UI) ignoreItem() {
629	if ui.currentDir == nil {
630		return
631	}
632	// do not allow ignoring parent dir
633	row, column := ui.table.GetSelection()
634	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
635	if !ok || selectedFile == ui.currentDir.GetParent() {
636		return
637	}
638
639	ui.AddIgnoreDirPath(selectedFile.GetPath())
640	ui.rescanDir()
641}