Test our newly acquired shortcut capabilities by finally allowing Ctrl+F to trigger...
[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(ChatLineModel::ColumnType col, QAbstractItemModel *model, QGraphicsItem *parent)
36   : QGraphicsItem(parent),
37     _fontMetrics(0),
38     _selectionMode(NoSelection),
39     _selectionStart(-1),
40     _layout(0)
41 {
42   Q_ASSERT(model);
43   QModelIndex index = model->index(row(), col);
44   _fontMetrics = QtUi::style()->fontMetrics(model->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
45   setAcceptHoverEvents(true);
46   setZValue(20);
47 }
48
49 ChatItem::~ChatItem() {
50   delete _layout;
51 }
52
53 QVariant ChatItem::data(int role) const {
54   QModelIndex index = model()->index(row(), column());
55   if(!index.isValid()) {
56     qWarning() << "ChatItem::data(): model index is invalid!" << index;
57     return QVariant();
58   }
59   return model()->data(index, role);
60 }
61
62 qreal ChatItem::setGeometry(qreal w, qreal h) {
63   if(w == _boundingRect.width()) return _boundingRect.height();
64   prepareGeometryChange();
65   _boundingRect.setWidth(w);
66   if(h < 0) h = computeHeight();
67   _boundingRect.setHeight(h);
68   if(haveLayout()) updateLayout();
69   return h;
70 }
71
72 qreal ChatItem::computeHeight() {
73   return fontMetrics()->lineSpacing(); // only contents can be multi-line
74 }
75
76 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
77   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
78
79   QTextOption option;
80   option.setWrapMode(wrapMode);
81   option.setAlignment(alignment);
82   layout->setTextOption(option);
83
84   QList<QTextLayout::FormatRange> formatRanges
85          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
86   layout->setAdditionalFormats(formatRanges);
87   return layout;
88 }
89
90 void ChatItem::updateLayout() {
91   if(!haveLayout())
92     setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft));
93
94   layout()->beginLayout();
95   QTextLine line = layout()->createLine();
96   if(line.isValid()) {
97     line.setLineWidth(width());
98     line.setPosition(QPointF(0,0));
99   }
100   layout()->endLayout();
101 }
102
103 void ChatItem::clearLayout() {
104   delete _layout;
105   _layout = 0;
106 }
107
108 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
109 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
110 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
111   Q_UNUSED(option); Q_UNUSED(widget);
112   if(!haveLayout()) updateLayout();
113   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
114   //if(_selectionMode == FullSelection) {
115     //painter->save();
116     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
117     //painter->restore();
118   //}
119   QVector<QTextLayout::FormatRange> formats = additionalFormats();
120   if(_selectionMode != NoSelection) {
121     QTextLayout::FormatRange selectFmt;
122     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
123     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
124     if(_selectionMode == PartialSelection) {
125       selectFmt.start = qMin(_selectionStart, _selectionEnd);
126       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
127     } else { // FullSelection
128       selectFmt.start = 0;
129       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
130     }
131     formats.append(selectFmt);
132   }
133   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
134 }
135
136 qint16 ChatItem::posToCursor(const QPointF &pos) {
137   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
138   if(pos.y() < 0) return 0;
139   if(!haveLayout()) updateLayout();
140   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
141     QTextLine line = layout()->lineAt(l);
142     if(pos.y() >= line.y()) {
143       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
144     }
145   }
146   return 0;
147 }
148
149 void ChatItem::setFullSelection() {
150   if(_selectionMode != FullSelection) {
151     _selectionMode = FullSelection;
152     update();
153   }
154 }
155
156 void ChatItem::clearSelection() {
157   _selectionMode = NoSelection;
158   update();
159 }
160
161 void ChatItem::continueSelecting(const QPointF &pos) {
162   _selectionMode = PartialSelection;
163   _selectionEnd = posToCursor(pos);
164   update();
165 }
166
167 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
168   QList<QRectF> resultList;
169   const QAbstractItemModel *model_ = model();
170   if(!model_)
171     return resultList;
172
173   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
174   QList<int> indexList;
175   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
176   while(searchIdx != -1) {
177     indexList << searchIdx;
178     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
179   }
180
181   if(!haveLayout())
182     updateLayout();
183
184   foreach(int idx, indexList) {
185     QTextLine line = layout()->lineForTextPosition(idx);
186     qreal x = line.cursorToX(idx);
187     qreal width = line.cursorToX(idx + searchWord.count()) - x;
188     qreal height = fontMetrics()->lineSpacing();
189     qreal y = height * line.lineNumber();
190     resultList << QRectF(x, y, width, height);
191   }
192   return resultList;
193 }
194
195 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
196   if(event->buttons() == Qt::LeftButton) {
197     chatScene()->setSelectingItem(this);
198     _selectionStart = _selectionEnd = posToCursor(event->pos());
199     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
200     update();
201     event->accept();
202   } else {
203     event->ignore();
204   }
205 }
206
207 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
208   if(event->buttons() == Qt::LeftButton) {
209     if(contains(event->pos())) {
210       qint16 end = posToCursor(event->pos());
211       if(end != _selectionEnd) {
212         _selectionEnd = end;
213         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
214         update();
215       }
216     } else {
217       setFullSelection();
218       chatScene()->startGlobalSelection(this, event->pos());
219     }
220     event->accept();
221   } else {
222     event->ignore();
223   }
224 }
225
226 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
227   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
228     _selectionEnd = posToCursor(event->pos());
229     QString selection
230         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
231     chatScene()->putToClipboard(selection);
232     event->accept();
233   } else {
234     event->ignore();
235   }
236 }
237
238 /*************************************************************************************************/
239
240 /*************************************************************************************************/
241
242 void SenderChatItem::updateLayout() {
243   if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignRight));
244   ChatItem::updateLayout();
245 }
246
247 /*************************************************************************************************/
248
249 ContentsChatItem::ContentsChatItem(QAbstractItemModel *model, QGraphicsItem *parent) : ChatItem(column(), model, parent),
250   _layoutData(0)
251 {
252
253 }
254
255 ContentsChatItem::~ContentsChatItem() {
256   delete _layoutData;
257 }
258
259 qreal ContentsChatItem::computeHeight() {
260   int lines = 1;
261   WrapColumnFinder finder(this);
262   while(finder.nextWrapColumn() > 0) lines++;
263   return lines * fontMetrics()->lineSpacing();
264 }
265
266 void ContentsChatItem::setLayout(QTextLayout *layout) {
267   if(!_layoutData) {
268     _layoutData = new LayoutData;
269     _layoutData->clickables = findClickables();
270   } else {
271     delete _layoutData->layout;
272   }
273   _layoutData->layout = layout;
274 }
275
276 void ContentsChatItem::clearLayout() {
277   delete _layoutData;
278   _layoutData = 0;
279 }
280
281 void ContentsChatItem::updateLayout() {
282   if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere));
283
284   // Now layout
285   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
286   if(!wrapList.count()) return; // empty chatitem
287
288   qreal h = 0;
289   WrapColumnFinder finder(this);
290   layout()->beginLayout();
291   forever {
292     QTextLine line = layout()->createLine();
293     if(!line.isValid())
294       break;
295
296     int col = finder.nextWrapColumn();
297     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
298     line.setPosition(QPointF(0, h));
299     h += fontMetrics()->lineSpacing();
300   }
301   layout()->endLayout();
302 }
303
304 // NOTE: This method is not threadsafe and not reentrant!
305 //       (RegExps are not constant while matching, and they are static here for efficiency)
306 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
307   // For matching URLs
308   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
309   static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
310
311   static QRegExp regExp[] = {
312     // URL
313     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
314     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
315
316     // Channel name
317     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
318     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
319
320     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
321   };
322
323   static const int regExpCount = 2;  // number of regexps in the array above
324
325   qint16 matches[] = { 0, 0, 0 };
326   qint16 matchEnd[] = { 0, 0, 0 };
327
328   QString str = data(ChatLineModel::DisplayRole).toString();
329
330   QList<Clickable> result;
331   qint16 idx = 0;
332   qint16 minidx;
333   int type = -1;
334
335   do {
336     type = -1;
337     minidx = str.length();
338     for(int i = 0; i < regExpCount; i++) {
339       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
340       if(idx >= matchEnd[i]) {
341         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
342         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
343       }
344       if(matches[i] >= 0 && matches[i] < minidx) {
345         minidx = matches[i];
346         type = i;
347       }
348     }
349     if(type >= 0) {
350       idx = matchEnd[type];
351       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
352         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
353       }
354       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
355     }
356   } while(type >= 0);
357
358   /* testing
359   if(!result.isEmpty()) qDebug() << str;
360   foreach(Clickable click, result) {
361     qDebug() << str.mid(click.start, click.length);
362   }
363   */
364   return result;
365 }
366
367 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
368   // mark a clickable if hovered upon
369   QVector<QTextLayout::FormatRange> fmt;
370   if(layoutData()->currentClickable.isValid()) {
371     Clickable click = layoutData()->currentClickable;
372     QTextLayout::FormatRange f;
373     f.start = click.start;
374     f.length = click.length;
375     f.format.setFontUnderline(true);
376     fmt.append(f);
377   }
378   return fmt;
379 }
380
381 void ContentsChatItem::endHoverMode() {
382   if(layoutData()->currentClickable.isValid()) {
383     setCursor(Qt::ArrowCursor);
384     layoutData()->currentClickable = Clickable();
385     update();
386   }
387 }
388
389 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
390   layoutData()->hasDragged = false;
391   ChatItem::mousePressEvent(event);
392 }
393
394 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
395   if(!event->buttons() && !layoutData()->hasDragged) {
396     // got a click
397     Clickable click = layoutData()->currentClickable;
398     if(click.isValid()) {
399       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
400       switch(click.type) {
401         case Clickable::Url:
402           QDesktopServices::openUrl(str);
403           break;
404         case Clickable::Channel:
405           // TODO join or whatever...
406           break;
407         default:
408           break;
409       }
410     }
411   }
412   ChatItem::mouseReleaseEvent(event);
413 }
414
415 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
416   // mouse move events always mean we're not hovering anymore...
417   endHoverMode();
418   // also, check if we have dragged the mouse
419   if(!layoutData()->hasDragged && event->buttons() & Qt::LeftButton
420     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
421     layoutData()->hasDragged = true;
422   ChatItem::mouseMoveEvent(event);
423 }
424
425 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
426   endHoverMode();
427   event->accept();
428 }
429
430 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
431   bool onClickable = false;
432   qint16 idx = posToCursor(event->pos());
433   for(int i = 0; i < layoutData()->clickables.count(); i++) {
434     Clickable click = layoutData()->clickables.at(i);
435     if(idx >= click.start && idx < click.start + click.length) {
436       if(click.type == Clickable::Url)
437         onClickable = true;
438       else if(click.type == Clickable::Channel) {
439         // TODO: don't make clickable if it's our own name
440         //onClickable = true; //FIXME disabled for now
441       }
442       if(onClickable) {
443         setCursor(Qt::PointingHandCursor);
444         layoutData()->currentClickable = click;
445         update();
446         break;
447       }
448     }
449   }
450   if(!onClickable) endHoverMode();
451   event->accept();
452 }
453
454 /*************************************************************************************************/
455
456 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
457   : item(_item),
458     layout(0),
459     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
460     wordidx(0),
461     lastwrapcol(0),
462     lastwrappos(0),
463     w(0)
464 {
465 }
466
467 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
468   delete layout;
469 }
470
471 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
472   while(wordidx < wrapList.count()) {
473     w += wrapList.at(wordidx).width;
474     if(w >= item->width()) {
475       if(lastwrapcol >= wrapList.at(wordidx).start) {
476         // first word, and it doesn't fit
477         if(!line.isValid()) {
478           layout = item->createLayout(QTextOption::NoWrap);
479           layout->beginLayout();
480           line = layout->createLine();
481           line.setLineWidth(item->width());
482           layout->endLayout();
483         }
484         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
485         qreal x = line.cursorToX(idx, QTextLine::Trailing);
486         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
487         lastwrappos = x;
488         lastwrapcol = idx;
489         return idx;
490       }
491       // not the first word, so just wrap before this
492       lastwrapcol = wrapList.at(wordidx).start;
493       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
494       w = 0;
495       return lastwrapcol;
496     }
497     w += wrapList.at(wordidx).trailing;
498     wordidx++;
499   }
500   return -1;
501 }