mirror of
https://github.com/xiaoqidun/ofdgo.git
synced 2026-10-30 14:18:04 +08:00
1 parent
385d7aa531
commit
8d435fe109
11 files changed
+648
-188
No files matched your search
@@ -18,10 +18,10 @@ import "embed"
|
||||
|
||||
// FS WebUI嵌入静态文件
|
||||
//
|
||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_util.js ofdgo_view.js ofdgo_wasm.js ofdgo_work.js wasm_exec.js
|
||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_theme.js ofdgo_util.js ofdgo_view.js ofdgo_wasm.js ofdgo_work.js wasm_exec.js
|
||||
var FS embed.FS
|
||||
|
||||
// NativeFS WebView嵌入静态文件
|
||||
//
|
||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_util.js ofdgo_view.js
|
||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_theme.js ofdgo_util.js ofdgo_view.js
|
||||
var NativeFS embed.FS
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="manifest" href="./ofdgo.json">
|
||||
<link rel="icon" type="image/x-icon" sizes="16x16 32x32 48x48 64x64 128x128 256x256" href="./ofdgo.ico">
|
||||
<link rel="icon" type="image/svg+xml" href="./ofdgo.svg">
|
||||
<script src="./ofdgo_theme.js"></script>
|
||||
<link rel="stylesheet" href="./ofdgo.css">
|
||||
</head>
|
||||
<body>
|
||||
@@ -16,6 +17,7 @@
|
||||
<div id="documentTabs" class="document-tabs"></div>
|
||||
<button id="documentNewTab" class="document-new-tab" type="button" title="新建"><span class="new-icon"></span></button>
|
||||
<div class="document-title-drag"></div>
|
||||
<button id="appearanceButton" class="app-appearance" type="button" title="设置"><span class="settings-icon"></span></button>
|
||||
<button id="refreshAppButton" class="app-update" type="button" title="更新" hidden><span class="update-icon"></span></button>
|
||||
</div>
|
||||
<header class="toolbar-frame">
|
||||
@@ -450,6 +452,17 @@
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<dialog id="appearancePanel" class="form-dialog appearance-dialog">
|
||||
<form method="dialog">
|
||||
<div class="appearance-heading"><h2 id="appearanceTitle" class="form-title">设置</h2><button class="appearance-close" type="submit" title="关闭"><span class="close-icon"></span></button></div>
|
||||
<div class="appearance-label">外观主题</div>
|
||||
<div class="appearance-themes">
|
||||
<button type="button" data-theme-choice="system"><span class="theme-system-icon"></span><span>系统</span></button>
|
||||
<button type="button" data-theme-choice="light"><span class="theme-light-icon"></span><span>浅色</span></button>
|
||||
<button type="button" data-theme-choice="dark"><span class="theme-dark-icon"></span><span>深色</span></button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<dialog id="settingsPanel" class="form-dialog settings-dialog">
|
||||
<form id="settingsForm">
|
||||
<header class="settings-header">
|
||||
|
||||
+401
-155
File diff suppressed because it is too large.
Load diff
+13
-6
@@ -192,6 +192,8 @@ function createDocumentState() {
|
||||
let state = createDocumentState();
|
||||
|
||||
const el = {
|
||||
appearanceButton: document.querySelector("#appearanceButton"),
|
||||
appearancePanel: document.querySelector("#appearancePanel"),
|
||||
printButton: document.querySelector("#printButton"),
|
||||
printPanel: document.querySelector("#printPanel"),
|
||||
documentTitleBar: document.querySelector("#documentTitleBar"),
|
||||
@@ -711,8 +713,8 @@ const annotationFields = Object.fromEntries(["CreateForm", "CreateCancel", "Cont
|
||||
el.editorTools.addEventListener("scroll", () => fontPicker.position());
|
||||
|
||||
const canvasEditor = new CanvasEditor(el.viewerPanel, {
|
||||
textControls: [el.textAlign, el.textFont, el.textFontToggle, el.textFontAdd, el.textFontList, el.textSize, el.textColor, el.textLineHeight, el.textSpacing, el.textWrap, el.paragraphButton, el.paragraphPanel, textBackground, ...textFormatButtons, el.undoButton, el.redoButton, el.saveButton, el.saveAsButton, el.fontInput, document.querySelector("#textReflow")],
|
||||
keepTextFocus: () => fontPicker.open || el.closePanel.open || el.paragraphPanel.open || canvasEditor.input?.fontDialog,
|
||||
textControls: [el.appearanceButton, el.appearancePanel, el.textAlign, el.textFont, el.textFontToggle, el.textFontAdd, el.textFontList, el.textSize, el.textColor, el.textLineHeight, el.textSpacing, el.textWrap, el.paragraphButton, el.paragraphPanel, textBackground, ...textFormatButtons, el.undoButton, el.redoButton, el.saveButton, el.saveAsButton, el.fontInput, document.querySelector("#textReflow")],
|
||||
keepTextFocus: () => el.appearancePanel.open || fontPicker.open || el.closePanel.open || el.paragraphPanel.open || canvasEditor.input?.fontDialog,
|
||||
prepareTextCommit: flushEditorInputs,
|
||||
onTextFormat: changeRangeFormat,
|
||||
onRichInput: ensureRichInput,
|
||||
@@ -2086,7 +2088,7 @@ function handleKeyDown(event) {
|
||||
|
||||
function formDialogOpen() {
|
||||
if (documentTab().print?.context) return true;
|
||||
return Boolean(sealPreview || resourceManager.pick) || el.aboutPanel.open || el.closePanel.open || el.attachmentDialog.open || settingsElements.Panel.open || fontBindingElements.Panel.open || el.signPanel.open || el.verifyPanel.open || el.credentialsPanel.open || el.encryptionPanel.open || batchElements.Panel.open || el.exportPanel.open || el.createPanel.open || el.insertPanel.open || el.pagePanel.open || el.paragraphPanel.open || el.importPanel.open || el.infoPanel.open || el.documentPanel.open
|
||||
return el.appearancePanel.open || Boolean(sealPreview || resourceManager.pick) || el.aboutPanel.open || el.closePanel.open || el.attachmentDialog.open || settingsElements.Panel.open || fontBindingElements.Panel.open || el.signPanel.open || el.verifyPanel.open || el.credentialsPanel.open || el.encryptionPanel.open || batchElements.Panel.open || el.exportPanel.open || el.createPanel.open || el.insertPanel.open || el.pagePanel.open || el.paragraphPanel.open || el.importPanel.open || el.infoPanel.open || el.documentPanel.open
|
||||
|| resourceElements.Panel.open || el.structureDialog.open || el.versionPanel.open || el.batchPagesPanel.open || el.objectStylePanel.open || el.outlinePanel.open || el.objectBoundsPanel.open || el.annotationNote.open || el.annotationCreate.open || el.objectPicker.open;
|
||||
}
|
||||
|
||||
@@ -2638,9 +2640,6 @@ function applyTitleBarInfo(info) {
|
||||
document.body.style.setProperty("--titlebar-height", `${info.height}px`);
|
||||
el.documentTitleBar.style.setProperty("--titlebar-left", `${info.left}px`);
|
||||
el.documentTitleBar.style.setProperty("--titlebar-right", `${info.right}px`);
|
||||
for (const [name, value] of Object.entries(info.colors || {})) {
|
||||
if (value) el.documentTitleBar.style.setProperty(`--titlebar-${name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)}`, value);
|
||||
}
|
||||
el.documentTitleBar.dataset.active = String(info.active);
|
||||
el.documentTitleBar.dataset.maximized = String(info.maximized);
|
||||
revealPanelTab(el.documentTabs);
|
||||
@@ -5502,6 +5501,14 @@ function resizeViewer() {
|
||||
}
|
||||
|
||||
async function boot() {
|
||||
window.ofdgoTheme.connect(nativeHost, error => showError(error, false));
|
||||
el.appearanceButton.addEventListener("click", () => {
|
||||
const bounds = el.appearanceButton.getBoundingClientRect();
|
||||
el.appearancePanel.style.setProperty("--appearance-top", `${bounds.bottom + 4}px`);
|
||||
el.appearancePanel.style.setProperty("--appearance-right", `${Math.max(12, innerWidth - bounds.right)}px`);
|
||||
documentDialogs.showApplication(el.appearancePanel);
|
||||
});
|
||||
for (const button of el.appearancePanel.querySelectorAll("[data-theme-choice]")) button.addEventListener("click", () => window.ofdgoTheme.set(button.dataset.themeChoice));
|
||||
documentDialogs = new DocumentDialogs({document, titlebar: el.documentTitleBar,
|
||||
targets: () => [...document.body.children].filter(node => node !== el.documentTitleBar)});
|
||||
for (const panel of document.querySelectorAll("dialog.form-dialog")) if (panel !== el.printPanel) documentDialogs.register(panel, {persistent: panel === batchElements.Panel});
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
(() => {
|
||||
const root = document.documentElement;
|
||||
const preference = matchMedia("(prefers-color-scheme: dark)");
|
||||
const key = "ofdgo.theme";
|
||||
let mode = root.dataset.themeMode || "system";
|
||||
let host = null, report = null, pending = Promise.resolve();
|
||||
if (!root.dataset.themeMode) {
|
||||
try { mode = localStorage.getItem(key) || "system"; } catch {}
|
||||
}
|
||||
if (!["system", "light", "dark"].includes(mode)) mode = "system";
|
||||
function apply() {
|
||||
root.dataset.themeMode = mode;
|
||||
root.dataset.theme = mode === "system" ? preference.matches ? "dark" : "light" : mode;
|
||||
document.querySelector('meta[name="theme-color"]').content = root.dataset.theme === "dark" ? "#272e33" : "#fafbfc";
|
||||
for (const button of document.querySelectorAll("[data-theme-choice]")) button.dataset.pressed = String(button.dataset.themeChoice === mode);
|
||||
}
|
||||
function sync() {
|
||||
if (!host) return;
|
||||
const value = {mode, dark: root.dataset.theme === "dark"};
|
||||
pending = pending.then(() => host.call("appearance", value)).catch(error => report(error));
|
||||
}
|
||||
function set(value) {
|
||||
mode = value;
|
||||
apply();
|
||||
if (!host) {
|
||||
try { localStorage.setItem(key, mode); } catch {}
|
||||
}
|
||||
sync();
|
||||
}
|
||||
preference.addEventListener("change", () => {
|
||||
if (mode !== "system") return;
|
||||
apply();
|
||||
sync();
|
||||
});
|
||||
window.addEventListener("storage", event => {
|
||||
if (host || event.key !== key && event.key !== null) return;
|
||||
mode = ["light", "dark"].includes(event.newValue) ? event.newValue : "system";
|
||||
apply();
|
||||
});
|
||||
window.ofdgoTheme = {set, connect(value, onError) { host = value; report = onError; apply(); sync(); }};
|
||||
apply();
|
||||
})();
|
||||
@@ -4,7 +4,7 @@ export class DocumentDialogs {
|
||||
this.backdrop = root.createElement("div");
|
||||
this.backdrop.className = "document-dialog-backdrop";
|
||||
this.backdrop.hidden = true;
|
||||
Object.assign(this.backdrop.style, { position: "fixed", inset: "0", background: "rgb(31 36 40 / 18%)", zIndex: "1000" });
|
||||
Object.assign(this.backdrop.style, { position: "fixed", inset: "0", background: "var(--backdrop)", zIndex: "1000" });
|
||||
root.body.append(this.backdrop);
|
||||
root.addEventListener("keydown", event => {
|
||||
if (event.defaultPrevented || this.applicationOpen()) return;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const CACHE_PREFIX = `ofdgo:${self.registration.scope}:app:`;
|
||||
const META_CACHE = `${CACHE_PREFIX}meta`;
|
||||
const ASSETS = ["./", "ofdgo.css", "ofdgo.ico", "ofdgo.js", "ofdgo.json", "ofdgo.png", "ofdgo.svg", "ofdgo.wasm", "ofdgo_edit.js", "ofdgo_font.js", "ofdgo_host.js", "ofdgo_print.js", "ofdgo_util.js", "ofdgo_view.js", "ofdgo_wasm.js", "ofdgo_work.js", "wasm_exec.js"]
|
||||
const ASSETS = ["./", "ofdgo.css", "ofdgo.ico", "ofdgo.js", "ofdgo.json", "ofdgo.png", "ofdgo.svg", "ofdgo.wasm", "ofdgo_edit.js", "ofdgo_font.js", "ofdgo_host.js", "ofdgo_print.js", "ofdgo_theme.js", "ofdgo_util.js", "ofdgo_view.js", "ofdgo_wasm.js", "ofdgo_work.js", "wasm_exec.js"]
|
||||
.map((path) => new URL(path, self.registration.scope).href);
|
||||
const CLIENT_PREFIX = new URL("__client/", self.registration.scope).href;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ require (
|
||||
github.com/go-text/typesetting v0.3.5
|
||||
github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c
|
||||
github.com/tdewolff/font v0.0.0-20261010204837-88a7f6b56918
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261026011429-36a970cd3fb6
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261030035206-e08505cc8719
|
||||
github.com/xiaoqidun/j2kgo v1.0.2
|
||||
github.com/xiaoqidun/jbig2 v1.1.8
|
||||
github.com/xiaoqidun/pdfgo v0.0.0-20261026125713-90454771d5d0
|
||||
|
||||
@@ -60,8 +60,8 @@ github.com/tdewolff/parse/v2 v2.8.16 h1:bLk5svUOQRkW/Y2SJ+DeENSIkZBcTIkq+Atyv5D8
|
||||
github.com/tdewolff/parse/v2 v2.8.16/go.mod h1:XdsoSFThlVIRIajAuqz1evNY7bagZS8LBOPA3aVopwQ=
|
||||
github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk=
|
||||
github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261026011429-36a970cd3fb6 h1:JqOQToWYKqyoIcvNx5MYfrdiuApjpBDnUjMHD7sCF6c=
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261026011429-36a970cd3fb6/go.mod h1:bXz+dPMVntPIVwePTTuMXt8Q0z1YoUGuROQSsXyUEfY=
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261030035206-e08505cc8719 h1:zTVHOkCXfL90vTCNEkKT95noDMTJ2QiA1SWbTcZb2ys=
|
||||
github.com/xiaoqidun/guigo v0.0.0-20261030035206-e08505cc8719/go.mod h1:bXz+dPMVntPIVwePTTuMXt8Q0z1YoUGuROQSsXyUEfY=
|
||||
github.com/xiaoqidun/j2kgo v1.0.2 h1:OAjjEOfaBaQzBNcj9wx+eM68UI5pewR6SzNZa1R1DIw=
|
||||
github.com/xiaoqidun/j2kgo v1.0.2/go.mod h1:DCwAfuDzCDYqUiAlZ7BDwigTjaXw7o9L1FtEma/D1aA=
|
||||
github.com/xiaoqidun/jbig2 v1.1.8 h1:dERPW7F8gs18a/DOD9gXHR3fP1Vl6KhCNsLnq5l3BIo=
|
||||
|
||||
+42
-20
@@ -48,6 +48,9 @@ const applicationDownloadURL = "https://ofdgo.aite.me/releases/"
|
||||
|
||||
// Host 连接桌面系统能力和共用文档业务
|
||||
type Host struct {
|
||||
themeMu sync.Mutex
|
||||
theme applicationTheme
|
||||
themePath string
|
||||
mu sync.Mutex
|
||||
window *guigo.Window
|
||||
files *fileStore
|
||||
@@ -104,7 +107,11 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
h := &Host{pendingPaths: paths}
|
||||
h := &Host{pendingPaths: paths, themePath: filepath.Join(options.UserDataDir, "appearance.json")}
|
||||
if err := h.loadTheme(); err != nil {
|
||||
return err
|
||||
}
|
||||
options.TitleBarColors = themeColors(h.theme.Dark)
|
||||
data, err := json.Marshal(paths)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -142,7 +149,7 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
||||
h.conversionPool = h.resources.ConversionPool()
|
||||
defer h.close()
|
||||
bindings := make(map[string]guigo.HandlerFunc)
|
||||
for _, name := range []string{"engine.open", "engine.close", "engine.call", "engine.start", "engine.cancel", "engine.finish", "batch", "open", "save", "directory", "file", "release", "drop.release", "child", "remove", "write.begin", "write.data", "write.commit", "write.abort", "fonts", "ready", "launch.done", "title", "window.info", "window.drag", "window.close", "update.check", "update.open", "association.query", "association.register", "association.remove", "print.capabilities", "print.dialog", "print.printers", "print.query", "print.properties", "print"} {
|
||||
for _, name := range []string{"engine.open", "engine.close", "engine.call", "engine.start", "engine.cancel", "engine.finish", "batch", "open", "save", "directory", "file", "release", "drop.release", "child", "remove", "write.begin", "write.data", "write.commit", "write.abort", "fonts", "ready", "launch.done", "title", "window.info", "window.drag", "window.close", "appearance", "update.check", "update.open", "association.query", "association.register", "association.remove", "print.capabilities", "print.dialog", "print.printers", "print.query", "print.properties", "print"} {
|
||||
bindings["ofdgo.host."+name] = func(ctx context.Context, args any) (any, error) { return h.call(ctx, name, args) }
|
||||
}
|
||||
static := http.FileServerFS(webuiassets.NativeFS)
|
||||
@@ -155,6 +162,18 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
|
||||
data, err := h.themeIndex()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("X-OFDGo-Build-Version", build.Version)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(data)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-OFDGo-Build-Version", build.Version)
|
||||
static.ServeHTTP(w, r)
|
||||
@@ -237,7 +256,13 @@ func (h *Host) resource(r *http.Request) (*guigo.Resource, error) {
|
||||
if name == "" {
|
||||
name = "index.html"
|
||||
}
|
||||
data, err := webuiassets.NativeFS.ReadFile(name)
|
||||
var data []byte
|
||||
var err error
|
||||
if name == "index.html" {
|
||||
data, err = h.themeIndex()
|
||||
} else {
|
||||
data, err = webuiassets.NativeFS.ReadFile(name)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -411,6 +436,8 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
||||
text := func(key string) string { value, _ := args[key].(string); return value }
|
||||
flag := func(key string) bool { value, _ := args[key].(bool); return value }
|
||||
switch name {
|
||||
case "appearance":
|
||||
return nil, h.setTheme(applicationTheme{Mode: text("mode"), Dark: flag("dark")})
|
||||
case "print.capabilities", "print.dialog", "print.printers", "print.query", "print.properties", "print":
|
||||
h.mu.Lock()
|
||||
window := h.window
|
||||
@@ -1186,22 +1213,17 @@ func windowOptions(dataDir string) (guigo.Options, error) {
|
||||
return guigo.Options{}, err
|
||||
}
|
||||
return guigo.Options{
|
||||
AppID: appID,
|
||||
Title: "OFDGo - OFD编辑器",
|
||||
TitleBar: guigo.TitleBarContent,
|
||||
TitleBarColors: guigo.TitleBarColors{
|
||||
Background: "#e8edf0",
|
||||
Foreground: "#1f2428",
|
||||
InactiveBackground: "#eef1f4",
|
||||
InactiveForeground: "#66737f",
|
||||
},
|
||||
Icon: icon,
|
||||
Width: 1440,
|
||||
Height: 900,
|
||||
MinWidth: 360,
|
||||
MinHeight: 240,
|
||||
Center: true,
|
||||
Maximized: true,
|
||||
UserDataDir: dataDir,
|
||||
AppID: appID,
|
||||
Title: "OFDGo - OFD编辑器",
|
||||
TitleBar: guigo.TitleBarContent,
|
||||
TitleBarColors: themeColors(false),
|
||||
Icon: icon,
|
||||
Width: 1440,
|
||||
Height: 900,
|
||||
MinWidth: 360,
|
||||
MinHeight: 240,
|
||||
Center: true,
|
||||
Maximized: true,
|
||||
UserDataDir: dataDir,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !js || !wasm
|
||||
|
||||
package webview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/xiaoqidun/guigo"
|
||||
webuiassets "github.com/xiaoqidun/ofdgo/assets/webui"
|
||||
)
|
||||
|
||||
// applicationTheme 保存应用主题偏好及最后一次解析的系统外观
|
||||
type applicationTheme struct {
|
||||
Mode string `json:"mode"`
|
||||
Dark bool `json:"dark"`
|
||||
}
|
||||
|
||||
// themeColors 返回应用对应外观的原生标题栏配色
|
||||
// 入参: dark 是否使用深色
|
||||
// 返回: guigo.TitleBarColors 标题栏配色
|
||||
func themeColors(dark bool) guigo.TitleBarColors {
|
||||
if dark {
|
||||
return guigo.TitleBarColors{Background: "#20272b", Foreground: "#e0e7eb", InactiveBackground: "#242b30", InactiveForeground: "#9aa8b1"}
|
||||
}
|
||||
return guigo.TitleBarColors{Background: "#e8edee", Foreground: "#263238", InactiveBackground: "#eef1f3", InactiveForeground: "#728087"}
|
||||
}
|
||||
|
||||
// loadTheme 在创建窗口前读取用户目录中的主题偏好
|
||||
// 返回: error 读取或解析错误
|
||||
func (h *Host) loadTheme() error {
|
||||
h.theme = applicationTheme{Mode: "system"}
|
||||
data, err := os.ReadFile(h.themePath)
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(data, &h.theme); err != nil {
|
||||
return err
|
||||
}
|
||||
return h.theme.validate()
|
||||
}
|
||||
|
||||
// validate 检查应用主题及解析后的配色是否一致
|
||||
// 返回: error 偏好错误
|
||||
func (a applicationTheme) validate() error {
|
||||
if a.Mode != "system" && a.Mode != "light" && a.Mode != "dark" {
|
||||
return fmt.Errorf("主题无效")
|
||||
}
|
||||
if a.Mode == "light" && a.Dark || a.Mode == "dark" && !a.Dark {
|
||||
return fmt.Errorf("主题配色无效")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// themeIndex 在页面首次绘制前提供当前主题偏好
|
||||
// 返回: []byte 页面内容, error 资源读取错误
|
||||
func (h *Host) themeIndex() ([]byte, error) {
|
||||
data, err := webuiassets.NativeFS.ReadFile("index.html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.themeMu.Lock()
|
||||
mode := h.theme.Mode
|
||||
h.themeMu.Unlock()
|
||||
if mode == "" {
|
||||
mode = "system"
|
||||
}
|
||||
return bytes.Replace(data, []byte(`<html lang="zh-CN">`), []byte(`<html lang="zh-CN" data-theme-mode="`+mode+`">`), 1), nil
|
||||
}
|
||||
|
||||
// setTheme 串行保存应用偏好并同步当前窗口配色
|
||||
// 入参: value 已解析的主题偏好
|
||||
// 返回: error 校验、持久化或窗口更新错误
|
||||
func (h *Host) setTheme(value applicationTheme) error {
|
||||
if err := value.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
h.themeMu.Lock()
|
||||
defer h.themeMu.Unlock()
|
||||
h.mu.Lock()
|
||||
window := h.window
|
||||
h.mu.Unlock()
|
||||
if window == nil {
|
||||
return fmt.Errorf("窗口尚未就绪")
|
||||
}
|
||||
if h.theme != value {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(filepath.Dir(h.themePath), "appearance-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
_, writeErr := file.Write(data)
|
||||
closeErr := file.Close()
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if err := os.Rename(file.Name(), h.themePath); err != nil {
|
||||
return err
|
||||
}
|
||||
h.theme = value
|
||||
}
|
||||
return window.SetTitleBarColors(themeColors(value.Dark))
|
||||
}
|
||||
Reference in new issue
Block a user