chatmessagedelegate.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. #include "chatmessagedelegate.h"
  2. #include "chatmessage.h"
  3. #include "thememanager.h"
  4. #include <QAbstractTextDocumentLayout>
  5. #include <QFontMetrics>
  6. #include <QPainter>
  7. #include <QPainterPath>
  8. #include <QTextDocument>
  9. #include <QTextLayout>
  10. ChatMessageDelegate::ChatMessageDelegate(QObject *parent)
  11. : QStyledItemDelegate(parent)
  12. , m_viewportWidth(600)
  13. {
  14. test.setWindowTitle("test ChatMessageDelegate");
  15. //test.show();
  16. }
  17. int ChatMessageDelegate::hitTestText(const QPoint &pos, const QString &text) const
  18. {
  19. QFont fn;
  20. QFontMetrics fm(fn);
  21. if (text.isEmpty() || pos.x() < 0 || pos.y() < 0)
  22. return -1;
  23. int maxWidth = viewportWidth() - 2 * ChatConstants::BUBBLE_PADDING - ChatConstants::AVATAR_SIZE
  24. - 2 * ChatConstants::BUBBLE_SPACING;
  25. // 使用QTextLayout计算文本布局
  26. QTextLayout textLayout(text);
  27. textLayout.setFont(QFont());
  28. QTextOption option;
  29. option.setWrapMode(QTextOption::WordWrap);
  30. option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
  31. textLayout.setTextOption(option);
  32. // 计算文本布局
  33. textLayout.beginLayout();
  34. int y = 0;
  35. int lineIndex = 0;
  36. QVector<QTextLine> lines;
  37. while (true) {
  38. QTextLine line = textLayout.createLine();
  39. if (!line.isValid())
  40. break;
  41. line.setLineWidth(maxWidth);
  42. int lineHeight = line.height();
  43. line.setPosition(QPointF(0, y));
  44. lines.append(line);
  45. y += lineHeight;
  46. lineIndex++;
  47. }
  48. textLayout.endLayout();
  49. // 查找点击位置对应的行和字符
  50. for (int i = 0; i < lines.size(); ++i) {
  51. QTextLine line = lines[i];
  52. QRectF lineRect(0, line.y(), line.width(), line.height());
  53. if (pos.y() >= lineRect.top() && pos.y() <= lineRect.bottom()) {
  54. // 找到了行,现在找字符位置
  55. int xPos = qBound(0, pos.x(), int(line.width()));
  56. return line.xToCursor(xPos);
  57. }
  58. }
  59. // 如果点击在最后一行之后,返回文本末尾
  60. if (pos.y() > y && !lines.isEmpty())
  61. return text.length();
  62. return -1;
  63. }
  64. void ChatMessageDelegate::paint(QPainter *painter,
  65. const QStyleOptionViewItem &option,
  66. const QModelIndex &index) const
  67. {
  68. painter->setRenderHint(QPainter::Antialiasing);
  69. painter->setRenderHint(QPainter::TextAntialiasing);
  70. const ChatMessage message = index.data().value<ChatMessage>();
  71. // 系统消息特殊处理
  72. if (message.type == MessageType::System) {
  73. drawSystemMessage(painter, option, message);
  74. return;
  75. }
  76. // 计算名字高度
  77. QFont nameFont = option.font;
  78. nameFont.setPointSize(std::max(option.font.pointSize() - 2, 8));
  79. QFontMetrics nameFm(nameFont);
  80. int nameHeight = message.senderName.isEmpty() ? 0 : nameFm.height();
  81. int nameSpacing = message.senderName.isEmpty() ? 0 : 2;
  82. // 计算各个元素的位置
  83. QSize textSize = calculateTextSize(option.fontMetrics, message.text);
  84. // 计算头像位置
  85. QRectF avatarRect;
  86. if (message.type == MessageType::Left) {
  87. avatarRect = QRectF(option.rect.left() + ChatConstants::BUBBLE_SPACING,
  88. option.rect.top() + nameHeight + nameSpacing,
  89. ChatConstants::AVATAR_SIZE,
  90. ChatConstants::AVATAR_SIZE);
  91. } else {
  92. avatarRect = QRectF(option.rect.right() - ChatConstants::AVATAR_SIZE
  93. - ChatConstants::BUBBLE_SPACING,
  94. option.rect.top() + nameHeight + nameSpacing,
  95. ChatConstants::AVATAR_SIZE,
  96. ChatConstants::AVATAR_SIZE);
  97. }
  98. // 计算气泡位置
  99. QRectF bubbleRect;
  100. if (message.type == MessageType::Left) {
  101. bubbleRect = QRectF(avatarRect.right() + ChatConstants::BUBBLE_SPACING,
  102. option.rect.top() + nameHeight + nameSpacing,
  103. textSize.width() + 2 * ChatConstants::BUBBLE_PADDING,
  104. textSize.height() + 2 * ChatConstants::BUBBLE_PADDING);
  105. } else {
  106. bubbleRect = QRectF(option.rect.right() - textSize.width()
  107. - 2 * ChatConstants::BUBBLE_PADDING - ChatConstants::AVATAR_SIZE
  108. - 2 * ChatConstants::BUBBLE_SPACING,
  109. option.rect.top() + nameHeight + nameSpacing,
  110. textSize.width() + 2 * ChatConstants::BUBBLE_PADDING,
  111. textSize.height() + 2 * ChatConstants::BUBBLE_PADDING);
  112. }
  113. // 绘制名字
  114. if (!message.senderName.isEmpty()) {
  115. painter->save();
  116. painter->setFont(nameFont);
  117. painter->setPen(QColor(120, 120, 120));
  118. int nameX, nameWidth;
  119. QRect nameRect;
  120. if (message.type == MessageType::Left) {
  121. // 左侧消息,名字左对齐,紧贴头像右侧
  122. nameX = avatarRect.right() + ChatConstants::BUBBLE_SPACING;
  123. nameWidth = bubbleRect.width();
  124. nameRect = QRect(nameX, option.rect.top(), nameWidth, nameHeight);
  125. painter->drawText(nameRect, Qt::AlignLeft | Qt::AlignVCenter, message.senderName);
  126. } else {
  127. // 右侧消息,名字右对齐,紧贴头像左侧
  128. nameWidth = nameFm.horizontalAdvance(message.senderName);
  129. // 名字宽度不超过气泡宽度
  130. nameWidth = std::min(nameWidth, static_cast<int>(bubbleRect.width()));
  131. nameX = bubbleRect.right() - nameWidth;
  132. nameRect = QRect(nameX, option.rect.top(), nameWidth, nameHeight);
  133. painter->drawText(nameRect, Qt::AlignRight | Qt::AlignVCenter, message.senderName);
  134. }
  135. painter->restore();
  136. }
  137. // 绘制气泡
  138. drawBubble(painter, bubbleRect, message.type == MessageType::Left);
  139. // 绘制头像
  140. drawAvatar(painter, avatarRect, message.avatar);
  141. // 绘制文本(带选择高亮)
  142. QRectF textRect = bubbleRect.adjusted(ChatConstants::BUBBLE_PADDING,
  143. ChatConstants::BUBBLE_PADDING,
  144. -ChatConstants::BUBBLE_PADDING,
  145. -ChatConstants::BUBBLE_PADDING);
  146. painter->setPen(ThemeManager::instance().color("colorText"));
  147. // 检查是否是当前选中的消息
  148. bool isCurrentMessage = (index == m_currentMessageIndex);
  149. drawTextWithSelection(painter, textRect, message.text, option.fontMetrics, isCurrentMessage);
  150. }
  151. QSize ChatMessageDelegate::sizeHint(const QStyleOptionViewItem &option,
  152. const QModelIndex &index) const
  153. {
  154. const ChatMessage message = index.data().value<ChatMessage>();
  155. QSize textSize = calculateTextSize(option.fontMetrics, message.text);
  156. // 系统消息特殊处理
  157. if (message.type == MessageType::System) {
  158. int width = qMin(textSize.width() + 2 * ChatConstants::BUBBLE_PADDING, viewportWidth() / 2);
  159. int height = textSize.height() + 2 * ChatConstants::BUBBLE_PADDING
  160. + ChatConstants::TIMESTAMP_HEIGHT + 2 * ChatConstants::BUBBLE_SPACING;
  161. return QSize(width, height);
  162. }
  163. // 计算名字高度
  164. QFont nameFont = option.font;
  165. nameFont.setPointSize(std::max(option.font.pointSize() - 2, 8));
  166. QFontMetrics nameFm(nameFont);
  167. int nameHeight = message.senderName.isEmpty() ? 0 : nameFm.height();
  168. int nameSpacing = message.senderName.isEmpty() ? 0 : 2;
  169. int width = textSize.width() + 2 * ChatConstants::BUBBLE_PADDING + ChatConstants::AVATAR_SIZE
  170. + 2 * ChatConstants::BUBBLE_SPACING;
  171. int height = qMax(textSize.height() + 2 * ChatConstants::BUBBLE_PADDING,
  172. ChatConstants::AVATAR_SIZE)
  173. + ChatConstants::TIMESTAMP_HEIGHT
  174. + nameHeight + nameSpacing;
  175. return QSize(qMin(width, viewportWidth()), height + ChatConstants::BUBBLE_SPACING);
  176. }
  177. void ChatMessageDelegate::setViewportWidth(int width)
  178. {
  179. m_viewportWidth = width - 2 * ChatConstants::BUBBLE_PADDING - ChatConstants::AVATAR_SIZE
  180. - 2 * ChatConstants::BUBBLE_SPACING;
  181. }
  182. void ChatMessageDelegate::drawBubble(QPainter *painter, const QRectF &rect, bool isLeft) const
  183. {
  184. QPainterPath path;
  185. path.addRoundedRect(rect, ChatConstants::BUBBLE_RADIUS, ChatConstants::BUBBLE_RADIUS);
  186. // 添加小三角
  187. const int triangleSize = 6;
  188. if (isLeft) {
  189. path.moveTo(rect.left(), rect.top() + ChatConstants::AVATAR_SIZE / 2 - triangleSize);
  190. path.lineTo(rect.left() - triangleSize, rect.top() + ChatConstants::AVATAR_SIZE / 2);
  191. path.lineTo(rect.left(), rect.top() + ChatConstants::AVATAR_SIZE / 2 + triangleSize);
  192. } else {
  193. path.moveTo(rect.right(), rect.top() + ChatConstants::AVATAR_SIZE / 2 - triangleSize);
  194. path.lineTo(rect.right() + triangleSize, rect.top() + ChatConstants::AVATAR_SIZE / 2);
  195. path.lineTo(rect.right(), rect.top() + ChatConstants::AVATAR_SIZE / 2 + triangleSize);
  196. }
  197. // 设置气泡颜色
  198. if (isLeft) {
  199. painter->fillPath(path, ThemeManager::instance().color("colorFillQuaternary"));
  200. } else {
  201. painter->fillPath(path, ThemeManager::instance().color("colorPrimaryBg"));
  202. }
  203. }
  204. void ChatMessageDelegate::drawAvatar(QPainter *painter,
  205. const QRectF &rect,
  206. const QString &avatarPath) const
  207. {
  208. // 检查缓存中是否已有头像
  209. if (!m_avatarCache.contains(avatarPath)) {
  210. QPixmap avatar(avatarPath);
  211. if (!avatar.isNull()) {
  212. avatar = avatar.scaled(ChatConstants::AVATAR_SIZE,
  213. ChatConstants::AVATAR_SIZE,
  214. Qt::KeepAspectRatio,
  215. Qt::SmoothTransformation);
  216. const_cast<ChatMessageDelegate *>(this)->m_avatarCache.insert(avatarPath, avatar);
  217. }
  218. }
  219. // 创建圆形裁剪区域
  220. QPainterPath path;
  221. path.addEllipse(rect);
  222. painter->setClipPath(path);
  223. if (m_avatarCache.contains(avatarPath)) {
  224. // 绘制缓存的头像
  225. painter->drawPixmap(rect.toRect(), m_avatarCache[avatarPath]);
  226. } else {
  227. // 绘制默认头像
  228. painter->setPen(Qt::NoPen);
  229. painter->setBrush(ThemeManager::instance().color("colorFill"));
  230. painter->drawEllipse(rect);
  231. }
  232. painter->setClipping(false);
  233. }
  234. void ChatMessageDelegate::drawSystemMessage(QPainter *painter,
  235. const QStyleOptionViewItem &option,
  236. const ChatMessage &message) const
  237. {
  238. // 为系统消息单独计算文本大小
  239. int maxWidth = viewportWidth() / (2.0 / 3.0);
  240. // 使用QTextDocument计算系统消息的实际大小
  241. QFont font = painter->font();
  242. int size = font.pointSize();
  243. font.setPointSize(std::max(size - 2, 8));
  244. QTextDocument doc;
  245. doc.setDefaultFont(font);
  246. doc.setDocumentMargin(0);
  247. doc.setTextWidth(maxWidth - 2 * ChatConstants::BUBBLE_PADDING);
  248. doc.setHtml(message.text.toHtmlEscaped().replace("\n", "<br>"));
  249. QSize textSize(doc.idealWidth(), doc.size().height());
  250. // 系统消息居中显示
  251. int bubbleWidth = qMin(textSize.width() + 2 * ChatConstants::BUBBLE_PADDING, maxWidth);
  252. // 计算气泡位置(居中)
  253. QRectF bubbleRect(option.rect.left() + (option.rect.width() - bubbleWidth) / 2,
  254. option.rect.top() + ChatConstants::BUBBLE_SPACING,
  255. bubbleWidth,
  256. textSize.height() + 2 * ChatConstants::BUBBLE_PADDING);
  257. // 绘制系统消息气泡(使用特殊样式)
  258. QPainterPath path;
  259. path.addRoundedRect(bubbleRect, ChatConstants::BUBBLE_RADIUS, ChatConstants::BUBBLE_RADIUS);
  260. // 使用半透明灰色背景
  261. painter->fillPath(path, QColor(200, 200, 200, 60));
  262. // 绘制文本
  263. QRectF textRect = bubbleRect.adjusted(ChatConstants::BUBBLE_PADDING,
  264. ChatConstants::BUBBLE_PADDING,
  265. -ChatConstants::BUBBLE_PADDING,
  266. -ChatConstants::BUBBLE_PADDING);
  267. // 使用特殊颜色
  268. painter->setPen(QColor(255, 0, 0));
  269. QTextCharFormat defaultFormat;
  270. defaultFormat.setForeground(ThemeManager::instance().color("colorText"));
  271. QTextCursor cursor(&doc);
  272. cursor.select(QTextCursor::Document);
  273. cursor.mergeCharFormat(defaultFormat);
  274. painter->save();
  275. painter->translate(textRect.topLeft());
  276. doc.drawContents(painter);
  277. painter->restore();
  278. // // // 绘制时间戳
  279. // QRectF timestampRect(bubbleRect.left(),
  280. // bubbleRect.bottom(),
  281. // bubbleRect.width(),
  282. // ChatConstants::TIMESTAMP_HEIGHT);
  283. // painter->setPen(ThemeManager::instance().color("colorTextSecondary"));
  284. // painter->setFont(QFont(option.font.family(), option.font.pointSize() - 2));
  285. // painter->drawText(timestampRect, Qt::AlignCenter, message.timestamp.toString("HH:mm"));
  286. }
  287. // 添加绘制带选择的文本方法
  288. void ChatMessageDelegate::drawTextWithSelection(QPainter *painter,
  289. const QRectF &rect,
  290. const QString &text,
  291. const QFontMetrics &fm,
  292. bool isCurrentMessage) const
  293. {
  294. // 如果不是当前消息或没有选择,直接绘制文本
  295. // 使用QTextDocument绘制多行文本
  296. QTextDocument doc;
  297. doc.setDefaultFont(painter->font());
  298. doc.setDocumentMargin(0);
  299. doc.setTextWidth(rect.width());
  300. doc.setHtml(text.toHtmlEscaped().replace("\n", "<br>"));
  301. // 设置默认文本格式(应用主题颜色)
  302. QTextCharFormat defaultFormat;
  303. defaultFormat.setForeground(ThemeManager::instance().color("colorText"));
  304. if (!isCurrentMessage || m_selectionStart < 0 || m_selectionEnd < 0
  305. || m_selectionStart == m_selectionEnd) {
  306. // 将普通文本转换为HTML,保留换行符
  307. QString htmlText = text.toHtmlEscaped().replace("\n", "<br>");
  308. doc.setHtml(htmlText);
  309. // 应用默认格式到整个文档
  310. QTextCursor cursor(&doc);
  311. cursor.select(QTextCursor::Document);
  312. cursor.mergeCharFormat(defaultFormat);
  313. painter->save();
  314. painter->translate(rect.topLeft());
  315. painter->setPen(ThemeManager::instance().color("colorText"));
  316. doc.drawContents(painter);
  317. painter->restore();
  318. return;
  319. }
  320. // 确保选择范围有效
  321. int start = qMin(m_selectionStart, m_selectionEnd);
  322. int end = qMax(m_selectionStart, m_selectionEnd);
  323. if (start >= text.length() || end <= 0) {
  324. QString htmlText = text.toHtmlEscaped().replace("\n", "<br>");
  325. doc.setHtml(htmlText);
  326. // 应用默认格式到整个文档
  327. QTextCursor cursor(&doc);
  328. cursor.select(QTextCursor::Document);
  329. cursor.mergeCharFormat(defaultFormat);
  330. painter->save();
  331. painter->translate(rect.topLeft());
  332. painter->setPen(ThemeManager::instance().color("colorText"));
  333. doc.drawContents(painter);
  334. painter->restore();
  335. return;
  336. }
  337. // 限制选择范围在文本长度内
  338. start = qMax(0, start);
  339. end = qMin(text.length(), end);
  340. // 将普通文本转换为HTML,保留换行符
  341. QString htmlText = text.toHtmlEscaped().replace("\n", "<br>");
  342. doc.setHtml(htmlText);
  343. // 首先应用默认格式到整个文档
  344. QTextCursor cursor(&doc);
  345. cursor.select(QTextCursor::Document);
  346. cursor.mergeCharFormat(defaultFormat);
  347. // 设置选择格式
  348. cursor.setPosition(start);
  349. cursor.setPosition(end, QTextCursor::KeepAnchor);
  350. QTextCharFormat selectionFormat;
  351. selectionFormat.setBackground(QColor(0, 120, 215, 128)); // 半透明蓝色背景
  352. selectionFormat.setForeground(Qt::white); // 白色文本
  353. cursor.mergeCharFormat(selectionFormat);
  354. // 绘制文本
  355. painter->save();
  356. painter->translate(rect.topLeft());
  357. doc.drawContents(painter);
  358. painter->restore();
  359. }
  360. QSize ChatMessageDelegate::calculateTextSize(const QFontMetrics &fm, const QString &text) const
  361. {
  362. int maxWidth = viewportWidth() - 2 * ChatConstants::BUBBLE_PADDING - ChatConstants::AVATAR_SIZE
  363. - 2 * ChatConstants::BUBBLE_SPACING;
  364. QRect textRect = fm.boundingRect(0,
  365. 0,
  366. maxWidth,
  367. INT_MAX,
  368. Qt::TextWordWrap | Qt::AlignLeft | Qt::AlignVCenter,
  369. text);
  370. return textRect.size();
  371. }
  372. int ChatMessageDelegate::getPositionFromPoint(const QPoint &pos,
  373. const QString &text,
  374. const QFontMetrics &fm)
  375. {
  376. if (text.isEmpty() || pos.x() < 0 || pos.y() < 0)
  377. return -1;
  378. int maxWidth = viewportWidth() - 2 * ChatConstants::BUBBLE_PADDING;
  379. // 使用QTextDocument处理多行文本
  380. QTextDocument doc;
  381. doc.setDefaultFont(QFont());
  382. doc.setDocumentMargin(0);
  383. doc.setTextWidth(maxWidth - 52); // AVATAR_SIZE + BUBBLE_PADDING
  384. doc.setHtml(text.toHtmlEscaped().replace("\n", "<br>"));
  385. test.setDocument(&doc);
  386. // 获取点击位置对应的文本位置
  387. QAbstractTextDocumentLayout *layout = doc.documentLayout();
  388. int position = layout->hitTest(pos, Qt::FuzzyHit);
  389. return position;
  390. }