fork/gdu

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

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

master
12.7 KiB452 linesraw
1package tui
2
3import (
4	"fmt"
5	"strconv"
6	"strings"
7	"time"
8
9	"github.com/gdamore/tcell/v2"
10	"github.com/rivo/tview"
11	log "github.com/sirupsen/logrus"
12
13	"github.com/dundee/gdu/v5/build"
14	"github.com/dundee/gdu/v5/pkg/analyze"
15	"github.com/dundee/gdu/v5/pkg/fs"
16)
17
18var (
19	helpDisabledSuffix = " (disabled)"
20
21	helpText = `     [::b]up/down, k/j    [white:black:-]Move cursor up/down
22  [::b]pgup/pgdn, g/G     [white:black:-]Move cursor top/bottom
23 [::b]enter, right, l     [white:black:-]Go to directory/device
24         [::b]left, h     [white:black:-]Go to parent directory
25
26               [::b]r     [white:black:-]Rescan current directory
27               [::b]E     [white:black:-]Export analysis data to file as JSON
28               [::b]/     [white:black:-]Search items by name
29               [::b]T     [white:black:-]Filter items by file type (extension)
30               [::b]a     [white:black:-]Toggle between showing disk usage and apparent size
31               [::b]B     [white:black:-]Toggle bar alignment to biggest file or directory
32               [::b]c     [white:black:-]Show/hide item count
33               [::b]m     [white:black:-]Show/hide latest mtime
34               [::b]b     [white:black:-]Spawn shell in current directory
35               [::b]q     [white:black:-]Quit gdu (asks to confirm after a long scan)
36               [::b]Q     [white:black:-]Quit gdu and print current directory path
37
38Item under cursor:
39               [::b]d     [white:black:-]Delete file or directory
40               [::b]e     [white:black:-]Empty file or directory
41               [::b]D     [white:black:-]Move file or directory to trash
42			   [::b]space [white:black:-]Mark file or directory for deletion
43			   [::b]p     [white:black:-]Print marked items paths to stdout after quitting
44			   [::b]y     [white:black:-]Copy path of file or directory to clipboard
45			   [::b]I     [white:black:-]Ignore file or directory
46               [::b]v     [white:black:-]Show content of file
47               [::b]o     [white:black:-]Open file or directory in external program
48               [::b]i     [white:black:-]Show info about item
49
50Sort by (twice toggles asc/desc):
51               [::b]n     [white:black:-]Sort by name (asc/desc)
52               [::b]s     [white:black:-]Sort by size (asc/desc)
53               [::b]C     [white:black:-]Sort by item count (asc/desc)
54               [::b]M     [white:black:-]Sort by mtime (asc/desc)`
55)
56
57// currentDirLabelText builds the breadcrumb label shown above the table,
58// annotated when a mid-scan preview is being displayed.
59func (ui *UI) currentDirLabelText() string {
60	label := "[::b] --- " +
61		tview.Escape(
62			strings.TrimPrefix(ui.currentDirPath, build.RootPathPrefix),
63		) +
64		" ---"
65	if ui.previewing {
66		label += "  [::b][yellow]scanning… (preview, Tab to resume)[-]"
67	}
68	return label
69}
70
71// followCurrentDirWithCwd moves the process working directory to the directory
72// being shown, when --change-cwd is enabled. The virtual top level dir has no
73// counterpart on disk, so it is skipped.
74func (ui *UI) followCurrentDirWithCwd() {
75	if ui.changeCwdFn == nil || ui.atVirtualRoot() {
76		return
77	}
78
79	if err := ui.changeCwdFn(ui.currentDirPath); err != nil {
80		log.Printf("error setting cwd: %s", err.Error())
81	}
82	log.Printf("changing cwd to %s", ui.currentDirPath)
83}
84
85// nolint: funlen // Why: complex function
86func (ui *UI) showDir() {
87	var (
88		totalUsage int64
89		totalSize  int64
90		maxima     rowMaxima
91		itemCount  int64
92	)
93
94	ui.currentDirPath = ui.currentDir.GetPath()
95
96	ui.followCurrentDirWithCwd()
97
98	ui.currentDirLabel.SetText(ui.currentDirLabelText()).SetDynamicColors(true)
99
100	ui.table.Clear()
101
102	rowIndex := 0
103	if ui.currentDirPath != ui.topDirPath {
104		prefix := strings.Repeat(" ", ui.columnsWidth())
105
106		cell := tview.NewTableCell(prefix + "[::b]/..")
107
108		// Use the collapsed parent logic to handle navigation back through collapsed paths
109		var collapsedParent fs.Item
110		if ui.collapsePath {
111			collapsedParent = findCollapsedParent(ui.currentDir)
112		} else {
113			collapsedParent = ui.currentDir.GetParent()
114		}
115		cell.SetReference(collapsedParent)
116		cell.SetStyle(tcell.Style{}.Foreground(tcell.ColorDefault))
117		ui.table.SetCell(0, 0, cell)
118		rowIndex++
119	}
120
121	sortBy, sortOrder := ui.getSortParams()
122
123	unlock := ui.currentDir.RLock()
124	defer unlock()
125
126	i := rowIndex
127	maxima = rowMaxima{}
128	for item := range ui.currentDir.GetFiles(sortBy, sortOrder) {
129		if _, ignored := ui.ignoredRows[i]; ignored {
130			i++
131			continue
132		}
133
134		count := fs.DisplayedItemCount(item)
135
136		if ui.ShowRelativeSize {
137			if item.GetUsage() > maxima.usage {
138				maxima.usage = item.GetUsage()
139			}
140			if item.GetSize() > maxima.size {
141				maxima.size = item.GetSize()
142			}
143			if count > maxima.count {
144				maxima.count = count
145			}
146		} else {
147			maxima.size += item.GetSize()
148			maxima.usage += item.GetUsage()
149			maxima.count += count
150		}
151		i++
152	}
153
154	for item := range ui.currentDir.GetFiles(sortBy, sortOrder) {
155		// filter on the label the row actually shows, which for a scanned root
156		// under the virtual top level dir is its absolute path
157		if ui.filterValue != "" && !strings.Contains(
158			strings.ToLower(analyze.ItemDisplayName(ui.currentDir, item)),
159			strings.ToLower(ui.filterValue),
160		) {
161			continue
162		}
163
164		if !ui.matchesTypeFilter(item.GetName(), item.IsDir()) {
165			continue
166		}
167
168		_, ignored := ui.ignoredRows[rowIndex]
169
170		if !ignored {
171			totalUsage += item.GetUsage()
172			totalSize += item.GetSize()
173			itemCount += item.GetItemCount()
174		}
175
176		_, marked := ui.markedRows[rowIndex]
177
178		var cell *tview.TableCell
179		var reference fs.Item
180
181		// Check if this directory can be collapsed
182		if item.IsDir() {
183			var collapsedPath *CollapsedPath
184			if ui.collapsePath {
185				collapsedPath = findCollapsiblePath(item)
186			}
187
188			if collapsedPath != nil {
189				// Format as collapsed path
190				cell = tview.NewTableCell(ui.formatCollapsedRow(collapsedPath, maxima, marked, ignored))
191				// Reference should point to the deepest directory for navigation
192				reference = collapsedPath.DeepestDir
193			} else {
194				// Regular directory formatting
195				cell = tview.NewTableCell(ui.formatFileRow(item, maxima, marked, ignored))
196				reference = item
197			}
198		} else {
199			// Regular file formatting
200			cell = tview.NewTableCell(ui.formatFileRow(item, maxima, marked, ignored))
201			reference = item
202		}
203
204		cell.SetReference(reference)
205
206		switch {
207		case ignored:
208			cell.SetStyle(tcell.Style{}.Foreground(tview.Styles.SecondaryTextColor))
209		case marked:
210			cell.SetStyle(tcell.Style{}.Foreground(ui.markedTextColor))
211			cell.SetBackgroundColor(ui.markedBackgroundColor)
212		default:
213			cell.SetStyle(tcell.Style{}.Foreground(tcell.ColorDefault))
214		}
215
216		ui.table.SetCell(rowIndex, 0, cell)
217		rowIndex++
218	}
219
220	var footerNumberColor, footerTextColor string
221	if ui.UseColors {
222		footerNumberColor = fmt.Sprintf(
223			"[%s:%s:b]",
224			ui.footerNumberColor,
225			ui.footerBackgroundColor,
226		)
227		footerTextColor = fmt.Sprintf(
228			"[%s:%s:-]",
229			ui.footerTextColor,
230			ui.footerBackgroundColor,
231		)
232	} else {
233		footerNumberColor = "[black:white:b]"
234		footerTextColor = blackOnWhite
235	}
236
237	selected := ""
238	if len(ui.markedRows) > 0 {
239		selected = " Selected items: " + footerNumberColor +
240			strconv.Itoa(len(ui.markedRows)) + footerTextColor
241	}
242
243	timeFilterText := ui.formatTimeFilterInfo()
244
245	typeFilterText := ui.formatTypeFilterInfo(footerNumberColor, footerTextColor)
246
247	ui.footerLabel.SetText(
248		selected + footerTextColor +
249			" Total disk usage: " +
250			footerNumberColor +
251			ui.formatSize(totalUsage, true, false) +
252			" Apparent size: " +
253			footerNumberColor +
254			ui.formatSize(totalSize, true, false) +
255			" Items: " + footerNumberColor + fmt.Sprintf("%d", itemCount) +
256			footerTextColor +
257			" Sorting by: " + ui.sortBy + " " + ui.sortOrder +
258			typeFilterText +
259			timeFilterText)
260
261	ui.table.Select(0, 0)
262	ui.table.ScrollToBeginning()
263
264	if !ui.filtering && !ui.typeFiltering {
265		ui.app.SetFocus(ui.table)
266	}
267}
268
269func (ui *UI) showDevices() {
270	var totalUsage int64
271
272	ui.table.Clear()
273	ui.table.SetCell(0, 0, tview.NewTableCell("Device name").SetSelectable(false))
274	ui.table.SetCell(0, 1, tview.NewTableCell("Size").SetSelectable(false))
275	ui.table.SetCell(0, 2, tview.NewTableCell("Used").SetSelectable(false))
276	ui.table.SetCell(0, 3, tview.NewTableCell("Used part").SetSelectable(false))
277	ui.table.SetCell(0, 4, tview.NewTableCell("Free").SetSelectable(false))
278	ui.table.SetCell(0, 5, tview.NewTableCell("Mount point").SetSelectable(false))
279
280	var textColor, sizeColor string
281	if ui.UseColors {
282		textColor = "[#3498db:-:b]"
283		sizeColor = "[#edb20a:-:b]"
284	} else {
285		textColor = "[white:-:b]"
286		sizeColor = "[white:-:b]"
287	}
288
289	ui.sortDevices()
290
291	for i, device := range ui.devices {
292		totalUsage += device.GetUsage()
293		ui.table.SetCell(i+1, 0, tview.NewTableCell(textColor+device.Name).SetReference(ui.devices[i]))
294		ui.table.SetCell(i+1, 1, tview.NewTableCell(ui.formatSize(device.Size, false, true)))
295		ui.table.SetCell(i+1, 2, tview.NewTableCell(sizeColor+ui.formatSize(device.Size-device.Free, false, true)))
296		ui.table.SetCell(i+1, 3, tview.NewTableCell(getDeviceUsagePart(device, ui.useOldSizeBar)))
297		ui.table.SetCell(i+1, 4, tview.NewTableCell(ui.formatSize(device.Free, false, true)))
298		ui.table.SetCell(i+1, 5, tview.NewTableCell(textColor+device.MountPoint).SetReference(ui.devices[i]))
299	}
300
301	var footerNumberColor, footerTextColor string
302	if ui.UseColors {
303		footerNumberColor = fmt.Sprintf(
304			"[%s:%s:b]",
305			ui.footerNumberColor,
306			ui.footerBackgroundColor,
307		)
308		footerTextColor = fmt.Sprintf(
309			"[%s:%s:-]",
310			ui.footerTextColor,
311			ui.footerBackgroundColor,
312		)
313	} else {
314		footerNumberColor = "[black:white:b]"
315		footerTextColor = blackOnWhite
316	}
317
318	ui.footerLabel.SetText(
319		" Total usage: " +
320			footerNumberColor +
321			ui.formatSize(totalUsage, true, false) +
322			footerTextColor +
323			" Sorting by: " + ui.sortBy + " " + ui.sortOrder)
324
325	ui.table.Select(1, 0)
326	ui.table.SetSelectedFunc(ui.deviceItemSelected)
327
328	if ui.topDirPath != "" {
329		for i, device := range ui.devices {
330			if device.MountPoint == ui.topDirPath {
331				ui.table.Select(i+1, 0)
332				break
333			}
334		}
335	}
336}
337
338func (ui *UI) showErr(msg string, err error) {
339	text := msg
340	if err != nil {
341		text += ": " + err.Error()
342	}
343
344	modal := tview.NewModal().
345		SetText(text).
346		AddButtons([]string{"ok"}).
347		SetDoneFunc(func(buttonIndex int, buttonLabel string) {
348			ui.pages.RemovePage("error")
349		})
350
351	if !ui.UseColors {
352		modal.SetBackgroundColor(tcell.ColorGray)
353	}
354
355	ui.pages.AddPage("error", modal, true, true)
356	ui.app.SetFocus(modal)
357}
358
359func (ui *UI) showErrFromGo(msg string, err error) {
360	ui.app.QueueUpdateDraw(func() {
361		ui.showErr(msg, err)
362	})
363}
364
365// messageTimeout is how long a transient status message stays in the header.
366const messageTimeout = 2 * time.Second
367
368// showMessage briefly replaces the header text with a status message and
369// restores the previous text afterwards.
370func (ui *UI) showMessage(message string) {
371	previousText := ui.header.GetText(false)
372	ui.header.SetText(message)
373
374	go func() {
375		time.Sleep(messageTimeout)
376		ui.app.QueueUpdateDraw(func() {
377			ui.header.Clear()
378			ui.header.SetText(previousText)
379		})
380	}()
381}
382
383func (ui *UI) showHelp() {
384	text := tview.NewTextView().SetDynamicColors(true)
385	text.SetBorder(true).SetBorderPadding(2, 2, 2, 2)
386	text.SetBorderColor(tcell.ColorDefault)
387	text.SetTitle(" gdu help ")
388	text.SetScrollable(true)
389
390	formattedHelpText := ui.formatHelpTextFor()
391	text.SetText(formattedHelpText)
392
393	maxHeight := strings.Count(formattedHelpText, "\n") + 7
394	_, height := ui.screen.Size()
395	if height > maxHeight {
396		height = maxHeight
397	}
398
399	flex := tview.NewFlex().
400		AddItem(nil, 0, 1, false).
401		AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
402			AddItem(nil, 0, 1, false).
403			AddItem(text, height, 1, false).
404			AddItem(nil, 0, 1, false), 80, 1, false).
405		AddItem(nil, 0, 1, false)
406
407	ui.help = flex
408	ui.pages.AddPage("help", flex, true, true)
409	ui.app.SetFocus(text)
410}
411
412func (ui *UI) formatHelpTextFor() string {
413	lines := strings.Split(helpText, "\n")
414
415	for i, line := range lines {
416		if ui.UseColors {
417			lines[i] = strings.ReplaceAll(
418				strings.ReplaceAll(line, defaultColorBold, "[red]"),
419				whiteOnBlack,
420				"[white]",
421			)
422		}
423
424		isFound := (strings.Contains(line, "Empty file or directory") ||
425			strings.Contains(line, "Delete file or directory") ||
426			strings.Contains(line, "Move file or directory to trash"))
427
428		if ui.noDelete && isFound {
429			lines[i] += helpDisabledSuffix
430		} else if ui.noDeleteWithFilter && isFound {
431			lines[i] += " (disabled/filter)"
432		}
433
434		if ui.noSpawnShell && (strings.Contains(line, "Spawn shell in current directory") ||
435			strings.Contains(line, "Open file or directory in external program")) {
436			lines[i] += helpDisabledSuffix
437		}
438
439		if ui.noViewFile && strings.Contains(line, "Show content of file") {
440			lines[i] += helpDisabledSuffix
441		}
442	}
443
444	return strings.Join(lines, "\n")
445}
446
447func (ui *UI) formatTypeFilterInfo(numberColor, textColor string) string {
448	if ui.typeFilterValue == "" {
449		return ""
450	}
451	return " Type filter: " + numberColor + ui.typeFilterValue + textColor
452}