Keep ordinary channel drafts until their correlated save result
This commit is contained in:
1 parent
6511946a17
commit
b39cd735cd
2 files changed
+50
-41
No files matched your search
@@ -38,6 +38,8 @@ extern "C" {
|
||||
#include "mem.h"
|
||||
}
|
||||
|
||||
quint64 InputBar::s_submissionSequence = 0;
|
||||
|
||||
static bool isImageFile(const QString& suffix) {
|
||||
QString s = suffix.toLower();
|
||||
return s == "jpg" || s == "jpeg" || s == "png" || s == "gif" ||
|
||||
@@ -255,7 +257,7 @@ void InputBar::setReply(const QByteArray& messageId, const QString& author, cons
|
||||
if (m_dmMode || messageId.size() != 32 || m_channelIdForRecord.isEmpty()) {
|
||||
GUI_ERROR("reply: invalid composer target/key bytes=%d", int(messageId.size())); return;
|
||||
}
|
||||
++m_replyGeneration; m_replyTo = messageId; m_replyFailed = false;
|
||||
++m_replyGeneration; m_replyTo = messageId; m_submissionFailed = false;
|
||||
m_replyLabel->setText(author.simplified() + "\n" + preview.simplified());
|
||||
m_replyPreview->show(); m_input->setFocus();
|
||||
GUI_DEBUG("reply: selected ch=%s id=%s generation=%llu", qPrintable(m_channelIdForRecord),
|
||||
@@ -265,21 +267,22 @@ void InputBar::setReply(const QByteArray& messageId, const QString& author, cons
|
||||
void InputBar::clearReply() {
|
||||
if (!m_replyTo.isEmpty()) GUI_DEBUG("reply: cleared ch=%s generation=%llu", qPrintable(m_channelIdForRecord),
|
||||
(unsigned long long)m_replyGeneration);
|
||||
++m_replyGeneration; m_replyTo.clear(); m_replyFailed = false; m_replyPreview->hide();
|
||||
++m_replyGeneration; m_replyTo.clear(); m_submissionFailed = false; m_replyPreview->hide();
|
||||
}
|
||||
|
||||
bool InputBar::replySending() const {
|
||||
for (const auto& pending : m_pendingReplies) if (pending.generation == m_replyGeneration) return true;
|
||||
bool InputBar::submissionPending() const {
|
||||
for (const auto& pending : m_pendingSubmissions)
|
||||
if (pending.generation == m_replyGeneration && pending.target == m_channelIdForRecord) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Каждая часть отправки (текст/вложение) имеет собственное подтверждение и снимок черновика. */
|
||||
quint64 InputBar::beginReplySend(const QByteArray& reply, quint64 generation, const QString& target,
|
||||
/* Канальный текст и каждая часть ответа имеют собственное подтверждение и снимок черновика. */
|
||||
quint64 InputBar::beginSubmission(const QByteArray& reply, quint64 generation, const QString& target,
|
||||
const QString& text, const QString& source) {
|
||||
if (reply.isEmpty()) return 0;
|
||||
const quint64 request = ++m_submissionSequence;
|
||||
m_pendingReplies.insert(request, {generation, target, text, source, m_input->document()->revision(), m_attachmentRevision});
|
||||
GUI_DEBUG("reply: submit ch=%s id=%s request=%llu", qPrintable(target), reply.toHex().constData(), (unsigned long long)request);
|
||||
if (reply.isEmpty() && (m_dmMode || text.isEmpty())) return 0;
|
||||
const quint64 request = ++s_submissionSequence;
|
||||
m_pendingSubmissions.insert(request, {generation, target, text, source, m_input->document()->revision(), m_attachmentRevision});
|
||||
GUI_DEBUG("send: pending ch=%s reply=%s request=%llu", qPrintable(target), reply.toHex().constData(), (unsigned long long)request);
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -293,24 +296,24 @@ void InputBar::submissionResult(quint64 request, bool success) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!request || !m_pendingReplies.contains(request)) return;
|
||||
const auto pending = m_pendingReplies.take(request);
|
||||
GUI_DEBUG("reply: result ch=%s request=%llu success=%d", qPrintable(pending.target), (unsigned long long)request, success);
|
||||
if (!request || !m_pendingSubmissions.contains(request)) return;
|
||||
const auto pending = m_pendingSubmissions.take(request);
|
||||
GUI_DEBUG("send: result ch=%s request=%llu success=%d", qPrintable(pending.target), (unsigned long long)request, success);
|
||||
if (pending.generation != m_replyGeneration || pending.target != m_channelIdForRecord) return;
|
||||
if (!success) {
|
||||
m_replyFailed = true;
|
||||
GUI_ERROR("reply: submission failed ch=%s request=%llu", qPrintable(pending.target), (unsigned long long)request);
|
||||
emit attachmentRejected(QCoreApplication::translate("ChatGui", "Could not send reply. Please try again."));
|
||||
m_submissionFailed = true;
|
||||
GUI_ERROR("send: submission failed ch=%s request=%llu", qPrintable(pending.target), (unsigned long long)request);
|
||||
emit attachmentRejected(QCoreApplication::translate("ChatGui", "Could not send message. Please try again."));
|
||||
return;
|
||||
}
|
||||
if (!pending.text.isEmpty() && pending.textRevision == m_input->document()->revision()) m_input->clear();
|
||||
if (!pending.source.isEmpty() && pending.attachmentRevision == m_attachmentRevision) clearPendingAttachment();
|
||||
if (!replySending() && !m_replyFailed && m_input->toPlainText().isEmpty() && m_pendingAttachSrc.isEmpty()) clearReply();
|
||||
if (!submissionPending() && !m_submissionFailed && m_input->toPlainText().isEmpty() && m_pendingAttachSrc.isEmpty()) clearReply();
|
||||
}
|
||||
|
||||
/* Черновик и выбранный ответ восстанавливаются после сохранения/отмены. Вложения остаются в composer. */
|
||||
void InputBar::editMessage(const QByteArray& id, quint64 version, const QString& text) {
|
||||
if (m_dmMode || id.size() != 32 || !version || m_editRequest || replySending() || m_pttActive) {
|
||||
if (m_dmMode || id.size() != 32 || !version || m_editRequest || submissionPending() || m_pttActive) {
|
||||
GUI_WARN("edit: composer busy/invalid target=%s", qPrintable(m_channelIdForRecord)); return;
|
||||
}
|
||||
if (!m_editId.isEmpty()) cancelEdit();
|
||||
@@ -441,17 +444,19 @@ void InputBar::adjustInputHeight() {
|
||||
}
|
||||
|
||||
void InputBar::onSendClicked() {
|
||||
if (!isEnabled()) { GUI_WARN("send: composer unavailable target=%s", qPrintable(m_channelIdForRecord)); return; }
|
||||
if (!isEnabled() || m_channelIdForRecord.isEmpty()) {
|
||||
GUI_WARN("send: composer unavailable target=%s", qPrintable(m_channelIdForRecord)); return;
|
||||
}
|
||||
if (!m_editId.isEmpty()) {
|
||||
const QString text = m_input->toPlainText();
|
||||
if (m_editRequest || text.isEmpty()) return;
|
||||
m_editRequest = ++m_submissionSequence; m_input->setReadOnly(true);
|
||||
m_editRequest = ++s_submissionSequence; m_input->setReadOnly(true);
|
||||
emit saveEdit(m_channelIdForRecord, m_editId, m_editVersion, text, m_editRequest); return;
|
||||
}
|
||||
if (replySending()) {
|
||||
GUI_WARN("reply: submission still pending ch=%s", qPrintable(m_channelIdForRecord)); return;
|
||||
if (submissionPending()) {
|
||||
GUI_WARN("send: submission still pending ch=%s", qPrintable(m_channelIdForRecord)); return;
|
||||
}
|
||||
m_replyFailed = false;
|
||||
m_submissionFailed = false;
|
||||
const QByteArray reply = m_replyTo;
|
||||
QString text = m_input->toPlainText();
|
||||
while (!text.isEmpty() && (text.back() == ' ' || text.back() == '\t'))
|
||||
@@ -461,7 +466,7 @@ void InputBar::onSendClicked() {
|
||||
if (!hasAttach && text.isEmpty()) return;
|
||||
|
||||
if (hasAttach) {
|
||||
const quint64 requestId = beginReplySend(reply, m_replyGeneration, m_channelIdForRecord, {}, m_pendingAttachSrc);
|
||||
const quint64 requestId = beginSubmission(reply, m_replyGeneration, m_channelIdForRecord, {}, m_pendingAttachSrc);
|
||||
const bool encrypted = !m_dmMode && m_encryptCheck->isChecked();
|
||||
if (encrypted) {
|
||||
auto* request = (struct attachment_send_req*)u_calloc(1, sizeof(struct attachment_send_req));
|
||||
@@ -508,9 +513,11 @@ void InputBar::onSendClicked() {
|
||||
if (reply.isEmpty()) clearPendingAttachment();
|
||||
}
|
||||
if (!text.isEmpty()) {
|
||||
const quint64 request = beginReplySend(reply, m_replyGeneration, m_channelIdForRecord, text);
|
||||
const quint64 request = beginSubmission(reply, m_replyGeneration, m_channelIdForRecord, text);
|
||||
QPointer<InputBar> alive(this);
|
||||
emit sendMessage(text, reply, request);
|
||||
if (reply.isEmpty()) m_input->clear();
|
||||
if (!alive) return;
|
||||
if (!request) m_input->clear();
|
||||
if (m_emojiPanel) m_emojiPanel->hide();
|
||||
m_input->setFocus();
|
||||
}
|
||||
@@ -570,14 +577,14 @@ void InputBar::setMediaEnabled(bool enabled) {
|
||||
void InputBar::onPttPressed() {
|
||||
if (!m_editId.isEmpty()) { GUI_WARN("voice: blocked while editing"); return; }
|
||||
if (!isEnabled() || m_channelIdForRecord.isEmpty()) { GUI_WARN("voice: composer unavailable"); return; }
|
||||
if (replySending()) { GUI_WARN("reply: recording blocked while submission pending"); return; }
|
||||
if (submissionPending()) { GUI_WARN("send: recording blocked while submission pending"); return; }
|
||||
if (!m_recorder || !m_recorder->isInitialized()) return;
|
||||
m_recorder->startRecording();
|
||||
m_pttActive = m_recorder->isRecording();
|
||||
if (!m_pttActive) { DEBUG_WARN(DEBUG_CATEGORY_MEDIA, "voice recording did not start; composer remains idle"); return; }
|
||||
m_recordTarget = m_channelIdForRecord;
|
||||
m_recordDmGeneration = m_dmGeneration;
|
||||
m_recordReply = m_replyTo; m_recordReplyGeneration = m_replyGeneration; m_replyFailed = false;
|
||||
m_recordReply = m_replyTo; m_recordReplyGeneration = m_replyGeneration; m_submissionFailed = false;
|
||||
m_pttBtn->setStyleSheet(m_pttBtn->styleSheet() +
|
||||
"QPushButton { background: #e74c3c; border-radius: 4px; }");
|
||||
}
|
||||
@@ -606,7 +613,7 @@ void InputBar::onPttReleased() {
|
||||
request->dm_generation = m_recordDmGeneration;
|
||||
if (!m_recorder->takeRecording(request)) { u_free(request); return; }
|
||||
if (m_recordReply.size() == 32) memcpy(request->reply_to, m_recordReply.constData(), 32);
|
||||
request->request_id = beginReplySend(m_recordReply, m_recordReplyGeneration, m_recordTarget);
|
||||
request->request_id = beginSubmission(m_recordReply, m_recordReplyGeneration, m_recordTarget);
|
||||
emit submitAttachment(m_recordTarget, request);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* GUI-composer канала/PM: текст, emoji, ответ/редактирование, голосовая запись и preview одного вложения.
|
||||
* Сам не отправляет данные в сеть: владелец обрабатывает сигналы в GUI и передаёт работу ядру.
|
||||
* Для submitAttachment нужен ровно один обработчик, принимающий request вместе с PCM/compressor даже при отказе.
|
||||
* Ответы/правки ждут submissionResult; обычный текст и вложение без reply очищаются сразу после сигнала отправки.
|
||||
* Канальный текст/ответы/правки ждут submissionResult; PM-текст и вложение без reply очищаются сразу после сигнала отправки.
|
||||
* emojiPanel/recorder заимствованы, могут быть nullptr и должны жить во время использования; остальные виджеты — дочерние. */
|
||||
#pragma once
|
||||
|
||||
@@ -52,7 +52,7 @@ public:
|
||||
* PM/пустая цель/неверный ключ отклоняются; edit сначала отменяется. Новый ответ имеет собственное поколение. */
|
||||
void setReply(const QByteArray& messageId, const QString& author, const QString& preview);
|
||||
void clearReply(); // Снять ответ и сменить поколение; текст/preview вложения не очищаются, старые результаты не применяются.
|
||||
/* Подтвердить правку либо одну часть ответа по request; 0/неизвестный ID игнорируется.
|
||||
/* Подтвердить канальный текст, правку либо одну часть ответа по request; 0/неизвестный ID игнорируется.
|
||||
* Ошибка сохраняет черновик и показывает отказ. Успех очищает лишь неизменённую ревизию текста/вложения;
|
||||
* ответ снимается после успеха всех частей и очистки черновика. Старое поколение/другая цель не затрагиваются. */
|
||||
void submissionResult(quint64 request, bool success);
|
||||
@@ -63,7 +63,7 @@ public:
|
||||
|
||||
signals:
|
||||
/* Текст текущего контекста; справа удалены только пробелы/табуляции. replyTo пуст либо ключ 32 байта.
|
||||
* request ненулевой для ответа, 0 для обычной отправки; владелец должен обработать текущую цель синхронно. */
|
||||
* request ненулевой для канала (включая обычный текст), 0 для PM; обработчик фиксирует текущую цель синхронно. */
|
||||
void sendMessage(const QString &text, const QByteArray& replyTo, quint64 request);
|
||||
/* Снимок правки: channel/id/version/text и ненулевой request; ввод read-only до результата/отмены. */
|
||||
void saveEdit(const QString& channel, const QByteArray& id, quint64 version, const QString& text, quint64 request);
|
||||
@@ -85,7 +85,7 @@ protected:
|
||||
void resizeEvent(QResizeEvent* event) override; // Выравнивает overlay записи по геометрии текстового поля.
|
||||
|
||||
private slots:
|
||||
void onSendClicked(); // Edit либо вложение и текст отдельными сигналами; повтор текущего pending reply блокируется.
|
||||
void onSendClicked(); // Edit либо вложение и текст отдельными сигналами; повтор текущей pending отправки блокируется.
|
||||
void adjustInputHeight(); // От 1 до 12 строк, дальше включает вертикальную прокрутку с сохранением видимости курсора.
|
||||
void onPttPressed(); // Запускает recorder и фиксирует target/generation/reply только при успешном старте.
|
||||
void onPttReleased(); // Stop; запись от 500 мс передаётся через takeRecording/submitAttachment, меньшая отбрасывается.
|
||||
@@ -97,16 +97,17 @@ private slots:
|
||||
|
||||
private:
|
||||
static QString formatFileSize(qint64 bytes); // Человекочитаемые B/KB/MB/GB, шаг 1024; bytes ожидается неотрицательным.
|
||||
struct PendingReply {
|
||||
quint64 generation; // Поколение выбранного ответа на момент отправки этой части.
|
||||
struct PendingSubmission {
|
||||
quint64 generation; // Ревизия выбора ответа/контекста на момент отправки этой части.
|
||||
QString target, text, source; // Собственные снимки цели и отправленного текста/исходника; одна из частей может быть пустой.
|
||||
int textRevision; // QTextDocument::revision для защиты нового/изменённого черновика от позднего success.
|
||||
quint64 attachmentRevision; // Ревизия preview для такой же защиты выбранного файла.
|
||||
};
|
||||
/* Создать запись подтверждения части ответа, вернуть ненулевой ID; без reply вернуть 0 и ничего не запоминать. */
|
||||
quint64 beginReplySend(const QByteArray& reply, quint64 generation, const QString& target,
|
||||
/* Запомнить канальный текст либо часть ответа; ID общий для всех composer, чтобы late result не попал новой форме.
|
||||
* Для PM-текста и вложения без reply вернуть 0 и ничего не запоминать. */
|
||||
quint64 beginSubmission(const QByteArray& reply, quint64 generation, const QString& target,
|
||||
const QString& text = {}, const QString& source = {});
|
||||
bool replySending() const; // Есть хотя бы одна ожидающая часть именно текущего поколения ответа.
|
||||
bool submissionPending() const; // Есть ожидающая часть текущего контекста/выбора ответа.
|
||||
QByteArray m_editId, m_savedReply; // Ключ редактируемого сообщения и ответ обычного черновика, сохранённый на время edit.
|
||||
QString m_savedText, m_savedReplyLabel; // Обычный текст/подпись ответа для cancelEdit или успешного сохранения.
|
||||
quint64 m_editVersion = 0, m_editRequest = 0; // Ожидаемая версия и ненулевой ID pending save; 0 — нет запроса.
|
||||
@@ -114,10 +115,11 @@ private:
|
||||
QWidget* m_replyPreview = nullptr; // Общий preview ответа или режима edit.
|
||||
QLabel* m_replyLabel = nullptr; // Plain text автора/цитаты либо подписи edit.
|
||||
QByteArray m_replyTo, m_recordReply; // Выбранный ответ и его снимок для начатой голосовой записи.
|
||||
quint64 m_replyGeneration = 0, m_recordReplyGeneration = 0, m_submissionSequence = 0; // Поколения ответов и общий счётчик request ID.
|
||||
bool m_replyFailed = false; // Хотя бы одна часть текущего ответа получила отказ; ответ не снимается при успехе другой части.
|
||||
quint64 m_replyGeneration = 0, m_recordReplyGeneration = 0; // Поколения текущего выбора и ответа голосовой записи.
|
||||
static quint64 s_submissionSequence; // GUI-only: общий для всех InputBar счётчик request ID, включая edit.
|
||||
bool m_submissionFailed = false; // Хотя бы одна часть получила отказ; ответ не снимается при успехе другой части.
|
||||
quint64 m_attachmentRevision = 0; // Меняется при замене/очистке preview, не зависит от совпадения пути файла.
|
||||
QHash<quint64, PendingReply> m_pendingReplies; // request ID → ожидающая часть; чужие поколения удаляются при получении результата.
|
||||
QHash<quint64, PendingSubmission> m_pendingSubmissions; // ID → ожидающая часть; чужие поколения удаляются при получении результата.
|
||||
|
||||
QTextEdit *m_input; // Plain-text поле и focusProxy composer.
|
||||
QPushButton *m_emojiBtn; // Переключает видимость заимствованной панели, если она есть.
|
||||
|
||||
Reference in new issue
Block a user