Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve theme watcher to only watch the current theme https://github.com/siyuan-note/siyuan/issues/18668

Daniel5fd295dc5ebb
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index a67710b800..d78d4c8c7c 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -759,6 +759,7 @@ func setAppearance(c *gin.Context) {
util.Lang = model.Conf.Lang
model.Conf.Save()
model.InitAppearance()
+ model.WatchThemes()
ret.Data = model.Conf.Appearance
util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)
@@ -865,6 +866,7 @@ func setTheme(c *gin.Context) {
}
model.InitAppearance()
+ model.WatchThemes()
util.BroadcastByType("main", "setAppearance", 0, "", model.Conf.Appearance)
}
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 93f5876e9c..d3f84c0962 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -1204,6 +1204,7 @@ func setAppearanceMode(c *gin.Context) {
mode := int(arg["mode"].(float64))
model.Conf.Appearance.Mode = mode
model.LoadThemes()
+ model.WatchThemes()
model.Conf.Save()
ret.Data = map[string]any{
diff --git a/kernel/model/appearance.go b/kernel/model/appearance.go
index 7ebd1b539a..4a4916ee09 100644
--- a/kernel/model/appearance.go
+++ b/kernel/model/appearance.go
@@ -280,6 +280,32 @@ func isCurrentUseTheme(themePath string) string {
return ""
}
+func currentThemeDir() string {
+ if nil == Conf {
+ return ""
+ }
+
+ Conf.m.RLock()
+ defer Conf.m.RUnlock()
+ if nil == Conf.Appearance {
+ return ""
+ }
+
+ var themeName string
+ switch Conf.Appearance.Mode {
+ case 0:
+ themeName = Conf.Appearance.ThemeLight
+ case 1:
+ themeName = Conf.Appearance.ThemeDark
+ default:
+ return ""
+ }
+ if "" == themeName || "." == themeName || ".." == themeName || filepath.Base(themeName) != themeName {
+ return ""
+ }
+ return filepath.Clean(filepath.Join(util.ThemesPath, themeName))
+}
+
func broadcastRefreshThemeIfCurrent(themeCssPath string) {
if !strings.HasSuffix(themeCssPath, "theme.css") {
return
diff --git a/kernel/model/themes_watcher.go b/kernel/model/themes_watcher.go
index 2cb43762b8..817af0ccff 100644
--- a/kernel/model/themes_watcher.go
+++ b/kernel/model/themes_watcher.go
@@ -19,8 +19,10 @@
package model
import (
+ "errors"
"os"
"path/filepath"
+ "sync"
"time"
"github.com/88250/gulu"
@@ -29,22 +31,26 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-var themesWatcher *fsnotify.Watcher
+var (
+ themesWatcher *fsnotify.Watcher
+ themesWatcherMu sync.Mutex
+ themesWatchThemeDir string
+)
func WatchThemes() {
if util.IsMobileContainer() {
return
}
- go watchThemes()
-}
+ themesWatcherMu.Lock()
+ defer themesWatcherMu.Unlock()
+ if nil != themesWatcher {
+ updateThemesWatchThemeDir(themesWatcher)
+ return
+ }
-func watchThemes() {
- CloseWatchThemes()
themesDir := util.ThemesPath
-
- var err error
- themesWatcher, err = fsnotify.NewWatcher()
+ w, err := fsnotify.NewWatcher()
if err != nil {
logging.LogErrorf("add themes watcher for folder [%s] failed: %s", themesDir, err)
return
@@ -54,44 +60,42 @@ func watchThemes() {
os.MkdirAll(themesDir, 0755)
}
- if err = themesWatcher.Add(themesDir); err != nil {
+ if err = w.Add(themesDir); err != nil {
logging.LogErrorf("add themes root watcher for folder [%s] failed: %s", themesDir, err)
- CloseWatchThemes()
+ w.Close()
return
}
- // 为每个子目录添加监听,以便收到 theme.css 的变更
- addThemesSubdirs(themesWatcher, themesDir)
+ themesWatcher = w
+ updateThemesWatchThemeDir(w)
- go func() {
+ go func(w *fsnotify.Watcher) {
defer logging.Recover()
- var (
- timer *time.Timer
- lastEvent fsnotify.Event
- )
- timer = time.NewTimer(100 * time.Millisecond)
- <-timer.C // timer should be expired at first
+ timer := time.NewTimer(time.Hour)
+ if !timer.Stop() {
+ <-timer.C
+ }
+ defer timer.Stop()
+ var lastEvent fsnotify.Event
for {
select {
- case event, ok := <-themesWatcher.Events:
+ case event, ok := <-w.Events:
if !ok {
return
}
- // 新目录创建时加入监听
if event.Op&fsnotify.Create == fsnotify.Create {
- if isThemesDirectSubdir(event.Name) {
- if addErr := themesWatcher.Add(event.Name); addErr != nil {
- logging.LogWarnf("add themes watcher for new folder [%s] failed: %s", event.Name, addErr)
- }
- }
+ addThemesWatchThemeDir(w, event.Name)
+ }
+ if event.Op&fsnotify.Write != fsnotify.Write {
+ continue
}
lastEvent = event
timer.Reset(time.Millisecond * 100)
- case err, ok := <-themesWatcher.Errors:
+ case err, ok := <-w.Errors:
if !ok {
return
}
@@ -100,50 +104,37 @@ func watchThemes() {
handleThemesEvent(lastEvent)
}
}
- }()
+ }(w)
}
-// addThemesSubdirs 为 themes 下每个子目录添加监听
-func addThemesSubdirs(w *fsnotify.Watcher, themesDir string) {
- entries, err := os.ReadDir(themesDir)
- if err != nil {
- logging.LogErrorf("read themes folder failed: %s", err)
+func updateThemesWatchThemeDir(w *fsnotify.Watcher) {
+ themeDir := currentThemeDir()
+ if themeDir == themesWatchThemeDir {
return
}
- for _, e := range entries {
- if !util.IsDirRegularOrSymlink(e) {
- continue
+
+ if "" != themeDir && gulu.File.IsDir(themeDir) {
+ if err := w.Add(themeDir); err != nil {
+ logging.LogWarnf("add themes watcher for folder [%s] failed: %s", themeDir, err)
}
- subdir := filepath.Join(themesDir, e.Name())
- if addErr := w.Add(subdir); addErr != nil {
- logging.LogWarnf("add themes watcher for folder [%s] failed: %s", subdir, addErr)
+ }
+ if "" != themesWatchThemeDir {
+ if err := w.Remove(themesWatchThemeDir); err != nil && !errors.Is(err, fsnotify.ErrNonExistentWatch) {
+ logging.LogWarnf("remove themes watcher for folder [%s] failed: %s", themesWatchThemeDir, err)
}
}
+ themesWatchThemeDir = themeDir
}
-// isThemesDirectSubdir 判断 path 是否为 themes 下的直接子目录
-func isThemesDirectSubdir(path string) bool {
- if !gulu.File.IsDir(path) {
- return false
- }
- rel, err := filepath.Rel(util.ThemesPath, path)
- if err != nil {
- return false
- }
- if filepath.Base(path) != rel {
- return false
- }
- entries, err := os.ReadDir(util.ThemesPath)
- if err != nil {
- return false
+func addThemesWatchThemeDir(w *fsnotify.Watcher, path string) {
+ themesWatcherMu.Lock()
+ defer themesWatcherMu.Unlock()
+ if themesWatcher != w || filepath.Clean(path) != themesWatchThemeDir || !gulu.File.IsDir(path) {
+ return
}
- name := filepath.Base(path)
- for _, e := range entries {
- if e.Name() == name {
- return util.IsDirRegularOrSymlink(e)
- }
+ if err := w.Add(path); err != nil {
+ logging.LogWarnf("add themes watcher for new folder [%s] failed: %s", path, err)
}
- return false
}
func handleThemesEvent(event fsnotify.Event) {
@@ -154,8 +145,13 @@ func handleThemesEvent(event fsnotify.Event) {
}
func CloseWatchThemes() {
- if nil != themesWatcher {
- themesWatcher.Close()
- themesWatcher = nil
+ themesWatcherMu.Lock()
+ w := themesWatcher
+ themesWatcher = nil
+ themesWatchThemeDir = ""
+ themesWatcherMu.Unlock()
+
+ if nil != w {
+ w.Close()
}
}
diff --git a/kernel/model/themes_watcher_darwin.go b/kernel/model/themes_watcher_darwin.go
index 1abd93936f..d93bdb1b48 100644
--- a/kernel/model/themes_watcher_darwin.go
+++ b/kernel/model/themes_watcher_darwin.go
@@ -22,6 +22,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"time"
"github.com/88250/gulu"
@@ -30,112 +31,101 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-var themesWatcher *watcher.Watcher
+var (
+ themesWatcher *watcher.Watcher
+ themesWatcherMu sync.Mutex
+ themesWatchThemeDir string
+)
func WatchThemes() {
if util.IsMobileContainer() {
return
}
- go watchThemes()
-}
+ themesWatcherMu.Lock()
+ defer themesWatcherMu.Unlock()
+ if nil != themesWatcher {
+ updateThemesWatchThemeDir(themesWatcher)
+ return
+ }
-func watchThemes() {
- CloseWatchThemes()
themesDir := util.ThemesPath
-
- themesWatcher = watcher.New()
+ w := watcher.New()
if !gulu.File.IsDir(themesDir) {
os.MkdirAll(themesDir, 0755)
}
- if err := themesWatcher.Add(themesDir); err != nil {
+ if err := w.Add(themesDir); err != nil {
logging.LogErrorf("add themes watcher for folder [%s] failed: %s", themesDir, err)
return
}
- // 为每个子目录添加监听,以便收到 theme.css 的变更
- addThemesSubdirs(themesWatcher, themesDir)
+ themesWatcher = w
+ updateThemesWatchThemeDir(w)
- go func() {
+ go func(w *watcher.Watcher) {
defer logging.Recover()
for {
select {
- case event, ok := <-themesWatcher.Event:
+ case event, ok := <-w.Event:
if !ok {
return
}
- // 新目录创建时加入监听
if watcher.Create == event.Op {
- if isThemesDirectSubdir(event.Path) {
- if addErr := themesWatcher.Add(event.Path); addErr != nil {
- logging.LogWarnf("add themes watcher for new folder [%s] failed: %s", event.Path, addErr)
- }
- }
+ addThemesWatchThemeDir(w, event.Path)
}
handleThemesEvent(event)
- case err, ok := <-themesWatcher.Error:
+ case err, ok := <-w.Error:
if !ok {
return
}
logging.LogErrorf("watch themes failed: %s", err)
- case <-themesWatcher.Closed:
+ case <-w.Closed:
return
}
}
- }()
+ }(w)
- if err := themesWatcher.Start(10 * time.Second); err != nil {
- logging.LogErrorf("start themes watcher for folder [%s] failed: %s", themesDir, err)
- return
- }
+ go func() {
+ if err := w.Start(10 * time.Second); err != nil {
+ logging.LogErrorf("start themes watcher for folder [%s] failed: %s", themesDir, err)
+ }
+ }()
+ w.Wait()
}
-// addThemesSubdirs 为 themes 下每个子目录添加监听
-func addThemesSubdirs(w *watcher.Watcher, themesDir string) {
- entries, err := os.ReadDir(themesDir)
- if err != nil {
- logging.LogErrorf("read themes folder failed: %s", err)
+func updateThemesWatchThemeDir(w *watcher.Watcher) {
+ themeDir := currentThemeDir()
+ if themeDir == themesWatchThemeDir {
return
}
- for _, e := range entries {
- if !util.IsDirRegularOrSymlink(e) {
- continue
+
+ if "" != themeDir && gulu.File.IsDir(themeDir) {
+ if err := w.Add(themeDir); err != nil {
+ logging.LogWarnf("add themes watcher for folder [%s] failed: %s", themeDir, err)
}
- subdir := filepath.Join(themesDir, e.Name())
- if addErr := w.Add(subdir); addErr != nil {
- logging.LogWarnf("add themes watcher for folder [%s] failed: %s", subdir, addErr)
+ }
+ if "" != themesWatchThemeDir {
+ if err := w.Remove(themesWatchThemeDir); err != nil {
+ logging.LogWarnf("remove themes watcher for folder [%s] failed: %s", themesWatchThemeDir, err)
}
}
+ themesWatchThemeDir = themeDir
}
-// isThemesDirectSubdir 判断 path 是否为 themes 下的直接子目录
-func isThemesDirectSubdir(path string) bool {
- if !gulu.File.IsDir(path) {
- return false
- }
- rel, err := filepath.Rel(util.ThemesPath, path)
- if err != nil {
- return false
- }
- if filepath.Base(path) != rel {
- return false
+func addThemesWatchThemeDir(w *watcher.Watcher, path string) {
+ themesWatcherMu.Lock()
+ defer themesWatcherMu.Unlock()
+ if themesWatcher != w || filepath.Clean(path) != themesWatchThemeDir || !gulu.File.IsDir(path) {
+ return
}
- entries, err := os.ReadDir(util.ThemesPath)
- if err != nil {
- return false
+ if err := w.Add(path); err != nil {
+ logging.LogWarnf("add themes watcher for new folder [%s] failed: %s", path, err)
}
- name := filepath.Base(path)
- for _, e := range entries {
- if e.Name() == name {
- return util.IsDirRegularOrSymlink(e)
- }
- }
- return false
}
func handleThemesEvent(event watcher.Event) {
@@ -149,8 +139,13 @@ func handleThemesEvent(event watcher.Event) {
}
func CloseWatchThemes() {
- if nil != themesWatcher {
- themesWatcher.Close()
- themesWatcher = nil
+ themesWatcherMu.Lock()
+ w := themesWatcher
+ themesWatcher = nil
+ themesWatchThemeDir = ""
+ themesWatcherMu.Unlock()
+
+ if nil != w {
+ w.Close()
}
}
diff --git a/kernel/model/themes_watcher_test.go b/kernel/model/themes_watcher_test.go
new file mode 100644
index 0000000000..530eaecfb3
--- /dev/null
+++ b/kernel/model/themes_watcher_test.go
@@ -0,0 +1,88 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+//go:build !darwin
+
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestWatchThemesCurrentThemeOnly(t *testing.T) {
+ originalConf, originalThemesPath := Conf, util.ThemesPath
+ t.Cleanup(func() {
+ CloseWatchThemes()
+ Conf = originalConf
+ util.ThemesPath = originalThemesPath
+ })
+
+ themesDir := t.TempDir()
+ for _, name := range []string{"daylight", "midnight", "unused"} {
+ if err := os.Mkdir(filepath.Join(themesDir, name), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.Appearance = conf.NewAppearance()
+ util.ThemesPath = themesDir
+
+ WatchThemes()
+ assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "daylight"))
+
+ Conf.m.Lock()
+ Conf.Appearance.Mode = 1
+ Conf.m.Unlock()
+ WatchThemes()
+ assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "midnight"))
+
+ Conf.m.Lock()
+ Conf.Appearance.Mode = -1
+ Conf.m.Unlock()
+ WatchThemes()
+ assertThemesWatchList(t, themesDir)
+
+ Conf.m.Lock()
+ Conf.Appearance.Mode = 0
+ Conf.Appearance.ThemeLight = ".."
+ Conf.m.Unlock()
+ WatchThemes()
+ assertThemesWatchList(t, themesDir)
+}
+
+func assertThemesWatchList(t *testing.T, expected ...string) {
+ t.Helper()
+ if nil == themesWatcher {
+ t.Fatal("themes watcher is not initialized")
+ }
+ actual := map[string]bool{}
+ for _, path := range themesWatcher.WatchList() {
+ actual[filepath.Clean(path)] = true
+ }
+ if len(actual) != len(expected) {
+ t.Fatalf("unexpected themes watch list: %v", actual)
+ }
+ for _, path := range expected {
+ if !actual[filepath.Clean(path)] {
+ t.Fatalf("themes watcher does not contain [%s]: %v", path, actual)
+ }
+ }
+}