a087d6cd49b5578b31d2a031e608e8ce26862647
[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
34 ChatItem::ChatItem(ChatLineModel::ColumnType col, QAbstractItemModel *model, QGraphicsItem *parent)
35   : QGraphicsItem(parent),
36     _fontMetrics(0),
37     _selectionMode(NoSelection),
38     _selectionStart(-1),
39     _layout(0)
40 {
41   Q_ASSERT(model);
42   QModelIndex index = model->index(row(), col);
43   _fontMetrics = QtUi::style()->fontMetrics(model->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
44   setAcceptHoverEvents(true);
45   setZValue(20);
46 }
47
48 ChatItem::~ChatItem() {
49   delete _layout;
50 }
51
52 QVariant ChatItem::data(int role) const {
53   QModelIndex index = model()->index(row(), column());
54   if(!index.isValid()) {
55     qWarning() << "ChatItem::data(): model index is invalid!" << index;
56     return QVariant();
57   }
58   return model()->data(index, role);
59 }
60
61 qreal ChatItem::setGeometry(qreal w, qreal h) {
62   if(w == _boundingRect.width()) return _boundingRect.height();
63   prepareGeometryChange();
64   _boundingRect.setWidth(w);
65   if(h < 0) h = computeHeight();
66   _boundingRect.setHeight(h);
67   if(haveLayout()) updateLayout();
68   return h;
69 }
70
71 qreal ChatItem::computeHeight() {
72   return fontMetrics()->lineSpacing(); // only contents can be multi-line
73 }
74
75 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
76   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
77
78   QTextOption option;
79   option.setWrapMode(wrapMode);
80   option.setAlignment(alignment);
81   layout->setTextOption(option);
82
83   QList<QTextLayout::FormatRange> formatRanges
84          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
85   layout->setAdditionalFormats(formatRanges);
86   return layout;
87 }
88
89 void ChatItem::updateLayout() {
90   if(!haveLayout())
91     setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft));
92
93   layout()->beginLayout();
94   QTextLine line = layout()->createLine();
95   if(line.isValid()) {
96     line.setLineWidth(width());
97     line.setPosition(QPointF(0,0));
98   }
99   layout()->endLayout();
100 }
101
102 void ChatItem::clearLayout() {
103   delete _layout;
104   _layout = 0;
105 }
106
107 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
108 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
109 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
110   Q_UNUSED(option); Q_UNUSED(widget);
111   if(!haveLayout()) updateLayout();
112   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
113   //if(_selectionMode == FullSelection) {
114     //painter->save();
115     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
116     //painter->restore();
117   //}
118   QVector<QTextLayout::FormatRange> formats = additionalFormats();
119   if(_selectionMode != NoSelection) {
120     QTextLayout::FormatRange selectFmt;
121     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
122     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
123     if(_selectionMode == PartialSelection) {
124       selectFmt.start = qMin(_selectionStart, _selectionEnd);
125       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
126     } else { // FullSelection
127       selectFmt.start = 0;
128       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
129     }
130     formats.append(selectFmt);
131   }
132   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
133 }
134
135 qint16 ChatItem::posToCursor(const QPointF &pos) {
136   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
137   if(pos.y() < 0) return 0;
138   if(!haveLayout()) updateLayout();
139   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
140     QTextLine line = layout()->lineAt(l);
141     if(pos.y() >= line.y()) {
142       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
143     }
144   }
145   return 0;
146 }
147
148 void ChatItem::setFullSelection() {
149   if(_selectionMode != FullSelection) {
150     _selectionMode = FullSelection;
151     update();
152   }
153 }
154
155 void ChatItem::clearSelection() {
156   _selectionMode = NoSelection;
157   update();
158 }
159
160 void ChatItem::continueSelecting(const QPointF &pos) {
161   _selectionMode = PartialSelection;
162   _selectionEnd = posToCursor(pos);
163   update();
164 }
165
166 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
167   QList<QRectF> resultList;
168   const QAbstractItemModel *model_ = model();
169   if(!model_)
170     return resultList;
171
172   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
173   QList<int> indexList;
174   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
175   while(searchIdx != -1) {
176     indexList << searchIdx;
177     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
178   }
179
180   if(!haveLayout())
181     updateLayout();
182
183   foreach(int idx, indexList) {
184     QTextLine line = layout()->lineForTextPosition(idx);
185     qreal x = line.cursorToX(idx);
186     qreal width = line.cursorToX(idx + searchWord.count()) - x;
187     qreal height = fontMetrics()->lineSpacing();
188     qreal y = height * line.lineNumber();
189     resultList << QRectF(x, y, width, height);
190   }
191   return resultList;
192 }
193
194 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
195   if(event->buttons() == Qt::LeftButton) {
196     chatScene()->setSelectingItem(this);
197     _selectionStart = _selectionEnd = posToCursor(event->pos());
198     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
199     update();
200     event->accept();
201   } else {
202     event->ignore();
203   }
204 }
205
206 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
207   if(event->buttons() == Qt::LeftButton) {
208     if(contains(event->pos())) {
209       qint16 end = posToCursor(event->pos());
210       if(end != _selectionEnd) {
211         _selectionEnd = end;
212         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
213         update();
214       }
215     } else {
216       setFullSelection();
217       chatScene()->startGlobalSelection(this, event->pos());
218     }
219     event->accept();
220   } else {
221     event->ignore();
222   }
223 }
224
225 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
226   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
227     _selectionEnd = posToCursor(event->pos());
228     QString selection
229         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
230     chatScene()->putToClipboard(selection);
231     event->accept();
232   } else {
233     event->ignore();
234   }
235 }
236
237 /*************************************************************************************************/
238
239 /*************************************************************************************************/
240
241 void SenderChatItem::updateLayout() {
242   if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignRight));
243   ChatItem::updateLayout();
244 }
245
246 /*************************************************************************************************/
247
248 ContentsChatItem::ContentsChatItem(QAbstractItemModel *model, QGraphicsItem *parent) : ChatItem(column(), model, parent),
249   _layoutData(0)
250 {
251
252 }
253
254 ContentsChatItem::~ContentsChatItem() {
255   delete _layoutData;
256 }
257
258 qreal ContentsChatItem::computeHeight() {
259   int lines = 1;
260   WrapColumnFinder finder(this);
261   while(finder.nextWrapColumn() > 0) lines++;
262   return lines * fontMetrics()->lineSpacing();
263 }
264
265 void ContentsChatItem::setLayout(QTextLayout *layout) {
266   if(!_layoutData) {
267     _layoutData = new LayoutData;
268     _layoutData->clickables = findClickables();
269   } else {
270     delete _layoutData->layout;
271   }
272   _layoutData->layout = layout;
273 }
274
275 void ContentsChatItem::clearLayout() {
276   delete _layoutData;
277   _layoutData = 0;
278 }
279
280 void ContentsChatItem::updateLayout() {
281   if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere));
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(layoutData()->currentClickable.isValid()) {
370     Clickable click = layoutData()->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(layoutData()->currentClickable.isValid()) {
382     setCursor(Qt::ArrowCursor);
383     layoutData()->currentClickable = Clickable();
384     update();
385   }
386 }
387
388 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
389   layoutData()->hasDragged = false;
390   ChatItem::mousePressEvent(event);
391 }
392
393 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
394   if(!event->buttons() && !layoutData()->hasDragged) {
395     // got a click
396     Clickable click = layoutData()->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(!layoutData()->hasDragged && event->buttons() & Qt::LeftButton
419     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
420     layoutData()->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 < layoutData()->clickables.count(); i++) {
433     Clickable click = layoutData()->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         layoutData()->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     lastwrapcol(0),
461     lastwrappos(0),
462     w(0)
463 {
464 }
465
466 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
467   delete layout;
468 }
469
470 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
471   while(wordidx < wrapList.count()) {
472     w += wrapList.at(wordidx).width;
473     if(w >= item->width()) {
474       if(lastwrapcol >= wrapList.at(wordidx).start) {
475         // first word, and it doesn't fit
476         if(!line.isValid()) {
477           layout = item->createLayout(QTextOption::NoWrap);
478           layout->beginLayout();
479           line = layout->createLine();
480           line.setLineWidth(item->width());
481           layout->endLayout();
482         }
483         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
484         qreal x = line.cursorToX(idx, QTextLine::Trailing);
485         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
486         lastwrappos = x;
487         lastwrapcol = idx;
488         return idx;
489       }
490       // not the first word, so just wrap before this
491       lastwrapcol = wrapList.at(wordidx).start;
492       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
493       w = 0;
494       return lastwrapcol;
495     }
496     w += wrapList.at(wordidx).trailing;
497     wordidx++;
498   }
499   return -1;
500 }