fork/gdu

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

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

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