#include "mologram/ui/dialogs/ChatDialogs.hpp"
#include <ctime>
#include <filesystem>
#include "mologram/ui/ActionRouter.hpp"
#include "mologram/ui/dialogs/DialogUtil.hpp"
namespace mologram::ui {
using namespace ttgui;
namespace fs = std::filesystem;
namespace {
std::vector<Dialog> allDialogs(UiContext& c) {
std::vector<Dialog> v = c.controller.dialogs();
for (const auto& d : c.controller.archived()) v.push_back(d);
return v;
}
std::string trim(const std::string& s) {
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos) return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
} // namespace
// ------------------------------------------------------------------ Forward
std::vector<Dialog> ForwardDialog::filter(const std::vector<Dialog>& all, const std::string& q) {
std::vector<Dialog> v;
for (const auto& d : all) if (dlg::containsNoCase(d.name, q)) v.push_back(d);
return v;
}
Window* ForwardDialog::open(UiContext& c, const Peer& from, std::vector<long long> ids) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.forward"), "ForwardDialog", 50, 18);
auto alive = dlg::track(f.win);
auto all = std::make_shared<std::vector<Dialog>>(allDialogs(c));
auto shown = std::make_shared<std::vector<Dialog>>(*all);
auto* search = c.kit.edit(f, c.t("label.search"));
std::vector<std::string> names;
for (const auto& d : *shown) names.push_back(d.name);
auto* list = c.kit.list(f, names);
Window* win = f.win;
search->onChanged.connect([list, all, shown](std::string q) {
*shown = filter(*all, q);
list->items.clear();
for (const auto& d : *shown) list->items.push_back(d.name);
list->selected = list->items.empty() ? -1 : 0;
});
auto doForward = [cp, from, ids, list, shown, win]() {
int i = list->selected;
if (i < 0 || i >= (int)shown->size()) return;
Dialog target = (*shown)[(size_t)i];
cp->kit.close(win); // closed first: the reply below only needs the always-alive context, not this window
js::Object p;
p["from"] = from.toJson();
p["to"] = target.peer.toJson();
js::Array a;
for (long long id : ids) a.push_back(js::id(id));
p["ids"] = js::Value(std::move(a));
cp->client.request("forward", "messages.forward", std::move(p), [cp, target](const RpcResult&) {
if (cp->toast) cp->toast("Forwarded", "Sent to " + target.name);
});
};
list->onActivated.connect([doForward](int) { doForward(); });
auto* r = c.kit.row(f);
c.kit.rowButton(r, c.t("title.forward"), doForward);
c.kit.rowButton(r, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, search);
return f.win;
}
// ------------------------------------------------------------------ Search
const std::vector<std::string>& SearchDialog::filters() {
static const std::vector<std::string> v = {"All", "Photos", "Videos", "Files", "Links", "Voice", "GIFs", "Music"};
return v;
}
std::string SearchDialog::filterId(int index) {
static const char* ids[] = {"", "photo", "video", "file", "link", "voice", "gif", "music"};
return (index >= 0 && index < 8) ? ids[index] : "";
}
Window* SearchDialog::open(UiContext& c, const Peer* scope, const std::string& initialQuery) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.search"), "SearchDialog", 70, 22);
auto alive = dlg::track(f.win);
Window* win = f.win;
struct State {
std::vector<SearchDialog::Result> results;
int generation = 0;
bool scoped = false;
Peer scope;
};
auto st = std::make_shared<State>();
if (scope) { st->scoped = true; st->scope = *scope; }
auto* query = c.kit.edit(f, c.t("label.search"), initialQuery);
auto* filter = c.kit.combo(f, filters(), 0);
auto* list = c.kit.list(f, {});
auto refresh = [list, st]() {
list->items.clear();
for (const auto& r : st->results) list->items.push_back(r.label);
list->selected = list->items.empty() ? -1 : 0;
};
auto run = [cp, query, filter, st, refresh, alive]() {
int gen = ++st->generation;
st->results.clear();
std::string q = query->text;
int fi = filter->selected;
if (q.empty() && fi == 0) { refresh(); return; }
if (!st->scoped && fi == 0) {
for (const auto& d : allDialogs(*cp)) if (dlg::containsNoCase(d.name, q)) st->results.push_back({SearchDialog::Result::Chat, d.peer, 0, "[chat] " + d.name});
refresh();
js::Object cq;
cq["query"] = js::Value(q);
cp->client.request("search contacts", "contacts.search", std::move(cq), [st, refresh, gen, alive](const RpcResult& r) {
if (!*alive || gen != st->generation) return;
if (const js::Array* a = js::getArr(r.value, "peers"))
for (const auto& e : *a) {
PeerInfo i = PeerInfo::fromJson(e);
st->results.push_back({SearchDialog::Result::Contact, i.peer, 0, "[contact] " + i.name + (i.username.empty() ? "" : " @" + i.username)});
}
refresh();
});
}
js::Object mq;
if (st->scoped) mq["peer"] = st->scope.toJson();
mq["query"] = js::Value(q);
std::string fid = SearchDialog::filterId(fi);
if (!fid.empty()) mq["filter"] = js::Value(fid);
cp->client.request("search messages", "messages.search", std::move(mq), [cp, st, refresh, gen, alive](const RpcResult& r) {
if (!*alive || gen != st->generation) return;
if (const js::Array* a = js::getArr(r.value, "messages"))
for (const auto& e : *a) {
Message m = Message::fromJson(e);
const Dialog* d = cp->controller.dialog(m.peer);
std::string where = st->scoped || !d ? "" : d->name + ": ";
std::string text = m.text.empty() ? "[media]" : m.text;
st->results.push_back({SearchDialog::Result::Message, m.peer, m.id, "[msg] " + where + m.senderName + ": " + text});
}
refresh();
});
};
query->onChanged.connect([run](std::string) { run(); });
filter->onSelected.connect([run](int) { run(); });
list->onActivated.connect([cp, st, win](int i) {
if (i < 0 || i >= (int)st->results.size()) return;
SearchDialog::Result r = st->results[(size_t)i];
cp->kit.close(win);
if (st->scoped) {
if (ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr) if (r.messageId) s->jumpTo(r.messageId);
return;
}
cp->controller.openPeer(r.peer);
if (r.messageId) cp->controller.session().jumpTo(r.messageId);
});
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.close"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, query);
if (!initialQuery.empty()) run();
return f.win;
}
// ------------------------------------------------------------------ Attach
std::vector<std::string> AttachDialog::listDir(const std::string& dir) {
std::vector<std::string> dirs, files;
std::error_code ec;
for (fs::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) {
std::error_code e2;
if (it->is_directory(e2)) dirs.push_back(it->path().filename().string() + "/");
else files.push_back(it->path().filename().string());
}
std::sort(dirs.begin(), dirs.end());
std::sort(files.begin(), files.end());
std::vector<std::string> out{"../"};
if (ec && dirs.empty() && files.empty()) return out;
out.insert(out.end(), dirs.begin(), dirs.end());
out.insert(out.end(), files.begin(), files.end());
return out;
}
bool AttachDialog::looksLikePath(const std::string& pasted, std::string* normalized) {
std::string t = trim(pasted);
if (t.size() >= 2 && ((t.front() == '\'' && t.back() == '\'') || (t.front() == '"' && t.back() == '"'))) t = t.substr(1, t.size() - 2);
if (t.rfind("file://", 0) == 0) t = t.substr(7);
if (t.empty() || t.find('\n') != std::string::npos) return false;
std::error_code ec;
if (!fs::is_regular_file(t, ec)) return false;
if (normalized) *normalized = t;
return true;
}
Window* AttachDialog::open(UiContext& c, const std::string& path) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.attach"), "AttachDialog", 64, 22);
auto alive = dlg::track(f.win);
Window* win = f.win;
std::string startDir = path.empty() ? fs::current_path().string() : fs::path(path).parent_path().string();
if (startDir.empty()) startDir = ".";
auto cwd = std::make_shared<std::string>(startDir);
auto entries = std::make_shared<std::vector<std::string>>(listDir(startDir));
auto* pathEdit = c.kit.edit(f, "path", path);
auto* caption = c.kit.edit(f, c.t("label.caption"));
auto* error = c.kit.label(f, "");
auto* list = c.kit.list(f, *entries);
list->onActivated.connect([=](int i) {
if (i < 0 || i >= (int)entries->size()) return;
const std::string& e = (*entries)[(size_t)i];
if (e == "../") *cwd = fs::path(*cwd).parent_path().string();
else if (e.back() == '/') *cwd = (fs::path(*cwd) / e.substr(0, e.size() - 1)).string();
else { pathEdit->text = (fs::path(*cwd) / e).string(); pathEdit->cursor = pathEdit->text.size(); return; }
if (cwd->empty()) *cwd = "/";
*entries = listDir(*cwd);
list->items = *entries;
list->selected = 0;
list->scroll = 0;
});
auto attach = [cp, pathEdit, caption, error, win]() {
std::string norm;
if (!AttachDialog::looksLikePath(pathEdit->text, &norm)) { error->text = "Not a file: " + pathEdit->text; return; }
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
if (!s || !s->isOpen()) { error->text = "Open a chat first"; return; }
cp->kit.close(win); // closed first (see ForwardDialog)
js::Object p;
p["peer"] = s->peer().toJson();
p["path"] = js::Value(norm);
if (!caption->text.empty()) p["caption"] = js::Value(caption->text);
std::string name = fs::path(norm).filename().string();
cp->client.request("send file", "messages.send_file", std::move(p), [cp, name](const RpcResult&) {
if (cp->toast) cp->toast("Sent", name);
});
};
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.attach"), attach);
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
pathEdit->onEnter.connect(attach);
c.kit.show(f, pathEdit);
return f.win;
}
// ------------------------------------------------------------------ Poll
Window* PollDialog::open(UiContext& c) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.poll"), "PollDialog", 56, 24);
auto alive = dlg::track(f.win);
Window* win = f.win;
auto* question = c.kit.edit(f, c.t("label.question"));
auto opts = std::make_shared<std::vector<EditBox*>>();
for (int i = 0; i < 10; i++) { // the server allows up to 10 options; the rest stay hidden until "Add option"
auto* e = c.kit.edit(f, "Option " + std::to_string(i + 1));
e->visible = i < 3;
opts->push_back(e);
}
auto* multiple = c.kit.check(f, "Multiple answers", false);
auto* quiz = c.kit.check(f, "Quiz", false);
auto* correct = c.kit.edit(f, "Correct option number (quiz)");
auto* addRow = c.kit.row(f);
Window* w2 = win;
c.kit.rowButton(addRow, "Add option", [opts, w2]() {
for (auto* e : *opts) if (!e->visible) { e->visible = true; break; }
w2->layout();
});
auto send = [cp, question, opts, multiple, quiz, correct, win]() {
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
if (!s || !s->isOpen()) return;
js::Object p;
p["peer"] = s->peer().toJson();
p["question"] = js::Value(question->text);
js::Array a;
for (auto* e : *opts) if (e->visible && !e->text.empty()) a.push_back(js::Value(e->text));
p["options"] = js::Value(std::move(a));
if (multiple->checked) p["multiple"] = js::Value(true);
if (quiz->checked) {
p["quiz"] = js::Value(true);
int n = std::atoi(correct->text.c_str());
p["correct"] = js::Value(n - 1);
}
Peer peer = s->peer();
cp->kit.close(win); // closed first (see ForwardDialog)
cp->client.request("create poll", "messages.send_poll", std::move(p), [cp, peer](const RpcResult& r) {
ChatSession* cur = cp->activeSession ? cp->activeSession() : nullptr;
if (cur && cur->peer() == peer) {
Event e;
e.name = "message.new";
js::Object d;
d["message"] = r.value;
e.data = js::Value(std::move(d));
cur->handleEvent(e); // shows the poll at once; the service event for it is ignored as a duplicate
}
});
};
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.send"), send);
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, question);
return f.win;
}
// ------------------------------------------------------------------ Schedule
bool ScheduleDialog::parseWhen(const std::string& text, std::int64_t& out) {
int y = 0, mo = 0, d = 0, h = 0, mi = 0;
char tail = 0;
if (std::sscanf(text.c_str(), "%d-%d-%d %d:%d%c", &y, &mo, &d, &h, &mi, &tail) != 5) return false;
if (mo < 1 || mo > 12 || d < 1 || d > 31 || h < 0 || h > 23 || mi < 0 || mi > 59) return false;
std::tm tm{};
tm.tm_year = y - 1900; tm.tm_mon = mo - 1; tm.tm_mday = d; tm.tm_hour = h; tm.tm_min = mi; tm.tm_isdst = -1;
std::time_t t = std::mktime(&tm);
if (t == (std::time_t)-1) return false;
out = (std::int64_t)t;
return true;
}
Window* ScheduleDialog::open(UiContext& c) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.schedule"), "ScheduleDialog", 56, 20);
auto alive = dlg::track(f.win);
Window* win = f.win;
auto* when = c.kit.edit(f, c.t("label.when"));
auto* error = c.kit.label(f, "");
c.kit.label(f, "Scheduled in this chat:");
auto* list = c.kit.list(f, {});
if (ChatSession* s = c.activeSession ? c.activeSession() : nullptr; s && s->isOpen()) {
js::Object p;
p["peer"] = s->peer().toJson();
c.client.request("load scheduled messages", "messages.scheduled", std::move(p), [list, alive](const RpcResult& r) {
if (!*alive) return;
if (const js::Array* a = js::getArr(r.value, "messages"))
for (const auto& e : *a) { Message m = Message::fromJson(e); list->items.push_back(TgAdapter::timeOf(m.date) + " " + m.text); }
}, [](const RpcError&) {});
}
auto schedule = [cp, when, error, win]() {
std::int64_t t = 0;
if (!ScheduleDialog::parseWhen(when->text, t)) { error->text = "Use YYYY-MM-DD HH:MM"; return; }
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
if (!s || !s->isOpen()) { error->text = "Open a chat first"; return; }
std::string text = s->surface().composer->editor->getText();
if (text.empty()) { error->text = "Type the message in the composer first"; return; }
s->sendScheduled(text, t);
s->surface().composer->editor->setText("");
cp->kit.close(win);
};
when->onEnter.connect(schedule);
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.send"), schedule);
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, when);
return f.win;
}
// ------------------------------------------------------------------ Delete
Window* DeleteDialog::open(UiContext& c, std::vector<long long> ids) {
UiContext* cp = &c;
auto f = c.kit.open("Delete", "DeleteDialog", 48, 8);
auto alive = dlg::track(f.win);
Window* win = f.win;
c.kit.label(f, "Delete " + std::to_string(ids.size()) + (ids.size() == 1 ? " message?" : " messages?"));
auto go = [cp, ids, win](bool revoke) {
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
cp->kit.close(win); // closed first (see ForwardDialog)
if (s) s->deleteMessages(ids, revoke);
};
auto* row = c.kit.row(f);
c.kit.rowButton(row, "Delete for me", [go]() { go(false); });
c.kit.rowButton(row, "Delete for everyone", [go]() { go(true); });
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, nullptr);
return f.win;
}
// ------------------------------------------------------------------ Reaction picker
Window* ReactionPicker::open(UiContext& c, long long messageId) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.reaction"), "ReactionPicker", 40, 18);
auto alive = dlg::track(f.win);
Window* win = f.win;
struct Entry { std::string label; Reaction r; bool custom; };
auto entries = std::make_shared<std::vector<Entry>>();
for (const char* e : {"\xF0\x9F\x91\x8D", "\xE2\x9D\xA4\xEF\xB8\x8F", "\xF0\x9F\x98\x82", "\xF0\x9F\x98\xAE", "\xF0\x9F\x98\xA2", "\xF0\x9F\x99\x8F", "\xF0\x9F\x94\xA5", "\xF0\x9F\x8E\x89"}) {
Reaction r;
r.emoji = e;
entries->push_back({e, r, false});
}
auto* list = c.kit.list(f, {});
auto fill = [list, entries]() {
list->items.clear();
for (const auto& e : *entries) list->items.push_back(e.label);
list->selected = list->items.empty() ? -1 : 0;
};
fill();
c.kit.label(f, "Custom emoji need Telegram Premium");
js::Object q;
c.client.request("load custom emoji", "emoji.custom", std::move(q), [cp, entries, fill, alive](const RpcResult& r) {
if (!*alive) return;
if (const js::Array* a = js::getArr(r.value, "emoji"))
for (const auto& e : *a) {
Reaction rc;
rc.customEmojiId = js::getId(e, "id");
entries->push_back({cp->premium.label(js::getStr(e, "fallback") + " " + js::getStr(e, "title"), cp->cfg.flag("ascii_mode")), rc, true});
}
fill();
}, [](const RpcError&) {});
list->onActivated.connect([cp, entries, messageId, win](int i) {
if (i < 0 || i >= (int)entries->size()) return;
Entry e = (*entries)[(size_t)i];
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
if (!s) return;
auto go = [s, messageId, e, win, cp]() { s->react(messageId, e.r, true); cp->kit.close(win); };
if (e.custom) cp->premium.use("custom_emoji_reactions", go); else go();
});
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, list);
return f.win;
}
// ------------------------------------------------------------------ Link
Window* LinkDialog::open(UiContext& c) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.link"), "LinkDialog", 50, 9);
auto alive = dlg::track(f.win);
Window* win = f.win;
auto* text = c.kit.edit(f, "Text");
auto* url = c.kit.edit(f, "https://");
auto ok = [cp, text, url, win]() {
ChatSession* s = cp->activeSession ? cp->activeSession() : nullptr;
if (s && !url->text.empty()) {
s->markFormatted();
s->insertText("<a href=\"" + url->text + "\">" + (text->text.empty() ? url->text : text->text) + "</a>");
}
cp->kit.close(win);
};
url->onEnter.connect(ok);
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.ok"), ok);
c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, text);
return f.win;
}
// ------------------------------------------------------------------ Bot commands
Window* CommandsDialog::open(UiContext& c) {
UiContext* cp = &c;
auto f = c.kit.open(c.t("title.commands"), "CommandsDialog", 50, 16);
auto alive = dlg::track(f.win);
Window* win = f.win;
ChatSession* s = c.activeSession ? c.activeSession() : nullptr;
std::vector<std::string> items, cmds;
if (s) for (const auto& bc : s->botCommands()) { items.push_back("/" + bc.first + " " + bc.second); cmds.push_back("/" + bc.first + " "); }
if (items.empty()) c.kit.label(f, "This chat has no bot commands");
auto* list = c.kit.list(f, items);
list->onActivated.connect([cp, cmds, win](int i) {
if (i < 0 || i >= (int)cmds.size()) return;
if (ChatSession* cur = cp->activeSession ? cp->activeSession() : nullptr) cur->insertText(cmds[(size_t)i]);
cp->kit.close(win);
});
auto* row = c.kit.row(f);
c.kit.rowButton(row, c.t("btn.close"), [cp, win]() { cp->kit.close(win); });
c.kit.show(f, list);
return f.win;
}
} // namespace mologram::ui