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),
279 // data->clickables = findClickables();
280 setPrivateData(data);
284 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
285 if(!wrapList.count()) return; // empty chatitem
288 WrapColumnFinder finder(this);
289 layout()->beginLayout();
291 QTextLine line = layout()->createLine();
295 int col = finder.nextWrapColumn();
296 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
297 line.setPosition(QPointF(0, h));
298 h += fontMetrics()->lineSpacing();
300 layout()->endLayout();
303 // NOTE: This method is not threadsafe and not reentrant!
304 // (RegExps are not constant while matching, and they are static here for efficiency)
305 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
307 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
308 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
310 static QRegExp regExp[] = {
312 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
313 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
316 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
317 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
319 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
322 static const int regExpCount = 2; // number of regexps in the array above
324 qint16 matches[] = { 0, 0, 0 };
325 qint16 matchEnd[] = { 0, 0, 0 };
327 QString str = data(ChatLineModel::DisplayRole).toString();
329 QList<Clickable> result;
336 minidx = str.length();
337 for(int i = 0; i < regExpCount; i++) {
338 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
339 if(idx >= matchEnd[i]) {
340 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
341 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
343 if(matches[i] >= 0 && matches[i] < minidx) {
349 idx = matchEnd[type];
350 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
351 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
353 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
358 if(!result.isEmpty()) qDebug() << str;
359 foreach(Clickable click, result) {
360 qDebug() << str.mid(click.start, click.length);
366 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
367 // mark a clickable if hovered upon
368 QVector<QTextLayout::FormatRange> fmt;
369 if(privateData()->currentClickable.isValid()) {
370 Clickable click = privateData()->currentClickable;
371 QTextLayout::FormatRange f;
372 f.start = click.start;
373 f.length = click.length;
374 f.format.setFontUnderline(true);
380 void ContentsChatItem::endHoverMode() {
381 if(privateData()->currentClickable.isValid()) {
382 setCursor(Qt::ArrowCursor);
383 privateData()->currentClickable = Clickable();
388 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
389 privateData()->hasDragged = false;
390 ChatItem::mousePressEvent(event);
393 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
394 if(!event->buttons() && !privateData()->hasDragged) {
396 Clickable click = privateData()->currentClickable;
397 if(click.isValid()) {
398 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
401 QDesktopServices::openUrl(str);
403 case Clickable::Channel:
404 // TODO join or whatever...
411 ChatItem::mouseReleaseEvent(event);
414 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
415 // mouse move events always mean we're not hovering anymore...
417 // also, check if we have dragged the mouse
418 if(!privateData()->hasDragged && event->buttons() & Qt::LeftButton
419 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
420 privateData()->hasDragged = true;
421 ChatItem::mouseMoveEvent(event);
424 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
429 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
430 bool onClickable = false;
431 qint16 idx = posToCursor(event->pos());
432 for(int i = 0; i < privateData()->clickables.count(); i++) {
433 Clickable click = privateData()->clickables.at(i);
434 if(idx >= click.start && idx < click.start + click.length) {
435 if(click.type == Clickable::Url)
437 else if(click.type == Clickable::Channel) {
438 // TODO: don't make clickable if it's our own name
439 //onClickable = true; //FIXME disabled for now
442 setCursor(Qt::PointingHandCursor);
443 privateData()->currentClickable = click;
449 if(!onClickable) endHoverMode();
453 /*************************************************************************************************/
455 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
458 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
465 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
469 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
470 if(wordidx >= wrapList.count())
474 qreal targetWidth = lineCount * item->width() + choppedTrailing;
476 qint16 start = wordidx;
477 qint16 end = wrapList.count() - 1;
479 // check if the whole line fits
480 if(wrapList.at(end).endX <= targetWidth) // || start == end)
483 // check if we have a very long word that needs inter word wrap
484 if(wrapList.at(start).endX > targetWidth) {
485 if(!line.isValid()) {
486 layout = item->createLayout(QTextOption::NoWrap);
487 layout->beginLayout();
488 line = layout->createLine();
491 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
495 if(start + 1 == end) {
497 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
499 // both cases should be cought preliminary
500 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
501 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
503 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
504 return wrapList.at(wordidx).start;
507 qint16 pivot = (end + start) / 2;
508 if(wrapList.at(pivot).endX > targetWidth) {