fork/gdu
git clone https://git.julia.blue/fork/gdu
34f3996
master
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 ( 19helpDisabledSuffix = " (disabled)" 20 21helpText = ` [::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 { 60label := "[::b] --- " + 61tview .Escape ( 62strings .TrimPrefix (ui .currentDirPath ,build .RootPathPrefix ), 63 )+ 64" ---" 65if ui .previewing { 66label += " [::b][yellow]scanning… (preview, Tab to resume)[-]" 67 } 68return 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 () { 75if ui .changeCwdFn == nil || ui .atVirtualRoot () { 76return 77 } 78 79if err := ui .changeCwdFn (ui .currentDirPath );err != nil { 80log .Printf ("error setting cwd: %s" ,err .Error ()) 81 } 82log .Printf ("changing cwd to %s" ,ui .currentDirPath ) 83} 84 85// nolint: funlen // Why: complex function 86func (ui * UI )showDir () { 87var ( 88totalUsage int64 89totalSize int64 90maxima rowMaxima 91itemCount int64 92 ) 93 94ui .currentDirPath = ui .currentDir .GetPath () 95 96ui .followCurrentDirWithCwd () 97 98ui .currentDirLabel .SetText (ui .currentDirLabelText ()).SetDynamicColors (true ) 99 100ui .table .Clear () 101 102rowIndex := 0 103if ui .currentDirPath != ui .topDirPath { 104prefix := strings .Repeat (" " ,ui .columnsWidth ()) 105 106cell := tview .NewTableCell (prefix + "[::b]/.." ) 107 108// Use the collapsed parent logic to handle navigation back through collapsed paths 109var collapsedParent fs.Item 110if ui .collapsePath { 111collapsedParent = findCollapsedParent (ui .currentDir ) 112 }else { 113collapsedParent = ui .currentDir .GetParent () 114 } 115cell .SetReference (collapsedParent ) 116cell .SetStyle (tcell.Style {}.Foreground (tcell .ColorDefault )) 117ui .table .SetCell (0 ,0 ,cell ) 118rowIndex ++ 119 } 120 121sortBy ,sortOrder := ui .getSortParams () 122 123unlock := ui .currentDir .RLock () 124defer unlock () 125 126i := rowIndex 127maxima = rowMaxima {} 128for item := range ui .currentDir .GetFiles (sortBy ,sortOrder ) { 129if _ ,ignored := ui .ignoredRows [i ];ignored { 130i ++ 131continue 132 } 133 134count := fs .DisplayedItemCount (item ) 135 136if ui .ShowRelativeSize { 137if item .GetUsage ()> maxima .usage { 138maxima .usage = item .GetUsage () 139 } 140if item .GetSize ()> maxima .size { 141maxima .size = item .GetSize () 142 } 143if count > maxima .count { 144maxima .count = count 145 } 146 }else { 147maxima .size += item .GetSize () 148maxima .usage += item .GetUsage () 149maxima .count += count 150 } 151i ++ 152 } 153 154for 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 157if ui .filterValue != "" && ! strings .Contains ( 158strings .ToLower (analyze .ItemDisplayName (ui .currentDir ,item )), 159strings .ToLower (ui .filterValue ), 160 ) { 161continue 162 } 163 164if ! ui .matchesTypeFilter (item .GetName (),item .IsDir ()) { 165continue 166 } 167 168_ ,ignored := ui .ignoredRows [rowIndex ] 169 170if ! ignored { 171totalUsage += item .GetUsage () 172totalSize += item .GetSize () 173itemCount += item .GetItemCount () 174 } 175 176_ ,marked := ui .markedRows [rowIndex ] 177 178var cell * tview.TableCell 179var reference fs.Item 180 181// Check if this directory can be collapsed 182if item .IsDir () { 183var collapsedPath * CollapsedPath 184if ui .collapsePath { 185collapsedPath = findCollapsiblePath (item ) 186 } 187 188if collapsedPath != nil { 189// Format as collapsed path 190cell = tview .NewTableCell (ui .formatCollapsedRow (collapsedPath ,maxima ,marked ,ignored )) 191// Reference should point to the deepest directory for navigation 192reference = collapsedPath .DeepestDir 193 }else { 194// Regular directory formatting 195cell = tview .NewTableCell (ui .formatFileRow (item ,maxima ,marked ,ignored )) 196reference = item 197 } 198 }else { 199// Regular file formatting 200cell = tview .NewTableCell (ui .formatFileRow (item ,maxima ,marked ,ignored )) 201reference = item 202 } 203 204cell .SetReference (reference ) 205 206switch { 207case ignored : 208cell .SetStyle (tcell.Style {}.Foreground (tview .Styles .SecondaryTextColor )) 209case marked : 210cell .SetStyle (tcell.Style {}.Foreground (ui .markedTextColor )) 211cell .SetBackgroundColor (ui .markedBackgroundColor ) 212default : 213cell .SetStyle (tcell.Style {}.Foreground (tcell .ColorDefault )) 214 } 215 216ui .table .SetCell (rowIndex ,0 ,cell ) 217rowIndex ++ 218 } 219 220var footerNumberColor ,footerTextColor string 221if ui .UseColors { 222footerNumberColor = fmt .Sprintf ( 223"[%s:%s:b]" , 224ui .footerNumberColor , 225ui .footerBackgroundColor , 226 ) 227footerTextColor = fmt .Sprintf ( 228"[%s:%s:-]" , 229ui .footerTextColor , 230ui .footerBackgroundColor , 231 ) 232 }else { 233footerNumberColor = "[black:white:b]" 234footerTextColor = blackOnWhite 235 } 236 237selected := "" 238if len (ui .markedRows )> 0 { 239selected = " Selected items: " + footerNumberColor + 240strconv .Itoa (len (ui .markedRows ))+ footerTextColor 241 } 242 243timeFilterText := ui .formatTimeFilterInfo () 244 245typeFilterText := ui .formatTypeFilterInfo (footerNumberColor ,footerTextColor ) 246 247ui .footerLabel .SetText ( 248selected + footerTextColor + 249" Total disk usage: " + 250footerNumberColor + 251ui .formatSize (totalUsage ,true ,false )+ 252" Apparent size: " + 253footerNumberColor + 254ui .formatSize (totalSize ,true ,false )+ 255" Items: " + footerNumberColor + fmt .Sprintf ("%d" ,itemCount )+ 256footerTextColor + 257" Sorting by: " + ui .sortBy + " " + ui .sortOrder + 258typeFilterText + 259timeFilterText ) 260 261ui .table .Select (0 ,0 ) 262ui .table .ScrollToBeginning () 263 264if ! ui .filtering && ! ui .typeFiltering { 265ui .app .SetFocus (ui .table ) 266 } 267} 268 269func (ui * UI )showDevices () { 270var totalUsage int64 271 272ui .table .Clear () 273ui .table .SetCell (0 ,0 ,tview .NewTableCell ("Device name" ).SetSelectable (false )) 274ui .table .SetCell (0 ,1 ,tview .NewTableCell ("Size" ).SetSelectable (false )) 275ui .table .SetCell (0 ,2 ,tview .NewTableCell ("Used" ).SetSelectable (false )) 276ui .table .SetCell (0 ,3 ,tview .NewTableCell ("Used part" ).SetSelectable (false )) 277ui .table .SetCell (0 ,4 ,tview .NewTableCell ("Free" ).SetSelectable (false )) 278ui .table .SetCell (0 ,5 ,tview .NewTableCell ("Mount point" ).SetSelectable (false )) 279 280var textColor ,sizeColor string 281if ui .UseColors { 282textColor = "[#3498db:-:b]" 283sizeColor = "[#edb20a:-:b]" 284 }else { 285textColor = "[white:-:b]" 286sizeColor = "[white:-:b]" 287 } 288 289ui .sortDevices () 290 291for i ,device := range ui .devices { 292totalUsage += device .GetUsage () 293ui .table .SetCell (i + 1 ,0 ,tview .NewTableCell (textColor + device .Name ).SetReference (ui .devices [i ])) 294ui .table .SetCell (i + 1 ,1 ,tview .NewTableCell (ui .formatSize (device .Size ,false ,true ))) 295ui .table .SetCell (i + 1 ,2 ,tview .NewTableCell (sizeColor + ui .formatSize (device .Size - device .Free ,false ,true ))) 296ui .table .SetCell (i + 1 ,3 ,tview .NewTableCell (getDeviceUsagePart (device ,ui .useOldSizeBar ))) 297ui .table .SetCell (i + 1 ,4 ,tview .NewTableCell (ui .formatSize (device .Free ,false ,true ))) 298ui .table .SetCell (i + 1 ,5 ,tview .NewTableCell (textColor + device .MountPoint ).SetReference (ui .devices [i ])) 299 } 300 301var footerNumberColor ,footerTextColor string 302if ui .UseColors { 303footerNumberColor = fmt .Sprintf ( 304"[%s:%s:b]" , 305ui .footerNumberColor , 306ui .footerBackgroundColor , 307 ) 308footerTextColor = fmt .Sprintf ( 309"[%s:%s:-]" , 310ui .footerTextColor , 311ui .footerBackgroundColor , 312 ) 313 }else { 314footerNumberColor = "[black:white:b]" 315footerTextColor = blackOnWhite 316 } 317 318ui .footerLabel .SetText ( 319" Total usage: " + 320footerNumberColor + 321ui .formatSize (totalUsage ,true ,false )+ 322footerTextColor + 323" Sorting by: " + ui .sortBy + " " + ui .sortOrder ) 324 325ui .table .Select (1 ,0 ) 326ui .table .SetSelectedFunc (ui .deviceItemSelected ) 327 328if ui .topDirPath != "" { 329for i ,device := range ui .devices { 330if device .MountPoint == ui .topDirPath { 331ui .table .Select (i + 1 ,0 ) 332break 333 } 334 } 335 } 336} 337 338func (ui * UI )showErr (msg string ,err error ) { 339text := msg 340if err != nil { 341text += ": " + err .Error () 342 } 343 344modal := tview .NewModal (). 345SetText (text ). 346AddButtons ([]string {"ok" }). 347SetDoneFunc (func (buttonIndex int ,buttonLabel string ) { 348ui .pages .RemovePage ("error" ) 349 }) 350 351if ! ui .UseColors { 352modal .SetBackgroundColor (tcell .ColorGray ) 353 } 354 355ui .pages .AddPage ("error" ,modal ,true ,true ) 356ui .app .SetFocus (modal ) 357} 358 359func (ui * UI )showErrFromGo (msg string ,err error ) { 360ui .app .QueueUpdateDraw (func () { 361ui .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 ) { 371previousText := ui .header .GetText (false ) 372ui .header .SetText (message ) 373 374go func () { 375time .Sleep (messageTimeout ) 376ui .app .QueueUpdateDraw (func () { 377ui .header .Clear () 378ui .header .SetText (previousText ) 379 }) 380 }() 381} 382 383func (ui * UI )showHelp () { 384text := tview .NewTextView ().SetDynamicColors (true ) 385text .SetBorder (true ).SetBorderPadding (2 ,2 ,2 ,2 ) 386text .SetBorderColor (tcell .ColorDefault ) 387text .SetTitle (" gdu help " ) 388text .SetScrollable (true ) 389 390formattedHelpText := ui .formatHelpTextFor () 391text .SetText (formattedHelpText ) 392 393maxHeight := strings .Count (formattedHelpText ,"\n" )+ 7 394_ ,height := ui .screen .Size () 395if height > maxHeight { 396height = maxHeight 397 } 398 399flex := tview .NewFlex (). 400AddItem (nil ,0 ,1 ,false ). 401AddItem (tview .NewFlex ().SetDirection (tview .FlexRow ). 402AddItem (nil ,0 ,1 ,false ). 403AddItem (text ,height ,1 ,false ). 404AddItem (nil ,0 ,1 ,false ),80 ,1 ,false ). 405AddItem (nil ,0 ,1 ,false ) 406 407ui .help = flex 408ui .pages .AddPage ("help" ,flex ,true ,true ) 409ui .app .SetFocus (text ) 410} 411 412func (ui * UI )formatHelpTextFor ()string { 413lines := strings .Split (helpText ,"\n" ) 414 415for i ,line := range lines { 416if ui .UseColors { 417lines [i ]= strings .ReplaceAll ( 418strings .ReplaceAll (line ,defaultColorBold ,"[red]" ), 419whiteOnBlack , 420"[white]" , 421 ) 422 } 423 424isFound := (strings .Contains (line ,"Empty file or directory" )|| 425strings .Contains (line ,"Delete file or directory" )|| 426strings .Contains (line ,"Move file or directory to trash" )) 427 428if ui .noDelete && isFound { 429lines [i ]+= helpDisabledSuffix 430 }else if ui .noDeleteWithFilter && isFound { 431lines [i ]+= " (disabled/filter)" 432 } 433 434if ui .noSpawnShell && (strings .Contains (line ,"Spawn shell in current directory" )|| 435strings .Contains (line ,"Open file or directory in external program" )) { 436lines [i ]+= helpDisabledSuffix 437 } 438 439if ui .noViewFile && strings .Contains (line ,"Show content of file" ) { 440lines [i ]+= helpDisabledSuffix 441 } 442 } 443 444return strings .Join (lines ,"\n" ) 445} 446 447func (ui * UI )formatTypeFilterInfo (numberColor ,textColor string )string { 448if ui .typeFilterValue == "" { 449return "" 450 } 451return " Type filter: " + numberColor + ui .typeFilterValue + textColor 452}