1package view
2
3import (
4 "encoding/base64"
5 "fmt"
6 "io"
7 "mime/quotedprintable"
8 "os"
9 "regexp"
10 "strings"
11 "sync/atomic"
12 "time"
13
14 "charm.land/lipgloss/v2"
15 "github.com/floatpane/matcha/clib"
16 "github.com/floatpane/matcha/internal/httpclient"
17 "github.com/floatpane/matcha/theme"
18 lru "github.com/hashicorp/golang-lru/v2"
19)
20
21func linkStyle() lipgloss.Style {
22 return lipgloss.NewStyle().Foreground(theme.ActiveTheme.Link)
23}
24
25// getTerminalCellSize returns the height of a terminal cell in pixels.
26// It queries the terminal using TIOCGWINSZ to get both character and pixel dimensions.
27// Falls back to a default of 18 pixels if the query fails.
28func getTerminalCellSize() int {
29 const defaultCellHeight = 18
30
31 // Try stdout, stdin, stderr, then /dev/tty as last resort
32 fds := []int{int(os.Stdout.Fd()), int(os.Stdin.Fd()), int(os.Stderr.Fd())}
33
34 for _, fd := range fds {
35 if cellHeight := getCellHeightFromFd(fd); cellHeight > 0 {
36 return cellHeight
37 }
38 }
39
40 // Try /dev/tty directly - this works even when stdio is redirected (e.g., in Bubble Tea)
41 if tty, err := os.Open("/dev/tty"); err == nil {
42 defer tty.Close()
43 if cellHeight := getCellHeightFromFd(int(tty.Fd())); cellHeight > 0 {
44 return cellHeight
45 }
46 }
47
48 debugImageProtocol("using default cell height: %d pixels", defaultCellHeight)
49 return defaultCellHeight
50}
51
52// hyperlinkSupported checks if the terminal supports OSC 8 hyperlinks.
53func hyperlinkSupported() bool {
54 term := strings.ToLower(os.Getenv("TERM"))
55
56 // Terminals known to support OSC 8 hyperlinks
57 supportedTerms := []string{
58 "kitty",
59 "ghostty",
60 "wezterm",
61 "alacritty",
62 "foot",
63 "tmux",
64 "screen",
65 }
66
67 for _, supported := range supportedTerms {
68 if strings.Contains(term, supported) {
69 return true
70 }
71 }
72
73 // Check for specific terminal programs
74 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
75 supportedPrograms := []string{
76 "iterm.app",
77 "hyper",
78 "vscode",
79 "ghostty",
80 "wezterm",
81 }
82
83 for _, supported := range supportedPrograms {
84 if strings.Contains(termProgram, supported) {
85 return true
86 }
87 }
88
89 // Check for VTE-based terminals (GNOME Terminal, etc.)
90 if os.Getenv("VTE_VERSION") != "" {
91 return true
92 }
93
94 // Check for specific environment variables that indicate hyperlink support
95 if os.Getenv("KITTY_WINDOW_ID") != "" ||
96 os.Getenv("GHOSTTY_RESOURCES_DIR") != "" ||
97 os.Getenv("WEZTERM_EXECUTABLE") != "" ||
98 os.Getenv("WT_SESSION") != "" {
99 return true
100 }
101
102 return false
103}
104
105// hyperlink formats a string as either a terminal-clickable hyperlink or plain text with URL.
106func hyperlink(url, text string) string {
107 if text == "" {
108 text = url
109 }
110
111 supported := hyperlinkSupported()
112
113 if supported {
114 // Use OSC 8 hyperlink sequence for supported terminals
115 return fmt.Sprintf("\x1b]8;;%s\x07%s\x1b]8;;\x07", url, linkStyle().Render(text))
116 } else {
117 // Fallback to plain text format for unsupported terminals
118 if text == url {
119 return fmt.Sprintf("<%s>", linkStyle().Render(url))
120 }
121 return fmt.Sprintf("%s <%s>", linkStyle().Render(text), linkStyle().Render(url))
122 }
123}
124
125func decodeQuotedPrintable(s string) (string, error) {
126 reader := quotedprintable.NewReader(strings.NewReader(s))
127 body, err := io.ReadAll(reader)
128 if err != nil {
129 return "", err
130 }
131 return string(body), nil
132}
133
134// markdownToHTML converts a Markdown string to an HTML string using md4c (C).
135func markdownToHTML(md []byte) []byte {
136 return clib.MarkdownToHTML(md)
137}
138
139func kittySupported() bool {
140 term := strings.ToLower(os.Getenv("TERM"))
141 if strings.Contains(term, "kitty") {
142 return true
143 }
144 return os.Getenv("KITTY_WINDOW_ID") != ""
145}
146
147func ghosttySupported() bool {
148 // Check for TERM containing ghostty
149 term := strings.ToLower(os.Getenv("TERM"))
150 if strings.Contains(term, "ghostty") {
151 return true
152 }
153
154 // Check for Ghostty-specific environment variables
155 if os.Getenv("TERM_PROGRAM") == "ghostty" {
156 return true
157 }
158
159 // Check for GHOSTTY_RESOURCES_DIR which Ghostty sets
160 return os.Getenv("GHOSTTY_RESOURCES_DIR") != ""
161}
162
163func iterm2Supported() bool {
164 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
165 if termProgram == "iterm.app" {
166 return true
167 }
168
169 // Check for iTerm2-specific environment variables
170 if os.Getenv("ITERM_SESSION_ID") != "" || os.Getenv("ITERM_PROFILE") != "" {
171 return true
172 }
173
174 return false
175}
176
177func weztermSupported() bool {
178 // Check for WezTerm-specific environment variables
179 if os.Getenv("WEZTERM_EXECUTABLE") != "" || os.Getenv("WEZTERM_CONFIG_FILE") != "" {
180 return true
181 }
182
183 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
184 if termProgram == "wezterm" {
185 return true
186 }
187
188 term := strings.ToLower(os.Getenv("TERM"))
189 if strings.Contains(term, "wezterm") {
190 return true
191 }
192
193 return false
194}
195
196func waystSupported() bool {
197 term := strings.ToLower(os.Getenv("TERM"))
198 if strings.Contains(term, "wayst") {
199 return true
200 }
201
202 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
203 if termProgram == "wayst" {
204 return true
205 }
206
207 return false
208}
209
210func warpSupported() bool {
211 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
212 if termProgram == "warp" {
213 return true
214 }
215
216 // Check for Warp-specific environment variables
217 if os.Getenv("WARP_IS_LOCAL_SHELL_SESSION") != "" || os.Getenv("WARP_COMBINED_PROMPT_COMMAND_FINISHED") != "" {
218 return true
219 }
220
221 return false
222}
223
224func konsoleSupported() bool {
225 // Check for Konsole-specific environment variables
226 if os.Getenv("KONSOLE_DBUS_SESSION") != "" || os.Getenv("KONSOLE_VERSION") != "" {
227 return true
228 }
229
230 termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
231 if termProgram == "konsole" {
232 return true
233 }
234
235 return false
236}
237
238func zellijSupported() bool {
239 return os.Getenv("ZELLIJ") != "" || os.Getenv("ZELLIJ_SESSION_NAME") != ""
240}
241
242func sixelSupported() bool {
243 // Zellij always supports Sixel
244 if zellijSupported() {
245 return true
246 }
247
248 // Native Sixel terminals
249 term := strings.ToLower(os.Getenv("TERM"))
250 return strings.Contains(term, "mlterm") ||
251 strings.Contains(term, "foot") ||
252 (strings.Contains(term, "xterm") && os.Getenv("SIXEL") == "1")
253}
254
255// ImageProtocolSupported checks if any supported image protocol terminal is detected.
256func ImageProtocolSupported() bool {
257 return imageProtocolSupported()
258}
259
260// SixelSupported returns true if the terminal uses the Sixel graphics protocol.
261func SixelSupported() bool {
262 return sixelSupported()
263}
264
265// imageProtocolSupported checks if any supported image protocol terminal is detected.
266func imageProtocolSupported() bool {
267 return sixelSupported() || kittySupported() || ghosttySupported() || iterm2Supported() ||
268 weztermSupported() || waystSupported() || warpSupported() || konsoleSupported()
269}
270
271func debugImageProtocol(format string, args ...interface{}) {
272 if os.Getenv("DEBUG_IMAGE_PROTOCOL") == "" && os.Getenv("DEBUG_KITTY_IMAGES") == "" {
273 return
274 }
275 msg := fmt.Sprintf("[img-protocol] "+format+"\n", args...)
276 fmt.Print(msg)
277 if path := os.Getenv("DEBUG_IMAGE_PROTOCOL_LOG"); path != "" {
278 if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
279 _, _ = f.WriteString(msg)
280 _ = f.Close()
281 }
282 } else if path := os.Getenv("DEBUG_KITTY_LOG"); path != "" {
283 if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
284 _, _ = f.WriteString(msg)
285 _ = f.Close()
286 }
287 }
288}
289
290const remoteImageCacheSize = 20
291
292// remoteImageCache caches fetched remote images (URL -> base64 PNG string).
293var remoteImageCache *lru.Cache[string, string]
294
295func init() {
296 c, err := lru.New[string, string](remoteImageCacheSize)
297 if err != nil {
298 panic(err) // only fails on size <= 0
299 }
300 remoteImageCache = c
301}
302
303// nextImageID is an auto-incrementing counter for Kitty image IDs.
304var nextImageID uint32 = 1000
305
306// allocImageID returns a unique Kitty image ID.
307func allocImageID() uint32 {
308 return atomic.AddUint32(&nextImageID, 1)
309}
310
311func fetchRemoteBase64(url string) string {
312 if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
313 return ""
314 }
315
316 // Check cache first
317 if cached, ok := remoteImageCache.Get(url); ok {
318 debugImageProtocol("remote cache hit url=%s", url)
319 return cached
320 }
321
322 client := httpclient.New(httpclient.RemoteImageTimeout)
323 resp, err := client.Get(url)
324 if err != nil {
325 debugImageProtocol("remote fetch failed url=%s err=%v", url, err)
326 return ""
327 }
328 defer resp.Body.Close()
329 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
330 debugImageProtocol("remote fetch non-200 url=%s status=%d", url, resp.StatusCode)
331 return ""
332 }
333 // Limit response body to 10 MB to prevent memory exhaustion from
334 // malicious or very large images.
335 const maxImageSize = 10 << 20 // 10 MB
336 data, err := io.ReadAll(io.LimitReader(resp.Body, maxImageSize))
337 if err != nil {
338 debugImageProtocol("remote fetch read error url=%s err=%v", url, err)
339 return ""
340 }
341
342 result, ok := clib.DecodeToPNG(data)
343 if !ok {
344 debugImageProtocol("remote decode failed url=%s", url)
345 return ""
346 }
347
348 encoded := base64.StdEncoding.EncodeToString(result.PNGData)
349 debugImageProtocol("remote fetch ok url=%s len=%d", url, len(encoded))
350 remoteImageCache.Add(url, encoded)
351 return encoded
352}
353
354func dataURIBase64(uri string) string {
355 if !strings.HasPrefix(uri, "data:") {
356 return ""
357 }
358 comma := strings.Index(uri, ",")
359 if comma == -1 || comma+1 >= len(uri) {
360 return ""
361 }
362 return uri[comma+1:]
363}
364
365// imageRowPlaceholderPrefix is used to mark where image row spacing should be inserted.
366// This prevents the newline-collapsing regex from removing intentional spacing.
367// Uses brackets instead of angle brackets to avoid being interpreted as HTML tags.
368const imageRowPlaceholderPrefix = "[[MATCHA_IMG_ROWS:"
369const imageRowPlaceholderSuffix = "]]"
370
371func kittyInlineImage(payload string) string {
372 if payload == "" {
373 return ""
374 }
375
376 const chunkSize = 4096
377 var b strings.Builder
378
379 // Calculate how many terminal rows the image occupies to advance text after it.
380 rows := 1
381 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
382 if _, h, ok := clib.ImageDimensions(data); ok {
383 cellHeight := getTerminalCellSize()
384 rows = (h + cellHeight - 1) / cellHeight
385 if rows < 1 {
386 rows = 1
387 }
388 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
389 }
390 }
391
392 for offset := 0; offset < len(payload); offset += chunkSize {
393 end := offset + chunkSize
394 if end > len(payload) {
395 end = len(payload)
396 }
397 more := "0"
398 if end < len(payload) {
399 more = "1"
400 }
401
402 chunk := payload[offset:end]
403 if offset == 0 {
404 // C=1 means cursor does NOT move after image render (stays at top-left of image position)
405 // This is needed for proper TUI rendering, but we must add newlines to push text below
406 b.WriteString(fmt.Sprintf("\x1b_Gf=100,a=T,q=2,C=1,m=%s;%s\x1b\\", more, chunk))
407 } else {
408 b.WriteString(fmt.Sprintf("\x1b_Gm=%s;%s\x1b\\", more, chunk))
409 }
410 }
411
412 // Add newlines to push cursor below the image.
413 // Use a placeholder that won't be collapsed by the newline regex.
414 b.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
415
416 return b.String()
417}
418
419// iterm2InlineImage renders an image using iTerm2's image protocol
420func iterm2InlineImage(payload string) string {
421 if payload == "" {
422 return ""
423 }
424
425 // Calculate rows for cursor positioning
426 rows := 1
427 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
428 if _, h, ok := clib.ImageDimensions(data); ok {
429 cellHeight := getTerminalCellSize()
430 rows = (h + cellHeight - 1) / cellHeight
431 if rows < 1 {
432 rows = 1
433 }
434 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
435 }
436 }
437
438 // iTerm2 image protocol: ESC]1337;File=inline=1:<base64_data>BEL
439 result := fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07\n", payload)
440
441 // Add placeholder for row spacing
442 result += fmt.Sprintf("%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix)
443
444 return result
445}
446
447// sixelInlineImage returns Sixel escape sequence + newline placeholders
448func sixelInlineImage(base64PNG string) string {
449 data, err := base64.StdEncoding.DecodeString(base64PNG)
450 if err != nil {
451 return ""
452 }
453
454 cellHeight := getTerminalCellSize()
455 sixel, rows, err := clib.EncodePNGToSixel(data, cellHeight)
456 if err != nil {
457 debugImageProtocol("Sixel encoding failed: %v", err)
458 return ""
459 }
460
461 debugImageProtocol("Sixel: encoded %d bytes, %d rows", len(sixel), rows)
462
463 // Sixel sequences don't auto-advance cursor
464 // Add newlines to preserve layout
465 return sixel + strings.Repeat("\n", rows)
466}
467
468// sixelImageEscapeOnly returns raw Sixel for out-of-band rendering
469func sixelImageEscapeOnly(base64PNG string) string {
470 data, err := base64.StdEncoding.DecodeString(base64PNG)
471 if err != nil {
472 return ""
473 }
474
475 cellHeight := getTerminalCellSize()
476 sixel, _, err := clib.EncodePNGToSixel(data, cellHeight)
477 if err != nil {
478 return ""
479 }
480
481 return sixel
482}
483
484// renderInlineImage renders an image using the appropriate protocol for the detected terminal
485func renderInlineImage(payload string) string {
486 if payload == "" {
487 return ""
488 }
489
490 // Priority: Sixel in multiplexers overrides native protocols
491 if sixelSupported() {
492 return sixelInlineImage(payload)
493 }
494
495 if kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported() {
496 // These terminals use the Kitty graphics protocol
497 return kittyInlineImage(payload)
498 } else if iterm2Supported() || warpSupported() {
499 // iTerm2 and Warp use the iTerm2 image protocol
500 return iterm2InlineImage(payload)
501 }
502
503 return ""
504}
505
506// imageRows calculates the number of terminal rows an image occupies.
507func imageRows(payload string) int {
508 rows := 1
509 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
510 if _, h, ok := clib.ImageDimensions(data); ok {
511 cellHeight := getTerminalCellSize()
512 rows = (h + cellHeight - 1) / cellHeight
513 if rows < 1 {
514 rows = 1
515 }
516 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
517 }
518 }
519 return rows
520}
521
522// kittyUploadImage uploads image data to the terminal with a unique ID using
523// the Kitty graphics protocol transmit action (a=t). The image is stored in
524// the terminal's memory and can be displayed later by ID without re-sending data.
525func kittyUploadImage(payload string, id uint32) {
526 if payload == "" {
527 return
528 }
529
530 const chunkSize = 4096
531 for offset := 0; offset < len(payload); offset += chunkSize {
532 end := offset + chunkSize
533 if end > len(payload) {
534 end = len(payload)
535 }
536 more := "0"
537 if end < len(payload) {
538 more = "1"
539 }
540
541 chunk := payload[offset:end]
542 if offset == 0 {
543 // a=t: transmit (upload) only, don't display yet
544 // i=ID: assign this image ID
545 fmt.Fprintf(os.Stdout, "\x1b_Gf=100,a=t,i=%d,q=2,m=%s;%s\x1b\\", id, more, chunk)
546 } else {
547 fmt.Fprintf(os.Stdout, "\x1b_Gm=%s;%s\x1b\\", more, chunk)
548 }
549 }
550 os.Stdout.Sync()
551}
552
553// kittyDisplayImage displays a previously uploaded image by its ID at the
554// current cursor position. This is very fast since no image data is transmitted.
555func kittyDisplayImage(id uint32) string {
556 // a=p: put (display) an already-uploaded image by ID
557 // C=1: cursor does not move
558 return fmt.Sprintf("\x1b_Ga=p,i=%d,q=2,C=1\x1b\\", id)
559}
560
561// iterm2ImageEscapeOnly returns only the iTerm2 image protocol escape sequence
562// without any row placeholders. Used for out-of-band rendering to stdout.
563func iterm2ImageEscapeOnly(payload string) string {
564 if payload == "" {
565 return ""
566 }
567 return fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07", payload)
568}
569
570// RenderImageToStdout writes an image directly to stdout at the given screen
571// row using cursor positioning. This bypasses bubbletea's cell-based renderer
572// which cannot handle graphics protocol escape sequences.
573//
574// For Kitty-protocol terminals, images are uploaded once and then displayed by
575// ID on subsequent calls, making scroll rendering nearly instant.
576func RenderImageToStdout(placement *ImagePlacement, screenRow int, screenCol ...int) {
577 if placement.Base64 == "" {
578 return
579 }
580
581 col := 1
582 if len(screenCol) > 0 && screenCol[0] > 0 {
583 col = screenCol[0]
584 }
585
586 // Priority: Sixel in multiplexers
587 if sixelSupported() {
588 debugImageProtocol("Sixel: RenderImageToStdout row=%d col=%d base64len=%d", screenRow, col, len(placement.Base64))
589
590 // Encode once, reuse cached Sixel on subsequent renders (like Kitty's upload-once pattern)
591 if placement.SixelEncoded == "" {
592 placement.SixelEncoded = sixelImageEscapeOnly(placement.Base64)
593 if placement.SixelEncoded == "" {
594 debugImageProtocol("Sixel: sixelImageEscapeOnly returned empty")
595 return
596 }
597 }
598
599 debugImageProtocol("Sixel: rendering %d bytes at row=%d col=%d", len(placement.SixelEncoded), screenRow+1, col)
600 // Position cursor + render Sixel
601 fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;%dH%s\x1b[u",
602 screenRow+1, col, placement.SixelEncoded)
603 os.Stdout.Sync()
604 return
605 }
606
607 useKitty := kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported()
608 useIterm2 := iterm2Supported() || warpSupported()
609
610 if useKitty {
611 // Upload once, display by ID on subsequent renders
612 if !placement.Uploaded {
613 placement.ID = allocImageID()
614 kittyUploadImage(placement.Base64, placement.ID)
615 placement.Uploaded = true
616 }
617 seq := kittyDisplayImage(placement.ID)
618 fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;%dH%s\x1b[u", screenRow+1, col, seq)
619 os.Stdout.Sync()
620 } else if useIterm2 {
621 seq := iterm2ImageEscapeOnly(placement.Base64)
622 fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;%dH%s\x1b[u", screenRow+1, col, seq)
623 os.Stdout.Sync()
624 }
625}
626
627// expandImageRowPlaceholders replaces image row placeholders with actual newlines.
628func expandImageRowPlaceholders(text string) string {
629 re := regexp.MustCompile(regexp.QuoteMeta(imageRowPlaceholderPrefix) + `(\d+)` + regexp.QuoteMeta(imageRowPlaceholderSuffix))
630 return re.ReplaceAllStringFunc(text, func(match string) string {
631 // Extract the number of rows from the placeholder
632 numStr := strings.TrimPrefix(match, imageRowPlaceholderPrefix)
633 numStr = strings.TrimSuffix(numStr, imageRowPlaceholderSuffix)
634 rows := 1
635 if _, err := fmt.Sscanf(numStr, "%d", &rows); err != nil || rows < 1 {
636 rows = 1
637 }
638 // Return the newlines needed to push content below the image
639 return strings.Repeat("\n", rows)
640 })
641}
642
643type InlineImage struct {
644 CID string
645 Base64 string
646}
647
648// ImagePlacement holds the data needed to render an image at a specific
649// line in the email body. Images are rendered directly to stdout (bypassing
650// bubbletea's cell-based renderer which cannot handle graphics protocols).
651type ImagePlacement struct {
652 Line int // Line number in the processed body text where the image starts
653 Base64 string // Base64-encoded image data (PNG)
654 Rows int // Number of terminal rows the image occupies
655 Uploaded bool // Whether the image has been uploaded to the terminal via Kitty ID
656 ID uint32 // Kitty image ID for display-by-reference
657 SixelEncoded string // Cached Sixel escape sequence (encode once, reuse on scroll)
658}
659
660// ProcessBodyWithInline renders the body and resolves CID inline images when provided.
661// Returns the rendered body text, image placements for out-of-band rendering, and any error.
662func ProcessBodyWithInline(rawBody string, inline []InlineImage, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
663 inlineMap := make(map[string]string, len(inline))
664 for _, img := range inline {
665 cid := strings.TrimSpace(img.CID)
666 cid = strings.TrimPrefix(cid, "<")
667 cid = strings.TrimSuffix(cid, ">")
668 cid = strings.TrimPrefix(cid, "cid:")
669 if cid == "" || img.Base64 == "" {
670 continue
671 }
672 inlineMap[cid] = img.Base64
673 }
674 return processBody(rawBody, inlineMap, h1Style, h2Style, bodyStyle, disableImages)
675}
676
677// ProcessBody takes a raw email body, decodes it, and formats it as plain
678// text with terminal hyperlinks.
679func ProcessBody(rawBody string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
680 return processBody(rawBody, nil, h1Style, h2Style, bodyStyle, disableImages)
681}
682
683func processBody(rawBody string, inline map[string]string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
684 decodedBody, err := decodeQuotedPrintable(rawBody)
685 if err != nil {
686 decodedBody = rawBody
687 }
688
689 htmlBody := markdownToHTML([]byte(decodedBody))
690
691 // Parse HTML into structured elements using C parser.
692 elements, ok := clib.HTMLToElements(string(htmlBody))
693 if !ok {
694 return "", nil, fmt.Errorf("could not parse email body")
695 }
696
697 // Process elements: apply styles and collect image placements.
698 var text strings.Builder
699 var imgIndex int
700 var pendingImages []struct {
701 index int
702 payload string
703 rows int
704 }
705
706 onWroteRegex := regexp.MustCompile(`On\s+(.+?),\s+(.+?)\s+wrote:`)
707
708 for _, elem := range elements {
709 switch elem.Type {
710 case clib.HElemText:
711 text.WriteString(elem.Text)
712
713 case clib.HElemH1:
714 text.WriteString(h1Style.Render(elem.Text))
715 text.WriteString("\n\n")
716
717 case clib.HElemH2:
718 text.WriteString(h2Style.Render(elem.Text))
719 text.WriteString("\n\n")
720
721 case clib.HElemLink:
722 text.WriteString(hyperlink(elem.Attr1, elem.Text))
723
724 case clib.HElemImage:
725 src := elem.Attr1
726 alt := elem.Attr2
727
728 if !disableImages && imageProtocolSupported() {
729 var payload string
730 if strings.HasPrefix(src, "data:image/") {
731 payload = dataURIBase64(src)
732 } else if strings.HasPrefix(src, "cid:") {
733 cid := strings.TrimPrefix(src, "cid:")
734 cid = strings.Trim(cid, "<>")
735 if inline != nil {
736 payload = inline[cid]
737 debugImageProtocol("cid lookup for %s found=%t len=%d", cid, payload != "", len(payload))
738 } else {
739 debugImageProtocol("cid lookup skipped inline map nil for %s", cid)
740 }
741 } else if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
742 payload = fetchRemoteBase64(src)
743 }
744
745 if payload != "" {
746 rows := imageRows(payload)
747 debugImageProtocol("collected image placement src=%s rows=%d", src, rows)
748
749 idx := imgIndex
750 imgIndex++
751 pendingImages = append(pendingImages, struct {
752 index int
753 payload string
754 rows int
755 }{idx, payload, rows})
756
757 text.WriteString(fmt.Sprintf("\n[[MATCHA_IMG:%d]]", idx))
758 text.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
759 continue
760 }
761 debugImageProtocol("no payload for src=%s", src)
762 }
763 if hyperlinkSupported() {
764 text.WriteString(hyperlink(src, fmt.Sprintf("\n [Click here to view image: %s] \n", alt)))
765 } else {
766 text.WriteString(fmt.Sprintf("\n %s \n", linkStyle().Render(fmt.Sprintf("[Image: %s, %s]", alt, src))))
767 }
768
769 case clib.HElemTable:
770 headerRows := 0
771 if elem.Attr1 != "" {
772 fmt.Sscanf(elem.Attr1, "%d", &headerRows)
773 }
774 text.WriteString("\n")
775 text.WriteString(renderTable(elem.Text, headerRows))
776 text.WriteString("\n")
777
778 case clib.HElemBlockquote:
779 var from, date string
780 prevText := elem.Attr2
781 cite := elem.Attr1
782
783 if matches := onWroteRegex.FindStringSubmatch(prevText); matches != nil {
784 date = parseDateForDisplay(matches[1])
785 from = matches[2]
786 } else if matches := onWroteRegex.FindStringSubmatch(cite); matches != nil {
787 date = parseDateForDisplay(matches[1])
788 from = matches[2]
789 }
790
791 text.WriteString(renderQuoteBox(from, date, strings.Split(elem.Text, "\n")))
792 }
793 }
794
795 result := text.String()
796
797 // Collapse excessive newlines, but not the image row placeholders
798 re := regexp.MustCompile(`\n{3,}`)
799 result = re.ReplaceAllString(result, "\n\n")
800
801 // Now expand the image row placeholders to actual newlines
802 result = expandImageRowPlaceholders(result)
803
804 // Build image placements by finding the line numbers of image markers.
805 var placements []ImagePlacement
806 if len(pendingImages) > 0 {
807 lines := strings.Split(result, "\n")
808 imgMarkerRegex := regexp.MustCompile(`\[\[MATCHA_IMG:(\d+)\]\]`)
809 for lineNum, line := range lines {
810 if matches := imgMarkerRegex.FindStringSubmatch(line); matches != nil {
811 var idx int
812 fmt.Sscanf(matches[1], "%d", &idx)
813 for _, pi := range pendingImages {
814 if pi.index == idx {
815 placements = append(placements, ImagePlacement{
816 Line: lineNum,
817 Base64: pi.payload,
818 Rows: pi.rows,
819 })
820 break
821 }
822 }
823 }
824 }
825
826 // Remove the image markers from the text (leave the spacing)
827 result = imgMarkerRegex.ReplaceAllString(result, "")
828 }
829
830 // Style quoted reply sections (for plain text > quotes)
831 result = styleQuotedReplies(result)
832
833 return bodyStyle.Render(result), placements, nil
834}
835
836func tableHeaderStyle() lipgloss.Style {
837 return lipgloss.NewStyle().Bold(true).Foreground(theme.ActiveTheme.Accent)
838}
839
840func tableBorderStyle() lipgloss.Style {
841 return lipgloss.NewStyle().Foreground(theme.ActiveTheme.Secondary)
842}
843
844// renderTable renders table data as a Unicode box-drawing table.
845// data is tab-separated cells, newline-separated rows.
846// headerRows is the number of header rows.
847func renderTable(data string, headerRows int) string {
848 rows := strings.Split(data, "\n")
849 if len(rows) == 0 {
850 return ""
851 }
852
853 // Parse into 2D grid and trim cell whitespace
854 var grid [][]string
855 maxCols := 0
856 for _, row := range rows {
857 cells := strings.Split(row, "\t")
858 trimmed := make([]string, len(cells))
859 for i, c := range cells {
860 trimmed[i] = strings.TrimSpace(c)
861 }
862 grid = append(grid, trimmed)
863 if len(trimmed) > maxCols {
864 maxCols = len(trimmed)
865 }
866 }
867
868 // Normalize: ensure all rows have the same number of columns
869 for i := range grid {
870 for len(grid[i]) < maxCols {
871 grid[i] = append(grid[i], "")
872 }
873 }
874
875 // Calculate column widths
876 colWidths := make([]int, maxCols)
877 for _, row := range grid {
878 for j, cell := range row {
879 if len(cell) > colWidths[j] {
880 colWidths[j] = len(cell)
881 }
882 }
883 }
884
885 // Minimum width per column
886 for i := range colWidths {
887 if colWidths[i] < 3 {
888 colWidths[i] = 3
889 }
890 }
891
892 bs := tableBorderStyle()
893 hs := tableHeaderStyle()
894
895 // Build horizontal borders
896 buildBorder := func(left, mid, right, fill string) string {
897 var b strings.Builder
898 b.WriteString(bs.Render(left))
899 for j, w := range colWidths {
900 b.WriteString(bs.Render(strings.Repeat(fill, w+2)))
901 if j < len(colWidths)-1 {
902 b.WriteString(bs.Render(mid))
903 }
904 }
905 b.WriteString(bs.Render(right))
906 return b.String()
907 }
908
909 topBorder := buildBorder("┌", "┬", "┐", "─")
910 midBorder := buildBorder("├", "┼", "┤", "─")
911 botBorder := buildBorder("└", "┴", "┘", "─")
912
913 var out strings.Builder
914 out.WriteString(topBorder)
915 out.WriteString("\n")
916
917 for i, row := range grid {
918 out.WriteString(bs.Render("│"))
919 for j, cell := range row {
920 padded := cell + strings.Repeat(" ", colWidths[j]-len(cell))
921 if i < headerRows {
922 out.WriteString(" " + hs.Render(padded) + " ")
923 } else {
924 out.WriteString(" " + padded + " ")
925 }
926 out.WriteString(bs.Render("│"))
927 }
928 out.WriteString("\n")
929
930 if i < headerRows && (i+1 == headerRows || i+1 == len(grid)) {
931 out.WriteString(midBorder)
932 out.WriteString("\n")
933 }
934 }
935
936 out.WriteString(botBorder)
937 return out.String()
938}
939
940func quoteBoxStyle() lipgloss.Style {
941 return lipgloss.NewStyle().
942 Border(lipgloss.RoundedBorder()).
943 BorderForeground(theme.ActiveTheme.Secondary).
944 Padding(0, 1).
945 Foreground(theme.ActiveTheme.Secondary)
946}
947
948func quoteHeaderStyle() lipgloss.Style {
949 return lipgloss.NewStyle().
950 Foreground(theme.ActiveTheme.Secondary)
951}
952
953// styleQuotedReplies detects quoted reply sections and styles them in a box
954func styleQuotedReplies(text string) string {
955 lines := strings.Split(text, "\n")
956 var result []string
957 var quoteBlock []string
958 var quoteFrom, quoteDate string
959 inQuote := false
960
961 // Regex to match "On DATE, EMAIL wrote:" pattern
962 // Matches various date formats
963 onWroteRegex := regexp.MustCompile(`^On\s+(.+?),\s+(.+?)\s+wrote:$`)
964
965 for i := 0; i < len(lines); i++ {
966 line := lines[i]
967 trimmedLine := strings.TrimSpace(line)
968
969 // Check for "On DATE, EMAIL wrote:" header
970 if matches := onWroteRegex.FindStringSubmatch(trimmedLine); matches != nil {
971 // If we were already in a quote block, render it first
972 if inQuote && len(quoteBlock) > 0 {
973 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
974 quoteBlock = nil
975 }
976
977 // Parse the date and email from the match
978 dateStr := matches[1]
979 quoteFrom = matches[2]
980 quoteDate = parseDateForDisplay(dateStr)
981 inQuote = true
982 continue
983 }
984
985 // Check if line starts with ">" (quoted text)
986 if strings.HasPrefix(trimmedLine, ">") {
987 if !inQuote {
988 // Start a new quote block without header info
989 inQuote = true
990 quoteFrom = ""
991 quoteDate = ""
992 }
993 // Remove the leading "> " and add to quote block
994 quotedContent := strings.TrimPrefix(trimmedLine, ">")
995 quotedContent = strings.TrimPrefix(quotedContent, " ")
996 quoteBlock = append(quoteBlock, quotedContent)
997 } else if inQuote {
998 // End of quote block - check if it's just whitespace
999 if trimmedLine == "" && i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), ">") {
1000 // Empty line within quote block, keep it
1001 quoteBlock = append(quoteBlock, "")
1002 } else if trimmedLine == "" && len(quoteBlock) == 0 {
1003 // Empty line before any quoted content, skip
1004 continue
1005 } else {
1006 // End of quote block
1007 if len(quoteBlock) > 0 {
1008 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
1009 quoteBlock = nil
1010 }
1011 inQuote = false
1012 quoteFrom = ""
1013 quoteDate = ""
1014 result = append(result, line)
1015 }
1016 } else {
1017 result = append(result, line)
1018 }
1019 }
1020
1021 // Handle any remaining quote block
1022 if inQuote && len(quoteBlock) > 0 {
1023 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
1024 }
1025
1026 return strings.Join(result, "\n")
1027}
1028
1029// parseDateForDisplay converts various date formats to DD:MM:YY HH:MM
1030func parseDateForDisplay(dateStr string) string {
1031 // Common date formats to try
1032 formats := []string{
1033 "Jan 2, 2006 at 3:04 PM",
1034 "02:01:06 15:04",
1035 "2006-01-02 15:04:05",
1036 "Mon, 02 Jan 2006 15:04:05 -0700",
1037 "Mon, 2 Jan 2006 15:04:05 -0700",
1038 "2 Jan 2006 15:04:05",
1039 "January 2, 2006 at 3:04 PM",
1040 "Jan 2, 2006 3:04 PM",
1041 time.RFC1123Z,
1042 time.RFC1123,
1043 time.RFC822Z,
1044 time.RFC822,
1045 }
1046
1047 for _, format := range formats {
1048 if t, err := time.Parse(format, dateStr); err == nil {
1049 return t.Format("02:01:06 15:04")
1050 }
1051 }
1052
1053 // Return original if parsing fails
1054 return dateStr
1055}
1056
1057// renderQuoteBox renders a quoted section in a styled box
1058func renderQuoteBox(from, date string, lines []string) string {
1059 // Build header with email on left and date on right
1060 var header string
1061 if from != "" || date != "" {
1062 if from != "" && date != "" {
1063 header = quoteHeaderStyle().Render(from + " " + date)
1064 } else if from != "" {
1065 header = quoteHeaderStyle().Render(from)
1066 } else {
1067 header = quoteHeaderStyle().Render(date)
1068 }
1069 }
1070
1071 // Join the quoted content
1072 content := strings.Join(lines, "\n")
1073
1074 // Build the box content
1075 var boxContent string
1076 if header != "" {
1077 boxContent = header + "\n\n" + content
1078 } else {
1079 boxContent = content
1080 }
1081
1082 return quoteBoxStyle().Render(boxContent)
1083}