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) {
275 prepareGeometryChange();
279 WrapColumnFinder finder(this);
280 while(finder.nextWrapColumn() > 0)
282 setHeight(lines * fontMetrics()->lineSpacing());
287 void ContentsChatItem::doLayout() {
288 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
289 if(!wrapList.count()) return; // empty chatitem
292 WrapColumnFinder finder(this);
293 layout()->beginLayout();
295 QTextLine line = layout()->createLine();
299 int col = finder.nextWrapColumn();
300 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
301 line.setPosition(QPointF(0, h));
302 h += fontMetrics()->lineSpacing();
304 layout()->endLayout();
307 // NOTE: This method is not threadsafe and not reentrant!
308 // (RegExps are not constant while matching, and they are static here for efficiency)
309 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
311 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
312 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#])");
314 static QRegExp regExp[] = {
316 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
317 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
320 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
321 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
323 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
326 static const int regExpCount = 2; // number of regexps in the array above
328 qint16 matches[] = { 0, 0, 0 };
329 qint16 matchEnd[] = { 0, 0, 0 };
331 QString str = data(ChatLineModel::DisplayRole).toString();
333 QList<Clickable> result;
340 minidx = str.length();
341 for(int i = 0; i < regExpCount; i++) {
342 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
343 if(idx >= matchEnd[i]) {
344 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
345 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
347 if(matches[i] >= 0 && matches[i] < minidx) {
353 idx = matchEnd[type];
354 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
355 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
357 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
362 if(!result.isEmpty()) qDebug() << str;
363 foreach(Clickable click, result) {
364 qDebug() << str.mid(click.start, click.length);
370 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
371 // mark a clickable if hovered upon
372 QVector<QTextLayout::FormatRange> fmt;
373 if(privateData()->currentClickable.isValid()) {
374 Clickable click = privateData()->currentClickable;
375 QTextLayout::FormatRange f;
376 f.start = click.start;
377 f.length = click.length;
378 f.format.setFontUnderline(true);
384 void ContentsChatItem::endHoverMode() {
385 if(hasPrivateData()) {
386 if(privateData()->currentClickable.isValid()) {
387 setCursor(Qt::ArrowCursor);
388 privateData()->currentClickable = Clickable();
395 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
396 privateData()->hasDragged = false;
397 ChatItem::mousePressEvent(event);
400 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
401 if(!event->buttons() && !privateData()->hasDragged) {
403 Clickable click = privateData()->currentClickable;
404 if(click.isValid()) {
405 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
408 if(!str.contains("://"))
409 str = "http://" + str;
410 QDesktopServices::openUrl(str);
412 case Clickable::Channel:
413 // TODO join or whatever...
420 ChatItem::mouseReleaseEvent(event);
423 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
424 // mouse move events always mean we're not hovering anymore...
426 // also, check if we have dragged the mouse
427 if(hasPrivateData() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
428 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
429 privateData()->hasDragged = true;
430 ChatItem::mouseMoveEvent(event);
433 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
438 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
439 bool onClickable = false;
440 qint16 idx = posToCursor(event->pos());
441 for(int i = 0; i < privateData()->clickables.count(); i++) {
442 Clickable click = privateData()->clickables.at(i);
443 if(idx >= click.start && idx < click.start + click.length) {
444 if(click.type == Clickable::Url) {
446 showWebPreview(click);
447 } else if(click.type == Clickable::Channel) {
448 // TODO: don't make clickable if it's our own name
449 //onClickable = true; //FIXME disabled for now
452 setCursor(Qt::PointingHandCursor);
453 privateData()->currentClickable = click;
459 if(!onClickable) endHoverMode();
463 void ContentsChatItem::showWebPreview(const Clickable &click) {
465 QTextLine line = layout()->lineForTextPosition(click.start);
466 qreal x = line.cursorToX(click.start);
467 qreal width = line.cursorToX(click.start + click.length) - x;
468 qreal height = line.height();
469 qreal y = height * line.lineNumber();
471 QPointF topLeft = scenePos() + QPointF(x, y);
472 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
474 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
475 if(!url.contains("://"))
476 url = "http://" + url;
477 chatScene()->loadWebPreview(this, url, urlRect);
481 void ContentsChatItem::clearWebPreview() {
483 chatScene()->clearWebPreview(this);
487 /*************************************************************************************************/
489 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
492 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
499 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
503 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
504 if(wordidx >= wrapList.count())
508 qreal targetWidth = lineCount * item->width() + choppedTrailing;
510 qint16 start = wordidx;
511 qint16 end = wrapList.count() - 1;
513 // check if the whole line fits
514 if(wrapList.at(end).endX <= targetWidth) // || start == end)
517 // check if we have a very long word that needs inter word wrap
518 if(wrapList.at(start).endX > targetWidth) {
519 if(!line.isValid()) {
520 layout = item->createLayout(QTextOption::NoWrap);
521 layout->beginLayout();
522 line = layout->createLine();
525 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
529 if(start + 1 == end) {
531 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
533 // both cases should be cought preliminary
534 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
535 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
537 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
538 return wrapList.at(wordidx).start;
541 qint16 pivot = (end + start) / 2;
542 if(wrapList.at(pivot).endX > targetWidth) {