Improve ChatMonitorFilter to use Message::Backlog rather than the timestamp
[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(int col, QAbstractItemModel *model, QGraphicsItem *parent)
35   : QGraphicsItem(parent),
36     _fontMetrics(0),
37     _col(col),
38     _lines(0),
39     _layoutData(0),
40     _selectionMode(NoSelection),
41     _selectionStart(-1)
42 {
43   Q_ASSERT(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 }
49
50 ChatItem::~ChatItem() {
51   delete _layoutData;
52 }
53
54 QVariant ChatItem::data(int role) const {
55   QModelIndex index = model()->index(row(), column());
56   if(!index.isValid()) {
57     qWarning() << "ChatItem::data(): model index is invalid!" << index;
58     return QVariant();
59   }
60   return model()->data(index, role);
61 }
62
63 qreal ChatItem::setGeometry(qreal w, qreal h) {
64   if(w == _boundingRect.width()) return _boundingRect.height();
65   prepareGeometryChange();
66   _boundingRect.setWidth(w);
67   if(h < 0) h = computeHeight();
68   _boundingRect.setHeight(h);
69   if(haveLayout()) updateLayout();
70   return h;
71 }
72
73 qreal ChatItem::computeHeight() {
74   if(data(ChatLineModel::ColumnTypeRole).toUInt() != ChatLineModel::ContentsColumn)
75     return fontMetrics()->lineSpacing(); // only contents can be multi-line
76
77   _lines = 1;
78   WrapColumnFinder finder(this);
79   while(finder.nextWrapColumn() > 0) _lines++;
80   return _lines * fontMetrics()->lineSpacing();
81 }
82
83 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
84   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
85
86   QTextOption option;
87   option.setWrapMode(wrapMode);
88   option.setAlignment(alignment);
89   layout->setTextOption(option);
90
91   QList<QTextLayout::FormatRange> formatRanges
92          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
93   layout->setAdditionalFormats(formatRanges);
94   return layout;
95 }
96
97 void ChatItem::setLayout(QTextLayout *layout) {
98   if(!_layoutData)
99     _layoutData = new LayoutData;
100   _layoutData->layout = layout;
101 }
102
103 void ChatItem::updateLayout() {
104   switch(data(ChatLineModel::ColumnTypeRole).toUInt()) {
105     case ChatLineModel::TimestampColumn:
106       if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft));
107       // fallthrough
108     case ChatLineModel::SenderColumn:
109       if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignRight));
110       layout()->beginLayout();
111       {
112         QTextLine line = layout()->createLine();
113         if(line.isValid()) {
114           line.setLineWidth(width());
115           line.setPosition(QPointF(0,0));
116         }
117         layout()->endLayout();
118       }
119       break;
120     case ChatLineModel::ContentsColumn: {
121       if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere));
122
123       // Now layout
124       ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
125       if(!wrapList.count()) return; // empty chatitem
126
127       qreal h = 0;
128       WrapColumnFinder finder(this);
129       layout()->beginLayout();
130       forever {
131         QTextLine line = layout()->createLine();
132         if(!line.isValid())
133           break;
134
135         int col = finder.nextWrapColumn();
136         line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
137         line.setPosition(QPointF(0, h));
138         h += line.height() + fontMetrics()->leading();
139       }
140       layout()->endLayout();
141     }
142     break;
143   }
144 }
145
146 void ChatItem::clearLayoutData() {
147   delete _layoutData;
148   _layoutData = 0;
149 }
150
151 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
152 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
153 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
154   Q_UNUSED(option); Q_UNUSED(widget);
155   if(!haveLayout()) updateLayout();
156   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
157   //if(_selectionMode == FullSelection) {
158     //painter->save();
159     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
160     //painter->restore();
161   //}
162   QVector<QTextLayout::FormatRange> formats;
163   if(_selectionMode != NoSelection) {
164     QTextLayout::FormatRange selectFmt;
165     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
166     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
167     if(_selectionMode == PartialSelection) {
168       selectFmt.start = qMin(_selectionStart, _selectionEnd);
169       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
170     } else { // FullSelection
171       selectFmt.start = 0;
172       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
173     }
174     formats.append(selectFmt);
175   }
176   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
177 }
178
179 qint16 ChatItem::posToCursor(const QPointF &pos) {
180   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
181   if(pos.y() < 0) return 0;
182   if(!haveLayout()) updateLayout();
183   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
184     QTextLine line = layout()->lineAt(l);
185     if(pos.y() >= line.y()) {
186       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
187     }
188   }
189   return 0;
190 }
191
192 void ChatItem::setFullSelection() {
193   if(_selectionMode != FullSelection) {
194     _selectionMode = FullSelection;
195     update();
196   }
197 }
198
199 void ChatItem::clearSelection() {
200   if(_selectionMode != NoSelection) {
201     _selectionMode = NoSelection;
202     update();
203   }
204 }
205
206 void ChatItem::continueSelecting(const QPointF &pos) {
207   _selectionMode = PartialSelection;
208   _selectionEnd = posToCursor(pos);
209   update();
210 }
211
212 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
213   QList<QRectF> resultList;
214   const QAbstractItemModel *model_ = model();
215   if(!model_)
216     return resultList;
217
218   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
219   QList<int> indexList;
220   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
221   while(searchIdx != -1) {
222     indexList << searchIdx;
223     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
224   }
225
226   if(!haveLayout())
227     updateLayout();
228
229   foreach(int idx, indexList) {
230     QTextLine line = layout()->lineForTextPosition(idx);
231     qreal x = line.cursorToX(idx);
232     qreal width = line.cursorToX(idx + searchWord.count()) - x;
233     qreal height = fontMetrics()->lineSpacing();
234     qreal y = height * line.lineNumber();
235     resultList << QRectF(x, y, width, height);
236   }
237   return resultList;
238 }
239
240
241 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
242   if(event->buttons() == Qt::LeftButton) {
243     if(_selectionMode == NoSelection) {
244       chatScene()->setSelectingItem(this);  // removes earlier selection if exists
245       _selectionStart = _selectionEnd = posToCursor(event->pos());
246       //_selectionMode = PartialSelection;
247     } else {
248       chatScene()->setSelectingItem(0);
249       _selectionMode = NoSelection;
250       update();
251     }
252     event->accept();
253   } else {
254     event->ignore();
255   }
256 }
257
258 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
259   if(event->buttons() == Qt::LeftButton) {
260     if(contains(event->pos())) {
261       qint16 end = posToCursor(event->pos());
262       if(end != _selectionEnd) {
263         _selectionEnd = end;
264         if(_selectionStart != _selectionEnd) _selectionMode = PartialSelection;
265         else _selectionMode = NoSelection;
266         update();
267       }
268     } else {
269       setFullSelection();
270       chatScene()->startGlobalSelection(this, event->pos());
271     }
272     event->accept();
273   } else {
274     event->ignore();
275   }
276 }
277
278 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
279   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
280     _selectionEnd = posToCursor(event->pos());
281     QString selection
282         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
283     chatScene()->putToClipboard(selection);
284     event->accept();
285   } else {
286     event->ignore();
287   }
288 }
289
290 void ChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
291   // FIXME dirty and fast hack to make http:// urls klickable
292
293   QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
294   QString str = data(ChatLineModel::DisplayRole).toString();
295   int idx = posToCursor(event->pos());
296   int mi = 0;
297   do {
298     mi = regex.indexIn(str, mi);
299     if(mi < 0) break;
300     if(idx >= mi && idx < mi + regex.matchedLength()) {
301       QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
302       break;
303     }
304     mi += regex.matchedLength();
305   } while(mi >= 0);
306   event->accept();
307 }
308
309 void ChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
310   //qDebug() << (void*)this << "entering";
311   event->ignore();
312 }
313
314 void ChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
315   //qDebug() << (void*)this << "leaving";
316   event->ignore();
317 }
318
319 void ChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
320   //qDebug() << (void*)this << event->pos();
321   event->ignore();
322 }
323
324
325 /*************************************************************************************************/
326
327 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
328   wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
329   wordidx = 0;
330   layout = 0;
331   lastwrapcol = 0;
332   lastwrappos = 0;
333   w = 0;
334 }
335
336 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
337   delete layout;
338 }
339
340 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
341   while(wordidx < wrapList.count()) {
342     w += wrapList.at(wordidx).width;
343     if(w >= item->width()) {
344       if(lastwrapcol >= wrapList.at(wordidx).start) {
345         // first word, and it doesn't fit
346         if(!line.isValid()) {
347           layout = item->createLayout(QTextOption::NoWrap);
348           layout->beginLayout();
349           line = layout->createLine();
350           line.setLineWidth(item->width());
351           layout->endLayout();
352         }
353         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
354         qreal x = line.cursorToX(idx, QTextLine::Trailing);
355         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
356         lastwrappos = x;
357         lastwrapcol = idx;
358         return idx;
359       }
360       // not the first word, so just wrap before this
361       lastwrapcol = wrapList.at(wordidx).start;
362       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
363       w = 0;
364       return lastwrapcol;
365     }
366     w += wrapList.at(wordidx).trailing;
367     wordidx++;
368   }
369   return -1;
370 }