fit images to window; fix GetOpenFile parsing response

This commit is contained in:
2025-04-12 14:21:27 -04:00
parent c2e5b542d0
commit 8c8bddce44
3 changed files with 113 additions and 106 deletions

35
main.go
View File

@@ -7,6 +7,8 @@ import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/disintegration/imaging"
tk "modernc.org/tk9.0"
@@ -36,6 +38,13 @@ var directoryState struct {
images []string
}
func must[T any](t T, err error) T {
if err != nil {
panic(err)
}
return t
}
func isImage(entry os.DirEntry) bool {
if entry.IsDir() {
return false
@@ -51,16 +60,17 @@ func isImage(entry os.DirEntry) bool {
func newFileInDirectory(img *tk.LabelWidget) func() {
return func() {
files := tk.GetOpenFile(tk.Filetypes(validFileTypes))
files := tk.GetOpenFile(tk.Filetypes(validFileTypes), tk.Multiple(false))
if len(files) < 1 || files[0] == "" {
log.Println("no file chosen")
return
}
directoryState.currentFile = filepath.Base(files[0])
directoryState.currentDirectory = filepath.Dir(files[0])
file := strings.Join(files, " ") // GetOpenFile returns an array split on spaces!
directoryState.currentFile = filepath.Base(file)
directoryState.currentDirectory = filepath.Dir(file)
dirfiles, err := os.ReadDir(directoryState.currentDirectory)
if err != nil {
log.Println(err)
log.Printf("could not open dir: %v", err)
return
}
directoryState.images = []string{}
@@ -69,7 +79,7 @@ func newFileInDirectory(img *tk.LabelWidget) func() {
directoryState.images = append(directoryState.images, v.Name())
}
}
updateImage(files[0], img)
updateImage(file, img)
}
}
@@ -99,22 +109,19 @@ func newDirectory(img *tk.LabelWidget) func() {
func updateImage(file string, img *tk.LabelWidget) {
i, err := imaging.Open(file, imaging.AutoOrientation(true))
if err != nil {
log.Println(err.Error())
log.Printf("error opening image: %v", err)
return
}
// todo: make these bounds max out at display size
if i.Bounds().Dy() > i.Bounds().Dx() {
i = imaging.Resize(i, 0, 1000, imaging.CatmullRom)
} else {
i = imaging.Resize(i, 1000, 0, imaging.CatmullRom)
}
i = imaging.Fit(i,
must(strconv.Atoi(tk.WinfoScreenWidth(tk.App))),
must(strconv.Atoi(tk.WinfoScreenHeight(tk.App))),
imaging.Linear,
)
repaint(img, filepath.Base(file), tk.Data(i))
directoryState.currentFile = filepath.Base(file)
}
func repaint(img *tk.LabelWidget, name string, opt tk.Opt) {
photo := tk.NewPhoto(opt)
log.Printf("height: %v, width: %v", photo.Height(), photo.Width())
img.Configure(tk.Image(tk.NewPhoto(opt)))
if name != "" {
tk.App.WmTitle(fmt.Sprintf("why | %s", name))