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