From 855ad680fb2a32fa969b8bfae198909762d419f7 Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 19 Nov 2026 10:40:23 +0000 Subject: [PATCH 1/3] Render rich Markdown in posts --- internal/ui/markdown.go | 179 ++++++++++++++++++++++++++++++++++ internal/ui/markdown_test.go | 93 ++++++++++++++++++ internal/ui/text.go | 45 +-------- internal/ui/web_links.go | 86 ++++++++-------- internal/ui/web_links_test.go | 4 +- 5 files changed, 321 insertions(+), 86 deletions(-) create mode 100644 internal/ui/markdown.go create mode 100644 internal/ui/markdown_test.go diff --git a/internal/ui/markdown.go b/internal/ui/markdown.go new file mode 100644 index 0000000..440bdbe --- /dev/null +++ b/internal/ui/markdown.go @@ -0,0 +1,179 @@ +package ui + +import ( + "bytes" + "strconv" + "strings" + "sync" + + glamour "charm.land/glamour/v2/ansi" + "charm.land/glamour/v2/styles" + "github.com/yuin/goldmark" + "github.com/yuin/goldmark/ast" + "github.com/yuin/goldmark/extension" + table "github.com/yuin/goldmark/extension/ast" + "github.com/yuin/goldmark/parser" + "github.com/yuin/goldmark/renderer" + "github.com/yuin/goldmark/text" + "github.com/yuin/goldmark/util" +) + +var ( + markdownParser = goldmark.New( + goldmark.WithExtensions(extension.GFM, extension.DefinitionList), + goldmark.WithParserOptions(parser.WithAutoHeadingID()), + ).Parser() + markdownRenderers sync.Map +) + +type markdownRenderer struct { + mu sync.Mutex + renderer.Renderer +} + +func renderMarkdown(source []byte, doc ast.Node, width int) (string, error) { + cached, ok := markdownRenderers.Load(width) + if !ok { + style := styles.NoTTYStyleConfig + style.Emph = glamour.StylePrimitive{Italic: new(true)} + style.Strong = glamour.StylePrimitive{Bold: new(true)} + style.Code.StylePrimitive = glamour.StylePrimitive{Inverse: new(true)} + style.Table.RowSeparator = new("─") + style.Table.ColumnSeparator = new("│") + style.Table.CenterSeparator = new("┼") + if width == 0 { + style.Document.Margin = nil + } + ansiRenderer := glamour.NewRenderer(glamour.Options{ + Styles: style, WordWrap: width, PreserveNewLines: true, InlineTableLinks: true, + }) + cached, _ = markdownRenderers.LoadOrStore(width, &markdownRenderer{Renderer: renderer.NewRenderer( + renderer.WithNodeRenderers(util.Prioritized(ansiRenderer, 1000)), + )}) + } + r := cached.(*markdownRenderer) + var output bytes.Buffer + r.mu.Lock() + defer r.mu.Unlock() + err := r.Render(&output, source, doc) + return strings.Trim(output.String(), "\n"), err +} + +func wrapLines(value string, width int, links bool) []string { + if width <= 0 { + return []string{""} + } + // Terminal styling and hyperlinks come from the renderer, never the source. + value = stripANSI(value) + source := []byte(expandBareWebURLs(value)) + doc := markdownParser.Parse(text.NewReader(source)) + rendered, err := renderMarkdownDocument(source, doc, width) + if err != nil { + rendered = linkify(stripHTML(value), links) + } + return webTextLines(rendered, width, links) +} + +func renderMarkdownDocument(source []byte, doc ast.Node, width int) (string, error) { + // Parse the whole document so references resolve across table boundaries. + // Render consecutive prose blocks together to keep Glamour's spacing. + var sections []string + prose := ast.NewDocument() + flush := func() error { + if !prose.HasChildren() { + return nil + } + section, err := renderMarkdown(source, prose, width) + sections = append(sections, section) + prose.RemoveChildren(prose) + return err + } + for block := doc.FirstChild(); block != nil; block = doc.FirstChild() { + doc.RemoveChild(doc, block) + if grid, ok := block.(*table.Table); ok { + if err := flush(); err != nil { + return "", err + } + section, err := renderMarkdownTable(source, grid, width) + if err != nil { + return "", err + } + sections = append(sections, section) + } else { + prose.AppendChild(prose, block) + } + } + if err := flush(); err != nil { + return "", err + } + return strings.Join(sections, "\n\n"), nil +} + +func renderMarkdownTable(source []byte, grid *table.Table, width int) (string, error) { + sizes := make([]int, len(grid.Alignments)) + rows := make([][]string, 0, grid.ChildCount()) + for row := grid.FirstChild(); row != nil; row = row.NextSibling() { + cells := make([]string, len(sizes)) + for cell, col := row.FirstChild(), 0; cell != nil; cell, col = cell.NextSibling(), col+1 { + doc, paragraph := ast.NewDocument(), ast.NewParagraph() + doc.AppendChild(doc, paragraph) + var inline ast.Node = paragraph + if row.Kind() == table.KindTableHeader { + inline = ast.NewEmphasis(2) + paragraph.AppendChild(paragraph, inline) + } + for child := cell.FirstChild(); child != nil; child = cell.FirstChild() { + cell.RemoveChild(cell, child) + inline.AppendChild(inline, child) + } + value, err := renderMarkdown(source, doc, 0) + if err != nil { + return "", err + } + cells[col] = value + sizes[col] = max(sizes[col], visibleWidth(value)) + } + rows = append(rows, cells) + } + + total := 2 * max(len(sizes)-1, 0) + for _, size := range sizes { + total += size + } + var lines []string + if total <= width { + for i, cells := range rows { + for col, value := range cells { + pad := sizes[col] - visibleWidth(value) + var left int + switch grid.Alignments[col] { + case table.AlignCenter: + left = pad / 2 + case table.AlignRight: + left = pad + } + cells[col] = strings.Repeat(" ", left) + value + strings.Repeat(" ", pad-left) + } + lines = append(lines, strings.TrimRight(strings.Join(cells, " "), " ")) + if i == 0 { + lines = append(lines, strings.Repeat("─", total)) + } + } + } else if len(rows) == 1 { + lines = rows[0] + } else if len(rows) > 1 { + for _, cells := range rows[1:] { + if len(lines) > 0 { + lines = append(lines, "") + } + for col, value := range cells { + label := rows[0][col] + if label == "" { + label = "#" + strconv.Itoa(col+1) + } + lines = append(lines, label+": "+value) + } + } + } + return strings.Join(lines, "\n"), nil +} diff --git a/internal/ui/markdown_test.go b/internal/ui/markdown_test.go new file mode 100644 index 0000000..0679af3 --- /dev/null +++ b/internal/ui/markdown_test.go @@ -0,0 +1,93 @@ +package ui + +import ( + "bytes" + "strings" + "testing" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/merefield/termcourse/internal/discourse" +) + +func TestPostMarkdownStylesStayInsideTheirSpans(t *testing.T) { + t.Setenv("TERMCOURSE_COLOR_MODE", "truecolor") + t.Setenv("TERMCOURSE_IMAGES", "0") + u := UI{style: NewStyle(testTheme(), &bytes.Buffer{})} + post := discourse.JSON{"username": "member", "raw": "**B** *I* `C*` P\n\n***abcdefghij***"} + for _, width := range []int{10, 40} { + lines := u.postBlock(post, true, width)[1:] + var seen strings.Builder + for _, line := range lines { + // Each line can be redrawn on its own when the post is scrolled. + for _, cell := range backgroundTestLines(line + "│")[0] { + var want uint8 + switch cell.Content { + case "B": + want = uv.AttrBold + case "I": + want = uv.AttrItalic + case "C", "*": + want = uv.AttrReverse + case " ", "│", "P": + default: + want = uv.AttrBold | uv.AttrItalic + } + if cell.Style.Attrs != want { + t.Fatalf("width %d, cell %q has attributes %v, want %v", width, cell.Content, cell.Style.Attrs, want) + } + if cell.Content != " " && cell.Content != "│" { + seen.WriteString(cell.Content) + assertBackground(t, cell.Style.Fg, u.style.roles[roleListText].GetForeground()) + } + } + } + if got := seen.String(); got != "BIC*Pabcdefghij" { + t.Fatalf("width %d displayed %q", width, got) + } + } +} + +func TestMarkdownTablesAlignAndReflow(t *testing.T) { + source := "| City | Total |\n|:---|---:|\n| **界** | `3` |\n| London | 100 |" + wide := wrapLines(source, 32, false) + if got := stripANSI(strings.Join(wide, "\n")); got != "City Total\n─────────────\n界 3\nLondon 100" { + t.Fatalf("unaligned table:\n%s", got) + } + cells := backgroundTestLines(strings.Join(wide, "\n")) + if cells[0][0].Style.Attrs != uv.AttrBold || cells[2][0].Style.Attrs != uv.AttrBold || cells[2][len(cells[2])-1].Style.Attrs != uv.AttrReverse { + t.Fatal("table header, emphasis or inline code lost its style") + } + + narrow := wrapLines(source, 10, false) + for _, line := range narrow { + if visibleWidth(line) > 10 { + t.Fatalf("table exceeds pane width: %q", line) + } + } + if got := stripANSI(strings.Join(narrow, "\n")); got != "City: 界\nTotal: 3\n\nCity: Lond\non\nTotal: 100" { + t.Fatalf("table lost a label or value when reflowing:\n%s", got) + } +} + +func TestMarkdownTableKeepsReferenceLinksInNarrowPanes(t *testing.T) { + const target = "https://example.com/termcourse" + source := "Before.\n\n| Docs |\n|---|\n| [Guide][docs] |\n\nAfter.\n\n[docs]: " + target + lines := wrapLines(source, 12, true) + for _, line := range lines { + if visibleWidth(line) > 12 { + t.Fatalf("table exceeds pane width: %q", line) + } + } + plain := strings.Join(strings.Fields(stripANSI(strings.Join(lines, "\n"))), "") + if plain != "Before.Docs:Guide"+target+"After." { + t.Fatalf("lost content around wrapped reference link: %q", plain) + } + for _, line := range lines { + for x := 0; x < visibleWidth(line); x++ { + if webLinkAt(line, x, 0) == target { + return + } + } + } + t.Fatal("reference link is no longer clickable") +} diff --git a/internal/ui/text.go b/internal/ui/text.go index a8a0c11..6474f9b 100644 --- a/internal/ui/text.go +++ b/internal/ui/text.go @@ -5,17 +5,11 @@ import ( "regexp" "strconv" "strings" - "sync" - "charm.land/glamour/v2" - "charm.land/glamour/v2/styles" "github.com/charmbracelet/x/ansi" ) -var ( - htmlPattern = regexp.MustCompile(`<[^>]*>`) - markdownRenderers sync.Map -) +var htmlPattern = regexp.MustCompile(`<[^>]*>`) func stripANSI(value string) string { return ansi.Strip(value) @@ -108,43 +102,6 @@ func stripHTML(value string) string { return html.UnescapeString(htmlPattern.ReplaceAllString(value, "")) } -func wrapLines(value string, width int, links bool) []string { - if width <= 0 { - return []string{""} - } - loaded, ok := markdownRenderers.Load(width) - if !ok { - renderer, err := glamour.NewTermRenderer( - glamour.WithStandardStyle(styles.NoTTYStyle), - glamour.WithWordWrap(width), - glamour.WithPreservedNewLines(), - glamour.WithInlineTableLinks(true), - ) - if err != nil { - return webTextLines(linkify(stripHTML(value), links), width, links) - } - loaded, _ = markdownRenderers.LoadOrStore(width, &markdownRenderer{renderer: renderer}) - } - cached := loaded.(*markdownRenderer) - value = expandBareWebURLs(value) - cached.mu.Lock() - rendered, err := cached.renderer.Render(value) - cached.mu.Unlock() - if err != nil { - return webTextLines(linkify(stripHTML(value), links), width, links) - } - rendered = strings.Trim(rendered, "\n") - if rendered == "" { - return []string{""} - } - return webTextLines(rendered, width, links) -} - -type markdownRenderer struct { - mu sync.Mutex - renderer *glamour.TermRenderer -} - func emojify(value string, enabled bool) string { if !enabled { return value diff --git a/internal/ui/web_links.go b/internal/ui/web_links.go index e6e7b66..ff39e83 100644 --- a/internal/ui/web_links.go +++ b/internal/ui/web_links.go @@ -7,6 +7,7 @@ import ( "unicode" tea "charm.land/bubbletea/v2" + uv "github.com/charmbracelet/ultraviolet" "github.com/charmbracelet/x/ansi" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" @@ -62,56 +63,61 @@ func walkWebText(text string, visit func(string, int, *ansi.Parser)) { } } -// Glamour expands destinations for every domain. Normalize its links, then -// give every wrapped line its own open/close pair so scrolling and padding -// cannot inherit a URL from an omitted line. +// Give each wrapped row its own styles and validated links. Rows can be +// scrolled into view independently, and their styling must stop before padding. func webTextLines(text string, width int, enabled bool) []string { - if !enabled { - return strings.Split(ansi.Hardwrap(ansi.Strip(text), width, true), "\n") - } - var normalized strings.Builder - var active string - walkWebText(text, func(seq string, _ int, p *ansi.Parser) { - if ansi.HasOscPrefix(seq) && p.Command() == 8 { - fields := strings.SplitN(string(p.Data()), ";", 3) - if active != "" { - normalized.WriteString("\x1b[24m" + ansi.ResetHyperlink()) - } - active = "" - if len(fields) == 3 && validWebURL(fields[2]) { - active = fields[2] - normalized.WriteString(ansi.SetHyperlink(active, webLinkID) + "\x1b[4m") - } - return - } - normalized.WriteString(seq) - }) - if active != "" { - normalized.WriteString("\x1b[24m" + ansi.ResetHyperlink()) - } - lines := strings.Split(ansi.Hardwrap(normalized.String(), width, true), "\n") - active = "" + lines := strings.Split(ansi.Hardwrap(text, width, true), "\n") + var style uv.Style + var activeLink string for i, line := range lines { - prefix := "" - if active != "" { - prefix = ansi.SetHyperlink(active, webLinkID) + "\x1b[4m" - } - walkWebText(line, func(seq string, _ int, p *ansi.Parser) { - if ansi.HasOscPrefix(seq) && p.Command() == 8 { - fields := strings.SplitN(string(p.Data()), ";", 3) - if len(fields) == 3 { - active = fields[2] + var out strings.Builder + var drawnStyle uv.Style + var drawnLink string + walkWebText(strings.TrimRight(line, " \t\r"), func(seq string, cells int, p *ansi.Parser) { + switch { + case ansi.HasCsiPrefix(seq) && p.Command() == 'm': + uv.ReadStyle(p.Params(), &style) + case ansi.HasOscPrefix(seq) && p.Command() == 8: + activeLink = "" + if enabled { + var link uv.Link + uv.ReadLink(p.Data(), &link) + if validWebURL(link.URL) { + activeLink = link.URL + } + } + case cells > 0 || seq == "\t": + if drawnLink != activeLink { + out.WriteString(ansi.SetHyperlink(activeLink, webLinkID)) + drawnLink = activeLink } + wanted := uv.Style{Attrs: style.Attrs & (uv.AttrBold | uv.AttrItalic | uv.AttrReverse)} + if drawnLink != "" { + wanted.Underline = uv.UnderlineSingle + } + out.WriteString(markdownStyleDiff(&drawnStyle, &wanted)) + drawnStyle = wanted + out.WriteString(seq) } }) - lines[i] = prefix + strings.TrimRight(line, " \t\r") - if active != "" { - lines[i] += "\x1b[24m" + ansi.ResetHyperlink() + if drawnLink != "" { + out.WriteString(ansi.ResetHyperlink()) } + out.WriteString(markdownStyleDiff(&drawnStyle, &uv.Style{})) + lines[i] = out.String() } return lines } +func markdownStyleDiff(from, to *uv.Style) string { + // The pane supplies foreground and background colours. Clear the inline + // attributes individually so an SGR reset doesn't erase those colours. + if to.IsZero() && !from.IsZero() { + return ansi.Style{}.Normal().Italic(false).Reverse(false).Underline(false).String() + } + return to.Diff(from) +} + // Use the renderer's grapheme widths, including both cells of wide characters. func webLinkAt(content string, x, y int) string { if x < 0 || y < 0 { diff --git a/internal/ui/web_links_test.go b/internal/ui/web_links_test.go index 014120b..a619c83 100644 --- a/internal/ui/web_links_test.go +++ b/internal/ui/web_links_test.go @@ -26,8 +26,8 @@ func TestWebLinksExpandAllDestinations(t *testing.T) { if !strings.Contains(plain, target) { t.Fatalf("address hidden: enabled=%v source=%q output=%q", enabled, source, plain) } - if !enabled && strings.Contains(strings.Join(lines, ""), "\x1b") { - t.Fatal("disabled links contain escape sequences") + if !enabled && strings.Contains(strings.Join(lines, ""), "\x1b]8;") { + t.Fatal("disabled links contain OSC 8 hyperlinks") } if enabled { found := false From 8e752f1bc494dc3935dc01b7437343b8f091689d Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 19 Nov 2026 10:45:49 +0000 Subject: [PATCH 2/3] Style Markdown headings, quotes, tasks, and strikethrough --- internal/ui/markdown.go | 11 +++++++++++ internal/ui/markdown_test.go | 35 +++++++++++++++++++++++++++++++++++ internal/ui/ui_test.go | 8 ++++++-- internal/ui/web_links.go | 4 ++-- 4 files changed, 54 insertions(+), 4 deletions(-) diff --git a/internal/ui/markdown.go b/internal/ui/markdown.go index 440bdbe..948acf4 100644 --- a/internal/ui/markdown.go +++ b/internal/ui/markdown.go @@ -38,6 +38,17 @@ func renderMarkdown(source []byte, doc ast.Node, width int) (string, error) { style.Emph = glamour.StylePrimitive{Italic: new(true)} style.Strong = glamour.StylePrimitive{Bold: new(true)} style.Code.StylePrimitive = glamour.StylePrimitive{Inverse: new(true)} + style.Heading.Bold = new(true) + style.H1.Prefix = "◆ " + style.H2.Prefix = "▌ " + style.H3.Prefix = "▎ " + style.H4.Prefix = "▏ " + style.H5.Prefix = "• " + style.H6.Prefix = "· " + style.Strikethrough = glamour.StylePrimitive{CrossedOut: new(true)} + style.BlockQuote.IndentToken = new("│ ") + style.Task.Unticked = "☐ " + style.Task.Ticked = "☑ " style.Table.RowSeparator = new("─") style.Table.ColumnSeparator = new("│") style.Table.CenterSeparator = new("┼") diff --git a/internal/ui/markdown_test.go b/internal/ui/markdown_test.go index 0679af3..6b0bd10 100644 --- a/internal/ui/markdown_test.go +++ b/internal/ui/markdown_test.go @@ -91,3 +91,38 @@ func TestMarkdownTableKeepsReferenceLinksInNarrowPanes(t *testing.T) { } t.Fatal("reference link is no longer clickable") } + +func TestMarkdownHeadingsQuotesAndTasks(t *testing.T) { + source := "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n\n> This quote wraps across lines.\n\n- [ ] Pending\n- [x] Done" + lines := wrapLines(source, 24, false) + plain := stripANSI(strings.Join(lines, "\n")) + for _, want := range []string{"◆ One", "▌ Two", "▎ Three", "▏ Four", "• Five", "· Six", "│ This quote", "│ across lines.", "☐ Pending", "☑ Done"} { + if !strings.Contains(plain, want) { + t.Fatalf("missing %q in rendered Markdown:\n%s", want, plain) + } + } + for _, line := range lines { + if strings.HasPrefix(strings.TrimSpace(stripANSI(line)), "▌ ") { + for _, cell := range backgroundTestLines(line)[0] { + if cell.Content != " " && cell.Style.Attrs&uv.AttrBold == 0 { + t.Fatalf("heading text %q was not bold", cell.Content) + } + } + } + } +} + +func TestMarkdownStrikethroughSurvivesWrapping(t *testing.T) { + lines := wrapLines("~~abcdefghij~~ Z", 10, false) + var crossed strings.Builder + for _, line := range lines { + for _, cell := range backgroundTestLines(line + "│")[0] { + if cell.Style.Attrs&uv.AttrStrikethrough != 0 { + crossed.WriteString(cell.Content) + } + } + } + if got := crossed.String(); got != "abcdefghij" { + t.Fatalf("strikethrough applied to %q", got) + } +} diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 0a20a11..3a5c7ea 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -677,11 +677,15 @@ func TestHeaderLineRightAlignsStatusAndStaysWithinWidth(t *testing.T) { func TestMarkdownRenderingUsesGFMAndTerminalLinks(t *testing.T) { lines := wrapLines("## Heading\n\n- first\n- second\n\n[site](https://example.com)", 40, true) joined := strings.Join(lines, "\n") - for _, expected := range []string{"## Heading", "first", "second", "\x1b]8;", "https://example.com"} { - if !strings.Contains(joined, expected) { + plain := stripANSI(joined) + for _, expected := range []string{"▌ Heading", "first", "second", "https://example.com"} { + if !strings.Contains(plain, expected) { t.Fatalf("rendered Markdown %q missing %q", joined, expected) } } + if !strings.Contains(joined, "\x1b]8;") { + t.Fatalf("rendered Markdown missing terminal hyperlink: %q", joined) + } for _, line := range lines { if visibleWidth(line) > 40 { t.Fatalf("Markdown line width = %d: %q", visibleWidth(line), line) diff --git a/internal/ui/web_links.go b/internal/ui/web_links.go index ff39e83..07d7421 100644 --- a/internal/ui/web_links.go +++ b/internal/ui/web_links.go @@ -91,7 +91,7 @@ func webTextLines(text string, width int, enabled bool) []string { out.WriteString(ansi.SetHyperlink(activeLink, webLinkID)) drawnLink = activeLink } - wanted := uv.Style{Attrs: style.Attrs & (uv.AttrBold | uv.AttrItalic | uv.AttrReverse)} + wanted := uv.Style{Attrs: style.Attrs & (uv.AttrBold | uv.AttrItalic | uv.AttrReverse | uv.AttrStrikethrough)} if drawnLink != "" { wanted.Underline = uv.UnderlineSingle } @@ -113,7 +113,7 @@ func markdownStyleDiff(from, to *uv.Style) string { // The pane supplies foreground and background colours. Clear the inline // attributes individually so an SGR reset doesn't erase those colours. if to.IsZero() && !from.IsZero() { - return ansi.Style{}.Normal().Italic(false).Reverse(false).Underline(false).String() + return ansi.Style{}.Normal().Italic(false).Reverse(false).Underline(false).Strikethrough(false).String() } return to.Diff(from) } From 8455c83cd11e8915810b4de683542cfb290286ca Mon Sep 17 00:00:00 2001 From: merefield Date: Thu, 19 Nov 2026 11:10:47 +0000 Subject: [PATCH 3/3] Keep fullscreen Sixel images inside the main pane --- internal/ui/images.go | 169 ++++++++++++++++++++++++------------- internal/ui/images_test.go | 92 ++++++++++++++++++++ internal/ui/terminal.go | 16 ++++ internal/ui/ui_test.go | 4 +- 4 files changed, 221 insertions(+), 60 deletions(-) diff --git a/internal/ui/images.go b/internal/ui/images.go index 5ea1c27..b83dfed 100644 --- a/internal/ui/images.go +++ b/internal/ui/images.go @@ -120,7 +120,7 @@ func (u *UI) imagePreview(raw string, width int) []string { if rendered, present := u.imageCache[key]; present { return append([]string{}, rendered...) } - rendered, err := u.renderImage(urls[0], backend, columns, rows, false, true) + rendered, err := u.renderImage(urls[0], backend, columns, rows, true) if err != nil || len(rendered) == 0 { u.imageCache[key] = nil return nil @@ -150,7 +150,7 @@ func imageBackend() string { return "" } -func (u *UI) renderImage(imageURL, backend string, width, lines int, sixel, filterQuality bool) ([]string, error) { +func (u *UI) renderImage(imageURL, backend string, width, lines int, filterQuality bool) ([]string, error) { body, err := u.client.GetBytes(imageURL, envInt("TERMCOURSE_IMAGE_MAX_BYTES", 5_242_880)) if err != nil { return nil, err @@ -173,7 +173,7 @@ func (u *UI) renderImage(imageURL, backend string, width, lines int, sixel, filt if backend == "viu" { command = exec.Command("viu", "-h", strconv.Itoa(lines), "--blocks", "--transparent", name) } else { - args := chafaArgs(name, width, lines, sixel) + args := chafaArgs(name, width, lines) command = exec.Command("chafa", args...) } if imageMode() != "compat" && imageColors() == "full" { @@ -183,9 +183,6 @@ func (u *UI) renderImage(imageURL, backend string, width, lines int, sixel, filt if err != nil { return nil, err } - if sixel { - return []string{string(output)}, nil - } var rendered []string preserve := backend == "viu" || imageMode() != "compat" for _, line := range strings.Split(strings.ReplaceAll(string(output), "\r", ""), "\n") { @@ -206,11 +203,8 @@ func (u *UI) renderImage(imageURL, backend string, width, lines int, sixel, filt return rendered, nil } -func chafaArgs(path string, width, lines int, sixel bool) []string { +func chafaArgs(path string, width, lines int) []string { size := fmt.Sprintf("%dx%d", width, lines) - if sixel { - return []string{"--format", "sixels", "--scale", "max", "--align", "top,left", "--margin-bottom", "0", "--optimize", "9", "--size", size, "--view-size", size, path} - } switch imageMode() { case "balanced": return []string{"--format", "symbols", "--symbols", "vhalf", "--colors", imageColors(), "--optimize", "5", "--work", "5", "--size", size, path} @@ -530,33 +524,23 @@ renderLoop: if backend == "" { return } - if backend == "chafa" && u.detectSixel() { - header := u.imageScreenHeader(width, height) - screen, pane := u.mainPane(header, width, height, 1) - if payload, nativeErr := u.renderNativeImage(imageURL, max(pane.width, 1), max(pane.height, 1), u.nativePixelViewport(width, height, pane)); nativeErr == nil && len(payload) > 0 && pane.width > 0 && pane.height > 0 { - // Keep Bubble Tea's current model intact while the raw Sixel payload - // owns the image rows beneath the persistent managed navigation. - u.drawMainPane(screen, pane, nil) - u.placeControlsFooter(screen, u.t("ui.controls.fullscreen_image"), width) - u.renderer.Render(screen, width, height, "fullscreen-image-sixel", -1, -1, true) - u.terminal.Raw(xansi.HideCursor + xansi.CursorPosition(pane.y+1, pane.x+1) + string(payload) + xansi.HideCursor) - for { - key, err := u.readKey(u.tick) - if err != nil || u.leaveImageForKey(key) { - u.renderer.Reset() - return - } - newWidth, newHeight := u.terminal.Size() - if key == keyThemeChanged || key == keyHoverChanged || newWidth != width || newHeight != height { - u.renderer.Reset() - continue renderLoop - } + if backend == "chafa" && u.detectSixel() && u.drawFullscreenSixel(imageURL, width, height) { + for { + key, err := u.readKey(u.tick) + if err != nil || u.leaveImageForKey(key) { + u.renderer.Reset() + return + } + newWidth, newHeight := u.terminal.Size() + if key == keyThemeChanged || key == keyHoverChanged || newWidth != width || newHeight != height { + u.renderer.Reset() + continue renderLoop } } } header := u.imageScreenHeader(width, height) screen, pane := u.mainPane(header, width, height, 1) - rendered, err := u.renderImage(imageURL, backend, max(pane.width, 1), max(pane.height, 1), false, false) + rendered, err := u.renderImage(imageURL, backend, max(pane.width, 1), max(pane.height, 1), false) if err != nil { u.showError(err) return @@ -579,6 +563,73 @@ renderLoop: } } +func (u *UI) drawFullscreenSixel(imageURL string, width, height int) bool { + header := u.imageScreenHeader(width, height) + screen, pane := u.mainPane(header, width, height, 1) + if pane.width == 0 || pane.height == 0 { + return false + } + cellSize := u.sixelCellSize(width, height) + maxPixels := image.Pt(pane.width*cellSize.X, pane.height*cellSize.Y) + // A Sixel band is six pixels tall. Keep even the last partial band inside + // the pane so it cannot paint over the bottom border. + maxPixels.Y -= maxPixels.Y % 6 + if maxPixels.X <= 0 || maxPixels.Y <= 0 { + return false + } + payload, err := u.renderNativeImage(imageURL, maxPixels) + if err != nil { + u.imageDebug("Fullscreen Sixel encoding failed: %v", err) + return false + } + sequence, ok := placeSixelInPane(payload, pane, cellSize) + if !ok { + u.imageDebug("Fullscreen Sixel raster did not fit the pane") + return false + } + if currentWidth, currentHeight := u.terminal.Size(); currentWidth != width || currentHeight != height { + return false + } + u.drawMainPane(screen, pane, nil) + u.placeControlsFooter(screen, u.t("ui.controls.fullscreen_image"), width) + u.renderer.Render(screen, width, height, "fullscreen-image-sixel", -1, -1, true) + if err := u.terminal.rawAfterFrame(sequence); err != nil { + u.imageDebug("Fullscreen Sixel frame sync failed: %v", err) + return false + } + return true +} + +func placeSixelInPane(encoded []byte, pane paneLayout, cellSize image.Point) (string, bool) { + const dcs, st = "\x1bP", "\x1b\\" + // Keep just the image. Encoders can add cursor controls or multiple frames + // that would escape the position set by the application. + _, afterDCS, found := bytes.Cut(encoded, []byte(dcs)) + if !found { + return "", false + } + frame, _, found := bytes.Cut(afterDCS, []byte(st)) + if !found { + return "", false + } + _, rasterData, found := bytes.Cut(frame, []byte("q")) + if !found { + return "", false + } + var width, height int + _, err := fmt.Fscanf(bytes.NewReader(rasterData), "\"1;1;%d;%d", &width, &height) + if err != nil || width <= 0 || height <= 0 || + width > pane.width*cellSize.X || height > pane.height*cellSize.Y/6*6 { + return "", false + } + pixelHeight := (height + 5) / 6 * 6 + col := pane.x + (pane.width*cellSize.X-width)/2/cellSize.X + row := pane.y + (pane.height*cellSize.Y-pixelHeight)/2/cellSize.Y + // Reset DEC Sixel display mode so the image starts at the cursor. + return xansi.SaveCursor + xansi.ResetMode(xansi.DECMode(80)) + + xansi.CursorPosition(col+1, row+1) + dcs + string(frame) + st + xansi.RestoreCursor, true +} + func (u *UI) fullscreenKittyImage(imageURL string) bool { for { width, height := u.terminal.Size() @@ -689,8 +740,17 @@ func parseGraphicsResponse(response, expectedItem string) (int, int, bool) { return width, height, width > 0 && height > 0 } -func (u *UI) nativePixelViewport(screenWidth, screenHeight int, pane paneLayout) *[2]int { - response, _ := u.terminal.Query(xansi.WindowOp(14), func(msg any) bool { +func (u *UI) sixelCellSize(screenWidth, screenHeight int) image.Point { + // Windows Terminal reports virtual Sixel pixels for the character cell. + response, _ := u.terminal.Query(xansi.WindowOp(16), func(msg any) bool { + _, ok := msg.(ultraviolet.CellSizeEvent) + return ok + }, 150*time.Millisecond) + if cell, ok := response.(ultraviolet.CellSizeEvent); ok && cell.Width > 0 && cell.Height > 0 { + return image.Pt(cell.Width, cell.Height) + } + + response, _ = u.terminal.Query(xansi.WindowOp(14), func(msg any) bool { _, ok := msg.(ultraviolet.PixelSizeEvent) return ok }, 150*time.Millisecond) @@ -706,28 +766,12 @@ func (u *UI) nativePixelViewport(screenWidth, screenHeight int, pane paneLayout) width, height, ok = parseGraphicsResponse(string(graphicsResponse), "2") } if !ok { - return nil + return image.Point{} } - cellResponse, _ := u.terminal.Query(xansi.WindowOp(16), func(msg any) bool { - _, ok := msg.(ultraviolet.CellSizeEvent) - return ok - }, 150*time.Millisecond) - cell, cellOK := cellResponse.(ultraviolet.CellSizeEvent) - cellWidth, cellHeight := cell.Width, cell.Height - if !cellOK || cellWidth <= 0 { - cellWidth = max(int(float64(width)/float64(max(screenWidth, 1))+0.5), 1) - } - if !cellOK || cellHeight <= 0 { - cellHeight = max(int(float64(height)/float64(max(screenHeight, 1))+0.5), 1) - } - viewport := [2]int{ - max(min(pane.width*cellWidth, width), 1), - max(min(pane.height*cellHeight, height), 1), - } - return &viewport + return image.Pt(width/max(screenWidth, 1), height/max(screenHeight, 1)) } -func (u *UI) renderNativeImage(imageURL string, width, lines int, viewport *[2]int) ([]byte, error) { +func (u *UI) renderNativeImage(imageURL string, maxPixels image.Point) ([]byte, error) { body, err := u.client.GetBytes(imageURL, envInt("TERMCOURSE_IMAGE_MAX_BYTES", 5_242_880)) if err != nil { return nil, err @@ -744,10 +788,11 @@ func (u *UI) renderNativeImage(imageURL string, width, lines int, viewport *[2]i return nil, err } _ = file.Close() - if viewport != nil { - for _, binary := range []string{"magick", "convert"} { - if path, lookupErr := exec.LookPath(binary); lookupErr == nil { - return exec.Command(path, name, "-resize", fmt.Sprintf("%dx%d", viewport[0], viewport[1]), "sixel:-").Output() + for _, binary := range []string{"magick", "convert"} { + if path, lookupErr := exec.LookPath(binary); lookupErr == nil { + size := fmt.Sprintf("%dx%d", maxPixels.X, maxPixels.Y) + if output, err := exec.Command(path, name+"[0]", "-resize", size, "sixel:-").Output(); err == nil && len(output) > 0 { + return output, nil } } } @@ -755,7 +800,15 @@ func (u *UI) renderNativeImage(imageURL string, width, lines int, viewport *[2]i if err != nil { return nil, err } - return exec.Command(path, chafaArgs(name, width, lines, true)...).Output() + // Chafa uses 8×8 output cells when run with piped output and no TTY. + const chafaCell = 8 + if maxPixels.X < chafaCell || maxPixels.Y < chafaCell { + return nil, fmt.Errorf("pane is too small for Chafa Sixel output") + } + size := fmt.Sprintf("%dx%d", maxPixels.X/chafaCell, maxPixels.Y/chafaCell) + return exec.Command(path, "--format", "sixels", "--font-ratio", "1", "--scale", "max", + "--animate", "off", "--polite", "on", "--passthrough", "none", + "--size", size, "--view-size", size, name).Output() } func lowQuality(lines []string) bool { diff --git a/internal/ui/images_test.go b/internal/ui/images_test.go index 1883f8b..1115413 100644 --- a/internal/ui/images_test.go +++ b/internal/ui/images_test.go @@ -1,16 +1,108 @@ package ui import ( + "fmt" "image" "image/color" "strconv" "strings" "testing" + "time" + tea "charm.land/bubbletea/v2" uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/x/ansi" "github.com/charmbracelet/x/ansi/kitty" ) +type terminalWrites chan string + +func (w terminalWrites) Write(p []byte) (int, error) { + w <- string(p) + return len(p), nil +} + +func TestSixelOverlayFollowsManagedFrame(t *testing.T) { + output := make(terminalWrites, 16) + terminal := NewTerminal(nil, output) + program := tea.NewProgram(terminalModel{state: terminal.state}, + tea.WithInput(nil), tea.WithOutput(output), tea.WithWindowSize(40, 10), tea.WithContext(t.Context())) + terminal.program = program + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = program.Run() + }() + t.Cleanup(func() { + program.Quit() + <-done + }) + + const header = "IMAGE FRAME" + const sixel = "\x1bPq#0;2;100;0;0#0~\x1b\\" + terminal.render(header, -1, -1, nil, true) + result := make(chan error, 1) + go func() { result <- terminal.rawAfterFrame(sixel) }() + + var stream strings.Builder + timeout := time.NewTimer(3 * time.Second) + defer timeout.Stop() + for { + select { + case write := <-output: + stream.WriteString(write) + if strings.Contains(write, ansi.RequestPrimaryDeviceAttributes) { + program.Send(uv.PrimaryDeviceAttributesEvent{4}) + } + if strings.Contains(write, sixel) { + if frame := strings.Index(stream.String(), header); frame < 0 || frame > strings.Index(stream.String(), sixel) { + t.Fatalf("Sixel sent before its managed frame: %q", stream.String()) + } + return + } + case err := <-result: + if err != nil { + t.Fatal(err) + } + case <-timeout.C: + t.Fatalf("Sixel output never arrived: %q", stream.String()) + } + } +} + +func TestSixelPlacementStaysInsidePane(t *testing.T) { + pane := paneLayout{x: 2, y: 7, width: 76, height: 19} + cellSize := image.Pt(10, 20) + for _, tc := range []struct { + name string + width, height int + cursor string + }{ + {"portrait", 180, 378, "\x1b[8;32H"}, + {"landscape", 760, 90, "\x1b[15;3H"}, + {"fills pane", 760, 378, "\x1b[8;3H"}, + {"too wide", 761, 300, ""}, + {"last band would clip border", 300, 380, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + frame := fmt.Sprintf("\x1bP0;0;0q\"1;1;%d;%d#0!10~\x1b\\", tc.width, tc.height) + // An encoder may emit extra cursor controls or animation frames. + encoded := "\x1b[?25l" + frame + "\x1b[?25h" + frame + sequence, ok := placeSixelInPane([]byte(encoded), pane, cellSize) + if tc.cursor == "" { + if ok { + t.Fatalf("accepted out-of-bounds Sixel raster: %q", sequence) + } + return + } + if !ok || !strings.Contains(sequence, tc.cursor+frame) || + strings.Count(sequence, frame) != 1 || strings.Contains(sequence, "\x1b[?25h") { + t.Fatalf("want one Sixel frame at %q, got %q", tc.cursor, sequence) + } + }) + } +} + func TestKittyPlacementSelectionSurvivesExpansionAndResize(t *testing.T) { // Each transition must replace the same explicitly selected placement. // An implicit placement can leave stale thumbnail geometry in Ghostty. diff --git a/internal/ui/terminal.go b/internal/ui/terminal.go index 16f6342..05600f5 100644 --- a/internal/ui/terminal.go +++ b/internal/ui/terminal.go @@ -10,6 +10,7 @@ import ( "time" tea "charm.land/bubbletea/v2" + uv "github.com/charmbracelet/ultraviolet" xansi "github.com/charmbracelet/x/ansi" "github.com/charmbracelet/x/term" ) @@ -162,6 +163,21 @@ func (t *Terminal) Raw(sequence string) { } } +func (t *Terminal) rawAfterFrame(sequence string) error { + // Bubble Tea flushes queued raw output before its managed frame. Wait for + // a terminal reply so the overlay is queued for a later flush than the + // frame beneath it. + _, err := t.Query(xansi.RequestPrimaryDeviceAttributes, func(msg any) bool { + _, ok := msg.(uv.PrimaryDeviceAttributesEvent) + return ok + }, 500*time.Millisecond) + if err != nil { + return err + } + t.Raw(sequence) + return nil +} + func (t *Terminal) Query(sequence string, accept func(any) bool, timeout time.Duration) (any, error) { if t.program == nil { return nil, errors.New("terminal program is not running") diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 3a5c7ea..0d3366a 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -1008,14 +1008,14 @@ func TestImageExtractionAndModes(t *testing.T) { } t.Setenv("TERMCOURSE_IMAGE_MODE", "balanced") t.Setenv("TERMCOURSE_IMAGE_COLORS", "full") - args := strings.Join(chafaArgs("/tmp/example.png", 40, 12, false), " ") + args := strings.Join(chafaArgs("/tmp/example.png", 40, 12), " ") for _, expected := range []string{"--symbols vhalf", "--colors full", "--optimize 5", "--work 5", "--size 40x12"} { if !strings.Contains(args, expected) { t.Fatalf("args %q missing %q", args, expected) } } t.Setenv("TERMCOURSE_IMAGE_MODE", "") - if defaults := strings.Join(chafaArgs("/tmp/example.png", 32, 6, false), " "); !strings.Contains(defaults, "--symbols vhalf") || !strings.Contains(defaults, "--colors full") { + if defaults := strings.Join(chafaArgs("/tmp/example.png", 32, 6), " "); !strings.Contains(defaults, "--symbols vhalf") || !strings.Contains(defaults, "--colors full") { t.Fatalf("default Chafa fallback is not colored and balanced: %q", defaults) } }