Introduce discardable LayoutData
[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 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
213   if(event->buttons() == Qt::LeftButton) {
214     if(_selectionMode == NoSelection) {
215       chatScene()->setSelectingItem(this);  // removes earlier selection if exists
216       _selectionStart = _selectionEnd = posToCursor(event->pos());
217       //_selectionMode = PartialSelection;
218     } else {
219       chatScene()->setSelectingItem(0);
220       _selectionMode = NoSelection;
221       update();
222     }
223     event->accept();
224   } else {
225     event->ignore();
226   }
227 }
228
229 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
230   if(event->buttons() == Qt::LeftButton) {
231     if(contains(event->pos())) {
232       qint16 end = posToCursor(event->pos());
233       if(end != _selectionEnd) {
234         _selectionEnd = end;
235         if(_selectionStart != _selectionEnd) _selectionMode = PartialSelection;
236         else _selectionMode = NoSelection;
237         update();
238       }
239     } else {
240       setFullSelection();
241       chatScene()->startGlobalSelection(this, event->pos());
242     }
243     event->accept();
244   } else {
245     event->ignore();
246   }
247 }
248
249 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
250   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
251     _selectionEnd = posToCursor(event->pos());
252     QString selection
253         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
254     chatScene()->putToClipboard(selection);
255     event->accept();
256   } else {
257     event->ignore();
258   }
259 }
260
261 void ChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
262   // FIXME dirty and fast hack to make http:// urls klickable
263
264   QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
265   QString str = data(ChatLineModel::DisplayRole).toString();
266   int idx = posToCursor(event->pos());
267   int mi = 0;
268   do {
269     mi = regex.indexIn(str, mi);
270     if(mi < 0) break;
271     if(idx >= mi && idx < mi + regex.matchedLength()) {
272       QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
273       break;
274     }
275     mi += regex.matchedLength();
276   } while(mi >= 0);
277   event->accept();
278 }
279
280 void ChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
281   //qDebug() << (void*)this << "entering";
282   event->ignore();
283 }
284
285 void ChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
286   //qDebug() << (void*)this << "leaving";
287   event->ignore();
288 }
289
290 void ChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
291   //qDebug() << (void*)this << event->pos();
292   event->ignore();
293 }
294
295
296 /*************************************************************************************************/
297
298 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
299   wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
300   wordidx = 0;
301   layout = 0;
302   lastwrapcol = 0;
303   lastwrappos = 0;
304   w = 0;
305 }
306
307 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
308   delete layout;
309 }
310
311 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
312   while(wordidx < wrapList.count()) {
313     w += wrapList.at(wordidx).width;
314     if(w >= item->width()) {
315       if(lastwrapcol >= wrapList.at(wordidx).start) {
316         // first word, and it doesn't fit
317         if(!line.isValid()) {
318           layout = item->createLayout(QTextOption::NoWrap);
319           layout->beginLayout();
320           line = layout->createLine();
321           line.setLineWidth(item->width());
322           layout->endLayout();
323         }
324         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
325         qreal x = line.cursorToX(idx, QTextLine::Trailing);
326         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
327         lastwrappos = x;
328         lastwrapcol = idx;
329         return idx;
330       }
331       // not the first word, so just wrap before this
332       lastwrapcol = wrapList.at(wordidx).start;
333       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
334       w = 0;
335       return lastwrapcol;
336     }
337     w += wrapList.at(wordidx).trailing;
338     wordidx++;
339   }
340   return -1;
341 }