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