10a523918b5138ccecd41cf1620102e49b3c6af0
[quassel.git] / src / qtgui / 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
23 //!\brief Construct a ChatLine object from a message.
24 /**
25  * \param m   The message to be layouted and rendered
26  * \param net The network name
27  * \param buf The buffer name
28  */
29 ChatLine::ChatLine(Message m) {
30   hght = 0;
31   //networkName = m.buffer.network();
32   //bufferName = m.buffer.buffer();
33   msg = m;
34   selectionMode = None;
35   formatMsg(msg);
36 }
37
38 ChatLine::~ChatLine() {
39
40 }
41
42 void ChatLine::formatMsg(Message msg) {
43   QString user = userFromMask(msg.sender());
44   QString host = hostFromMask(msg.sender());
45   QString nick = nickFromMask(msg.sender());
46   QString text = Style::mircToInternal(msg.text());
47   QString networkName = msg.buffer().network();
48   QString bufferName = msg.buffer().buffer();
49
50   QString c = tr("%DT[%1]").arg(msg.timeStamp().toLocalTime().toString("hh:mm:ss"));
51   QString s, t;
52   switch(msg.type()) {
53     case Message::Plain:
54       s = tr("%DS<%1>").arg(nick); t = tr("%D0%1").arg(text); break;
55     case Message::Server:
56       s = tr("%Ds*"); t = tr("%Ds%1").arg(text); break;
57     case Message::Error:
58       s = tr("%De*"); t = tr("%De%1").arg(text); break;
59     case Message::Join:
60       s = tr("%Dj-->"); t = tr("%Dj%DN%DU%1%DU%DN %DH(%2@%3)%DH has joined %DC%DU%4%DU%DC").arg(nick, user, host, bufferName); break;
61     case Message::Part:
62       s = tr("%Dp<--"); t = tr("%Dp%DN%DU%1%DU%DN %DH(%2@%3)%DH has left %DC%DU%4%DU%DC").arg(nick, user, host, bufferName);
63       if(!text.isEmpty()) t = QString("%1 (%2)").arg(t).arg(text);
64       break;
65     case Message::Quit:
66       s = tr("%Dq<--"); t = tr("%Dq%DN%DU%1%DU%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
67       if(!text.isEmpty()) t = QString("%1 (%2)").arg(t).arg(text);
68       break;
69     case Message::Kick:
70     { s = tr("%Dk<-*");
71     QString victim = text.section(" ", 0, 0);
72         //if(victim == ui.ownNick->currentText()) victim = tr("you");
73     QString kickmsg = text.section(" ", 1);
74     t = tr("%Dk%DN%DU%1%DU%DN has kicked %DN%DU%2%DU%DN from %DC%DU%3%DU%DC").arg(nick).arg(victim).arg(bufferName);
75     if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
76     }
77     break;
78     case Message::Nick:
79       s = tr("%Dr<->");
80       if(nick == msg.text()) t = tr("%DrYou are now known as %DN%1%DN").arg(msg.text());
81       else t = tr("%Dr%DN%1%DN is now known as %DN%DU%2%DU%DN").arg(nick, msg.text());
82       break;
83     case Message::Mode:
84       s = tr("%Dm***");
85       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(msg.text());
86       else t = tr("%DmMode %DM%1%DM by %DN%DU%2%DU%DN").arg(msg.text(), nick);
87       break;
88     case Message::Action:
89       s = tr("%Da-*-");
90       t = tr("%Da%DN%DU%1%DU%DN %2").arg(nick).arg(msg.text());
91       break;
92     default:
93       s = tr("%De%1").arg(msg.sender());
94       t = tr("%De[%1]").arg(msg.text());
95   }
96   QTextOption tsOption, senderOption, textOption;
97   tsFormatted = Style::internalToFormatted(c);
98   senderFormatted = Style::internalToFormatted(s);
99   textFormatted = Style::internalToFormatted(t);
100   precomputeLine();
101 }
102
103 QList<ChatLine::FormatRange> ChatLine::calcFormatRanges(const Style::FormattedString &fs, QTextLayout::FormatRange additional) {
104   QList<FormatRange> ranges;
105   QList<QTextLayout::FormatRange> formats = fs.formats;
106   formats.append(additional);
107   int cur = -1;
108   FormatRange range, lastrange;
109   for(int i = 0; i < fs.text.length(); i++) {
110     QTextCharFormat format;
111     foreach(QTextLayout::FormatRange f, formats) {
112       if(i >= f.start && i < f.start + f.length) format.merge(f.format);
113     }
114     if(cur < 0) {
115       range.start = 0; range.length = 1; range.format= format;
116       cur = 0;
117     } else {
118       if(format == range.format) range.length++;
119       else {
120         QFontMetrics metrics(range.format.font());
121         range.height = metrics.lineSpacing();
122         ranges.append(range);
123         range.start = i; range.length = 1; range.format = format;
124         cur++;
125       }
126     }
127   }
128   if(cur >= 0) {
129     QFontMetrics metrics(range.format.font());
130     range.height = metrics.lineSpacing();
131     ranges.append(range);
132   }
133   return ranges;
134 }
135
136 void ChatLine::setSelection(SelectionMode mode, int start, int end) {
137   selectionMode = mode;
138   //tsFormat.clear(); senderFormat.clear(); textFormat.clear();
139   QPalette pal = QApplication::palette();
140   QTextLayout::FormatRange tsSel, senderSel, textSel;
141   switch (mode) {
142     case None:
143       tsFormat = calcFormatRanges(tsFormatted);
144       senderFormat = calcFormatRanges(senderFormatted);
145       textFormat = calcFormatRanges(textFormatted);
146       break;
147     case Partial:
148       selectionStart = qMin(start, end); selectionEnd = qMax(start, end);
149       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
150       textSel.format.setBackground(pal.brush(QPalette::Highlight));
151       textSel.start = selectionStart;
152       textSel.length = selectionEnd - selectionStart;
153       //textFormat.append(textSel);
154       textFormat = calcFormatRanges(textFormatted, textSel);
155       foreach(FormatRange fr, textFormat);
156       break;
157     case Full:
158       tsSel.format.setForeground(pal.brush(QPalette::HighlightedText));
159       tsSel.format.setBackground(pal.brush(QPalette::Highlight));
160       tsSel.start = 0; tsSel.length = tsFormatted.text.length();
161       tsFormat = calcFormatRanges(tsFormatted, tsSel);
162       senderSel.format.setForeground(pal.brush(QPalette::HighlightedText));
163       senderSel.format.setBackground(pal.brush(QPalette::Highlight));
164       senderSel.start = 0; senderSel.length = senderFormatted.text.length();
165       senderFormat = calcFormatRanges(senderFormatted, senderSel);
166       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
167       textSel.format.setBackground(pal.brush(QPalette::Highlight));
168       textSel.start = 0; textSel.length = textFormatted.text.length();
169       textFormat = calcFormatRanges(textFormatted, textSel);
170       break;
171   }
172 }
173
174 uint ChatLine::msgId() const {
175   return msg.buffer().uid();
176 }
177
178 BufferId ChatLine::bufferId() const {
179   return msg.buffer();
180 }
181
182 QDateTime ChatLine::timeStamp() const {
183   return msg.timeStamp();
184 }
185
186 QString ChatLine::sender() const {
187   return senderFormatted.text;
188 }
189
190 QString ChatLine::text() const {
191   return textFormatted.text;
192 }
193
194 bool ChatLine::isUrl(int c) const {
195   if(c < 0 || c >= charUrlIdx.count()) return false;;
196   return charUrlIdx[c] >= 0;
197 }
198
199 QUrl ChatLine::getUrl(int c) const {
200   if(c < 0 || c >= charUrlIdx.count()) return QUrl();
201   int i = charUrlIdx[c];
202   if(i >= 0) return textFormatted.urls[i].url;
203   else return QUrl();
204 }
205
206 //!\brief Return the cursor position for the given coordinate pos.
207 /**
208  * \param pos The position relative to the ChatLine
209  * \return The cursor position, [or -3 for invalid,] or -2 for timestamp, or -1 for sender
210  */
211 int ChatLine::posToCursor(QPointF pos) {
212   if(pos.x() < tsWidth + (int)Style::sepTsSender()/2) return -2;
213   qreal textStart = tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText();
214   if(pos.x() < textStart) return -1;
215   int x = (int)(pos.x() - textStart);
216   for(int l = lineLayouts.count() - 1; l >=0; l--) {
217     LineLayout line = lineLayouts[l];
218     if(pos.y() >= line.y) {
219       int offset = charPos[line.start]; x += offset;
220       for(int i = line.start + line.length - 1; i >= line.start; i--) {
221         if((charPos[i] + charPos[i+1])/2 <= x) return i+1; // FIXME: Optimize this!
222       }
223       return line.start;
224     }
225   }
226   return 0;
227 }
228
229 void ChatLine::precomputeLine() {
230   tsFormat = calcFormatRanges(tsFormatted);
231   senderFormat = calcFormatRanges(senderFormatted);
232   textFormat = calcFormatRanges(textFormatted);
233
234   minHeight = 0;
235   foreach(FormatRange fr, tsFormat) minHeight = qMax(minHeight, fr.height);
236   foreach(FormatRange fr, senderFormat) minHeight = qMax(minHeight, fr.height);
237
238   words.clear();
239   charPos.resize(textFormatted.text.length() + 1);
240   charHeights.resize(textFormatted.text.length());
241   charUrlIdx.fill(-1, textFormatted.text.length());
242   for(int i = 0; i < textFormatted.urls.count(); i++) {
243     Style::UrlInfo url = textFormatted.urls[i];
244     for(int j = url.start; j < url.end; j++) charUrlIdx[j] = i;
245   }
246   if(!textFormat.count()) return;
247   int idx = 0; int cnt = 0; int w = 0;
248   QFontMetrics metrics(textFormat[0].format.font());
249   Word wr;
250   wr.start = -1; wr.trailing = -1;
251   for(int i = 0; i < textFormatted.text.length(); ) {
252     charPos[i] = w; charHeights[i] = textFormat[idx].height;
253     w += metrics.charWidth(textFormatted.text, i);
254     if(!textFormatted.text[i].isSpace()) {
255       if(wr.trailing >= 0) {
256         // new word after space
257         words.append(wr);
258         wr.start = -1;
259       }
260       if(wr.start < 0) {
261         wr.start = i; wr.length = 1; wr.trailing = -1; wr.height = textFormat[idx].height;
262       } else {
263         wr.length++; wr.height = qMax(wr.height, textFormat[idx].height);
264       }
265     } else {
266       if(wr.start < 0) {
267         wr.start = i; wr.length = 0; wr.trailing = 1; wr.height = 0;
268       } else {
269         wr.trailing++;
270       }
271     }
272     if(++i < textFormatted.text.length() && ++cnt >= textFormat[idx].length) {
273       cnt = 0; idx++;
274       Q_ASSERT(idx < textFormat.count());
275       metrics = QFontMetrics(textFormat[idx].format.font());
276     }
277   }
278   charPos[textFormatted.text.length()] = w;
279   if(wr.start >= 0) words.append(wr);
280 }
281
282 qreal ChatLine::layout(qreal tsw, qreal senderw, qreal textw) {
283   tsWidth = tsw; senderWidth = senderw; textWidth = textw;
284   if(textw <= 0) return minHeight;
285   lineLayouts.clear(); LineLayout line;
286   int h = 0;
287   int offset = 0; int numWords = 0;
288   line.y = 0;
289   line.start = 0;
290   line.height = minHeight;  // first line needs room for ts and sender
291   for(int i = 0; i < words.count(); i++) {
292     int lastpos = charPos[words[i].start + words[i].length]; // We use charPos[lastchar + 1], 'coz last char needs to fit
293     if(lastpos - offset <= textw) {
294       line.height = qMax(line.height, words[i].height);
295       line.length = words[i].start + words[i].length - line.start;
296       numWords++;
297     } else {
298       // we need to wrap!
299       if(numWords > 0) {
300         // ok, we had some words before, so store the layout and start a new line
301         h += line.height;
302         line.length = words[i-1].start + words[i-1].length - line.start;
303         lineLayouts.append(line);
304         line.y += line.height;
305         line.start = words[i].start;
306         line.height = words[i].height;
307         offset = charPos[words[i].start];
308       }
309       numWords = 1;
310       // check if the word fits into the current line
311       if(lastpos - offset <= textw) {
312         line.length = words[i].length;
313       } else {
314         // we need to break a word in the middle
315         int border = (int)textw + offset; // save some additions
316         line.start = words[i].start;
317         line.length = 1;
318         line.height = charHeights[line.start];
319         int j = line.start + 1;
320         for(int l = 1; l < words[i].length; j++, l++) {
321           if(charPos[j+1] < border) {
322             line.length++;
323             line.height = qMax(line.height, charHeights[j]);
324             continue;
325           } else {
326             h += line.height;
327             lineLayouts.append(line);
328             line.y += line.height;
329             line.start = j;
330             line.height = charHeights[j];
331             line.length = 1;
332             offset = charPos[j];
333             border = (int)textw + offset;
334           }
335         }
336       }
337     }
338   }
339   h += line.height;
340   if(numWords > 0) {
341     lineLayouts.append(line);
342   }
343   hght = h;
344   return hght;
345 }
346
347 //!\brief Draw ChatLine on the given QPainter at the given position.
348 void ChatLine::draw(QPainter *p, const QPointF &pos) {
349   QPalette pal = QApplication::palette();
350
351   if(selectionMode == Full) {
352     p->setPen(Qt::NoPen);
353     p->setBrush(pal.brush(QPalette::Highlight));
354     p->drawRect(QRectF(pos, QSizeF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText() + textWidth, height())));
355   } else if(selectionMode == Partial) {
356
357   } /*
358   p->setClipRect(QRectF(pos, QSizeF(tsWidth, height())));
359   tsLayout.draw(p, pos, tsFormat);
360   p->setClipRect(QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, height())));
361   senderLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender(), 0), senderFormat);
362   p->setClipping(false);
363   textLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0), textFormat);
364     */
365   //p->setClipRect(QRectF(pos, QSizeF(tsWidth, 15)));
366   //p->drawRect(QRectF(pos, QSizeF(tsWidth, minHeight)));
367   p->setBackgroundMode(Qt::OpaqueMode);
368   QPointF tp = pos;
369   QRectF rect(pos, QSizeF(tsWidth, minHeight));
370   QRectF brect;
371   foreach(FormatRange fr, tsFormat) {
372     p->setFont(fr.format.font());
373     p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
374     p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, tsFormatted.text.mid(fr.start, fr.length), &brect);
375     rect.setLeft(brect.right());
376   }
377   rect = QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, minHeight));
378   for(int i = senderFormat.count() - 1; i >= 0; i--) {
379     FormatRange fr = senderFormat[i];
380     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
381     p->drawText(rect, Qt::AlignRight|Qt::TextSingleLine, senderFormatted.text.mid(fr.start, fr.length), &brect);
382     rect.setRight(brect.left());
383   }
384   QPointF tpos = pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0);
385   qreal h = 0; int l = 0;
386   rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
387   int offset = 0;
388   foreach(FormatRange fr, textFormat) {
389     if(l >= lineLayouts.count()) break;
390     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
391     int start, end, frend, llend;
392     do {
393       frend = fr.start + fr.length;
394       if(frend <= lineLayouts[l].start) break;
395       llend = lineLayouts[l].start + lineLayouts[l].length;
396       start = qMax(fr.start, lineLayouts[l].start); end = qMin(frend, llend);
397       rect.setLeft(tpos.x() + charPos[start] - offset);
398       p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, textFormatted.text.mid(start, end - start), &brect);
399       if(llend <= end) {
400         h += lineLayouts[l].height;
401         l++;
402         if(l < lineLayouts.count()) {
403           rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
404           offset = charPos[lineLayouts[l].start];
405         }
406       }
407     } while(end < frend && l < lineLayouts.count());
408   }
409 }