Wordwrap in ChatView almost working.
[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 <QFontMetrics>
22 #include <QGraphicsSceneMouseEvent>
23 #include <QPainter>
24 #include <QTextLayout>
25
26 #include "chatitem.h"
27 #include "chatlinemodel.h"
28 #include "qtui.h"
29
30 ChatItem::ChatItem(const QPersistentModelIndex &index_, QGraphicsItem *parent) : QGraphicsItem(parent), _index(index_) {
31   _fontMetrics = QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
32   _layout = 0;
33   _lines = 0;
34 }
35
36 ChatItem::~ChatItem() {
37
38 }
39
40 QVariant ChatItem::data(int role) const {
41   if(!_index.isValid()) {
42     qWarning() << "ChatItem::data(): Model index is invalid!" << _index;
43     return QVariant();
44   }
45   return _index.data(role);
46 }
47
48 int ChatItem::setWidth(int w) {
49   w -= 10;
50   if(w == _boundingRect.width()) return _boundingRect.height();
51   int h = heightForWidth(w);
52   _boundingRect.setWidth(w);
53   _boundingRect.setHeight(h);
54   if(haveLayout()) updateLayout();
55   return h;
56 }
57
58 int ChatItem::heightForWidth(int width) {
59   if(data(ChatLineModel::ColumnTypeRole).toUInt() != ChatLineModel::ContentsColumn)
60     return fontMetrics()->lineSpacing(); // only contents can be multi-line
61
62   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
63   _lines = 1;
64   qreal w = 0;
65   for(int i = 0; i < wrapList.count(); i++) {
66     w += wrapList.at(i).width;
67     if(w <= width) {
68       w += wrapList.at(i).trailing;
69       continue;
70     }
71     _lines++;
72     w = wrapList.at(i).width;
73     while(w >= width) {  // handle words longer than a line
74       _lines++;
75       // We do not want to compute an exact split position (that would require us to calculate glyph widths
76       // and also apply formats in this step...)
77       // Just using width should be a good estimate, but since a character can't be split in the middle, we
78       // subtract averageCharWidth as well... sometimes this won't be enough, but meh.
79       w -= width - 4*fontMetrics()->averageCharWidth();
80     }
81   }
82   return _lines * fontMetrics()->lineSpacing();
83 }
84
85 void ChatItem::layout() {
86   if(haveLayout()) return;
87   _layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
88
89   QTextOption option;
90   option.setWrapMode(QTextOption::WrapAnywhere);
91   _layout->setTextOption(option);
92
93   // Convert format information into a FormatRange
94   QList<QTextLayout::FormatRange> formatRanges;
95   UiStyle::FormatList formatList = data(MessageModel::FormatRole).value<UiStyle::FormatList>();
96   QTextLayout::FormatRange range;
97   int i = 0;
98   for(i = 0; i < formatList.count(); i++) {
99     range.format = QtUi::style()->mergedFormat(formatList.at(i).second);
100     range.start = formatList.at(i).first;
101     if(i > 0) formatRanges.last().length = range.start - formatRanges.last().start;
102     formatRanges.append(range);
103   }
104   if(i > 0) formatRanges.last().length = _layout->text().length() - formatRanges.last().start;
105   _layout->setAdditionalFormats(formatRanges);
106   updateLayout();
107 }
108
109 void ChatItem::updateLayout() {
110   if(!haveLayout()) layout();
111
112   // Now layout
113   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
114   if(!wrapList.count()) return; // empty chatitem
115   int wordidx = 0;
116   ChatLineModel::Word word = wrapList.at(0);
117
118   qreal h = 0;
119   _layout->beginLayout();
120   forever {
121     QTextLine line = _layout->createLine();
122     if (!line.isValid())
123       break;
124
125     if(word.width >= width()) {
126       line.setLineWidth(width());
127       word.width -= line.naturalTextWidth();
128       word.start = line.textStart() + line.textLength();
129       //qDebug() << "setting width: " << width();
130     } else {
131       int w = 0;
132       while((w += word.width) <= width() && wordidx < wrapList.count()) {
133         w += word.trailing;
134         if(++wordidx < wrapList.count()) word = wrapList.at(wordidx);
135         else {
136           // last word (and it fits), but if we expected an extra line, wrap anyway here
137           // yeah, this is cheating, but much cheaper than computing widths ourself
138           if(_layout->lineCount() < _lines) {
139             wordidx--; qDebug() << "trigger!" << _lines << _layout->text();
140             break;
141           }
142         }
143       }
144       int lastcol = wordidx < wrapList.count() ? word.start : _layout->text().length();
145       line.setNumColumns(lastcol - line.textStart());// qDebug() << "setting cols:" << lastcol - line.textStart();
146     }
147
148     h += fontMetrics()->leading();
149     line.setPosition(QPointF(0, h));
150     h += line.height();
151   }
152   _layout->endLayout();
153 }
154
155 void ChatItem::clearLayout() {
156   delete _layout;
157   _layout = 0;
158 }
159
160 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
161   Q_UNUSED(option); Q_UNUSED(widget);
162   layout();
163   _layout->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>(), boundingRect());
164   painter->drawRect(boundingRect());
165   int width = 0;
166   QVariantList wrapList = data(ChatLineModel::WrapListRole).toList();
167   for(int i = 2; i < wrapList.count(); i+=2) {
168     QRect r(wrapList[i-1].toUInt(), 0, wrapList[i+1].toUInt() - wrapList[i-1].toUInt(), fontMetrics()->lineSpacing());
169     painter->drawRect(r);
170   }
171 }
172
173 /*
174 void ChatItem::layout() {
175   if(!_layout.additionalFormats().count()) return; // no text set
176   if(_width <= 0) return;
177   prepareGeometryChange();
178   QFontMetrics metrics(_layout.additionalFormats()[0].format.font());
179   int leading = metrics.leading();
180   int height = 0;
181   _layout.setTextOption(textOption());
182   _layout.beginLayout();
183   while(1) {
184     QTextLine line = _layout.createLine();
185     if(!line.isValid()) break;
186     line.setLineWidth(_width);
187     if(textOption().wrapMode() != QTextOption::NoWrap && line.naturalTextWidth() > _width) {
188       // word did not fit, we need to wrap it in the middle
189       // this is a workaround for Qt failing to handle WrapAtWordBoundaryOrAnywhere correctly
190       QTextOption::WrapMode mode = textOption().wrapMode();
191       textOption().setWrapMode(QTextOption::WrapAnywhere);
192       _layout.setTextOption(textOption());
193       line.setLineWidth(_width);
194       textOption().setWrapMode(mode);
195       _layout.setTextOption(textOption());
196     }
197     height += leading;
198     line.setPosition(QPoint(0, height));
199     height += line.height();
200   }
201   _layout.endLayout();
202   update();
203 }    QDateTime _timestamp;
204     MsgId _msgId;
205
206
207 QRectF ChatItem::boundingRect() const {
208   return _layout.boundingRect();
209 }
210
211 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
212   Q_UNUSED(option); Q_UNUSED(widget);
213   _layout.draw(painter, QPointF(0, 0));
214
215 }
216 */
217
218 /*
219 void ChatItem::mouseMoveEvent ( QGraphicsSceneMouseEvent * event ) {
220   qDebug() << (void*)this << "moving" << event->pos();
221   if(event->pos().y() < 0) {
222     QTextCursor cursor(document());
223     //cursor.insertText("foo");
224     //cursor.select(QTextCursor::Document);
225     event->ignore();
226   } else QGraphicsTextItem::mouseMoveEvent(event);
227 }
228 */