1package view
2
3import (
4 "bytes"
5 "encoding/base64"
6 "fmt"
7 "image"
8 "image/png"
9 "io"
10 "mime/quotedprintable"
11 "net/http"
12 "os"
13 "regexp"
14 "strings"
15 "time"
16
17 _ "image/gif"
18 _ "image/jpeg"
19
20 "github.com/PuerkitoBio/goquery"
21 "github.com/charmbracelet/lipgloss"
22 "github.com/yuin/goldmark"
23 "github.com/yuin/goldmark/renderer/html"
24 "golang.org/x/sys/unix"
25)
26
27// getTerminalCellSize returns the height of a terminal cell in pixels.
28// It queries the terminal using TIOCGWINSZ to get both character and pixel dimensions.
29// Falls back to a default of 18 pixels if the query fails.
30func getTerminalCellSize() int {
31 const defaultCellHeight = 18
32
33 // Try stdout, stdin, stderr, then /dev/tty as last resort
34 fds := []int{int(os.Stdout.Fd()), int(os.Stdin.Fd()), int(os.Stderr.Fd())}
35
36 for _, fd := range fds {
37 if cellHeight := getCellHeightFromFd(fd); cellHeight > 0 {
38 return cellHeight
39 }
40 }
41
42 // Try /dev/tty directly - this works even when stdio is redirected (e.g., in Bubble Tea)
43 if tty, err := os.Open("/dev/tty"); err == nil {
44 defer tty.Close()
45 if cellHeight := getCellHeightFromFd(int(tty.Fd())); cellHeight > 0 {
46 return cellHeight
47 }
48 }
49
50 debugImageProtocol("using default cell height: %d pixels", defaultCellHeight)
51 return defaultCellHeight
52}
53
54// getCellHeightFromFd attempts to get the terminal cell height from a file descriptor.
55// Returns 0 if it fails or if pixel dimensions are not available.
56func getCellHeightFromFd(fd int) int {
57 ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
58 if err != nil {
59 return 0
60 }
61
62 // ws.Row = number of character rows
63 // ws.Ypixel = height in pixels
64 // Some terminals don't report pixel dimensions (return 0)
65 if ws.Row > 0 && ws.Ypixel > 0 {
66 cellHeight := int(ws.Ypixel) / int(ws.Row)
67 if cellHeight > 0 {
68 debugImageProtocol("terminal cell height: %d pixels (rows=%d, ypixel=%d, fd=%d)", cellHeight, ws.Row, ws.Ypixel, fd)
69 return cellHeight
70 }
71 }
72
73 // Terminal reported dimensions but no pixel info - this is common
74 if ws.Row > 0 && ws.Ypixel == 0 {
75 debugImageProtocol("terminal fd=%d has rows=%d but no pixel info (ypixel=0)", fd, ws.Row)
76 }
77
78 return 0
79}
80
81// hyperlinkSupported checks if the terminal supports OSC 8 hyperlinks.
82func hyperlinkSupported() bool {
83 term := strings.ToLower(os.Getenv("TERM"))
84
85 // Terminals known to support OSC 8 hyperlinks
86 supportedTerms := []string{
87 "kitty",
88 "ghostty",
89 "wezterm",
90 "alacritty",
91 "foot",
92 "tmux",
93 "screen",
94 }
95
96 for _, supported := range supportedTerms {
97 if strings.Contains(term, supported) {
98 return true
99 }
100 }
101
102 // Check for specific terminal programs
103 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
104 supportedPrograms := []string{
105 "iterm.app",
106 "hyper",
107 "vscode",
108 "ghostty",
109 "wezterm",
110 }
111
112 for _, supported := range supportedPrograms {
113 if strings.Contains(termProgram, supported) {
114 return true
115 }
116 }
117
118 // Check for VTE-based terminals (GNOME Terminal, etc.)
119 if os.Getenv("VTE_VERSION") != "" {
120 return true
121 }
122
123 // Check for specific environment variables that indicate hyperlink support
124 if os.Getenv("KITTY_WINDOW_ID") != "" ||
125 os.Getenv("GHOSTTY_RESOURCES_DIR") != "" ||
126 os.Getenv("WEZTERM_EXECUTABLE") != "" {
127 return true
128 }
129
130 return false
131}
132
133// hyperlink formats a string as either a terminal-clickable hyperlink or plain text with URL.
134func hyperlink(url, text string) string {
135 if text == "" {
136 text = url
137 }
138
139 supported := hyperlinkSupported()
140
141 if supported {
142 // Use OSC 8 hyperlink sequence for supported terminals
143 return fmt.Sprintf("\x1b]8;;%s\x07%s\x1b]8;;\x07", url, text)
144 } else {
145 // Fallback to plain text format for unsupported terminals
146 if text == url {
147 return fmt.Sprintf("<%s>", url)
148 }
149 return fmt.Sprintf("%s <%s>", text, url)
150 }
151}
152
153func decodeQuotedPrintable(s string) (string, error) {
154 reader := quotedprintable.NewReader(strings.NewReader(s))
155 body, err := io.ReadAll(reader)
156 if err != nil {
157 return "", err
158 }
159 return string(body), nil
160}
161
162// markdownToHTML converts a Markdown string to an HTML string.
163func markdownToHTML(md []byte) []byte {
164 var buf bytes.Buffer
165 p := goldmark.New(
166 goldmark.WithRendererOptions(
167 html.WithUnsafe(), // Allow raw HTML in email.
168 ),
169 )
170 if err := p.Convert(md, &buf); err != nil {
171 return md // Fallback to original markdown.
172 }
173 return buf.Bytes()
174}
175
176func kittySupported() bool {
177 term := strings.ToLower(os.Getenv("TERM"))
178 if strings.Contains(term, "kitty") {
179 return true
180 }
181 return os.Getenv("KITTY_WINDOW_ID") != ""
182}
183
184func ghosttySupported() bool {
185 // Check for TERM containing ghostty
186 term := strings.ToLower(os.Getenv("TERM"))
187 if strings.Contains(term, "ghostty") {
188 return true
189 }
190
191 // Check for Ghostty-specific environment variables
192 if os.Getenv("TERM_PROGRAM") == "ghostty" {
193 return true
194 }
195
196 // Check for GHOSTTY_RESOURCES_DIR which Ghostty sets
197 return os.Getenv("GHOSTTY_RESOURCES_DIR") != ""
198}
199
200// imageProtocolSupported checks if any supported image protocol terminal is detected.
201func imageProtocolSupported() bool {
202 return kittySupported() || ghosttySupported()
203}
204
205func debugImageProtocol(format string, args ...interface{}) {
206 if os.Getenv("DEBUG_IMAGE_PROTOCOL") == "" && os.Getenv("DEBUG_KITTY_IMAGES") == "" {
207 return
208 }
209 msg := fmt.Sprintf("[img-protocol] "+format+"\n", args...)
210 fmt.Print(msg)
211 if path := os.Getenv("DEBUG_IMAGE_PROTOCOL_LOG"); path != "" {
212 if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
213 _, _ = f.WriteString(msg)
214 _ = f.Close()
215 }
216 } else if path := os.Getenv("DEBUG_KITTY_LOG"); path != "" {
217 if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
218 _, _ = f.WriteString(msg)
219 _ = f.Close()
220 }
221 }
222}
223
224func fetchRemoteBase64(url string) string {
225 if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
226 return ""
227 }
228 client := &http.Client{Timeout: 5 * time.Second}
229 resp, err := client.Get(url)
230 if err != nil {
231 debugImageProtocol("remote fetch failed url=%s err=%v", url, err)
232 return ""
233 }
234 defer resp.Body.Close()
235 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
236 debugImageProtocol("remote fetch non-200 url=%s status=%d", url, resp.StatusCode)
237 return ""
238 }
239 data, err := io.ReadAll(resp.Body)
240 if err != nil {
241 debugImageProtocol("remote fetch read error url=%s err=%v", url, err)
242 return ""
243 }
244
245 img, _, err := image.Decode(bytes.NewReader(data))
246 if err != nil {
247 debugImageProtocol("remote decode failed url=%s err=%v", url, err)
248 return ""
249 }
250
251 var buf bytes.Buffer
252 if err := png.Encode(&buf, img); err != nil {
253 debugImageProtocol("remote png encode failed url=%s err=%v", url, err)
254 return ""
255 }
256
257 encoded := base64.StdEncoding.EncodeToString(buf.Bytes())
258 debugImageProtocol("remote fetch ok url=%s len=%d", url, len(encoded))
259 return encoded
260}
261
262func dataURIBase64(uri string) string {
263 if !strings.HasPrefix(uri, "data:") {
264 return ""
265 }
266 comma := strings.Index(uri, ",")
267 if comma == -1 || comma+1 >= len(uri) {
268 return ""
269 }
270 return uri[comma+1:]
271}
272
273// imageRowPlaceholderPrefix is used to mark where image row spacing should be inserted.
274// This prevents the newline-collapsing regex from removing intentional spacing.
275// Uses brackets instead of angle brackets to avoid being interpreted as HTML tags.
276const imageRowPlaceholderPrefix = "[[MATCHA_IMG_ROWS:"
277const imageRowPlaceholderSuffix = "]]"
278
279func kittyInlineImage(payload string) string {
280 if payload == "" {
281 return ""
282 }
283
284 const chunkSize = 4096
285 var b strings.Builder
286
287 // Calculate how many terminal rows the image occupies to advance text after it.
288 rows := 1
289 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
290 if img, _, err := image.Decode(bytes.NewReader(data)); err == nil {
291 cellHeight := getTerminalCellSize()
292 h := img.Bounds().Dy()
293 rows = (h + cellHeight - 1) / cellHeight
294 if rows < 1 {
295 rows = 1
296 }
297 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
298 }
299 }
300
301 for offset := 0; offset < len(payload); offset += chunkSize {
302 end := offset + chunkSize
303 if end > len(payload) {
304 end = len(payload)
305 }
306 more := "0"
307 if end < len(payload) {
308 more = "1"
309 }
310
311 chunk := payload[offset:end]
312 if offset == 0 {
313 // C=1 means cursor does NOT move after image render (stays at top-left of image position)
314 // This is needed for proper TUI rendering, but we must add newlines to push text below
315 b.WriteString(fmt.Sprintf("\x1b_Gf=100,a=T,q=2,C=1,m=%s;%s\x1b\\", more, chunk))
316 } else {
317 b.WriteString(fmt.Sprintf("\x1b_Gm=%s;%s\x1b\\", more, chunk))
318 }
319 }
320
321 // Add newlines to push cursor below the image.
322 // Use a placeholder that won't be collapsed by the newline regex.
323 b.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
324
325 return b.String()
326}
327
328// expandImageRowPlaceholders replaces image row placeholders with actual newlines.
329func expandImageRowPlaceholders(text string) string {
330 re := regexp.MustCompile(regexp.QuoteMeta(imageRowPlaceholderPrefix) + `(\d+)` + regexp.QuoteMeta(imageRowPlaceholderSuffix))
331 return re.ReplaceAllStringFunc(text, func(match string) string {
332 // Extract the number of rows from the placeholder
333 numStr := strings.TrimPrefix(match, imageRowPlaceholderPrefix)
334 numStr = strings.TrimSuffix(numStr, imageRowPlaceholderSuffix)
335 rows := 1
336 if _, err := fmt.Sscanf(numStr, "%d", &rows); err != nil || rows < 1 {
337 rows = 1
338 }
339 // Return the newlines needed to push content below the image
340 return strings.Repeat("\n", rows)
341 })
342}
343
344type InlineImage struct {
345 CID string
346 Base64 string
347}
348
349// ProcessBodyWithInline renders the body and resolves CID inline images when provided.
350func ProcessBodyWithInline(rawBody string, inline []InlineImage, h1Style, h2Style, bodyStyle lipgloss.Style) (string, error) {
351 inlineMap := make(map[string]string, len(inline))
352 for _, img := range inline {
353 cid := strings.TrimSpace(img.CID)
354 cid = strings.TrimPrefix(cid, "<")
355 cid = strings.TrimSuffix(cid, ">")
356 cid = strings.TrimPrefix(cid, "cid:")
357 if cid == "" || img.Base64 == "" {
358 continue
359 }
360 inlineMap[cid] = img.Base64
361 }
362 return processBody(rawBody, inlineMap, h1Style, h2Style, bodyStyle)
363}
364
365// ProcessBody takes a raw email body, decodes it, and formats it as plain
366// text with terminal hyperlinks.
367func ProcessBody(rawBody string, h1Style, h2Style, bodyStyle lipgloss.Style) (string, error) {
368 return processBody(rawBody, nil, h1Style, h2Style, bodyStyle)
369}
370
371func processBody(rawBody string, inline map[string]string, h1Style, h2Style, bodyStyle lipgloss.Style) (string, error) {
372 decodedBody, err := decodeQuotedPrintable(rawBody)
373 if err != nil {
374 decodedBody = rawBody
375 }
376
377 htmlBody := markdownToHTML([]byte(decodedBody))
378
379 doc, err := goquery.NewDocumentFromReader(bytes.NewReader(htmlBody))
380 if err != nil {
381 return "", fmt.Errorf("could not parse email body: %w", err)
382 }
383
384 doc.Find("style, script").Remove()
385
386 // Style headers by setting their text content.
387 // We use SetText so the h1/h2 tags remain in the document for spacing logic.
388 doc.Find("h1").Each(func(i int, s *goquery.Selection) {
389 s.SetText(h1Style.Render(s.Text()))
390 })
391
392 doc.Find("h2").Each(func(i int, s *goquery.Selection) {
393 s.SetText(h2Style.Render(s.Text()))
394 })
395
396 // Add newlines after block elements for better spacing.
397 doc.Find("p, div, h1, h2").Each(func(i int, s *goquery.Selection) {
398 s.After("\n\n")
399 })
400
401 // Replace <br> tags with newlines
402 doc.Find("br").Each(func(i int, s *goquery.Selection) {
403 s.ReplaceWithHtml("\n")
404 })
405
406 // Format links and images
407 doc.Find("a").Each(func(i int, s *goquery.Selection) {
408 href, exists := s.Attr("href")
409 if !exists {
410 return
411 }
412 s.ReplaceWithHtml(hyperlink(href, s.Text()))
413 })
414
415 doc.Find("img").Each(func(i int, s *goquery.Selection) {
416 src, exists := s.Attr("src")
417 if !exists {
418 return
419 }
420 alt, _ := s.Attr("alt")
421 if alt == "" {
422 alt = "Does not contain alt text"
423 }
424
425 if imageProtocolSupported() {
426 var payload string
427 if strings.HasPrefix(src, "data:image/") {
428 payload = dataURIBase64(src)
429 } else if strings.HasPrefix(src, "cid:") {
430 cid := strings.TrimPrefix(src, "cid:")
431 cid = strings.Trim(cid, "<>")
432 if inline != nil {
433 payload = inline[cid]
434 debugImageProtocol("cid lookup for %s found=%t len=%d", cid, payload != "", len(payload))
435 } else {
436 debugImageProtocol("cid lookup skipped inline map nil for %s", cid)
437 }
438 } else if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
439 payload = fetchRemoteBase64(src)
440 }
441
442 if payload != "" {
443 if rendered := kittyInlineImage(payload); rendered != "" {
444 debugImageProtocol("rendered inline image src=%s len=%d dataURI=%t cid=%t (kitty=%t ghostty=%t)", src, len(payload), strings.HasPrefix(src, "data:"), strings.HasPrefix(src, "cid:"), kittySupported(), ghosttySupported())
445 s.ReplaceWithHtml("\n" + rendered + "\n")
446 return
447 }
448 debugImageProtocol("payload present but renderer returned empty src=%s len=%d", src, len(payload))
449 } else {
450 debugImageProtocol("no payload for src=%s dataURI=%t cid=%t", src, strings.HasPrefix(src, "data:"), strings.HasPrefix(src, "cid:"))
451 }
452 } else {
453 debugImageProtocol("image protocol not supported for src=%s (kitty=%t ghostty=%t)", src, kittySupported(), ghosttySupported())
454 }
455 if hyperlinkSupported() {
456 s.ReplaceWithHtml(hyperlink(src, fmt.Sprintf("\n [Click here to view image: %s] \n", alt)))
457 } else {
458 s.ReplaceWithHtml(fmt.Sprintf("\n [Image: %s, %s] \n", alt, src))
459 }
460 })
461
462 text := doc.Text()
463
464 // Collapse excessive newlines, but not the image row placeholders
465 re := regexp.MustCompile(`\n{3,}`)
466 text = re.ReplaceAllString(text, "\n\n")
467
468 // Now expand the image row placeholders to actual newlines
469 text = expandImageRowPlaceholders(text)
470
471 return bodyStyle.Render(text), nil
472}