commit 333c27f

delthas  ·  2025-12-19 11:17:09 +0000 UTC
parent 2132570
Fix panic on image preview on terminals without cell size

Thanks to Kieran Musser for reporting the issue!

Fixes: https://todo.sr.ht/~delthas/senpai/227
1 files changed,  +43, -35
+43, -35
 1@@ -1039,41 +1039,7 @@ func (ui *UI) DecodeImage(r io.Reader) (image.Image, string, error) {
 2 		return img, format, err
 3 	}
 4 
 5-	w, h := ui.vx.window.Size()
 6-	w = w * 9 / 10
 7-	h = h * 9 / 10
 8-	if w > 0 && h > 0 {
 9-		wp := img.Bounds().Dx()
10-		hp := img.Bounds().Dy()
11-		switch o {
12-		case 6, 8:
13-			wp, hp = hp, wp
14-		}
15-		cellPixW := ui.vx.xPixel / w
16-		cellPixH := ui.vx.yPixel / h
17-		columns := (wp + cellPixW - 1) / cellPixW
18-		lines := (hp + cellPixH - 1) / cellPixH
19-		if columns > w || lines > h {
20-			sfX := float64(w) / float64(columns)
21-			sfY := float64(h) / float64(lines)
22-			nwp := wp
23-			nhp := hp
24-			switch {
25-			case sfX < sfY:
26-				nwp = int(sfX * float64(wp))
27-				nhp = int(sfX * float64(hp))
28-			case sfX > sfY:
29-				nwp = int(sfY * float64(wp))
30-				nhp = int(sfY * float64(hp))
31-			}
32-			switch o {
33-			case 6, 8:
34-				nwp, nhp = nhp, nwp
35-			}
36-			img = imaging.Resize(img, nwp, nhp, imaging.NearestNeighbor)
37-		}
38-	}
39-
40+	img = ui.maybeResizeImage(img, o)
41 	switch o {
42 	case 3:
43 		img = imaging.Rotate180(img)
44@@ -1084,3 +1050,45 @@ func (ui *UI) DecodeImage(r io.Reader) (image.Image, string, error) {
45 	}
46 	return img, format, nil
47 }
48+
49+func (ui *UI) maybeResizeImage(img image.Image, exifOrientation int) image.Image {
50+	if ui.vx.xPixel <= 0 || ui.vx.yPixel <= 0 {
51+		return img
52+	}
53+	w, h := ui.vx.window.Size()
54+	w = w * 9 / 10
55+	h = h * 9 / 10
56+	if w <= 0 || h <= 0 {
57+		return img
58+	}
59+	wp := img.Bounds().Dx()
60+	hp := img.Bounds().Dy()
61+	switch exifOrientation {
62+	case 6, 8:
63+		wp, hp = hp, wp
64+	}
65+	cellPixW := ui.vx.xPixel / w
66+	cellPixH := ui.vx.yPixel / h
67+	columns := (wp + cellPixW - 1) / cellPixW
68+	lines := (hp + cellPixH - 1) / cellPixH
69+	if columns <= w && lines <= h {
70+		return img
71+	}
72+	sfX := float64(w) / float64(columns)
73+	sfY := float64(h) / float64(lines)
74+	nwp := wp
75+	nhp := hp
76+	switch {
77+	case sfX < sfY:
78+		nwp = int(sfX * float64(wp))
79+		nhp = int(sfX * float64(hp))
80+	case sfX > sfY:
81+		nwp = int(sfY * float64(wp))
82+		nhp = int(sfY * float64(hp))
83+	}
84+	switch exifOrientation {
85+	case 6, 8:
86+		nwp, nhp = nhp, nwp
87+	}
88+	return imaging.Resize(img, nwp, nhp, imaging.NearestNeighbor)
89+}