@@ -3,6 +3,7 @@ package osc
33import (
44 "bytes"
55 "encoding/base64"
6+ "errors"
67 "fmt"
78 "io"
89 "os"
@@ -15,6 +16,9 @@ import (
1516var ecsi = "\033 ]"
1617var st = "\007 "
1718
19+ var cellSizeOnce sync.Once
20+ var cellWidth , cellHeight float64
21+
1822func init () {
1923 if os .Getenv ("TERM" ) == "screen" {
2024 ecsi = "\033 Ptmux;\033 " + ecsi
@@ -35,26 +39,38 @@ type TermSize struct {
3539 Height int
3640}
3741
38- // Size gathers sizing information of the current session's controling terminal.
39- func Size () (size TermSize , err error ) {
40- size .Col , size .Row , err = terminal .GetSize (1 )
41- if err != nil {
42- return
43- }
42+ func initCellSize () {
4443 s , err := terminal .MakeRaw (1 )
4544 if err != nil {
4645 return
4746 }
4847 defer terminal .Restore (1 , s )
49- var cellWidth , cellHeight float64
5048 fmt .Fprint (os .Stdout , ecsi + "1337;ReportCellSize" + st )
5149 fileSetReadDeadline (os .Stdout , time .Now ().Add (time .Second ))
5250 defer fileSetReadDeadline (os .Stdout , time.Time {})
53- _ , err = fmt .Fscanf (os .Stdout , "\033 ]1337;ReportCellSize=%f;%f\033 \\ " , & cellHeight , & cellWidth )
51+ fmt .Fscanf (os .Stdout , "\033 ]1337;ReportCellSize=%f;%f\033 \\ " , & cellHeight , & cellWidth )
52+ }
53+
54+ // Size gathers sizing information of the current session's controling terminal.
55+ func Size () (size TermSize , err error ) {
56+ size .Col , size .Row , err = terminal .GetSize (1 )
57+ if err != nil {
58+ return
59+ }
60+ cellSizeOnce .Do (initCellSize )
61+ if cellWidth + cellHeight == 0 {
62+ err = errors .New ("cannot get iTerm2 cell size" )
63+ }
5464 size .Width , size .Height = size .Col * int (cellWidth ), size .Row * int (cellHeight )
5565 return
5666}
5767
68+ // Rows returns the number of rows for the controling terminal.
69+ func Rows () (rows int , err error ) {
70+ _ , rows , err = terminal .GetSize (1 )
71+ return
72+ }
73+
5874// ImageWriter is a writer that write into iTerm2 terminal the PNG data written
5975// to it.
6076type ImageWriter struct {
0 commit comments