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