Pimp my ChatView!
[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   QVector<QTextLayout::FormatRange> formats = additionalFormats();
105   QTextLayout::FormatRange selectFmt = selectionFormat();
106   if(selectFmt.format.isValid()) formats.append(selectFmt);
107   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
108
109   // Debuging Stuff
110   // uncomment partially or all of the following stuff:
111   //
112   // 0) alternativ painter color for debug stuff
113 //   if(row() % 2)
114 //     painter->setPen(Qt::red);
115 //   else
116 //     painter->setPen(Qt::blue);
117   // 1) draw wordwrap points in the first line
118 //   if(column() == 2) {
119 //     ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
120 //     foreach(ChatLineModel::Word word, wrapList) {
121 //       if(word.endX > width())
122 //      break;
123 //       painter->drawLine(word.endX, 0, word.endX, height());
124 //     }
125 //   }
126   // 2) draw MsgId over the time column
127 //   if(column() == 0) {
128 //     QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
129 //     QPointF bottomPoint = boundingRect().bottomLeft();
130 //     bottomPoint.ry() -= 2;
131 //     painter->drawText(bottomPoint, msgIdString);
132 //   }
133   // 3) draw bounding rect
134 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
135 }
136
137 qint16 ChatItem::posToCursor(const QPointF &pos) {
138   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
139   if(pos.y() < 0) return 0;
140   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
141     QTextLine line = layout()->lineAt(l);
142     if(pos.y() >= line.y()) {
143       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
144     }
145   }
146   return 0;
147 }
148
149 void ChatItem::setFullSelection() {
150   if(_selectionMode != FullSelection) {
151     _selectionMode = FullSelection;
152     update();
153   }
154 }
155
156 void ChatItem::clearSelection() {
157   _selectionMode = NoSelection;
158   update();
159 }
160
161 void ChatItem::continueSelecting(const QPointF &pos) {
162   _selectionMode = PartialSelection;
163   _selectionEnd = posToCursor(pos);
164   update();
165 }
166
167 QTextLayout::FormatRange ChatItem::selectionFormat() const {
168   QTextLayout::FormatRange selectFmt;
169   if(_selectionMode != NoSelection) {
170     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
171     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
172     if(_selectionMode == PartialSelection) {
173       selectFmt.start = qMin(_selectionStart, _selectionEnd);
174       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
175     } else { // FullSelection
176       selectFmt.start = 0;
177       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
178     }
179   } else {
180     selectFmt.start = -1;
181     selectFmt.length = 0;
182   }
183   return selectFmt;
184 }
185
186 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
187   QList<QRectF> resultList;
188   const QAbstractItemModel *model_ = model();
189   if(!model_)
190     return resultList;
191
192   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
193   QList<int> indexList;
194   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
195   while(searchIdx != -1) {
196     indexList << searchIdx;
197     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
198   }
199
200   bool hadPrivateData = hasPrivateData();
201
202   foreach(int idx, indexList) {
203     QTextLine line = layout()->lineForTextPosition(idx);
204     qreal x = line.cursorToX(idx);
205     qreal width = line.cursorToX(idx + searchWord.count()) - x;
206     qreal height = line.height();
207     qreal y = height * line.lineNumber();
208     resultList << QRectF(x, y, width, height);
209   }
210
211   if(!hadPrivateData)
212     clearLayout();
213   return resultList;
214 }
215
216 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
217   if(event->buttons() == Qt::LeftButton) {
218     chatScene()->setSelectingItem(this);
219     _selectionStart = _selectionEnd = posToCursor(event->pos());
220     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
221     update();
222     event->accept();
223   } else {
224     event->ignore();
225   }
226 }
227
228 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
229   if(event->buttons() == Qt::LeftButton) {
230     if(contains(event->pos())) {
231       qint16 end = posToCursor(event->pos());
232       if(end != _selectionEnd) {
233         _selectionEnd = end;
234         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
235         update();
236       }
237     } else {
238       setFullSelection();
239       chatScene()->startGlobalSelection(this, event->pos());
240     }
241     event->accept();
242   } else {
243     event->ignore();
244   }
245 }
246
247 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
248   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
249     _selectionEnd = posToCursor(event->pos());
250     QString selection
251         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
252     chatScene()->putToClipboard(selection);
253     event->accept();
254   } else {
255     event->ignore();
256   }
257 }
258
259 // ************************************************************
260 // SenderChatItem
261 // ************************************************************
262
263 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
264   Q_UNUSED(option); Q_UNUSED(widget);
265
266   //painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
267   qreal layoutWidth = layout()->minimumWidth();
268   qreal offset = 0;
269   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
270     offset = qMin(width() - layoutWidth, (qreal)0);
271   else
272     offset = qMax(layoutWidth - width(), (qreal)0);
273
274   QTextLayout::FormatRange selectFmt = selectionFormat();
275
276   if(layoutWidth > width()) {
277     // Draw a nice gradient for longer items
278     // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
279     QPixmap pixmap(QSize(layout()->boundingRect().width(), layout()->boundingRect().height()));
280     pixmap.fill(QApplication::palette().brush(QPalette::Base).color());
281     QPainter pixPainter(&pixmap);
282     layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
283     pixPainter.end();
284
285     // Create alpha channel mask
286     QPixmap mask(pixmap.size());
287     QPainter maskPainter(&mask);
288     QLinearGradient gradient;
289     if(offset < 0) {
290       gradient.setStart(0, 0);
291       gradient.setFinalStop(12, 0);
292       gradient.setColorAt(0, Qt::black);
293       gradient.setColorAt(1, Qt::white);
294     } else {
295       gradient.setStart(width()-10, 0);
296       gradient.setFinalStop(width(), 0);
297       gradient.setColorAt(0, Qt::white);
298       gradient.setColorAt(1, Qt::black);
299     }
300     maskPainter.fillRect(boundingRect(), gradient);
301     pixmap.setAlphaChannel(mask);
302     painter->drawPixmap(0, 0, pixmap);
303   } else {
304     layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
305   }
306 }
307
308 // ************************************************************
309 // ContentsChatItem
310 // ************************************************************
311 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
312   : ChatItem(0, 0, pos, parent)
313 {
314   const QAbstractItemModel *model_ = model();
315   QModelIndex index = model_->index(row(), column());
316   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
317
318   setGeometryByWidth(width);
319 }
320
321 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
322   if(w != width()) {
323     prepareGeometryChange();
324     setWidth(w);
325     // compute height
326     int lines = 1;
327     WrapColumnFinder finder(this);
328     while(finder.nextWrapColumn() > 0)
329       lines++;
330     setHeight(lines * fontMetrics()->lineSpacing());
331   }
332   return height();
333 }
334
335 void ContentsChatItem::doLayout() {
336   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
337   if(!wrapList.count()) return; // empty chatitem
338
339   qreal h = 0;
340   WrapColumnFinder finder(this);
341   layout()->beginLayout();
342   forever {
343     QTextLine line = layout()->createLine();
344     if(!line.isValid())
345       break;
346
347     int col = finder.nextWrapColumn();
348     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
349     line.setPosition(QPointF(0, h));
350     h += fontMetrics()->lineSpacing();
351   }
352   layout()->endLayout();
353 }
354
355 // NOTE: This method is not threadsafe and not reentrant!
356 //       (RegExps are not constant while matching, and they are static here for efficiency)
357 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
358   // For matching URLs
359   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
360   static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#])");
361
362   static QRegExp regExp[] = {
363     // URL
364     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
365     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
366
367     // Channel name
368     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
369     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
370
371     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
372   };
373
374   static const int regExpCount = 2;  // number of regexps in the array above
375
376   qint16 matches[] = { 0, 0, 0 };
377   qint16 matchEnd[] = { 0, 0, 0 };
378
379   QString str = data(ChatLineModel::DisplayRole).toString();
380
381   QList<Clickable> result;
382   qint16 idx = 0;
383   qint16 minidx;
384   int type = -1;
385
386   do {
387     type = -1;
388     minidx = str.length();
389     for(int i = 0; i < regExpCount; i++) {
390       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
391       if(idx >= matchEnd[i]) {
392         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
393         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
394       }
395       if(matches[i] >= 0 && matches[i] < minidx) {
396         minidx = matches[i];
397         type = i;
398       }
399     }
400     if(type >= 0) {
401       idx = matchEnd[type];
402       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
403         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
404       }
405       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
406     }
407   } while(type >= 0);
408
409   /* testing
410   if(!result.isEmpty()) qDebug() << str;
411   foreach(Clickable click, result) {
412     qDebug() << str.mid(click.start, click.length);
413   }
414   */
415   return result;
416 }
417
418 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
419   // mark a clickable if hovered upon
420   QVector<QTextLayout::FormatRange> fmt;
421   if(privateData()->currentClickable.isValid()) {
422     Clickable click = privateData()->currentClickable;
423     QTextLayout::FormatRange f;
424     f.start = click.start;
425     f.length = click.length;
426     f.format.setFontUnderline(true);
427     fmt.append(f);
428   }
429   return fmt;
430 }
431
432 void ContentsChatItem::endHoverMode() {
433   if(hasPrivateData()) {
434     if(privateData()->currentClickable.isValid()) {
435       setCursor(Qt::ArrowCursor);
436       privateData()->currentClickable = Clickable();
437     }
438     clearWebPreview();
439     update();
440   }
441 }
442
443 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
444   privateData()->hasDragged = false;
445   ChatItem::mousePressEvent(event);
446 }
447
448 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
449   if(!event->buttons() && !privateData()->hasDragged) {
450     // got a click
451     Clickable click = privateData()->currentClickable;
452     if(click.isValid()) {
453       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
454       switch(click.type) {
455         case Clickable::Url:
456           if(!str.contains("://"))
457             str = "http://" + str;
458           QDesktopServices::openUrl(str);
459           break;
460         case Clickable::Channel:
461           // TODO join or whatever...
462           break;
463         default:
464           break;
465       }
466     }
467   }
468   ChatItem::mouseReleaseEvent(event);
469 }
470
471 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
472   // mouse move events always mean we're not hovering anymore...
473   endHoverMode();
474   // also, check if we have dragged the mouse
475   if(hasPrivateData() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
476     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
477     privateData()->hasDragged = true;
478   ChatItem::mouseMoveEvent(event);
479 }
480
481 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
482   endHoverMode();
483   event->accept();
484 }
485
486 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
487   bool onClickable = false;
488   qint16 idx = posToCursor(event->pos());
489   for(int i = 0; i < privateData()->clickables.count(); i++) {
490     Clickable click = privateData()->clickables.at(i);
491     if(idx >= click.start && idx < click.start + click.length) {
492       if(click.type == Clickable::Url) {
493         onClickable = true;
494         showWebPreview(click);
495       } else if(click.type == Clickable::Channel) {
496         // TODO: don't make clickable if it's our own name
497         //onClickable = true; //FIXME disabled for now
498       }
499       if(onClickable) {
500         setCursor(Qt::PointingHandCursor);
501         privateData()->currentClickable = click;
502         update();
503         break;
504       }
505     }
506   }
507   if(!onClickable) endHoverMode();
508   event->accept();
509 }
510
511 void ContentsChatItem::showWebPreview(const Clickable &click) {
512 #ifdef HAVE_WEBKIT
513   QTextLine line = layout()->lineForTextPosition(click.start);
514   qreal x = line.cursorToX(click.start);
515   qreal width = line.cursorToX(click.start + click.length) - x;
516   qreal height = line.height();
517   qreal y = height * line.lineNumber();
518
519   QPointF topLeft = scenePos() + QPointF(x, y);
520   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
521
522   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
523   if(!url.contains("://"))
524     url = "http://" + url;
525   chatScene()->loadWebPreview(this, url, urlRect);
526 #endif
527 }
528
529 void ContentsChatItem::clearWebPreview() {
530 #ifdef HAVE_WEBKIT
531   chatScene()->clearWebPreview(this);
532 #endif
533 }
534
535 /*************************************************************************************************/
536
537 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
538   : item(_item),
539     layout(0),
540     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
541     wordidx(0),
542     lineCount(0),
543     choppedTrailing(0)
544 {
545 }
546
547 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
548   delete layout;
549 }
550
551 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
552   if(wordidx >= wrapList.count())
553     return -1;
554
555   lineCount++;
556   qreal targetWidth = lineCount * item->width() + choppedTrailing;
557
558   qint16 start = wordidx;
559   qint16 end = wrapList.count() - 1;
560
561   // check if the whole line fits
562   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
563     return -1;
564
565   // check if we have a very long word that needs inter word wrap
566   if(wrapList.at(start).endX > targetWidth) {
567     if(!line.isValid()) {
568       layout = item->createLayout(QTextOption::NoWrap);
569       layout->beginLayout();
570       line = layout->createLine();
571       layout->endLayout();
572     }
573     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
574   }
575
576   while(true) {
577     if(start + 1 == end) {
578       wordidx = end;
579       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
580
581       // both cases should be cought preliminary
582       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
583       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
584
585       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
586       return wrapList.at(wordidx).start;
587     }
588
589     qint16 pivot = (end + start) / 2;
590     if(wrapList.at(pivot).endX > targetWidth) {
591       end = pivot;
592     } else {
593       start = pivot;
594     }
595   }
596   Q_ASSERT(false);
597   return -1;
598 }
599