Skip to content

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

10.1 KB
Raw Blame
// SiYuan - https://github.com/siyuan-note/siyuan
// Copyright (c) 2020-present, b3log.org
// SPDX-License-Identifier: AGPL-3.0-or-later

package model

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/88250/gulu"
	"github.com/siyuan-note/filelock"
	"github.com/siyuan-note/logging"
	"github.com/siyuan-note/siyuan/kernel/bazaar"
	"github.com/siyuan-note/siyuan/kernel/conf"
	"github.com/siyuan-note/siyuan/kernel/util"
)

func InitAppearance() {
	util.SetBootDetails(Conf.Language(302))
	if err := MigrateAppearancePackages(); err != nil {
		logging.LogErrorf("migrate appearance packages failed: %s", err)
		util.ReportFileSysFatalError(err)
		return
	}
	if err := os.Mkdir(util.AppearancePath, 0755); err != nil && !os.IsExist(err) {
		logging.LogErrorf("create appearance folder [%s] failed: %s", util.AppearancePath, err)
		util.ReportFileSysFatalError(err)
		return
	}

	from := filepath.Join(util.WorkingDir, "appearance")
	if err := filelock.CopyWritable(from, util.AppearancePath); err != nil {
		logging.LogErrorf("copy appearance resources from [%s] to [%s] failed: %s", from, util.AppearancePath, err)
		util.ReportFileSysFatalError(err)
		return
	}

	if err := util.CleanupLegacyFonts(util.AppearancePath); err != nil {
		logging.LogWarnf("clean up legacy fonts failed: %s", err)
	}

	refreshAppearanceConfig()
	util.InitEmojiChars()
}

// refreshAppearanceConfig 按完整可用的包刷新本机外观选择,缺失或不兼容时使用内置资源。
func refreshAppearanceConfig() {
	LoadThemes()
	LoadIcons()

	var reloadThemes, reloadIcons bool
	Conf.m.Lock()
	replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {
		if !containTheme(appearance.ThemeDark, appearance.DarkThemes) {
			appearance.ThemeDark = "midnight"
			reloadThemes = true
		}
		if !containTheme(appearance.ThemeLight, appearance.LightThemes) {
			appearance.ThemeLight = "daylight"
			reloadThemes = true
		}
		if !containIcon(appearance.Icon, appearance.Icons) {
			appearance.Icon = "litheness"
			reloadIcons = true
		}
		return reloadThemes || reloadIcons
	})
	Conf.m.Unlock()
	if reloadThemes {
		LoadThemes()
	}
	if reloadIcons {
		LoadIcons()
	}
	Conf.Save()
}

func SetIcon(icon string) error {
	Conf.m.Lock()
	defer Conf.m.Unlock()

	if !containIcon(icon, Conf.Appearance.Load().Icons) {
		return fmt.Errorf("icon [%s] not exists or not available", icon)
	}
	replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {
		appearance.Icon = icon
		return true
	})
	return nil
}

// SetTheme 校验全部参数后一次性替换外观配置段,任一参数无效时保持原配置不变。
func SetTheme(theme string, modes []int, appearanceMode string) (err error) {
	Conf.m.Lock()
	defer Conf.m.Unlock()

	replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {
		if theme != "" {
			for _, mode := range modes {
				switch mode {
				case 0:
					if !containTheme(theme, appearance.LightThemes) {
						err = fmt.Errorf("theme [%s] not exists or not available for light mode", theme)
						return false
					}
					appearance.ThemeLight = theme
				case 1:
					if !containTheme(theme, appearance.DarkThemes) {
						err = fmt.Errorf("theme [%s] not exists or not available for dark mode", theme)
						return false
					}
					appearance.ThemeDark = theme
				}
			}
		}

		if appearanceMode != "" {
			switch appearanceMode {
			case "light":
				appearance.ModeOS = false
				appearance.Mode = 0
			case "dark":
				appearance.ModeOS = false
				appearance.Mode = 1
			case "system":
				appearance.ModeOS = true
			default:
				err = fmt.Errorf("invalid appearance mode: %s", appearanceMode)
				return false
			}
		}
		return true
	})
	return
}

