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