├── README ├── .gitignore ├── term ├── Makefile ├── codes.go ├── term_test.go ├── term_frame_test.go ├── doc.go ├── term_frame.go ├── term_line_test.go ├── term_line.go └── term.go ├── termios ├── termios_test.go └── termios.go ├── goat.go └── LICENSE /README: -------------------------------------------------------------------------------- 1 | term/doc.go -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.a 3 | *.[568vq] 4 | [568vq].out 5 | *.so 6 | _obj 7 | _test 8 | _testmain.go 9 | *.exe 10 | _cgo* 11 | test.out 12 | build.out 13 | *.sw[op] 14 | *.log 15 | *.dat 16 | goat 17 | *.test 18 | goat 19 | -------------------------------------------------------------------------------- /term/Makefile: -------------------------------------------------------------------------------- 1 | include $(GOROOT)/src/Make.inc 2 | 3 | TARG=github.com/kylelemons/goat/term 4 | GOFILES=\ 5 | term.go\ 6 | term_cooked.go\ 7 | term_frame.go\ 8 | codes.go\ 9 | termio.go\ 10 | 11 | include $(GOROOT)/src/Make.pkg 12 | -------------------------------------------------------------------------------- /termios/termios_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Run this test with: 16 | // go test -c && ./term.test 17 | 18 | package termios 19 | 20 | import ( 21 | "testing" 22 | ) 23 | 24 | func TestTermSettings(t *testing.T) { 25 | tio, err := NewTermSettings(0) 26 | if err != nil { 27 | t.Fatalf("NewTermSettings: %s", err) 28 | } 29 | if err := tio.Apply(); err != nil { 30 | t.Errorf("Apply: %s", err) 31 | } 32 | if err := tio.Reset(); err != nil { 33 | t.Errorf("Reset: %s", err) 34 | } 35 | t.Log(tio) 36 | } 37 | 38 | func TestTermSize(t *testing.T) { 39 | tio, err := NewTermSettings(0) 40 | if err != nil { 41 | t.Fatalf("NewTermSettings: %s", err) 42 | } 43 | w, h, err := tio.GetSize() 44 | if err != nil { 45 | t.Fatalf("GetSize: %s", err) 46 | } 47 | t.Logf("Size: %d cols, %d rows", w, h) 48 | } 49 | -------------------------------------------------------------------------------- /term/codes.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | // Terminal Control Codes 18 | const ( 19 | NUL = iota 20 | SOH // Start of Header 21 | STX // Start of Text 22 | ETX // End of Text 23 | EOT // End of Transmission 24 | ENQ // Enquire 25 | ACK // Acknowledge 26 | BEL // Bell 27 | BS // Backspace 28 | TAB // Horizontal tab 29 | LF // Line feed 30 | VT // Vertical tab 31 | FF // Form feed 32 | CR // Carriage return 33 | SO // Shift out 34 | SI // Shift in 35 | DLE // Data link escape 36 | DC1 // Device Control 1 37 | DC2 // Device Control 2 38 | DC3 // Device Control 3 39 | DC4 // Device Control 4 40 | NAK // Negative Acknowledge 41 | SYN // Synchronize 42 | ETB // End Transmission Block 43 | CAN // CANCEL 44 | EM // End of Medium 45 | SUB // Substitute 46 | ESC // Escape 47 | FS // File separator 48 | GS // Group separator 49 | RS // Record separator 50 | US // Unit separator 51 | 52 | DEL = 127 // Delete 53 | ) 54 | 55 | // Control Constants 56 | // 57 | // These are all emitted by themselves to easily discern them from the rest of 58 | // the sequence of chunks. 59 | const ( 60 | Interrupt = "\x03" // ^C 61 | EndOfFile = "\x04" // ^D 62 | Suspend = "\x1a" // ^Z 63 | Quit = "\x1c" // ^\ 64 | 65 | CarriageReturn = "\r" 66 | NewLine = "\n" 67 | ) 68 | -------------------------------------------------------------------------------- /term/term_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | import ( 18 | "io" 19 | "testing" 20 | ) 21 | 22 | type RW struct { 23 | *io.PipeReader 24 | *io.PipeWriter 25 | } 26 | 27 | func (rw *RW) Close() error { 28 | return rw.PipeWriter.Close() 29 | } 30 | 31 | func (rw *RW) CloseWithError(err error) error { 32 | return rw.PipeWriter.CloseWithError(err) 33 | } 34 | 35 | type DoublePipe struct { 36 | Local *RW 37 | Remote *RW 38 | } 39 | 40 | func NewDoublePipe() *DoublePipe { 41 | inR, inW := io.Pipe() 42 | outR, outW := io.Pipe() 43 | return &DoublePipe{ 44 | Local: &RW{inR, outW}, 45 | Remote: &RW{outR, inW}, 46 | } 47 | } 48 | 49 | func VerifyReads(t *testing.T, desc, what string, r io.Reader, chunks []string, done chan bool) { 50 | raw := make([]byte, 4096) 51 | var idx int 52 | for idx = 0; idx < 1000; idx++ { 53 | n, err := r.Read(raw) 54 | if err == io.EOF { 55 | break 56 | } else if err != nil { 57 | t.Errorf("%s: %s[%d]: %s", desc, what, idx, err) 58 | continue 59 | } 60 | if chunks == nil { 61 | continue 62 | } 63 | if idx >= len(chunks) { 64 | t.Errorf("%s: extra %s: %q", desc, what, string(raw[:n])) 65 | continue 66 | } 67 | if got, want := string(raw[:n]), chunks[idx]; got != want { 68 | t.Errorf("%s: %s[%d] = %q, want %q", desc, what, idx, got, want) 69 | } 70 | } 71 | for idx < len(chunks) { 72 | t.Errorf("%s: missing %s: %q", desc, what, chunks[idx]) 73 | idx++ 74 | } 75 | done <- true 76 | } 77 | -------------------------------------------------------------------------------- /term/term_frame_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | import ( 18 | "io" 19 | "reflect" 20 | "testing" 21 | ) 22 | 23 | var growTests = []struct { 24 | Start rect 25 | Dw, Dh int 26 | Expect rect 27 | }{ 28 | { 29 | rect{1, 2, 10, 5}, 30 | 1, 1, 31 | rect{0, 1, 12, 7}, 32 | }, 33 | { 34 | rect{1, 2, 10, 5}, 35 | -1, -1, 36 | rect{2, 3, 8, 3}, 37 | }, 38 | } 39 | 40 | func TestGrow(t *testing.T) { 41 | for _, test := range growTests { 42 | grown := test.Start.grow(test.Dw, test.Dh) 43 | if got, want := grown, test.Expect; !reflect.DeepEqual(got, want) { 44 | t.Errorf("%v.grow(%d,%d) = %v, want %v", 45 | test.Start, test.Dw, test.Dh, got, want) 46 | } 47 | } 48 | } 49 | 50 | var frameTests = []struct { 51 | Desc string 52 | Func func(*Region) 53 | Input []string 54 | Output []string 55 | }{ 56 | { 57 | "Empty region", 58 | func(r *Region) { 59 | r.SetSize(4, 3) 60 | }, 61 | []string{}, 62 | []string{ 63 | "\x1b[1;1H", " ", 64 | "\x1b[2;1H", " ", 65 | "\x1b[3;1H", " ", 66 | "\x1b[1;1H", 67 | }, 68 | }, 69 | { 70 | "Empty region, with border", 71 | func(r *Region) { 72 | r.SetSize(4, 3) 73 | r.SetBorder(SimpleBorder) 74 | }, 75 | []string{}, 76 | []string{ 77 | "\x1b[1;1H", ",--.", 78 | "\x1b[2;1H", "| |", 79 | "\x1b[3;1H", "`--'", 80 | "\x1b[2;2H", 81 | }, 82 | }, 83 | } 84 | 85 | func TestFrame(t *testing.T) { 86 | for _, test := range frameTests { 87 | desc := test.Desc 88 | done := make(chan bool) 89 | pipe := NewDoublePipe() 90 | tty, region := NewFrameTTY(pipe.Remote) 91 | 92 | go VerifyReads(t, desc, "read", tty, nil, done) 93 | go VerifyReads(t, desc, "echo", pipe.Local, test.Output, done) 94 | 95 | go func() { 96 | test.Func(region) 97 | region.Draw() 98 | done <- true 99 | }() 100 | 101 | for _, chunk := range test.Input { 102 | if _, err := io.WriteString(pipe.Local, chunk); err != nil { 103 | t.Errorf("%s: write(%q): %s", desc, chunk, err) 104 | } 105 | } 106 | 107 | <-done 108 | 109 | pipe.Local.Close() 110 | <-done 111 | 112 | pipe.Remote.Close() 113 | <-done 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /term/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Package term provides a basic terminal emulation framework. 16 | // 17 | // The TTY class abstracts the logic of providing line editing and line 18 | // buffering, as well as escape sequence recognition. When creating a TTY with 19 | // the NewTTY function, interactive echo will automatically be enabled if the 20 | // provided io.Reader's underlying object also implements io.Writer. 21 | // 22 | // Line editing capabilities (Line mode) 23 | // 24 | // The line editing facilities are very basic; you can type, and you can 25 | // backspace out characters up to the beginning of the line. Note that for all 26 | // internal purposes, typing a control character (e.g. ^D or ^C) starts a new 27 | // line, including for line history below. 28 | // 29 | // You can also use the arrow keys for editing: 30 | // LEFT Move back one character 31 | // RIGHT Move forward one character 32 | // DOWN Move to the end of the line 33 | // UP Restore previous line (see below) 34 | // 35 | // Line history (Line mode) 36 | // 37 | // Currently the TTY only has a single-line history. Pressing the return key 38 | // will save the current line in that history, and pressing the "up" arrow at 39 | // any time will restore the previous line. 40 | // 41 | // Example 42 | // 43 | // The following example reads from standard input, calling runCommand with 44 | // the complete lines it accumulates. 45 | // 46 | // tty := term.NewTTY(os.Stdin) 47 | // 48 | // line := "" 49 | // for { 50 | // n, err := tty.Read(raw) 51 | // if err != nil { 52 | // log.Printf("read: %s", err) 53 | // return 54 | // } 55 | // 56 | // switch str := string(raw[:n]); str { 57 | // case "quit", term.Interrupt, term.EndOfFile: 58 | // fmt.Println("Goodbye!") 59 | // return 60 | // case term.CarriageReturn, term.NewLine: 61 | // runCommand(line) 62 | // line = "" 63 | // default: 64 | // line += str 65 | // } 66 | // } 67 | // 68 | // In order for the above example to work, the terminal must be in raw mode, 69 | // which can be done by running your binary like so (on a unix-like operating 70 | // system like linux or darwin): 71 | // 72 | // stty raw; cmd; stty cooked 73 | // 74 | package term 75 | -------------------------------------------------------------------------------- /goat.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // goat 16 | // 17 | // It is a basic example of terminal emulation with the "goat/term" package. 18 | // It reads chunks in and writes them to standard output. Try typing a line 19 | // and then hitting the up key on the next line. Try editing a previous line 20 | // and hitting the up key again. 21 | // 22 | // Press ^C, ^D, or type "quit" to exit. 23 | // 24 | // If something happens and you can't exit, try "killall goat" from another 25 | // terminal; this shouldn't happen, but it's possible. 26 | package main 27 | 28 | import ( 29 | "flag" 30 | "io" 31 | "log" 32 | "os" 33 | 34 | "github.com/kylelemons/goat/term" 35 | "github.com/kylelemons/goat/termios" 36 | ) 37 | 38 | var frame = flag.Bool("frame", false, "Do a frame demo instead of line editing") 39 | 40 | func main() { 41 | flag.Parse() 42 | 43 | tio, err := termios.NewTermSettings(0) 44 | if err != nil { 45 | log.Fatalf("terminal: %s", err) 46 | } 47 | if err := tio.Raw(); err != nil { 48 | log.Fatalf("rawterm: %s", err) 49 | } 50 | defer tio.Reset() 51 | 52 | if *frame { 53 | frameDemo(tio) 54 | } else { 55 | lineDemo() 56 | } 57 | } 58 | 59 | func lineDemo() { 60 | tty := term.NewTTY(os.Stdin) 61 | 62 | // Prompt after each newline 63 | prompt := func() { 64 | io.WriteString(tty, "> ") 65 | } 66 | prompt() 67 | 68 | // Allocate the line buffer and accumulator 69 | linebuf := make([]byte, 128) 70 | line := "" 71 | 72 | for { 73 | // Read from the TTY 74 | n, err := tty.Read(linebuf) 75 | if err != nil { 76 | log.Printf("read: %s", err) 77 | return 78 | } 79 | 80 | // Examine the chunk 81 | switch str := string(linebuf[:n]); str { 82 | case "quit", term.Interrupt, term.EndOfFile: 83 | // Quit on "quit", ^C, and ^D 84 | io.WriteString(os.Stdout, "Goodbye!\r\n") 85 | return 86 | case term.CarriageReturn, term.NewLine: 87 | // Print out lines 88 | log.Printf("read: %q\r\n", line) 89 | prompt() 90 | line = "" 91 | default: 92 | // Accumulate lines 93 | line += str 94 | } 95 | } 96 | } 97 | 98 | func frameDemo(tio *termios.TermSettings) { 99 | // Allocate a TTY connected to standard input 100 | tty, region := term.NewFrameTTY(os.Stdin) 101 | tty.Clear() 102 | region.SetBorder(term.SimpleBorder) 103 | 104 | width, height, err := tio.GetSize() 105 | if err == nil && width > 0 && height > 0 { 106 | region.SetSize(width, height) 107 | } 108 | 109 | region.Draw() 110 | 111 | // Allocate the line buffer and accumulator 112 | linebuf := make([]byte, 128) 113 | 114 | for { 115 | // Read from the TTY 116 | n, err := tty.Read(linebuf) 117 | if err != nil { 118 | log.Printf("read: %s", err) 119 | return 120 | } 121 | 122 | // Examine the chunk 123 | switch str := string(linebuf[:n]); str { 124 | case "quit", term.Interrupt, term.EndOfFile: 125 | // Quit on "quit", ^C, and ^D 126 | tty.Clear() 127 | tty.SetCursor(0, 0) 128 | io.WriteString(tty, "Goodbye!\r\n") 129 | log.Printf("%dx%d\r", width, height) 130 | return 131 | } 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /term/term_frame.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | import ( 18 | "fmt" 19 | ) 20 | 21 | type rect struct { 22 | x, y, width, height int 23 | } 24 | 25 | func (r rect) grow(dw, dh int) rect { 26 | return rect{ 27 | x: r.x - dw, 28 | y: r.y - dh, 29 | width: r.width + 2*dw, 30 | height: r.height + 2*dh, 31 | } 32 | } 33 | 34 | func (r rect) String() string { 35 | return fmt.Sprintf("[%dx%d@(%d,%d)]", r.width, r.height, r.x, r.y) 36 | } 37 | 38 | type Region struct { 39 | tty *TTY 40 | content rect 41 | border borderStyle 42 | } 43 | 44 | func (t *TTY) NewRegion(w, h, x, y int) *Region { 45 | if t.screen == nil { 46 | return nil 47 | } 48 | 49 | if x < 0 || y < 0 { 50 | return nil 51 | } 52 | 53 | return &Region{ 54 | tty: t, 55 | content: rect{x, y, w, h}, 56 | } 57 | } 58 | 59 | func (r *Region) SetBorder(style borderStyle) { 60 | if r.border == nil { 61 | r.content = r.content.grow(-1, -1) 62 | } 63 | r.border = style 64 | if r.border == nil { 65 | r.content = r.content.grow(1, 1) 66 | } 67 | } 68 | 69 | func (r *Region) SetPos(x, y int) { 70 | if r.border != nil { 71 | x, y = x+1, y+1 72 | } 73 | r.content.x, r.content.y = x, y 74 | } 75 | 76 | func (r *Region) SetSize(width, height int) { 77 | if r.border != nil { 78 | width, height = width-2, height-2 79 | } 80 | if width < 0 { 81 | width = 0 82 | } 83 | if height < 0 { 84 | height = 0 85 | } 86 | r.content.width, r.content.height = width, height 87 | } 88 | 89 | func (r *Region) Draw() { 90 | rect := r.content 91 | border := r.border != nil 92 | if border { 93 | rect = rect.grow(1, 1) 94 | } 95 | 96 | line := make([]byte, rect.width) 97 | start, end := 0, rect.width 98 | if border { 99 | start, end = 1, rect.width-1 100 | } 101 | 102 | for row := 0; row < rect.height; row++ { 103 | if row < 2 || row == rect.height-1 { 104 | fill := byte(' ') 105 | if border { 106 | switch row { 107 | case 0: 108 | fill = r.border[borderHorizontal] 109 | line[0] = r.border[borderTopLeft] 110 | line[len(line)-1] = r.border[borderTopRight] 111 | default: 112 | line[0] = r.border[borderVertical] 113 | line[len(line)-1] = r.border[borderVertical] 114 | case rect.height - 1: 115 | fill = r.border[borderHorizontal] 116 | line[0] = r.border[borderBottomLeft] 117 | line[len(line)-1] = r.border[borderBottomRight] 118 | } 119 | } 120 | for col := start; col < end; col++ { 121 | line[col] = fill 122 | } 123 | } 124 | r.tty.SetCursor(rect.x, rect.y+row) 125 | r.tty.echo(line...) 126 | } 127 | 128 | r.tty.SetCursor(r.content.x, r.content.y) 129 | } 130 | 131 | func (t *TTY) Clear() { 132 | t.echo('\x1b', '[', '2', 'J') 133 | } 134 | 135 | // SetCursor Places the cursor at the given x,y position. 136 | // 137 | // Both x and y start at 0 and increase right and down. 138 | func (t *TTY) SetCursor(x, y int) { 139 | if t.screen == nil { 140 | return 141 | } 142 | fmt.Fprintf(t.screen, "\x1b[%d;%dH", y+1, x+1) 143 | } 144 | 145 | type borderStyle []byte 146 | 147 | var SimpleBorder = borderStyle{ 148 | '-', '|', // Horizontal, Vertical 149 | ',', '+', '.', // Top: Left, Tee, Right 150 | '+', '+', '+', // Left Tee, Center, Right Tee 151 | '`', '+', '\'', // Bottom: Left, Tee, Right 152 | } 153 | 154 | var FancyBorder = borderStyle{ 155 | 196, 179, // Horizontal, Vertical 156 | 218, 194, 191, // Top: Left, Tee, Right 157 | 195, 197, 180, // Left Tee, Center, Right Tee 158 | 192, 193, 217, // Bottom: Left, Tee, Right 159 | } 160 | 161 | const ( 162 | borderHorizontal = iota 163 | borderVertical 164 | borderTopLeft 165 | borderTopTee 166 | borderTopRight 167 | borderLeftTee 168 | borderCenter 169 | borderRightTee 170 | borderBottomLeft 171 | borderBottomTee 172 | borderBottomRight 173 | borderCount 174 | ) 175 | -------------------------------------------------------------------------------- /term/term_line_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | import ( 18 | "io" 19 | "testing" 20 | ) 21 | 22 | var termTests = []struct { 23 | Desc string 24 | Chunks []string 25 | Echo []string 26 | Output []string 27 | }{ 28 | { 29 | Desc: "basic", 30 | Chunks: []string{"test"}, 31 | Output: []string{"test"}, 32 | }, 33 | { 34 | Desc: "lines", 35 | Chunks: []string{"one\ntwo"}, 36 | Output: []string{"one", "\n", "two"}, 37 | }, 38 | { 39 | Desc: "\\r\\n", 40 | Chunks: []string{"one\r\ntwo"}, 41 | Output: []string{"one", "\r", "\n", "two"}, 42 | }, 43 | { 44 | Desc: "echo", 45 | Chunks: []string{"o", "n", "e"}, 46 | Echo: []string{"o", "n", "e"}, 47 | }, 48 | { 49 | Desc: "newline", 50 | Chunks: []string{"o", "n", "e", "\r", "\n"}, 51 | Echo: []string{"o", "n", "e", "\r\n", "\r\n"}, 52 | }, 53 | { 54 | Desc: "word", 55 | Chunks: []string{"one\n"}, 56 | Echo: []string{"o", "n", "e", "\r\n"}, 57 | }, 58 | { 59 | Desc: "backspace", 60 | Chunks: []string{"spee\bll"}, 61 | Echo: []string{"s", "p", "e", "e", "\b \b", "l", "l"}, 62 | Output: []string{"spell"}, 63 | }, 64 | { 65 | Desc: "bksp start", 66 | Chunks: []string{"\b\bbkx\bsp"}, 67 | Echo: []string{"b", "k", "x", "\b \b", "s", "p"}, 68 | Output: []string{"bksp"}, 69 | }, 70 | { 71 | Desc: "bksp lines", 72 | Chunks: []string{"\b\bbkx\bsp\ntext\b\bst"}, 73 | Output: []string{"bksp", "\n", "test"}, 74 | }, 75 | { 76 | Desc: "bksp start chars", 77 | Chunks: []string{"\b", "b", "k", "s", "p", "\n"}, 78 | Output: []string{"bksp", "\n"}, 79 | }, 80 | { 81 | Desc: "escape only", 82 | Chunks: []string{"\x1b"}, 83 | Echo: []string{}, // EOF before escape completes won't echo 84 | Output: []string{"\x1b"}, 85 | }, 86 | { 87 | Desc: "escape non-CSI", 88 | Chunks: []string{"\x1b0"}, 89 | Echo: []string{"\x1b", "0"}, 90 | Output: []string{"\x1b0"}, 91 | }, 92 | { 93 | Desc: "escape embedded", 94 | Chunks: []string{"one\x1btwo"}, 95 | Echo: []string{"o", "n", "e", "\x1b", "t", "w", "o"}, 96 | Output: []string{"one\x1btwo"}, 97 | }, 98 | { 99 | Desc: "esc BS", 100 | Chunks: []string{"one\x1b\b\btwo"}, 101 | Output: []string{"ontwo"}, 102 | }, 103 | { 104 | Desc: "unknown seq", 105 | Chunks: []string{"\x1b[5G"}, // CHA[5] 106 | Echo: []string{}, // Well-formed escapes, even unknown, aren't echoed 107 | Output: []string{"\x1b[5G"}, // but they are outputted 108 | }, 109 | { 110 | Desc: "unknown seq inline", 111 | Chunks: []string{"on\x1b[5Ge"}, 112 | Echo: []string{"o", "n", "e"}, 113 | Output: []string{"on\x1b[5Ge"}, 114 | }, 115 | { 116 | Desc: "up", 117 | Chunks: []string{"one\n\x1b[Atwo\n"}, 118 | Echo: []string{ 119 | "o", "n", "e", "\r\n", 120 | "one", 121 | "t", "w", "o", "\r\n", 122 | }, 123 | Output: []string{"one", "\n", "onetwo", "\n"}, 124 | }, 125 | { 126 | Desc: "zero up", 127 | Chunks: []string{"0\n\x1b[A1"}, 128 | Echo: []string{"0", "\r\n", "0", "1"}, 129 | Output: []string{"0", "\n", "01"}, 130 | }, 131 | { 132 | Desc: "up noop", 133 | Chunks: []string{"y\x1b[A", "x"}, 134 | Echo: []string{"y", "x"}, 135 | Output: []string{"yx"}, 136 | }, 137 | { 138 | Desc: "late up", 139 | Chunks: []string{"one\ntwo\x1b[A\n"}, 140 | Echo: []string{ 141 | "o", "n", "e", "\r\n", 142 | "t", "w", "o", 143 | "\b\b\bone", "\r\n", 144 | }, 145 | Output: []string{"one", "\n", "one", "\n"}, 146 | }, 147 | { 148 | Desc: "up up", 149 | Chunks: []string{"one\n\x1b[Atwo\x1b[Athree\n"}, 150 | Echo: []string{ 151 | "o", "n", "e", "\r\n", 152 | "one", "t", "w", "o", 153 | "\b\b\b\b\b\bone \b\b\b", 154 | "t", "h", "r", "e", "e", "\r\n"}, 155 | Output: []string{"one", "\n", "onethree", "\n"}, 156 | }, 157 | { 158 | Desc: "left", 159 | Chunks: []string{ 160 | "abcde", 161 | "\x1b[D", // LEFT 162 | }, 163 | Echo: []string{ 164 | "a", "b", "c", "d", "e", 165 | "\x1b[D", 166 | }, 167 | Output: []string{"abcde"}, 168 | }, 169 | { 170 | Desc: "left noop", 171 | Chunks: []string{ 172 | "\x1b[D", // LEFT 173 | "abcde", 174 | }, 175 | Echo: []string{ 176 | "a", "b", "c", "d", "e", 177 | }, 178 | Output: []string{"abcde"}, 179 | }, 180 | { 181 | Desc: "left insert", 182 | Chunks: []string{ 183 | "abc", 184 | "\x1b[D", // LEFT 185 | "d", 186 | }, 187 | Echo: []string{ 188 | "a", "b", "c", 189 | "\x1b[D", 190 | "dc\b", 191 | }, 192 | Output: []string{"abdc"}, 193 | }, 194 | { 195 | Desc: "left bksp", 196 | Chunks: []string{ 197 | "abcd", 198 | "\x1b[D", // LEFT 199 | "\x1b[D", // LEFT 200 | "\b", 201 | }, 202 | Echo: []string{ 203 | "a", "b", "c", "d", 204 | "\x1b[D", 205 | "\x1b[D", 206 | "\bcd \b\b\b", 207 | }, 208 | Output: []string{"acd"}, 209 | }, 210 | { 211 | Desc: "left noop insert", 212 | Chunks: []string{ 213 | "a", 214 | "\x1b[D", // LEFT 215 | "\x1b[D", // LEFT 216 | "b", 217 | }, 218 | Echo: []string{ 219 | "a", 220 | "\x1b[D", 221 | "ba\b", 222 | }, 223 | Output: []string{"ba"}, 224 | }, 225 | { 226 | Desc: "right noop", 227 | Chunks: []string{ 228 | "abc", 229 | "\x1b[C", // RIGHT 230 | }, 231 | Echo: []string{ 232 | "a", "b", "c", 233 | }, 234 | Output: []string{"abc"}, 235 | }, 236 | { 237 | Desc: "left right", 238 | Chunks: []string{ 239 | "ab", 240 | "\x1b[D", // LEFT 241 | "\x1b[C", // RIGHT 242 | "c", 243 | }, 244 | Echo: []string{ 245 | "a", "b", 246 | "\x1b[D", // LEFT 247 | "\x1b[C", // RIGHT 248 | "c", 249 | }, 250 | Output: []string{"abc"}, 251 | }, 252 | { 253 | Desc: "left right right", 254 | Chunks: []string{ 255 | "01234", 256 | "\x1b[D", // LEFT 257 | "\x1b[D", // LEFT 258 | "\x1b[D", // LEFT 259 | "\x1b[C", // RIGHT 260 | "\x1b[C", // RIGHT 261 | "X", 262 | }, 263 | Echo: []string{ 264 | "0", "1", "2", "3", "4", 265 | "\x1b[D", // LEFT 266 | "\x1b[D", // LEFT 267 | "\x1b[D", // LEFT 268 | "\x1b[C", // RIGHT 269 | "\x1b[C", // RIGHT 270 | "X4\b", 271 | }, 272 | Output: []string{"0123X4"}, 273 | }, 274 | { 275 | Desc: "left left down", 276 | Chunks: []string{ 277 | "abc", 278 | "\x1b[D", // LEFT 279 | "\x1b[D", // LEFT 280 | "\x1b[B", // DOWN 281 | }, 282 | Echo: []string{ 283 | "a", "b", "c", 284 | "\x1b[D", 285 | "\x1b[D", 286 | "bc", 287 | }, 288 | Output: []string{"abc"}, 289 | }, 290 | { 291 | Desc: "left up", 292 | Chunks: []string{ 293 | "qwerty\nabc", 294 | "\x1b[D", // LEFT 295 | "\x1b[A", // UP 296 | "!", 297 | }, 298 | Echo: []string{ 299 | "q", "w", "e", "r", "t", "y", "\r\n", 300 | "a", "b", "c", 301 | "\x1b[D", 302 | "\b\bqwerty", 303 | "!", 304 | }, 305 | Output: []string{"qwerty", "\n", "qwerty!"}, 306 | }, 307 | } 308 | 309 | // TestTerm test up to 1000 reads of up to 4096 bytes each per testcase. 310 | func TestTerm(t *testing.T) { 311 | for _, test := range termTests { 312 | desc := test.Desc 313 | done := make(chan bool) 314 | pipe := NewDoublePipe() 315 | tty := NewTTY(pipe.Remote) 316 | 317 | go VerifyReads(t, desc, "read", tty, test.Output, done) 318 | go VerifyReads(t, desc, "echo", pipe.Local, test.Echo, done) 319 | 320 | for _, chunk := range test.Chunks { 321 | if _, err := io.WriteString(pipe.Local, chunk); err != nil { 322 | t.Errorf("%s: write(%q): %s", desc, chunk, err) 323 | } 324 | } 325 | 326 | pipe.Local.Close() 327 | <-done 328 | 329 | pipe.Remote.Close() 330 | <-done 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /term/term_line.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | // hpush (history push) stores the line for later reuse if it 18 | // is not an escape sequence and contains characters. 19 | // 20 | // Side effects: (only if output is nonzero and not an escape sequence) 21 | // - t.last will contain a copy of output 22 | func (t *TTY) hpush() { 23 | if len(t.output) == 0 || t.output[0] < 32 { 24 | return 25 | } 26 | t.last = make([]byte, len(t.output)) 27 | copy(t.last, t.output) 28 | } 29 | 30 | // hprev (history previous) replaces the current output with the last 31 | // saved line (unless no line has been saved). 32 | // 33 | // To echo the new line, the following is written: 34 | // 35 | // Where is the new output and are present if the 36 | // previous line was long enough to require them to not leave dangling letters, 37 | // and is enough backspace characters to get to the beginning of the 38 | // current line of text. 39 | // 40 | // Preconditions: 41 | // - Must be called within an escape sequence 42 | // Side effects: 43 | // - t.output will contain a copy of t.last or will contain preescape 44 | // - t.preescape will be nil 45 | func (t *TTY) hprev() { 46 | if len(t.last) == 0 { 47 | t.output = t.preescape 48 | t.preescape = nil 49 | return 50 | } 51 | 52 | t.output = make([]byte, len(t.last)) 53 | copy(t.output, t.last) 54 | 55 | width := len(t.preescape) 56 | t.preescape = nil 57 | 58 | home := width 59 | if t.linepos >= 0 { 60 | home = t.linepos 61 | } 62 | t.linepos = -1 63 | 64 | if t.screen != nil { 65 | size, delta := home+len(t.output), width-len(t.output) 66 | if delta > 0 { 67 | size += 2 * delta 68 | } 69 | overwrite := make([]byte, size) 70 | for i := 0; i < home; i++ { 71 | overwrite[i] = '\b' 72 | } 73 | copy(overwrite[home:], t.output) 74 | for i := len(t.output); i < width; i++ { 75 | overwrite[home+i] = ' ' 76 | overwrite[home+i+delta] = '\b' 77 | } 78 | t.echo(overwrite...) 79 | } 80 | } 81 | 82 | // linechar processes the next character of input in line mode. 83 | // 84 | // If ch is ESC, it begins a new escape sequence by storing the current output 85 | // into preescape and creating a new 8-cap byte slice for the escape sequence. 86 | // 87 | // If ch is a low nonprinting character, the current output is written and then 88 | // the control character is written by itself. This is to allow easy detection 89 | // of things like ^C and ^D. 90 | // 91 | // If ch is BS (and there are characters in output), the length of output is 92 | // shortened by one and a "\b \b" sequence is echoed to blank the space on the 93 | // console. 94 | // 95 | // If ch is carriage return or newline (some terminals emit one, some emit the 96 | // other), the output is written and then a the character is written, but in 97 | // both cases a CRLF is echoed. 98 | // 99 | // If ch is anything else (basicaly a printing character), it is echoed and 100 | // appended to output. 101 | // 102 | // Side Effects (possible): 103 | // - t.preescape points to a new/different slice 104 | // - t.output points to a new/different slice or has changed 105 | // - t.next has data sent over it 106 | // - hpush() is called 107 | func (t *TTY) linechar(ch byte) { 108 | switch ch { 109 | case ESC: 110 | if len(t.output) > 0 { 111 | t.preescape = t.output 112 | t.output = make([]byte, 0, 8) 113 | } 114 | t.output = append(t.output, ESC) 115 | case '\r', '\n': 116 | t.echo('\r', '\n') 117 | t.hpush() 118 | fallthrough 119 | case SOH, STX, ETX, EOT, ENQ, ACK, BEL, VT, FF, SO, SI, DLE, DC1, 120 | DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, FS, GS, RS, US: 121 | t.emit() 122 | t.next <- []byte{ch} 123 | case BS, DEL: 124 | if len(t.output) == 0 || t.linepos == 0 { 125 | break 126 | } 127 | if t.linepos > 0 { 128 | // Delete onscreen 129 | if t.screen != nil { 130 | delta := len(t.output) - t.linepos 131 | overwrite := make([]byte, 1+1+2*delta+1) 132 | overwrite[0] = ch 133 | copy(overwrite[1:], t.output[t.linepos:]) 134 | overwrite[1+delta] = ' ' 135 | for i := 0; i < delta+1; i++ { 136 | overwrite[2+delta+i] = '\b' 137 | } 138 | t.echo(overwrite...) 139 | } 140 | // Delete from output 141 | t.output = append(t.output[:t.linepos-1], t.output[t.linepos:]...) 142 | t.linepos-- 143 | break 144 | } 145 | t.echo(ch, ' ', ch) 146 | t.output = t.output[:len(t.output)-1] 147 | default: 148 | if t.linepos >= 0 { 149 | // Insert on screen 150 | if t.screen != nil { 151 | delta := len(t.output) - t.linepos 152 | overwrite := make([]byte, 1+2*delta) 153 | overwrite[0] = ch 154 | copy(overwrite[1:], t.output[t.linepos:]) 155 | for i := 0; i < delta; i++ { 156 | overwrite[1+delta+i] = '\b' 157 | } 158 | t.echo(overwrite...) 159 | } 160 | // Insert into output 161 | t.output = append(t.output[:t.linepos], 162 | append([]byte{ch}, t.output[t.linepos:]...)...) 163 | t.linepos++ 164 | break 165 | } 166 | t.echo(ch) 167 | t.output = append(t.output, ch) 168 | } 169 | } 170 | 171 | // lineesc processes the next character from a potential escape sequence in 172 | // line mode. 173 | // 174 | // If the second character is not [, then the original output is restored and 175 | // the queued bytes are echoed and the character is processed by char() 176 | // 177 | // The escape sequence ends with the first "printing" character (@ to ~) after 178 | // the [ sequence, and that character indicates the action. The following 179 | // actions are known: 180 | // A - Up 181 | // B - Down 182 | // C - Right 183 | // D - Left 184 | // ~ - PageUp/PageDown 185 | // These have optional arguments before them, which are all currently ignored. 186 | // Most of them don't do anything, but these known escape sequences are not 187 | // written out. If the escape sequence is not known, however, the original 188 | // output is restored with the escape sequence appended. 189 | // Up - loads the last saved line 190 | // Down - goes to the end of the current line 191 | // Left - goes one character closer to the beginning of the line 192 | // Right - goes one character closer to the end of the line 193 | // 194 | // Side Effects: (possible) 195 | // - t.output refers to a new/different slice 196 | // - t.preescape refers to a new/different slice or nil 197 | // - char() is called 198 | func (t *TTY) lineesc(ch byte) { 199 | if len(t.output) == 1 { 200 | if ch != '[' { 201 | t.echo(t.output...) 202 | t.output = append(t.preescape, t.output...) 203 | t.preescape = nil 204 | t.linechar(ch) 205 | } else { 206 | t.output = append(t.output, ch) 207 | } 208 | return 209 | } 210 | t.output = append(t.output, ch) 211 | if ch >= '@' && ch <= '~' { 212 | switch ch { 213 | case 'A': // up 214 | t.hprev() 215 | return 216 | case 'B': // down 217 | if t.linepos < 0 { 218 | break 219 | } 220 | t.echo(t.preescape[t.linepos:]...) 221 | t.linepos = -1 222 | case 'C': // right 223 | if len(t.preescape) == 0 { 224 | break 225 | } 226 | if t.linepos < 0 { 227 | break 228 | } 229 | t.echo(t.output...) 230 | t.linepos++ 231 | if t.linepos == len(t.preescape) { 232 | t.linepos = -1 233 | } 234 | case 'D': // left 235 | if len(t.preescape) == 0 { 236 | break 237 | } 238 | if t.linepos < 0 { 239 | t.linepos = len(t.preescape) 240 | } 241 | if t.linepos > 0 { 242 | t.echo(t.output...) 243 | t.linepos-- 244 | } 245 | case '~': // pgup(5~)/dn(6~) 246 | default: 247 | t.output = append(t.preescape, t.output...) 248 | t.preescape = nil 249 | return 250 | } 251 | t.output = t.preescape 252 | t.preescape = nil 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /termios/termios.go: -------------------------------------------------------------------------------- 1 | // +build linux darwin 2 | 3 | // Copyright 2013 Google, Inc. All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // Package termios implements low-level terminal settings. 18 | package termios 19 | 20 | import ( 21 | "fmt" 22 | "syscall" 23 | "unsafe" 24 | ) 25 | 26 | /* 27 | #include 28 | #include 29 | */ 30 | import "C" 31 | 32 | type ( 33 | inMode C.tcflag_t 34 | outMode C.tcflag_t 35 | ctlMode C.tcflag_t 36 | locMode C.tcflag_t 37 | charIndex C.cc_t 38 | ) 39 | 40 | // Input Flags 41 | const ( 42 | IGNBRK inMode = C.IGNBRK // ignore BREAK condition 43 | BRKINT inMode = C.BRKINT // map BREAK to SIGINTR 44 | IGNPAR inMode = C.IGNPAR // ignore (discard) parity errors 45 | PARMRK inMode = C.PARMRK // mark parity and framing errors 46 | INPCK inMode = C.INPCK // enable checking of parity errors 47 | ISTRIP inMode = C.ISTRIP // strip 8th bit off chars 48 | INLCR inMode = C.INLCR // map NL into CR 49 | IGNCR inMode = C.IGNCR // ignore CR 50 | ICRNL inMode = C.ICRNL // map CR to NL (ala CRMOD) 51 | IXON inMode = C.IXON // enable output flow control 52 | IXOFF inMode = C.IXOFF // enable input flow control 53 | IXANY inMode = C.IXANY // any char will restart after stop 54 | IMAXBEL inMode = C.IMAXBEL // ring bell on input queue full 55 | IUTF8 inMode = C.IUTF8 // maintain state for UTF-8 VERASE 56 | ) 57 | 58 | // Output Flags 59 | const ( 60 | OPOST outMode = C.OPOST // enable following output processing 61 | ONLCR outMode = C.ONLCR // map NL to CR-NL (ala CRMOD) 62 | OCRNL outMode = C.OCRNL // map CR to NL on output 63 | ONOCR outMode = C.ONOCR // no CR output at column 0 64 | ONLRET outMode = C.ONLRET // NL performs CR function 65 | OFILL outMode = C.OFILL // use fill characters for delay 66 | NLDLY outMode = C.NLDLY // \n delay 67 | TABDLY outMode = C.TABDLY // horizontal tab delay 68 | CRDLY outMode = C.CRDLY // \r delay 69 | FFDLY outMode = C.FFDLY // form feed delay 70 | BSDLY outMode = C.BSDLY // \b delay 71 | VTDLY outMode = C.VTDLY // vertical tab delay 72 | OFDEL outMode = C.OFDEL // fill is DEL, else NUL 73 | ) 74 | 75 | // Control Flags 76 | const ( 77 | CSIZE ctlMode = C.CSIZE // character size mask 78 | CS6 ctlMode = C.CS6 // 6 bits 79 | CS7 ctlMode = C.CS7 // 7 bits 80 | CS8 ctlMode = C.CS8 // 8 bits 81 | CSTOPB ctlMode = C.CSTOPB // send 2 stop bits 82 | CREAD ctlMode = C.CREAD // enable receiver 83 | PARENB ctlMode = C.PARENB // parity enable 84 | PARODD ctlMode = C.PARODD // odd parity, else even 85 | HUPCL ctlMode = C.HUPCL // hang up on last close 86 | CLOCAL ctlMode = C.CLOCAL // ignore modem status lines 87 | ) 88 | 89 | // Local flags 90 | const ( 91 | ECHOKE locMode = C.ECHOKE // visual erase for line kill 92 | ECHOE locMode = C.ECHOE // visually erase chars 93 | ECHOK locMode = C.ECHOK // echo NL after line kill 94 | ECHO locMode = C.ECHO // enable echoing 95 | ECHONL locMode = C.ECHONL // echo NL even if ECHO is off 96 | ECHOPRT locMode = C.ECHOPRT // visual erase mode for hardcopy 97 | ECHOCTL locMode = C.ECHOCTL // echo control chars as ^(Char) 98 | ISIG locMode = C.ISIG // enable signals INTR, QUIT, [D]SUSP 99 | ICANON locMode = C.ICANON // canonicalize input lines 100 | IEXTEN locMode = C.IEXTEN // enable DISCARD and LNEXT 101 | EXTPROC locMode = C.EXTPROC // external processing 102 | TOSTOP locMode = C.TOSTOP // stop background jobs from output 103 | FLUSHO locMode = C.FLUSHO // output being flushed (state) 104 | PENDIN locMode = C.PENDIN // XXX retype pending input (state) 105 | NOFLSH locMode = C.NOFLSH // don't flush after interrupt 106 | ) 107 | 108 | // Control Character Indices 109 | const ( 110 | VEOF charIndex = C.VEOF // ICANON 111 | VEOL charIndex = C.VEOL // ICANON 112 | VEOL2 charIndex = C.VEOL2 // ICANON together with IEXTEN 113 | VERASE charIndex = C.VERASE // ICANON 114 | VWERASE charIndex = C.VWERASE // ICANON together with IEXTEN 115 | VKILL charIndex = C.VKILL // ICANON 116 | VREPRINT charIndex = C.VREPRINT // ICANON together with IEXTEN 117 | VINTR charIndex = C.VINTR // ISIG 118 | VQUIT charIndex = C.VQUIT // ISIG 119 | VSUSP charIndex = C.VSUSP // ISIG 120 | VSTART charIndex = C.VSTART // IXON, IXOFF 121 | VSTOP charIndex = C.VSTOP // IXON, IXOFF 122 | VLNEXT charIndex = C.VLNEXT // IEXTEN 123 | VDISCARD charIndex = C.VDISCARD // IEXTEN 124 | VMIN charIndex = C.VMIN // !ICANON 125 | VTIME charIndex = C.VTIME // !ICANON 126 | NCC charIndex = C.NCCS // Number of control chars 127 | ) 128 | 129 | // TermSettings contain both the original settings from when it was created 130 | // and the current settings being manipulated. At any time, Reset will 131 | // restore the terminal to its original state. 132 | type TermSettings struct { 133 | fd int 134 | original C.struct_termios 135 | current C.struct_termios 136 | } 137 | 138 | // NewTermSettings examines the state of the current terminal and 139 | // stores it in a fresh TermSettings. 140 | func NewTermSettings(fd int) (*TermSettings, error) { 141 | tio := &TermSettings{fd: fd} 142 | 143 | if ret, errno := C.tcgetattr(C.int(fd), &tio.current); ret != 0 { 144 | return nil, errno 145 | } 146 | tio.original = tio.current 147 | return tio, nil 148 | } 149 | 150 | // Char returns the rune associated with the given control 151 | // character. These will generally be ASCII control characters. 152 | func (tio *TermSettings) Char(idx charIndex) rune { 153 | return rune(tio.current.c_cc[int(idx)]) 154 | } 155 | 156 | // String returns a debugging string which contains low-level 157 | // information about the terminal. 158 | func (tio *TermSettings) String() string { 159 | return fmt.Sprintf(`Terminal[%d]: 160 | Input = 0x%X 161 | Output = 0x%X 162 | Control = 0x%X 163 | Local = 0x%X 164 | Chars = %v 165 | `, 166 | tio.fd, 167 | tio.current.c_iflag, 168 | tio.current.c_oflag, 169 | tio.current.c_cflag, 170 | tio.current.c_lflag, 171 | tio.current.c_cc) 172 | } 173 | 174 | // GetSize attempts to determine the size of the terminal with which 175 | // this TermSettings is associated and return the number of rows (the height) 176 | // and the number of columns (width). 177 | func (tio *TermSettings) GetSize() (width, height int, err error) { 178 | var ws C.struct_winsize 179 | _, _, errno := syscall.RawSyscall(syscall.SYS_IOCTL, 180 | uintptr(tio.fd), 181 | uintptr(syscall.TIOCGWINSZ), 182 | uintptr(unsafe.Pointer(&ws))) 183 | if errno != 0 { 184 | return 0, 0, syscall.Errno(errno) 185 | } 186 | height = int(ws.ws_row) 187 | width = int(ws.ws_col) 188 | return 189 | } 190 | 191 | // Raw sets the terminal to a very minimal raw mode suitable for simulating a 192 | // terminal emulator or doing raw line editing. 193 | // 194 | // The changes are applied immediately. 195 | // 196 | // I recommend this being done early on in main() and having a deferred call to 197 | // tio.Reset so that the changes will be reverted when everything exits 198 | // cleanly. 199 | func (tio *TermSettings) Raw() error { 200 | //tio.SetInput(IGNBRK | IXANY) 201 | //tio.SetOutput(0) 202 | //tio.SetLocal(0) 203 | C.cfmakeraw(&tio.current) 204 | return tio.Apply() 205 | } 206 | 207 | // Reset sets the terminal settings to match those that were in effect when the 208 | // call to NewTermSettings was made. 209 | func (tio *TermSettings) Reset() error { 210 | tio.current = tio.original 211 | return tio.Apply() 212 | } 213 | 214 | func (tio *TermSettings) SetInput(mode inMode) { tio.current.c_iflag = C.tcflag_t(mode) } 215 | func (tio *TermSettings) SetOutput(mode outMode) { tio.current.c_oflag = C.tcflag_t(mode) } 216 | func (tio *TermSettings) SetControl(mode ctlMode) { tio.current.c_cflag = C.tcflag_t(mode) } 217 | func (tio *TermSettings) SetLocal(mode locMode) { tio.current.c_lflag = C.tcflag_t(mode) } 218 | 219 | // Apply applies the settings currently stored in tio. This is mostly useful 220 | // for maintaining multiple TerminalSettings for different modes, and you can 221 | // simply Apply whichever you need. 222 | func (tio *TermSettings) Apply() error { 223 | const when = C.TCSANOW 224 | if ret, errno := C.tcsetattr(C.int(tio.fd), when, &tio.current); ret != 0 { 225 | return errno 226 | } 227 | return nil 228 | } 229 | 230 | /* 231 | Cooked: 232 | Input = 0x00002B02 233 | Output = 0x00000003 234 | Control = 0x00004B00 235 | Local = 0x200005CB 236 | 237 | Raw: 238 | 239 | iIGNBRK + 0x00000001 // ignore BREAK condition 240 | iIXANY + 0x00000800 // any char will restart after stop 241 | Input = 0x00000801 242 | 243 | oONLCR + 0x00000002 // map NL to CR-NL (ala CRMOD) 244 | Output = 0x00000002 245 | 246 | lECHOKE + 0x00000001 // visual erase for line kill 247 | lECHOCTL + 0x00000040 // echo control chars as ^(Char) 248 | Local = 0x00000041 249 | */ 250 | -------------------------------------------------------------------------------- /term/term.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Google, Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package term 16 | 17 | import ( 18 | "io" 19 | "sync" 20 | ) 21 | 22 | // The following constants are provided for your own edification; they are the 23 | // internal defaults and cannot be changed. 24 | const ( 25 | ReadBufferLength = 32 26 | DefaultLineBufferSize = 32 27 | DefaultRawBufferSize = 256 28 | DefaultFrameBufferSize = 8 29 | ) 30 | 31 | type ttyMode int 32 | 33 | // The following constants are the modes in which the TTY can be set 34 | const ( 35 | Raw ttyMode = iota // All reads are passed through 36 | Line // Basic line-editing capabilities are provided 37 | Frame // Basic screen-editing capabilities are provided 38 | ) 39 | 40 | // A TTY is a simple interface for reading input from a user over a raw 41 | // terminal emulation interface. 42 | // 43 | // All methods on TTY are goroutine-safe (though calling Read concurrently 44 | // is probably not the most deterministic thing in the world to do). 45 | type TTY struct { 46 | // IO 47 | console io.Reader 48 | screen io.Writer 49 | 50 | // Synchronization and reading 51 | next chan []byte // Completed chunks (usually lines) 52 | partial []byte // Store partial reads 53 | lock sync.RWMutex // Synchronize multiple readers (locks partial) 54 | error error // The error when the reader closed 55 | update chan chan bool // Take ownership of the IO and Settings data 56 | 57 | // Settings 58 | mode ttyMode // The current mode of the TTY 59 | bsize int // Initial line buffer size 60 | 61 | // State (Line mode) 62 | buffer []byte // The last read from console 63 | output []byte // The pending line/chunk 64 | last []byte // The last line/chunk (used for prevline) 65 | preescape []byte // The contents of output before the escape sequence 66 | linepos int // >= 0 if doing in-place line editing 67 | 68 | // State (Frame mode) 69 | regions []*Region 70 | active int 71 | } 72 | 73 | // NewTTY creates a new TTY for interacting with a user via a limited 74 | // line-oriented interface. If the given reader is also an io.Writer, 75 | // interactive echo is enabled. 76 | func NewTTY(console io.Reader) *TTY { 77 | t := &TTY{ 78 | console: console, 79 | next: make(chan []byte, ReadBufferLength), 80 | mode: Line, 81 | bsize: DefaultLineBufferSize, 82 | update: make(chan chan bool), 83 | } 84 | 85 | t.screen, _ = console.(io.Writer) 86 | 87 | go t.run() 88 | return t 89 | } 90 | 91 | // NewFrameTTY creates a new TTY for interacting with a user via a 92 | // screen-oriented interface. If the given reader is also an io.Writer, 93 | // interactive echo is enabled. 94 | // 95 | // A TTY created with NewFrameTTY has synchronized reads, so further input is 96 | // not processed until the chunk has been read. The default read buffer size 97 | // for a Frame TTY is much smaller than the others. 98 | // 99 | // The default region for a new Frame is an 80x24 region with the initial 100 | // cursor placed in the upper right-hand corner. This region is returned, 101 | // but will not have been been drawn (e.g. its settings can be changed). 102 | func NewFrameTTY(console io.ReadWriter) (*TTY, *Region) { 103 | t := &TTY{ 104 | console: console, 105 | screen: console, 106 | next: make(chan []byte), 107 | mode: Frame, 108 | bsize: DefaultFrameBufferSize, 109 | update: make(chan chan bool), 110 | } 111 | 112 | go t.run() 113 | r := t.NewRegion(80, 24, 0, 0) 114 | return t, r 115 | } 116 | 117 | // NewRawTTY creates a new TTY without line editing and with a larger potential 118 | // input buffer size, and with no interactive echo. 119 | func NewRawTTY(console io.Reader) *TTY { 120 | t := &TTY{ 121 | console: console, 122 | next: make(chan []byte, ReadBufferLength), 123 | bsize: DefaultRawBufferSize, 124 | update: make(chan chan bool), 125 | } 126 | 127 | go t.run() 128 | return t 129 | } 130 | 131 | // SetEcho enables or disables interactive echo, sending all writes on the 132 | // given writer. Whether the echo writer is specified here or inferred in 133 | // NewTTY, any write error will disable echo. Providing nil to SetEcho 134 | // disables interactive echo. 135 | func (t *TTY) SetEcho(echo io.Writer) { 136 | lock := make(chan bool, 1) 137 | t.update <- lock 138 | t.screen = echo 139 | lock <- true 140 | } 141 | 142 | // SetLineBuffer sets the initial line buffer size. In general, you shouldn't 143 | // need to change this, as the line buffer will continue to grow if the line is 144 | // really long, but if you find that you have lots of really long lines it 145 | // might help reduce garbage. 146 | func (t *TTY) SetLineBuffer(size int) { 147 | lock := make(chan bool, 1) 148 | t.update <- lock 149 | t.bsize = size 150 | lock <- true 151 | } 152 | 153 | // SetMode sets the TTY mode. 154 | // 155 | // Raw: No line buffering is performed, and data is written exactly as it is 156 | // received, including control sequences. The input is not broken up into 157 | // logical units, reads are passed through directly. In the case of an 158 | // interactive session, this will often be broken up into individual characters 159 | // or control sequences, not lines or words. 160 | // 161 | // Line: Basic line-buffering is performed. See the package comment. 162 | // 163 | // Frame: Basic screen-editing is enabled. Currently the same as Line. 164 | // 165 | // Switching modes will suspend any state tracking for the old mode. Switching 166 | // back will resume with the state where it was before the mode was changed, 167 | // but this may result in unforseen side effects. Changing modes does not 168 | // effect the line buffer size or whether reads are synchronous, as is the case 169 | // for TTYs created explicitly in a certain mode. It should not usually be 170 | // necessary to change modes. 171 | func (t *TTY) SetMode(mode ttyMode) { 172 | lock := make(chan bool, 1) 173 | t.update <- lock 174 | t.mode = mode 175 | lock <- true 176 | } 177 | 178 | // echo echoes the bytes if interactive editing is enabled 179 | // 180 | // Side effects: 181 | // - If there is a write error, interactive editing is disabled 182 | func (t *TTY) echo(b ...byte) { 183 | if t.screen != nil { 184 | if _, err := t.screen.Write(b); err != nil { 185 | t.screen = nil 186 | } 187 | } 188 | } 189 | 190 | // yield gives the chance for an update to proceed 191 | // 192 | // Side effects: 193 | // - anything 194 | func (t *TTY) yield() { 195 | select { 196 | case done := <-t.update: 197 | <-done 198 | default: 199 | } 200 | } 201 | 202 | // emit sends the contents of t.output over the t.next channel, optionally 203 | // prefixing it with the preescape if any. Nothing is done if the length of 204 | // output (including preescape) is zero. 205 | // 206 | // Side effects: 207 | // - t.output refers to a newly allocated zero-length slice (with capacity t.bsize) 208 | // - t.preescape is nil 209 | // - the output is written to t.next 210 | func (t *TTY) emit() { 211 | if len(t.preescape) > 0 { 212 | t.output = append(t.preescape, t.output...) 213 | t.preescape = nil 214 | } 215 | if len(t.output) > 0 { 216 | t.next <- t.output 217 | t.output = make([]byte, 0, t.bsize) 218 | t.linepos = -1 219 | } 220 | } 221 | 222 | // run is the primary reading goroutine. It reads chunks from the console, and processes them 223 | // or (if not in cooked mode) outputs them directly. Before each read, it gives the setter 224 | // methods the opportunity to pause it while they poke at the TTY internals. This is not 225 | // necessary for reading, which takes data directly from the next channel. 226 | func (t *TTY) run() { 227 | defer close(t.next) 228 | 229 | t.buffer = make([]byte, t.bsize) 230 | t.output = make([]byte, 0, t.bsize) 231 | t.linepos = -1 232 | 233 | for { 234 | t.yield() 235 | n, err := t.console.Read(t.buffer) 236 | if err != nil { 237 | t.emit() 238 | t.error = err 239 | return 240 | } 241 | t.yield() 242 | 243 | switch t.mode { 244 | case Raw: 245 | t.next <- t.buffer[:n] 246 | case Line, Frame: 247 | // Process each character that was read 248 | for _, ch := range t.buffer[:n] { 249 | if len(t.output) > 0 && t.output[0] == ESC { 250 | t.lineesc(ch) 251 | } else { 252 | t.linechar(ch) 253 | } 254 | } 255 | } 256 | } 257 | } 258 | 259 | // Read reads the next line, chunk, control sequence, etc from the console. 260 | func (t *TTY) Read(b []byte) (n int, err error) { 261 | t.lock.Lock() 262 | defer t.lock.Unlock() 263 | 264 | var ok bool 265 | if len(t.partial) == 0 { 266 | if t.partial, ok = <-t.next; !ok { 267 | return 0, t.error 268 | } 269 | } 270 | 271 | n = copy(b, t.partial) 272 | t.partial = t.partial[n:] 273 | return 274 | } 275 | 276 | // Write writes to the same io.Writer that is handing the interactive echo. If 277 | // interactive echo is disabled (either directly or because an echo write 278 | // failed) Write will return EOF. 279 | func (t *TTY) Write(b []byte) (n int, err error) { 280 | w := t.screen 281 | if w == nil { 282 | return 0, io.EOF 283 | } 284 | return w.Write(b) 285 | } 286 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------