Introduce WrapColumnFinder.
[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   _boundingRect.setWidth(w);
52   int h = heightForWidth(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   _lines = 1;
63   QTextLine line;
64   WrapColumnFinder finder(this);
65   while(finder.nextWrapColumn(line) > 0) _lines++;
66   return _lines * fontMetrics()->lineSpacing();
67 }
68
69 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
70   wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
71   wordidx = 0;
72   layout = 0;
73   lastwrapcol = 0;
74   lastwrappos = 0;
75   w = 0;
76 }
77
78 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
79   delete layout;
80 }
81
82 int ChatItem::WrapColumnFinder::nextWrapColumn(QTextLine &line) {
83   while(wordidx < wrapList.count()) {
84     w += wrapList.at(wordidx).width;
85     if(w >= item->width()) {
86       if(lastwrapcol == wrapList.at(wordidx).start) {
87         // first word, and it doesn't fit
88         if(!line.isValid()) {
89           layout = item->createLayout();
90           layout->beginLayout();
91           line = layout->createLine();
92           line.setLineWidth(item->width());
93           layout->endLayout();
94         }
95         int idx = line.xToCursor((line.textStart() ? 0 : lastwrappos) + item->width());
96         qreal x = line.cursorToX(idx);
97         idx += line.textStart();
98         w = w - x - wrapList.at(wordidx).width;
99         if(line.textStart()) lastwrappos += x;
100         else lastwrappos = x;
101         lastwrapcol = idx;
102         return idx;
103       }
104       // not the first word, so just wrap before this
105       lastwrapcol = wrapList.at(wordidx).start;
106       lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
107       w = 0;
108       return lastwrapcol;
109     }
110     w += wrapList.at(wordidx).trailing;
111     wordidx++;
112   }
113   return -1;
114 }
115
116 QTextLayout *ChatItem::createLayout() {
117   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
118
119   QTextOption option;
120   option.setWrapMode(QTextOption::WrapAnywhere);
121   layout->setTextOption(option);
122
123   QList<QTextLayout::FormatRange> formatRanges
124          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
125   layout->setAdditionalFormats(formatRanges);
126   return layout;
127 }
128
129 void ChatItem::updateLayout() {
130   if(!haveLayout()) _layout = createLayout();
131
132   // Now layout
133   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
134   if(!wrapList.count()) return; // empty chatitem
135   int wordidx = 0;
136   ChatLineModel::Word word = wrapList.at(0);
137
138   qreal h = 0;
139   WrapColumnFinder finder(this);
140   _layout->beginLayout();
141   forever {
142     QTextLine line = _layout->createLine();
143     if (!line.isValid())
144       break;
145
146     int col = finder.nextWrapColumn(line);
147     line.setNumColumns(col >= 0 ? col - line.textStart() : _layout->text().length());
148
149     h += fontMetrics()->leading();
150     line.setPosition(QPointF(0, h));
151     h += line.height();
152   }
153   _layout->endLayout();
154 }
155
156 void ChatItem::clearLayout() {
157   delete _layout;
158   _layout = 0;
159 }
160
161 //int ChatItem::findNextWrapColumn(
162
163 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
164   Q_UNUSED(option); Q_UNUSED(widget);
165   if(!haveLayout()) updateLayout();
166   _layout->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>(), boundingRect());
167   painter->drawRect(boundingRect());
168   int width = 0;
169   QVariantList wrapList = data(ChatLineModel::WrapListRole).toList();
170   for(int i = 2; i < wrapList.count(); i+=2) {
171     QRect r(wrapList[i-1].toUInt(), 0, wrapList[i+1].toUInt() - wrapList[i-1].toUInt(), fontMetrics()->lineSpacing());
172     painter->drawRect(r);
173   }
174 }
175
176
177 /*
178 void ChatItem::layout() {
179   if(!_layout.additionalFormats().count()) return; // no text set
180   if(_width <= 0) return;
181   prepareGeometryChange();
182   QFontMetrics metrics(_layout.additionalFormats()[0].format.font());
183   int leading = metrics.leading();
184   int height = 0;
185   _layout.setTextOption(textOption());
186   _layout.beginLayout();
187   while(1) {
188     QTextLine line = _layout.createLine();
189     if(!line.isValid()) break;
190     line.setLineWidth(_width);
191     if(textOption().wrapMode() != QTextOption::NoWrap && line.naturalTextWidth() > _width) {
192       // word did not fit, we need to wrap it in the middle
193       // this is a workaround for Qt failing to handle WrapAtWordBoundaryOrAnywhere correctly
194       QTextOption::WrapMode mode = textOption().wrapMode();
195       textOption().setWrapMode(QTextOption::WrapAnywhere);
196       _layout.setTextOption(textOption());
197       line.setLineWidth(_width);
198       textOption().setWrapMode(mode);
199       _layout.setTextOption(textOption());
200     }
201     height += leading;
202     line.setPosition(QPoint(0, height));
203     height += line.height();
204   }
205   _layout.endLayout();
206   update();
207 }    QDateTime _timestamp;
208     MsgId _msgId;
209
210
211 QRectF ChatItem::boundingRect() const {
212   return _layout.boundingRect();
213 }
214
215 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
216   Q_UNUSED(option); Q_UNUSED(widget);
217   _layout.draw(painter, QPointF(0, 0));
218
219 }
220 */
221
222 /*
223 void ChatItem::mouseMoveEvent ( QGraphicsSceneMouseEvent * event ) {
224   qDebug() << (void*)this << "moving" << event->pos();
225   if(event->pos().y() < 0) {
226     QTextCursor cursor(document());
227     //cursor.insertText("foo");
228     //cursor.select(QTextCursor::Document);
229     event->ignore();
230   } else QGraphicsTextItem::mouseMoveEvent(event);
231 }
232 */