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 the following lines to draw the bounding rect and the row number in alternating colors
124 // painter->setPen(Qt::red);
126 // painter->setPen(Qt::blue);
127 // QString rowString = QString::number(row());
128 // QRect rowRect = painter->fontMetrics().boundingRect(rowString);
129 // QPointF topPoint = _boundingRect.topLeft();
130 // topPoint.ry() += rowRect.height();
131 // painter->drawText(topPoint, rowString);
132 // QPointF bottomPoint = _boundingRect.bottomRight();
133 // bottomPoint.rx() -= rowRect.width();
134 // painter->drawText(bottomPoint, rowString);
135 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
138 qint16 ChatItem::posToCursor(const QPointF &pos) {
139 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
140 if(pos.y() < 0) return 0;
143 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
144 QTextLine line = layout()->lineAt(l);
145 if(pos.y() >= line.y()) {
146 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
152 void ChatItem::setFullSelection() {
153 if(_selectionMode != FullSelection) {
154 _selectionMode = FullSelection;
159 void ChatItem::clearSelection() {
160 _selectionMode = NoSelection;
164 void ChatItem::continueSelecting(const QPointF &pos) {
165 _selectionMode = PartialSelection;
166 _selectionEnd = posToCursor(pos);
170 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
171 QList<QRectF> resultList;
172 const QAbstractItemModel *model_ = model();
176 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
177 QList<int> indexList;
178 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
179 while(searchIdx != -1) {
180 indexList << searchIdx;
181 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
184 bool hadLayout = hasLayout();
188 foreach(int idx, indexList) {
189 QTextLine line = layout()->lineForTextPosition(idx);
190 qreal x = line.cursorToX(idx);
191 qreal width = line.cursorToX(idx + searchWord.count()) - x;
192 qreal height = line.height();
193 qreal y = height * line.lineNumber();
194 resultList << QRectF(x, y, width, height);
202 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
203 if(event->buttons() == Qt::LeftButton) {
204 chatScene()->setSelectingItem(this);
205 _selectionStart = _selectionEnd = posToCursor(event->pos());
206 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
214 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
215 if(event->buttons() == Qt::LeftButton) {
216 if(contains(event->pos())) {
217 qint16 end = posToCursor(event->pos());
218 if(end != _selectionEnd) {
220 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
225 chatScene()->startGlobalSelection(this, event->pos());
233 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
234 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
235 _selectionEnd = posToCursor(event->pos());
237 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
238 chatScene()->putToClipboard(selection);
245 // ************************************************************
247 // ************************************************************
249 // ************************************************************
251 // ************************************************************
252 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
253 : ChatItem(0, 0, pos, parent)
255 const QAbstractItemModel *model_ = model();
256 QModelIndex index = model_->index(row(), column());
257 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
259 setGeometryByWidth(width);
262 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
267 WrapColumnFinder finder(this);
268 while(finder.nextWrapColumn() > 0)
270 setHeight(lines * fontMetrics()->lineSpacing());
275 void ContentsChatItem::updateLayout() {
277 ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
278 setPrivateData(data);
282 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
283 if(!wrapList.count()) return; // empty chatitem
286 WrapColumnFinder finder(this);
287 layout()->beginLayout();
289 QTextLine line = layout()->createLine();
293 int col = finder.nextWrapColumn();
294 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
295 line.setPosition(QPointF(0, h));
296 h += fontMetrics()->lineSpacing();
298 layout()->endLayout();
301 // NOTE: This method is not threadsafe and not reentrant!
302 // (RegExps are not constant while matching, and they are static here for efficiency)
303 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
305 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
306 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
308 static QRegExp regExp[] = {
310 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
311 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
314 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
315 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
317 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
320 static const int regExpCount = 2; // number of regexps in the array above
322 qint16 matches[] = { 0, 0, 0 };
323 qint16 matchEnd[] = { 0, 0, 0 };
325 QString str = data(ChatLineModel::DisplayRole).toString();
327 QList<Clickable> result;
334 minidx = str.length();
335 for(int i = 0; i < regExpCount; i++) {
336 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
337 if(idx >= matchEnd[i]) {
338 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
339 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
341 if(matches[i] >= 0 && matches[i] < minidx) {
347 idx = matchEnd[type];
348 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
349 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
351 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
356 if(!result.isEmpty()) qDebug() << str;
357 foreach(Clickable click, result) {
358 qDebug() << str.mid(click.start, click.length);
364 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
365 // mark a clickable if hovered upon
366 QVector<QTextLayout::FormatRange> fmt;
367 if(privateData()->currentClickable.isValid()) {
368 Clickable click = privateData()->currentClickable;
369 QTextLayout::FormatRange f;
370 f.start = click.start;
371 f.length = click.length;
372 f.format.setFontUnderline(true);
378 void ContentsChatItem::endHoverMode() {
380 if(privateData()->currentClickable.isValid()) {
381 setCursor(Qt::ArrowCursor);
382 privateData()->currentClickable = Clickable();
389 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
390 privateData()->hasDragged = false;
391 ChatItem::mousePressEvent(event);
394 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
395 if(!event->buttons() && !privateData()->hasDragged) {
397 Clickable click = privateData()->currentClickable;
398 if(click.isValid()) {
399 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
402 if(!str.contains("://"))
403 str = "http://" + str;
404 QDesktopServices::openUrl(str);
406 case Clickable::Channel:
407 // TODO join or whatever...
414 ChatItem::mouseReleaseEvent(event);
417 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
418 // mouse move events always mean we're not hovering anymore...
420 // also, check if we have dragged the mouse
421 if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
422 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
423 privateData()->hasDragged = true;
424 ChatItem::mouseMoveEvent(event);
427 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
432 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
433 bool onClickable = false;
434 qint16 idx = posToCursor(event->pos());
435 for(int i = 0; i < privateData()->clickables.count(); i++) {
436 Clickable click = privateData()->clickables.at(i);
437 if(idx >= click.start && idx < click.start + click.length) {
438 if(click.type == Clickable::Url) {
440 showWebPreview(click);
441 } else if(click.type == Clickable::Channel) {
442 // TODO: don't make clickable if it's our own name
443 //onClickable = true; //FIXME disabled for now
446 setCursor(Qt::PointingHandCursor);
447 privateData()->currentClickable = click;
453 if(!onClickable) endHoverMode();
457 void ContentsChatItem::showWebPreview(const Clickable &click) {
462 QTextLine line = layout()->lineForTextPosition(click.start);
463 qreal x = line.cursorToX(click.start);
464 qreal width = line.cursorToX(click.start + click.length) - x;
465 qreal height = line.height();
466 qreal y = height * line.lineNumber();
468 QPointF topLeft = scenePos() + QPointF(x, y);
469 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
471 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
472 if(!url.contains("://"))
473 url = "http://" + url;
474 chatScene()->loadWebPreview(this, url, urlRect);
478 void ContentsChatItem::clearWebPreview() {
480 chatScene()->clearWebPreview(this);
484 /*************************************************************************************************/
486 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
489 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
496 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
500 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
501 if(wordidx >= wrapList.count())
505 qreal targetWidth = lineCount * item->width() + choppedTrailing;
507 qint16 start = wordidx;
508 qint16 end = wrapList.count() - 1;
510 // check if the whole line fits
511 if(wrapList.at(end).endX <= targetWidth) // || start == end)
514 // check if we have a very long word that needs inter word wrap
515 if(wrapList.at(start).endX > targetWidth) {
516 if(!line.isValid()) {
517 layout = item->createLayout(QTextOption::NoWrap);
518 layout->beginLayout();
519 line = layout->createLine();
522 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
526 if(start + 1 == end) {
528 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
530 // both cases should be cought preliminary
531 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
532 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
534 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
535 return wrapList.at(wordidx).start;
538 qint16 pivot = (end + start) / 2;
539 if(wrapList.at(pivot).endX > targetWidth) {