From 0312d4676a4dae58482802c6c696b05148b5a2fb Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 11 Nov 2026 01:02:02 -0800 Subject: [PATCH] markdown, components: images in MarkdownView from host bitmaps The parser makes ![alt](destination) a Span whose Image is the destination as written. MarkdownStyle.Image asks the application for each image's bitmap; the view lays it out inline, scaled down to the column and never up, makes a line as tall as its tallest image, keeps a linked image a link, and paints it. Without a bitmap the alt text shows, as before. The framework never reads files or the network. Closes the need of vivaui/viva#220 in this fork. Co-Authored-By: Claude Opus 5.5 --- components/markdown.go | 80 ++++++++++++++++++++++++++++++++++--- components/markdown_test.go | 38 ++++++++++++++++++ markdown/inline.go | 10 +++++ markdown/markdown.go | 7 +++- markdown/markdown_test.go | 20 ++++++++++ 5 files changed, 148 insertions(+), 7 deletions(-) diff --git a/components/markdown.go b/components/markdown.go index 5bd2dd8db..7366781db 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -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 @@ -167,6 +174,7 @@ type MarkdownView struct { boxes []mdBox links []mdLink codes []MarkdownCode + images []mdImage anchors []MarkdownAnchor atoms []mdAtom numbers []byte @@ -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 { @@ -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 @@ -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 @@ -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) @@ -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 @@ -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 { @@ -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 } @@ -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 } @@ -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 } @@ -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() } @@ -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 { diff --git a/components/markdown_test.go b/components/markdown_test.go index d076036a1..656b417a4 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -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())) + } +} diff --git a/markdown/inline.go b/markdown/inline.go index fa80c0d08..3da7a8fc0 100644 --- a/markdown/inline.go +++ b/markdown/inline.go @@ -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 { diff --git a/markdown/markdown.go b/markdown/markdown.go index b435d8d64..4412a0b64 100644 --- a/markdown/markdown.go +++ b/markdown/markdown.go @@ -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" @@ -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. diff --git a/markdown/markdown_test.go b/markdown/markdown_test.go index a6f599dce..554f2e58e 100644 --- a/markdown/markdown_test.go +++ b/markdown/markdown_test.go @@ -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]) + } +}