1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include <QApplication>
23 #include <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
28 #include <QTextLayout>
31 #include "chatlinemodel.h"
33 #include "qtuistyle.h"
35 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
36 : QGraphicsItem(parent),
38 _boundingRect(0, 0, width, height),
39 _selectionMode(NoSelection),
42 setAcceptHoverEvents(true);
47 ChatItem::~ChatItem() {
51 QVariant ChatItem::data(int role) const {
52 QModelIndex index = model()->index(row(), column());
53 if(!index.isValid()) {
54 qWarning() << "ChatItem::data(): model index is invalid!" << index;
57 return model()->data(index, role);
60 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
61 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
64 option.setWrapMode(wrapMode);
65 option.setAlignment(alignment);
66 layout->setTextOption(option);
68 QList<QTextLayout::FormatRange> formatRanges
69 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
70 layout->setAdditionalFormats(formatRanges);
74 void ChatItem::updateLayout() {
76 setPrivateData(new ChatItemPrivate(createLayout()));
78 QTextLayout *layout_ = layout();
79 layout_->beginLayout();
80 QTextLine line = layout_->createLine();
82 line.setLineWidth(width());
83 line.setPosition(QPointF(0,0));
88 void ChatItem::clearLayout() {
93 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
94 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
95 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
96 Q_UNUSED(option); Q_UNUSED(widget);
99 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
100 //if(_selectionMode == FullSelection) {
102 //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
103 //painter->restore();
105 QVector<QTextLayout::FormatRange> formats = additionalFormats();
106 if(_selectionMode != NoSelection) {
107 QTextLayout::FormatRange selectFmt;
108 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
109 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
110 if(_selectionMode == PartialSelection) {
111 selectFmt.start = qMin(_selectionStart, _selectionEnd);
112 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
113 } else { // FullSelection
115 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
117 formats.append(selectFmt);
119 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
122 // uncomment partially or all of the following stuff:
124 // 0) alternativ painter color for debug stuff
126 // painter->setPen(Qt::red);
128 // painter->setPen(Qt::blue);
129 // 1) draw wordwrap points in the first line
130 // if(column() == 2) {
131 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
132 // foreach(ChatLineModel::Word word, wrapList) {
133 // if(word.endX > width())
135 // painter->drawLine(word.endX, 0, word.endX, height());
138 // 2) draw MsgId over the time column
139 // if(column() == 0) {
140 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
141 // QPointF bottomPoint = boundingRect().bottomLeft();
142 // bottomPoint.ry() -= 2;
143 // painter->drawText(bottomPoint, msgIdString);
145 // 3) draw bounding rect
146 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
149 qint16 ChatItem::posToCursor(const QPointF &pos) {
150 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
151 if(pos.y() < 0) return 0;
154 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
155 QTextLine line = layout()->lineAt(l);
156 if(pos.y() >= line.y()) {
157 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
163 void ChatItem::setFullSelection() {
164 if(_selectionMode != FullSelection) {
165 _selectionMode = FullSelection;
170 void ChatItem::clearSelection() {
171 _selectionMode = NoSelection;
175 void ChatItem::continueSelecting(const QPointF &pos) {
176 _selectionMode = PartialSelection;
177 _selectionEnd = posToCursor(pos);
181 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
182 QList<QRectF> resultList;
183 const QAbstractItemModel *model_ = model();
187 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
188 QList<int> indexList;
189 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
190 while(searchIdx != -1) {
191 indexList << searchIdx;
192 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
195 bool hadLayout = hasLayout();
199 foreach(int idx, indexList) {
200 QTextLine line = layout()->lineForTextPosition(idx);
201 qreal x = line.cursorToX(idx);
202 qreal width = line.cursorToX(idx + searchWord.count()) - x;
203 qreal height = line.height();
204 qreal y = height * line.lineNumber();
205 resultList << QRectF(x, y, width, height);
213 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
214 if(event->buttons() == Qt::LeftButton) {
215 chatScene()->setSelectingItem(this);
216 _selectionStart = _selectionEnd = posToCursor(event->pos());
217 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
225 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
226 if(event->buttons() == Qt::LeftButton) {
227 if(contains(event->pos())) {
228 qint16 end = posToCursor(event->pos());
229 if(end != _selectionEnd) {
231 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
236 chatScene()->startGlobalSelection(this, event->pos());
244 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
245 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
246 _selectionEnd = posToCursor(event->pos());
248 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
249 chatScene()->putToClipboard(selection);
256 // ************************************************************
258 // ************************************************************
260 // ************************************************************
262 // ************************************************************
263 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
264 : ChatItem(0, 0, pos, parent)
266 const QAbstractItemModel *model_ = model();
267 QModelIndex index = model_->index(row(), column());
268 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
270 setGeometryByWidth(width);
273 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
278 WrapColumnFinder finder(this);
279 while(finder.nextWrapColumn() > 0)
281 setHeight(lines * fontMetrics()->lineSpacing());
286 void ContentsChatItem::updateLayout() {
288 ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
289 setPrivateData(data);
293 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
294 if(!wrapList.count()) return; // empty chatitem
297 WrapColumnFinder finder(this);
298 layout()->beginLayout();
300 QTextLine line = layout()->createLine();
304 int col = finder.nextWrapColumn();
305 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
306 line.setPosition(QPointF(0, h));
307 h += fontMetrics()->lineSpacing();
309 layout()->endLayout();
312 // NOTE: This method is not threadsafe and not reentrant!
313 // (RegExps are not constant while matching, and they are static here for efficiency)
314 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
316 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
317 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
319 static QRegExp regExp[] = {
321 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
322 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
325 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
326 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
328 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
331 static const int regExpCount = 2; // number of regexps in the array above
333 qint16 matches[] = { 0, 0, 0 };
334 qint16 matchEnd[] = { 0, 0, 0 };
336 QString str = data(ChatLineModel::DisplayRole).toString();
338 QList<Clickable> result;
345 minidx = str.length();
346 for(int i = 0; i < regExpCount; i++) {
347 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
348 if(idx >= matchEnd[i]) {
349 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
350 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
352 if(matches[i] >= 0 && matches[i] < minidx) {
358 idx = matchEnd[type];
359 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
360 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
362 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
367 if(!result.isEmpty()) qDebug() << str;
368 foreach(Clickable click, result) {
369 qDebug() << str.mid(click.start, click.length);
375 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
376 // mark a clickable if hovered upon
377 QVector<QTextLayout::FormatRange> fmt;
378 if(privateData()->currentClickable.isValid()) {
379 Clickable click = privateData()->currentClickable;
380 QTextLayout::FormatRange f;
381 f.start = click.start;
382 f.length = click.length;
383 f.format.setFontUnderline(true);
389 void ContentsChatItem::endHoverMode() {
391 if(privateData()->currentClickable.isValid()) {
392 setCursor(Qt::ArrowCursor);
393 privateData()->currentClickable = Clickable();
400 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
401 privateData()->hasDragged = false;
402 ChatItem::mousePressEvent(event);
405 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
406 if(!event->buttons() && !privateData()->hasDragged) {
408 Clickable click = privateData()->currentClickable;
409 if(click.isValid()) {
410 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
413 if(!str.contains("://"))
414 str = "http://" + str;
415 QDesktopServices::openUrl(str);
417 case Clickable::Channel:
418 // TODO join or whatever...
425 ChatItem::mouseReleaseEvent(event);
428 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
429 // mouse move events always mean we're not hovering anymore...
431 // also, check if we have dragged the mouse
432 if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
433 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
434 privateData()->hasDragged = true;
435 ChatItem::mouseMoveEvent(event);
438 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
443 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
444 bool onClickable = false;
445 qint16 idx = posToCursor(event->pos());
446 for(int i = 0; i < privateData()->clickables.count(); i++) {
447 Clickable click = privateData()->clickables.at(i);
448 if(idx >= click.start && idx < click.start + click.length) {
449 if(click.type == Clickable::Url) {
451 showWebPreview(click);
452 } else if(click.type == Clickable::Channel) {
453 // TODO: don't make clickable if it's our own name
454 //onClickable = true; //FIXME disabled for now
457 setCursor(Qt::PointingHandCursor);
458 privateData()->currentClickable = click;
464 if(!onClickable) endHoverMode();
468 void ContentsChatItem::showWebPreview(const Clickable &click) {
473 QTextLine line = layout()->lineForTextPosition(click.start);
474 qreal x = line.cursorToX(click.start);
475 qreal width = line.cursorToX(click.start + click.length) - x;
476 qreal height = line.height();
477 qreal y = height * line.lineNumber();
479 QPointF topLeft = scenePos() + QPointF(x, y);
480 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
482 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
483 if(!url.contains("://"))
484 url = "http://" + url;
485 chatScene()->loadWebPreview(this, url, urlRect);
489 void ContentsChatItem::clearWebPreview() {
491 chatScene()->clearWebPreview(this);
495 /*************************************************************************************************/
497 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
500 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
507 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
511 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
512 if(wordidx >= wrapList.count())
516 qreal targetWidth = lineCount * item->width() + choppedTrailing;
518 qint16 start = wordidx;
519 qint16 end = wrapList.count() - 1;
521 // check if the whole line fits
522 if(wrapList.at(end).endX <= targetWidth) // || start == end)
525 // check if we have a very long word that needs inter word wrap
526 if(wrapList.at(start).endX > targetWidth) {
527 if(!line.isValid()) {
528 layout = item->createLayout(QTextOption::NoWrap);
529 layout->beginLayout();
530 line = layout->createLine();
533 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
537 if(start + 1 == end) {
539 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
541 // both cases should be cought preliminary
542 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
543 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
545 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
546 return wrapList.at(wordidx).start;
549 qint16 pivot = (end + start) / 2;
550 if(wrapList.at(pivot).endX > targetWidth) {