diff --git a/ansi/sixel.go b/ansi/sixel.go new file mode 100644 index 00000000..b9b77ad6 --- /dev/null +++ b/ansi/sixel.go @@ -0,0 +1,73 @@ +package ansi + +import ( + "bytes" + "strconv" +) + +type SixelSequence struct { + PixelWidth int + PixelHeight int + ImageWidth int + ImageHeight int + PaletteString string + PixelString string +} + +var _ Sequence = &SixelSequence{} + +// Clone returns a copy of the DCS sequence. +func (s SixelSequence) Clone() Sequence { + return SixelSequence{ + PixelWidth: s.PixelWidth, + PixelHeight: s.PixelHeight, + ImageWidth: s.ImageWidth, + ImageHeight: s.ImageHeight, + PaletteString: s.PaletteString, + PixelString: s.PixelString, + } +} + +// String returns a string representation of the sequence. +// The string will always be in the 7-bit format i.e (ESC P p..p i..i f ESC \). +func (s SixelSequence) String() string { + return s.buffer().String() +} + +// Bytes returns the byte representation of the sequence. +// The bytes will always be in the 7-bit format i.e (ESC P p..p i..i F ESC \). +func (s SixelSequence) Bytes() []byte { + return s.buffer().Bytes() +} + +func (s SixelSequence) buffer() *bytes.Buffer { + var b bytes.Buffer + + b.WriteByte(ESC) + // P;;q + // a = pixel aspect ratio (deprecated) + // b = how to color unfilled pixels, 1 = transparent + // (0 means background color but terminals seem to draw it arbitrarily making it useless) + // c = horizontal grid size, I think everyone ignores this + b.WriteString("P0;1;0q") + // ";;; + // a = pixel width + // b = pixel height + // c = image width in pixels + // d = image height in pixels + b.WriteByte('"') + b.WriteString(strconv.Itoa(s.PixelWidth)) + b.WriteByte(';') + b.WriteString(strconv.Itoa(s.PixelHeight)) + b.WriteByte(';') + b.WriteString(strconv.Itoa(s.ImageWidth)) + b.WriteByte(';') + b.WriteString(strconv.Itoa(s.ImageHeight)) + b.WriteString(s.PaletteString) + b.WriteString(s.PixelString) + // ST + b.WriteByte(ESC) + b.WriteByte('\\') + + return &b +} diff --git a/ansi/sixel_test.go b/ansi/sixel_test.go new file mode 100644 index 00000000..601e7ee8 --- /dev/null +++ b/ansi/sixel_test.go @@ -0,0 +1,19 @@ +package ansi + +import "testing" + +func TestSixelSequence(t *testing.T) { + expectedResult := "\x1bP0;1;0q\"3;4;5;6PALETTEPIXELS\x1b\\" + result := (SixelSequence{ + PixelWidth: 3, + PixelHeight: 4, + ImageWidth: 5, + ImageHeight: 6, + PaletteString: "PALETTE", + PixelString: "PIXELS", + }).String() + if result != expectedResult { + t.Errorf("Expected sixel sequence to output %q but it output %q.", expectedResult, result) + return + } +}