Fixed URL recognizer to not endlessly loop anymore
[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     _layout(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 _layout;
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::setWidth(qreal w) {
64   if(w == _boundingRect.width()) return _boundingRect.height();
65   prepareGeometryChange();
66   _boundingRect.setWidth(w);
67   qreal 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::updateLayout() {
98   switch(data(ChatLineModel::ColumnTypeRole).toUInt()) {
99     case ChatLineModel::TimestampColumn:
100       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft);
101       // fallthrough
102     case ChatLineModel::SenderColumn:
103       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere, Qt::AlignRight);
104       _layout->beginLayout();
105       {
106         QTextLine line = _layout->createLine();
107         if(line.isValid()) {
108           line.setLineWidth(width());
109           line.setPosition(QPointF(0,0));
110         }
111         _layout->endLayout();
112       }
113       break;
114     case ChatLineModel::ContentsColumn: {
115       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere);
116
117       // Now layout
118       ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
119       if(!wrapList.count()) return; // empty chatitem
120
121       qreal h = 0;
122       WrapColumnFinder finder(this);
123       _layout->beginLayout();
124       forever {
125         QTextLine line = _layout->createLine();
126         if(!line.isValid())
127           break;
128
129         int col = finder.nextWrapColumn();
130         line.setNumColumns(col >= 0 ? col - line.textStart() : _layout->text().length());
131         line.setPosition(QPointF(0, h));
132         h += line.height() + fontMetrics()->leading();
133       }
134       _layout->endLayout();
135     }
136     break;
137   }
138 }
139
140 void ChatItem::clearLayout() {
141   delete _layout;
142   _layout = 0;
143 }
144
145 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
146 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
147 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
148   Q_UNUSED(option); Q_UNUSED(widget);
149   if(!haveLayout()) updateLayout();
150   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
151   //if(_selectionMode == FullSelection) {
152     //painter->save();
153     //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
154     //painter->restore();
155   //}
156   QVector<QTextLayout::FormatRange> formats;
157   if(_selectionMode != NoSelection) {
158     QTextLayout::FormatRange selectFmt;
159     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
160     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
161     if(_selectionMode == PartialSelection) {
162       selectFmt.start = qMin(_selectionStart, _selectionEnd);
163       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
164     } else { // FullSelection
165       selectFmt.start = 0;
166       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
167     }
168     formats.append(selectFmt);
169   }
170   _layout->draw(painter, QPointF(0,0), formats, boundingRect());
171 }
172
173 qint16 ChatItem::posToCursor(const QPointF &pos) {
174   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
175   if(pos.y() < 0) return 0;
176   if(!haveLayout()) updateLayout();
177   for(int l = _layout->lineCount() - 1; l >= 0; l--) {
178     QTextLine line = _layout->lineAt(l);
179     if(pos.y() >= line.y()) {
180       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
181     }
182   }
183   return 0;
184 }
185
186 void ChatItem::setFullSelection() {
187   if(_selectionMode != FullSelection) {
188     _selectionMode = FullSelection;
189     update();
190   }
191 }
192
193 void ChatItem::clearSelection() {
194   if(_selectionMode != NoSelection) {
195     _selectionMode = NoSelection;
196     update();
197   }
198 }
199
200 void ChatItem::continueSelecting(const QPointF &pos) {
201   _selectionMode = PartialSelection;
202   _selectionEnd = posToCursor(pos);
203   update();
204 }
205
206 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
207   if(event->buttons() & Qt::LeftButton) {
208     if(_selectionMode == NoSelection) {
209       chatScene()->setSelectingItem(this);  // removes earlier selection if exists
210       _selectionStart = _selectionEnd = posToCursor(event->pos());
211       _selectionMode = PartialSelection;
212     } else {
213       chatScene()->setSelectingItem(0);
214       _selectionMode = NoSelection;
215       update();
216     }
217     event->accept();
218   } else {
219     event->ignore();
220   }
221 }
222
223 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
224   if(contains(event->pos())) {
225     qint16 end = posToCursor(event->pos());
226     if(end != _selectionEnd) {
227       _selectionEnd = end;
228       update();
229     }
230   } else {
231     setFullSelection();
232     chatScene()->startGlobalSelection(this, event->pos());
233   }
234 }
235
236 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
237   if(_selectionMode != NoSelection) {
238     _selectionEnd = posToCursor(event->pos());
239     QString selection
240         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
241     QApplication::clipboard()->setText(selection, QClipboard::Clipboard);  // TODO configure where selections should go
242     event->accept();
243   } else {
244     event->ignore();
245   }
246 }
247
248 void ChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
249   // FIXME dirty and fast hack to make http:// urls klickable
250
251   QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
252   QString str = data(ChatLineModel::DisplayRole).toString();
253   int idx = posToCursor(event->pos());
254   int mi = 0;
255   do {
256     mi = regex.indexIn(str, mi);
257     if(mi < 0) break;
258     if(idx >= mi && idx < mi + regex.matchedLength()) {
259       QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
260       break;
261     }
262     mi += regex.matchedLength();
263   } while(mi >= 0);
264   event->accept();
265 }
266
267 void ChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
268   //qDebug() << (void*)this << "entering";
269
270 }
271
272 void ChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
273   //qDebug() << (void*)this << "leaving";
274
275 }
276
277 void ChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
278   //qDebug() << (void*)this << event->pos();
279
280 }
281
282
283 /*************************************************************************************************/
284
285 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
286   wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
287   wordidx = 0;
288   layout = 0;
289   lastwrapcol = 0;
290   lastwrappos = 0;
291   w = 0;
292 }
293
294 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
295   delete layout;
296 }
297
298 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
299   while(wordidx < wrapList.count()) {
300     w += wrapList.at(wordidx).width;
301     if(w >= item->width()) {
302       if(lastwrapcol >= wrapList.at(wordidx).start) {
303         // first word, and it doesn't fit
304         if(!line.isValid()) {
305           layout = item->createLayout(QTextOption::NoWrap);
306           layout->beginLayout();
307           line = layout->createLine();
308           line.setLineWidth(item->width());
309           layout->endLayout();
310         }
311         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
312         qreal x = line.cursorToX(idx, QTextLine::Trailing);
313         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
314         lastwrappos = x;
315         lastwrapcol = idx;
316         return idx;
317       }
318       // not the first word, so just wrap before this
319       lastwrapcol = wrapList.at(wordidx).start;
320       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
321       w = 0;
322       return lastwrapcol;
323     }
324     w += wrapList.at(wordidx).trailing;
325     wordidx++;
326   }
327   return -1;
328 }