| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- package com.mes.core;
- import com.alibaba.fastjson2.JSON;
- import com.alibaba.fastjson2.JSONObject;
- import com.alibaba.fastjson2.JSONWriter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * 本机 UI 偏好 - 管理“始终显示”的菜单白名单
- *
- * 存储位置:config/ui_prefs.json
- * 结构:
- * {
- * "alwaysShow": ["manual_submit"]
- * }
- */
- public class UiPrefs {
- private static final Logger log = LoggerFactory.getLogger(UiPrefs.class);
- private static final String CONFIG_FILE = "config/ui_prefs.json";
- /** 菜单 key:手动提交子菜单 */
- public static final String KEY_MANUAL_SUBMIT = "manual_submit";
- private static UiPrefs INSTANCE;
- private final Path configPath;
- private final Set<String> alwaysShow = new HashSet<>();
- private UiPrefs() {
- this.configPath = Paths.get(CONFIG_FILE);
- load();
- }
- public static synchronized UiPrefs getInstance() {
- if (INSTANCE == null) {
- INSTANCE = new UiPrefs();
- }
- return INSTANCE;
- }
- /** 是否勾选了“始终显示” */
- public boolean isAlwaysShow(String key) {
- return alwaysShow.contains(key);
- }
- /** 设置“始终显示”状态,立即落盘 */
- public void setAlwaysShow(String key, boolean always) {
- boolean changed;
- if (always) {
- changed = alwaysShow.add(key);
- } else {
- changed = alwaysShow.remove(key);
- }
- if (changed) {
- save();
- }
- }
- private void load() {
- try {
- if (!Files.exists(configPath)) {
- log.info("UI偏好文件不存在,使用默认值: {}", configPath);
- return;
- }
- String content = new String(Files.readAllBytes(configPath), StandardCharsets.UTF_8);
- JSONObject json = JSON.parseObject(content);
- if (json == null) return;
- alwaysShow.clear();
- java.util.List<Object> list = json.getJSONArray("alwaysShow");
- if (list != null) {
- for (Object o : list) {
- if (o != null) alwaysShow.add(o.toString());
- }
- }
- log.info("UI偏好加载成功: alwaysShow={}", alwaysShow);
- } catch (Exception e) {
- log.error("加载UI偏好失败: {}", e.getMessage(), e);
- }
- }
- private void save() {
- try {
- if (configPath.getParent() != null && !Files.exists(configPath.getParent())) {
- Files.createDirectories(configPath.getParent());
- }
- JSONObject root = new JSONObject();
- root.put("alwaysShow", new java.util.ArrayList<>(alwaysShow));
- String content = JSON.toJSONString(root, JSONWriter.Feature.PrettyFormat);
- Files.write(configPath, content.getBytes(StandardCharsets.UTF_8));
- log.info("UI偏好已保存: {}", alwaysShow);
- } catch (IOException e) {
- log.error("保存UI偏好失败: {}", e.getMessage(), e);
- }
- }
- }
|