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