Note to self: a QSet is not ordered.
[quassel.git] / src / qtui / chatitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include <QApplication>
22 #include <QClipboard>
23 #include <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QPainter>
27 #include <QPalette>
28 #include <QTextLayout>
29
30 #include "chatitem.h"
31 #include "chatlinemodel.h"
32 #include "qtui.h"
33 #include "qtuistyle.h"
34
35 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
36   : QGraphicsItem(parent),
37     _data(0),
38     _boundingRect(0, 0, width, height),
39     _selectionMode(NoSelection),
40     _selectionStart(-1)
41 {
42   setAcceptHoverEvents(true);
43   setZValue(20);
44   setPos(pos);
45 }
46
47 ChatItem::~ChatItem() {
48   delete _data;
49 }
50
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;
55     return QVariant();
56   }
57   return model()->data(index, role);
58 }
59
60 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
61   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
62
63   QTextOption option;
64   option.setWrapMode(wrapMode);
65   option.setAlignment(alignment);
66   layout->setTextOption(option);
67
68   QList<QTextLayout::FormatRange> formatRanges
69          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
70   layout->setAdditionalFormats(formatRanges);
71   return layout;
72 }
73
74 void ChatItem::doLayout() {
75   QTextLayout *layout_ = layout();
76   layout_->beginLayout();
77   QTextLine line = layout_->createLine();
78   if(line.isValid()) {
79     line.setLineWidth(width());
80     line.setPosition(QPointF(0,0));
81   }
82   layout_->endLayout();
83 }
84
85 void ChatItem::clearLayout() {
86   delete _data;
87   _data = 0;
88 }
89
90 ChatItemPrivate *ChatItem::privateData() const {
91   if(!_data) {
92     ChatItem *that = const_cast<ChatItem *>(this);
93     that->_data = that->newPrivateData();
94     that->doLayout();
95   }
96   return _data;
97 }
98
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) {
105     //painter->save();
106     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
107     //painter->restore();
108   //}
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
118       selectFmt.start = 0;
119       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
120     }
121     formats.append(selectFmt);
122   }
123   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
124
125   // Debuging Stuff
126   // uncomment partially or all of the following stuff:
127   //
128   // 0) alternativ painter color for debug stuff
129 //   if(row() % 2)
130 //     painter->setPen(Qt::red);
131 //   else
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())
138 //      break;
139 //       painter->drawLine(word.endX, 0, word.endX, height());
140 //     }
141 //   }
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);
148 //   }
149   // 3) draw bounding rect
150 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
151 }
152
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);
160     }
161   }
162   return 0;
163 }
164
165 void ChatItem::setFullSelection() {
166   if(_selectionMode != FullSelection) {
167     _selectionMode = FullSelection;
168     update();
169   }
170 }
171
172 void ChatItem::clearSelection() {
173   _selectionMode = NoSelection;
174   update();
175 }
176
177 void ChatItem::continueSelecting(const QPointF &pos) {
178   _selectionMode = PartialSelection;
179   _selectionEnd = posToCursor(pos);
180   update();
181 }
182
183 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
184   QList<QRectF> resultList;
185   const QAbstractItemModel *model_ = model();
186   if(!model_)
187     return resultList;
188
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);
195   }
196
197   bool hadPrivateData = hasPrivateData();
198
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);
206   }
207
208   if(!hadPrivateData)
209     clearLayout();
210   return resultList;
211 }
212
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
218     update();
219     event->accept();
220   } else {
221     event->ignore();
222   }
223 }
224
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) {
230         _selectionEnd = end;
231         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
232         update();
233       }
234     } else {
235       setFullSelection();
236       chatScene()->startGlobalSelection(this, event->pos());
237     }
238     event->accept();
239   } else {
240     event->ignore();
241   }
242 }
243
244 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
245   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
246     _selectionEnd = posToCursor(event->pos());
247     QString selection
248         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
249     chatScene()->putToClipboard(selection);
250     event->accept();
251   } else {
252     event->ignore();
253   }
254 }
255
256 // ************************************************************
257 // SenderChatItem
258 // ************************************************************
259
260 // ************************************************************
261 // ContentsChatItem
262 // ************************************************************
263 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
264   : ChatItem(0, 0, pos, parent)
265 {
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);
269
270   setGeometryByWidth(width);
271 }
272
273 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
274   if(w != width()) {
275     setWidth(w);
276     // compute height
277     int lines = 1;
278     WrapColumnFinder finder(this);
279     while(finder.nextWrapColumn() > 0)
280       lines++;
281     setHeight(lines * fontMetrics()->lineSpacing());
282   }
283   return height();
284 }
285
286 void ContentsChatItem::doLayout() {
287   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
288   if(!wrapList.count()) return; // empty chatitem
289
290   qreal h = 0;
291   WrapColumnFinder finder(this);
292   layout()->beginLayout();
293   forever {
294     QTextLine line = layout()->createLine();
295     if(!line.isValid())
296       break;
297
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();
302   }
303   layout()->endLayout();
304 }
305
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 {
309   // For matching URLs
310   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
311   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
312
313   static QRegExp regExp[] = {
314     // URL
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)),
317
318     // Channel name
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")
321
322     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
323   };
324
325   static const int regExpCount = 2;  // number of regexps in the array above
326
327   qint16 matches[] = { 0, 0, 0 };
328   qint16 matchEnd[] = { 0, 0, 0 };
329
330   QString str = data(ChatLineModel::DisplayRole).toString();
331
332   QList<Clickable> result;
333   qint16 idx = 0;
334   qint16 minidx;
335   int type = -1;
336
337   do {
338     type = -1;
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();
345       }
346       if(matches[i] >= 0 && matches[i] < minidx) {
347         minidx = matches[i];
348         type = i;
349       }
350     }
351     if(type >= 0) {
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]--;
355       }
356       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
357     }
358   } while(type >= 0);
359
360   /* testing
361   if(!result.isEmpty()) qDebug() << str;
362   foreach(Clickable click, result) {
363     qDebug() << str.mid(click.start, click.length);
364   }
365   */
366   return result;
367 }
368
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);
378     fmt.append(f);
379   }
380   return fmt;
381 }
382
383 void ContentsChatItem::endHoverMode() {
384   if(hasPrivateData()) {
385     if(privateData()->currentClickable.isValid()) {
386       setCursor(Qt::ArrowCursor);
387       privateData()->currentClickable = Clickable();
388     }
389     clearWebPreview();
390     update();
391   }
392 }
393
394 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
395   privateData()->hasDragged = false;
396   ChatItem::mousePressEvent(event);
397 }
398
399 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
400   if(!event->buttons() && !privateData()->hasDragged) {
401     // got a click
402     Clickable click = privateData()->currentClickable;
403     if(click.isValid()) {
404       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
405       switch(click.type) {
406         case Clickable::Url:
407           if(!str.contains("://"))
408             str = "http://" + str;
409           QDesktopServices::openUrl(str);
410           break;
411         case Clickable::Channel:
412           // TODO join or whatever...
413           break;
414         default:
415           break;
416       }
417     }
418   }
419   ChatItem::mouseReleaseEvent(event);
420 }
421
422 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
423   // mouse move events always mean we're not hovering anymore...
424   endHoverMode();
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);
430 }
431
432 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
433   endHoverMode();
434   event->accept();
435 }
436
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) {
444         onClickable = true;
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
449       }
450       if(onClickable) {
451         setCursor(Qt::PointingHandCursor);
452         privateData()->currentClickable = click;
453         update();
454         break;
455       }
456     }
457   }
458   if(!onClickable) endHoverMode();
459   event->accept();
460 }
461
462 void ContentsChatItem::showWebPreview(const Clickable &click) {
463 #ifdef HAVE_WEBKIT
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();
469
470   QPointF topLeft = scenePos() + QPointF(x, y);
471   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
472
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);
477 #endif
478 }
479
480 void ContentsChatItem::clearWebPreview() {
481 #ifdef HAVE_WEBKIT
482   chatScene()->clearWebPreview(this);
483 #endif
484 }
485
486 /*************************************************************************************************/
487
488 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
489   : item(_item),
490     layout(0),
491     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
492     wordidx(0),
493     lineCount(0),
494     choppedTrailing(0)
495 {
496 }
497
498 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
499   delete layout;
500 }
501
502 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
503   if(wordidx >= wrapList.count())
504     return -1;
505
506   lineCount++;
507   qreal targetWidth = lineCount * item->width() + choppedTrailing;
508
509   qint16 start = wordidx;
510   qint16 end = wrapList.count() - 1;
511
512   // check if the whole line fits
513   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
514     return -1;
515
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();
522       layout->endLayout();
523     }
524     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
525   }
526
527   while(true) {
528     if(start + 1 == end) {
529       wordidx = end;
530       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
531
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
535
536       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
537       return wrapList.at(wordidx).start;
538     }
539
540     qint16 pivot = (end + start) / 2;
541     if(wrapList.at(pivot).endX > targetWidth) {
542       end = pivot;
543     } else {
544       start = pivot;
545     }
546   }
547   Q_ASSERT(false);
548   return -1;
549 }
550