···
1
+
// Copyright 2024 The Forgejo Authors. All rights reserved.
2
+
// Copyright 2025 The Tangled Authors -- repurposed for Tangled use.
3
+
// SPDX-License-Identifier: MIT
20
+
"github.com/goki/freetype"
21
+
"github.com/goki/freetype/truetype"
22
+
"github.com/srwiley/oksvg"
23
+
"github.com/srwiley/rasterx"
24
+
"golang.org/x/image/draw"
25
+
"golang.org/x/image/font"
26
+
"tangled.org/core/appview/pages"
28
+
_ "golang.org/x/image/webp" // for processing webp images
39
+
var fontCache = sync.OnceValues(func() (*truetype.Font, error) {
40
+
interVar, err := pages.Files.ReadFile("static/fonts/InterVariable.ttf")
44
+
return truetype.Parse(interVar)
47
+
// DefaultSize returns the default size for a card
48
+
func DefaultSize() (int, int) {
52
+
// NewCard creates a new card with the given dimensions in pixels
53
+
func NewCard(width, height int) (*Card, error) {
54
+
img := image.NewRGBA(image.Rect(0, 0, width, height))
55
+
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
57
+
font, err := fontCache()
71
+
// Split splits the card horizontally or vertically by a given percentage; the first card returned has the percentage
72
+
// size, and the second card has the remainder. Both cards draw to a subsection of the same image buffer.
73
+
func (c *Card) Split(vertical bool, percentage int) (*Card, *Card) {
74
+
bounds := c.Img.Bounds()
75
+
bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
77
+
mid := (bounds.Dx() * percentage / 100) + bounds.Min.X
78
+
subleft := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, mid, bounds.Max.Y)).(*image.RGBA)
79
+
subright := c.Img.SubImage(image.Rect(mid, bounds.Min.Y, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
80
+
return &Card{Img: subleft, Font: c.Font, Width: subleft.Bounds().Dx(), Height: subleft.Bounds().Dy()},
81
+
&Card{Img: subright, Font: c.Font, Width: subright.Bounds().Dx(), Height: subright.Bounds().Dy()}
83
+
mid := (bounds.Dy() * percentage / 100) + bounds.Min.Y
84
+
subtop := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, bounds.Max.X, mid)).(*image.RGBA)
85
+
subbottom := c.Img.SubImage(image.Rect(bounds.Min.X, mid, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
86
+
return &Card{Img: subtop, Font: c.Font, Width: subtop.Bounds().Dx(), Height: subtop.Bounds().Dy()},
87
+
&Card{Img: subbottom, Font: c.Font, Width: subbottom.Bounds().Dx(), Height: subbottom.Bounds().Dy()}
90
+
// SetMargin sets the margins for the card
91
+
func (c *Card) SetMargin(margin int) {
112
+
// DrawText draws text within the card, respecting margins and alignment
113
+
func (c *Card) DrawText(text string, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) ([]string, error) {
114
+
ft := freetype.NewContext()
117
+
ft.SetFontSize(sizePt)
118
+
ft.SetClip(c.Img.Bounds())
120
+
ft.SetSrc(image.NewUniform(textColor))
122
+
face := truetype.NewFace(c.Font, &truetype.Options{Size: sizePt, DPI: 72})
123
+
fontHeight := ft.PointToFixed(sizePt).Ceil()
125
+
bounds := c.Img.Bounds()
126
+
bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
127
+
boxWidth, boxHeight := bounds.Size().X, bounds.Size().Y
128
+
// draw.Draw(c.Img, bounds, image.NewUniform(color.Gray{128}), image.Point{}, draw.Src) // Debug draw box
130
+
// Try to apply wrapping to this text; we'll find the most text that will fit into one line, record that line, move
131
+
// on. We precalculate each line before drawing so that we can support valign="middle" correctly which requires
132
+
// knowing the total height, which is related to how many lines we'll have.
133
+
lines := make([]string, 0)
134
+
textWords := strings.Split(text, " ")
139
+
if len(textWords) == 0 {
140
+
// Ran out of words.
141
+
if currentLine != "" {
142
+
heightTotal += fontHeight
143
+
lines = append(lines, currentLine)
148
+
nextWord := textWords[0]
149
+
proposedLine := currentLine
150
+
if proposedLine != "" {
151
+
proposedLine += " "
153
+
proposedLine += nextWord
155
+
proposedLineWidth := font.MeasureString(face, proposedLine)
156
+
if proposedLineWidth.Ceil() > boxWidth {
157
+
// no, proposed line is too big; we'll use the last "currentLine"
158
+
heightTotal += fontHeight
159
+
if currentLine != "" {
160
+
lines = append(lines, currentLine)
162
+
// leave nextWord in textWords and keep going
164
+
// just nextWord by itself doesn't fit on a line; well, we can't skip it, but we'll consume it
165
+
// regardless as a line by itself. It will be clipped by the drawing routine.
166
+
lines = append(lines, nextWord)
167
+
textWords = textWords[1:]
170
+
// yes, it will fit
171
+
currentLine = proposedLine
172
+
textWords = textWords[1:]
181
+
textY = boxHeight - heightTotal + fontHeight
183
+
textY = ((boxHeight - heightTotal) / 2) + fontHeight
186
+
for _, line := range lines {
187
+
lineWidth := font.MeasureString(face, line)
194
+
textX = boxWidth - lineWidth.Ceil()
196
+
textX = (boxWidth - lineWidth.Ceil()) / 2
199
+
pt := freetype.Pt(bounds.Min.X+textX, bounds.Min.Y+textY)
200
+
_, err := ft.DrawString(line, pt)
205
+
textY += fontHeight
211
+
// DrawTextAt draws text at a specific position with the given alignment
212
+
func (c *Card) DrawTextAt(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) error {
213
+
_, err := c.DrawTextAtWithWidth(text, x, y, textColor, sizePt, valign, halign)
217
+
// DrawTextAtWithWidth draws text at a specific position and returns the text width
218
+
func (c *Card) DrawTextAtWithWidth(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) (int, error) {
219
+
ft := freetype.NewContext()
222
+
ft.SetFontSize(sizePt)
223
+
ft.SetClip(c.Img.Bounds())
225
+
ft.SetSrc(image.NewUniform(textColor))
227
+
face := truetype.NewFace(c.Font, &truetype.Options{Size: sizePt, DPI: 72})
228
+
fontHeight := ft.PointToFixed(sizePt).Ceil()
229
+
lineWidth := font.MeasureString(face, text)
230
+
textWidth := lineWidth.Ceil()
232
+
// Adjust position based on alignment
238
+
// x is already at the left position
240
+
adjustedX = x - textWidth
242
+
adjustedX = x - textWidth/2
247
+
adjustedY = y + fontHeight
251
+
adjustedY = y + fontHeight/2
254
+
pt := freetype.Pt(adjustedX, adjustedY)
255
+
_, err := ft.DrawString(text, pt)
256
+
return textWidth, err
259
+
// DrawBoldText draws bold text by rendering multiple times with slight offsets
260
+
func (c *Card) DrawBoldText(text string, x, y int, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) (int, error) {
261
+
// Draw the text multiple times with slight offsets to create bold effect
262
+
offsets := []struct{ dx, dy int }{
263
+
{0, 0}, // original
266
+
{1, 1}, // diagonal
270
+
for _, offset := range offsets {
271
+
w, err := c.DrawTextAtWithWidth(text, x+offset.dx, y+offset.dy, textColor, sizePt, valign, halign)
282
+
// DrawSVGIcon draws an SVG icon from the embedded files at the specified position
283
+
func (c *Card) DrawSVGIcon(svgPath string, x, y, size int, iconColor color.Color) error {
284
+
svgData, err := pages.Files.ReadFile(svgPath)
286
+
return fmt.Errorf("failed to read SVG file %s: %w", svgPath, err)
289
+
// Convert color to hex string for SVG
290
+
rgba, isRGBA := iconColor.(color.RGBA)
292
+
r, g, b, a := iconColor.RGBA()
293
+
rgba = color.RGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)}
295
+
colorHex := fmt.Sprintf("#%02x%02x%02x", rgba.R, rgba.G, rgba.B)
297
+
// Replace currentColor with our desired color in the SVG
298
+
svgString := string(svgData)
299
+
svgString = strings.ReplaceAll(svgString, "currentColor", colorHex)
301
+
// Make the stroke thicker
302
+
svgString = strings.ReplaceAll(svgString, `stroke-width="2"`, `stroke-width="3"`)
305
+
icon, err := oksvg.ReadIconStream(strings.NewReader(svgString))
307
+
return fmt.Errorf("failed to parse SVG %s: %w", svgPath, err)
310
+
// Set the icon size
311
+
w, h := float64(size), float64(size)
312
+
icon.SetTarget(0, 0, w, h)
314
+
// Create a temporary RGBA image for the icon
315
+
iconImg := image.NewRGBA(image.Rect(0, 0, size, size))
317
+
// Create scanner and rasterizer
318
+
scanner := rasterx.NewScannerGV(size, size, iconImg, iconImg.Bounds())
319
+
raster := rasterx.NewDasher(size, size, scanner)
322
+
icon.Draw(raster, 1.0)
324
+
// Draw the icon onto the card at the specified position
325
+
bounds := c.Img.Bounds()
326
+
destRect := image.Rect(x, y, x+size, y+size)
328
+
// Make sure we don't draw outside the card bounds
329
+
if destRect.Max.X > bounds.Max.X {
330
+
destRect.Max.X = bounds.Max.X
332
+
if destRect.Max.Y > bounds.Max.Y {
333
+
destRect.Max.Y = bounds.Max.Y
336
+
draw.Draw(c.Img, destRect, iconImg, image.Point{}, draw.Over)
341
+
// DrawImage fills the card with an image, scaled to maintain the original aspect ratio and centered with respect to the non-filled dimension
342
+
func (c *Card) DrawImage(img image.Image) {
343
+
bounds := c.Img.Bounds()
344
+
targetRect := image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
345
+
srcBounds := img.Bounds()
346
+
srcAspect := float64(srcBounds.Dx()) / float64(srcBounds.Dy())
347
+
targetAspect := float64(targetRect.Dx()) / float64(targetRect.Dy())
350
+
if srcAspect > targetAspect {
351
+
// Image is wider than target, scale by width
352
+
scale = float64(targetRect.Dx()) / float64(srcBounds.Dx())
354
+
// Image is taller or equal, scale by height
355
+
scale = float64(targetRect.Dy()) / float64(srcBounds.Dy())
358
+
newWidth := int(math.Round(float64(srcBounds.Dx()) * scale))
359
+
newHeight := int(math.Round(float64(srcBounds.Dy()) * scale))
361
+
// Center the image within the target rectangle
362
+
offsetX := (targetRect.Dx() - newWidth) / 2
363
+
offsetY := (targetRect.Dy() - newHeight) / 2
365
+
scaledRect := image.Rect(targetRect.Min.X+offsetX, targetRect.Min.Y+offsetY, targetRect.Min.X+offsetX+newWidth, targetRect.Min.Y+offsetY+newHeight)
366
+
draw.CatmullRom.Scale(c.Img, scaledRect, img, srcBounds, draw.Over, nil)
369
+
func fallbackImage() image.Image {
370
+
// can't usage image.Uniform(color.White) because it's infinitely sized causing a panic in the scaler in DrawImage
371
+
img := image.NewRGBA(image.Rect(0, 0, 1, 1))
372
+
img.Set(0, 0, color.White)
376
+
// As defensively as possible, attempt to load an image from a presumed external and untrusted URL
377
+
func (c *Card) fetchExternalImage(url string) (image.Image, bool) {
378
+
// Use a short timeout; in the event of any failure we'll be logging and returning a placeholder, but we don't want
379
+
// this rendering process to be slowed down
380
+
client := &http.Client{
381
+
Timeout: 1 * time.Second, // 1 second timeout
384
+
resp, err := client.Get(url)
386
+
log.Printf("error when fetching external image from %s: %v", url, err)
389
+
defer resp.Body.Close()
391
+
if resp.StatusCode != http.StatusOK {
392
+
log.Printf("non-OK error code when fetching external image from %s: %s", url, resp.Status)
396
+
contentType := resp.Header.Get("Content-Type")
397
+
// Support content types are in-sync with the allowed custom avatar file types
398
+
if contentType != "image/png" && contentType != "image/jpeg" && contentType != "image/gif" && contentType != "image/webp" {
399
+
log.Printf("fetching external image returned unsupported Content-Type which was ignored: %s", contentType)
404
+
bodyBytes, err := io.ReadAll(body)
406
+
log.Printf("error when fetching external image from %s: %v", url, err)
410
+
bodyBuffer := bytes.NewReader(bodyBytes)
411
+
_, imgType, err := image.DecodeConfig(bodyBuffer)
413
+
log.Printf("error when decoding external image from %s: %v", url, err)
417
+
// Verify that we have a match between actual data understood in the image body and the reported Content-Type
418
+
if (contentType == "image/png" && imgType != "png") ||
419
+
(contentType == "image/jpeg" && imgType != "jpeg") ||
420
+
(contentType == "image/gif" && imgType != "gif") ||
421
+
(contentType == "image/webp" && imgType != "webp") {
422
+
log.Printf("while fetching external image, mismatched image body (%s) and Content-Type (%s)", imgType, contentType)
426
+
_, err = bodyBuffer.Seek(0, io.SeekStart) // reset for actual decode
428
+
log.Printf("error w/ bodyBuffer.Seek")
431
+
img, _, err := image.Decode(bodyBuffer)
433
+
log.Printf("error when decoding external image from %s: %v", url, err)
440
+
func (c *Card) DrawExternalImage(url string) {
441
+
image, ok := c.fetchExternalImage(url)
443
+
image = fallbackImage()
448
+
// DrawCircularExternalImage draws an external image as a circle at the specified position
449
+
func (c *Card) DrawCircularExternalImage(url string, x, y, size int) error {
450
+
img, ok := c.fetchExternalImage(url)
452
+
img = fallbackImage()
455
+
// Create a circular mask
456
+
circle := image.NewRGBA(image.Rect(0, 0, size, size))
458
+
radius := float64(size / 2)
460
+
// Scale the source image to fit the circle
461
+
srcBounds := img.Bounds()
462
+
scaledImg := image.NewRGBA(image.Rect(0, 0, size, size))
463
+
draw.CatmullRom.Scale(scaledImg, scaledImg.Bounds(), img, srcBounds, draw.Src, nil)
465
+
// Draw the image with circular clipping
466
+
for cy := 0; cy < size; cy++ {
467
+
for cx := 0; cx < size; cx++ {
468
+
// Calculate distance from center
469
+
dx := float64(cx - center)
470
+
dy := float64(cy - center)
471
+
distance := math.Sqrt(dx*dx + dy*dy)
473
+
// Only draw pixels within the circle
474
+
if distance <= radius {
475
+
circle.Set(cx, cy, scaledImg.At(cx, cy))
480
+
// Draw the circle onto the card
481
+
bounds := c.Img.Bounds()
482
+
destRect := image.Rect(x, y, x+size, y+size)
484
+
// Make sure we don't draw outside the card bounds
485
+
if destRect.Max.X > bounds.Max.X {
486
+
destRect.Max.X = bounds.Max.X
488
+
if destRect.Max.Y > bounds.Max.Y {
489
+
destRect.Max.Y = bounds.Max.Y
492
+
draw.Draw(c.Img, destRect, circle, image.Point{}, draw.Over)
497
+
// DrawRect draws a rect with the given color
498
+
func (c *Card) DrawRect(startX, startY, endX, endY int, color color.Color) {
499
+
draw.Draw(c.Img, image.Rect(startX, startY, endX, endY), &image.Uniform{color}, image.Point{}, draw.Src)