tdewolff / canvas

Cairo in Go: vector to raster, SVG, PDF, EPS, WASM, OpenGL, Gio, etc.
MIT License
1.46k stars 96 forks source link

panic in RichText.ToText on initial and consecutive newlines #189

Closed arvidfm closed 1 year ago

arvidfm commented 1 year ago

Calling Context.DrawText with a TextBox containing a newline at the start of the text string, or multiple newlines in a row, results in a panic due to an index out of range error.

The offending line is here - apparently t.lines[j].spans ends up being nil here.

MWE:

func TestTextBox(t *testing.T) {
    c := canvas.New(100, 100)
    ctx := canvas.NewContext(c)
    font, err := canvas.LoadFontFile("/usr/share/fonts/liberation/LiberationSans-Bold.ttf", canvas.FontRegular)
    if err != nil {
        t.Fatal(err)
    }
    face := font.Face(12, canvas.Black)
    //ctx.DrawText(0, 0, canvas.NewTextBox(face, "\ntext", 100, 100, canvas.Left, canvas.Top, 0, 0))
    ctx.DrawText(0, 0, canvas.NewTextBox(face, "text\n\ntext2", 100, 100, canvas.Left, canvas.Top, 0, 0))
}

Output:

panic: runtime error: index out of range [-1] [recovered]
    panic: runtime error: index out of range [-1]

goroutine 6 [running]:
testing.tRunner.func1.2({0x916e60, 0xc000690d38})
    /usr/lib/go/src/testing/testing.go:1396 +0x24e
testing.tRunner.func1()
    /usr/lib/go/src/testing/testing.go:1399 +0x39f
panic({0x916e60, 0xc000690d38})
    /usr/lib/go/src/runtime/panic.go:884 +0x212
github.com/tdewolff/canvas.(*RichText).ToText(0xc0007b9da8, 0x4059000000000000, 0x4059000000000000, 0x0, 0x3, 0xc0002d80c0?, 0x0)
    /home/arvid/go/pkg/mod/github.com/tdewolff/canvas@v0.0.0-20221018191302-6bed7f464e8f/text.go:447 +0x2319
github.com/tdewolff/canvas.NewTextBox(0xc0001abef0?, {0x958135?, 0xb?}, 0xc0007989b4?, 0x0?, 0x0?, 0x0?, 0xae1eff?, 0xf?)
    /home/arvid/go/pkg/mod/github.com/tdewolff/canvas@v0.0.0-20221018191302-6bed7f464e8f/text.go:216 +0x276
github.com/TheFoundryVisionmongers/go-utils/pdf_test.TestTextBox(0xc0002fab60)
    /home/arvid/Documents/Flix/go-utils/pdf/example_test.go:114 +0x211
testing.tRunner(0xc0002fab60, 0x9ca390)
    /usr/lib/go/src/testing/testing.go:1446 +0x10b
created by testing.(*T).Run
    /usr/lib/go/src/testing/testing.go:1493 +0x35f
tdewolff commented 1 year ago

Thank you for the bug report, has been fixed!