diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..d207b18
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.go text eol=lf
diff --git a/audio.go b/audio.go
index 1fe6b44..1ad256f 100644
--- a/audio.go
+++ b/audio.go
@@ -255,7 +255,12 @@ func audioCaptureLoop() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
- ole32dll.NewProc("CoInitializeEx").Call(0, 0)
+ hrInit, _, _ := ole32dll.NewProc("CoInitializeEx").Call(0, 0)
+ if hrInit != 0 && hrInit != 1 { // S_OK / S_FALSE 之外的 HRESULT 视为失败
+ log.Printf("音频捕获: CoInitializeEx 失败 hr=0x%x", hrInit)
+ close(audioDone)
+ return
+ }
defer ole32dll.NewProc("CoUninitialize").Call()
var enumerator uintptr
diff --git a/bing.go b/bing.go
index 36dd223..fe4dd21 100644
--- a/bing.go
+++ b/bing.go
@@ -112,6 +112,26 @@ func bingKey(market, date string) string {
return market + "_" + date
}
+// fetchBingImage 下载图片字节,校验 HTTP 状态与读取错误,失败返回 error
+func fetchBingImage(imgURL string) ([]byte, error) {
+ resp, err := httpClient.Get(imgURL)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 200 {
+ return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, imgURL)
+ }
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ if len(data) == 0 {
+ return nil, fmt.Errorf("empty body: %s", imgURL)
+ }
+ return data, nil
+}
+
// downloadBingImage downloads a single Bing image from the record's URLBase
func downloadBingImage(r *BingRecord) error {
imgURL := r.URLBase
@@ -184,8 +204,12 @@ func fetchBingHistory() {
log.Printf("Bing API 请求失败 (market=%s, idx=%d): %v", market, idx, err)
break
}
- data, _ := io.ReadAll(resp.Body)
+ data, err := io.ReadAll(resp.Body)
resp.Body.Close()
+ if err != nil {
+ log.Printf("Bing API 响应读取失败 (market=%s, idx=%d): %v", market, idx, err)
+ break
+ }
var br bingResponse
if json.Unmarshal(data, &br) != nil || len(br.Images) == 0 {
@@ -212,15 +236,10 @@ func fetchBingHistory() {
imgURL = "https://www.bing.com" + imgURL
}
- imgResp, err := httpClient.Get(imgURL)
+ imgData, err := fetchBingImage(imgURL)
if err != nil {
continue
}
- imgData, _ := io.ReadAll(imgResp.Body)
- imgResp.Body.Close()
- if len(imgData) == 0 {
- continue
- }
filename := fmt.Sprintf("%s_%s.jpg", market, date)
localPath := filepath.Join(bingDir(), filename)
@@ -255,8 +274,12 @@ func fetchBingHistory() {
time.Sleep(300 * time.Millisecond)
continue
}
- data, _ := io.ReadAll(resp.Body)
+ data, err := io.ReadAll(resp.Body)
resp.Body.Close()
+ if err != nil {
+ time.Sleep(300 * time.Millisecond)
+ continue
+ }
var bit biturlResponse
if json.Unmarshal(data, &bit) != nil || bit.StartDate == "" {
@@ -276,18 +299,11 @@ func fetchBingHistory() {
}
// Download from biturl URL
- imgURL := bit.URL
- imgResp, err := httpClient.Get(imgURL)
+ imgData, err := fetchBingImage(bit.URL)
if err != nil {
time.Sleep(300 * time.Millisecond)
continue
}
- imgData, _ := io.ReadAll(imgResp.Body)
- imgResp.Body.Close()
- if len(imgData) == 0 {
- time.Sleep(300 * time.Millisecond)
- continue
- }
filename := fmt.Sprintf("%s_%s.jpg", market, date)
localPath := filepath.Join(bingDir(), filename)
@@ -302,7 +318,7 @@ func fetchBingHistory() {
Market: market,
Source: "bing_biturl",
}
- time.Sleep(300 * time.Millisecond)
+ break // 该 market 补充成功,不再重试
}
}
@@ -329,23 +345,36 @@ func fetchBingHistory() {
})
// ---- Phase 3: Enforce 2000 cap ----
+ currentIdx := existing.CurrentIdx
+ if currentIdx >= len(records) {
+ currentIdx = len(records) - 1
+ }
+ if currentIdx < 0 {
+ currentIdx = 0
+ }
if len(records) > maxBingRecords {
// Records sorted oldest-first, so oldest are at the head
toRemove := records[:len(records)-maxBingRecords]
+ removed := len(records) - maxBingRecords
records = records[len(records)-maxBingRecords:]
for _, r := range toRemove {
p := filepath.Join(bingDir(), r.Filename)
os.Remove(p)
}
log.Printf("Bing 壁纸: 裁剪到 %d 张, 删除 %d 张旧图", maxBingRecords, len(toRemove))
+ // 当前索引左移裁剪掉的数量并夹取到有效范围
+ currentIdx -= removed
+ if currentIdx >= len(records) {
+ currentIdx = len(records) - 1
+ }
+ if currentIdx < 0 {
+ currentIdx = 0
+ }
}
history := &BingHistory{
Records: records,
- CurrentIdx: 0,
- }
- if existing.CurrentIdx < len(records) {
- history.CurrentIdx = existing.CurrentIdx
+ CurrentIdx: currentIdx,
}
saveBingHistory(history)
@@ -589,6 +618,7 @@ func bingWallpaperLoop() {
}
// Move to next (newer) image, skip hidden
attempts := 0
+ allHidden := false
for {
h.CurrentIdx = (h.CurrentIdx + 1) % len(h.Records)
if !h.Records[h.CurrentIdx].Hidden {
@@ -596,9 +626,14 @@ func bingWallpaperLoop() {
}
attempts++
if attempts >= len(h.Records) {
+ allHidden = true
break
}
}
+ if allHidden {
+ bingMu.Unlock()
+ continue
+ }
saveBingHistory(h)
bingMu.Unlock()
bingReloadImage()
diff --git a/config.go b/config.go
index 2b8a432..f4b616e 100644
--- a/config.go
+++ b/config.go
@@ -6,6 +6,7 @@ import (
"log"
"os"
"path/filepath"
+ "sync"
)
type WallpaperType string
@@ -86,6 +87,8 @@ const defaultZodiac = "射手座"
var configPath string
+var configMu sync.Mutex
+
//go:embed assets/icons/tray.ico
var trayIcon []byte
@@ -94,6 +97,8 @@ func configDir() string {
}
func loadConfig() *Config {
+ configMu.Lock()
+ defer configMu.Unlock()
data, err := os.ReadFile(configPath)
if err != nil {
return defaultConfig()
@@ -138,12 +143,25 @@ func defaultConfig() *Config {
}
func saveConfig(cfg *Config) error {
+ configMu.Lock()
+ defer configMu.Unlock()
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Println("配置序列化失败:", err)
return err
}
- return os.WriteFile(configPath, data, 0644)
+ tmpPath := configPath + ".tmp"
+ if err := os.WriteFile(tmpPath, data, 0644); err != nil {
+ log.Println("配置临时文件写入失败:", err)
+ return err
+ }
+ // os.Rename 在 Windows 上经 MoveFileEx(REPLACE_EXISTING) 可直接覆盖,先 Remove 反而留崩溃窗口
+ if err := os.Rename(tmpPath, configPath); err != nil {
+ os.Remove(tmpPath)
+ log.Println("配置原子替换失败:", err)
+ return err
+ }
+ return nil
}
func getSecret(envName, cfgValue string) string {
diff --git a/knowledge.go b/knowledge.go
index 0cc3626..6de6fe3 100644
--- a/knowledge.go
+++ b/knowledge.go
@@ -434,8 +434,8 @@ func fetchAndPushKnowledge() {
pushKnowledgeJSON(content, keyword)
preview := content
- if len(preview) > 30 {
- preview = preview[:30] + "..."
+ if len([]rune(preview)) > 30 {
+ preview = string([]rune(preview)[:30]) + "..."
}
log.Println("知识卡片已推送:", preview)
}
diff --git a/photo.go b/photo.go
index eb3e1b4..0b15a40 100644
--- a/photo.go
+++ b/photo.go
@@ -100,6 +100,14 @@ func pushCurrentPhoto(interval int) {
}
func startPhotoLoop() {
+ // 重入保护:已有循环在跑则先停掉
+ photoMu.Lock()
+ running := photoStop != nil
+ photoMu.Unlock()
+ if running {
+ stopPhotoLoop()
+ }
+
cfg := loadConfig()
if cfg.PhotoDir == "" || cfg.HidePhoto {
return
@@ -117,6 +125,11 @@ func startPhotoLoop() {
}
photoMu.Lock()
+ if photoStop != nil {
+ // 停旧与注册新之间有并发 startPhotoLoop 已完成注册,放弃本次避免覆盖其 stop channel
+ photoMu.Unlock()
+ return
+ }
photoDir = cfg.PhotoDir
photoFiles = files
photoIdx = 0
diff --git a/settings.go b/settings.go
index 85ee73c..143800c 100644
--- a/settings.go
+++ b/settings.go
@@ -26,6 +26,7 @@ var (
settingsOldWndProc uintptr // 子类化前的原始 wndproc
settingsWndProcCb uintptr // NewCallback 指针,防止 GC
settingsCreated bool // 首次创建完成后 true
+ settingsCreating bool // 创建中占位,防止双开竞态
)
const runKeyPath = `Software\Microsoft\Windows\CurrentVersion\Run`
@@ -128,6 +129,11 @@ func openSettingsWindow() {
})
return
}
+ if settingsCreating {
+ settingsMu.Unlock()
+ return
+ }
+ settingsCreating = true
settingsMu.Unlock()
go func() {
@@ -148,6 +154,9 @@ func openSettingsWindow() {
})
if w == nil {
log.Println("设置窗口: 创建失败")
+ settingsMu.Lock()
+ settingsCreating = false
+ settingsMu.Unlock()
return
}
@@ -611,5 +620,12 @@ func openSettingsWindow() {
log.Println("设置窗口已打开")
w.Run()
log.Println("设置窗口消息循环退出")
+ settingsMu.Lock()
+ settingsCreated = false
+ settingsCreating = false
+ settingsWv = nil
+ settingsHwnd = 0
+ settingsOldWndProc = 0
+ settingsMu.Unlock()
}()
}
diff --git a/systray.go b/systray.go
index cea8736..d194a5c 100644
--- a/systray.go
+++ b/systray.go
@@ -65,8 +65,15 @@ func onSystrayReady() {
go func() {
for {
<-mRestart.ClickedCh
- exe, _ := os.Executable()
- exec.Command(exe).Start()
+ exe, err := os.Executable()
+ if err != nil {
+ log.Println("重启失败: 获取自身路径失败:", err)
+ continue
+ }
+ if err := exec.Command(exe).Start(); err != nil {
+ log.Println("重启失败: 启动新进程失败:", err)
+ continue
+ }
os.Exit(0)
}
}()
@@ -185,7 +192,7 @@ func startWebView() {
uintptr(unsafe.Pointer(&m)),
0, 0, 0,
)
- if ret == 0 {
+ if ret == 0 || int32(ret) == -1 {
break
}
if m.message == wmEvalJS {
diff --git a/updater.go b/updater.go
index f7141a1..8e10fab 100644
--- a/updater.go
+++ b/updater.go
@@ -162,20 +162,24 @@ func showUpdateWindow(info *UpdateInfo) {
}
w.Bind("getUpdateInfo", func() string {
+ updateMu.Lock()
+ defer updateMu.Unlock()
if updateInfo == nil {
return "{}"
}
data, _ := json.Marshal(map[string]interface{}{
- "version": updateInfo.Version,
- "force": updateInfo.Force,
- "releaseNotes": updateInfo.ReleaseNotes,
- "size": updateInfo.Package.Size,
+ "version": updateInfo.Version,
+ "force": updateInfo.Force,
+ "releaseNotes": updateInfo.ReleaseNotes,
+ "size": updateInfo.Package.Size,
"currentVersion": version,
})
return string(data)
})
w.Bind("skipUpdate", func() string {
+ updateMu.Lock()
+ defer updateMu.Unlock()
if updateInfo != nil && !updateInfo.Force {
cfg := loadConfig()
cfg.SkipVersion = updateInfo.Version
@@ -185,10 +189,13 @@ func showUpdateWindow(info *UpdateInfo) {
})
w.Bind("startUpdate", func() string {
- if updateInfo == nil {
+ updateMu.Lock()
+ info := updateInfo
+ updateMu.Unlock()
+ if info == nil {
return ""
}
- go doStartUpdate(updateInfo)
+ go doStartUpdate(info)
return ""
})
diff --git a/weather.go b/weather.go
index d5c2afc..6fb1863 100644
--- a/weather.go
+++ b/weather.go
@@ -594,7 +594,9 @@ func fetchAndPushWeather(city City) {
}
wd.City = cityName
+ fetchOK := false
if now := fetchCurrentWeather(city.ID); now != nil {
+ fetchOK = true
icon := getWeatherIcon(now.Text)
wd.Current = fmt.Sprintf("📍 %s %s %s %s°C", cityName, icon, now.Text, now.Temp)
} else {
@@ -605,10 +607,12 @@ func fetchAndPushWeather(city City) {
wd.Daily = fetchDailyForecast(city.ID)
jsonData, _ := json.Marshal(wd)
- weatherCacheMu.Lock()
- weatherCache[city.ID] = time.Now()
- weatherCacheData[city.ID] = string(jsonData)
- weatherCacheMu.Unlock()
+ if fetchOK {
+ weatherCacheMu.Lock()
+ weatherCache[city.ID] = time.Now()
+ weatherCacheData[city.ID] = string(jsonData)
+ weatherCacheMu.Unlock()
+ }
evalJS(fmt.Sprintf(`if(window.updateWeatherFromGo) window.updateWeatherFromGo(%s)`, string(jsonData)))
log.Println("天气已推送:", wd.Current)
}
diff --git a/web-ui/src/overlay/App.vue b/web-ui/src/overlay/App.vue
index 936b370..1d6731f 100644
--- a/web-ui/src/overlay/App.vue
+++ b/web-ui/src/overlay/App.vue
@@ -24,6 +24,8 @@ const bgMount = ref
"),o=o.replace(/`([^`]+)`/g,"$2$1"),o=o.replace(/\*\*(.+?)\*\*/g,"$1"),o=o.replace(/(?$1"),o=o.replace(/^##\s+(.+)$/gm,"$1
"),o=o.replace(/^[-*]\s+(.+)$/gm,"$1
"),o=o.replace(/\n\n+/g,"
"),o=o.replace(/(?|<\/h3>|<\/pre>|<\/code>)\n(?!
|<\/ul>)/g,"
"),o.startsWith("<")||(o=""+o+"
"),o}const i=ct(()=>r(w.knowledge.content));return(l,o)=>(E(),H("div",rc,[F("div",ic,[o[0]||(o[0]=F("span",{class:"knowledge-label"},"知识卡片",-1)),M(w).knowledge.keyword?(E(),H("span",oc,"#"+W(M(w).knowledge.keyword),1)):U("",!0),F("button",{class:"knowledge-refresh-btn",onClick:t,title:"换一条"},"↻")]),o[2]||(o[2]=F("div",{class:"knowledge-divider"},null,-1)),M(w).knowledge.content?(E(),H("div",lc,[o[1]||(o[1]=F("span",{class:"knowledge-quote"},'"',-1)),F("div",{class:"knowledge-text",innerHTML:i.value},null,8,cc)])):(E(),H("div",fc,"请在设置中配置知识关键字"))]))}}),ei=Be(uc,[["__scopeId","data-v-47aa1c52"]]);function ac(e){const t=String(e||"").trim();return/^(https?:|data:image\/)/i.test(t)?t:""}const dc=["src"],hc={class:"ainews-body"},pc={class:"ainews-title-row"},gc={class:"ainews-title"},_c={class:"ainews-source"},mc={key:0,class:"ainews-desc"},yc=ke({__name:"AINewsCard",setup(e){function t(s){return s?.length>10?s.substring(5,10):s}return(s,n)=>(E(),H("div",null,[n[1]||(n[1]=F("div",{class:"ainews-header"},"🤖 AI 资讯",-1)),(E(!0),H(te,null,is(M(w).aiNews.slice(0,5),(r,i)=>(E(),H("div",{class:"ainews-item",key:i},[M(ac)(r.picUrl)?(E(),H("img",{key:0,class:"ainews-img",src:r.picUrl,loading:"lazy",onError:n[0]||(n[0]=l=>l.target.style.display="none")},null,40,dc)):U("",!0),F("div",hc,[F("div",pc,[F("span",gc,W(r.title),1),F("span",_c,W(r.source)+" · "+W(t(r.ctime)),1)]),r.description?(E(),H("div",mc,W(r.description),1)):U("",!0)])]))),128))]))}}),ti=Be(yc,[["__scopeId","data-v-842d17af"]]),bc={id:"layout-single"},vc={id:"info",class:"card"},wc={key:2,class:"divider"},xc={key:4,class:"divider"},Sc={key:6,class:"divider"},Cc=ke({__name:"SingleLayout",setup(e){return(t,s)=>(E(),H("div",bc,[F("div",vc,[M(w).cardVisibility.time?(E(),Ze(Yr,{key:0})):U("",!0),s[0]||(s[0]=F("div",{class:"divider"},null,-1)),M(w).cardVisibility.ainews?(E(),Ze(ti,{key:1})):U("",!0),M(w).cardVisibility.ainews?(E(),H("div",wc)):U("",!0),M(w).cardVisibility.knowledge?(E(),Ze(ei,{key:3})):U("",!0),M(w).cardVisibility.knowledge?(E(),H("div",xc)):U("",!0),M(w).cardVisibility.weather?(E(),Ze(Xr,{key:5})):U("",!0),M(w).cardVisibility.weather?(E(),H("div",Sc)):U("",!0),M(w).cardVisibility.zodiac?(E(),Ze(Qr,{key:7})):U("",!0)])]))}}),Tc=Be(Cc,[["__scopeId","data-v-89757d39"]]),Ac={key:0,id:"card-photo",class:"card"},Ec={class:"photo-wrap"},Oc=["src"],Mc={class:"photo-info"},$c={class:"photo-counter"},Ic={class:"photo-progress"},Pc=ke({__name:"PhotoCard",setup(e){const t=Ye(!1),s=Ye();return Fe(()=>w.photo?.src,()=>{if(t.value=!1,!s.value)return;const n=s.value;n.style.transition="none",n.style.width="0%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{const r=w.photo?.interval||15;n.style.transition=`width ${r}s linear`,n.style.width="100%"})})}),(n,r)=>M(w).photo?.src?(E(),H("div",Ac,[F("div",Ec,[F("img",{src:M(w).photo.src,alt:"",onLoad:r[0]||(r[0]=i=>t.value=!0),style:lt({opacity:t.value?1:0})},null,44,Oc),F("div",Mc,[F("span",$c,W(M(w).photo.counter),1),F("div",Ic,[F("div",{class:"photo-progress-bar",ref_key:"progressBar",ref:s},null,512)])])])])):U("",!0)}}),Fc=Be(Pc,[["__scopeId","data-v-32718552"]]),Rc={id:"layout-multi"},Hc={key:0,id:"card-time",class:"card"},kc={key:1,id:"card-zodiac",class:"card"},Dc={key:2,id:"card-knowledge",class:"card"},Nc={key:3,id:"card-ainews",class:"card"},Lc={key:4,id:"card-weather",class:"card"},Vc=ke({__name:"MultiLayout",setup(e){return(t,s)=>(E(),H("div",Rc,[M(w).cardVisibility.time?(E(),H("div",Hc,[ce(Yr)])):U("",!0),M(w).cardVisibility.zodiac?(E(),H("div",kc,[ce(Qr)])):U("",!0),M(w).cardVisibility.knowledge?(E(),H("div",Dc,[ce(ei)])):U("",!0),M(w).cardVisibility.ainews?(E(),H("div",Nc,[ce(ti)])):U("",!0),M(w).cardVisibility.weather?(E(),H("div",Lc,[ce(Xr)])):U("",!0),ce(Fc)]))}}),jc=Be(Vc,[["__scopeId","data-v-a78a7499"]]),Kc=["src"],Wc=["src"],Uc={class:"photo-frame-clock"},Bc={class:"photo-frame-date"},zc=ke({__name:"PhotoFrame",setup(e){const{timeStr:t,dateStr:s}=Zr(),n=Ye(!1);return Fe(()=>w.photo?.src,()=>{!w.photoFrameMode||!w.photo?.src||(n.value=!1,setTimeout(()=>{n.value=!0},400))}),(r,i)=>M(w).photoFrameMode?(E(),H(te,{key:0},[F("img",{id:"photo-frame-bg",src:M(w).photo?.src,alt:"",style:lt({opacity:n.value?1:0})},null,12,Kc),F("img",{id:"photo-frame-img",src:M(w).photo?.src,alt:"",style:lt({opacity:n.value?1:0})},null,12,Wc),F("div",Uc,W(M(t)),1),F("div",Bc,W(M(s)),1)],64)):U("",!0)}}),qc=Be(zc,[["__scopeId","data-v-fd359286"]]),Gc=ke({__name:"App",setup(e){const t=Ye();function s(n){const r=t.value;r&&(window.__themeCleanup?.(),r.innerHTML=n,r.querySelectorAll("script").forEach(i=>{const l=document.createElement("script");i.src?l.src=i.src:l.textContent=i.textContent;for(const o of i.attributes)l.setAttribute(o.name,o.value);i.parentNode?.replaceChild(l,i)}))}return ms(()=>{Ml(),w.backgroundHtml&&w.wallpaperVisible&&s(w.backgroundHtml)}),Fe(()=>w.backgroundHtml,n=>{w.wallpaperVisible&&s(n)}),Fe(()=>w.wallpaperVisible,n=>{const r=t.value;r&&(n&&w.backgroundHtml?s(w.backgroundHtml):(window.__themeCleanup?.(),r.innerHTML=""))}),(n,r)=>(E(),H(te,null,[F("div",{id:"bg-mount",ref_key:"bgMount",ref:t},null,512),M(w).photoFrameMode?U("",!0):(E(),H(te,{key:0},[M(w).layout==="single"?(E(),Ze(Tc,{key:0})):(E(),Ze(jc,{key:1}))],64)),ce(qc),r[0]||(r[0]=F("div",{id:"author"},"绝尘",-1))],64))}});function at(e){return typeof e=="string"?JSON.parse(e):e}const Bn=new Map;function dt(e,t){const s=JSON.stringify(t);return Bn.get(e)===s?!1:(Bn.set(e,s),!0)}function Jc(){const e=window;e.updateHoroscopeFromGo=t=>{const s=at(t);dt("horoscope",s)&&(w.horoscope=s)},e.updateAINewsFromGo=t=>{const s=at(t);s?.length&&dt("ainews",s)&&(w.aiNews=s)},e.updateKnowledgeFromGo=t=>{const s=at(t);dt("knowledge",s)&&(w.knowledge=s)},e.updateWeatherFromGo=t=>{const s=at(t);dt("weather",s)&&(w.weather=s)},e.updatePhotoFromGo=t=>{const s=at(t);if(s==null){dt("photo",s)&&(w.photo=null);return}s?.src&&dt("photo",s)&&(w.photo=s)},e.setCardVisible=(t,s)=>{t in w.cardVisibility&&(w.cardVisibility[t]=s)},e.setWallpaperVisible=t=>{w.wallpaperVisible=t},e.setPhotoFrameMode=t=>{w.photoFrameMode=t},e.setShowSeconds=t=>{w.showSeconds=t},Object.defineProperty(e,"userZodiac",{set(t){w.userZodiac=t},get(){return w.userZodiac}}),e.__updateBackgroundHtml=t=>{w.backgroundHtml=t},e.updateAudioDataFromGo=t=>{const s=at(t);Array.isArray(s)&&(window.__audioBins=s)}}Jc();Al(Gc).mount("#app"); + diff --git a/web/themes/audio-viz.html b/web/themes/audio-viz.html index 730959e..4e28c51 100644 --- a/web/themes/audio-viz.html +++ b/web/themes/audio-viz.html @@ -33,6 +33,13 @@ function resizeCanvas() { resizeCanvas(); window.addEventListener('resize', resizeCanvas); +// 主题被替换前由挂载方调用,终止 rAF / 监听,防 CPU 累积 +var __stopped = false; +window.__themeCleanup = function() { + __stopped = true; + window.removeEventListener('resize', resizeCanvas); +}; + // === 配色系统 === function getGradient(n) { var stops = []; @@ -1188,6 +1195,7 @@ function renderIdle(w, h, ts) { var FPS = 30, lastFrame = 0; function render(ts) { + if (__stopped) return; requestAnimationFrame(render); if (ts - lastFrame < 1000 / FPS) return; lastFrame = ts; diff --git a/web/themes/aurora.html b/web/themes/aurora.html index d32a8b2..bc04919 100644 --- a/web/themes/aurora.html +++ b/web/themes/aurora.html @@ -58,7 +58,10 @@ gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,1,-1]),gl.STATIC_ var startTime=Date.now(); var FPS=15,lastFrame=0; +var __stopped=false; +window.__themeCleanup=function(){__stopped=true;}; function render(ts){ + if(__stopped)return; requestAnimationFrame(render); if(ts-lastFrame<1000/FPS)return; lastFrame=ts; diff --git a/web/themes/fractal.html b/web/themes/fractal.html index 9b1e000..30007c6 100644 --- a/web/themes/fractal.html +++ b/web/themes/fractal.html @@ -137,7 +137,10 @@ resize(); var lastFrame=0, targetFPS=30; +var __stopped=false; +window.__themeCleanup=function(){__stopped=true;window.removeEventListener('resize',resize);}; function render(now){ + if(__stopped)return; requestAnimationFrame(render); if(window._paused||window._fullscreen)return; diff --git a/web/themes/particles.html b/web/themes/particles.html index 9afafcf..57def60 100644 --- a/web/themes/particles.html +++ b/web/themes/particles.html @@ -25,7 +25,11 @@ for (var i = 0; i < 80; i++) { var FPS = 15, lastFrame = 0; +var __stopped = false; +window.__themeCleanup = function() { __stopped = true; }; + function render(ts) { + if (__stopped) return; requestAnimationFrame(render); if (ts - lastFrame < 1000 / FPS) return; lastFrame = ts; diff --git a/web/themes/starfield.html b/web/themes/starfield.html index 9df3613..88634e0 100644 --- a/web/themes/starfield.html +++ b/web/themes/starfield.html @@ -22,7 +22,11 @@ for (var i = 0; i < 300; i++) { var FPS = 15, lastFrame = 0; +var __stopped = false; +window.__themeCleanup = function() { __stopped = true; }; + function render(ts) { + if (__stopped) return; requestAnimationFrame(render); if (ts - lastFrame < 1000 / FPS) return; lastFrame = ts; diff --git a/web/update.html b/web/update.html index 849a89a..a58a591 100644 --- a/web/update.html +++ b/web/update.html @@ -82,13 +82,32 @@ body {