fork/gdu

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

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

master
21.0 KiB767 linesraw
1package tui
2
3import (
4	"fmt"
5	"io"
6	"os"
7	"os/signal"
8	"runtime"
9	"strings"
10	"sync"
11	"sync/atomic"
12	"syscall"
13	"time"
14	"unicode"
15
16	log "github.com/sirupsen/logrus"
17
18	"github.com/dundee/gdu/v5/internal/common"
19	"github.com/dundee/gdu/v5/pkg/analyze"
20	"github.com/dundee/gdu/v5/pkg/device"
21	"github.com/dundee/gdu/v5/pkg/fs"
22	"github.com/dundee/gdu/v5/pkg/remove"
23	"github.com/dundee/gdu/v5/pkg/timefilter"
24	"github.com/gdamore/tcell/v2"
25	"github.com/rivo/tview"
26)
27
28// UI struct
29type UI struct {
30	app        common.TermApplication
31	screen     tcell.Screen
32	output     io.Writer
33	currentDir fs.Item
34	topDir     fs.Item
35	getter     device.DevicesInfoGetter
36	*common.UI
37	grid                    *tview.Grid
38	header                  *tview.TextView
39	footer                  *tview.Flex
40	footerLabel             *tview.TextView
41	currentDirLabel         *tview.TextView
42	pages                   *tview.Pages
43	progress                *tview.TextView
44	progressBar             *ProgressBar
45	status                  *tview.TextView
46	help                    *tview.Flex
47	table                   *tview.Table
48	filteringInput          *tview.InputField
49	typeFilteringInput      *tview.InputField
50	done                    chan struct{}
51	remover                 func(fs.Item, fs.Item) error
52	emptier                 func(fs.Item, fs.Item) error
53	trasher                 func(fs.Item, fs.Item) error
54	exec                    func(argv0 string, argv []string, envv []string) error
55	changeCwdFn             func(string) error
56	linkedItems             fs.HardLinkedItems
57	ignoredRows             map[int]struct{}
58	markedRows              map[int]struct{}
59	markedPaths             []string
60	deleteQueue             chan deleteQueueItem
61	resultRow               ResultRow
62	topDirPath              string
63	currentDirPath          string
64	filterValue             string
65	typeFilterValue         string
66	sortBy                  string
67	sortOrder               string
68	footerTextColor         string
69	footerBackgroundColor   string
70	footerNumberColor       string
71	headerTextColor         string
72	headerBackgroundColor   string
73	defaultSortBy           string
74	defaultSortOrder        string
75	exportName              string
76	devices                 []*device.Device
77	selectedTextColor       tcell.Color
78	selectedBackgroundColor tcell.Color
79	markedTextColor         tcell.Color
80	markedBackgroundColor   tcell.Color
81	currentItemNameMaxLen   int
82	activeWorkers           int
83	deleteWorkersCount      int
84	statusMut               sync.RWMutex
85	workersMut              sync.Mutex
86	askBeforeDelete         bool
87	showItemCount           bool
88	showSymlinkTarget       bool
89	showMtime               bool
90	filtering               bool
91	typeFiltering           bool
92	headerHidden            bool
93	useOldSizeBar           bool
94	showBarPercentage       bool
95	showItemCountBar        bool
96	noDelete                bool
97	noViewFile              bool
98	noSpawnShell            bool
99	deleteInBackground      bool
100	timeFilter              *timefilter.TimeFilter
101	timeFilterLoc           *time.Location
102	noDeleteWithFilter      bool
103	collapsePath            bool
104	browseParentDirs        bool
105	showDiskProgressBar     bool
106	currentDeviceSize       int64
107	confirmQuit             bool
108	scanning                bool
109	scanCancelled           bool
110	// scanCancelRequested mirrors scanCancelled for readers outside the UI
111	// goroutine. A multi-root scan resets the analyzer between roots, which
112	// clears the analyzer's own cancelled flag, so the request has to survive
113	// somewhere the scanning goroutine can safely read it.
114	scanCancelRequested atomic.Bool
115	scanStart           time.Time
116	scanDuration        time.Duration
117	previewing          bool
118	previewSavedDir     fs.Item
119	progressFlex        *tview.Flex
120}
121
122type deleteQueueItem struct {
123	item   fs.Item
124	action DeleteAction
125}
126
127// ResultRow is a struct for a row in the result table
128type ResultRow struct {
129	NumberColor    string
130	DirectoryColor string
131}
132
133// Option is optional function customizing the behaviour of UI
134type Option func(ui *UI)
135
136// CreateUI creates the whole UI app
137func CreateUI(
138	app common.TermApplication,
139	screen tcell.Screen,
140	output io.Writer,
141	useColors bool,
142	showApparentSize bool,
143	showRelativeSize bool,
144	useSIPrefix bool,
145	opts ...Option,
146) *UI {
147	ui := &UI{
148		UI: &common.UI{
149			UseColors:        useColors,
150			ShowApparentSize: showApparentSize,
151			ShowRelativeSize: showRelativeSize,
152			Analyzer:         analyze.CreateAnalyzer(),
153			UseSIPrefix:      useSIPrefix,
154		},
155		app:                     app,
156		screen:                  screen,
157		output:                  output,
158		askBeforeDelete:         true,
159		confirmQuit:             true,
160		showItemCount:           false,
161		remover:                 remove.ItemFromDir,
162		emptier:                 remove.EmptyFileFromDir,
163		trasher:                 remove.MoveItemToTrash,
164		exec:                    Execute,
165		linkedItems:             make(fs.HardLinkedItems, 10),
166		selectedTextColor:       tview.Styles.TitleColor,
167		selectedBackgroundColor: tview.Styles.MoreContrastBackgroundColor,
168		markedTextColor:         tview.Styles.PrimaryTextColor,
169		markedBackgroundColor:   tview.Styles.ContrastBackgroundColor,
170		currentItemNameMaxLen:   70,
171		defaultSortBy:           "size",
172		defaultSortOrder:        "desc",
173		ignoredRows:             make(map[int]struct{}),
174		markedRows:              make(map[int]struct{}),
175		exportName:              "export.json",
176		noDelete:                false,
177		noViewFile:              false,
178		noSpawnShell:            false,
179		deleteQueue:             make(chan deleteQueueItem, 1000),
180		deleteWorkersCount:      3 * runtime.GOMAXPROCS(0),
181	}
182	if !useSIPrefix {
183		ui.SetBlockSizeFromEnvironment()
184	}
185	for _, o := range opts {
186		o(ui)
187	}
188
189	ui.resetSorting()
190
191	app.SetBeforeDrawFunc(func(screen tcell.Screen) bool {
192		screen.Clear()
193		return false
194	})
195
196	ui.app.SetInputCapture(ui.keyPressed)
197	ui.app.SetMouseCapture(ui.onMouse)
198
199	ui.header = tview.NewTextView()
200	ui.header.SetText(" gdu ~ Use arrow keys to navigate, press ? for help ")
201	ui.header.SetTextColor(tcell.GetColor(ui.headerTextColor))
202	ui.header.SetBackgroundColor(tcell.GetColor(ui.headerBackgroundColor))
203
204	ui.currentDirLabel = tview.NewTextView()
205	ui.currentDirLabel.SetTextColor(tcell.ColorDefault)
206	ui.currentDirLabel.SetBackgroundColor(tcell.ColorDefault)
207
208	ui.table = tview.NewTable().SetSelectable(true, false)
209	ui.table.SetBackgroundColor(tcell.ColorDefault)
210	ui.table.SetSelectedFunc(ui.fileItemSelected)
211
212	if ui.UseColors {
213		ui.table.SetSelectedStyle(tcell.Style{}.
214			Foreground(ui.selectedTextColor).
215			Background(ui.selectedBackgroundColor).Bold(true))
216	} else {
217		ui.table.SetSelectedStyle(tcell.Style{}.
218			Foreground(tcell.ColorWhite).
219			Background(tcell.ColorGray).Bold(true))
220	}
221
222	ui.footerLabel = tview.NewTextView().SetDynamicColors(true)
223	ui.footerLabel.SetTextColor(tcell.GetColor(ui.footerTextColor))
224	ui.footerLabel.SetBackgroundColor(tcell.GetColor(ui.footerBackgroundColor))
225	ui.footerLabel.SetText(" No items to display. ")
226
227	ui.footer = tview.NewFlex()
228	ui.footer.AddItem(ui.footerLabel, 0, 1, false)
229
230	ui.createGrid()
231
232	ui.pages = tview.NewPages().
233		AddPage("background", ui.grid, true, true)
234	ui.pages.SetBackgroundColor(tcell.ColorDefault)
235
236	ui.app.SetRoot(ui.pages, true)
237
238	return ui
239}
240
241// createGrid creates the main grid layout
242func (ui *UI) createGrid() {
243	if ui.headerHidden {
244		ui.grid = tview.NewGrid().SetRows(1, 0, 1).SetColumns(0)
245		ui.grid.AddItem(ui.currentDirLabel, 0, 0, 1, 1, 0, 0, false).
246			AddItem(ui.table, 1, 0, 1, 1, 0, 0, true).
247			AddItem(ui.footer, 2, 0, 1, 1, 0, 0, false)
248	} else {
249		ui.grid = tview.NewGrid().SetRows(1, 1, 0, 1).SetColumns(0)
250		ui.grid.AddItem(ui.header, 0, 0, 1, 1, 0, 0, false).
251			AddItem(ui.currentDirLabel, 1, 0, 1, 1, 0, 0, false).
252			AddItem(ui.table, 2, 0, 1, 1, 0, 0, true).
253			AddItem(ui.footer, 3, 0, 1, 1, 0, 0, false)
254	}
255}
256
257// SetSelectedTextColor sets the color for the highlighted selected text
258func (ui *UI) SetSelectedTextColor(color tcell.Color) {
259	ui.selectedTextColor = color
260}
261
262// SetSelectedBackgroundColor sets the color for the highlighted selected text
263func (ui *UI) SetSelectedBackgroundColor(color tcell.Color) {
264	ui.selectedBackgroundColor = color
265}
266
267// SetMarkedTextColor sets the text color for marked items
268func (ui *UI) SetMarkedTextColor(color tcell.Color) {
269	ui.markedTextColor = color
270}
271
272// SetMarkedBackgroundColor sets the background color for marked items
273func (ui *UI) SetMarkedBackgroundColor(color tcell.Color) {
274	ui.markedBackgroundColor = color
275}
276
277// SetFooterTextColor sets the color for the footer text
278func (ui *UI) SetFooterTextColor(color string) {
279	ui.footerTextColor = color
280}
281
282// SetFooterBackgroundColor sets the color for the footer background
283func (ui *UI) SetFooterBackgroundColor(color string) {
284	ui.footerBackgroundColor = color
285}
286
287// SetFooterNumberColor sets the color for the footer number
288func (ui *UI) SetFooterNumberColor(color string) {
289	ui.footerNumberColor = color
290}
291
292// SetHeaderTextColor sets the color for the header text
293func (ui *UI) SetHeaderTextColor(color string) {
294	ui.headerTextColor = color
295}
296
297// SetHeaderBackgroundColor sets the color for the header background
298func (ui *UI) SetHeaderBackgroundColor(color string) {
299	ui.headerBackgroundColor = color
300}
301
302// SetHeaderHidden sets the flag to hide the header
303func (ui *UI) SetHeaderHidden() {
304	ui.headerHidden = true
305}
306
307// SetResultRowDirectoryColor sets the color for the result row directory
308func (ui *UI) SetResultRowDirectoryColor(color string) {
309	ui.resultRow.DirectoryColor = color
310}
311
312// SetResultRowNumberColor sets the color for the result row number
313func (ui *UI) SetResultRowNumberColor(color string) {
314	ui.resultRow.NumberColor = color
315}
316
317// SetCurrentItemNameMaxLen sets the maximum length of the path of the currently processed item
318// to be shown in the progress modal
319func (ui *UI) SetCurrentItemNameMaxLen(maxLen int) {
320	ui.currentItemNameMaxLen = maxLen
321}
322
323// UseOldSizeBar uses the old size bar (# chars) instead of the new one (unicode block elements)
324func (ui *UI) UseOldSizeBar() {
325	ui.useOldSizeBar = true
326}
327
328// SetShowBarPercentage shows the numeric usage percentage next to the size bar
329func (ui *UI) SetShowBarPercentage() {
330	ui.showBarPercentage = true
331}
332
333// SetShowItemCountBar shows a bar next to the item count column, drawn in
334// proportion to the item counts of the sibling items. It only takes effect
335// while the item count column itself is visible (the "c" key).
336func (ui *UI) SetShowItemCountBar() {
337	ui.showItemCountBar = true
338}
339
340// SetChangeCwdFn sets function that can be used to change current working dir
341// during dir browsing
342func (ui *UI) SetChangeCwdFn(fn func(string) error) {
343	ui.changeCwdFn = fn
344}
345
346// SetDeleteInParallel sets the flag to delete files in parallel
347func (ui *UI) SetDeleteInParallel() {
348	ui.remover = remove.ItemFromDirParallel
349}
350
351// SetTrashCommand replaces the built-in trash with an external command
352func (ui *UI) SetTrashCommand(command string) {
353	ui.trasher = remove.TrashCommand(command)
354}
355
356// StartUILoop starts tview application
357func (ui *UI) StartUILoop() error {
358	signals := make(chan os.Signal, 1)
359	signal.Notify(
360		signals,
361		syscall.SIGHUP,
362		syscall.SIGINT,
363		syscall.SIGQUIT,
364		syscall.SIGILL,
365		syscall.SIGTRAP,
366		syscall.SIGABRT,
367		syscall.SIGPIPE,
368		syscall.SIGTERM,
369	)
370	defer signal.Stop(signals)
371
372	return ui.runUILoop(signals)
373}
374
375func (ui *UI) runUILoop(signals <-chan os.Signal) error {
376	stopSignals := make(chan struct{})
377	signalsDone := make(chan struct{})
378	go func() {
379		defer close(signalsDone)
380		ui.handleSignals(signals, stopSignals)
381	}()
382
383	err := ui.app.Run()
384	close(stopSignals)
385	<-signalsDone
386	return err
387}
388
389func (ui *UI) handleSignals(signals <-chan os.Signal, stop <-chan struct{}) {
390	for {
391		select {
392		case <-stop:
393			return
394		case current, ok := <-signals:
395			if !ok {
396				return
397			}
398			log.Printf("Got signal: %s", current)
399			ui.postSignalEvent(signalEvent(current), stop)
400		}
401	}
402}
403
404func (ui *UI) postSignalEvent(event *tcell.EventKey, stop <-chan struct{}) {
405	if err := ui.screen.PostEvent(event); err == nil {
406		return
407	}
408
409	retry := time.NewTicker(time.Millisecond)
410	defer retry.Stop()
411	for {
412		select {
413		case <-stop:
414			return
415		case <-retry.C:
416			if err := ui.screen.PostEvent(event); err == nil {
417				return
418			}
419		}
420	}
421}
422
423func signalEvent(current os.Signal) *tcell.EventKey {
424	modifiers := tcell.ModNone
425	if current == syscall.SIGINT {
426		modifiers = tcell.ModCtrl
427	}
428	return tcell.NewEventKey(tcell.KeyExit, 0, modifiers)
429}
430
431func (ui *UI) handleSignalEvent(event *tcell.EventKey) {
432	if event.Modifiers() == tcell.ModCtrl && (ui.cancelScan() || ui.scanning) {
433		return
434	}
435	ui.printMarkedPaths()
436	ui.app.Stop()
437}
438
439func (ui *UI) cancelScan() bool {
440	if !ui.scanning || ui.scanCancelled {
441		return false
442	}
443
444	ui.Analyzer.Cancel()
445	ui.scanCancelled = true
446	ui.scanCancelRequested.Store(true)
447	ui.progress.SetTitle(" Stopping scan... ")
448	ui.progress.SetText("Stopping scan and keeping results...")
449	return true
450}
451
452// SetConfirmQuit sets whether gdu asks for confirmation before quitting
453// after a scan that took a noticeable amount of time
454func (ui *UI) SetConfirmQuit(value bool) {
455	ui.confirmQuit = value
456}
457
458// SetShowItemCount sets the flag to show number of items in directory
459func (ui *UI) SetShowItemCount() {
460	ui.showItemCount = true
461}
462
463// SetShowMTime sets the flag to show last modification time of items in directory
464func (ui *UI) SetShowMTime() {
465	ui.showMtime = true
466}
467
468// SetShowSymlinkTarget enables displaying the symlink target (name -> target)
469func (ui *UI) SetShowSymlinkTarget(value bool) {
470	ui.showSymlinkTarget = value
471}
472
473// SetNoDelete disables all write operations
474func (ui *UI) SetNoDelete() {
475	ui.noDelete = true
476}
477
478// SetNoSpawnShell disables shell spawning
479func (ui *UI) SetNoSpawnShell() {
480	ui.noSpawnShell = true
481}
482
483func (ui *UI) SetNoViewFile() {
484	ui.noViewFile = true
485}
486
487// SetNoDelete disables delete when time filters are active
488func (ui *UI) SetNoDeleteWithFilter() {
489	ui.noDeleteWithFilter = true
490}
491
492// SetBrowseParentDirs enables navigating above the launch directory
493func (ui *UI) SetBrowseParentDirs() {
494	ui.browseParentDirs = true
495}
496
497// SetCollapsePath sets the flag to collapse paths
498func (ui *UI) SetCollapsePath(value bool) {
499	ui.collapsePath = value
500}
501
502// SetShowDiskProgressBar sets whether to show a progress bar when scanning a whole disk
503func (ui *UI) SetShowDiskProgressBar(value bool) {
504	ui.showDiskProgressBar = value
505}
506
507// SetDeleteInBackground sets the flag to delete files in background
508func (ui *UI) SetDeleteInBackground() {
509	ui.deleteInBackground = true
510
511	for i := 0; i < ui.deleteWorkersCount; i++ {
512		go ui.deleteWorker()
513	}
514	go ui.updateStatusWorker()
515}
516
517func (ui *UI) resetSorting() {
518	ui.sortBy = ui.defaultSortBy
519	ui.sortOrder = ui.defaultSortOrder
520}
521
522// atVirtualRoot reports whether the view is at the synthetic dir grouping
523// several scanned roots. That dir has no path on disk, so operations that
524// resolve currentDirPath back to the filesystem must not run there.
525func (ui *UI) atVirtualRoot() bool {
526	return analyze.IsVirtualRootDir(ui.currentDir)
527}
528
529func (ui *UI) rescanDir() {
530	ui.linkedItems = make(fs.HardLinkedItems)
531
532	// at the virtual root there is nothing to rescan but the roots below it
533	if ui.atVirtualRoot() {
534		if err := ui.AnalyzePaths(ui.scannedRootPaths()); err != nil {
535			ui.showErr("Error rescanning paths", err)
536		}
537		return
538	}
539
540	err := ui.AnalyzePath(ui.currentDirPath, ui.currentDir.GetParent())
541	if err != nil {
542		ui.showErr("Error rescanning path", err)
543	}
544}
545
546// scannedRootPaths returns the paths of the roots grouped under the virtual root.
547func (ui *UI) scannedRootPaths() []string {
548	paths := make([]string, 0)
549	for item := range ui.currentDir.GetFiles(fs.SortByName, fs.SortAsc) {
550		paths = append(paths, item.GetPath())
551	}
552	return paths
553}
554
555func (ui *UI) fileItemSelected(row, column int) {
556	if ui.currentDir == nil {
557		return // Add this check to handle nil case
558	}
559
560	selectedDirCell := ui.table.GetCell(row, column)
561
562	// Check if the selectedDirCell is nil before using it
563	if selectedDirCell == nil || selectedDirCell.GetReference() == nil {
564		return
565	}
566
567	selectedDir := selectedDirCell.GetReference().(fs.Item)
568	if selectedDir == nil || !selectedDir.IsDir() {
569		return
570	}
571
572	origDir := ui.currentDir
573	ui.currentDir = selectedDir
574	ui.hideFilterInput()
575	ui.hideTypeFilterInput()
576	ui.markedRows = make(map[int]struct{})
577	ui.ignoredRows = make(map[int]struct{})
578	ui.showDir()
579
580	// while previewing a mid-scan snapshot there is no stable top dir to anchor
581	// the "select last visited" logic to, so just render the navigated dir
582	if ui.previewing {
583		return
584	}
585
586	if row != 0 || origDir.GetPath() == ui.topDir.GetPath() {
587		return
588	}
589
590	// we are going up in the directory tree, select the last visited directory
591	if origDir.GetParent() != nil {
592		nestedDir := origDir
593		for nestedDir.GetParent() != nil {
594			if selectedDir.GetName() == nestedDir.GetParent().GetName() {
595				sortBy, sortOrder := ui.getSortParams()
596				index := -1
597				i := 0
598				for item := range ui.currentDir.GetFiles(sortBy, sortOrder) {
599					if item.GetName() == nestedDir.GetName() {
600						index = i
601						break
602					}
603					i++
604				}
605				if index >= 0 {
606					if ui.currentDir.GetPath() != ui.topDir.GetPath() {
607						index++
608					}
609					ui.table.Select(index, 0)
610				}
611				break
612			}
613			nestedDir = nestedDir.GetParent()
614		}
615	}
616}
617
618func (ui *UI) deviceItemSelected(row, column int) {
619	var err error
620	selectedDevice, ok := ui.table.GetCell(row, column).GetReference().(*device.Device)
621	if !ok {
622		return
623	}
624
625	paths := device.GetNestedMountpointsPaths(selectedDevice.MountPoint, ui.devices)
626	ui.IgnoreDirPathPatterns, err = common.CreateIgnorePattern(paths)
627	if err != nil {
628		log.Printf("Creating path patterns for other devices failed: %s", paths)
629	}
630
631	ui.resetSorting()
632
633	ui.currentDeviceSize = selectedDevice.Size
634	ui.Analyzer.ResetProgress()
635	ui.linkedItems = make(fs.HardLinkedItems)
636	err = ui.AnalyzePath(selectedDevice.MountPoint, nil)
637	if err != nil {
638		ui.showErr("Error analyzing device", err)
639	}
640}
641
642func (ui *UI) confirmDeletion(action DeleteAction) {
643	if ui.noDelete {
644		ui.showMessage(" Deletion is disabled!")
645		return
646	}
647
648	// Check if deletion is allowed with active time filters
649	if ui.noDeleteWithFilter {
650		modal := tview.NewModal().
651			SetText("Deletion is disabled when a time filter is active.\n\n" +
652				"To override, set GDU_ALLOW_DELETE_WITH_FILTER=1").
653			AddButtons([]string{"OK"}).
654			SetDoneFunc(func(buttonIndex int, buttonLabel string) {
655				ui.pages.RemovePage("confirm")
656			})
657		if !ui.UseColors {
658			modal.SetBackgroundColor(tcell.ColorGray)
659		}
660		ui.pages.AddPage("confirm", modal, true, true)
661		return
662	}
663
664	if len(ui.markedRows) > 0 {
665		ui.confirmDeletionMarked(action)
666	} else {
667		ui.confirmDeletionSelected(action)
668	}
669}
670
671func (ui *UI) confirmDeletionSelected(action DeleteAction) {
672	row, column := ui.table.GetSelection()
673	selectedFile := ui.table.GetCell(row, column).GetReference().(fs.Item)
674	modal := tview.NewModal().
675		SetText(
676			"Are you sure you want to " +
677				action.Verb() +
678				" \"" +
679				tview.Escape(selectedFile.GetName()) +
680				"\"?",
681		).
682		AddButtons([]string{No, Yes, DontAskAgain}).
683		SetDoneFunc(func(buttonIndex int, buttonLabel string) {
684			switch buttonIndex {
685			case 2:
686				ui.askBeforeDelete = false
687				fallthrough
688			case 1:
689				ui.deleteSelected(action)
690			}
691			ui.pages.RemovePage("confirm")
692		})
693
694	if !ui.UseColors {
695		modal.SetBackgroundColor(tcell.ColorGray)
696	} else {
697		modal.SetBackgroundColor(tcell.ColorBlack)
698	}
699	modal.SetBorderColor(tcell.ColorDefault)
700
701	ui.pages.AddPage("confirm", modal, true, true)
702}
703
704// SetTimeFilterWithInfo sets both the time filter function and stores the filter info for display
705func (ui *UI) SetTimeFilterWithInfo(tf *timefilter.TimeFilter, loc *time.Location) {
706	ui.timeFilter = tf
707	ui.timeFilterLoc = loc
708
709	if tf != nil && !tf.IsEmpty() {
710		timeFilterFunc := func(mtime time.Time) bool {
711			return tf.IncludeByTimeFilter(mtime, loc)
712		}
713		ui.SetTimeFilter(timeFilterFunc)
714		if !ui.isDeleteAllowedWithFilter() {
715			ui.SetNoDeleteWithFilter()
716		}
717	}
718}
719
720// hasActiveTimeFilter returns true if any time filter is active
721func (ui *UI) hasActiveTimeFilter() bool {
722	return ui.timeFilter != nil && !ui.timeFilter.IsEmpty()
723}
724
725// formatTimeFilterInfo formats the time filter information for display
726func (ui *UI) formatTimeFilterInfo() string {
727	if !ui.hasActiveTimeFilter() {
728		return ""
729	}
730
731	return ui.timeFilter.FormatForDisplay(ui.timeFilterLoc)
732}
733
734// isDeleteAllowedWithFilter checks if deletion is allowed when filters are active
735func (ui *UI) isDeleteAllowedWithFilter() bool {
736	if !ui.hasActiveTimeFilter() {
737		return true
738	}
739
740	// Check environment variable override
741	if os.Getenv("GDU_ALLOW_DELETE_WITH_FILTER") == "1" {
742		return true
743	}
744
745	return false
746}
747
748// sanitizePathForDisplay replaces control characters (which can include
749// terminal escape sequences) with the Unicode replacement character. A
750// scanned directory entry's name has no character restrictions, and these
751// paths are printed to the real terminal after the tview screen has
752// stopped, bypassing tview's own protective rendering entirely.
753func sanitizePathForDisplay(s string) string {
754	return strings.Map(func(r rune) rune {
755		if unicode.IsControl(r) {
756			return '�'
757		}
758		return r
759	}, s)
760}
761
762// printMarkedPaths prints the paths of the marked items to the output
763func (ui *UI) printMarkedPaths() {
764	for _, path := range ui.markedPaths {
765		fmt.Fprintf(ui.output, "%s\n", sanitizePathForDisplay(path))
766	}
767}