fork/gdu

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

cosmolifeat: move items to XDG trash with D key (#12) (#608)9ca5c60

subvolume
14.2 KiB648 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.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			previousHeaderText := ui.header.GetText(false)
377
378			// show feedback to user
379			ui.header.SetText(" Shell spawning is disabled!")
380
381			go func() {
382				time.Sleep(2 * time.Second)
383				ui.app.QueueUpdateDraw(func() {
384					ui.header.Clear()
385					ui.header.SetText(previousHeaderText)
386				})
387			}()
388
389			return nil
390		}
391		ui.spawnShell()
392		return nil
393	}
394	return key
395}
396
397func (ui *UI) handleLeftRight(key *tcell.EventKey) *tcell.EventKey {
398	if key.Rune() == 'h' || key.Key() == tcell.KeyLeft {
399		ui.handleLeft()
400		return nil
401	}
402
403	if key.Rune() == 'l' || key.Key() == tcell.KeyRight {
404		ui.handleRight()
405		return nil
406	}
407	return key
408}
409
410func (ui *UI) handleFiltering(key *tcell.EventKey) *tcell.EventKey {
411	if key.Key() != tcell.KeyTab {
412		return key
413	}
414	if ui.filteringInput != nil {
415		ui.filtering = true
416		ui.app.SetFocus(ui.filteringInput)
417		return nil
418	}
419	if ui.typeFilteringInput != nil {
420		ui.typeFiltering = true
421		ui.app.SetFocus(ui.typeFilteringInput)
422		return nil
423	}
424	return key
425}
426
427// nolint: funlen // Why: there's a lot of options to handle
428func (ui *UI) handleMainActions(key *tcell.EventKey) *tcell.EventKey {
429	switch key.Rune() {
430	case 'd':
431		if ui.isInArchive() {
432			ui.showErr("Deletion is not supported in archives", nil)
433			return nil
434		}
435		ui.handleDelete(ActionDelete)
436	case 'e':
437		if ui.isInArchive() {
438			ui.showErr("Deletion is not supported in archives", nil)
439			return nil
440		}
441		ui.handleDelete(ActionEmpty)
442	case 'D':
443		if ui.isInArchive() {
444			ui.showErr("Deletion is not supported in archives", nil)
445			return nil
446		}
447		ui.handleDelete(ActionMoveToTrash)
448	case 'v':
449		if ui.isInArchive() {
450			ui.showErr("Viewing content is not supported in archives", nil)
451			return nil
452		}
453		if ui.noViewFile {
454			previousHeaderText := ui.header.GetText(false)
455
456			ui.header.SetText(" Viewing files is disabled!")
457
458			go func() {
459				time.Sleep(2 * time.Second)
460				ui.app.QueueUpdateDraw(func() {
461					ui.header.Clear()
462					ui.header.SetText(previousHeaderText)
463				})
464			}()
465
466			return nil
467		}
468		ui.showFile()
469	case 'o':
470		if ui.noSpawnShell {
471			previousHeaderText := ui.header.GetText(false)
472
473			// show feedback to user
474			ui.header.SetText(" Opening items is disabled!")
475
476			go func() {
477				time.Sleep(2 * time.Second)
478				ui.app.QueueUpdateDraw(func() {
479					ui.header.Clear()
480					ui.header.SetText(previousHeaderText)
481				})
482			}()
483			return nil
484		}
485		ui.openItem()
486	case 'i':
487		ui.showInfo()
488	case 'a', 'B', 'c', 'm':
489		ui.handleToggles(key)
490	case 'r':
491		if ui.currentDir != nil {
492			ui.rescanDir()
493		}
494	case 'E':
495		ui.confirmExport()
496		return nil
497	case 's', 'C', 'n', 'M':
498		ui.handleSorting(key)
499	case '/':
500		ui.showFilterInput()
501		return nil
502	case 'T':
503		ui.showTypeFilterInput()
504		return nil
505	case ' ':
506		ui.handleMark()
507	case 'p':
508		ui.printMarked()
509		return nil
510	case 'I':
511		ui.ignoreItem()
512	}
513	return key
514}
515
516func (ui *UI) handleToggles(key *tcell.EventKey) {
517	switch key.Rune() {
518	case 'a':
519		ui.ShowApparentSize = !ui.ShowApparentSize
520	case 'B':
521		ui.ShowRelativeSize = !ui.ShowRelativeSize
522	case 'c':
523		ui.showItemCount = !ui.showItemCount
524	case 'm':
525		ui.showMtime = !ui.showMtime
526	}
527	if ui.currentDir != nil {
528		row, column := ui.table.GetSelection()
529		ui.showDir()
530		ui.table.Select(row, column)
531	}
532}
533
534func (ui *UI) handleSorting(key *tcell.EventKey) {
535	switch key.Rune() {
536	case 's':
537		ui.setSorting("size")
538	case 'C':
539		ui.setSorting("itemCount")
540	case 'n':
541		ui.setSorting("name")
542	case 'M':
543		ui.setSorting("mtime")
544	}
545}
546
547func (ui *UI) handleLeft() {
548	if ui.currentDirPath == ui.topDirPath {
549		if ui.devices != nil {
550			ui.currentDir = nil
551			err := ui.ListDevices(ui.getter)
552			if err != nil {
553				ui.showErr("Error listing devices", err)
554			}
555		} else if ui.browseParentDirs {
556			ui.analyzeParentOfTopDir()
557		}
558		return
559	}
560	if ui.currentDir != nil {
561		ui.fileItemSelected(0, 0)
562	}
563}
564
565func (ui *UI) analyzeParentOfTopDir() {
566	if ui.currentDir == nil || ui.isInArchive() {
567		return
568	}
569
570	currentPath := ui.currentDir.GetPath()
571	parentPath := filepath.Dir(currentPath)
572	if parentPath == currentPath {
573		return
574	}
575
576	ui.Analyzer.ResetProgress()
577	ui.linkedItems = make(fs.HardLinkedItems)
578
579	if err := analyzeParentPath(ui, parentPath, nil); err != nil {
580		ui.showErr("Error analyzing parent directory", err)
581	}
582}
583
584func (ui *UI) handleRight() {
585	row, column := ui.table.GetSelection()
586	if ui.currentDirPath != ui.topDirPath && row == 0 { // do not select /..
587		return
588	}
589
590	if ui.currentDir != nil {
591		ui.fileItemSelected(row, column)
592	} else {
593		ui.deviceItemSelected(row, column)
594	}
595}
596
597func (ui *UI) handleDelete(action DeleteAction) {
598	if ui.currentDir == nil {
599		return
600	}
601	// do not allow deleting parent dir
602	row, column := ui.table.GetSelection()
603	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
604	if !ok || selectedFile == ui.currentDir.GetParent() {
605		return
606	}
607
608	if ui.askBeforeDelete {
609		ui.confirmDeletion(action)
610	} else {
611		ui.delete(action)
612	}
613}
614
615func (ui *UI) handleMark() {
616	if ui.currentDir == nil {
617		return
618	}
619	// do not allow deleting parent dir
620	row, column := ui.table.GetSelection()
621	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
622	if !ok || selectedFile == ui.currentDir.GetParent() {
623		return
624	}
625
626	ui.fileItemMarked(row)
627}
628
629func (ui *UI) ignoreItem() {
630	if ui.currentDir == nil {
631		return
632	}
633	// do not allow ignoring parent dir
634	row, column := ui.table.GetSelection()
635	selectedFile, ok := ui.table.GetCell(row, column).GetReference().(fs.Item)
636	if !ok || selectedFile == ui.currentDir.GetParent() {
637		return
638	}
639
640	if _, ok := ui.ignoredRows[row]; ok {
641		delete(ui.ignoredRows, row)
642	} else {
643		ui.ignoredRows[row] = struct{}{}
644	}
645	ui.showDir()
646	// select next row if possible
647	ui.table.Select(min(row+1, ui.table.GetRowCount()-1), 0)
648}