#include "mologram/ui/MologramApp.hpp"
#include <algorithm>
#include <cstring>
#include <map>
#include "imagewidget.hpp"
#include "mologram/ActionRegistry.hpp"
#include "mologram/TerminalGuard.hpp"
#include "mologram/Version.hpp"
#include "mologram/ui/FloatingChat.hpp"
#include "mologram/ui/ComposerSuggest.hpp"
#include "mologram/ui/ExtrasModule.hpp"
#include "mologram/ui/HelpOverlay.hpp"
#include "mologram/ui/PremiumPanel.hpp"
#include "mologram/ui/media/MediaModule.hpp"
#include "mologram/ui/TearOff.hpp"
#include "mologram/ui/ThemeCatalog.hpp"
#include "mologram/ui/dialogs/ChatDialogs.hpp"
#include "mologram/ui/dialogs/EmojiDialog.hpp"
#include "mologram/ui/dialogs/LoginDialog.hpp"
#include "mologram/ui/dialogs/PeopleDialogs.hpp"
#include "mologram/ui/dialogs/SettingsDialog.hpp"
namespace mologram::ui {
using namespace ttgui;
namespace {
std::string base64(const std::string& in) {
static const char* t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
size_t i = 0;
while (i + 2 < in.size()) {
unsigned v = (unsigned char)in[i] << 16 | (unsigned char)in[i + 1] << 8 | (unsigned char)in[i + 2];
out += t[v >> 18]; out += t[(v >> 12) & 63]; out += t[(v >> 6) & 63]; out += t[v & 63];
i += 3;
}
if (i + 1 == in.size()) { unsigned v = (unsigned char)in[i] << 16; out += t[v >> 18]; out += t[(v >> 12) & 63]; out += "=="; }
else if (i + 2 == in.size()) { unsigned v = (unsigned char)in[i] << 16 | (unsigned char)in[i + 1] << 8; out += t[v >> 18]; out += t[(v >> 12) & 63]; out += t[(v >> 6) & 63]; out += '='; }
return out;
}
bool isDialogWindow(const Window* w) {
const std::string& n = w->appName;
auto ends = [&](const char* s) { size_t l = std::strlen(s); return n.size() >= l && n.compare(n.size() - l, l, s) == 0; };
return ends("Dialog") || ends("Picker") || ends("Panel") || ends("Overlay");
}
std::string prefsPathFor(const Config& cfg, const std::string& given) { return given.empty() ? cfg.str("data_dir") + "/prefs.json" : given; }
} // namespace
MologramApp::MologramApp(const Config& cfg, ITelegramService& service) : MologramApp(cfg, service, Options()) {}
MologramApp::MologramApp(const Config& cfg, ITelegramService& service, Options opt)
: cfg_(cfg), service_(service), opt_(std::move(opt)), app_(cfg_.rguiConfig()), client_(service, dispatcher_), actions_(cfg_),
prefs_(prefsPathFor(cfg_, opt_.prefsPath)), kit_(app_) {}
MologramApp::~MologramApp() {
floating_.clear();
if (controller_) service_.removeSink(controller_.get());
}
ChatSession* MologramApp::activeSession() {
if (Window* fw = app_.wm.focusedWin)
for (auto& f : floating_) if (f->window() == fw) return &f->session();
if (chatOnly() && !floating_.empty()) return &floating_.front()->session();
return controller_ ? &controller_->session() : nullptr;
}
void MologramApp::build(int w, int h) {
screenW_ = w;
screenH_ = h;
std::string perr;
bool prefsOk = prefs_.load(perr);
if (std::string lang = prefs_.str("language"); !lang.empty() && tr_.set(lang)) cfg_.override("language", js::Value(lang));
else tr_.set(cfg_.str("language"));
if (std::string theme = prefs_.str("theme"); !theme.empty()) { cfg_.override("theme", js::Value(theme)); }
ThemeCatalog::apply(app_.cfg, cfg_.str("theme"));
for (const auto& kv : prefs_.keybindings()) cfg_.setKeybinding(kv.first, kv.second);
app_.wm.workArea = {0, 1, w, std::max(1, h - 2)};
auto shell = std::make_unique<TelegramShell>();
shell_ = shell.get();
controller_ = std::make_unique<ChatController>(client_, dispatcher_, *shell_, premium_);
controller_->toast = [this](const std::string& t, const std::string& b) { app_.notify(t, b); };
controller_->copyToClipboard = [this](const std::string& text) { app_.terminal.writeStr("\x1b]52;c;" + base64(text) + "\x07"); };
premium_.showPanel = [this](const PremiumFeature& f) { PremiumPanel::open(app_, f); };
shell_->setup(&app_.cfg, nullptr);
service_.addSink(controller_.get());
if (opt_.log) client_.onFailure = [this](const std::string& what, const RpcError& e) { opt_.log->warn("ui", "could not " + what + ": " + e.code + " " + e.text); };
client_.scopeProvider = [this]() { return kit_.tokenOf(app_.wm.focusedWin); }; // a reply for a closed dialog is dropped
ctx_ = std::make_unique<UiContext>(UiContext{app_, cfg_, client_, premium_, *controller_, actions_, tr_, prefs_, kit_, {}, {}, {}, {}, {}, {}, {}, {}, {}});
ctx_->activeSession = [this]() { return activeSession(); };
ctx_->openFloating = [this](const Peer& p) { openFloating(p); };
ctx_->openNewWindow = [this](const Peer& p) {
std::string err;
if (!openNewWindow(p, err)) { app_.notify("New window", err + " - opened as a floating window instead"); openFloating(p); }
};
ctx_->toast = [this](const std::string& t, const std::string& b) { app_.notify(t, b); };
ctx_->switchAccount = [this](const std::string& name) { restartAccount_ = name; app_.quit("switch account"); };
ctx_->reloadMenus = [this]() {
if (!menu_) return;
menu_->menus.clear();
menu_->dropdowns.clear();
buildMenus();
};
ctx_->applyTheme = [this]() { ThemeCatalog::apply(app_.cfg, cfg_.str("theme")); };
if (!prefsOk) app_.notify("Preferences", perr);
menu_ = new MenuBar();
menu_->cfg = &app_.cfg;
buildMenus();
topPanel_ = std::make_unique<Panel>();
topPanel_->cfg = &app_.cfg;
topPanel_->windowClass = "grey";
topPanel_->bounds = {0, 0, w, 1};
topPanel_->addChild(std::unique_ptr<Widget>(menu_));
menu_->bounds = {0, 0, w, 1};
app_.topPanel = topPanel_.get();
status_ = new StatusBar();
status_->cfg = &app_.cfg;
bottomPanel_ = std::make_unique<Panel>();
bottomPanel_->cfg = &app_.cfg;
bottomPanel_->bounds = {0, h - 1, w, 1};
bottomPanel_->addChild(std::unique_ptr<Widget>(status_));
status_->bounds = {0, 0, w, 1};
app_.bottomPanel = bottomPanel_.get();
if (!chatOnly()) {
main_ = app_.wm.createWindow("mologram", "lightblue", app_.wm.workArea);
main_->appName = "MainWindow";
main_->maximized = true;
main_->closable = false;
main_->popFrames = 0;
main_->setContent(std::move(shell));
main_->bounds = app_.wm.workArea;
main_->layout();
wireShell();
} else {
hiddenShell_ = std::move(shell); // data holder for the controller; never drawn
}
bindActions();
app_.onGlobalEvent = [this](ttgui::Event& e) { onGlobal(e); };
app_.onTickExtra = [this]() {
dispatcher_.drain();
updateStatus();
graveyard_.clear();
checkEdgeHold();
for (auto& f : floating_) f->refreshTitle();
if (TerminalGuard::quitRequested()) { saveWindows(); app_.quit("signal"); } // SIGTERM or SIGHUP: leave normally, terminal restored
};
premium_.onChanged([this](PremiumState) { updateStatus(); });
controller_->onAnyEvent = [this](const Event& ev) {
if (ev.name == "auth.state" && ctx_->onAuthState) ctx_->onAuthState(js::getStr(ev.data, "state"));
auto hooks = eventHooks_; // a hook may register another hook
for (auto& h : hooks) h(ev);
};
controller_->onIncoming = [this](const Dialog& d, const Message& m) {
if (cfg_.flag("notifications.enabled")) app_.notify(d.name, m.text.empty() ? "[media]" : m.text);
if (cfg_.flag("notifications.bell")) app_.bell.ring("app");
};
controller_->session().suggest = std::make_unique<ComposerSuggest>(*ctx_, controller_->session());
media_ = media::MediaModule::install(*this);
extras_ = ExtrasModule::install(*this);
controller_->start();
client_.request("check login", "auth.state", {}, [this](const RpcResult& r) {
std::string s = js::getStr(r.value, "state");
if (!s.empty() && s != "ready") LoginDialog::open(*ctx_, s, "");
}, [](const RpcError&) {});
if (chatOnly()) {
Peer p = Peer::fromKey(opt_.openChat);
FloatingChat* f = openFloating(p, &app_.wm.workArea);
if (f) { main_ = f->window(); main_->maximized = true; main_->closable = false; }
} else {
restoreWindows();
if (!opt_.openChat.empty()) {}
}
updateStatus();
}
void MologramApp::wireShell() {
shell_->pinned->onClose.connect([this]() { shell_->layout(); });
shell_->header->setActions({"Search", "Profile"});
shell_->header->onAction.connect([this](std::string a) {
if (a == "Search") actions_.run("search_in_chat");
else if (a == "Profile") actions_.run("profile");
else if (a == "Commands") CommandsDialog::open(*ctx_);
else if (a == "Call") actions_.run("call");
});
controller_->onOpened = [this](const Peer& p) {
const Dialog* d = controller_->dialog(p);
if (d && d->isBot) shell_->header->setActions({"Search", "Commands", "Profile"});
else if (p.kind == PeerKind::User) shell_->header->setActions({"Search", "Call", "Profile"}); // a person can be called
else shell_->header->setActions({"Search", "Profile"});
controller_->session().surface().relayout();
};
controller_->session().requestForward = [this](const std::vector<long long>& ids) { ForwardDialog::open(*ctx_, controller_->session().peer(), ids); };
controller_->session().requestReactionPicker = [this](long long id) { ReactionPicker::open(*ctx_, id); };
controller_->session().requestDelete = [this](const std::vector<long long>& ids) { DeleteDialog::open(*ctx_, ids); };
shell_->list->onClicked.connect([this](int i) { shell_->openChatAt(i); });
shell_->list->onDoubleClick.connect([this](int i) {
if (i < 0 || i >= (int)shell_->shownRows.size()) return;
ctx_->openNewWindow(TgAdapter::peerOf(shell_->shownRows[(size_t)i].id));
});
shell_->list->onContextRow.connect([this](int i, Point at) { openChatMenu(i, at); });
shell_->list->onDragRow.connect([this](int i, Point) { dragRow_ = i; });
}
void MologramApp::openChatMenu(int row, Point at) {
if (row < 0 || row >= (int)shell_->shownRows.size()) return;
Peer p = TgAdapter::peerOf(shell_->shownRows[(size_t)row].id);
shell_->ctx->items.clear();
for (const std::string& label : controller_->chatMenuFor(p)) {
Menu::Item it;
it.label = label;
it.action = [this, p, row, label]() {
shell_->ctx->open = false;
shell_->ctx->visible = false;
if (label == "Open") shell_->openChatAt(row);
else if (label == "Open in new window") ctx_->openNewWindow(p);
else if (label == "Open floating window") openFloating(p);
else controller_->chatAction(p, label);
};
shell_->ctx->items.push_back(it);
}
Rect a = shell_->absoluteBounds();
int mw = 24, mh = (int)shell_->ctx->items.size() + 2;
shell_->ctx->open = true;
shell_->ctx->visible = true;
shell_->ctx->selected = 0;
shell_->ctx->bounds = {std::clamp(at.x - a.x, 0, std::max(0, shell_->bounds.w - mw)), std::clamp(at.y - a.y, 0, std::max(0, shell_->bounds.h - mh)), mw, mh};
}
void MologramApp::buildMenus() {
std::vector<std::string> order;
std::map<std::string, std::vector<Menu::Item>> items;
for (const auto& a : ActionRegistry::all()) {
size_t slash = a.menu.find('/');
if (slash == std::string::npos) continue;
std::string top = a.menu.substr(0, slash), label = a.menu.substr(slash + 1);
if (!items.count(top)) order.push_back(top);
auto& v = items[top];
bool dup = false;
for (const auto& it : v) if (it.label == label) dup = true;
if (dup) continue;
std::string id = a.id;
Menu::Item it{label, cfg_.keyFor(a.id), false, false, [this, id]() { actions_.run(id); }};
v.push_back(it);
}
for (const auto& top : order) menu_->menus.push_back(tr_.tr("menu." + top));
for (const auto& top : order) menu_->dropdowns.push_back(items[top]);
}
void MologramApp::bindActions() {
auto& A = actions_;
A.bind("quit", [this]() { saveWindows(); app_.quit("quit"); });
A.bind("help", [this]() { HelpOverlay::open(app_, cfg_); });
A.bind("search", [this]() { SearchDialog::open(*ctx_, nullptr); });
A.bind("search_chat", [this]() { A_search_in_chat(); });
A.bind("search_in_chat", [this]() { A_search_in_chat(); });
auto step = [this](int d) {
if (!shell_ || shell_->shownRows.empty()) return;
int n = (int)shell_->shownRows.size();
int i = std::clamp(shell_->list->selected + d, 0, n - 1);
shell_->list->select(i);
shell_->openChatAt(i);
};
A.bind("chat_prev", [step]() { step(-1); });
A.bind("chat_next", [step]() { step(1); });
A.bind("chat_prev_alt", [step]() { step(-1); });
A.bind("chat_next_alt", [step]() { step(1); });
auto folder = [this](int d) {
if (!shell_) return;
int n = (int)shell_->folders->folders.size();
if (n == 0) return;
int i = (shell_->folders->active + d + n) % n;
shell_->folders->active = i;
shell_->folders->tabs->active = i;
shell_->folders->onChanged.emit(i);
};
A.bind("folder_prev", [folder]() { folder(-1); });
A.bind("folder_next", [folder]() { folder(1); });
A.bind("back", [this]() { if (shell_) { KeyEventData k(KeyCode::Escape); shell_->onKey(k); } });
A.bind("send", [this]() { if (auto* s = activeSession()) s->surface().composer->doSend(); });
A.bind("newline", [this]() { if (auto* s = activeSession()) s->insertText("\n"); });
A.bind("edit_last", [this]() { if (auto* s = activeSession()) s->editLastOwn(); });
A.bind("reply", [this]() { if (auto* s = activeSession()) s->replyTo(s->target()); });
A.bind("delete", [this]() { if (auto* s = activeSession()) s->deleteSelected(); });
A.bind("info", [this]() { if (shell_) shell_->infoOpen = !shell_->infoOpen; });
A.bind("close_window", [this]() {
Window* fw = app_.wm.focusedWin;
if (!fw || fw == main_) return;
for (auto& f : floating_) if (f->window() == fw) { closeFloating(f.get()); return; }
app_.wm.closeWindow(fw);
});
A.bind("emoji", [this]() { EmojiDialog::open(*ctx_); });
A.bind("attach", [this]() { AttachDialog::open(*ctx_); });
A.bind("forward", [this]() {
ChatSession* s = activeSession();
if (!s || !s->isOpen()) return;
std::vector<long long> ids(s->selection().begin(), s->selection().end());
if (ids.empty() && s->target() != 0) ids.push_back(s->target());
if (!ids.empty()) ForwardDialog::open(*ctx_, s->peer(), ids);
});
A.bind("pin", [this]() { if (auto* s = activeSession()) s->togglePin(s->target()); });
A.bind("pinned_next", [this]() {
ChatSession* s = activeSession();
if (!s) return;
auto* bar = s->surface().pinned;
if (bar->pins.empty()) return;
long long id = bar->pins[(size_t)bar->index].first;
bar->cycle(1);
s->jumpTo(id);
});
A.bind("react", [this]() { if (auto* s = activeSession()) if (s->target() != 0) ReactionPicker::open(*ctx_, s->target()); });
A.bind("select", [this]() { if (auto* s = activeSession()) s->toggleSelect(s->target()); });
A.bind("poll", [this]() { PollDialog::open(*ctx_); });
A.bind("schedule", [this]() { ScheduleDialog::open(*ctx_); });
A.bind("contacts", [this]() { ContactsDialog::open(*ctx_); });
A.bind("new_chat", [this]() { NewChatDialog::open(*ctx_); });
A.bind("profile", [this]() { if (auto* s = activeSession()) if (s->isOpen()) ProfileDialog::open(*ctx_, s->peer()); });
A.bind("accounts", [this]() { AccountsDialog::open(*ctx_); });
A.bind("settings", [this]() { SettingsDialog::open(*ctx_); });
A.bind("mute", [this]() {
ChatSession* s = activeSession();
if (!s || !s->isOpen()) return;
const Dialog* d = controller_->dialog(s->peer());
controller_->chatAction(s->peer(), d && d->muted ? "Unmute" : "Mute");
});
A.bind("archive", [this]() {
ChatSession* s = activeSession();
if (!s || !s->isOpen()) return;
const Dialog* d = controller_->dialog(s->peer());
controller_->chatAction(s->peer(), d && d->archived ? "Unarchive" : "Archive");
});
A.bind("mark_read", [this]() { if (auto* s = activeSession()) if (s->isOpen()) controller_->chatAction(s->peer(), "Mark as read"); });
A.bind("tear_off", [this]() { if (auto* s = activeSession()) if (s->isOpen()) ctx_->openNewWindow(s->peer()); });
A.bind("float_chat", [this]() { if (auto* s = activeSession()) if (s->isOpen()) openFloating(s->peer()); });
A.bind("fmt_bold", [this]() { if (auto* s = activeSession()) s->insertTagPair("<b>", "</b>"); });
A.bind("fmt_italic", [this]() { if (auto* s = activeSession()) s->insertTagPair("<i>", "</i>"); });
A.bind("fmt_underline", [this]() { if (auto* s = activeSession()) s->insertTagPair("<u>", "</u>"); });
A.bind("fmt_code", [this]() { if (auto* s = activeSession()) s->insertTagPair("<code>", "</code>"); });
A.bind("fmt_spoiler", [this]() { if (auto* s = activeSession()) s->insertTagPair("<tg-spoiler>", "</tg-spoiler>"); });
A.bind("fmt_link", [this]() { LinkDialog::open(*ctx_); });
}
void MologramApp::A_search_in_chat() {
ChatSession* s = activeSession();
if (s && s->isOpen()) {
Peer p = s->peer();
SearchDialog::open(*ctx_, &p);
} else {
SearchDialog::open(*ctx_, nullptr);
}
}
Peer MologramApp::dragPeer() const {
if (dragRow_ >= 0 && dragRow_ < (int)shell_->shownRows.size()) return TgAdapter::peerOf(shell_->shownRows[(size_t)dragRow_].id);
if (headerDrag_) return controller_->current();
return Peer{};
}
bool MologramApp::onMouseGlobal(ttgui::Event& e) {
const MouseEventData& m = e.mouse;
bool atEdge = m.pos.x <= 0 || m.pos.y <= 0 || m.pos.x >= screenW_ - 1 || m.pos.y >= screenH_ - 1; // terminals clamp a drag that leaves the window (A-02)
if (m.kind == MouseKind::Down) {
dragRow_ = -1;
headerDrag_ = false;
edgeSince_ = -1;
if (shell_ && !chatOnly() && shell_->header->visible && controller_->current().valid() && shell_->header->absoluteBounds().contains(m.pos)) headerDrag_ = true;
return false;
}
if (m.kind == MouseKind::Drag || m.kind == MouseKind::DragStart) {
// The pointer is held on the edge: the tick handler tears the chat off once it has stayed there long enough (checkEdgeHold).
if (dragRow_ >= 0 || headerDrag_) edgeSince_ = atEdge ? (edgeSince_ >= 0 ? edgeSince_ : app_.tickMs) : -1;
return false;
}
if (m.kind != MouseKind::Up && m.kind != MouseKind::DragEnd) return false;
Peer p = dragPeer();
dragRow_ = -1;
headerDrag_ = false;
edgeSince_ = -1;
if (!atEdge || !p.valid()) return false; // released at the edge: tear off at once
ctx_->openNewWindow(p);
return true;
}
void MologramApp::checkEdgeHold() {
if (edgeSince_ < 0) return;
int holdMs = cfg_.num("tearoff.edge_hold_ms");
if (holdMs <= 0 || app_.tickMs - edgeSince_ < holdMs) return; // 0 turns the hold gesture off; release at the edge still works
Peer p = dragPeer();
dragRow_ = -1;
headerDrag_ = false;
edgeSince_ = -1;
if (p.valid()) ctx_->openNewWindow(p);
}
void MologramApp::onGlobal(ttgui::Event& e) {
if (e.type == EventType::Paste && onPaste && onPaste(e.pasteText)) { e.pasteText.clear(); e.handled = true; return; }
if (e.type == EventType::Mouse) { onMouseGlobal(e); return; }
if (e.type == EventType::Paste) {
std::string path;
ChatSession* s = activeSession();
bool composerFocused = s && (app_.focusedWidget == s->surface().composer || app_.focusedWidget == s->surface().composer->editor);
if (composerFocused && AttachDialog::looksLikePath(e.pasteText, &path)) {
AttachDialog::open(*ctx_, path); // a pasted file path attaches the file (bracketed paste)
e.pasteText.clear();
}
return;
}
if (e.type != EventType::Key) return;
if (ctx_ && ctx_->keyCapture) {
auto capture = ctx_->keyCapture; // a copy: the capture may clear ctx_->keyCapture (and so destroy itself) while it runs
if (capture(e.key)) e.key = KeyEventData();
return;
}
if (ChatSession* sg = activeSession(); sg && sg->suggest) { // the suggestion popup of the focused composer (people, hashtags, commands)
bool inComposer = app_.focusedWidget == sg->surface().composer || app_.focusedWidget == sg->surface().composer->editor;
if (!inComposer) sg->suggest->close();
else if (sg->suggest->handleKey(e.key)) { e.key = KeyEventData(); return; }
}
if (e.key.code == KeyCode::Escape && app_.wm.focusedWin && app_.wm.focusedWin != main_) {
Window* fw = app_.wm.focusedWin;
if (isDialogWindow(fw)) { app_.wm.closeWindow(fw); e.key = KeyEventData(); return; }
}
ChatSession* s = activeSession();
bool composerFocused = s && (app_.focusedWidget == s->surface().composer || app_.focusedWidget == s->surface().composer->editor);
std::string id = actions_.actionFor(e.key, composerFocused);
if (id.empty()) {
// Up in an empty composer edits the last own message (Telegram Desktop behaviour)
if (e.key.code == KeyCode::Up && !e.key.ctrl && !e.key.alt && composerFocused && s->surface().composer->editor->getText().empty()) {
actions_.run("edit_last");
e.key = KeyEventData();
}
return;
}
if (actions_.run(id)) e.key = KeyEventData(); // consumed: later dispatch sees an empty key
}
void MologramApp::updateStatus() {
if (!status_) return;
std::string prem = premium_.state() == PremiumState::Premium ? "Premium" : premium_.state() == PremiumState::NotPremium ? "No Premium" : "Premium: ?";
const std::string& conn = controller_->connection();
std::string connT = (conn == "connected" || conn == "connecting" || conn == "disconnected") ? tr_.tr("status." + conn) : conn;
status_->sections = {connT, prem, controller_->account().empty() ? std::string("mologram ") + MOLOGRAM_VERSION : controller_->account()};
}
// ------------------------------------------------------------------ floating windows and tear-off (M7)
FloatingChat* MologramApp::openFloating(const Peer& p, const Rect* where) {
if (!p.valid()) return nullptr;
Rect r = where ? *where : Rect{4 + (int)floating_.size() * 3, 2 + (int)floating_.size() * 2, std::min(60, screenW_ - 4), std::min(20, screenH_ - 4)};
auto f = std::make_unique<FloatingChat>(*this, *ctx_, p, r);
FloatingChat* raw = f.get();
floating_.push_back(std::move(f));
saveWindows();
return raw;
}
void MologramApp::closeFloating(FloatingChat* f) {
if (f->window()) app_.wm.closeWindow(f->window()); // fires onClose -> floatingWindowClosed
else floatingWindowClosed(f);
}
void MologramApp::floatingWindowClosed(FloatingChat* f) {
auto it = std::find_if(floating_.begin(), floating_.end(), [&](const std::unique_ptr<FloatingChat>& x) { return x.get() == f; });
if (it == floating_.end()) return;
controller_->removeSession(&f->session());
f->session().flushDraft();
f->clearWindow();
graveyard_.push_back(std::move(*it)); // destroyed on the next tick, after the window manager released the window
floating_.erase(it);
saveWindows();
}
bool MologramApp::openNewWindow(const Peer& p, std::string& err) {
std::string self = opt_.selfPath.empty() ? "/proc/self/exe" : opt_.selfPath;
std::string socket = opt_.socketPath.empty() ? cfg_.str("socket_path") : opt_.socketPath;
std::vector<std::string> argv = TearOff::command(cfg_, self, p.key(), socket);
if (argv.empty()) { err = "no terminal emulator found (set terminal.command or $TERMINAL)"; return false; }
if (!TearOff::spawn(argv, err)) return false;
if (!cfg_.flag("tearoff.keep_source")) {
for (auto& f : floating_) if (f->peer() == p) { closeFloating(f.get()); break; }
if (shell_ && !chatOnly() && controller_->current() == p) shell_->showChat = false;
}
return true;
}
void MologramApp::saveWindows() {
if (chatOnly()) return;
std::vector<PrefsStore::WindowRec> recs;
for (auto& f : floating_) {
Window* w = f->window();
if (!w) continue;
recs.push_back({f->peer().key(), w->bounds.x, w->bounds.y, w->bounds.w, w->bounds.h});
}
prefs_.setWindows(recs);
std::string err;
prefs_.save(err);
}
void MologramApp::restoreWindows() {
for (const auto& r : prefs_.windows()) {
Rect rect{std::max(0, r.x), std::max(1, r.y), std::max(20, std::min(r.w, screenW_)), std::max(6, std::min(r.h, screenH_ - 2))};
openFloating(Peer::fromKey(r.peer), &rect);
}
}
std::string MologramApp::snapshot(int w, int h) {
Canvas c(w, h);
CellStyle bg;
c.clear(bg);
dispatcher_.drain();
updateStatus();
app_.render(c);
return c.text();
}
int MologramApp::run() {
auto sz = app_.terminal.size();
int w = sz.first < 20 ? 80 : sz.first, h = sz.second < 10 ? 24 : sz.second;
installImageDetection(app_);
build(w, h);
auto base = app_.onGlobalEvent;
app_.onGlobalEvent = [this, base](ttgui::Event& e) {
if (e.type == EventType::Resize) {
int nw = e.newW, nh = e.newH;
screenW_ = nw;
screenH_ = nh;
app_.wm.workArea = {0, 1, nw, std::max(1, nh - 2)};
if (main_) { main_->bounds = app_.wm.workArea; main_->layout(); }
if (topPanel_) { topPanel_->bounds = {0, 0, nw, 1}; menu_->bounds = {0, 0, nw, 1}; }
if (bottomPanel_) { bottomPanel_->bounds = {0, nh - 1, nw, 1}; status_->bounds = {0, 0, nw, 1}; }
}
base(e);
};
int rc = app_.run();
saveWindows();
return rc;
}
} // namespace mologram::ui