some minor tweaks
[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 }
227
228 void ChatLine::precomputeLine() {
229   tsFormat = calcFormatRanges(tsFormatted);
230   senderFormat = calcFormatRanges(senderFormatted);
231   textFormat = calcFormatRanges(textFormatted);
232
233   minHeight = 0;
234   foreach(FormatRange fr, tsFormat) minHeight = qMax(minHeight, fr.height);
235   foreach(FormatRange fr, senderFormat) minHeight = qMax(minHeight, fr.height);
236
237   words.clear();
238   charPos.resize(textFormatted.text.length() + 1);
239   charHeights.resize(textFormatted.text.length());
240   charUrlIdx.fill(-1, textFormatted.text.length());
241   for(int i = 0; i < textFormatted.urls.count(); i++) {
242     Style::UrlInfo url = textFormatted.urls[i];
243     for(int j = url.start; j < url.end; j++) charUrlIdx[j] = i;
244   }
245   if(!textFormat.count()) return;
246   int idx = 0; int cnt = 0; int w = 0; int h = 0;
247   QFontMetrics metrics(textFormat[0].format.font());
248   Word wr;
249   wr.start = -1; wr.trailing = -1;
250   for(int i = 0; i < textFormatted.text.length(); ) {
251     charPos[i] = w; charHeights[i] = textFormat[idx].height;
252     w += metrics.charWidth(textFormatted.text, i);
253     if(!textFormatted.text[i].isSpace()) {
254       if(wr.trailing >= 0) {
255         // new word after space
256         words.append(wr);
257         wr.start = -1;
258       }
259       if(wr.start < 0) {
260         wr.start = i; wr.length = 1; wr.trailing = -1; wr.height = textFormat[idx].height;
261       } else {
262         wr.length++; wr.height = qMax(wr.height, textFormat[idx].height);
263       }
264     } else {
265       if(wr.start < 0) {
266         wr.start = i; wr.length = 0; wr.trailing = 1; wr.height = 0;
267       } else {
268         wr.trailing++;
269       }
270     }
271     if(++i < textFormatted.text.length() && ++cnt >= textFormat[idx].length) {
272       cnt = 0; idx++;
273       Q_ASSERT(idx < textFormat.count());
274       metrics = QFontMetrics(textFormat[idx].format.font());
275     }
276   }
277   charPos[textFormatted.text.length()] = w;
278   if(wr.start >= 0) words.append(wr);
279 }
280
281 qreal ChatLine::layout(qreal tsw, qreal senderw, qreal textw) {
282   tsWidth = tsw; senderWidth = senderw; textWidth = textw;
283   if(textw <= 0) return minHeight;
284   lineLayouts.clear(); LineLayout line;
285   int h = 0;
286   int offset = 0; int numWords = 0;
287   line.y = 0;
288   line.start = 0;
289   line.height = minHeight;  // first line needs room for ts and sender
290   for(int i = 0; i < words.count(); i++) {
291     int lastpos = charPos[words[i].start + words[i].length]; // We use charPos[lastchar + 1], 'coz last char needs to fit
292     if(lastpos - offset <= textw) {
293       line.height = qMax(line.height, words[i].height);
294       line.length = words[i].start + words[i].length - line.start;
295       numWords++;
296     } else {
297       // we need to wrap!
298       if(numWords > 0) {
299         // ok, we had some words before, so store the layout and start a new line
300         h += line.height;
301         line.length = words[i-1].start + words[i-1].length - line.start;
302         lineLayouts.append(line);
303         line.y += line.height;
304         line.start = words[i].start;
305         line.height = words[i].height;
306         offset = charPos[words[i].start];
307       }
308       numWords = 1;
309       // check if the word fits into the current line
310       if(lastpos - offset <= textw) {
311         line.length = words[i].length;
312       } else {
313         // we need to break a word in the middle
314         int border = (int)textw + offset; // save some additions
315         line.start = words[i].start;
316         line.length = 1;
317         line.height = charHeights[line.start];
318         int j = line.start + 1;
319         for(int l = 1; l < words[i].length; j++, l++) {
320           if(charPos[j+1] < border) {
321             line.length++;
322             line.height = qMax(line.height, charHeights[j]);
323             continue;
324           } else {
325             h += line.height;
326             lineLayouts.append(line);
327             line.y += line.height;
328             line.start = j;
329             line.height = charHeights[j];
330             line.length = 1;
331             offset = charPos[j];
332             border = (int)textw + offset;
333           }
334         }
335       }
336     }
337   }
338   h += line.height;
339   if(numWords > 0) {
340     lineLayouts.append(line);
341   }
342   hght = h;
343   return hght;
344 }
345
346 //!\brief Draw ChatLine on the given QPainter at the given position.
347 void ChatLine::draw(QPainter *p, const QPointF &pos) {
348   QPalette pal = QApplication::palette();
349
350   if(selectionMode == Full) {
351     p->setPen(Qt::NoPen);
352     p->setBrush(pal.brush(QPalette::Highlight));
353     p->drawRect(QRectF(pos, QSizeF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText() + textWidth, height())));
354   } else if(selectionMode == Partial) {
355
356   } /*
357   p->setClipRect(QRectF(pos, QSizeF(tsWidth, height())));
358   tsLayout.draw(p, pos, tsFormat);
359   p->setClipRect(QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, height())));
360   senderLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender(), 0), senderFormat);
361   p->setClipping(false);
362   textLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0), textFormat);
363     */
364   //p->setClipRect(QRectF(pos, QSizeF(tsWidth, 15)));
365   //p->drawRect(QRectF(pos, QSizeF(tsWidth, minHeight)));
366   p->setBackgroundMode(Qt::OpaqueMode);
367   QPointF tp = pos;
368   QRectF rect(pos, QSizeF(tsWidth, minHeight));
369   QRectF brect;
370   foreach(FormatRange fr, tsFormat) {
371     p->setFont(fr.format.font());
372     p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
373     p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, tsFormatted.text.mid(fr.start, fr.length), &brect);
374     rect.setLeft(brect.right());
375   }
376   rect = QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, minHeight));
377   for(int i = senderFormat.count() - 1; i >= 0; i--) {
378     FormatRange fr = senderFormat[i];
379     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
380     p->drawText(rect, Qt::AlignRight|Qt::TextSingleLine, senderFormatted.text.mid(fr.start, fr.length), &brect);
381     rect.setRight(brect.left());
382   }
383   QPointF tpos = pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0);
384   qreal h = 0; int l = 0;
385   rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
386   int offset = 0;
387   foreach(FormatRange fr, textFormat) {
388     if(l >= lineLayouts.count()) break;
389     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
390     int start, end, frend, llend;
391     do {
392       frend = fr.start + fr.length;
393       if(frend <= lineLayouts[l].start) break;
394       llend = lineLayouts[l].start + lineLayouts[l].length;
395       start = qMax(fr.start, lineLayouts[l].start); end = qMin(frend, llend);
396       rect.setLeft(tpos.x() + charPos[start] - offset);
397       p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, textFormatted.text.mid(start, end - start), &brect);
398       if(llend <= end) {
399         h += lineLayouts[l].height;
400         l++;
401         if(l < lineLayouts.count()) {
402           rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
403           offset = charPos[lineLayouts[l].start];
404         }
405       }
406     } while(end < frend && l < lineLayouts.count());
407   }
408 }