Skip to content
Repos

mologram

C++ 7.9 KB222 lines Opens in site

Directory Raw Download

#include "mologram/Config.hpp"

#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iterator>

#include "mologram/ActionRegistry.hpp"

namespace mologram {
namespace fs = std::filesystem;
using ttgui::json::Value;

static std::string envOr(const char* name, const std::string& fallback) {
  const char* e = std::getenv(name);
  return (e && *e) ? std::string(e) : fallback;
}

void Config::setDefaults() {
  std::string home = envOr("HOME", "");
  std::string dataHome = envOr("XDG_DATA_HOME", home + "/.local/share");
  std::string runtime = envOr("XDG_RUNTIME_DIR", "/tmp");
  values_["data_dir"] = Value(dataHome + "/mologram");
  values_["session_path"] = Value(dataHome + "/mologram/main.session");
  values_["socket_path"] = Value(runtime + "/mologram.sock");
  values_["theme"] = Value("default");
  values_["ascii_mode"] = Value(false);
  values_["unicode.probe"] = Value(true);
  values_["unicode.emojiWidth"] = Value(0);
  values_["unicode.vs16Width"] = Value(0);
  values_["unicode.zwjMode"] = Value("first");
  values_["media.image_mode"] = Value("auto");
  values_["media.auto_download"] = Value(true);
  values_["notifications.enabled"] = Value(true);
  values_["notifications.bell"] = Value(true);
  values_["notifications.mute_default"] = Value(false);
  values_["language"] = Value("en");
  values_["account"] = Value("main");
  values_["keep_daemon"] = Value(false);
  values_["tearoff.keep_source"] = Value(true);
  values_["tearoff.edge_hold_ms"] = Value(600);
  values_["premium.show_locked"] = Value(true);
}

static bool typeMatches(const Value& v, ConfigType t) {
  switch (t) {
    case ConfigType::Int: return v.isNum();
    case ConfigType::String: return v.isStr();
    case ConfigType::Bool: return v.isBool();
    case ConfigType::Object: return v.isObj();
  }
  return false;
}

void Config::applyRoot(const Value& root) {
  if (!root.isObj()) { warnings_.push_back("config root is not an object"); return; }
  for (const auto& kv : *root.asObj()) {
    const std::string& top = kv.first;
    if (ConfigSchema::find(top)) {
      const ConfigKey* k = ConfigSchema::find(top);
      if (typeMatches(kv.second, k->type)) { values_[top] = kv.second; explicit_.insert(top); }
      else warnings_.push_back("wrong type for key (expected " + ConfigSchema::typeName(k->type) + "): " + top);
      continue;
    }
    // nested group: "unicode": { "probe": true }
    if (kv.second.isObj()) {
      bool group = false;
      for (const auto& sk : ConfigSchema::keys()) if (sk.name.rfind(top + ".", 0) == 0) { group = true; break; }
      if (group) {
        for (const auto& inner : *kv.second.asObj()) {
          std::string dotted = top + "." + inner.first;
          const ConfigKey* k = ConfigSchema::find(dotted);
          if (!k) { warnings_.push_back("unknown key: " + dotted); continue; }
          if (typeMatches(inner.second, k->type)) { values_[dotted] = inner.second; explicit_.insert(dotted); }
          else warnings_.push_back("wrong type for key (expected " + ConfigSchema::typeName(k->type) + "): " + dotted);
        }
        continue;
      }
    }
    warnings_.push_back("unknown key: " + top);
  }
}

Config Config::fromText(const std::string& text, const std::string& origin) {
  Config c;
  c.setDefaults();
  ttgui::json::ParseError pe;
  auto v = ttgui::json::parse(text, &pe);
  if (!v) {
    c.warnings_.push_back(origin + ": JSON error at " + std::to_string(pe.line) + ":" + std::to_string(pe.col) + " " + pe.msg);
    return c;
  }
  c.applyRoot(*v);
  c.loadedPath_ = origin;
  c.deriveAccountPaths();
  return c;
}

Config Config::load(const std::string& explicitPath) {
  std::vector<std::string> candidates;
  if (!explicitPath.empty()) candidates.push_back(explicitPath);
  else {
    if (const char* e = std::getenv("MOLOGRAM_CONFIG"); e && *e) candidates.push_back(e);
    candidates.push_back(".env.json");
    std::string home = envOr("HOME", "");
    candidates.push_back(envOr("XDG_CONFIG_HOME", home + "/.config") + "/mologram/.env.json");
  }
  for (const auto& p : candidates) {
    std::error_code ec;
    if (!fs::exists(p, ec)) continue;
    std::ifstream in(p);
    if (!in) continue;
    std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
    return fromText(text, p);
  }
  Config c;
  c.setDefaults();
  if (!explicitPath.empty()) c.warnings_.push_back("config not found: " + explicitPath);
  return c;
}

std::string Config::str(const std::string& key) const {
  auto it = values_.find(key);
  return it == values_.end() ? std::string() : it->second.asStr();
}
int Config::num(const std::string& key) const {
  auto it = values_.find(key);
  return it == values_.end() ? 0 : it->second.asInt();
}
bool Config::flag(const std::string& key) const {
  auto it = values_.find(key);
  return it == values_.end() ? false : it->second.asBool();
}
const Value* Config::object(const std::string& key) const {
  auto it = values_.find(key);
  return it == values_.end() ? nullptr : &it->second;
}

std::vector<std::string> Config::missingRequired() const {
  std::vector<std::string> out;
  for (const auto& k : ConfigSchema::keys()) if (k.required && !isSet(k.name)) out.push_back(k.name);
  return out;
}

std::string Config::dumpRedacted() const {
  ttgui::json::Object o;
  for (const auto& k : ConfigSchema::keys()) {
    auto it = values_.find(k.name);
    if (it == values_.end()) { if (k.required) o[k.name] = Value("<missing>"); continue; }
    o[k.name] = k.secret ? Value("<redacted>") : it->second;
  }
  return ttgui::json::dump(Value(std::move(o)));
}

ttgui::Config Config::rguiConfig() const {
  ttgui::Config c = ttgui::Config::defaults();
  ttgui::json::Object root;
  for (const char* k : {"colors", "uiColors", "glyphs"}) if (const Value* v = object(k)) root[k] = *v;
  root["asciiMode"] = Value(flag("ascii_mode"));
  root["unicodeProbe"] = Value(flag("unicode.probe"));
  root["emojiWidth"] = Value(num("unicode.emojiWidth"));
  root["vs16Width"] = Value(num("unicode.vs16Width"));
  root["zwjMode"] = Value(str("unicode.zwjMode"));
  ttgui::json::Object media;
  media["image_mode"] = Value(str("media.image_mode"));
  root["media"] = Value(std::move(media));
  c.applyJson(Value(std::move(root)));
  if (c.asciiMode) c.bevelStyle = "ascii";
  return c;
}

std::string Config::keyFor(const std::string& action) const {
  if (const Value* kb = object("keybindings")) {
    if (const Value* v = kb->find(action); v && v->isStr()) return v->asStr();
  }
  const ActionDef* a = ActionRegistry::find(action);
  return a ? a->defaultKey : std::string();
}

} // namespace mologram

