Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 74 additions & 6 deletions components/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ type MarkdownStyle struct {
// string that runs over several lines is only colored where the lexer can
// tell from the line itself. The colors come from MarkdownLook.Code.
Highlight func(language, line string, dst []MarkdownCodeRun) []MarkdownCodeRun
// Image, when set, is asked for the bitmap of every image (![alt](destination)),
// with the destination as written. The view never reads files or the network:
// an application resolves relative paths and fetches what it allows. A bitmap's
// pixels are its size in the layout, scaled down to the column and never up.
// false lays the image out as its alt text, so an application can answer once
// the image has loaded and lay the document out again.
Image func(destination string) (gfx.Bitmap, bool)
}

// MarkdownCodeClass says what a stretch of code is, which MarkdownLook.Code turns
Expand Down Expand Up @@ -167,6 +174,7 @@ type MarkdownView struct {
boxes []mdBox
links []mdLink
codes []MarkdownCode
images []mdImage
anchors []MarkdownAnchor
atoms []mdAtom
numbers []byte
Expand Down Expand Up @@ -489,11 +497,21 @@ type mdLink struct {
text, dest string
}

// mdImage is an image laid out at x, y, w by h.
type mdImage struct {
bitmap gfx.Bitmap
x, y, w, h float32
}

type mdAtom struct {
span, lo, hi int32
w, space float32 // width, and the width of the blank that follows it
brk bool // a line break
glue bool // punctuation that may not start a line
// image marks an image's atom: w by h of bitmap.
image bool
h float32
bitmap gfx.Bitmap
w, space float32 // width, and the width of the blank that follows it
brk bool // a line break
glue bool // punctuation that may not start a line
}

type mdFont struct {
Expand All @@ -503,6 +521,8 @@ type mdFont struct {

// mdLayout is the state of one Layout call.
type mdLayout struct {
// column is the widest an image may be laid out, set by inline.
column float32
v *MarkdownView
canvas *gfx.Canvas
style MarkdownStyle
Expand All @@ -519,6 +539,7 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark
if style.LineHeight <= 0 {
style.LineHeight = float32(int(style.Size*1.55 + 0.5))
}
v.images = v.images[:0]
v.pieces, v.boxes, v.links, v.codes, v.anchors, v.numbers, v.runs, v.tabs, v.tabBound, v.plain, v.spanBase = v.pieces[:0], v.boxes[:0], v.links[:0], v.codes[:0], v.anchors[:0], v.numbers[:0], v.runs[:0], v.tabs[:0], v.tabBound[:0], v.plain[:0], v.spanBase[:0]
v.bars = [markdownMaxQuote + 1]int32{}
v.face = style.MonoFace
Expand Down Expand Up @@ -1070,6 +1091,20 @@ func (l *mdLayout) atomize(spans []markdown.Span, t mdFont) {
pending = 0
continue
}
if sp.Image != "" && l.style.Image != nil {
if bitmap, ok := l.style.Image(sp.Image); ok && bitmap.Width > 0 && bitmap.Height > 0 {
w, h := float32(bitmap.Width), float32(bitmap.Height)
if column := l.column; column > 0 && w > column {
w, h = column, h*column/w
}
if pending > 0 && len(atoms) > 0 && !atoms[len(atoms)-1].brk {
atoms[len(atoms)-1].space = pending
}
pending = 0
atoms = append(atoms, mdAtom{span: int32(si), image: true, w: w, h: h, bitmap: bitmap})
continue
}
}
mono := sp.Style&markdown.Mono != 0
italic := sp.Style&markdown.Italic != 0
size, weight := t.size, spanWeight(t.weight, sp.Style)
Expand Down Expand Up @@ -1148,9 +1183,12 @@ type mdLine struct {
piece int // the open piece, or -1
lo int32
span int32
pieceP int // first piece, box and link of the line, for alignment
pieceP int // first piece, box, link and image of the line, for alignment
pieceB int
pieceL int
pieceI int
// tall is the height of the tallest image on the line.
tall float32
// grew reports that the open piece took a second atom, so its width is a
// running sum that closePiece must settle.
grew bool
Expand All @@ -1167,7 +1205,9 @@ func (l *mdLayout) inline(spans []markdown.Span, x, width, y float32, t mdFont,
if len(spans) == 0 {
return y
}
l.column = width
l.atomize(spans, t)
l.column = 0
m := mdLine{l: l, spans: spans, t: t, align: align, x0: x, width: width, y: y, piece: -1}
m.reset()
for _, a := range l.v.atoms {
Expand Down Expand Up @@ -1232,7 +1272,8 @@ func (m *mdLine) fit(a mdAtom) (mdAtom, bool) {
func (m *mdLine) reset() {
v := m.l.v
m.x, m.w, m.has, m.piece = 0, 0, false, -1
m.pieceP, m.pieceB, m.pieceL = len(v.pieces), len(v.boxes), len(v.links)
m.pieceP, m.pieceB, m.pieceL, m.pieceI = len(v.pieces), len(v.boxes), len(v.links), len(v.images)
m.tall = 0
m.measuredSpan, m.measuredLo, m.measuredHi, m.measuredEnd = -1, 0, 0, 0
m.grew = false
}
Expand Down Expand Up @@ -1261,6 +1302,9 @@ func (m *mdLine) spanPad(sp markdown.Span) float32 {
}

func (m *mdLine) exactWidth(a mdAtom) float32 {
if a.image {
return a.w
}
if a.hi <= a.lo {
return 0
}
Expand Down Expand Up @@ -1431,6 +1475,20 @@ func (m *mdLine) place(a mdAtom) {
v := l.v
sp := m.spans[a.span]
mono := sp.Style&markdown.Mono != 0
if a.image {
m.closePiece()
x := m.x0 + m.x
v.images = append(v.images, mdImage{bitmap: a.bitmap, x: x, y: m.y, w: a.w, h: a.h})
if sp.Link != "" {
v.links = append(v.links, mdLink{x: x, y: m.y, w: a.w, h: a.h, size: m.t.size, text: sp.Text, dest: sp.Link})
}
m.x += a.w
m.w = m.x
m.x += a.space
m.has = true
m.tall = max(m.tall, a.h)
return
}
if a.hi <= a.lo {
return
}
Expand Down Expand Up @@ -1553,9 +1611,13 @@ func (m *mdLine) endLine() {
for i := m.pieceL; i < len(v.links); i++ {
v.links[i].x += shift
}
for i := m.pieceI; i < len(v.images); i++ {
v.images[i].x += shift
}
}
}
m.y += m.t.line
// A line with an image is as tall as the image, with the text along its top.
m.y += max(m.t.line, m.tall+4)
m.l.lines++
m.reset()
}
Expand Down Expand Up @@ -1592,6 +1654,12 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) {
canvas.Rounded(rect, 4, look.InlineCodeFill)
}
}
for _, image := range v.images {
rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h}
if visible(rect.Y, rect.Height) {
canvas.DrawBitmap(image.bitmap, rect)
}
}
start, end := p.Selection.Range(v.plain)
if start < end && look.Selection.Alpha > 0 {
for index := range v.pieces {
Expand Down
38 changes: 38 additions & 0 deletions components/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1740,3 +1740,41 @@ func TestHeadingInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) {
t.Errorf("heading inline code selection is %v wide, want %v", rects[0].Bounds.Width, want)
}
}

func TestMarkdownImagesAreScaledToTheColumnAndPainted(t *testing.T) {
wide := gfx.Bitmap{Pix: make([]byte, 400*100*4), Width: 400, Height: 100, Stride: 400 * 4, ID: 1}
small := gfx.Bitmap{Pix: make([]byte, 20*10*4), Width: 20, Height: 10, Stride: 20 * 4, ID: 2}
style := MarkdownStyle{Size: 12, Image: func(dest string) (gfx.Bitmap, bool) {
switch dest {
case "wide.png":
return wide, true
case "small.png":
return small, true
}
return gfx.Bitmap{}, false
}}
view, _ := layoutMarkdown(t, "![a](wide.png)\n\n[![b](small.png)](https://example.com/) ![missing](gone.png)", 200, style)
if len(view.images) != 2 {
t.Fatalf("images = %+v", view.images)
}
if got := view.images[0]; got.w != 200 || got.h != 50 {
t.Errorf("a wide image is %vx%v, want 200x50", got.w, got.h)
}
if got := view.images[1]; got.w != 20 || got.h != 10 {
t.Errorf("a small image is %vx%v, want its own 20x10", got.w, got.h)
}
if view.Height() < 50 {
t.Errorf("height %v leaves no room for the image", view.Height())
}
if view.LinkCount() != 1 || view.Link(0) != "https://example.com/" {
t.Errorf("the linked badge is not a link: %d", view.LinkCount())
}
if !strings.Contains(string(view.plain), "missing") {
t.Errorf("an unresolved image shows no alt text: %q", view.plain)
}
var canvas gfx.Canvas
view.Paint(&canvas, MarkdownPaint{X: 0, Y: 0})
if len(canvas.Images()) != 2 {
t.Errorf("painted %d images", len(canvas.Images()))
}
}
10 changes: 10 additions & 0 deletions markdown/inline.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ func (d *Document) inline(s string, style Style, link string, depth int) {
}
i += n
continue
case '!':
if i+1 < len(s) && s[i+1] == '[' {
if labelEnd, dest, end := d.findLink(s, i+1); end >= 0 {
d.emit(s[text:i], style, link)
d.spans = append(d.spans, Span{Text: s[i+2 : labelEnd], Style: style, Link: link, Image: dest})
i = end
text = i
continue
}
}
case '[':
if link == "" && depth < maxNesting {
if labelEnd, dest, end := d.findLink(s, i); end >= 0 {
Expand Down
7 changes: 6 additions & 1 deletion markdown/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
// not closed (a "**" with no partner, a fence nobody ended yet) stays as typed,
// so half a message that is still arriving reads sensibly. Links are kept only
// when they point to http, https or mailto; any other destination is shown as
// plain text. HTML, images, footnotes and indented code are not interpreted.
// plain text. HTML, footnotes and indented code are not interpreted; an image is a
// Span whose Image is its destination.
package markdown

import "strings"
Expand Down Expand Up @@ -55,6 +56,10 @@ type Span struct {
// Link is the destination when the text is a link, and empty otherwise.
// Only http, https and mailto destinations are ever set.
Link string
// Image is the destination of an image (![alt](destination)) as written,
// whatever its scheme, and empty for text; Text is then the alt text. The
// package never reads it: a view asks the application for the bitmap.
Image string
}

// Newline is the Text of the Span that separates two lines of a block.
Expand Down
20 changes: 20 additions & 0 deletions markdown/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,23 @@ func TestBlockRangesNameTheLinesOfTheirBlocks(t *testing.T) {
}
}
}

func TestAnImageIsASpanWithItsDestination(t *testing.T) {
var d Document
d.Parse("see ![the diagram](docs/arch.png) and [![build](https://x/badge.svg)](https://x/ci)")
var images []Span
for _, span := range d.Spans(&d.Blocks[0]) {
if span.Image != "" {
images = append(images, span)
}
}
if len(images) != 2 {
t.Fatalf("images = %+v", images)
}
if images[0].Image != "docs/arch.png" || images[0].Text != "the diagram" || images[0].Link != "" {
t.Errorf("first image %+v", images[0])
}
if images[1].Image != "https://x/badge.svg" || images[1].Link != "https://x/ci" {
t.Errorf("a linked badge %+v", images[1])
}
}