Debian Codegraph @

_examples/main.go

raw symbols SCIP
1 // _examples/simple/main.go
2 package main
3
4 import (
5 "bytes"
6 "fmt"
7 "log"
8 "os"
9 "os/signal"
10 "strings"
11 "sync"
12 "syscall"
13
14 "github.com/xo/terminfo"
15 )
16
17 func main() {
18 //r := rand.New(nil)
19
20 // load terminfo
21 ti, err := terminfo.LoadFromEnv()
22 if err != nil {
23 log.Fatal(err)
24 }
25
26 // cleanup
27 defer func() {
28 err := recover()
29 termreset(ti)
30 if err != nil {
31 log.Fatal(err)
32 }
33 }()
34
35 terminit(ti)
36 termtitle(ti, "simple example!")
37 termputs(ti, 3, 3, "Ctrl-C to exit")
38 maxColors := termcolors(ti)
39 if maxColors > 256 {
40 maxColors = 256
41 }
42 for i := 0; i < maxColors; i++ {
43 termputs(ti, 5+i/16, 5+i%16, ti.Colorf(i, 0, "█"))
44 }
45
46 // wait for signal
47 sigs := make(chan os.Signal, 1)
48 signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
49 <-sigs
50 }
51
52 // terminit initializes the special CA mode on the terminal, and makes the
53 // cursor invisible.
54 func terminit(ti *terminfo.Terminfo) {
55 buf := new(bytes.Buffer)
56 // set the cursor invisible
57 ti.Fprintf(buf, terminfo.CursorInvisible)
58 // enter special mode
59 ti.Fprintf(buf, terminfo.EnterCaMode)
60 // clear the screen
61 ti.Fprintf(buf, terminfo.ClearScreen)
62 os.Stdout.Write(buf.Bytes())
63 }
64
65 // termreset is the inverse of terminit.
66 func termreset(ti *terminfo.Terminfo) {
67 buf := new(bytes.Buffer)
68 ti.Fprintf(buf, terminfo.ExitCaMode)
69 ti.Fprintf(buf, terminfo.CursorNormal)
70 os.Stdout.Write(buf.Bytes())
71 }
72
73 // termputs puts a string at row, col, interpolating v.
74 func termputs(ti *terminfo.Terminfo, row, col int, s string, v ...interface{}) {
75 buf := new(bytes.Buffer)
76 ti.Fprintf(buf, terminfo.CursorAddress, row, col)
77 fmt.Fprintf(buf, s, v...)
78 os.Stdout.Write(buf.Bytes())
79 }
80
81 // sl is the status line terminfo.
82 var sl *terminfo.Terminfo
83
84 // termtitle sets the window title.
85 func termtitle(ti *terminfo.Terminfo, s string) {
86 var once sync.Once
87 once.Do(func() {
88 if ti.Has(terminfo.HasStatusLine) {
89 return
90 }
91 // load the sl xterm if terminal is an xterm or has COLORTERM
92 if strings.Contains(strings.ToLower(os.Getenv("TERM")), "xterm") || os.Getenv("COLORTERM") == "truecolor" {
93 sl, _ = terminfo.Load("xterm+sl")
94 }
95 })
96 if sl != nil {
97 ti = sl
98 }
99 if !ti.Has(terminfo.HasStatusLine) {
100 return
101 }
102 buf := new(bytes.Buffer)
103 ti.Fprintf(buf, terminfo.ToStatusLine)
104 fmt.Fprint(buf, s)
105 ti.Fprintf(buf, terminfo.FromStatusLine)
106 os.Stdout.Write(buf.Bytes())
107 }
108
109 // termcolors returns the maximum colors available for the terminal.
110 func termcolors(ti *terminfo.Terminfo) int {
111 if colors := ti.Num(terminfo.MaxColors); colors > 0 {
112 return colors
113 }
114 return int(terminfo.ColorLevelBasic)
115 }