| 1 | package ansi |
| 2 | |
| 3 | import "unsafe" |
| 4 | |
| 5 | // Params represents a list of packed parameters. |
| 6 | type Params []Param |
| 7 | |
| 8 | // Param returns the parameter at the given index and if it is part of a |
| 9 | // sub-parameters. It falls back to the default value if the parameter is |
| 10 | // missing. If the index is out of bounds, it returns the default value and |
| 11 | // false. |
| 12 | func (p Params) Param(i, def int) (int, bool, bool) { |
| 13 | if i < 0 || i >= len(p) { |
| 14 | return def, false, false |
| 15 | } |
| 16 | return p[i].Param(def), p[i].HasMore(), true |
| 17 | } |
| 18 | |
| 19 | // ForEach iterates over the parameters and calls the given function for each |
| 20 | // parameter. If a parameter is part of a sub-parameter, it will be called with |
| 21 | // hasMore set to true. |
| 22 | // Use def to set a default value for missing parameters. |
| 23 | func (p Params) ForEach(def int, f func(i, param int, hasMore bool)) { |
| 24 | for i := range p { |
| 25 | f(i, p[i].Param(def), p[i].HasMore()) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // ToParams converts a list of integers to a list of parameters. |
| 30 | func ToParams(params []int) Params { |
| 31 | return unsafe.Slice((*Param)(unsafe.Pointer(¶ms[0])), len(params)) |
| 32 | } |
| 33 | |
| 34 | // Handler handles actions performed by the parser. |
| 35 | // It is used to handle ANSI escape sequences, control characters, and runes. |
| 36 | type Handler struct { |
| 37 | // Print is called when a printable rune is encountered. |
| 38 | Print func(r rune) |
| 39 | // Execute is called when a control character is encountered. |
| 40 | Execute func(b byte) |
| 41 | // HandleCsi is called when a CSI sequence is encountered. |
| 42 | HandleCsi func(cmd Cmd, params Params) |
| 43 | // HandleEsc is called when an ESC sequence is encountered. |
| 44 | HandleEsc func(cmd Cmd) |
| 45 | // HandleDcs is called when a DCS sequence is encountered. |
| 46 | HandleDcs func(cmd Cmd, params Params, data []byte) |
| 47 | // HandleOsc is called when an OSC sequence is encountered. |
| 48 | HandleOsc func(cmd int, data []byte) |
| 49 | // HandlePm is called when a PM sequence is encountered. |
| 50 | HandlePm func(data []byte) |
| 51 | // HandleApc is called when an APC sequence is encountered. |
| 52 | HandleApc func(data []byte) |
| 53 | // HandleSos is called when a SOS sequence is encountered. |
| 54 | HandleSos func(data []byte) |
| 55 | } |
| 56 | |
| 57 | // SetHandler sets the handler for the parser. |
| 58 | func (p *Parser) SetHandler(h Handler) { |
| 59 | p.handler = h |
| 60 | } |