From 5e93e0458159ef1e02da0e5f6d0a84c8ef0d01bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BB=9D=E5=B0=98?= <237809796@qq.com> Date: Wed, 2 Dec 2026 22:30:43 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D:=20=E8=B5=B0=E6=9F=A5?= =?UTF-8?q?=E6=89=B9=E4=BF=AE22=E9=A1=B9=E7=BC=BA=E9=99=B7(=E6=A0=B7?= =?UTF-8?q?=E5=BC=8F=E5=B8=B8=E9=87=8F/=E9=85=8D=E7=BD=AE=E5=8E=9F?= =?UTF-8?q?=E5=AD=90=E5=86=99/=E5=A3=81=E7=BA=B8=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C/=E5=89=8D=E7=AB=AF=E6=B3=84=E6=BC=8F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GWL_EXSTYLE 常量多写一个F致样式写入错误偏移 - 配置读写加锁+临时文件原子替换;更新窗口Promise化修白屏 - Bing壁纸: 裁剪后索引同步/下载校验状态码/超2000裁剪/隐藏图切换 - 天气假兜底不再入缓存; 相册循环重入保护; 中文日志按rune截断 - 主题壁纸rAF泄漏清理钩子; 知识卡热区复位; 照片清空指令透传 - 设置窗双开竞态+销毁后可重建; 消息循环-1退出; 重启失败不退出 --- .gitattributes | 1 + audio.go | 7 +- bing.go | 77 ++++++++++++++----- config.go | 20 ++++- knowledge.go | 4 +- photo.go | 13 ++++ settings.go | 16 ++++ systray.go | 13 +++- updater.go | 19 +++-- weather.go | 12 ++- web-ui/src/overlay/App.vue | 7 +- web-ui/src/overlay/bridge.ts | 4 + .../src/overlay/components/KnowledgeCard.vue | 14 +++- web/overlay.html | 12 +-- web/themes/audio-viz.html | 8 ++ web/themes/aurora.html | 3 + web/themes/fractal.html | 3 + web/themes/particles.html | 4 + web/themes/starfield.html | 4 + web/update.html | 32 +++++--- win32.go | 2 +- 21 files changed, 217 insertions(+), 58 deletions(-) create mode 100644 .gitattributes 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() function mountBackground(html: string) { const el = bgMount.value if (!el) return + // 主题被替换前先终止其自续 rAF / 监听,防 CPU 累积 + ;(window as any).__themeCleanup?.() el.innerHTML = html // v-html skips diff --git a/web-ui/src/overlay/bridge.ts b/web-ui/src/overlay/bridge.ts index 92aef45..c421c7f 100644 --- a/web-ui/src/overlay/bridge.ts +++ b/web-ui/src/overlay/bridge.ts @@ -38,6 +38,10 @@ export function registerGoBridge() { w.updatePhotoFromGo = (data: any) => { const parsed = parseArg(data) + if (parsed == null) { + if (shouldUpdate('photo', parsed)) state.photo = null + return + } if (parsed?.src && shouldUpdate('photo', parsed)) state.photo = parsed } diff --git a/web-ui/src/overlay/components/KnowledgeCard.vue b/web-ui/src/overlay/components/KnowledgeCard.vue index 8c55638..6c9ecc9 100644 --- a/web-ui/src/overlay/components/KnowledgeCard.vue +++ b/web-ui/src/overlay/components/KnowledgeCard.vue @@ -15,7 +15,7 @@ - +**/let Us;const Fn=typeof window<"u"&&window.trustedTypes;if(Fn)try{Us=Fn.createPolicy("vue",{createHTML:e=>e})}catch{}const Jr=Us?e=>Us.createHTML(e):e=>e,sl="http://www.w3.org/2000/svg",nl="http://www.w3.org/1998/Math/MathML",Ne=typeof document<"u"?document:null,Rn=Ne&&Ne.createElement("template"),rl={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const r=t==="svg"?Ne.createElementNS(sl,e):t==="mathml"?Ne.createElementNS(nl,e):s?Ne.createElement(e,{is:s}):Ne.createElement(e);return e==="select"&&n&&n.multiple!=null&&r.setAttribute("multiple",n.multiple),r},createText:e=>Ne.createTextNode(e),createComment:e=>Ne.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Ne.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,r,i){const l=s?s.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),s),!(r===i||!(r=r.nextSibling)););else{Rn.innerHTML=Jr(n==="svg"?`${e}`:n==="mathml"?`${e}`:e);const o=Rn.content;if(n==="svg"||n==="mathml"){const f=o.firstChild;for(;f.firstChild;)o.appendChild(f.firstChild);o.removeChild(f)}t.insertBefore(o,s)}return[l?l.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},il=Symbol("_vtc");function ol(e,t,s){const n=e[il];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const Hn=Symbol("_vod"),ll=Symbol("_vsh"),cl=Symbol(""),fl=/(?:^|;)\s*display\s*:/;function ul(e,t,s){const n=e.style,r=ee(s);let i=!1;if(s&&!r){if(t)if(ee(t))for(const l of t.split(";")){const o=l.slice(0,l.indexOf(":")).trim();s[o]==null&&Ot(n,o,"")}else for(const l in t)s[l]==null&&Ot(n,l,"");for(const l in s){l==="display"&&(i=!0);const o=s[l];o!=null?dl(e,l,!ee(t)&&t?t[l]:void 0,o)||Ot(n,l,o):Ot(n,l,"")}}else if(r){if(t!==s){const l=n[cl];l&&(s+=";"+l),n.cssText=s,i=fl.test(s)}}else t&&e.removeAttribute("style");Hn in e&&(e[Hn]=i?n.display:"",e[ll]&&(n.display="none"))}const kn=/\s*!important$/;function Ot(e,t,s){if(R(s))s.forEach(n=>Ot(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=al(e,t);kn.test(s)?e.setProperty(ft(n),s.replace(kn,""),"important"):e[n]=s}}const Dn=["Webkit","Moz","ms"],Is={};function al(e,t){const s=Is[t];if(s)return s;let n=ye(t);if(n!=="filter"&&n in e)return Is[t]=n;n=Yn(n);for(let r=0;rPs||(ml.then(()=>Ps=0),Ps=Date.now());function bl(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;He(vl(n,s.value),t,5,[n])};return s.value=e,s.attached=yl(),s}function vl(e,t){if(R(t)){const s=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{s.call(e),e._stopped=!0},t.map(n=>r=>!r._stopped&&n&&n(r))}else return t}const Wn=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,wl=(e,t,s,n,r,i)=>{const l=r==="svg";t==="class"?ol(e,n,l):t==="style"?ul(e,s,n):cs(t)?fs(t)||gl(e,t,s,n,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):xl(e,t,n,l))?(Vn(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&Ln(e,t,n,l,i,t!=="value")):e._isVueCE&&(Sl(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!ee(n)))?Vn(e,ye(t),n,i,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._falseValue=n),Ln(e,t,n,l))};function xl(e,t,s,n){if(n)return!!(t==="innerHTML"||t==="textContent"||t in e&&Wn(t)&&k(s));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return Wn(t)&&ee(s)?!1:t in e}function Sl(e,t){const s=e._def.props;if(!s)return!1;const n=ye(t);return Array.isArray(s)?s.some(r=>ye(r)===n):Object.keys(s).some(r=>ye(r)===n)}const Cl=oe({patchProp:wl},rl);let Un;function Tl(){return Un||(Un=ko(Cl))}const Al=((...e)=>{const t=Tl().createApp(...e),{mount:s}=t;return t.mount=n=>{const r=Ol(n);if(!r)return;const i=t._component;!k(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const l=s(r,!1,El(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),l},t});function El(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Ol(e){return ee(e)?document.querySelector(e):e}const w=ps({layout:"single",showSeconds:!0,userZodiac:"射手座",wallpaperVisible:!0,photoFrameMode:!1,cardVisibility:{time:!0,weather:!0,zodiac:!0,knowledge:!0,ainews:!0,photo:!0},backgroundHtml:"",weather:null,horoscope:null,aiNews:[],knowledge:{content:"",keyword:""},photo:null});function Ml(){const e=window.__INITIAL_DATA__;e&&(e.layout&&(w.layout=e.layout),e.showSeconds!==void 0&&(w.showSeconds=e.showSeconds),e.userZodiac&&(w.userZodiac=e.userZodiac),e.wallpaperVisible!==void 0&&(w.wallpaperVisible=e.wallpaperVisible),e.photoFrameMode!==void 0&&(w.photoFrameMode=e.photoFrameMode),e.cardVisibility&&Object.assign(w.cardVisibility,e.cardVisibility),e.backgroundHtml&&(w.backgroundHtml=e.backgroundHtml))}function Zr(){const e=Ye("00:00"),t=Ye("1月1日 周一"),s=Ye("");let n=null,r="",i="";const l=[{m:1,d:1,name:"元旦"},{m:2,d:14,name:"情人节"},{m:3,d:8,name:"妇女节"},{m:4,d:5,name:"清明节"},{m:5,d:1,name:"劳动节"},{m:5,d:4,name:"青年节"},{m:6,d:1,name:"儿童节"},{m:7,d:1,name:"建党节"},{m:8,d:1,name:"建军节"},{m:9,d:10,name:"教师节"},{m:10,d:1,name:"国庆节"},{m:10,d:31,name:"万圣节"},{m:12,d:25,name:"圣诞节"}];function o(d){const a=d.getFullYear(),p=[];for(const x of l){const T=new Date(a,x.m-1,x.d);let D=Math.ceil((T.getTime()-d.getTime())/864e5);if(D>0&&D<=60&&p.push({diff:D,name:x.name}),D<0){const $=new Date(a+1,x.m-1,x.d);D=Math.ceil(($.getTime()-d.getTime())/864e5),D>0&&D<=60&&p.push({diff:D,name:x.name})}}return p.sort((x,T)=>x.diff-T.diff),p.length>0?`距${p[0].name}还有${p[0].diff}天`:""}function f(){const d=new Date,a=String(d.getHours()).padStart(2,"0"),p=String(d.getMinutes()).padStart(2,"0"),x=String(d.getSeconds()).padStart(2,"0"),T=w.showSeconds?`${a}:${p}:${x}`:`${a}:${p}`,D=d.getMonth()+1,$=d.getDate(),Q=["周日","周一","周二","周三","周四","周五","周六"][d.getDay()],K=`${D}月${$}日 ${Q}`;if(T!==r&&(e.value=T,r=T),K!==i){const N=o(d);t.value=K,s.value=N,i=K}}return ms(()=>{f(),n=window.setInterval(f,1e3)}),Wt(()=>{n&&clearInterval(n)}),{timeStr:e,dateStr:t,holidayStr:s}}const $l=["innerHTML"],Il=ke({__name:"TimeCard",setup(e){const{timeStr:t,dateStr:s,holidayStr:n}=Zr(),r=Ye(!1);let i=null;const l=ct(()=>n.value?`${s.value} 「${n.value}」`:s.value);return Fe(t,o=>{(o.endsWith(":00:00")||o.endsWith(":00"))&&(r.value=!1,requestAnimationFrame(()=>{r.value=!0}),i&&clearTimeout(i),i=window.setTimeout(()=>{r.value=!1},6e3))}),Wt(()=>{i&&clearTimeout(i)}),(o,f)=>(E(),H(te,null,[F("div",{class:"date",innerHTML:l.value},null,8,$l),F("div",{class:ds(["time",{"hourly-glow":r.value}])},W(M(t)),3)],64))}}),Be=(e,t)=>{const s=e.__vccOpts||e;for(const[n,r]of t)s[n]=r;return s},Yr=Be(Il,[["__scopeId","data-v-fc6abe16"]]),Pl={key:0,class:"current-weather"},Fl={class:"weather-forecast"},Rl={class:"forecast-time"},Hl={class:"forecast-icon"},kl={class:"forecast-temp"},Dl={key:0,class:"forecast-pop"},Nl={class:"daily-forecast"},Ll={style:{opacity:"0.6","font-size":"10px"}},Vl={class:"daily-icon"},jl={class:"forecast-temp"},Kl=ke({__name:"WeatherCard",setup(e){return(t,s)=>(E(),H(te,null,[M(w).weather?.current?(E(),H("div",Pl,W(M(w).weather.current),1)):U("",!0),M(w).weather?.hourly?.length?(E(),H(te,{key:1},[s[0]||(s[0]=F("div",{class:"forecast-title"},"24小时预报",-1)),F("div",Fl,[(E(!0),H(te,null,is(M(w).weather.hourly,n=>(E(),H("div",{class:"forecast-item",key:n.time},[F("div",Rl,W(n.time),1),F("div",Hl,W(n.icon),1),F("div",kl,W(n.temp),1),n.pop&&n.pop!=="0"?(E(),H("div",Dl,W(n.pop)+"%",1)):U("",!0)]))),128))])],64)):U("",!0),M(w).weather?.daily?.length?(E(),H(te,{key:2},[s[1]||(s[1]=F("div",{class:"forecast-title",style:{"margin-top":"12px"}},"7日预报",-1)),F("div",Nl,[(E(!0),H(te,null,is(M(w).weather.daily,n=>(E(),H("div",{class:"daily-item",key:n.date},[F("div",Ll,W(n.date),1),F("div",Vl,W(n.icon),1),F("div",jl,W(n.tempMin)+"°~"+W(n.tempMax)+"°",1)]))),128))])],64)):U("",!0)],64))}}),Xr=Be(Kl,[["__scopeId","data-v-874326b5"]]),Wl={白羊座:{icon:"♈",date:"3.21-4.19"},金牛座:{icon:"♉",date:"4.20-5.20"},双子座:{icon:"♊",date:"5.21-6.21"},巨蟹座:{icon:"♋",date:"6.22-7.22"},狮子座:{icon:"♌",date:"7.23-8.22"},处女座:{icon:"♍",date:"8.23-9.22"},天秤座:{icon:"♎",date:"9.23-10.23"},天蝎座:{icon:"♏",date:"10.24-11.22"},射手座:{icon:"♐",date:"11.23-12.21"},摩羯座:{icon:"♑",date:"12.22-1.19"},水瓶座:{icon:"♒",date:"1.20-2.18"},双鱼座:{icon:"♓",date:"2.19-3.20"}},At={all:"#e0e0e0",love:"#ff6b9d",work:"#4fc3f7",money:"#ffd54f",health:"#81c784"};function Ul(){const e=ct(()=>Wl[w.userZodiac]||{icon:"✨",date:""}),t=ct(()=>w.horoscope);return{zodiacInfo:e,data:t}}const Bl={class:"zodiac-text"},zl={class:"zodiac-title"},ql={class:"zodiac-date"},Gl={class:"zodiac-bar-label"},Jl={class:"zodiac-bar-track"},Zl={class:"zodiac-bar-val"},Yl={key:0,class:"zodiac-tags"},Xl={key:0,class:"zodiac-tag"},Ql={key:1,class:"zodiac-tag"},ec={key:2,class:"zodiac-tag"},tc={key:1,class:"zodiac-summary"},sc={key:1,style:{opacity:"0.4","font-size":"12px","margin-top":"8px"}},nc=ke({__name:"ZodiacCard",setup(e){const{zodiacInfo:t,data:s}=Ul(),n=ct(()=>s.value?[{label:"综合",val:parseInt(s.value.all)||0,color:At.all},{label:"爱情",val:parseInt(s.value.love)||0,color:At.love},{label:"工作",val:parseInt(s.value.work)||0,color:At.work},{label:"财运",val:parseInt(s.value.money)||0,color:At.money},{label:"健康",val:parseInt(s.value.health)||0,color:At.health}]:[]),r=ct(()=>s.value?.luckyColor||s.value?.luckyNum||s.value?.noble);return(i,l)=>(E(),H("div",Bl,[F("div",zl,W(M(t).icon)+" "+W(M(w).userZodiac)+"运势",1),F("div",ql,W(M(t).date),1),M(s)?(E(),H(te,{key:0},[(E(!0),H(te,null,is(n.value,o=>(E(),H("div",{class:"zodiac-bar",key:o.label},[F("span",Gl,W(o.label),1),F("div",Jl,[F("div",{class:"zodiac-bar-fill",style:lt({width:o.val+"%",background:o.color})},null,4)]),F("span",Zl,W(o.val)+"%",1)]))),128)),r.value?(E(),H("div",Yl,[M(s).luckyColor?(E(),H("span",Xl,"🎨 "+W(M(s).luckyColor),1)):U("",!0),M(s).luckyNum?(E(),H("span",Ql,"🔢 "+W(M(s).luckyNum),1)):U("",!0),M(s).noble?(E(),H("span",ec,"⭐ "+W(M(s).noble),1)):U("",!0)])):U("",!0),M(s).summary?(E(),H("div",tc,W(M(s).summary),1)):U("",!0)],64)):(E(),H("div",sc,"运势加载中..."))]))}}),Qr=Be(nc,[["__scopeId","data-v-d8a0edca"]]),rc={class:"knowledge-card"},ic={class:"knowledge-header"},oc={key:0,class:"knowledge-keyword-tag"},lc={key:0,class:"knowledge-body"},cc=["innerHTML"],fc={key:1,class:"knowledge-placeholder"},uc=ke({__name:"KnowledgeCard",setup(e){function t(){w.knowledge={...w.knowledge,content:"加载中..."},window.refreshKnowledge?.()}function s(){const l=document.querySelector(".knowledge-refresh-btn");if(!l)return;const o=l.getBoundingClientRect(),f=window.devicePixelRatio||1,d=8*f;window.setInteractiveRect?.(Math.round(o.left*f-d),Math.round(o.top*f-d),Math.round(o.right*f+d),Math.round(o.bottom*f+d))}function n(){window.setInteractiveRect?.(0,0,0,0)}ms(()=>{s(),window.addEventListener("resize",s)}),Wt(()=>{window.removeEventListener("resize",s),n()}),Fe(()=>w.cardVisibility.knowledge,l=>{l?Ns(s):n()}),Fe(()=>w.knowledge.content,()=>Ns(s));function r(l){let o=l;return o=o.replace(/```(\w*)\n?([\s\S]*?)```/g,"
$2
"),o=o.replace(/`([^`]+)`/g,"$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(/((?:
  • [\s\S]*?<\/li>\s*)+)/g,"
      $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 {
    diff --git a/win32.go b/win32.go index 5dab9f5..ae8cc9f 100644 --- a/win32.go +++ b/win32.go @@ -52,7 +52,7 @@ const ( const ( gwlStyle = uintptr(0xFFFFFFF0) // GWL_STYLE = -16 - gwlExStyle = uintptr(0xFFFFFFFEC) // GWL_EXSTYLE = -20 + gwlExStyle = ^uintptr(19) // GWL_EXSTYLE = -20 wsPopup = uintptr(0x80000000) wsVisible = uintptr(0x10000000) wsChild = uintptr(0x02000000)