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