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) const {
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::doLayout() {
75 QTextLayout *layout_ = layout();
76 layout_->beginLayout();
77 QTextLine line = layout_->createLine();
79 line.setLineWidth(width());
80 line.setPosition(QPointF(0,0));
85 void ChatItem::clearLayout() {
90 ChatItemPrivate *ChatItem::privateData() const {
92 ChatItem *that = const_cast<ChatItem *>(this);
93 that->_data = that->newPrivateData();
99 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
100 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
101 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
102 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 partially or all of the following stuff:
128 // 0) alternativ painter color for debug stuff
130 // painter->setPen(Qt::red);
132 // painter->setPen(Qt::blue);
133 // 1) draw wordwrap points in the first line
134 // if(column() == 2) {
135 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
136 // foreach(ChatLineModel::Word word, wrapList) {
137 // if(word.endX > width())
139 // painter->drawLine(word.endX, 0, word.endX, height());
142 // 2) draw MsgId over the time column
143 // if(column() == 0) {
144 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
145 // QPointF bottomPoint = boundingRect().bottomLeft();
146 // bottomPoint.ry() -= 2;
147 // painter->drawText(bottomPoint, msgIdString);
149 // 3) draw bounding rect
150 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
153 qint16 ChatItem::posToCursor(const QPointF &pos) {
154 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
155 if(pos.y() < 0) return 0;
156 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
157 QTextLine line = layout()->lineAt(l);
158 if(pos.y() >= line.y()) {
159 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
165 void ChatItem::setFullSelection() {
166 if(_selectionMode != FullSelection) {
167 _selectionMode = FullSelection;
172 void ChatItem::clearSelection() {
173 _selectionMode = NoSelection;
177 void ChatItem::continueSelecting(const QPointF &pos) {
178 _selectionMode = PartialSelection;
179 _selectionEnd = posToCursor(pos);
183 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
184 QList<QRectF> resultList;
185 const QAbstractItemModel *model_ = model();
189 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
190 QList<int> indexList;
191 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
192 while(searchIdx != -1) {
193 indexList << searchIdx;
194 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
197 bool hadPrivateData = hasPrivateData();
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::doLayout() {
287 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
288 if(!wrapList.count()) return; // empty chatitem
291 WrapColumnFinder finder(this);
292 layout()->beginLayout();
294 QTextLine line = layout()->createLine();
298 int col = finder.nextWrapColumn();
299 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
300 line.setPosition(QPointF(0, h));
301 h += fontMetrics()->lineSpacing();
303 layout()->endLayout();
306 // NOTE: This method is not threadsafe and not reentrant!
307 // (RegExps are not constant while matching, and they are static here for efficiency)
308 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
310 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
311 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
313 static QRegExp regExp[] = {
315 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
316 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
319 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
320 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
322 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
325 static const int regExpCount = 2; // number of regexps in the array above
327 qint16 matches[] = { 0, 0, 0 };
328 qint16 matchEnd[] = { 0, 0, 0 };
330 QString str = data(ChatLineModel::DisplayRole).toString();
332 QList<Clickable> result;
339 minidx = str.length();
340 for(int i = 0; i < regExpCount; i++) {
341 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
342 if(idx >= matchEnd[i]) {
343 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
344 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
346 if(matches[i] >= 0 && matches[i] < minidx) {
352 idx = matchEnd[type];
353 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
354 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
356 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
361 if(!result.isEmpty()) qDebug() << str;
362 foreach(Clickable click, result) {
363 qDebug() << str.mid(click.start, click.length);
369 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
370 // mark a clickable if hovered upon
371 QVector<QTextLayout::FormatRange> fmt;
372 if(privateData()->currentClickable.isValid()) {
373 Clickable click = privateData()->currentClickable;
374 QTextLayout::FormatRange f;
375 f.start = click.start;
376 f.length = click.length;
377 f.format.setFontUnderline(true);
383 void ContentsChatItem::endHoverMode() {
384 if(hasPrivateData()) {
385 if(privateData()->currentClickable.isValid()) {
386 setCursor(Qt::ArrowCursor);
387 privateData()->currentClickable = Clickable();
394 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
395 privateData()->hasDragged = false;
396 ChatItem::mousePressEvent(event);
399 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
400 if(!event->buttons() && !privateData()->hasDragged) {
402 Clickable click = privateData()->currentClickable;
403 if(click.isValid()) {
404 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
407 if(!str.contains("://"))
408 str = "http://" + str;
409 QDesktopServices::openUrl(str);
411 case Clickable::Channel:
412 // TODO join or whatever...
419 ChatItem::mouseReleaseEvent(event);
422 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
423 // mouse move events always mean we're not hovering anymore...
425 // also, check if we have dragged the mouse
426 if(hasPrivateData() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
427 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
428 privateData()->hasDragged = true;
429 ChatItem::mouseMoveEvent(event);
432 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
437 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
438 bool onClickable = false;
439 qint16 idx = posToCursor(event->pos());
440 for(int i = 0; i < privateData()->clickables.count(); i++) {
441 Clickable click = privateData()->clickables.at(i);
442 if(idx >= click.start && idx < click.start + click.length) {
443 if(click.type == Clickable::Url) {
445 showWebPreview(click);
446 } else if(click.type == Clickable::Channel) {
447 // TODO: don't make clickable if it's our own name
448 //onClickable = true; //FIXME disabled for now
451 setCursor(Qt::PointingHandCursor);
452 privateData()->currentClickable = click;
458 if(!onClickable) endHoverMode();
462 void ContentsChatItem::showWebPreview(const Clickable &click) {
464 QTextLine line = layout()->lineForTextPosition(click.start);
465 qreal x = line.cursorToX(click.start);
466 qreal width = line.cursorToX(click.start + click.length) - x;
467 qreal height = line.height();
468 qreal y = height * line.lineNumber();
470 QPointF topLeft = scenePos() + QPointF(x, y);
471 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
473 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
474 if(!url.contains("://"))
475 url = "http://" + url;
476 chatScene()->loadWebPreview(this, url, urlRect);
480 void ContentsChatItem::clearWebPreview() {
482 chatScene()->clearWebPreview(this);
486 /*************************************************************************************************/
488 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
491 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
498 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
502 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
503 if(wordidx >= wrapList.count())
507 qreal targetWidth = lineCount * item->width() + choppedTrailing;
509 qint16 start = wordidx;
510 qint16 end = wrapList.count() - 1;
512 // check if the whole line fits
513 if(wrapList.at(end).endX <= targetWidth) // || start == end)
516 // check if we have a very long word that needs inter word wrap
517 if(wrapList.at(start).endX > targetWidth) {
518 if(!line.isValid()) {
519 layout = item->createLayout(QTextOption::NoWrap);
520 layout->beginLayout();
521 line = layout->createLine();
524 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
528 if(start + 1 == end) {
530 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
532 // both cases should be cought preliminary
533 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
534 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
536 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
537 return wrapList.at(wordidx).start;
540 qint16 pivot = (end + start) / 2;
541 if(wrapList.at(pivot).endX > targetWidth) {