func containTheme(name string, themes []*conf.AppearanceTheme) bool {
	for _, t := range themes {
		if t != nil && t.Name == name {
			return true
		}
	}
	return false
}

func containIcon(name string, icons []*conf.AppearanceIcon) bool {
	for _, i := range icons {
		if i != nil && i.Name == name {
			return true
		}
	}
	return false
}

// appearancePackageNames 保留内置包,并从数据目录读取第三方包,避免同名包覆盖内置资源。
func appearancePackageNames(kind string) ([]string, error) {
	root, names := util.ThemesPath, []string{"daylight", "midnight"}
	if kind == "icons" {
		root, names = util.IconsPath, []string{"litheness"}
	}
	dirs, err := os.ReadDir(root)
	if os.IsNotExist(err) {
		return names, nil
	}
	if err != nil {
		return nil, err
	}
	for _, dir := range dirs {
		name := dir.Name()
		if !util.IsDirRegularOrSymlink(dir) || !bazaar.IsValidPackageName(name) ||
			(kind == "themes" && isBuiltInTheme(name)) || (kind == "icons" && isBuiltInIcon(name)) {
			continue
		}
		names = append(names, name)
	}
	return names, nil
}

func LoadThemes() {
	confAppearanceSnapshot := Conf.LoadAppearance()

	themeNames, err := appearancePackageNames("themes")
	if err != nil {
		logging.LogErrorf("read appearance themes folder failed: %s", err)
		util.ReportFileSysFatalError(err)
		return
	}

	var darkThemes, lightThemes []*conf.AppearanceTheme
	var daylightTheme, midnightTheme *conf.AppearanceTheme
	var themeVer string
	var themeJS bool
	mode := confAppearanceSnapshot.Mode
	themeLight := confAppearanceSnapshot.ThemeLight
	themeDark := confAppearanceSnapshot.ThemeDark
	for _, name := range themeNames {
		themePath := util.AppearancePackagePath("themes", name)
		themeConf, parseErr := bazaar.ParsePackageJSON(filepath.Join(themePath, "theme.json"))
		if nil != parseErr || !bazaar.IsValidInstalledPackage(themeConf, name) ||
			bazaar.IsBelowRequiredAppVersion(themeConf) || !gulu.File.IsExist(filepath.Join(themePath, "theme.css")) {
			continue
		}

		var modes []string
		if nil != themeConf.Modes {
			modes = *themeConf.Modes
		}
		for _, mode := range modes {
			t := &conf.AppearanceTheme{Name: name, Frontends: themeConf.Frontends}
			if isBuiltInTheme(name) {
				t.Label = name + Conf.Language(281)
			} else {
				t.Label = name
				if len(themeConf.DisplayName) > 0 {
					v := strings.TrimSpace(themeConf.DisplayName[util.Lang])
					if "" == v {
						v = strings.TrimSpace(themeConf.DisplayName["default"])
					}
					if "" != v && name != v {
						t.Label = v + " (" + name + ")"
					}
				}
			}

			if "midnight" == name {
				midnightTheme = t
				continue
			} else if "daylight" == name {
				daylightTheme = t
				continue
			}

			if "dark" == mode {
				darkThemes = append(darkThemes, t)
			} else if "light" == mode {
				lightThemes = append(lightThemes, t)
			}
		}

		if 0 == mode {
			if themeLight == name {
				themeVer = themeConf.Version
				themeJS = gulu.File.IsExist(filepath.Join(themePath, "theme.js"))
			}
		} else {
			if themeDark == name {
				themeVer = themeConf.Version
				themeJS = gulu.File.IsExist(filepath.Join(themePath, "theme.js"))
			}
		}
	}

	if daylightTheme != nil {
		lightThemes = append([]*conf.AppearanceTheme{daylightTheme}, lightThemes...)
	}
	if midnightTheme != nil {
		darkThemes = append([]*conf.AppearanceTheme{midnightTheme}, darkThemes...)
	}

	Conf.m.Lock()
	replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {
		appearance.DarkThemes = darkThemes
		appearance.LightThemes = lightThemes
		appearance.ThemeVer = themeVer
		appearance.ThemeJS = themeJS
		return true
	})
	Conf.m.Unlock()
}

