clean up
[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 the following lines to draw the bounding rect and the row number in alternating colors
123 //   if(row() % 2)
124 //     painter->setPen(Qt::red);
125 //   else
126 //     painter->setPen(Qt::blue);
127 //   QString rowString = QString::number(row());
128 //   QRect rowRect = painter->fontMetrics().boundingRect(rowString);
129 //   QPointF topPoint = _boundingRect.topLeft();
130 //   topPoint.ry() += rowRect.height();
131 //   painter->drawText(topPoint, rowString);
132 //   QPointF bottomPoint = _boundingRect.bottomRight();
133 //   bottomPoint.rx() -= rowRect.width();
134 //   painter->drawText(bottomPoint, rowString);
135 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
136 }
137
138 qint16 ChatItem::posToCursor(const QPointF &pos) {
139   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
140   if(pos.y() < 0) return 0;
141   if(!hasLayout())
142     updateLayout();
143   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
144     QTextLine line = layout()->lineAt(l);
145     if(pos.y() >= line.y()) {
146       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
147     }
148   }
149   return 0;
150 }
151
152 void ChatItem::setFullSelection() {
153   if(_selectionMode != FullSelection) {
154     _selectionMode = FullSelection;
155     update();
156   }
157 }
158
159 void ChatItem::clearSelection() {
160   _selectionMode = NoSelection;
161   update();
162 }
163
164 void ChatItem::continueSelecting(const QPointF &pos) {
165   _selectionMode = PartialSelection;
166   _selectionEnd = posToCursor(pos);
167   update();
168 }
169
170 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
171   QList<QRectF> resultList;
172   const QAbstractItemModel *model_ = model();
173   if(!model_)
174     return resultList;
175
176   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
177   QList<int> indexList;
178   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
179   while(searchIdx != -1) {
180     indexList << searchIdx;
181     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
182   }
183
184   bool hadLayout = hasLayout();
185   if(!hadLayout)
186     updateLayout();
187
188   foreach(int idx, indexList) {
189     QTextLine line = layout()->lineForTextPosition(idx);
190     qreal x = line.cursorToX(idx);
191     qreal width = line.cursorToX(idx + searchWord.count()) - x;
192     qreal height = line.height();
193     qreal y = height * line.lineNumber();
194     resultList << QRectF(x, y, width, height);
195   }
196
197   if(!hadLayout)
198     clearLayout();
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, parent)
254 {
255   const QAbstractItemModel *model_ = model();
256   QModelIndex index = model_->index(row(), column());
257   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
258
259   setGeometryByWidth(width);
260 }
261
262 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
263   if(w != width()) {
264     setWidth(w);
265     // compute height
266     int lines = 1;
267     WrapColumnFinder finder(this);
268     while(finder.nextWrapColumn() > 0)
269       lines++;
270     setHeight(lines * fontMetrics()->lineSpacing());
271   }
272   return height();
273 }
274
275 void ContentsChatItem::updateLayout() {
276   if(!privateData()) {
277     ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere),
278                                                                 findClickables());
279     // data->clickables = findClickables();
280     setPrivateData(data);
281   }
282
283   // Now layout
284   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
285   if(!wrapList.count()) return; // empty chatitem
286
287   qreal h = 0;
288   WrapColumnFinder finder(this);
289   layout()->beginLayout();
290   forever {
291     QTextLine line = layout()->createLine();
292     if(!line.isValid())
293       break;
294
295     int col = finder.nextWrapColumn();
296     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
297     line.setPosition(QPointF(0, h));
298     h += fontMetrics()->lineSpacing();
299   }
300   layout()->endLayout();
301 }
302
303 // NOTE: This method is not threadsafe and not reentrant!
304 //       (RegExps are not constant while matching, and they are static here for efficiency)
305 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
306   // For matching URLs
307   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
308   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
309
310   static QRegExp regExp[] = {
311     // URL
312     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
313     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
314
315     // Channel name
316     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
317     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
318
319     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
320   };
321
322   static const int regExpCount = 2;  // number of regexps in the array above
323
324   qint16 matches[] = { 0, 0, 0 };
325   qint16 matchEnd[] = { 0, 0, 0 };
326
327   QString str = data(ChatLineModel::DisplayRole).toString();
328
329   QList<Clickable> result;
330   qint16 idx = 0;
331   qint16 minidx;
332   int type = -1;
333
334   do {
335     type = -1;
336     minidx = str.length();
337     for(int i = 0; i < regExpCount; i++) {
338       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
339       if(idx >= matchEnd[i]) {
340         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
341         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
342       }
343       if(matches[i] >= 0 && matches[i] < minidx) {
344         minidx = matches[i];
345         type = i;
346       }
347     }
348     if(type >= 0) {
349       idx = matchEnd[type];
350       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
351         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
352       }
353       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
354     }
355   } while(type >= 0);
356
357   /* testing
358   if(!result.isEmpty()) qDebug() << str;
359   foreach(Clickable click, result) {
360     qDebug() << str.mid(click.start, click.length);
361   }
362   */
363   return result;
364 }
365
366 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
367   // mark a clickable if hovered upon
368   QVector<QTextLayout::FormatRange> fmt;
369   if(privateData()->currentClickable.isValid()) {
370     Clickable click = privateData()->currentClickable;
371     QTextLayout::FormatRange f;
372     f.start = click.start;
373     f.length = click.length;
374     f.format.setFontUnderline(true);
375     fmt.append(f);
376   }
377   return fmt;
378 }
379
380 void ContentsChatItem::endHoverMode() {
381   if(privateData()->currentClickable.isValid()) {
382     setCursor(Qt::ArrowCursor);
383     privateData()->currentClickable = Clickable();
384     update();
385   }
386 }
387
388 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
389   privateData()->hasDragged = false;
390   ChatItem::mousePressEvent(event);
391 }
392
393 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
394   if(!event->buttons() && !privateData()->hasDragged) {
395     // got a click
396     Clickable click = privateData()->currentClickable;
397     if(click.isValid()) {
398       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
399       switch(click.type) {
400         case Clickable::Url:
401           QDesktopServices::openUrl(str);
402           break;
403         case Clickable::Channel:
404           // TODO join or whatever...
405           break;
406         default:
407           break;
408       }
409     }
410   }
411   ChatItem::mouseReleaseEvent(event);
412 }
413
414 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
415   // mouse move events always mean we're not hovering anymore...
416   endHoverMode();
417   // also, check if we have dragged the mouse
418   if(!privateData()->hasDragged && event->buttons() & Qt::LeftButton
419     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
420     privateData()->hasDragged = true;
421   ChatItem::mouseMoveEvent(event);
422 }
423
424 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
425   endHoverMode();
426   event->accept();
427 }
428
429 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
430   bool onClickable = false;
431   qint16 idx = posToCursor(event->pos());
432   for(int i = 0; i < privateData()->clickables.count(); i++) {
433     Clickable click = privateData()->clickables.at(i);
434     if(idx >= click.start && idx < click.start + click.length) {
435       if(click.type == Clickable::Url)
436         onClickable = true;
437       else if(click.type == Clickable::Channel) {
438         // TODO: don't make clickable if it's our own name
439         //onClickable = true; //FIXME disabled for now
440       }
441       if(onClickable) {
442         setCursor(Qt::PointingHandCursor);
443         privateData()->currentClickable = click;
444         update();
445         break;
446       }
447     }
448   }
449   if(!onClickable) endHoverMode();
450   event->accept();
451 }
452
453 /*************************************************************************************************/
454
455 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
456   : item(_item),
457     layout(0),
458     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
459     wordidx(0),
460     lineCount(0),
461     choppedTrailing(0)
462 {
463 }
464
465 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
466   delete layout;
467 }
468
469 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
470   if(wordidx >= wrapList.count())
471     return -1;
472
473   lineCount++;
474   qreal targetWidth = lineCount * item->width() + choppedTrailing;
475
476   qint16 start = wordidx;
477   qint16 end = wrapList.count() - 1;
478
479   // check if the whole line fits
480   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
481     return -1;
482
483   // check if we have a very long word that needs inter word wrap
484   if(wrapList.at(start).endX > targetWidth) {
485     if(!line.isValid()) {
486       layout = item->createLayout(QTextOption::NoWrap);
487       layout->beginLayout();
488       line = layout->createLine();
489       layout->endLayout();
490     }
491     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
492   }
493
494   while(true) {
495     if(start + 1 == end) {
496       wordidx = end;
497       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
498
499       // both cases should be cought preliminary
500       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
501       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
502
503       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
504       return wrapList.at(wordidx).start;
505     }
506
507     qint16 pivot = (end + start) / 2;
508     if(wrapList.at(pivot).endX > targetWidth) {
509       end = pivot;
510     } else {
511       start = pivot;
512     }
513   }
514   Q_ASSERT(false);
515   return -1;
516 }
517