making webkit optional
[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() && privateData()->currentClickable.isValid()) {
384     setCursor(Qt::ArrowCursor);
385     privateData()->currentClickable = Clickable();
386 #ifdef HAVE_WEBKIT
387     privateData()->clearPreview();
388 #endif
389     update();
390   }
391 }
392
393 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
394   privateData()->hasDragged = false;
395   ChatItem::mousePressEvent(event);
396 }
397
398 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
399   if(!event->buttons() && !privateData()->hasDragged) {
400     // got a click
401     Clickable click = privateData()->currentClickable;
402     if(click.isValid()) {
403       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
404       switch(click.type) {
405         case Clickable::Url:
406           if(!str.contains("://"))
407             str = "http://" + str;
408           QDesktopServices::openUrl(str);
409           break;
410         case Clickable::Channel:
411           // TODO join or whatever...
412           break;
413         default:
414           break;
415       }
416     }
417   }
418   ChatItem::mouseReleaseEvent(event);
419 }
420
421 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
422   // mouse move events always mean we're not hovering anymore...
423   endHoverMode();
424   // also, check if we have dragged the mouse
425   if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
426     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
427     privateData()->hasDragged = true;
428   ChatItem::mouseMoveEvent(event);
429 }
430
431 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
432   endHoverMode();
433   event->accept();
434 }
435
436 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
437   bool onClickable = false;
438   qint16 idx = posToCursor(event->pos());
439   for(int i = 0; i < privateData()->clickables.count(); i++) {
440     Clickable click = privateData()->clickables.at(i);
441     if(idx >= click.start && idx < click.start + click.length) {
442       if(click.type == Clickable::Url) {
443         onClickable = true;
444
445         if(!hasLayout())
446           updateLayout();
447
448 #ifdef HAVE_WEBKIT
449         QTextLine line = layout()->lineForTextPosition(click.start);
450         qreal x = line.cursorToX(click.start);
451         qreal width = line.cursorToX(click.start + click.length) - x;
452         qreal height = line.height();
453         qreal y = height * line.lineNumber();
454         QRectF urlRect(x, y, width, height);
455         QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
456         if(!url.contains("://"))
457           url = "http://" + url;
458         privateData()->loadWebPreview(url, urlRect);
459 #endif
460       } else if(click.type == Clickable::Channel) {
461         // TODO: don't make clickable if it's our own name
462         //onClickable = true; //FIXME disabled for now
463       }
464       if(onClickable) {
465         setCursor(Qt::PointingHandCursor);
466         privateData()->currentClickable = click;
467         update();
468         break;
469       }
470     }
471   }
472   if(!onClickable) endHoverMode();
473   event->accept();
474 }
475
476 // ****************************************
477 // ContentsChatItemPrivate
478 // ****************************************
479 ContentsChatItemPrivate::~ContentsChatItemPrivate() {
480 #ifdef HAVE_WEBKIT
481   clearPreview();
482 #endif
483 }
484
485 #ifdef HAVE_WEBKIT
486 void ContentsChatItemPrivate::loadWebPreview(const QString &url, const QRectF &urlRect) {
487   if(!controller)
488     controller = new PreviewController(contentsItem);
489   controller->loadPage(url, urlRect);
490 }
491
492 void ContentsChatItemPrivate::clearPreview() {
493   delete controller;
494   controller = 0;
495 }
496
497 ContentsChatItemPrivate::PreviewController::~PreviewController() {
498   if(previewItem) {
499     contentsItem->scene()->removeItem(previewItem);
500     delete previewItem;
501   }
502 }
503
504 void ContentsChatItemPrivate::PreviewController::loadPage(const QString &newUrl, const QRectF &urlRect) {
505   if(newUrl.isEmpty() || newUrl == url)
506     return;
507
508   url = newUrl;
509   QWebView *view = new QWebView;
510   connect(view, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
511   view->load(url);
512   previewItem = new ContentsChatItemPrivate::PreviewItem(view);
513
514   QPointF sPos = contentsItem->scenePos();
515   qreal previewY = sPos.y() + urlRect.y() + urlRect.height(); // bottom of url;
516   qreal previewX = sPos.x() + urlRect.x();
517   if(previewY + previewItem->boundingRect().height() > contentsItem->scene()->sceneRect().bottom())
518     previewY = sPos.y() + urlRect.y() - previewItem->boundingRect().height();
519
520   if(previewX + previewItem->boundingRect().width() > contentsItem->scene()->sceneRect().width())
521     previewX = contentsItem->scene()->sceneRect().right() - previewItem->boundingRect().width();
522
523   previewItem->setPos(previewX, previewY);
524   contentsItem->scene()->addItem(previewItem);
525 }
526
527 void ContentsChatItemPrivate::PreviewController::pageLoaded(bool success) {
528   Q_UNUSED(success)
529 }
530
531 ContentsChatItemPrivate::PreviewItem::PreviewItem(QWebView *webView)
532   : QGraphicsItem(0), // needs to be a top level item as we otherwise cannot guarantee that it's on top of other chatlines
533     _boundingRect(0, 0, 400, 300)
534 {
535   qreal frameWidth = 5;
536   webView->resize(1000, 750);
537   QGraphicsProxyWidget *proxyItem = new QGraphicsProxyWidget(this);
538   proxyItem->setWidget(webView);
539   proxyItem->setAcceptHoverEvents(false);
540
541   qreal xScale = (_boundingRect.width() - 2 * frameWidth) / webView->width();
542   qreal yScale = (_boundingRect.height() - 2 * frameWidth) / webView->height();
543   proxyItem->scale(xScale, yScale);
544   proxyItem->setPos(frameWidth, frameWidth);
545
546   setZValue(30);
547 }
548
549 void ContentsChatItemPrivate::PreviewItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
550   Q_UNUSED(option); Q_UNUSED(widget);
551   painter->setClipRect(boundingRect());
552   painter->setPen(QPen(Qt::black, 5));
553   painter->setBrush(Qt::black);
554   painter->setRenderHints(QPainter::Antialiasing);
555   painter->drawRoundedRect(boundingRect(), 10, 10);
556
557   painter->setPen(QPen(Qt::green));
558   QString text = QString::number(zValue());
559   painter->drawText(_boundingRect.center(), text);
560 }
561 #endif // #ifdef HAVE_WEBKIT
562
563 /*************************************************************************************************/
564
565 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
566   : item(_item),
567     layout(0),
568     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
569     wordidx(0),
570     lineCount(0),
571     choppedTrailing(0)
572 {
573 }
574
575 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
576   delete layout;
577 }
578
579 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
580   if(wordidx >= wrapList.count())
581     return -1;
582
583   lineCount++;
584   qreal targetWidth = lineCount * item->width() + choppedTrailing;
585
586   qint16 start = wordidx;
587   qint16 end = wrapList.count() - 1;
588
589   // check if the whole line fits
590   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
591     return -1;
592
593   // check if we have a very long word that needs inter word wrap
594   if(wrapList.at(start).endX > targetWidth) {
595     if(!line.isValid()) {
596       layout = item->createLayout(QTextOption::NoWrap);
597       layout->beginLayout();
598       line = layout->createLine();
599       layout->endLayout();
600     }
601     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
602   }
603
604   while(true) {
605     if(start + 1 == end) {
606       wordidx = end;
607       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
608
609       // both cases should be cought preliminary
610       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
611       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
612
613       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
614       return wrapList.at(wordidx).start;
615     }
616
617     qint16 pivot = (end + start) / 2;
618     if(wrapList.at(pivot).endX > targetWidth) {
619       end = pivot;
620     } else {
621       start = pivot;
622     }
623   }
624   Q_ASSERT(false);
625   return -1;
626 }
627