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