github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/pkg/utils/display/screen.go (about) 1 package display 2 3 import ( 4 "os" 5 "os/exec" 6 "regexp" 7 "strconv" 8 "strings" 9 10 commonUtils "github.com/easysoft/zendata/pkg/utils/common" 11 shellUtils "github.com/easysoft/zendata/pkg/utils/shell" 12 ) 13 14 func GetScreenSize() (int, int) { 15 var cmd string 16 var width int 17 var height int 18 19 if commonUtils.IsWin() { 20 cmd = "mode" // tested for win7 21 out, _ := shellUtils.Exec(cmd) 22 23 //out := `设备状态 CON: 24 // --------- 25 // 行: 300 26 // 列: 80 27 // 键盘速度: 31 28 // 键盘延迟: 1 29 // 代码页: 936 30 //` 31 myExp := regexp.MustCompile(`CON:\s+[^\s]+\s*(.*?)(\d+)\s\s*(.*?)(\d+)\s`) 32 arr := myExp.FindStringSubmatch(out) 33 if len(arr) > 4 { 34 height, _ = strconv.Atoi(strings.TrimSpace(arr[2])) 35 width, _ = strconv.Atoi(strings.TrimSpace(arr[4])) 36 } 37 } else { 38 width, height = noWindowsSize() 39 } 40 41 return width, height 42 } 43 44 func noWindowsSize() (int, int) { 45 cmd := exec.Command("stty", "size") 46 cmd.Stdin = os.Stdin 47 out, err := cmd.Output() 48 output := string(out) 49 50 if err != nil { 51 return 0, 0 52 } 53 width, height, err := parseSize(output) 54 55 return width, height 56 } 57 func parseSize(input string) (int, int, error) { 58 parts := strings.Split(input, " ") 59 h, err := strconv.Atoi(parts[0]) 60 if err != nil { 61 return 0, 0, err 62 } 63 w, err := strconv.Atoi(strings.Replace(parts[1], "\n", "", 1)) 64 if err != nil { 65 return 0, 0, err 66 } 67 return int(w), int(h), nil 68 }