Skip to content
Repos

mologram

C++ 23.7 KB620 lines Opens in site

Directory Raw Download

#include "mologram/ui/ChatSession.hpp"
#include "mologram/ui/ComposerSuggest.hpp"

#include <algorithm>
#include <cstring>
#include <ctime>

namespace mologram::ui {
using namespace ttgui;

namespace {

/// Length of a UTF-8 string in UTF-16 code units (Telegram entity offsets are UTF-16).
std::int64_t utf16Len(const std::string& s) {
  std::int64_t n = 0;
  for (size_t i = 0; i < s.size();) {
    unsigned char c = (unsigned char)s[i];
    size_t len = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;
    n += len == 4 ? 2 : 1;
    i += len;
  }
  return n;
}

/// Escapes &, < and > but keeps the tags the formatting actions insert (b i u s code pre tg-spoiler and a href).
std::string escapeKeepingTags(const std::string& t) {
  static const char* tags[] = {"<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<s>", "</s>", "<code>", "</code>", "<pre>", "</pre>", "<tg-spoiler>", "</tg-spoiler>", "</a>"};
  std::string out;
  for (size_t i = 0; i < t.size();) {
    if (t[i] == '<') {
      bool kept = false;
      for (const char* tg : tags) {
        size_t n = std::strlen(tg);
        if (t.compare(i, n, tg) == 0) { out.append(tg, n); i += n; kept = true; break; }
      }
      if (!kept && t.compare(i, 9, "<a href=\"") == 0) {
        size_t close = t.find("\">", i + 9);
        if (close != std::string::npos) { out.append(t, i, close + 2 - i); i = close + 2; kept = true; }
      }
      if (kept) continue;
      out += "&lt;"; i++;
    } else if (t[i] == '>') { out += "&gt;"; i++; }
    else if (t[i] == '&') { out += "&amp;"; i++; }
    else out += t[i++];
  }
  return out;
}

/// True when the text contains one of the formatting tags the format actions insert. Only then is it sent as formatted text.
bool hasFormattingTag(const std::string& t) {
  static const char* tags[] = {"<b>", "<i>", "<u>", "<s>", "<code>", "<pre>", "<tg-spoiler>", "<a href=\""};
  for (const char* tg : tags) if (t.find(tg) != std::string::npos) return true;
  return false;
}

std::vector<std::int64_t> idsOf(const js::Value& d, const char* key) {
  std::vector<std::int64_t> ids;
  if (const js::Array* a = js::getArr(d, key))
    for (const auto& v : *a) ids.push_back(v.isStr() ? std::stoll(v.asStr()) : (std::int64_t)v.asNum());
  return ids;
}

}  // namespace

ChatSession::ChatSession(ServiceClient& svc, PremiumModel& premium, ChatSurface surface) : svc_(svc), premium_(premium), s_(std::move(surface)) {}

ChatSession::~ChatSession() { *alive_ = false; }

std::int64_t ChatSession::nowSeconds() const { return now ? now() : (std::int64_t)std::time(nullptr); }

TgMessage ChatSession::convert(const Message& m) {
  return TgAdapter::message(m, nowSeconds(), [this](std::int64_t id) { return message(id); });
}

const Message* ChatSession::message(std::int64_t id) const {
  auto it = cache_.find(id);
  return it == cache_.end() ? nullptr : &it->second;
}

void ChatSession::cacheAdd(const Message& m) { cache_[m.id] = m; }

void ChatSession::attach() {
  s_.composer->onCancelBanner.connect([this]() { replyTo_ = 0; editing_ = 0; });
  s_.composer->editor->onChanged.connect([this]() {
    if (s_.composer->editor->getText().empty()) { formatted_ = false; customEmoji_.clear(); }  // an emptied composer starts plain again
    if (!applyingRemote_) scheduleDraft();
  });
  s_.view->onReact.connect([this](long long id, std::string emoji, bool mine) {
    Reaction r;
    r.emoji = emoji;
    react(id, r, mine);
  });
  s_.view->onButtonMsg.connect([this](long long id, std::string data) { pressButton(id, data); });
  s_.view->onVote.connect([this](long long id, std::vector<int> v) { vote(id, v); });
  s_.view->onNeedNewer.connect([this](long long) { loadNewer(); });
  s_.view->onContext.connect([this](long long id, Point) { target_ = id; });
  s_.pinned->onJump.connect([this](long long id) { jumpTo(id); });
  s_.pinned->onClose.connect([this]() { s_.pinned->pins.clear(); if (s_.relayout) s_.relayout(); });
}

void ChatSession::applyDraftText(const std::string& text) {
  applyingRemote_ = true;
  s_.composer->editor->setText(text);
  applyingRemote_ = false;
}

void ChatSession::open(const Peer& p, int unread, const std::string& draft, bool loadHistory) {
  auto scope = svc_.scope(alive_);
  flushDraft();
  peer_ = p;
  cache_.clear();
  selected_.clear();
  replyTo_ = editing_ = 0;
  target_ = 0;
  unread_ = unread;
  formatted_ = false;
  customEmoji_.clear();
  botCommands_.clear();
  draftInFlight_ = draftDirty_ = false;
  s_.composer->banner.clear();
  s_.typing->who.clear();
  s_.pinned->pins.clear();
  applyDraftText(draft);
  loadInfo();
  loadPins();
  if (loadHistory) {
    s_.view->setMessages({}, true);
    s_.view->hasOlder = false;
    loadPage(p, 0, 30, [this, p](std::vector<TgMessage> page, bool more) {
      if (!(peer_ == p)) return;
      s_.view->setMessages(std::move(page), true);
      s_.view->hasOlder = more;
    });
  }
}

void ChatSession::reload() {
  if (!peer_.valid()) return;
  std::string typed = s_.composer->editor->getText();
  open(peer_, 0, typed, true);
}

void ChatSession::loadInfo() {
  Peer p = peer_;
  svc_.peerInfo(p, [this, p](PeerInfo i) {
    if (!(peer_ == p)) return;
    s_.header->name = i.name;
    s_.header->status = i.status;
    if (s_.profile) {
      s_.profile->name = i.name;
      s_.profile->status = i.status;
      s_.profile->fields->rows = {{"Username", i.username.empty() ? "" : "@" + i.username}, {"Phone", i.phone}, {"Bio", i.bio}};
    }
    if (s_.relayout) s_.relayout();
    if (i.isBot) {
      js::Object q;
      q["peer"] = p.toJson();
      svc_.request("load bot commands", "bot.commands", std::move(q), [this, p](const RpcResult& r) {
        if (!(peer_ == p)) return;
        botCommands_.clear();
        if (const js::Array* a = js::getArr(r.value, "commands"))
          for (const auto& c : *a) botCommands_.push_back({js::getStr(c, "command"), js::getStr(c, "description")});
      }, [](const RpcError&) {});
    }
  });
}

void ChatSession::loadPins() {
  Peer p = peer_;
  js::Object q;
  q["peer"] = p.toJson();
  svc_.request("load pinned messages", "messages.pinned", std::move(q), [this, p](const RpcResult& r) {
    if (!(peer_ == p)) return;
    s_.pinned->pins.clear();
    if (const js::Array* a = js::getArr(r.value, "messages")) {
      std::vector<Message> ms;
      for (const auto& e : *a) ms.push_back(Message::fromJson(e));
      std::reverse(ms.begin(), ms.end());  // newest first
      for (const auto& m : ms) { cacheAdd(m); s_.pinned->pins.push_back({m.id, m.text.empty() ? "[media]" : m.text}); }
    }
    s_.pinned->index = 0;
    if (s_.relayout) s_.relayout();
  }, [](const RpcError&) {});
}

void ChatSession::loadPage(const Peer& p, long long before, int n, std::function<void(std::vector<TgMessage>, bool)> done) {
  auto scope = svc_.scope(alive_);
  svc_.history(p, before, "older", n, [this, p, n, before, done](std::vector<Message> msgs) {
    if (!(peer_ == p)) return;
    for (const auto& m : msgs) cacheAdd(m);
    std::vector<TgMessage> out;
    for (const auto& m : msgs) out.push_back(convert(m));
    if (before == 0 && unread_ > 0 && (size_t)unread_ <= out.size()) out[out.size() - (size_t)unread_].firstUnread = true;
    done(std::move(out), (int)msgs.size() >= n);
  });
}

void ChatSession::loadNewer() {
  auto scope = svc_.scope(alive_);
  if (s_.view->msgs.empty()) { s_.view->loadingNewer = false; return; }
  Peer p = peer_;
  svc_.history(p, s_.view->msgs.back().id, "newer", 30, [this, p](std::vector<Message> msgs) {
    if (!(peer_ == p)) return;
    std::vector<TgMessage> out;
    for (const auto& m : msgs) { cacheAdd(m); out.push_back(convert(m)); }
    bool more = msgs.size() >= 30;
    s_.view->append(std::move(out), more);
    s_.view->unread = 0;
  });
}

void ChatSession::jumpTo(long long id) {
  auto scope = svc_.scope(alive_);
  if (s_.view->scrollToMessage(id)) return;
  Peer p = peer_;
  svc_.history(p, id + 1, "older", 30, [this, p, id](std::vector<Message> msgs) {
    if (!(peer_ == p)) return;
    std::vector<TgMessage> out;
    for (const auto& m : msgs) { cacheAdd(m); out.push_back(convert(m)); }
    bool more = msgs.size() >= 30;
    s_.view->setMessages(std::move(out), false);
    s_.view->hasOlder = more;
    s_.view->hasNewer = true;  // the page ends at the target; newer messages load when scrolling down
    s_.view->scrollToMessage(id);
  });
}

long long ChatSession::target() const {
  if (target_ != 0) return target_;
  return s_.view->msgs.empty() ? 0 : s_.view->msgs.back().id;
}

void ChatSession::send(const std::string& text) { sendInternal(text, 0); }
void ChatSession::sendScheduled(const std::string& text, std::int64_t when) { sendInternal(text, when); }

void ChatSession::sendInternal(const std::string& text, std::int64_t when) {
  auto scope = svc_.scope(alive_);
  if (!peer_.valid()) return;
  // "@bot some query" asks that inline bot instead of sending text (Telegram Desktop behaviour), when "bot" is a known bot username.
  if (text.size() > 2 && text[0] == '@' && editing_ == 0 && isBotUsername) {
    size_t sp = text.find(' ');
    if (sp != std::string::npos && sp > 1 && sp + 1 < text.size()) {
      std::string name = text.substr(1, sp - 1);
      if (isBotUsername(name)) { sendInline(name, text.substr(sp + 1)); return; }
    }
  }
  js::Object p;
  p["peer"] = peer_.toJson();
  bool fmt = hasFormattingTag(text);
  p["text"] = js::Value(fmt ? escapeKeepingTags(text) : text);
  if (fmt) p["format"] = js::Value("html");
  std::string feature;
  if (!customEmoji_.empty() && fmt) {
    // Entity offsets refer to the plain text; with markup in the message they cannot be computed, so the markup wins (documented).
    if (toast) toast("Custom emoji", "Custom emoji and formatting cannot be combined; the formatting was kept.");
  } else if (!customEmoji_.empty()) {
    js::Array ents;
    size_t from = 0;
    for (const auto& ce : customEmoji_) {
      size_t at = text.find(ce.first, from);
      if (at == std::string::npos) continue;
      js::Object e;
      e["type"] = js::Value("custom_emoji");
      e["offset"] = js::Value((double)utf16Len(text.substr(0, at)));
      e["length"] = js::Value((double)utf16Len(ce.first));
      e["document_id"] = js::id(ce.second);
      ents.push_back(js::Value(std::move(e)));
      from = at + ce.first.size();
    }
    if (!ents.empty()) { p["entities"] = js::Value(std::move(ents)); feature = "custom_emoji_message"; }
  }
  Peer peer = peer_;
  // A failed send must not lose what the user typed (FR-64): the text comes back into the empty composer and the reason is shown.
  auto onFail = [this, text](const RpcError& e) {
    if (e.code != ErrorCode::PremiumRequired && e.code != ErrorCode::Disconnected && toast) toast("Could not send message", e.text);
    if (s_.composer->editor->getText().empty()) applyDraftText(text);
  };
  if (editing_ != 0) {
    std::int64_t id = editing_;
    p["id"] = js::id(id);
    editing_ = 0;
    formatted_ = false;
    customEmoji_.clear();
    svc_.request("edit message", "messages.edit", std::move(p), [this, peer](const RpcResult& r) {
      if (!(peer_ == peer)) return;
      Message m = Message::fromJson(r.value);
      cacheAdd(m);
      replaceMessage(m);
    }, onFail, feature);
    return;
  }
  if (replyTo_ != 0) p["reply_to"] = js::id(replyTo_);
  if (when != 0) p["schedule"] = js::id(when);
  {  // the composer is emptied right after this call, so the draft on the server must be emptied as well
    static const std::string none;
    if (draftInFlight_) draftDirty_ = true; else sendDraftNow(&none);
  }
  replyTo_ = 0;
  formatted_ = false;
  customEmoji_.clear();
  svc_.request("send message", "messages.send", std::move(p), [this, peer, when](const RpcResult& r) {
    Message m = Message::fromJson(r.value);
    if (when != 0) { if (toast) toast("Scheduled", "The message will be sent at the chosen time."); return; }
    if (!(peer_ == peer)) return;
    cacheAdd(m);
    appendIfNew(m);
  }, onFail, feature);
}

void ChatSession::addCustomEmoji(const std::string& fallback, std::int64_t documentId) { customEmoji_.push_back({fallback, documentId}); }

void ChatSession::replyTo(long long id) {
  const Message* m = message(id);
  if (!m) return;
  replyTo_ = id;
  editing_ = 0;
  s_.composer->banner = "Reply to " + (m->senderName.empty() ? std::string("message") : m->senderName);
  if (s_.relayout) s_.relayout();
}

void ChatSession::editMessage(long long id) {
  const Message* m = message(id);
  if (!m || !m->outgoing) return;
  editing_ = id;
  replyTo_ = 0;
  s_.composer->banner = "Editing";
  applyingRemote_ = true;  // the edit text is not a draft
  s_.composer->editor->setText(m->text);
  applyingRemote_ = false;
  if (s_.relayout) s_.relayout();
}

void ChatSession::editLastOwn() {
  for (auto it = s_.view->msgs.rbegin(); it != s_.view->msgs.rend(); ++it)
    if (it->outgoing) { editMessage(it->id); return; }
}

void ChatSession::deleteMessage(long long id) { deleteMessages({id}, true); }

void ChatSession::deleteMessages(const std::vector<long long>& ids, bool revoke) {
  auto scope = svc_.scope(alive_);
  if (!peer_.valid() || ids.empty()) return;
  js::Object p;
  p["peer"] = peer_.toJson();
  js::Array a;
  for (long long id : ids) a.push_back(js::id(id));
  p["ids"] = js::Value(std::move(a));
  p["revoke"] = js::Value(revoke);
  svc_.request("delete messages", "messages.delete", std::move(p), [](const RpcResult&) {});
  for (long long id : ids) selected_.erase(id);
}

void ChatSession::deleteSelected() {
  std::vector<long long> ids(selected_.begin(), selected_.end());
  if (ids.empty() && target() != 0) ids.push_back(target());
  if (ids.empty()) return;
  if (requestDelete) requestDelete(ids); else deleteMessages(ids, true);
}

void ChatSession::toggleSelect(long long id) {
  if (id == 0) return;
  if (!selected_.erase(id)) selected_.insert(id);
  if (toast) toast("Selection", std::to_string(selected_.size()) + " message(s) selected");
}

void ChatSession::clearSelection() { selected_.clear(); }

const std::vector<Message*> ChatSession::selectedMessages() {
  std::vector<Message*> v;
  for (long long id : selected_) { auto it = cache_.find(id); if (it != cache_.end()) v.push_back(&it->second); }
  return v;
}

void ChatSession::react(long long id, const Reaction& r, bool add) {
  auto scope = svc_.scope(alive_);
  auto it = cache_.find(id);
  if (it == cache_.end()) return;
  std::vector<Reaction> mine;
  for (const auto& x : it->second.reactions) if (x.mine && !(x.emoji == r.emoji && x.customEmojiId == r.customEmojiId)) mine.push_back(x);
  if (add) mine.push_back(r);
  bool needsPremium = mine.size() > 1;
  std::string feature = needsPremium ? "extra_reactions" : "";
  if (r.isCustom() && add) { needsPremium = true; feature = "custom_emoji_reactions"; }
  if (needsPremium && premium_.state() == PremiumState::NotPremium) {
    premium_.use(feature, nullptr);  // shows the calm panel, nothing is sent (FR-63)
    replaceMessage(it->second);      // undo the local toggle of the chip
    return;
  }
  js::Object p;
  p["peer"] = peer_.toJson();
  p["id"] = js::id(id);
  js::Array rs;
  for (auto x : mine) { x.count = 1; x.mine = true; rs.push_back(x.toJson()); }
  p["reactions"] = js::Value(std::move(rs));
  Peer peer = peer_;
  svc_.request("react", "messages.react", std::move(p), [this, peer, id, r, add](const RpcResult&) {
    if (!(peer_ == peer)) return;
    auto cit = cache_.find(id);
    if (cit == cache_.end()) return;
    auto& rs2 = cit->second.reactions;
    auto same = [&](const Reaction& x) { return x.emoji == r.emoji && x.customEmojiId == r.customEmojiId; };
    auto found = std::find_if(rs2.begin(), rs2.end(), same);
    if (add && found == rs2.end()) { Reaction n = r; n.count = 1; n.mine = true; rs2.push_back(n); }
    else if (add) { found->mine = true; found->count++; }
    else if (found != rs2.end()) { found->mine = false; if (--found->count <= 0) rs2.erase(found); }
  }, [this, id](const RpcError&) {
    auto cit = cache_.find(id);
    if (cit != cache_.end()) replaceMessage(cit->second);  // the server refused: show the real state again
  }, feature);
}

void ChatSession::togglePin(long long id) {
  auto scope = svc_.scope(alive_);
  const Message* m = message(id);
  if (!m) return;
  bool on = !m->pinned;
  js::Object p;
  p["peer"] = peer_.toJson();
  p["id"] = js::id(id);
  p["on"] = js::Value(on);
  Peer peer = peer_;
  svc_.request(on ? "pin message" : "unpin message", "messages.pin", std::move(p), [this, peer, id, on](const RpcResult&) {
    if (!(peer_ == peer)) return;
    auto it = cache_.find(id);
    if (it != cache_.end()) it->second.pinned = on;
    loadPins();
  });
}

void ChatSession::vote(long long id, const std::vector<int>& options) {
  auto scope = svc_.scope(alive_);
  js::Object p;
  p["peer"] = peer_.toJson();
  p["id"] = js::id(id);
  js::Array o;
  for (int i : options) o.push_back(js::Value(std::to_string(i)));
  p["options"] = js::Value(std::move(o));
  svc_.request("vote", "messages.vote", std::move(p), [](const RpcResult&) {});
}

void ChatSession::pressButton(long long id, const std::string& data) {
  auto scope = svc_.scope(alive_);
  if (data.rfind("http", 0) == 0) { if (toast) toast("Link", data); return; }
  js::Object p;
  p["peer"] = peer_.toJson();
  p["id"] = js::id(id);
  p["data"] = js::Value(data);
  svc_.request("press button", "messages.click_button", std::move(p), [this](const RpcResult& r) {
    std::string a = js::getStr(r.value, "answer");
    if (!a.empty() && toast) toast("Bot", a);
  });
}

void ChatSession::sendSticker(const std::string& stickerId) {
  auto scope = svc_.scope(alive_);
  js::Object p;
  p["peer"] = peer_.toJson();
  p["sticker"] = js::Value(stickerId);
  Peer peer = peer_;
  svc_.request("send sticker", "messages.send_sticker", std::move(p), [this, peer](const RpcResult& r) {
    if (!(peer_ == peer)) return;
    Message m = Message::fromJson(r.value);
    cacheAdd(m);
    appendIfNew(m);
  }, {}, "premium_stickers");
}

void ChatSession::sendInline(const std::string& botName, const std::string& query) {
  auto scope = svc_.scope(alive_);
  js::Object p;
  p["bot"] = js::Value(botName);
  p["peer"] = peer_.toJson();
  p["query"] = js::Value(query);
  svc_.request("query inline bot", "bot.inline", std::move(p), [this](const RpcResult& r) {
    std::string qid = js::getStr(r.value, "query_id");
    const js::Array* a = js::getArr(r.value, "results");
    if (!a || a->empty()) { if (toast) toast("Inline bot", "No results"); return; }
    js::Object q;
    q["peer"] = peer_.toJson();
    q["query_id"] = js::Value(qid);
    q["result_id"] = js::Value(js::getStr((*a)[0], "id"));
    Peer peer = peer_;
    svc_.request("send inline result", "bot.inline_send", std::move(q), [this, peer](const RpcResult& rr) {
      if (!(peer_ == peer)) return;
      Message m = Message::fromJson(rr.value);
      cacheAdd(m);
      appendIfNew(m);
    });
  });
}

bool ChatSession::onMenu(const std::string& action, long long id) {
  target_ = id;
  if (action == "Reply") { replyTo(id); return true; }
  if (action == "React") { if (requestReactionPicker) requestReactionPicker(id); return true; }
  if (action == "Edit") { editMessage(id); return true; }
  if (action == "Delete") {
    std::vector<long long> ids;
    if (selected_.count(id)) ids.assign(selected_.begin(), selected_.end()); else ids.push_back(id);
    if (requestDelete) requestDelete(ids); else deleteMessages(ids, true);
    return true;
  }
  if (action == "Pin") { togglePin(id); return true; }
  if (action == "Select") { toggleSelect(id); return true; }
  if (action == "Forward") {
    std::vector<long long> ids(selected_.begin(), selected_.end());
    if (ids.empty()) ids.push_back(id);
    if (requestForward) requestForward(ids);
    return true;
  }
  if (action == "Copy") {
    std::string text;
    if (selected_.empty()) { if (const Message* m = message(id)) text = m->text; }
    else for (long long sid : selected_) if (const Message* m = message(sid)) text += (text.empty() ? "" : "\n") + m->text;
    if (copyToClipboard && !text.empty()) copyToClipboard(text);
    return true;
  }
  return false;
}

void ChatSession::appendIfNew(const Message& m) {
  if (!(m.peer == peer_)) return;
  for (const auto& e : s_.view->msgs) if (e.id == m.id) return;
  s_.view->append({convert(m)});
}

void ChatSession::replaceMessage(const Message& m) {
  for (auto& e : s_.view->msgs) if (e.id == m.id) { e = convert(m); s_.view->dirty = true; return; }
}

void ChatSession::removeMessages(const std::vector<std::int64_t>& ids) {
  auto& v = s_.view->msgs;
  v.erase(std::remove_if(v.begin(), v.end(), [&](const TgMessage& m) { return std::find(ids.begin(), ids.end(), m.id) != ids.end(); }), v.end());
  for (auto id : ids) { cache_.erase(id); selected_.erase(id); }
  s_.view->dirty = true;
}

void ChatSession::handleEvent(const Event& e) {
  auto scope = svc_.scope(alive_);
  if (!peer_.valid()) return;
  const js::Value& d = e.data;
  if (e.name == "message.new" || e.name == "message.edited") {
    const js::Value* mv = d.find("message");
    if (!mv) return;
    Message m = Message::fromJson(*mv);
    if (!(m.peer == peer_)) return;
    cacheAdd(m);
    if (e.name == "message.new") { appendIfNew(m); if (!m.outgoing) { js::Object p; p["peer"] = peer_.toJson(); svc_.request("mark read", "dialogs.mark_read", std::move(p), [](const RpcResult&) {}); } }
    else replaceMessage(m);
  } else if (e.name == "message.deleted") {
    const js::Value* pv = d.find("peer");
    if (!pv || !(Peer::fromJson(*pv) == peer_)) return;
    removeMessages(idsOf(d, "ids"));
  } else if (e.name == "message.read") {
    const js::Value* pv = d.find("peer");
    if (!pv || !(Peer::fromJson(*pv) == peer_) || !js::getBool(d, "outgoing")) return;
    std::int64_t maxId = js::getId(d, "max_id");
    for (auto& m : s_.view->msgs) if (m.outgoing && m.id <= maxId) m.state = 2;
    s_.view->dirty = true;
  } else if (e.name == "typing") {
    const js::Value* pv = d.find("peer");
    if (!pv || !(Peer::fromJson(*pv) == peer_)) return;
    s_.typing->who = js::getStr(d, "action").empty() ? "" : js::getStr(d, "name");
    if (s_.relayout) s_.relayout();
  } else if (e.name == "presence") {
    const js::Value* pv = d.find("peer");
    if (pv && Peer::fromJson(*pv) == peer_) s_.header->status = js::getStr(d, "status");
  } else if (e.name == "dialog.updated") {
    const js::Value* dv = d.find("dialog");
    if (!dv) return;
    Dialog nd = Dialog::fromJson(*dv);
    if (!(nd.peer == peer_)) return;
    // A draft written in another window of the same account shows up here (FR-73: windows stay in sync), unless we are typing.
    if (!draftInFlight_ && !draftDirty_ && !s_.composer->focused && editing_ == 0 && nd.draft != s_.composer->editor->getText()) applyDraftText(nd.draft);
  }
}

void ChatSession::scheduleDraft() {
  if (!peer_.valid() || editing_ != 0) return;
  if (draftInFlight_) { draftDirty_ = true; return; }  // coalesced: one request in flight, the latest text goes next
  sendDraftNow();
}

void ChatSession::sendDraftNow(const std::string* text) {
  auto scope = svc_.scope(alive_);
  draftInFlight_ = true;
  draftDirty_ = false;
  js::Object p;
  p["peer"] = peer_.toJson();
  p["text"] = js::Value(text ? *text : s_.composer->editor->getText());
  std::weak_ptr<bool> alive = alive_;
  svc_.request("save draft", "messages.draft", std::move(p), [this, alive](const RpcResult&) {
    auto a = alive.lock();
    if (!a || !*a) return;
    draftInFlight_ = false;
    if (draftDirty_) sendDraftNow();
  }, [this, alive](const RpcError&) {
    auto a = alive.lock();
    if (!a || !*a) return;
    draftInFlight_ = false;
  });
}

void ChatSession::flushDraft() {
  if (!peer_.valid() || draftInFlight_ || editing_ != 0) return;
  if (draftDirty_) sendDraftNow();
}

}  // namespace mologram::ui

namespace mologram::ui {

void ChatSession::insertTagPair(const std::string& open, const std::string& close) {
  markFormatted();
  s_.composer->insertText(open + close);
  auto& ed = *s_.composer->editor;
  ed.cx = std::max(0, ed.cx - (int)close.size());  // caret between the tags (cx is a byte index in the current line)
}

}  // namespace mologram::ui
39.5ms