func LoadIcons() {
	iconNames, err := appearancePackageNames("icons")
	if err != nil {
		logging.LogErrorf("read appearance icons folder failed: %s", err)
		util.ReportFileSysFatalError(err)
		return
	}

	var icons []*conf.AppearanceIcon
	var iconVer string
	currentIcon := Conf.Appearance.Load().Icon
	for _, name := range iconNames {
		iconPath := util.AppearancePackagePath("icons", name)
		iconConf, err := bazaar.ParsePackageJSON(filepath.Join(iconPath, "icon.json"))
		if err != nil || !bazaar.IsValidInstalledPackage(iconConf, name) ||
			bazaar.IsBelowRequiredAppVersion(iconConf) || !gulu.File.IsExist(filepath.Join(iconPath, "icon.js")) {
			continue
		}
		t := &conf.AppearanceIcon{Name: name}
		if isBuiltInIcon(name) {
			t.Label = name + Conf.Language(288)
		} else {
			t.Label = name
			if len(iconConf.DisplayName) > 0 {
				v := strings.TrimSpace(iconConf.DisplayName[util.Lang])
				if "" == v {
					v = strings.TrimSpace(iconConf.DisplayName["default"])
				}
				if "" != v && name != v {
					t.Label = v + " (" + name + ")"
				}
			}
		}
		icons = append(icons, t)
		if currentIcon == name {
			iconVer = iconConf.Version
		}
	}
	Conf.m.Lock()
	replaceConfSectionLocked(&Conf.Appearance, func(appearance *conf.Appearance) bool {
		appearance.Icons = icons
		appearance.IconVer = iconVer
		return true
	})
	Conf.m.Unlock()
}

func isCurrentUseTheme(themePath string) string {
	confAppearanceSnapshot := Conf.LoadAppearance()

	themeName := filepath.Base(filepath.Dir(themePath))
	if 0 == confAppearanceSnapshot.Mode { // 明亮
		if confAppearanceSnapshot.ThemeLight == themeName {
			return themeName
		}
	} else if 1 == confAppearanceSnapshot.Mode { // 暗黑
		if confAppearanceSnapshot.ThemeDark == themeName {
			return themeName
		}
	}
	return ""
}

func currentThemeDir() string {
	confAppearanceReadSnapshot := Conf.LoadAppearance()

	if nil == Conf {
		return ""
	}

	Conf.m.RLock()
	defer Conf.m.RUnlock()
	if nil == confAppearanceReadSnapshot {
		return ""
	}

	var themeName string
	switch confAppearanceReadSnapshot.Mode {
	case 0:
		themeName = confAppearanceReadSnapshot.ThemeLight
	case 1:
		themeName = confAppearanceReadSnapshot.ThemeDark
	default:
		return ""
	}
	if "" == themeName || "." == themeName || ".." == themeName || filepath.Base(themeName) != themeName {
		return ""
	}
	return util.AppearancePackagePath("themes", themeName)
}

func broadcastRefreshThemeIfCurrent(themeCssPath string) {
	if !strings.HasSuffix(themeCssPath, "theme.css") {
		return
	}
	// 只处理主题根目录中的 theme.css
	themeDir := filepath.Clean(filepath.Dir(themeCssPath))
	if themeDir != util.AppearancePackagePath("themes", filepath.Base(themeDir)) {
		return
	}
	themeName := isCurrentUseTheme(themeCssPath)
	if themeName == "" {
		return
	}
	util.BroadcastByType("main", "refreshtheme", 0, "", map[string]any{
		"theme": "/appearance/themes/" + themeName + "/theme.css?" + fmt.Sprintf("%d", time.Now().Unix()),
	})
}