072ae1b08419da6b13e4800375613d37b3572ae9
[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 #ifdef HAVE_WEBKIT
30 #include <QWebView>
31 #endif
32 #include <QGraphicsProxyWidget>
33
34 #include "chatitem.h"
35 #include "chatlinemodel.h"
36 #include "qtui.h"
37 #include "qtuistyle.h"
38
39 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
40   : QGraphicsItem(parent),
41     _data(0),
42     _boundingRect(0, 0, width, height),
43     _selectionMode(NoSelection),
44     _selectionStart(-1)
45 {
46   setAcceptHoverEvents(true);
47   setZValue(20);
48   setPos(pos);
49 }
50
51 ChatItem::~ChatItem() {
52   delete _data;
53 }
54
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;
59     return QVariant();
60   }
61   return model()->data(index, role);
62 }
63
64 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
65   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
66
67   QTextOption option;
68   option.setWrapMode(wrapMode);
69   option.setAlignment(alignment);
70   layout->setTextOption(option);
71
72   QList<QTextLayout::FormatRange> formatRanges
73          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
74   layout->setAdditionalFormats(formatRanges);
75   return layout;
76 }
77
78 void ChatItem::updateLayout() {
79   if(!privateData()) {
80     setPrivateData(new ChatItemPrivate(createLayout()));
81   }
82   QTextLayout *layout_ = layout();
83   layout_->beginLayout();
84   QTextLine line = layout_->createLine();
85   if(line.isValid()) {
86     line.setLineWidth(width());
87     line.setPosition(QPointF(0,0));
88   }
89   layout_->endLayout();
90 }
91
92 void ChatItem::clearLayout() {
93   delete _data;
94   _data = 0;
95 }
96
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);
101   if(!hasLayout())
102     updateLayout();
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 the following lines to draw the bounding rect and the row number in alternating colors
127 //   if(row() % 2)
128 //     painter->setPen(Qt::red);
129 //   else
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));
140 }
141
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;
145   if(!hasLayout())
146     updateLayout();
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);
151     }
152   }
153   return 0;
154 }
155
156 void ChatItem::setFullSelection() {
157   if(_selectionMode != FullSelection) {
158     _selectionMode = FullSelection;
159     update();
160   }
161 }
162
163 void ChatItem::clearSelection() {
164   _selectionMode = NoSelection;
165   update();
166 }
167
168 void ChatItem::continueSelecting(const QPointF &pos) {
169   _selectionMode = PartialSelection;
170   _selectionEnd = posToCursor(pos);
171   update();
172 }
173
174 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
175   QList<QRectF> resultList;
176   const QAbstractItemModel *model_ = model();
177   if(!model_)
178     return resultList;
179
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);
186   }
187
188   bool hadLayout = hasLayout();
189   if(!hadLayout)
190     updateLayout();
191
192   foreach(int idx, indexList) {
193     QTextLine line = layout()->lineForTextPosition(idx);
194     qreal x = line.cursorToX(idx);
195     qreal width = line.cursorToX(idx + searchWord.count()) - x;
196     qreal height = line.height();
197     qreal y = height * line.lineNumber();
198     resultList << QRectF(x, y, width, height);
199   }
200
201   if(!hadLayout)
202     clearLayout();
203   return resultList;
204 }
205
206 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
207   if(event->buttons() == Qt::LeftButton) {
208     chatScene()->setSelectingItem(this);
209     _selectionStart = _selectionEnd = posToCursor(event->pos());
210     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
211     update();
212     event->accept();
213   } else {
214     event->ignore();
215   }
216 }
217
218 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
219   if(event->buttons() == Qt::LeftButton) {
220     if(contains(event->pos())) {
221       qint16 end = posToCursor(event->pos());
222       if(end != _selectionEnd) {
223         _selectionEnd = end;
224         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
225         update();
226       }
227     } else {
228       setFullSelection();
229       chatScene()->startGlobalSelection(this, event->pos());
230     }
231     event->accept();
232   } else {
233     event->ignore();
234   }
235 }
236
237 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
238   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
239     _selectionEnd = posToCursor(event->pos());
240     QString selection
241         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
242     chatScene()->putToClipboard(selection);
243     event->accept();
244   } else {
245     event->ignore();
246   }
247 }
248
249 // ************************************************************
250 // SenderChatItem
251 // ************************************************************
252
253 // ************************************************************
254 // ContentsChatItem
255 // ************************************************************
256 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
257   : ChatItem(0, 0, pos, parent)
258 {
259   const QAbstractItemModel *model_ = model();
260   QModelIndex index = model_->index(row(), column());
261   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
262
263   setGeometryByWidth(width);
264 }
265
266 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
267   if(w != width()) {
268     setWidth(w);
269     // compute height
270     int lines = 1;
271     WrapColumnFinder finder(this);
272     while(finder.nextWrapColumn() > 0)
273       lines++;
274     setHeight(lines * fontMetrics()->lineSpacing());
275   }
276   return height();
277 }
278
279 void ContentsChatItem::updateLayout() {
280   if(!privateData()) {
281     ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
282     setPrivateData(data);
283   }
284
285   // Now layout
286   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
287   if(!wrapList.count()) return; // empty chatitem
288
289   qreal h = 0;
290   WrapColumnFinder finder(this);
291   layout()->beginLayout();
292   forever {
293     QTextLine line = layout()->createLine();
294     if(!line.isValid())
295       break;
296
297     int col = finder.nextWrapColumn();
298     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
299     line.setPosition(QPointF(0, h));
300     h += fontMetrics()->lineSpacing();
301   }
302   layout()->endLayout();
303 }
304
305 // NOTE: This method is not threadsafe and not reentrant!
306 //       (RegExps are not constant while matching, and they are static here for efficiency)
307 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
308   // For matching URLs
309   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
310   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
311
312   static QRegExp regExp[] = {
313     // URL
314     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
315     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
316
317     // Channel name
318     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
319     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
320
321     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
322   };
323
324   static const int regExpCount = 2;  // number of regexps in the array above
325
326   qint16 matches[] = { 0, 0, 0 };
327   qint16 matchEnd[] = { 0, 0, 0 };
328
329   QString str = data(ChatLineModel::DisplayRole).toString();
330
331   QList<Clickable> result;
332   qint16 idx = 0;
333   qint16 minidx;
334   int type = -1;
335
336   do {
337     type = -1;
338     minidx = str.length();
339     for(int i = 0; i < regExpCount; i++) {
340       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
341       if(idx >= matchEnd[i]) {
342         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
343         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
344       }
345       if(matches[i] >= 0 && matches[i] < minidx) {
346         minidx = matches[i];
347         type = i;
348       }
349     }
350     if(type >= 0) {
351       idx = matchEnd[type];
352       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
353         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
354       }
355       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
356     }
357   } while(type >= 0);
358
359   /* testing
360   if(!result.isEmpty()) qDebug() << str;
361   foreach(Clickable click, result) {
362     qDebug() << str.mid(click.start, click.length);
363   }
364   */
365   return result;
366 }
367
368 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
369   // mark a clickable if hovered upon
370   QVector<QTextLayout::FormatRange> fmt;
371   if(privateData()->currentClickable.isValid()) {
372     Clickable click = privateData()->currentClickable;
373     QTextLayout::FormatRange f;
374     f.start = click.start;
375     f.length = click.length;
376     f.format.setFontUnderline(true);
377     fmt.append(f);
378   }
379   return fmt;
380 }
381
382 void ContentsChatItem::endHoverMode() {
383   if(hasLayout()) {
384     if(privateData()->currentClickable.isValid()) {
385       setCursor(Qt::ArrowCursor);
386       privateData()->currentClickable = Clickable();
387     }
388 #ifdef HAVE_WEBKIT
389     clearWebPreview();
390 #endif
391     update();
392   }
393 }
394
395 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
396   privateData()->hasDragged = false;
397   ChatItem::mousePressEvent(event);
398 }
399
400 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
401   if(!event->buttons() && !privateData()->hasDragged) {
402     // got a click
403     Clickable click = privateData()->currentClickable;
404     if(click.isValid()) {
405       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
406       switch(click.type) {
407         case Clickable::Url:
408           if(!str.contains("://"))
409             str = "http://" + str;
410           QDesktopServices::openUrl(str);
411           break;
412         case Clickable::Channel:
413           // TODO join or whatever...
414           break;
415         default:
416           break;
417       }
418     }
419   }
420   ChatItem::mouseReleaseEvent(event);
421 }
422
423 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
424   // mouse move events always mean we're not hovering anymore...
425   endHoverMode();
426   // also, check if we have dragged the mouse
427   if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
428     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
429     privateData()->hasDragged = true;
430   ChatItem::mouseMoveEvent(event);
431 }
432
433 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
434   endHoverMode();
435   event->accept();
436 }
437
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) {
445         onClickable = true;
446 #ifdef HAVE_WEBKIT
447         showWebPreview(click);
448 #endif
449       } else if(click.type == Clickable::Channel) {
450         // TODO: don't make clickable if it's our own name
451         //onClickable = true; //FIXME disabled for now
452       }
453       if(onClickable) {
454         setCursor(Qt::PointingHandCursor);
455         privateData()->currentClickable = click;
456         update();
457         break;
458       }
459     }
460   }
461   if(!onClickable) endHoverMode();
462   event->accept();
463 }
464
465 #ifdef HAVE_WEBKIT
466 void ContentsChatItem::showWebPreview(const Clickable &click) {
467   if(!hasLayout())
468     updateLayout();
469
470   QTextLine line = layout()->lineForTextPosition(click.start);
471   qreal x = line.cursorToX(click.start);
472   qreal width = line.cursorToX(click.start + click.length) - x;
473   qreal height = line.height();
474   qreal y = height * line.lineNumber();
475   QRectF urlRect(x, y, width, height);
476   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
477   if(!url.contains("://"))
478     url = "http://" + url;
479   privateData()->loadWebPreview(url, urlRect);
480 }
481
482 void ContentsChatItem::clearWebPreview() {
483   if(hasLayout())
484     privateData()->clearWebPreview();
485 }
486 #endif
487
488 // ****************************************
489 // ContentsChatItemPrivate
490 // ****************************************
491 #ifdef HAVE_WEBKIT
492 ContentsChatItemPrivate::~ContentsChatItemPrivate() {
493   clearWebPreview();
494 }
495
496 void ContentsChatItemPrivate::loadWebPreview(const QString &url, const QRectF &urlRect) {
497   if(url != previewUrl) {
498     previewUrl = url;
499     // load a new web view and delete the old one (if exists)
500     if(previewItem) {
501       contentsItem->scene()->removeItem(previewItem);
502       delete previewItem;
503     }
504     QWebView *view = new QWebView;
505     view->load(url);
506     previewItem = new ContentsChatItemPrivate::PreviewItem(view);
507     contentsItem->scene()->addItem(previewItem);
508   }
509   if(urlRect != previewUrlRect) {
510     previewUrlRect = urlRect;
511     QPointF sPos = contentsItem->scenePos();
512     qreal previewY = sPos.y() + urlRect.y() + urlRect.height(); // bottom of url;
513     qreal previewX = sPos.x() + urlRect.x();
514     if(previewY + previewItem->boundingRect().height() > contentsItem->scene()->sceneRect().bottom())
515       previewY = sPos.y() + urlRect.y() - previewItem->boundingRect().height();
516     
517     if(previewX + previewItem->boundingRect().width() > contentsItem->scene()->sceneRect().width())
518       previewX = contentsItem->scene()->sceneRect().right() - previewItem->boundingRect().width();
519   
520     previewItem->setPos(previewX, previewY);
521   }
522 }
523
524 void ContentsChatItemPrivate::clearWebPreview() {
525   if(previewItem) {
526     contentsItem->scene()->removeItem(previewItem);
527     delete previewItem;
528     previewItem = 0;
529   }
530   previewUrl = QString();
531   previewUrlRect = QRectF();
532 }
533
534 ContentsChatItemPrivate::PreviewItem::PreviewItem(QWebView *webView)
535   : QGraphicsItem(0), // needs to be a top level item as we otherwise cannot guarantee that it's on top of other chatlines
536     _boundingRect(0, 0, 400, 300)
537 {
538   qreal frameWidth = 5;
539   webView->resize(1000, 750);
540   QGraphicsProxyWidget *proxyItem = new QGraphicsProxyWidget(this);
541   proxyItem->setWidget(webView);
542   proxyItem->setAcceptHoverEvents(false);
543
544   qreal xScale = (_boundingRect.width() - 2 * frameWidth) / webView->width();
545   qreal yScale = (_boundingRect.height() - 2 * frameWidth) / webView->height();
546   proxyItem->scale(xScale, yScale);
547   proxyItem->setPos(frameWidth, frameWidth);
548
549   setZValue(30);
550 }
551
552 void ContentsChatItemPrivate::PreviewItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
553   Q_UNUSED(option); Q_UNUSED(widget);
554   painter->setClipRect(boundingRect());
555   painter->setPen(QPen(Qt::black, 5));
556   painter->setBrush(Qt::black);
557   painter->setRenderHints(QPainter::Antialiasing);
558   painter->drawRoundedRect(boundingRect(), 10, 10);
559
560   painter->setPen(QPen(Qt::green));
561   QString text = QString::number(zValue());
562   painter->drawText(_boundingRect.center(), text);
563 }
564 #endif // #ifdef HAVE_WEBKIT
565
566 /*************************************************************************************************/
567
568 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
569   : item(_item),
570     layout(0),
571     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
572     wordidx(0),
573     lineCount(0),
574     choppedTrailing(0)
575 {
576 }
577
578 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
579   delete layout;
580 }
581
582 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
583   if(wordidx >= wrapList.count())
584     return -1;
585
586   lineCount++;
587   qreal targetWidth = lineCount * item->width() + choppedTrailing;
588
589   qint16 start = wordidx;
590   qint16 end = wrapList.count() - 1;
591
592   // check if the whole line fits
593   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
594     return -1;
595
596   // check if we have a very long word that needs inter word wrap
597   if(wrapList.at(start).endX > targetWidth) {
598     if(!line.isValid()) {
599       layout = item->createLayout(QTextOption::NoWrap);
600       layout->beginLayout();
601       line = layout->createLine();
602       layout->endLayout();
603     }
604     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
605   }
606
607   while(true) {
608     if(start + 1 == end) {
609       wordidx = end;
610       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
611
612       // both cases should be cought preliminary
613       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
614       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
615
616       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
617       return wrapList.at(wordidx).start;
618     }
619
620     qint16 pivot = (end + start) / 2;
621     if(wrapList.at(pivot).endX > targetWidth) {
622       end = pivot;
623     } else {
624       start = pivot;
625     }
626   }
627   Q_ASSERT(false);
628   return -1;
629 }
630