495a97ef434b2a0a376721e6db47d9f29160bca2
[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, ChatLineModel::ColumnType col, QGraphicsItem *parent)
36   : QGraphicsItem(parent),
37     _data(0),
38     _boundingRect(0, 0, width, height),
39     _fontMetrics(0),
40     _selectionMode(NoSelection),
41     _selectionStart(-1)
42 {
43   const QAbstractItemModel *model_ = model();
44   QModelIndex index = model_->index(row(), col);
45   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
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   if(!hasLayout())
189     updateLayout();
190
191   foreach(int idx, indexList) {
192     QTextLine line = layout()->lineForTextPosition(idx);
193     qreal x = line.cursorToX(idx);
194     qreal width = line.cursorToX(idx + searchWord.count()) - x;
195     qreal height = fontMetrics()->lineSpacing();
196     qreal y = height * line.lineNumber();
197     resultList << QRectF(x, y, width, height);
198   }
199   return resultList;
200 }
201
202 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
203   if(event->buttons() == Qt::LeftButton) {
204     chatScene()->setSelectingItem(this);
205     _selectionStart = _selectionEnd = posToCursor(event->pos());
206     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
207     update();
208     event->accept();
209   } else {
210     event->ignore();
211   }
212 }
213
214 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
215   if(event->buttons() == Qt::LeftButton) {
216     if(contains(event->pos())) {
217       qint16 end = posToCursor(event->pos());
218       if(end != _selectionEnd) {
219         _selectionEnd = end;
220         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
221         update();
222       }
223     } else {
224       setFullSelection();
225       chatScene()->startGlobalSelection(this, event->pos());
226     }
227     event->accept();
228   } else {
229     event->ignore();
230   }
231 }
232
233 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
234   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
235     _selectionEnd = posToCursor(event->pos());
236     QString selection
237         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
238     chatScene()->putToClipboard(selection);
239     event->accept();
240   } else {
241     event->ignore();
242   }
243 }
244
245 // ************************************************************
246 // SenderChatItem
247 // ************************************************************
248
249 // ************************************************************
250 // ContentsChatItem
251 // ************************************************************
252 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
253   : ChatItem(0, 0, pos, column(), parent)
254 {
255   setGeometryByWidth(width);
256 }
257
258 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
259   if(w != width()) {
260     setWidth(w);
261     // compute height
262     int lines = 1;
263     WrapColumnFinder finder(this);
264     while(finder.nextWrapColumn() > 0)
265       lines++;
266     setHeight(lines * fontMetrics()->lineSpacing());
267   }
268   return height();
269 }
270
271 void ContentsChatItem::updateLayout() {
272   if(!privateData()) {
273     ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere),
274                                                                 findClickables());
275     // data->clickables = findClickables();
276     setPrivateData(data);
277   }
278
279   // Now layout
280   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
281   if(!wrapList.count()) return; // empty chatitem
282
283   qreal h = 0;
284   WrapColumnFinder finder(this);
285   layout()->beginLayout();
286   forever {
287     QTextLine line = layout()->createLine();
288     if(!line.isValid())
289       break;
290
291     int col = finder.nextWrapColumn();
292     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
293     line.setPosition(QPointF(0, h));
294     h += fontMetrics()->lineSpacing();
295   }
296   layout()->endLayout();
297 }
298
299 // NOTE: This method is not threadsafe and not reentrant!
300 //       (RegExps are not constant while matching, and they are static here for efficiency)
301 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
302   // For matching URLs
303   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
304   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
305
306   static QRegExp regExp[] = {
307     // URL
308     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
309     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
310
311     // Channel name
312     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
313     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
314
315     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
316   };
317
318   static const int regExpCount = 2;  // number of regexps in the array above
319
320   qint16 matches[] = { 0, 0, 0 };
321   qint16 matchEnd[] = { 0, 0, 0 };
322
323   QString str = data(ChatLineModel::DisplayRole).toString();
324
325   QList<Clickable> result;
326   qint16 idx = 0;
327   qint16 minidx;
328   int type = -1;
329
330   do {
331     type = -1;
332     minidx = str.length();
333     for(int i = 0; i < regExpCount; i++) {
334       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
335       if(idx >= matchEnd[i]) {
336         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
337         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
338       }
339       if(matches[i] >= 0 && matches[i] < minidx) {
340         minidx = matches[i];
341         type = i;
342       }
343     }
344     if(type >= 0) {
345       idx = matchEnd[type];
346       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
347         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
348       }
349       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
350     }
351   } while(type >= 0);
352
353   /* testing
354   if(!result.isEmpty()) qDebug() << str;
355   foreach(Clickable click, result) {
356     qDebug() << str.mid(click.start, click.length);
357   }
358   */
359   return result;
360 }
361
362 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
363   // mark a clickable if hovered upon
364   QVector<QTextLayout::FormatRange> fmt;
365   if(privateData()->currentClickable.isValid()) {
366     Clickable click = privateData()->currentClickable;
367     QTextLayout::FormatRange f;
368     f.start = click.start;
369     f.length = click.length;
370     f.format.setFontUnderline(true);
371     fmt.append(f);
372   }
373   return fmt;
374 }
375
376 void ContentsChatItem::endHoverMode() {
377   if(privateData()->currentClickable.isValid()) {
378     setCursor(Qt::ArrowCursor);
379     privateData()->currentClickable = Clickable();
380     update();
381   }
382 }
383
384 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
385   privateData()->hasDragged = false;
386   ChatItem::mousePressEvent(event);
387 }
388
389 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
390   if(!event->buttons() && !privateData()->hasDragged) {
391     // got a click
392     Clickable click = privateData()->currentClickable;
393     if(click.isValid()) {
394       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
395       switch(click.type) {
396         case Clickable::Url:
397           QDesktopServices::openUrl(str);
398           break;
399         case Clickable::Channel:
400           // TODO join or whatever...
401           break;
402         default:
403           break;
404       }
405     }
406   }
407   ChatItem::mouseReleaseEvent(event);
408 }
409
410 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
411   // mouse move events always mean we're not hovering anymore...
412   endHoverMode();
413   // also, check if we have dragged the mouse
414   if(!privateData()->hasDragged && event->buttons() & Qt::LeftButton
415     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
416     privateData()->hasDragged = true;
417   ChatItem::mouseMoveEvent(event);
418 }
419
420 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
421   endHoverMode();
422   event->accept();
423 }
424
425 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
426   bool onClickable = false;
427   qint16 idx = posToCursor(event->pos());
428   for(int i = 0; i < privateData()->clickables.count(); i++) {
429     Clickable click = privateData()->clickables.at(i);
430     if(idx >= click.start && idx < click.start + click.length) {
431       if(click.type == Clickable::Url)
432         onClickable = true;
433       else if(click.type == Clickable::Channel) {
434         // TODO: don't make clickable if it's our own name
435         //onClickable = true; //FIXME disabled for now
436       }
437       if(onClickable) {
438         setCursor(Qt::PointingHandCursor);
439         privateData()->currentClickable = click;
440         update();
441         break;
442       }
443     }
444   }
445   if(!onClickable) endHoverMode();
446   event->accept();
447 }
448
449 /*************************************************************************************************/
450
451 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
452   : item(_item),
453     layout(0),
454     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
455     wordidx(0),
456     lineCount(0),
457     choppedTrailing(0),
458     lastwrapcol(0),
459     lastwrappos(0),
460     width(0)
461 {
462 }
463
464 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
465   delete layout;
466 }
467
468 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
469   if(wordidx >= wrapList.count())
470     return -1;
471
472   lineCount++;
473   qreal targetWidth = lineCount * item->width() + choppedTrailing;
474
475   qint16 start = wordidx;
476   qint16 end = wrapList.count() - 1;
477
478   // check if the whole line fits
479   if(wrapList.at(end).endX <= targetWidth || start == end)
480     return -1;
481
482   while(true) {
483     if(start == end) {
484       wordidx = start;
485       if(wordidx > 0) {
486         const ChatLineModel::Word &prevWord = wrapList.at(wordidx - 1);
487         choppedTrailing += prevWord.trailing - (targetWidth - prevWord.endX);
488       }
489       return wrapList.at(wordidx).start;
490     }
491     qint16 pivot = (end + start) / 2;
492     if(wrapList.at(pivot).endX > targetWidth && wordidx != pivot) {
493       end = pivot;
494     } else {
495       start = pivot + 1;
496     }
497   }
498   return -1;
499 }
500