namespace mologram {

void Config::deriveAccountPaths() {
  std::string acct = str("account");
  if (acct.empty() || acct == "main") return;
  std::string dataDir = str("data_dir");
  if (!explicit_.count("session_path")) values_["session_path"] = ttgui::json::Value(dataDir + "/" + acct + ".session");
  if (!explicit_.count("socket_path")) {
    std::string runtime = envOr("XDG_RUNTIME_DIR", "/tmp");
    values_["socket_path"] = ttgui::json::Value(runtime + "/mologram-" + acct + ".sock");
  }
}

void Config::setAccount(const std::string& name) {
  values_["account"] = ttgui::json::Value(name);
  explicit_.insert("account");
  deriveAccountPaths();
}

void Config::override(const std::string& key, const ttgui::json::Value& v) {
  const ConfigKey* k = ConfigSchema::find(key);
  if (!k) { warnings_.push_back("unknown key: " + key); return; }
  if (!typeMatches(v, k->type)) { warnings_.push_back("wrong type for key (expected " + ConfigSchema::typeName(k->type) + "): " + key); return; }
  values_[key] = v;
  explicit_.insert(key);
}

} // namespace mologram

namespace mologram {

void Config::setKeybinding(const std::string& action, const std::string& key) {
  ttgui::json::Object o;
  auto it = values_.find("keybindings");
  if (it != values_.end() && it->second.isObj()) o = *it->second.asObj();
  if (key.empty()) o.erase(action); else o[action] = ttgui::json::Value(key);
  values_["keybindings"] = ttgui::json::Value(std::move(o));
  explicit_.insert("keybindings");
}

} // namespace mologram
31.7ms