gitee.com/quant1x/gox@v1.21.2/progressbar/print.go (about)

     1  package progressbar
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/quant1x/gox/api"
     6  	"strings"
     7  	"sync"
     8  )
     9  
    10  var (
    11  	mu           sync.Mutex
    12  	gSrcLine     = 0 //起点行
    13  	gCurrentLine = 0 //当前行
    14  	gMaxLine     = 0 //最大行
    15  )
    16  
    17  func barMove(line int) {
    18  	//fmt.Println("\n\n\n\n", gCurrentLine, line)
    19  	fmt.Printf("\033[%dA\033[%dB", gCurrentLine, line)
    20  	gCurrentLine = line
    21  }
    22  
    23  func barPrint(line int, args ...any) {
    24  	mu.Lock()
    25  	defer mu.Unlock()
    26  
    27  	barMove(line)
    28  	var realArgs []any
    29  	realArgs = append(realArgs, "\r")
    30  	realArgs = append(realArgs, args...)
    31  	fmt.Print(realArgs...)
    32  	barMove(gMaxLine)
    33  }
    34  
    35  func barPrintf(line int, format string, args ...any) {
    36  	mu.Lock()
    37  	defer mu.Unlock()
    38  
    39  	barMove(line)
    40  	fmt.Printf("\r"+format, args...)
    41  	barMove(gMaxLine)
    42  }
    43  
    44  func barPrintln(line int, args ...any) {
    45  	mu.Lock()
    46  	defer mu.Unlock()
    47  
    48  	barMove(line)
    49  	var realArgs []any
    50  	realArgs = append(realArgs, "\r")
    51  	realArgs = append(realArgs, args...)
    52  	fmt.Print(realArgs...)
    53  	barMove(gMaxLine)
    54  }
    55  
    56  func Print(args ...any) {
    57  	mu.Lock()
    58  	lf := countLF("", args...)
    59  	if gMaxLine == 0 {
    60  		gMaxLine += lf + 1
    61  	} else {
    62  		gMaxLine += lf
    63  	}
    64  	mu.Unlock()
    65  
    66  	barPrint(gMaxLine, args...)
    67  }
    68  
    69  func Printf(format string, args ...any) {
    70  	mu.Lock()
    71  
    72  	lf := countLF(format, args...)
    73  	if gMaxLine == 0 {
    74  		gMaxLine += lf + 1
    75  	} else {
    76  		gMaxLine += lf
    77  	}
    78  	mu.Unlock()
    79  
    80  	barPrintf(gMaxLine, format, args...)
    81  }
    82  
    83  func Println(args ...any) {
    84  	mu.Lock()
    85  
    86  	lf := countLF("", args...)
    87  	lf++
    88  	if gMaxLine == 0 {
    89  		gMaxLine += lf + 1
    90  	} else {
    91  		gMaxLine += lf
    92  	}
    93  	mu.Unlock()
    94  
    95  	barPrintln(gMaxLine, args...)
    96  }
    97  
    98  func countLF(format string, args ...any) int {
    99  	var count int
   100  	count = strings.Count(format, "\n")
   101  	for _, arg := range args {
   102  		count += strings.Count(api.ToString(arg), "\n")
   103  	}
   104  
   105  	return count
   106  }