#include "mologram/ui/dialogs/SettingsDialog.hpp"
#include "mologram/ActionRegistry.hpp"
#include "mologram/PremiumFeatures.hpp"
#include "mologram/ui/ActionRouter.hpp"
#include "mologram/ui/ThemeCatalog.hpp"
#include "mologram/ui/dialogs/DialogUtil.hpp"
#include "mologram/ui/dialogs/ExtrasPanels.hpp"
namespace mologram::ui {
using namespace ttgui;
const std::vector<std::string>& SettingsDialog::sections() {
static const std::vector<std::string> v = {"Profile", "Privacy", "Sessions", "Notifications", "Appearance", "Keys", "Premium", "Business", "Gifts", "Passport"};
return v;
}
const std::vector<SettingsDialog::PrivacyKey>& SettingsDialog::privacyKeys() {
static const std::vector<PrivacyKey> v = {
{"last_seen", "Last seen", ""}, {"profile_photo", "Profile photo", ""}, {"phone_number", "Phone number", ""},
{"calls", "Calls", ""}, {"groups", "Group invites", ""}, {"forwards", "Forwarded messages", ""},
{"about", "Bio", ""}, {"voice_messages", "Voice messages", "voice_privacy"}, {"read_time", "Read time", "read_time_privacy"}};
return v;
}
std::string SettingsDialog::nextRule(const std::string& rule) { return rule == "everybody" ? "contacts" : rule == "contacts" ? "nobody" : "everybody"; }
std::string SettingsDialog::conflictFor(const Config& cfg, const std::string& action, const std::string& key) {
for (const auto& a : ActionRegistry::all()) {
if (a.id == action || ActionRouter::canonicalKey(cfg.keyFor(a.id)) != ActionRouter::canonicalKey(key)) continue;
bool sharedPair = (a.id == "search" && action == "fmt_link") || (a.id == "fmt_link" && action == "search");
if (!sharedPair) return a.id;
}
return "";
}
std::string SettingsDialog::keyName(const KeyEventData& k) { return ActionRouter::canonicalKey(k.name()); }
namespace {
struct Ctx {
UiContext* c;
Window* win;
VBox* holder;
int generation = 0;
};
void buildProfile(Ctx& x, DialogKit::Form& f, std::shared_ptr<Ctx> st, int gen) {
UiContext& c = *x.c;
auto* first = c.kit.edit(f, "First name");
auto* last = c.kit.edit(f, "Last name");
auto* user = c.kit.edit(f, "Username");
auto* bio = c.kit.edit(f, "Bio");
auto* note = c.kit.label(f, "");
UiContext* cp = &c;
c.client.request("load profile", "account.profile", {}, [st, gen, first, last, user, bio](const RpcResult& r) {
if (st->generation != gen) return;
std::string name = js::getStr(r.value, "name");
size_t sp = name.find(' ');
first->text = sp == std::string::npos ? name : name.substr(0, sp);
last->text = sp == std::string::npos ? "" : name.substr(sp + 1);
user->text = js::getStr(r.value, "username");
bio->text = js::getStr(r.value, "bio");
first->cursor = first->text.size(); last->cursor = last->text.size(); user->cursor = user->text.size(); bio->cursor = bio->text.size();
});
c.kit.button(f, c.t("btn.save"), [cp, first, last, user, bio, note]() {
js::Object fields;
fields["first_name"] = js::Value(first->text);
fields["last_name"] = js::Value(last->text);
fields["username"] = js::Value(user->text);
fields["about"] = js::Value(bio->text);
js::Object p;
p["fields"] = js::Value(std::move(fields));
cp->client.request("save profile", "account.update_profile", std::move(p), [note](const RpcResult&) { note->text = "Saved"; });
});
}
void buildPrivacy(Ctx& x, DialogKit::Form& f, std::shared_ptr<Ctx> st, int gen) {
UiContext& c = *x.c;
UiContext* cp = &c;
c.kit.label(f, "Enter changes: everybody, contacts, nobody");
auto rules = std::make_shared<std::vector<std::string>>(SettingsDialog::privacyKeys().size(), "everybody");
auto* list = c.kit.list(f, {});
auto redraw = [list, rules, cp]() {
int sel = list->selected;
list->items.clear();
const auto& keys = SettingsDialog::privacyKeys();
for (size_t i = 0; i < keys.size(); i++) {
std::string label = keys[i].label + ": " + (*rules)[i];
if (!keys[i].premiumFeature.empty()) label = cp->premium.label(label, cp->cfg.flag("ascii_mode"));
list->items.push_back(label);
}
list->selected = sel < 0 ? 0 : sel;
};
redraw();
const auto& keys = SettingsDialog::privacyKeys();
for (size_t i = 0; i < keys.size(); i++) {
js::Object p;
p["key"] = js::Value(keys[i].id);
c.client.request("load privacy", "account.privacy", std::move(p), [st, gen, rules, i, redraw](const RpcResult& r) {
if (st->generation != gen) return;
(*rules)[i] = js::getStr(r.value, "rule", "everybody");
redraw();
}, [](const RpcError&) {});
}
list->onActivated.connect([cp, rules, redraw](int i) {
const auto& ks = SettingsDialog::privacyKeys();
if (i < 0 || i >= (int)ks.size()) return;
auto change = [cp, rules, redraw, i]() {
std::string next = SettingsDialog::nextRule((*rules)[(size_t)i]);
js::Object p;
p["key"] = js::Value(SettingsDialog::privacyKeys()[(size_t)i].id);
p["rule"] = js::Value(next);
cp->client.request("change privacy", "account.set_privacy", std::move(p), [rules, redraw, i, next](const RpcResult&) { (*rules)[(size_t)i] = next; redraw(); }, {}, SettingsDialog::privacyKeys()[(size_t)i].premiumFeature);
};
if (!ks[(size_t)i].premiumFeature.empty()) cp->premium.use(ks[(size_t)i].premiumFeature, change); else change();
});
}
void buildSessions(Ctx& x, DialogKit::Form& f, std::shared_ptr<Ctx> st, int gen) {
UiContext& c = *x.c;
UiContext* cp = &c;
auto* table = c.kit.table(f, {"Device", "This", "Id"}, {}, {28, 6, 16});
auto hashes = std::make_shared<std::vector<std::string>>();
auto* note = c.kit.label(f, "");
auto load = std::make_shared<std::function<void()>>();
*load = [cp, table, hashes, st, gen]() {
cp->client.request("load sessions", "account.sessions", {}, [table, hashes, st, gen](const RpcResult& r) {
if (st->generation != gen) return;
table->rows.clear();
hashes->clear();
if (const js::Array* a = js::getArr(r.value, "sessions"))
for (const auto& e : *a) {
table->rows.push_back({js::getStr(e, "device"), js::getBool(e, "current") ? "yes" : "", js::getStr(e, "hash")});
hashes->push_back(js::getStr(e, "hash"));
}
});
};
(*load)();
c.kit.button(f, c.t("btn.terminate"), [cp, table, hashes, note, load]() {
int i = table->selected;
if (i < 0 || i >= (int)hashes->size()) return;
js::Object p;
p["hash"] = js::Value((*hashes)[(size_t)i]);
cp->client.request("terminate session", "account.terminate_session", std::move(p), [note, load](const RpcResult&) { note->text = "Session ended"; (*load)(); });
});
}
void buildNotifications(Ctx& x, DialogKit::Form& f, std::shared_ptr<Ctx> st, int gen) {
UiContext& c = *x.c;
UiContext* cp = &c;
struct Scope { const char* id; const char* label; };
static const Scope scopes[] = {{"private", "Mute private chats"}, {"groups", "Mute groups"}, {"channels", "Mute channels"}};
auto boxes = std::make_shared<std::vector<CheckBox*>>();
for (const auto& s : scopes) {
std::string id = s.id;
auto* cb = c.kit.check(f, s.label, false);
cb->onChanged.connect([cp, id](bool on) {
js::Object p;
p["scope"] = js::Value(id);
p["muted"] = js::Value(on);
cp->client.request("change notifications", "account.set_notifications", std::move(p), [](const RpcResult&) {});
});
boxes->push_back(cb);
}
c.client.request("load notifications", "account.notifications", {}, [st, gen, boxes](const RpcResult& r) {
if (st->generation != gen) return;
for (size_t i = 0; i < 3; i++) if (const js::Value* s = r.value.find(scopes[i].id)) (*boxes)[i]->checked = js::getBool(*s, "muted");
}, [](const RpcError&) {});
c.kit.check(f, "Sound (bell) for new messages", c.cfg.flag("notifications.bell"), [cp](bool on) { cp->cfg.override("notifications.bell", js::Value(on)); });
c.kit.check(f, "Notifications on", c.cfg.flag("notifications.enabled"), [cp](bool on) { cp->cfg.override("notifications.enabled", js::Value(on)); });
}
void buildAppearance(Ctx& x, DialogKit::Form& f) {
UiContext& c = *x.c;
UiContext* cp = &c;
c.kit.label(f, c.t("label.theme"));
auto themes = ThemeCatalog::names();
int ti = 0;
for (size_t i = 0; i < themes.size(); i++) if (themes[i] == c.cfg.str("theme")) ti = (int)i;
auto* tc = c.kit.combo(f, themes, ti);
tc->onSelected.connect([cp, themes](int i) {
if (i < 0 || i >= (int)themes.size()) return;
cp->cfg.override("theme", js::Value(themes[(size_t)i]));
cp->prefs.setStr("theme", themes[(size_t)i]);
std::string err;
cp->prefs.save(err);
if (cp->applyTheme) cp->applyTheme();
});
c.kit.label(f, c.t("label.language"));
std::vector<std::string> names;
int li = 0;
const auto& codes = Strings::languages();
for (size_t i = 0; i < codes.size(); i++) { names.push_back(Strings::languageName(codes[i])); if (codes[i] == c.tr.language()) li = (int)i; }
auto* lc = c.kit.combo(f, names, li);
lc->onSelected.connect([cp](int i) {
const auto& cs = Strings::languages();
if (i < 0 || i >= (int)cs.size()) return;
cp->tr.set(cs[(size_t)i]);
cp->cfg.override("language", js::Value(cs[(size_t)i]));
cp->prefs.setStr("language", cs[(size_t)i]);
std::string err;
cp->prefs.save(err);
if (cp->reloadMenus) cp->reloadMenus();
});
}
void buildKeys(Ctx& x, DialogKit::Form& f) {
UiContext& c = *x.c;
UiContext* cp = &c;
auto rows = std::make_shared<std::vector<std::string>>();
auto* table = c.kit.table(f, {"Action", "Key"}, {}, {26, 18});
auto* note = c.kit.label(f, "");
auto fill = [cp, table, rows]() {
table->rows.clear();
rows->clear();
for (const auto& a : ActionRegistry::all()) { table->rows.push_back({a.id, cp->cfg.keyFor(a.id)}); rows->push_back(a.id); }
};
fill();
auto* r = c.kit.row(f);
c.kit.rowButton(r, c.t("btn.rebind"), [cp, table, rows, note, fill]() {
int i = table->selected;
if (i < 0 || i >= (int)rows->size()) return;
std::string action = (*rows)[(size_t)i];
note->text = "Press the new key for " + action + " (Escape cancels)";
cp->keyCapture = [cp, action, note, fill](const KeyEventData& k) {
cp->keyCapture = nullptr;
if (k.code == KeyCode::Escape) { note->text = "Cancelled"; return true; }
std::string name = SettingsDialog::keyName(k);
std::string other = SettingsDialog::conflictFor(cp->cfg, action, name);
if (!other.empty()) { note->text = name + " is already used by " + other; return true; }
cp->cfg.setKeybinding(action, name);
cp->prefs.setKeybinding(action, name);
std::string err;
cp->prefs.save(err);
note->text = action + " is now " + name;
fill();
if (cp->reloadMenus) cp->reloadMenus();
return true;
};
});
c.kit.rowButton(r, "Reset all", [cp, note, fill]() {
for (const auto& a : ActionRegistry::all()) cp->cfg.setKeybinding(a.id, "");
cp->prefs.clearKeybindings();
std::string err;
cp->prefs.save(err);
note->text = "Default keys restored";
fill();
if (cp->reloadMenus) cp->reloadMenus();
});
}
void buildPremium(Ctx& x, DialogKit::Form& f) {
UiContext& c = *x.c;
const char* st = c.premium.state() == PremiumState::Premium ? "Telegram Premium: active" : c.premium.state() == PremiumState::NotPremium ? "Telegram Premium: not active" : "Telegram Premium: unknown";
c.kit.label(f, st);
std::vector<std::vector<std::string>> rows;
bool ascii = c.cfg.flag("ascii_mode");
for (const auto& p : PremiumFeatures::all()) rows.push_back({c.premium.label(p.id, ascii), p.fallback});
auto* t = c.kit.table(f, {"Feature", "Without Premium"}, rows, {26, 30});
UiContext* cp = &c;
c.kit.button(f, "Use selected feature", [cp, t]() {
const auto& all = PremiumFeatures::all();
int i = t->selected;
if (i >= 0 && i < (int)all.size()) cp->premium.use(all[(size_t)i].id, nullptr); // without Premium: the calm explanation panel
});
c.kit.label(f, "Get Premium: open the chat with @PremiumBot");
}
void showSection(std::shared_ptr<Ctx> st, int idx) {
UiContext& c = *st->c;
int gen = ++st->generation;
st->holder->clearChildren();
auto* sec = new VBox();
sec->flex = 1;
DialogKit::Form f{st->win, sec};
switch (idx) {
case 0: buildProfile(*st, f, st, gen); break;
case 1: buildPrivacy(*st, f, st, gen); break;
case 2: buildSessions(*st, f, st, gen); break;
case 3: buildNotifications(*st, f, st, gen); break;
case 4: buildAppearance(*st, f); break;
case 5: buildKeys(*st, f); break;
case 6: buildPremium(*st, f); break;
case 7: BusinessPanel::build(c, f); break;
case 8: GiftsPanel::build(c, f); break;
default: PassportPanel::build(c, f); break;
}
st->holder->addChild(std::unique_ptr<Widget>(sec));
st->win->layout();
(void)c;
}
} // namespace
Window* SettingsDialog::open(UiContext& c, int section) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.settings"), "SettingsDialog", 70, 24);
auto alive = dlg::track(f.win);
auto st = std::make_shared<Ctx>();
st->c = cp;
st->win = f.win;
auto* combo = c.kit.combo(f, sections(), std::max(0, std::min(section, (int)sections().size() - 1)));
st->holder = new VBox();
st->holder->flex = 1;
f.box->addChild(std::unique_ptr<Widget>(st->holder));
Window* win = f.win;
auto* r = c.kit.row(f);
c.kit.rowButton(r, c.t("btn.close"), [cp, win]() { cp->kit.close(win); });
combo->onSelected.connect([st](int i) { showSection(st, i); });
c.kit.show(f, combo);
showSection(st, combo->selected);
return f.win;
}
} // namespace mologram::ui