parser_handler.go 2.1 KB

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