internal debug helpers for chatitems
[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) {
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::updateLayout() {
75   if(!privateData()) {
76     setPrivateData(new ChatItemPrivate(createLayout()));
77   }
78   QTextLayout *layout_ = layout();
79   layout_->beginLayout();
80   QTextLine line = layout_->createLine();
81   if(line.isValid()) {
82     line.setLineWidth(width());
83     line.setPosition(QPointF(0,0));
84   }
85   layout_->endLayout();
86 }
87
88 void ChatItem::clearLayout() {
89   delete _data;
90   _data = 0;
91 }
92
93 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
94 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
95 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
96   Q_UNUSED(option); Q_UNUSED(widget);
97   if(!hasLayout())
98     updateLayout();
99   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
100   //if(_selectionMode == FullSelection) {
101     //painter->save();
102     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
103     //painter->restore();
104   //}
105   QVector<QTextLayout::FormatRange> formats = additionalFormats();
106   if(_selectionMode != NoSelection) {
107     QTextLayout::FormatRange selectFmt;
108     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
109     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
110     if(_selectionMode == PartialSelection) {
111       selectFmt.start = qMin(_selectionStart, _selectionEnd);
112       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
113     } else { // FullSelection
114       selectFmt.start = 0;
115       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
116     }
117     formats.append(selectFmt);
118   }
119   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
120
121   // Debuging Stuff
122   // uncomment partially or all of the following stuff:
123   //
124   // 0) alternativ painter color for debug stuff
125 //   if(row() % 2)
126 //     painter->setPen(Qt::red);
127 //   else
128 //     painter->setPen(Qt::blue);
129   // 1) draw wordwrap points in the first line
130 //   if(column() == 2) {
131 //     ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
132 //     foreach(ChatLineModel::Word word, wrapList) {
133 //       if(word.endX > width())
134 //      break;
135 //       painter->drawLine(word.endX, 0, word.endX, height());
136 //     }
137 //   }
138   // 2) draw MsgId over the time column
139 //   if(column() == 0) {
140 //     QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
141 //     QPointF bottomPoint = boundingRect().bottomLeft();
142 //     bottomPoint.ry() -= 2;
143 //     painter->drawText(bottomPoint, msgIdString);
144 //   }
145   // 3) draw bounding rect
146 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
147 }
148
149 qint16 ChatItem::posToCursor(const QPointF &pos) {
150   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
151   if(pos.y() < 0) return 0;
152   if(!hasLayout())
153     updateLayout();
154   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
155     QTextLine line = layout()->lineAt(l);
156     if(pos.y() >= line.y()) {
157       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
158     }
159   }
160   return 0;
161 }
162
163 void ChatItem::setFullSelection() {
164   if(_selectionMode != FullSelection) {
165     _selectionMode = FullSelection;
166     update();
167   }
168 }
169
170 void ChatItem::clearSelection() {
171   _selectionMode = NoSelection;
172   update();
173 }
174
175 void ChatItem::continueSelecting(const QPointF &pos) {
176   _selectionMode = PartialSelection;
177   _selectionEnd = posToCursor(pos);
178   update();
179 }
180
181 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
182   QList<QRectF> resultList;
183   const QAbstractItemModel *model_ = model();
184   if(!model_)
185     return resultList;
186
187   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
188   QList<int> indexList;
189   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
190   while(searchIdx != -1) {
191     indexList << searchIdx;
192     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
193   }
194
195   bool hadLayout = hasLayout();
196   if(!hadLayout)
197     updateLayout();
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(!hadLayout)
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::updateLayout() {
287   if(!privateData()) {
288     ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
289     setPrivateData(data);
290   }
291
292   // Now layout
293   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
294   if(!wrapList.count()) return; // empty chatitem
295
296   qreal h = 0;
297   WrapColumnFinder finder(this);
298   layout()->beginLayout();
299   forever {
300     QTextLine line = layout()->createLine();
301     if(!line.isValid())
302       break;
303
304     int col = finder.nextWrapColumn();
305     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
306     line.setPosition(QPointF(0, h));
307     h += fontMetrics()->lineSpacing();
308   }
309   layout()->endLayout();
310 }
311
312 // NOTE: This method is not threadsafe and not reentrant!
313 //       (RegExps are not constant while matching, and they are static here for efficiency)
314 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
315   // For matching URLs
316   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
317   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
318
319   static QRegExp regExp[] = {
320     // URL
321     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
322     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
323
324     // Channel name
325     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
326     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
327
328     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
329   };
330
331   static const int regExpCount = 2;  // number of regexps in the array above
332
333   qint16 matches[] = { 0, 0, 0 };
334   qint16 matchEnd[] = { 0, 0, 0 };
335
336   QString str = data(ChatLineModel::DisplayRole).toString();
337
338   QList<Clickable> result;
339   qint16 idx = 0;
340   qint16 minidx;
341   int type = -1;
342
343   do {
344     type = -1;
345     minidx = str.length();
346     for(int i = 0; i < regExpCount; i++) {
347       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
348       if(idx >= matchEnd[i]) {
349         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
350         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
351       }
352       if(matches[i] >= 0 && matches[i] < minidx) {
353         minidx = matches[i];
354         type = i;
355       }
356     }
357     if(type >= 0) {
358       idx = matchEnd[type];
359       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
360         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
361       }
362       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
363     }
364   } while(type >= 0);
365
366   /* testing
367   if(!result.isEmpty()) qDebug() << str;
368   foreach(Clickable click, result) {
369     qDebug() << str.mid(click.start, click.length);
370   }
371   */
372   return result;
373 }
374
375 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
376   // mark a clickable if hovered upon
377   QVector<QTextLayout::FormatRange> fmt;
378   if(privateData()->currentClickable.isValid()) {
379     Clickable click = privateData()->currentClickable;
380     QTextLayout::FormatRange f;
381     f.start = click.start;
382     f.length = click.length;
383     f.format.setFontUnderline(true);
384     fmt.append(f);
385   }
386   return fmt;
387 }
388
389 void ContentsChatItem::endHoverMode() {
390   if(hasLayout()) {
391     if(privateData()->currentClickable.isValid()) {
392       setCursor(Qt::ArrowCursor);
393       privateData()->currentClickable = Clickable();
394     }
395     clearWebPreview();
396     update();
397   }
398 }
399
400 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
401   privateData()->hasDragged = false;
402   ChatItem::mousePressEvent(event);
403 }
404
405 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
406   if(!event->buttons() && !privateData()->hasDragged) {
407     // got a click
408     Clickable click = privateData()->currentClickable;
409     if(click.isValid()) {
410       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
411       switch(click.type) {
412         case Clickable::Url:
413           if(!str.contains("://"))
414             str = "http://" + str;
415           QDesktopServices::openUrl(str);
416           break;
417         case Clickable::Channel:
418           // TODO join or whatever...
419           break;
420         default:
421           break;
422       }
423     }
424   }
425   ChatItem::mouseReleaseEvent(event);
426 }
427
428 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
429   // mouse move events always mean we're not hovering anymore...
430   endHoverMode();
431   // also, check if we have dragged the mouse
432   if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
433     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
434     privateData()->hasDragged = true;
435   ChatItem::mouseMoveEvent(event);
436 }
437
438 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
439   endHoverMode();
440   event->accept();
441 }
442
443 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
444   bool onClickable = false;
445   qint16 idx = posToCursor(event->pos());
446   for(int i = 0; i < privateData()->clickables.count(); i++) {
447     Clickable click = privateData()->clickables.at(i);
448     if(idx >= click.start && idx < click.start + click.length) {
449       if(click.type == Clickable::Url) {
450         onClickable = true;
451         showWebPreview(click);
452       } else if(click.type == Clickable::Channel) {
453         // TODO: don't make clickable if it's our own name
454         //onClickable = true; //FIXME disabled for now
455       }
456       if(onClickable) {
457         setCursor(Qt::PointingHandCursor);
458         privateData()->currentClickable = click;
459         update();
460         break;
461       }
462     }
463   }
464   if(!onClickable) endHoverMode();
465   event->accept();
466 }
467
468 void ContentsChatItem::showWebPreview(const Clickable &click) {
469 #ifdef HAVE_WEBKIT
470   if(!hasLayout())
471     updateLayout();
472
473   QTextLine line = layout()->lineForTextPosition(click.start);
474   qreal x = line.cursorToX(click.start);
475   qreal width = line.cursorToX(click.start + click.length) - x;
476   qreal height = line.height();
477   qreal y = height * line.lineNumber();
478
479   QPointF topLeft = scenePos() + QPointF(x, y);
480   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
481
482   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
483   if(!url.contains("://"))
484     url = "http://" + url;
485   chatScene()->loadWebPreview(this, url, urlRect);
486 #endif
487 }
488
489 void ContentsChatItem::clearWebPreview() {
490 #ifdef HAVE_WEBKIT
491   chatScene()->clearWebPreview(this);
492 #endif
493 }
494
495 /*************************************************************************************************/
496
497 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
498   : item(_item),
499     layout(0),
500     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
501     wordidx(0),
502     lineCount(0),
503     choppedTrailing(0)
504 {
505 }
506
507 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
508   delete layout;
509 }
510
511 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
512   if(wordidx >= wrapList.count())
513     return -1;
514
515   lineCount++;
516   qreal targetWidth = lineCount * item->width() + choppedTrailing;
517
518   qint16 start = wordidx;
519   qint16 end = wrapList.count() - 1;
520
521   // check if the whole line fits
522   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
523     return -1;
524
525   // check if we have a very long word that needs inter word wrap
526   if(wrapList.at(start).endX > targetWidth) {
527     if(!line.isValid()) {
528       layout = item->createLayout(QTextOption::NoWrap);
529       layout->beginLayout();
530       line = layout->createLine();
531       layout->endLayout();
532     }
533     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
534   }
535
536   while(true) {
537     if(start + 1 == end) {
538       wordidx = end;
539       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
540
541       // both cases should be cought preliminary
542       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
543       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
544
545       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
546       return wrapList.at(wordidx).start;
547     }
548
549     qint16 pivot = (end + start) / 2;
550     if(wrapList.at(pivot).endX > targetWidth) {
551       end = pivot;
552     } else {
553       start = pivot;
554     }
555   }
556   Q_ASSERT(false);
557   return -1;
558 }
559