f3b4a3574fc151137e3417a0164bd598aff664e0
[quassel.git] / src / qtui / chatline.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel IRC Development Team             *
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) any later version.                                   *
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 "chatline.h"
22 #include "qtui.h"
23
24 //!\brief Construct a ChatLine object from a message.
25 /**
26  * \param m   The message to be layouted and rendered
27  * \param net The network name
28  * \param buf The buffer name
29  */
30 ChatLine::ChatLine(Message m) {
31   hght = 0;
32   //networkName = m.buffer.network();
33   //bufferName = m.buffer.buffer();
34   msg = m;
35   selectionMode = None;
36   formatMsg(msg);
37 }
38
39 ChatLine::~ChatLine() {
40
41 }
42
43 void ChatLine::formatMsg(Message msg) {
44   QTextOption tsOption, senderOption, textOption;
45   styledTimeStamp = QtUi::style()->styleString(msg.formattedTimeStamp());
46   styledSender = QtUi::style()->styleString(msg.formattedSender());
47   styledText = QtUi::style()->styleString(msg.formattedText());
48   precomputeLine();
49 }
50
51 // This function is almost obsolete, since with the new style engine, we already get a list of formats...
52 // We don't know yet if we keep this implementation of ChatLine, so I won't bother making this actually nice.
53 // Also, the additional format is ignored for now, which means that you won't see a selection...
54 // FIXME TODO
55 QList<ChatLine::FormatRange> ChatLine::calcFormatRanges(const UiStyle::StyledString &fs, QTextLayout::FormatRange additional) {
56   QList<FormatRange> ranges;
57
58   foreach(QTextLayout::FormatRange f, fs.formats) {
59     FormatRange range;
60     range.start = f.start;
61     range.length = f.length;
62     range.format = f.format;
63     QFontMetrics metrics(range.format.font());
64     range.height = metrics.lineSpacing();
65     ranges.append(range);
66   }
67   /*
68   QList<QTextLayout::FormatRange> formats = fs.formats;
69   formats.append(additional);
70   int cur = -1;
71   FormatRange range, lastrange;
72   for(int i = 0; i < fs.text.length(); i++) {
73     QTextCharFormat format;
74     foreach(QTextLayout::FormatRange f, formats) {
75       if(i >= f.start && i < f.start + f.length) format.merge(f.format);
76     }
77     if(cur < 0) {
78       range.start = 0; range.length = 1; range.format= format;
79       cur = 0;
80     } else {
81       if(format == range.format) range.length++;
82       else {
83         QFontMetrics metrics(range.format.font());
84         range.height = metrics.lineSpacing();
85         ranges.append(range);
86         range.start = i; range.length = 1; range.format = format;
87         cur++;
88       }
89     }
90   }
91   if(cur >= 0) {
92     QFontMetrics metrics(range.format.font());
93     range.height = metrics.lineSpacing();
94     ranges.append(range);
95   }
96   */
97   return ranges;
98 }
99
100 void ChatLine::setSelection(SelectionMode mode, int start, int end) {
101   selectionMode = mode;
102   //tsFormat.clear(); senderFormat.clear(); textFormat.clear();
103   QPalette pal = QApplication::palette();
104   QTextLayout::FormatRange tsSel, senderSel, textSel;
105   switch (mode) {
106     case None:
107       tsFormat = calcFormatRanges(styledTimeStamp);
108       senderFormat = calcFormatRanges(styledSender);
109       textFormat = calcFormatRanges(styledText);
110       break;
111     case Partial:
112       selectionStart = qMin(start, end); selectionEnd = qMax(start, end);
113       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
114       textSel.format.setBackground(pal.brush(QPalette::Highlight));
115       textSel.start = selectionStart;
116       textSel.length = selectionEnd - selectionStart;
117       //textFormat.append(textSel);
118       textFormat = calcFormatRanges(styledText, textSel);
119       foreach(FormatRange fr, textFormat);
120       break;
121     case Full:
122       tsSel.format.setForeground(pal.brush(QPalette::HighlightedText));
123       tsSel.format.setBackground(pal.brush(QPalette::Highlight));
124       tsSel.start = 0; tsSel.length = styledTimeStamp.text.length();
125       tsFormat = calcFormatRanges(styledTimeStamp, tsSel);
126       senderSel.format.setForeground(pal.brush(QPalette::HighlightedText));
127       senderSel.format.setBackground(pal.brush(QPalette::Highlight));
128       senderSel.start = 0; senderSel.length = styledSender.text.length();
129       senderFormat = calcFormatRanges(styledSender, senderSel);
130       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
131       textSel.format.setBackground(pal.brush(QPalette::Highlight));
132       textSel.start = 0; textSel.length = styledText.text.length();
133       textFormat = calcFormatRanges(styledText, textSel);
134       break;
135   }
136 }
137
138 uint ChatLine::msgId() const {
139   return msg.buffer().uid();
140 }
141
142 BufferInfo ChatLine::bufferInfo() const {
143   return msg.buffer();
144 }
145
146 QDateTime ChatLine::timeStamp() const {
147   return msg.timeStamp();
148 }
149
150 QString ChatLine::sender() const {
151   return styledSender.text;
152 }
153
154 QString ChatLine::text() const {
155   return styledText.text;
156 }
157
158 bool ChatLine::isUrl(int c) const {
159   if(c < 0 || c >= charUrlIdx.count()) return false;;
160   return charUrlIdx[c] >= 0;
161 }
162
163 QUrl ChatLine::getUrl(int c) const {
164   if(c < 0 || c >= charUrlIdx.count()) return QUrl();
165   int i = charUrlIdx[c];
166   if(i >= 0) return styledText.urls[i].url;
167   else return QUrl();
168 }
169
170 //!\brief Return the cursor position for the given coordinate pos.
171 /**
172  * \param pos The position relative to the ChatLine
173  * \return The cursor position, [or -3 for invalid,] or -2 for timestamp, or -1 for sender
174  */
175 int ChatLine::posToCursor(QPointF pos) {
176   if(pos.x() < tsWidth + (int)QtUi::style()->sepTsSender()/2) return -2;
177   qreal textStart = tsWidth + QtUi::style()->sepTsSender() + senderWidth + QtUi::style()->sepSenderText();
178   if(pos.x() < textStart) return -1;
179   int x = (int)(pos.x() - textStart);
180   for(int l = lineLayouts.count() - 1; l >=0; l--) {
181     LineLayout line = lineLayouts[l];
182     if(pos.y() >= line.y) {
183       int offset = charPos[line.start]; x += offset;
184       for(int i = line.start + line.length - 1; i >= line.start; i--) {
185         if((charPos[i] + charPos[i+1])/2 <= x) return i+1; // FIXME: Optimize this!
186       }
187       return line.start;
188     }
189   }
190   return 0;
191 }
192
193 void ChatLine::precomputeLine() {
194   tsFormat = calcFormatRanges(styledTimeStamp);
195   senderFormat = calcFormatRanges(styledSender);
196   textFormat = calcFormatRanges(styledText);
197
198   minHeight = 0;
199   foreach(FormatRange fr, tsFormat) minHeight = qMax(minHeight, fr.height);
200   foreach(FormatRange fr, senderFormat) minHeight = qMax(minHeight, fr.height);
201
202   words.clear();
203   charPos.resize(styledText.text.length() + 1);
204   charHeights.resize(styledText.text.length());
205   charUrlIdx.fill(-1, styledText.text.length());
206   for(int i = 0; i < styledText.urls.count(); i++) {
207     QtUiStyle::UrlInfo url = styledText.urls[i];
208     for(int j = url.start; j < url.end; j++) charUrlIdx[j] = i;
209   }
210   if(!textFormat.count()) return;
211   int idx = 0; int cnt = 0; int w = 0;
212   QFontMetrics metrics(textFormat[0].format.font());
213   Word wr;
214   wr.start = -1; wr.trailing = -1;
215   for(int i = 0; i < styledText.text.length(); ) {
216     charPos[i] = w; charHeights[i] = textFormat[idx].height;
217     w += metrics.charWidth(styledText.text, i);
218     if(!styledText.text[i].isSpace()) {
219       if(wr.trailing >= 0) {
220         // new word after space
221         words.append(wr);
222         wr.start = -1;
223       }
224       if(wr.start < 0) {
225         wr.start = i; wr.length = 1; wr.trailing = -1; wr.height = textFormat[idx].height;
226       } else {
227         wr.length++; wr.height = qMax(wr.height, textFormat[idx].height);
228       }
229     } else {
230       if(wr.start < 0) {
231         wr.start = i; wr.length = 0; wr.trailing = 1; wr.height = 0;
232       } else {
233         wr.trailing++;
234       }
235     }
236     if(++i < styledText.text.length() && ++cnt >= textFormat[idx].length) {
237       cnt = 0; idx++;
238       Q_ASSERT(idx < textFormat.count());
239       metrics = QFontMetrics(textFormat[idx].format.font());
240     }
241   }
242   charPos[styledText.text.length()] = w;
243   if(wr.start >= 0) words.append(wr);
244 }
245
246 qreal ChatLine::layout(qreal tsw, qreal senderw, qreal textw) {
247   tsWidth = tsw; senderWidth = senderw; textWidth = textw;
248   if(textw <= 0) return minHeight;
249   lineLayouts.clear(); LineLayout line;
250   int h = 0;
251   int offset = 0; int numWords = 0;
252   line.y = 0;
253   line.start = 0;
254   line.height = minHeight;  // first line needs room for ts and sender
255   for(uint i = 0; i < (uint)words.count(); i++) {
256     int lastpos = charPos[words[i].start + words[i].length]; // We use charPos[lastchar + 1], 'coz last char needs to fit
257     if(lastpos - offset <= textw) {
258       line.height = qMax(line.height, words[i].height);
259       line.length = words[i].start + words[i].length - line.start;
260       numWords++;
261     } else {
262       // we need to wrap!
263       if(numWords > 0) {
264         // ok, we had some words before, so store the layout and start a new line
265         h += line.height;
266         line.length = words[i-1].start + words[i-1].length - line.start;
267         lineLayouts.append(line);
268         line.y += line.height;
269         line.start = words[i].start;
270         line.height = words[i].height;
271         offset = charPos[words[i].start];
272       }
273       numWords = 1;
274       // check if the word fits into the current line
275       if(lastpos - offset <= textw) {
276         line.length = words[i].length;
277       } else {
278         // we need to break a word in the middle
279         int border = (int)textw + offset; // save some additions
280         line.start = words[i].start;
281         line.length = 1;
282         line.height = charHeights[line.start];
283         int j = line.start + 1;
284         for(int l = 1; l < words[i].length; j++, l++) {
285           if(charPos[j+1] < border) {
286             line.length++;
287             line.height = qMax(line.height, charHeights[j]);
288             continue;
289           } else {
290             h += line.height;
291             lineLayouts.append(line);
292             line.y += line.height;
293             line.start = j;
294             line.height = charHeights[j];
295             line.length = 1;
296             offset = charPos[j];
297             border = (int)textw + offset;
298           }
299         }
300       }
301     }
302   }
303   h += line.height;
304   if(numWords > 0) {
305     lineLayouts.append(line);
306   }
307   hght = h;
308   return hght;
309 }
310
311 //!\brief Draw ChatLine on the given QPainter at the given position.
312 void ChatLine::draw(QPainter *p, const QPointF &pos) {
313   QPalette pal = QApplication::palette();
314
315   if(selectionMode == Full) {
316     p->setPen(Qt::NoPen);
317     p->setBrush(pal.brush(QPalette::Highlight));
318     p->drawRect(QRectF(pos, QSizeF(tsWidth + QtUi::style()->sepTsSender() + senderWidth + QtUi::style()->sepSenderText() + textWidth, height())));
319   } else if(selectionMode == Partial) {
320
321   } /*
322   p->setClipRect(QRectF(pos, QSizeF(tsWidth, height())));
323   tsLayout.draw(p, pos, tsFormat);
324   p->setClipRect(QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, height())));
325   senderLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender(), 0), senderFormat);
326   p->setClipping(false);
327   textLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0), textFormat);
328     */
329   //p->setClipRect(QRectF(pos, QSizeF(tsWidth, 15)));
330   //p->drawRect(QRectF(pos, QSizeF(tsWidth, minHeight)));
331   p->setBackgroundMode(Qt::OpaqueMode);
332   QPointF tp = pos;
333   QRectF rect(pos, QSizeF(tsWidth, minHeight));
334   QRectF brect;
335   foreach(FormatRange fr, tsFormat) {
336     p->setFont(fr.format.font());
337     p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
338     p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, styledTimeStamp.text.mid(fr.start, fr.length), &brect);
339     rect.setLeft(brect.right());
340   }
341   rect = QRectF(pos + QPointF(tsWidth + QtUi::style()->sepTsSender(), 0), QSizeF(senderWidth, minHeight));
342   for(int i = senderFormat.count() - 1; i >= 0; i--) {
343     FormatRange fr = senderFormat[i];
344     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
345     p->drawText(rect, Qt::AlignRight|Qt::TextSingleLine, styledSender.text.mid(fr.start, fr.length), &brect);
346     rect.setRight(brect.left());
347   }
348   QPointF tpos = pos + QPointF(tsWidth + QtUi::style()->sepTsSender() + senderWidth + QtUi::style()->sepSenderText(), 0);
349   qreal h = 0; int l = 0;
350   rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
351   int offset = 0;
352   foreach(FormatRange fr, textFormat) {
353     if(l >= lineLayouts.count()) break;
354     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
355     int start, end, frend, llend;
356     do {
357       frend = fr.start + fr.length;
358       if(frend <= lineLayouts[l].start) break;
359       llend = lineLayouts[l].start + lineLayouts[l].length;
360       start = qMax(fr.start, lineLayouts[l].start); end = qMin(frend, llend);
361       rect.setLeft(tpos.x() + charPos[start] - offset);
362       p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, styledText.text.mid(start, end - start), &brect);
363       if(llend <= end) {
364         h += lineLayouts[l].height;
365         l++;
366         if(l < lineLayouts.count()) {
367           rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
368           offset = charPos[lineLayouts[l].start];
369         }
370       }
371     } while(end < frend && l < lineLayouts.count());
372   }
373 }