Files
u-desktop/wallpaper.go

114 lines
2.6 KiB
Go

package main
import (
_ "embed"
"encoding/base64"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
)
//go:embed web/overlay.html
var overlayHTML string
//go:embed web/themes/aurora.html
var themeAurora string
//go:embed web/themes/starfield.html
var themeStarfield string
//go:embed web/themes/gradient.html
var themeGradient string
//go:embed web/themes/particles.html
var themeParticles string
var themeMap = map[ThemeName]string{
ThemeAurora: themeAurora,
ThemeStar: themeStarfield,
ThemeGradient: themeGradient,
ThemeParticle: themeParticles,
}
func buildWallpaperHTML(cfg *Config) string {
var bg string
switch cfg.WallpaperType {
case WPTheme:
if t, ok := themeMap[cfg.Theme]; ok {
bg = t
} else {
bg = themeAurora
}
case WPImage:
if cfg.ImagePath != "" {
src := imageToDataURI(cfg.ImagePath)
if src != "" {
bg = fmt.Sprintf(`<img src="%s" style="position:fixed;top:0;left:0;width:100%%;height:100%%;object-fit:cover;z-index:1;">`, src)
}
}
case WPBing:
bingPath := filepath.Join(configDir(), "bing_wallpaper.jpg")
if _, err := os.Stat(bingPath); err == nil {
src := imageToDataURI(bingPath)
if src != "" {
bg = fmt.Sprintf(`<img src="%s" style="position:fixed;top:0;left:0;width:100%%;height:100%%;object-fit:cover;z-index:1;">`, src)
}
}
case WPColor:
if cfg.ColorGradient && cfg.Color2 != "" {
bg = fmt.Sprintf(`<div style="position:fixed;top:0;left:0;width:100%%;height:100%%;z-index:1;background:linear-gradient(135deg,%s,%s);"></div>`, cfg.Color1, cfg.Color2)
} else {
bg = fmt.Sprintf(`<div style="position:fixed;top:0;left:0;width:100%%;height:100%%;z-index:1;background:%s;"></div>`, cfg.Color1)
}
}
if bg == "" {
bg = themeAurora
}
return strings.Replace(overlayHTML, "{{BACKGROUND}}", bg, 1)
}
func imageToDataURI(path string) string {
data, err := os.ReadFile(path)
if err != nil {
log.Println("读取图片失败:", err)
return ""
}
ext := strings.ToLower(filepath.Ext(path))
mime := "image/jpeg"
switch ext {
case ".png":
mime = "image/png"
case ".gif":
mime = "image/gif"
case ".webp":
mime = "image/webp"
case ".bmp":
mime = "image/bmp"
}
return fmt.Sprintf("data:%s;base64,%s", mime, base64.StdEncoding.EncodeToString(data))
}
func reloadWallpaper() {
if wv == nil || wvHwnd == 0 {
return
}
cfg := loadConfig()
html := buildWallpaperHTML(cfg)
select {
case htmlQueue <- html:
default:
}
procPostMessageW.Call(wvHwnd, wmSetHtml, 0, 0)
go func() {
time.Sleep(1 * time.Second)
evalJS(fmt.Sprintf(`window.userZodiac = %q;`, cfg.Zodiac))
city := getCurrentCity()
go fetchAndPushWeather(city)
}()
}