Refactor and simplify ChatItem, implement full selection, use qreal where appropriate
[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 }
40
41 ChatItem::~ChatItem() {
42   delete _layout;
43 }
44
45 QVariant ChatItem::data(int role) const {
46   if(!_index.isValid()) {
47     qWarning() << "ChatItem::data(): Model index is invalid!" << _index;
48     return QVariant();
49   }
50   return _index.data(role);
51 }
52
53 qreal ChatItem::setWidth(qreal w) {
54   if(w == _boundingRect.width()) return _boundingRect.height();
55   prepareGeometryChange();
56   _boundingRect.setWidth(w);
57   qreal h = computeHeight();
58   _boundingRect.setHeight(h);
59   if(haveLayout()) updateLayout();
60   return h;
61 }
62
63 qreal ChatItem::computeHeight() {
64   if(data(ChatLineModel::ColumnTypeRole).toUInt() != ChatLineModel::ContentsColumn)
65     return fontMetrics()->lineSpacing(); // only contents can be multi-line
66
67   _lines = 1;
68   WrapColumnFinder finder(this);
69   while(finder.nextWrapColumn() > 0) _lines++;
70   return _lines * fontMetrics()->lineSpacing();
71 }
72
73 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
74   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
75
76   QTextOption option;
77   option.setWrapMode(wrapMode);
78   option.setAlignment(alignment);
79   layout->setTextOption(option);
80
81   QList<QTextLayout::FormatRange> formatRanges
82          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
83   layout->setAdditionalFormats(formatRanges);
84   return layout;
85 }
86
87 void ChatItem::updateLayout() {
88   switch(data(ChatLineModel::ColumnTypeRole).toUInt()) {
89     case ChatLineModel::TimestampColumn:
90       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft);
91       // fallthrough
92     case ChatLineModel::SenderColumn:
93       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere, Qt::AlignRight);
94       _layout->beginLayout();
95       {
96         QTextLine line = _layout->createLine();
97         if(line.isValid()) {
98           line.setLineWidth(width());
99           line.setPosition(QPointF(0,0));
100         }
101         _layout->endLayout();
102       }
103       break;
104     case ChatLineModel::ContentsColumn: {
105       if(!haveLayout()) _layout = createLayout(QTextOption::WrapAnywhere);
106
107       // Now layout
108       ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
109       if(!wrapList.count()) return; // empty chatitem
110
111       qreal h = 0;
112       WrapColumnFinder finder(this);
113       _layout->beginLayout();
114       forever {
115         QTextLine line = _layout->createLine();
116         if(!line.isValid())
117           break;
118
119         int col = finder.nextWrapColumn();
120         line.setNumColumns(col >= 0 ? col - line.textStart() : _layout->text().length());
121         line.setPosition(QPointF(0, h));
122         h += line.height() + fontMetrics()->leading();
123       }
124       _layout->endLayout();
125     }
126     break;
127   }
128 }
129
130 void ChatItem::clearLayout() {
131   delete _layout;
132   _layout = 0;
133 }
134
135 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
136 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
137 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
138   Q_UNUSED(option); Q_UNUSED(widget);
139   if(!haveLayout()) updateLayout();
140   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
141   if(_selectionMode == FullSelection) {
142     painter->save();
143    painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
144     painter->restore();
145   } // TODO: add selection format here
146   QVector<QTextLayout::FormatRange> formats;
147   if(_selectionMode != NoSelection) {
148     QTextLayout::FormatRange selectFmt;
149     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
150     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
151     if(_selectionMode == PartialSelection) {
152       selectFmt.start = qMin(_selectionStart, _selectionEnd);
153       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
154     } else { // FullSelection
155       selectFmt.start = 0;
156       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
157     }
158     formats.append(selectFmt);
159   }
160   _layout->draw(painter, QPointF(0,0), formats, boundingRect());
161 }
162
163 qint16 ChatItem::posToCursor(const QPointF &pos) {
164   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
165   if(pos.y() < 0) return 0;
166   if(!haveLayout()) updateLayout();
167   for(int l = _layout->lineCount() - 1; l >= 0; l--) {
168     QTextLine line = _layout->lineAt(l);
169     if(pos.y() >= line.y()) {
170       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
171     }
172   }
173   return 0;
174 }
175
176 void ChatItem::setFullSelection() {
177   _selectionMode = FullSelection;
178   update();
179 }
180
181 void ChatItem::clearSelection() {
182   _selectionMode = NoSelection;
183   update();
184 }
185
186 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
187   if(event->buttons() & Qt::LeftButton) {
188     chatScene()->setSelectingItem(this);  // removes earlier selection if exists
189     _selectionStart = _selectionEnd = posToCursor(event->pos());
190     _selectionMode = PartialSelection;
191     event->accept();
192   } else {
193     event->ignore();
194   }
195 }
196
197 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
198   if(contains(event->pos())) {
199     _selectionEnd = posToCursor(event->pos());
200     update();
201   } else {
202     setFullSelection();
203     ungrabMouse();
204     chatScene()->startGlobalSelection(this);
205   }
206 }
207
208 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
209   if(_selectionMode != NoSelection) {
210     _selectionEnd = posToCursor(event->pos());
211     QString selection
212         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
213     QApplication::clipboard()->setText(selection, QClipboard::Clipboard);  // TODO configure where selections should go
214     event->accept();
215   } else {
216     event->ignore();
217   }
218 }
219
220 /*************************************************************************************************/
221
222 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
223   wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
224   wordidx = 0;
225   layout = 0;
226   lastwrapcol = 0;
227   lastwrappos = 0;
228   w = 0;
229 }
230
231 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
232   delete layout;
233 }
234
235 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
236   while(wordidx < wrapList.count()) {
237     w += wrapList.at(wordidx).width;
238     if(w >= item->width()) {
239       if(lastwrapcol >= wrapList.at(wordidx).start) {
240         // first word, and it doesn't fit
241         if(!line.isValid()) {
242           layout = item->createLayout(QTextOption::NoWrap);
243           layout->beginLayout();
244           line = layout->createLine();
245           line.setLineWidth(item->width());
246           layout->endLayout();
247         }
248         int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
249         qreal x = line.cursorToX(idx, QTextLine::Trailing);
250         w = w - wrapList.at(wordidx).width - (x - lastwrappos);
251         lastwrappos = x;
252         lastwrapcol = idx;
253         return idx;
254       }
255       // not the first word, so just wrap before this
256       lastwrapcol = wrapList.at(wordidx).start;
257       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
258       w = 0;
259       return lastwrapcol;
260     }
261     w += wrapList.at(wordidx).trailing;
262     wordidx++;
263   }
264   return -1;
265 }