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, ChatLineModel::ColumnType col, QGraphicsItem *parent)
36 : QGraphicsItem(parent),
38 _boundingRect(0, 0, width, height),
40 _selectionMode(NoSelection),
43 const QAbstractItemModel *model_ = model();
44 QModelIndex index = model_->index(row(), col);
45 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
46 setAcceptHoverEvents(true);
51 ChatItem::~ChatItem() {
55 QVariant ChatItem::data(int role) const {
56 QModelIndex index = model()->index(row(), column());
57 if(!index.isValid()) {
58 qWarning() << "ChatItem::data(): model index is invalid!" << index;
61 return model()->data(index, role);
64 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
65 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
68 option.setWrapMode(wrapMode);
69 option.setAlignment(alignment);
70 layout->setTextOption(option);
72 QList<QTextLayout::FormatRange> formatRanges
73 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
74 layout->setAdditionalFormats(formatRanges);
78 void ChatItem::updateLayout() {
80 setPrivateData(new ChatItemPrivate(createLayout()));
82 QTextLayout *layout_ = layout();
83 layout_->beginLayout();
84 QTextLine line = layout_->createLine();
86 line.setLineWidth(width());
87 line.setPosition(QPointF(0,0));
92 void ChatItem::clearLayout() {
97 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
98 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
99 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
100 Q_UNUSED(option); Q_UNUSED(widget);
103 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
104 //if(_selectionMode == FullSelection) {
106 //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
107 //painter->restore();
109 QVector<QTextLayout::FormatRange> formats = additionalFormats();
110 if(_selectionMode != NoSelection) {
111 QTextLayout::FormatRange selectFmt;
112 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
113 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
114 if(_selectionMode == PartialSelection) {
115 selectFmt.start = qMin(_selectionStart, _selectionEnd);
116 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
117 } else { // FullSelection
119 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
121 formats.append(selectFmt);
123 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
126 // uncomment the following lines to draw the bounding rect and the row number in alternating colors
128 // painter->setPen(Qt::red);
130 // painter->setPen(Qt::blue);
131 // QString rowString = QString::number(row());
132 // QRect rowRect = painter->fontMetrics().boundingRect(rowString);
133 // QPointF topPoint = _boundingRect.topLeft();
134 // topPoint.ry() += rowRect.height();
135 // painter->drawText(topPoint, rowString);
136 // QPointF bottomPoint = _boundingRect.bottomRight();
137 // bottomPoint.rx() -= rowRect.width();
138 // painter->drawText(bottomPoint, rowString);
139 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
142 qint16 ChatItem::posToCursor(const QPointF &pos) {
143 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
144 if(pos.y() < 0) return 0;
147 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
148 QTextLine line = layout()->lineAt(l);
149 if(pos.y() >= line.y()) {
150 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
156 void ChatItem::setFullSelection() {
157 if(_selectionMode != FullSelection) {
158 _selectionMode = FullSelection;
163 void ChatItem::clearSelection() {
164 _selectionMode = NoSelection;
168 void ChatItem::continueSelecting(const QPointF &pos) {
169 _selectionMode = PartialSelection;
170 _selectionEnd = posToCursor(pos);
174 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
175 QList<QRectF> resultList;
176 const QAbstractItemModel *model_ = model();
180 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
181 QList<int> indexList;
182 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
183 while(searchIdx != -1) {
184 indexList << searchIdx;
185 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
191 foreach(int idx, indexList) {
192 QTextLine line = layout()->lineForTextPosition(idx);
193 qreal x = line.cursorToX(idx);
194 qreal width = line.cursorToX(idx + searchWord.count()) - x;
195 qreal height = fontMetrics()->lineSpacing();
196 qreal y = height * line.lineNumber();
197 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, column(), parent)
255 setGeometryByWidth(width);
258 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
263 WrapColumnFinder finder(this);
264 while(finder.nextWrapColumn() > 0)
266 setHeight(lines * fontMetrics()->lineSpacing());
271 void ContentsChatItem::updateLayout() {
273 ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere),
275 // data->clickables = findClickables();
276 setPrivateData(data);
280 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
281 if(!wrapList.count()) return; // empty chatitem
284 WrapColumnFinder finder(this);
285 layout()->beginLayout();
287 QTextLine line = layout()->createLine();
291 int col = finder.nextWrapColumn();
292 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
293 line.setPosition(QPointF(0, h));
294 h += fontMetrics()->lineSpacing();
296 layout()->endLayout();
299 // NOTE: This method is not threadsafe and not reentrant!
300 // (RegExps are not constant while matching, and they are static here for efficiency)
301 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
303 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
304 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
306 static QRegExp regExp[] = {
308 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
309 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
312 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
313 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
315 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
318 static const int regExpCount = 2; // number of regexps in the array above
320 qint16 matches[] = { 0, 0, 0 };
321 qint16 matchEnd[] = { 0, 0, 0 };
323 QString str = data(ChatLineModel::DisplayRole).toString();
325 QList<Clickable> result;
332 minidx = str.length();
333 for(int i = 0; i < regExpCount; i++) {
334 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
335 if(idx >= matchEnd[i]) {
336 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
337 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
339 if(matches[i] >= 0 && matches[i] < minidx) {
345 idx = matchEnd[type];
346 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
347 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
349 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
354 if(!result.isEmpty()) qDebug() << str;
355 foreach(Clickable click, result) {
356 qDebug() << str.mid(click.start, click.length);
362 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
363 // mark a clickable if hovered upon
364 QVector<QTextLayout::FormatRange> fmt;
365 if(privateData()->currentClickable.isValid()) {
366 Clickable click = privateData()->currentClickable;
367 QTextLayout::FormatRange f;
368 f.start = click.start;
369 f.length = click.length;
370 f.format.setFontUnderline(true);
376 void ContentsChatItem::endHoverMode() {
377 if(privateData()->currentClickable.isValid()) {
378 setCursor(Qt::ArrowCursor);
379 privateData()->currentClickable = Clickable();
384 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
385 privateData()->hasDragged = false;
386 ChatItem::mousePressEvent(event);
389 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
390 if(!event->buttons() && !privateData()->hasDragged) {
392 Clickable click = privateData()->currentClickable;
393 if(click.isValid()) {
394 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
397 QDesktopServices::openUrl(str);
399 case Clickable::Channel:
400 // TODO join or whatever...
407 ChatItem::mouseReleaseEvent(event);
410 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
411 // mouse move events always mean we're not hovering anymore...
413 // also, check if we have dragged the mouse
414 if(!privateData()->hasDragged && event->buttons() & Qt::LeftButton
415 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
416 privateData()->hasDragged = true;
417 ChatItem::mouseMoveEvent(event);
420 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
425 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
426 bool onClickable = false;
427 qint16 idx = posToCursor(event->pos());
428 for(int i = 0; i < privateData()->clickables.count(); i++) {
429 Clickable click = privateData()->clickables.at(i);
430 if(idx >= click.start && idx < click.start + click.length) {
431 if(click.type == Clickable::Url)
433 else if(click.type == Clickable::Channel) {
434 // TODO: don't make clickable if it's our own name
435 //onClickable = true; //FIXME disabled for now
438 setCursor(Qt::PointingHandCursor);
439 privateData()->currentClickable = click;
445 if(!onClickable) endHoverMode();
449 /*************************************************************************************************/
451 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
454 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
464 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
468 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
469 if(wordidx >= wrapList.count())
473 qreal targetWidth = lineCount * item->width() + choppedTrailing;
475 qint16 start = wordidx;
476 qint16 end = wrapList.count() - 1;
478 // check if the whole line fits
479 if(wrapList.at(end).endX <= targetWidth || start == end)
486 const ChatLineModel::Word &prevWord = wrapList.at(wordidx - 1);
487 choppedTrailing += prevWord.trailing - (targetWidth - prevWord.endX);
489 return wrapList.at(wordidx).start;
491 qint16 pivot = (end + start) / 2;
492 if(wrapList.at(pivot).endX > targetWidth && wordidx != pivot) {