forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1// Copyright 2024 The Forgejo Authors. All rights reserved.
2// Copyright 2025 The Tangled Authors -- repurposed for Tangled use.
3// SPDX-License-Identifier: MIT
4
5package ogcard
6
7import (
8 "bytes"
9 "fmt"
10 "html/template"
11 "image"
12 "image/color"
13 "io"
14 "log"
15 "math"
16 "net/http"
17 "strings"
18 "sync"
19 "time"
20
21 "github.com/goki/freetype"
22 "github.com/goki/freetype/truetype"
23 "github.com/srwiley/oksvg"
24 "github.com/srwiley/rasterx"
25 "golang.org/x/image/draw"
26 "golang.org/x/image/font"
27 "tangled.org/core/appview/pages"
28
29 _ "golang.org/x/image/webp" // for processing webp images
30)
31
32type Card struct {
33 Img *image.RGBA
34 Font *truetype.Font
35 Margin int
36 Width int
37 Height int
38}
39
40var fontCache = sync.OnceValues(func() (*truetype.Font, error) {
41 interVar, err := pages.Files.ReadFile("static/fonts/InterVariable.ttf")
42 if err != nil {
43 return nil, err
44 }
45 return truetype.Parse(interVar)
46})
47
48// DefaultSize returns the default size for a card
49func DefaultSize() (int, int) {
50 return 1200, 630
51}
52
53// NewCard creates a new card with the given dimensions in pixels
54func NewCard(width, height int) (*Card, error) {
55 img := image.NewRGBA(image.Rect(0, 0, width, height))
56 draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
57
58 font, err := fontCache()
59 if err != nil {
60 return nil, err
61 }
62
63 return &Card{
64 Img: img,
65 Font: font,
66 Margin: 0,
67 Width: width,
68 Height: height,
69 }, nil
70}
71
72// Split splits the card horizontally or vertically by a given percentage; the first card returned has the percentage
73// size, and the second card has the remainder. Both cards draw to a subsection of the same image buffer.
74func (c *Card) Split(vertical bool, percentage int) (*Card, *Card) {
75 bounds := c.Img.Bounds()
76 bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
77 if vertical {
78 mid := (bounds.Dx() * percentage / 100) + bounds.Min.X
79 subleft := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, mid, bounds.Max.Y)).(*image.RGBA)
80 subright := c.Img.SubImage(image.Rect(mid, bounds.Min.Y, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
81 return &Card{Img: subleft, Font: c.Font, Width: subleft.Bounds().Dx(), Height: subleft.Bounds().Dy()},
82 &Card{Img: subright, Font: c.Font, Width: subright.Bounds().Dx(), Height: subright.Bounds().Dy()}
83 }
84 mid := (bounds.Dy() * percentage / 100) + bounds.Min.Y
85 subtop := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, bounds.Max.X, mid)).(*image.RGBA)
86 subbottom := c.Img.SubImage(image.Rect(bounds.Min.X, mid, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
87 return &Card{Img: subtop, Font: c.Font, Width: subtop.Bounds().Dx(), Height: subtop.Bounds().Dy()},
88 &Card{Img: subbottom, Font: c.Font, Width: subbottom.Bounds().Dx(), Height: subbottom.Bounds().Dy()}
89}
90
91// SetMargin sets the margins for the card
92func (c *Card) SetMargin(margin int) {
93 c.Margin = margin
94}
95
96type (
97 VAlign int64
98 HAlign int64
99)
100
101const (
102 Top VAlign = iota
103 Middle
104 Bottom
105)
106
107const (
108 Left HAlign = iota
109 Center
110 Right
111)
112
113// DrawText draws text within the card, respecting margins and alignment
114func (c *Card) DrawText(text string, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) ([]string, error) {
115 ft := freetype.NewContext()
116 ft.SetDPI(72)
117 ft.SetFont(c.Font)
118 ft.SetFontSize(sizePt)
119 ft.SetClip(c.Img.Bounds())
120 ft.SetDst(c.Img)
121 ft.SetSrc(image.NewUniform(textColor))
122
123 face := truetype.NewFace(c.Font, &truetype.Options{Size: sizePt, DPI: 72})
124 fontHeight := ft.PointToFixed(sizePt).Ceil()
125
126 bounds := c.Img.Bounds()
127 bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
128 boxWidth, boxHeight := bounds.Size().X, bounds.Size().Y
129 // draw.Draw(c.Img, bounds, image.NewUniform(color.Gray{128}), image.Point{}, draw.Src) // Debug draw box
130
131 // Try to apply wrapping to this text; we'll find the most text that will fit into one line, record that line, move
132 // on. We precalculate each line before drawing so that we can support valign="middle" correctly which requires
133 // knowing the total height, which is related to how many lines we'll have.
134 lines := make([]string, 0)
135 textWords := strings.Split(text, " ")
136 currentLine := ""
137 heightTotal := 0
138
139 for {
140 if len(textWords) == 0 {
141 // Ran out of words.
142 if currentLine != "" {
143 heightTotal += fontHeight
144 lines = append(lines, currentLine)
145 }
146 break
147 }
148
149 nextWord := textWords[0]
150 proposedLine := currentLine
151 if proposedLine != "" {
152 proposedLine += " "
153 }
154 proposedLine += nextWord
155
156 proposedLineWidth := font.MeasureString(face, proposedLine)
157 if proposedLineWidth.Ceil() > boxWidth {
158 // no, proposed line is too big; we'll use the last "currentLine"
159 heightTotal += fontHeight
160 if currentLine != "" {
161 lines = append(lines, currentLine)
162 currentLine = ""
163 // leave nextWord in textWords and keep going
164 } else {
165 // just nextWord by itself doesn't fit on a line; well, we can't skip it, but we'll consume it
166 // regardless as a line by itself. It will be clipped by the drawing routine.
167 lines = append(lines, nextWord)
168 textWords = textWords[1:]
169 }
170 } else {
171 // yes, it will fit
172 currentLine = proposedLine
173 textWords = textWords[1:]
174 }
175 }
176
177 textY := 0
178 switch valign {
179 case Top:
180 textY = fontHeight
181 case Bottom:
182 textY = boxHeight - heightTotal + fontHeight
183 case Middle:
184 textY = ((boxHeight - heightTotal) / 2) + fontHeight
185 }
186
187 for _, line := range lines {
188 lineWidth := font.MeasureString(face, line)
189
190 textX := 0
191 switch halign {
192 case Left:
193 textX = 0
194 case Right:
195 textX = boxWidth - lineWidth.Ceil()
196 case Center:
197 textX = (boxWidth - lineWidth.Ceil()) / 2
198 }
199
200 pt := freetype.Pt(bounds.Min.X+textX, bounds.Min.Y+textY)
201 _, err := ft.DrawString(line, pt)
202 if err != nil {
203 return nil, err
204 }
205
206 textY += fontHeight
207 }
208
209 return lines, nil
210}
211
212// DrawTextAt draws text at a specific position with the given alignment
213func (c *Card) DrawTextAt(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) error {
214 _, err := c.DrawTextAtWithWidth(text, x, y, textColor, sizePt, valign, halign)
215 return err
216}
217
218// DrawTextAtWithWidth draws text at a specific position and returns the text width
219func (c *Card) DrawTextAtWithWidth(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) (int, error) {
220 ft := freetype.NewContext()
221 ft.SetDPI(72)
222 ft.SetFont(c.Font)
223 ft.SetFontSize(sizePt)
224 ft.SetClip(c.Img.Bounds())
225 ft.SetDst(c.Img)
226 ft.SetSrc(image.NewUniform(textColor))
227
228 face := truetype.NewFace(c.Font, &truetype.Options{Size: sizePt, DPI: 72})
229 fontHeight := ft.PointToFixed(sizePt).Ceil()
230 lineWidth := font.MeasureString(face, text)
231 textWidth := lineWidth.Ceil()
232
233 // Adjust position based on alignment
234 adjustedX := x
235 adjustedY := y
236
237 switch halign {
238 case Left:
239 // x is already at the left position
240 case Right:
241 adjustedX = x - textWidth
242 case Center:
243 adjustedX = x - textWidth/2
244 }
245
246 switch valign {
247 case Top:
248 adjustedY = y + fontHeight
249 case Bottom:
250 adjustedY = y
251 case Middle:
252 adjustedY = y + fontHeight/2
253 }
254
255 pt := freetype.Pt(adjustedX, adjustedY)
256 _, err := ft.DrawString(text, pt)
257 return textWidth, err
258}
259
260// DrawBoldText draws bold text by rendering multiple times with slight offsets
261func (c *Card) DrawBoldText(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) (int, error) {
262 // Draw the text multiple times with slight offsets to create bold effect
263 offsets := []struct{ dx, dy int }{
264 {0, 0}, // original
265 {1, 0}, // right
266 {0, 1}, // down
267 {1, 1}, // diagonal
268 }
269
270 var width int
271 for _, offset := range offsets {
272 w, err := c.DrawTextAtWithWidth(text, x+offset.dx, y+offset.dy, textColor, sizePt, valign, halign)
273 if err != nil {
274 return 0, err
275 }
276 if width == 0 {
277 width = w
278 }
279 }
280 return width, nil
281}
282
283func BuildSVGIconFromData(svgData []byte, iconColor color.Color) (*oksvg.SvgIcon, error) {
284 // Convert color to hex string for SVG
285 rgba, isRGBA := iconColor.(color.RGBA)
286 if !isRGBA {
287 r, g, b, a := iconColor.RGBA()
288 rgba = color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)}
289 }
290 colorHex := fmt.Sprintf("#%02x%02x%02x", rgba.R, rgba.G, rgba.B)
291
292 // Replace currentColor with our desired color in the SVG
293 svgString := string(svgData)
294 svgString = strings.ReplaceAll(svgString, "currentColor", colorHex)
295
296 // Make the stroke thicker
297 svgString = strings.ReplaceAll(svgString, `stroke-width="2"`, `stroke-width="3"`)
298
299 // Parse SVG
300 icon, err := oksvg.ReadIconStream(strings.NewReader(svgString))
301 if err != nil {
302 return nil, fmt.Errorf("failed to parse SVG: %w", err)
303 }
304
305 return icon, nil
306}
307
308func BuildSVGIconFromPath(svgPath string, iconColor color.Color) (*oksvg.SvgIcon, error) {
309 svgData, err := pages.Files.ReadFile(svgPath)
310 if err != nil {
311 return nil, fmt.Errorf("failed to read SVG file %s: %w", svgPath, err)
312 }
313
314 icon, err := BuildSVGIconFromData(svgData, iconColor)
315 if err != nil {
316 return nil, fmt.Errorf("failed to build SVG icon %s: %w", svgPath, err)
317 }
318
319 return icon, nil
320}
321
322func BuildLucideIcon(name string, iconColor color.Color) (*oksvg.SvgIcon, error) {
323 return BuildSVGIconFromPath(fmt.Sprintf("static/icons/%s.svg", name), iconColor)
324}
325
326func (c *Card) DrawLucideIcon(name string, x, y, size int, iconColor color.Color) error {
327 icon, err := BuildSVGIconFromPath(fmt.Sprintf("static/icons/%s.svg", name), iconColor)
328 if err != nil {
329 return err
330 }
331
332 c.DrawSVGIcon(icon, x, y, size)
333
334 return nil
335}
336
337func (c *Card) DrawDollySilhouette(x, y, size int, iconColor color.Color) error {
338 tpl, err := template.New("dolly").
339 ParseFS(pages.Files, "templates/fragments/dolly/silhouette.html")
340 if err != nil {
341 return fmt.Errorf("failed to read dolly silhouette template: %w", err)
342 }
343
344 var svgData bytes.Buffer
345 if err = tpl.ExecuteTemplate(&svgData, "fragments/dolly/silhouette", nil); err != nil {
346 return fmt.Errorf("failed to execute dolly silhouette template: %w", err)
347 }
348
349 icon, err := BuildSVGIconFromData(svgData.Bytes(), iconColor)
350 if err != nil {
351 return err
352 }
353
354 c.DrawSVGIcon(icon, x, y, size)
355
356 return nil
357}
358
359// DrawSVGIcon draws an SVG icon from the embedded files at the specified position
360func (c *Card) DrawSVGIcon(icon *oksvg.SvgIcon, x, y, size int) {
361 // Set the icon size
362 w, h := float64(size), float64(size)
363 icon.SetTarget(0, 0, w, h)
364
365 // Create a temporary RGBA image for the icon
366 iconImg := image.NewRGBA(image.Rect(0, 0, size, size))
367
368 // Create scanner and rasterizer
369 scanner := rasterx.NewScannerGV(size, size, iconImg, iconImg.Bounds())
370 raster := rasterx.NewDasher(size, size, scanner)
371
372 // Draw the icon
373 icon.Draw(raster, 1.0)
374
375 // Draw the icon onto the card at the specified position
376 bounds := c.Img.Bounds()
377 destRect := image.Rect(x, y, x+size, y+size)
378
379 // Make sure we don't draw outside the card bounds
380 if destRect.Max.X > bounds.Max.X {
381 destRect.Max.X = bounds.Max.X
382 }
383 if destRect.Max.Y > bounds.Max.Y {
384 destRect.Max.Y = bounds.Max.Y
385 }
386
387 draw.Draw(c.Img, destRect, iconImg, image.Point{}, draw.Over)
388}
389
390// DrawImage fills the card with an image, scaled to maintain the original aspect ratio and centered with respect to the non-filled dimension
391func (c *Card) DrawImage(img image.Image) {
392 bounds := c.Img.Bounds()
393 targetRect := image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
394 srcBounds := img.Bounds()
395 srcAspect := float64(srcBounds.Dx()) / float64(srcBounds.Dy())
396 targetAspect := float64(targetRect.Dx()) / float64(targetRect.Dy())
397
398 var scale float64
399 if srcAspect > targetAspect {
400 // Image is wider than target, scale by width
401 scale = float64(targetRect.Dx()) / float64(srcBounds.Dx())
402 } else {
403 // Image is taller or equal, scale by height
404 scale = float64(targetRect.Dy()) / float64(srcBounds.Dy())
405 }
406
407 newWidth := int(math.Round(float64(srcBounds.Dx()) * scale))
408 newHeight := int(math.Round(float64(srcBounds.Dy()) * scale))
409
410 // Center the image within the target rectangle
411 offsetX := (targetRect.Dx() - newWidth) / 2
412 offsetY := (targetRect.Dy() - newHeight) / 2
413
414 scaledRect := image.Rect(targetRect.Min.X+offsetX, targetRect.Min.Y+offsetY, targetRect.Min.X+offsetX+newWidth, targetRect.Min.Y+offsetY+newHeight)
415 draw.CatmullRom.Scale(c.Img, scaledRect, img, srcBounds, draw.Over, nil)
416}
417
418func fallbackImage() image.Image {
419 // can't usage image.Uniform(color.White) because it's infinitely sized causing a panic in the scaler in DrawImage
420 img := image.NewRGBA(image.Rect(0, 0, 1, 1))
421 img.Set(0, 0, color.White)
422 return img
423}
424
425// As defensively as possible, attempt to load an image from a presumed external and untrusted URL
426func (c *Card) fetchExternalImage(url string) (image.Image, bool) {
427 // Use a short timeout; in the event of any failure we'll be logging and returning a placeholder, but we don't want
428 // this rendering process to be slowed down
429 client := &http.Client{
430 Timeout: 1 * time.Second, // 1 second timeout
431 }
432
433 resp, err := client.Get(url)
434 if err != nil {
435 log.Printf("error when fetching external image from %s: %v", url, err)
436 return nil, false
437 }
438 defer resp.Body.Close()
439
440 if resp.StatusCode != http.StatusOK {
441 log.Printf("non-OK error code when fetching external image from %s: %s", url, resp.Status)
442 return nil, false
443 }
444
445 contentType := resp.Header.Get("Content-Type")
446
447 body := resp.Body
448 bodyBytes, err := io.ReadAll(body)
449 if err != nil {
450 log.Printf("error when fetching external image from %s: %v", url, err)
451 return nil, false
452 }
453
454 // Handle SVG separately
455 if contentType == "image/svg+xml" || strings.HasSuffix(url, ".svg") {
456 return c.convertSVGToPNG(bodyBytes)
457 }
458
459 // Support content types are in-sync with the allowed custom avatar file types
460 if contentType != "image/png" && contentType != "image/jpeg" && contentType != "image/gif" && contentType != "image/webp" {
461 log.Printf("fetching external image returned unsupported Content-Type which was ignored: %s", contentType)
462 return nil, false
463 }
464
465 bodyBuffer := bytes.NewReader(bodyBytes)
466 _, imgType, err := image.DecodeConfig(bodyBuffer)
467 if err != nil {
468 log.Printf("error when decoding external image from %s: %v", url, err)
469 return nil, false
470 }
471
472 // Verify that we have a match between actual data understood in the image body and the reported Content-Type
473 if (contentType == "image/png" && imgType != "png") ||
474 (contentType == "image/jpeg" && imgType != "jpeg") ||
475 (contentType == "image/gif" && imgType != "gif") ||
476 (contentType == "image/webp" && imgType != "webp") {
477 log.Printf("while fetching external image, mismatched image body (%s) and Content-Type (%s)", imgType, contentType)
478 return nil, false
479 }
480
481 _, err = bodyBuffer.Seek(0, io.SeekStart) // reset for actual decode
482 if err != nil {
483 log.Printf("error w/ bodyBuffer.Seek")
484 return nil, false
485 }
486 img, _, err := image.Decode(bodyBuffer)
487 if err != nil {
488 log.Printf("error when decoding external image from %s: %v", url, err)
489 return nil, false
490 }
491
492 return img, true
493}
494
495// convertSVGToPNG converts SVG data to a PNG image
496func (c *Card) convertSVGToPNG(svgData []byte) (image.Image, bool) {
497 // Parse the SVG
498 icon, err := oksvg.ReadIconStream(bytes.NewReader(svgData))
499 if err != nil {
500 log.Printf("error parsing SVG: %v", err)
501 return nil, false
502 }
503
504 // Set a reasonable size for the rasterized image
505 width := 256
506 height := 256
507 icon.SetTarget(0, 0, float64(width), float64(height))
508
509 // Create an image to draw on
510 rgba := image.NewRGBA(image.Rect(0, 0, width, height))
511
512 // Fill with white background
513 draw.Draw(rgba, rgba.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
514
515 // Create a scanner and rasterize the SVG
516 scanner := rasterx.NewScannerGV(width, height, rgba, rgba.Bounds())
517 raster := rasterx.NewDasher(width, height, scanner)
518
519 icon.Draw(raster, 1.0)
520
521 return rgba, true
522}
523
524func (c *Card) DrawExternalImage(url string) {
525 image, ok := c.fetchExternalImage(url)
526 if !ok {
527 image = fallbackImage()
528 }
529 c.DrawImage(image)
530}
531
532// DrawCircularExternalImage draws an external image as a circle at the specified position
533func (c *Card) DrawCircularExternalImage(url string, x, y, size int) error {
534 img, ok := c.fetchExternalImage(url)
535 if !ok {
536 img = fallbackImage()
537 }
538
539 // Create a circular mask
540 circle := image.NewRGBA(image.Rect(0, 0, size, size))
541 center := size / 2
542 radius := float64(size / 2)
543
544 // Scale the source image to fit the circle
545 srcBounds := img.Bounds()
546 scaledImg := image.NewRGBA(image.Rect(0, 0, size, size))
547 draw.CatmullRom.Scale(scaledImg, scaledImg.Bounds(), img, srcBounds, draw.Src, nil)
548
549 // Draw the image with circular clipping
550 for cy := 0; cy < size; cy++ {
551 for cx := 0; cx < size; cx++ {
552 // Calculate distance from center
553 dx := float64(cx - center)
554 dy := float64(cy - center)
555 distance := math.Sqrt(dx*dx + dy*dy)
556
557 // Only draw pixels within the circle
558 if distance <= radius {
559 circle.Set(cx, cy, scaledImg.At(cx, cy))
560 }
561 }
562 }
563
564 // Draw the circle onto the card
565 bounds := c.Img.Bounds()
566 destRect := image.Rect(x, y, x+size, y+size)
567
568 // Make sure we don't draw outside the card bounds
569 if destRect.Max.X > bounds.Max.X {
570 destRect.Max.X = bounds.Max.X
571 }
572 if destRect.Max.Y > bounds.Max.Y {
573 destRect.Max.Y = bounds.Max.Y
574 }
575
576 draw.Draw(c.Img, destRect, circle, image.Point{}, draw.Over)
577
578 return nil
579}
580
581// DrawRect draws a rect with the given color
582func (c *Card) DrawRect(startX, startY, endX, endY int, color color.Color) {
583 draw.Draw(c.Img, image.Rect(startX, startY, endX, endY), &image.Uniform{color}, image.Point{}, draw.Src)
584}