added first and simple version of Tabcompletion (Nicks only atm)
[quassel.git] / gui / chatwidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel 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 "util.h"
22 #include "style.h"
23 #include "chatwidget.h"
24 #include <QtGui>
25 #include <QtCore>
26
27 ChatWidget::ChatWidget(QWidget *parent) : QAbstractScrollArea(parent) {
28   scrollTimer = new QTimer(this);
29   scrollTimer->setSingleShot(false);
30   scrollTimer->setInterval(100);
31   setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
32   setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
33   setMinimumSize(QSize(400,400));
34   setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
35   setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
36   bottomLine = -1;
37   height = 0;
38   ycoords.append(0);
39   pointerPosition = QPoint(0,0);
40   connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(scrollBarAction(int)));
41   connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrollBarValChanged(int)));
42 }
43
44 void ChatWidget::init(QString netname, QString bufname) {
45   networkName = netname;
46   bufferName = bufname;
47   setBackgroundRole(QPalette::Base);
48   setFont(QFont("Fixed"));
49   tsWidth = 90;
50   senderWidth = 100;
51   computePositions();
52   adjustScrollBar();
53   verticalScrollBar()->setValue(verticalScrollBar()->maximum());
54   //verticalScrollBar()->setPageStep(viewport()->height());
55   //verticalScrollBar()->setSingleStep(20);
56   //verticalScrollBar()->setMinimum(0);
57   //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
58
59   setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
60   setMouseTracking(true);
61   mouseMode = Normal;
62   selectionMode = NoSelection;
63   connect(scrollTimer, SIGNAL(timeout()), this, SLOT(handleScrollTimer()));
64 }
65
66 ChatWidget::~ChatWidget() {
67   //qDebug() << "destroying chatwidget" << bufferName;
68   foreach(ChatLine *l, lines) {
69     delete l;
70   }
71 }
72
73 QSize ChatWidget::sizeHint() const {
74   //qDebug() << size();
75   return size();
76 }
77
78 void ChatWidget::adjustScrollBar() {
79   verticalScrollBar()->setPageStep(viewport()->height());
80   verticalScrollBar()->setSingleStep(20);
81   verticalScrollBar()->setMinimum(0);
82   verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
83   //qDebug() << height << viewport()->height() << verticalScrollBar()->pageStep();
84   //if(bottomLine < 0) {
85   //  verticalScrollBar()->setValue(verticalScrollBar()->maximum());
86   //} else {
87     //int bot = verticalScrollBar()->value() + viewport()->height(); //qDebug() << bottomLine;
88     //verticalScrollBar()->setValue(qMax(0, (int)ycoords[bottomLine+1] - viewport()->height()));
89   //}
90 }
91
92 void ChatWidget::scrollBarValChanged(int val) {
93   return;
94   if(val >= verticalScrollBar()->maximum()) bottomLine = -1;
95   else {
96     int bot = val + viewport()->height();
97     int line = yToLineIdx(bot);
98     //bottomLine = line;
99   }
100 }
101
102 void ChatWidget::scrollBarAction(int action) {
103   switch(action) {
104     case QScrollBar::SliderSingleStepAdd:
105       // More elaborate. But what with loooong lines?
106       // verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value() + viewport()->height()) + 1] - viewport()->height());
107       break;
108     case QScrollBar::SliderSingleStepSub:
109       //verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value())]);
110       break;
111
112   }
113
114 }
115
116 void ChatWidget::handleScrollTimer() {
117   if(mouseMode == MarkText || mouseMode == MarkLines) {
118     if(pointerPosition.y() > viewport()->height()) {
119       verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y() - viewport()->height());
120       handleMouseMoveEvent(QPoint(pointerPosition.x(), viewport()->height()));
121     } else if(pointerPosition.y() < 0) {
122       verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y());
123       handleMouseMoveEvent(QPoint(pointerPosition.x(), 0));
124     }
125   }
126 }
127
128 void ChatWidget::ensureVisible(int line) {
129   int top = verticalScrollBar()->value();
130   int bot = top + viewport()->height();
131   if(ycoords[line+1] > bot) {
132     verticalScrollBar()->setValue(qMax(0, (int)ycoords[line+1] - viewport()->height()));
133   } else if(ycoords[line] < top) {
134     verticalScrollBar()->setValue((int)ycoords[line]);
135   }
136
137 }
138
139 void ChatWidget::clear() {
140   //contents->clear();
141 }
142
143 void ChatWidget::prependChatLines(QList<ChatLine *> clist) {
144   QList<qreal> tmpy; tmpy.append(0);
145   qreal h = 0;
146   foreach(ChatLine *l, clist) {
147     h += l->layout(tsWidth, senderWidth, textWidth);
148     tmpy.append(h);
149   }
150   ycoords.removeFirst();
151   for(int i = 0; i < ycoords.count(); i++) ycoords[i] += h;
152   ycoords = tmpy + ycoords;
153   lines = clist + lines;
154   height += h;
155   /* Fix all variables containing line numbers */
156   int i = clist.count();
157   dragStartLine += i;
158   curLine += i;
159   selectionStart += i; selectionEnd += i; selectionEnd += i;
160   //if(bottomLine >= 0) bottomLine += i;
161   adjustScrollBar();
162   //verticalScrollBar()->setPageStep(viewport()->height());
163   //verticalScrollBar()->setSingleStep(20);
164   //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
165   verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
166   viewport()->update();
167 }
168
169 void ChatWidget::appendMsg(Message msg) {
170   ChatLine *line = new ChatLine(msg, networkName, bufferName);
171   qreal h = line->layout(tsWidth, senderWidth, textWidth);
172   ycoords.append(h + ycoords[ycoords.count() - 1]);
173   height += h;
174   bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
175   adjustScrollBar();
176   if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
177   lines.append(line);
178   viewport()->update();
179 }
180
181 void ChatWidget::appendMsgList(QList<Message> *list) {
182   foreach(Message msg, *list) {
183    ChatLine *line = new ChatLine(msg, networkName, bufferName);
184     qreal h = line->layout(tsWidth, senderWidth, textWidth);
185     ycoords.append(h + ycoords[ycoords.count() - 1]);
186     height += h;
187     lines.append(line);
188   }
189   bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
190   adjustScrollBar();
191   if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
192   viewport()->update();
193 }
194
195 //!\brief Computes the different x position vars for given tsWidth and senderWidth.
196 void ChatWidget::computePositions() {
197   senderX = tsWidth + Style::sepTsSender();
198   textX = senderX + senderWidth + Style::sepSenderText();
199   tsGrabPos = tsWidth + (int)Style::sepTsSender()/2;
200   senderGrabPos = senderX + senderWidth + (int)Style::sepSenderText()/2;
201   textWidth = viewport()->size().width() - textX;
202 }
203
204 void ChatWidget::resizeEvent(QResizeEvent *event) {
205   //qDebug() << bufferName << isVisible() << event->size() << event->oldSize();
206   /*if(event->oldSize().isValid())*/
207   //contents->setWidth(event->size().width());
208   //setAlignment(Qt::AlignBottom);
209   if(event->size().width() != event->oldSize().width()) {
210     computePositions();
211     layout();
212   }
213   //adjustScrollBar();
214   //qDebug() << viewport()->size() << viewport()->height();
215   //QAbstractScrollArea::resizeEvent(event);
216   //qDebug() << viewport()->size() << viewport()->geometry();
217 }
218
219 void ChatWidget::paintEvent(QPaintEvent *event) {
220   QPainter painter(viewport());
221
222   //qDebug() <<  verticalScrollBar()->value();
223   painter.translate(0, -verticalScrollBar()->value());
224   int top = event->rect().top() + verticalScrollBar()->value();
225   int bot = top + event->rect().height();
226   int idx = yToLineIdx(top);
227   if(idx < 0) return;
228   for(int i = idx; i < lines.count() ; i++) {
229     lines[i]->draw(&painter, QPointF(0, ycoords[i]));
230     if(ycoords[i+1] > bot) return;
231   }
232 }
233
234 //!\brief Layout the widget.
235 void ChatWidget::layout() {
236   // TODO fix scrollbars
237   //int botLine = yToLineIdx(verticalScrollBar()->value() + 
238   qreal y = 0;
239   for(int i = 0; i < lines.count(); i++) {
240     qreal h = lines[i]->layout(tsWidth, senderWidth, textWidth);
241     ycoords[i+1] = h + ycoords[i];
242   }
243   height = ycoords[ycoords.count()-1];
244   adjustScrollBar();
245   verticalScrollBar()->setValue(verticalScrollBar()->maximum());
246   viewport()->update();
247 }
248
249 int ChatWidget::yToLineIdx(qreal y) {
250   if(y >= ycoords[ycoords.count()-1]) ycoords.count()-1;
251   if(ycoords.count() <= 1) return 0;
252   int uidx = 0;
253   int oidx = ycoords.count() - 1;
254   int idx;
255   while(1) {
256     if(uidx == oidx - 1) return uidx;
257     idx = (uidx + oidx) / 2;
258     if(ycoords[idx] > y) oidx = idx;
259     else uidx = idx;
260   }
261 }
262
263 void ChatWidget::mousePressEvent(QMouseEvent *event) {
264   if(lines.isEmpty()) return;
265   QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
266   if(event->button() == Qt::LeftButton) {
267     dragStartPos = pos;
268     dragStartMode = Normal;
269     switch(mouseMode) {
270       case Normal:
271         if(mousePos == OverTsSep) {
272           dragStartMode = DragTsSep;
273           setCursor(Qt::ClosedHandCursor);
274         } else if(mousePos == OverTextSep) {
275           dragStartMode = DragTextSep;
276           setCursor(Qt::ClosedHandCursor);
277         } else {
278           dragStartLine = yToLineIdx(pos.y());
279           dragStartCursor = lines[dragStartLine]->posToCursor(QPointF(pos.x(), pos.y()-ycoords[dragStartLine]));
280         }
281         mouseMode = Pressed;
282         break;
283     }
284   }
285 }
286
287 void ChatWidget::mouseDoubleClickEvent(QMouseEvent *event) {
288
289
290
291 }
292
293 void ChatWidget::mouseReleaseEvent(QMouseEvent *event) {
294   //QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
295
296   if(event->button() == Qt::LeftButton) {
297     dragStartPos = QPoint();
298     if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
299     else setCursor(Qt::ArrowCursor);
300
301     switch(mouseMode) {
302       case Pressed:
303         mouseMode = Normal;
304         clearSelection();
305         break;
306       case MarkText:
307         mouseMode = Normal;
308         selectionMode = TextSelected;
309         selectionLine = dragStartLine;
310         selectionStart = qMin(dragStartCursor, curCursor);
311         selectionEnd = qMax(dragStartCursor, curCursor);
312         // TODO Make X11SelectionMode configurable!
313         QApplication::clipboard()->setText(selectionToString());
314         break;
315       case MarkLines:
316         mouseMode = Normal;
317         selectionMode = LinesSelected;
318         selectionStart = qMin(dragStartLine, curLine);
319         selectionEnd = qMax(dragStartLine, curLine);
320         // TODO Make X11SelectionMode configurable!
321         QApplication::clipboard()->setText(selectionToString());
322         break;
323       default:
324         mouseMode = Normal;
325     }
326   }
327 }
328
329 //!\brief React to mouse movements over the ChatWidget.
330 /** This is called by Qt whenever the mouse moves. Here we have to do most of the mouse handling,
331  * such as changing column widths, marking text or initiating drag & drop.
332  */
333 void ChatWidget::mouseMoveEvent(QMouseEvent *event) {
334   QPoint pos = event->pos(); pointerPosition = pos;
335   // Scroll if mouse pointer leaves widget while dragging
336   if((mouseMode == MarkText || mouseMode == MarkLines) && (pos.y() > viewport()->height() || pos.y() < 0)) {
337     if(!scrollTimer->isActive()) {
338       scrollTimer->start();
339     }
340   } else {
341     if(scrollTimer->isActive()) {
342       scrollTimer->stop();
343     }
344   }
345   handleMouseMoveEvent(pos);
346 }
347
348 void ChatWidget::handleMouseMoveEvent(const QPoint &_pos) {
349   // FIXME
350   if(lines.count() <= 0) return;
351   // Set some basic properties of the current position
352   QPoint pos = _pos + QPoint(0, verticalScrollBar()->value());
353   int x = pos.x();
354   int y = pos.y();
355   MousePos oldpos = mousePos;
356   if(x >= tsGrabPos - 3 && x <= tsGrabPos + 3) mousePos = OverTsSep;
357   else if(x >= senderGrabPos - 3 && x <= senderGrabPos + 3) mousePos = OverTextSep;
358   else mousePos = None;
359
360   // Pass 1: Do whatever we can before switching mouse mode (if at all).
361   switch(mouseMode) {
362     // No special mode. Set mouse cursor if appropriate.
363     case Normal:
364     {
365       //if(oldpos != mousePos) {
366       if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
367       else {
368         int l = yToLineIdx(y);
369         int c = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
370         if(c >= 0 && lines[l]->isUrl(c)) {
371           setCursor(Qt::PointingHandCursor);
372         } else {
373           setCursor(Qt::ArrowCursor);
374         }
375       }
376     }
377       break;
378     // Left button pressed. Might initiate marking or drag & drop if we moved past the drag distance.
379     case Pressed:
380       if(!dragStartPos.isNull() && (dragStartPos - pos).manhattanLength() >= QApplication::startDragDistance()) {
381         // Moving a column separator?
382         if(dragStartMode == DragTsSep) mouseMode = DragTsSep;
383         else if(dragStartMode == DragTextSep) mouseMode = DragTextSep;
384         // Nope. Check if we are over a selection to start drag & drop.
385         else if(dragStartMode == Normal) {
386           bool dragdrop = false;
387           if(selectionMode == TextSelected) {
388             int l = yToLineIdx(y);
389             if(selectionLine == l) {
390               int p = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
391               if(p >= selectionStart && p <= selectionEnd) dragdrop = true;
392             }
393           } else if(selectionMode == LinesSelected) {
394             int l = yToLineIdx(y);
395             if(l >= selectionStart && l <= selectionEnd) dragdrop = true;
396           }
397           // Ok, so just start drag & drop if appropriate.
398           if(dragdrop) {
399             QDrag *drag = new QDrag(this);
400             QMimeData *mimeData = new QMimeData;
401             mimeData->setText(selectionToString());
402             drag->setMimeData(mimeData);
403             drag->start();
404             mouseMode = Normal;
405           // Otherwise, clear the selection and start text marking!
406           } else {
407             setCursor(Qt::ArrowCursor);
408             clearSelection();
409             if(dragStartCursor < 0) { mouseMode = MarkLines; curLine = -1; }
410             else mouseMode = MarkText;
411           }
412         }
413       }
414       break;
415     case DragTsSep:
416       break;
417     case DragTextSep:
418       break;
419   }
420   // Pass 2: Some mouse modes need work after being set...
421   if(mouseMode == DragTsSep && x < size().width() - Style::sepSenderText() - senderWidth - 10) {
422     // Drag first column separator
423     int foo = Style::sepTsSender()/2;
424     tsWidth = qMax(x, foo) - foo;
425     computePositions();
426     layout();
427   } else if(mouseMode == DragTextSep && x < size().width() - 10) {
428     // Drag second column separator
429     int foo = tsWidth + Style::sepTsSender() + Style::sepSenderText()/2;
430     senderWidth = qMax(x, foo) - foo;
431     computePositions();
432     layout();
433   } else if(mouseMode == MarkText) {
434     // Change currently marked text
435     curLine = yToLineIdx(y);
436     int c = lines[curLine]->posToCursor(QPointF(x, y - ycoords[curLine]));
437     if(curLine == dragStartLine && c >= 0) {
438       if(c != curCursor) {
439         curCursor = c;
440         lines[curLine]->setSelection(ChatLine::Partial, dragStartCursor, c);
441         viewport()->update();
442       }
443     } else {
444       mouseMode = MarkLines;
445       selectionStart = qMin(curLine, dragStartLine); selectionEnd = qMax(curLine, dragStartLine);
446       for(int i = selectionStart; i <= selectionEnd; i++) lines[i]->setSelection(ChatLine::Full);
447       viewport()->update();
448     }
449   } else if(mouseMode == MarkLines) {
450     // Line marking
451     int l = yToLineIdx(y);
452     if(l != curLine) {
453       selectionStart = qMin(l, dragStartLine); selectionEnd = qMax(l, dragStartLine);
454       if(curLine < 0) {
455         Q_ASSERT(selectionStart == selectionEnd);
456         lines[l]->setSelection(ChatLine::Full);
457       } else {
458         if(curLine < selectionStart) {
459           for(int i = curLine; i < selectionStart; i++) lines[i]->setSelection(ChatLine::None);
460         } else if(curLine > selectionEnd) {
461           for(int i = selectionEnd+1; i <= curLine; i++) lines[i]->setSelection(ChatLine::None);
462         } else if(selectionStart < curLine && l < curLine) {
463           for(int i = selectionStart; i < curLine; i++) lines[i]->setSelection(ChatLine::Full);
464         } else if(curLine < selectionEnd && l > curLine) {
465           for(int i = curLine+1; i <= selectionEnd; i++) lines[i]->setSelection(ChatLine::Full);
466         }
467       }
468       curLine = l;
469       //ensureVisible(l);
470       viewport()->update();
471     }
472   }
473 }
474
475 //!\brief Clear current text selection.
476 void ChatWidget::clearSelection() {
477   if(selectionMode == TextSelected) {
478     lines[selectionLine]->setSelection(ChatLine::None);
479   } else if(selectionMode == LinesSelected) {
480     for(int i = selectionStart; i <= selectionEnd; i++) {
481       lines[i]->setSelection(ChatLine::None);
482     }
483   }
484   selectionMode = NoSelection;
485   viewport()->update();
486 }
487
488 //!\brief Convert current selection to human-readable string.
489 QString ChatWidget::selectionToString() {
490   //TODO Make selection format configurable!
491   if(selectionMode == NoSelection) return "";
492   if(selectionMode == LinesSelected) {
493     QString result;
494     for(int l = selectionStart; l <= selectionEnd; l++) {
495       result += QString("[%1] %2 %3\n").arg(lines[l]->getTimeStamp().toLocalTime().toString("hh:mm:ss"))
496           .arg(lines[l]->getSender()).arg(lines[l]->getText());
497     }
498     return result;
499   }
500   // selectionMode == TextSelected
501   return lines[selectionLine]->getText().mid(selectionStart, selectionEnd - selectionStart);
502 }
503
504 /************************************************************************************/
505
506 //!\brief Construct a ChatLine object from a message.
507 /**
508  * \param m   The message to be layouted and rendered
509  * \param net The network name
510  * \param buf The buffer name
511  */ 
512 ChatLine::ChatLine(Message m, QString net, QString buf) : QObject() {
513   hght = 0;
514   networkName = net;
515   bufferName = buf;
516   msg = m;
517   selectionMode = None;
518   formatMsg(msg);
519
520 }
521
522 ChatLine::~ChatLine() {
523
524 }
525
526 void ChatLine::formatMsg(Message msg) {
527   QString user = userFromMask(msg.sender);
528   QString host = hostFromMask(msg.sender);
529   QString nick = nickFromMask(msg.sender);
530   QString text = Style::mircToInternal(msg.text);
531
532   QString c = tr("%DT[%1]").arg(msg.timeStamp.toLocalTime().toString("hh:mm:ss"));
533   QString s, t;
534   switch(msg.type) {
535     case Message::Plain:
536       s = tr("%DS<%1>").arg(nick); t = tr("%D0%1").arg(text); break;
537     case Message::Server:
538       s = tr("%Ds*"); t = tr("%Ds%1").arg(text); break;
539     case Message::Error:
540       s = tr("%De*"); t = tr("%De%1").arg(text); break;
541     case Message::Join:
542       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;
543     case Message::Part:
544       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);
545       if(!text.isEmpty()) t = QString("%1 (%2)").arg(t).arg(text);
546       break;
547     case Message::Quit:
548       s = tr("%Dq<--"); t = tr("%Dq%DN%DU%1%DU%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
549       if(!text.isEmpty()) t = QString("%1 (%2)").arg(t).arg(text);
550       break;
551     case Message::Kick:
552       { s = tr("%Dk<-*");
553         QString victim = text.section(" ", 0, 0);
554         //if(victim == ui.ownNick->currentText()) victim = tr("you");
555         QString kickmsg = text.section(" ", 1);
556         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);
557         if(!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
558       }
559       break;
560     case Message::Nick:
561       s = tr("%Dr<->");
562       if(nick == msg.text) t = tr("%DrYou are now known as %DN%1%DN").arg(msg.text);
563       else t = tr("%Dr%DN%1%DN is now known as %DN%DU%2%DU%DN").arg(nick, msg.text);
564       break;
565     case Message::Mode:
566       s = tr("%Dm***");
567       if(nick.isEmpty()) t = tr("%DmUser mode: %DM%1%DM").arg(msg.text);
568       else t = tr("%DmMode %DM%1%DM by %DN%DU%2%DU%DN").arg(msg.text, nick);
569       break;
570     default:
571       s = tr("%De%1").arg(msg.sender);
572       t = tr("%De[%1]").arg(msg.text);
573   }
574   QTextOption tsOption, senderOption, textOption;
575   tsFormatted = Style::internalToFormatted(c);
576   senderFormatted = Style::internalToFormatted(s);
577   textFormatted = Style::internalToFormatted(t);
578   precomputeLine();
579 }
580
581 QList<ChatLine::FormatRange> ChatLine::calcFormatRanges(const Style::FormattedString &fs, QTextLayout::FormatRange additional) {
582   QList<FormatRange> ranges;
583   QList<QTextLayout::FormatRange> formats = fs.formats;
584   formats.append(additional);
585   int cur = -1;
586   FormatRange range, lastrange;
587   for(int i = 0; i < fs.text.length(); i++) {
588     QTextCharFormat format;
589     foreach(QTextLayout::FormatRange f, formats) {
590       if(i >= f.start && i < f.start + f.length) format.merge(f.format);
591     }
592     if(cur < 0) {
593       range.start = 0; range.length = 1; range.format= format;
594       cur = 0;
595     } else {
596       if(format == range.format) range.length++;
597       else {
598         QFontMetrics metrics(range.format.font());
599         range.height = metrics.lineSpacing();
600         ranges.append(range);
601         range.start = i; range.length = 1; range.format = format;
602         cur++;
603       }
604     }
605   }
606   if(cur >= 0) {
607     QFontMetrics metrics(range.format.font());
608     range.height = metrics.lineSpacing();
609     ranges.append(range);
610   }
611   return ranges;
612 }
613
614 void ChatLine::setSelection(SelectionMode mode, int start, int end) {
615   selectionMode = mode;
616   //tsFormat.clear(); senderFormat.clear(); textFormat.clear();
617   QPalette pal = QApplication::palette();
618   QTextLayout::FormatRange tsSel, senderSel, textSel;
619   switch (mode) {
620     case None:
621       tsFormat = calcFormatRanges(tsFormatted);
622       senderFormat = calcFormatRanges(senderFormatted);
623       textFormat = calcFormatRanges(textFormatted);
624       break;
625     case Partial:
626       selectionStart = qMin(start, end); selectionEnd = qMax(start, end);
627       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
628       textSel.format.setBackground(pal.brush(QPalette::Highlight));
629       textSel.start = selectionStart;
630       textSel.length = selectionEnd - selectionStart;
631       //textFormat.append(textSel);
632       textFormat = calcFormatRanges(textFormatted, textSel);
633       foreach(FormatRange fr, textFormat);
634       break;
635     case Full:
636       tsSel.format.setForeground(pal.brush(QPalette::HighlightedText));
637       tsSel.format.setBackground(pal.brush(QPalette::Highlight));
638       tsSel.start = 0; tsSel.length = tsFormatted.text.length();
639       tsFormat = calcFormatRanges(tsFormatted, tsSel);
640       senderSel.format.setForeground(pal.brush(QPalette::HighlightedText));
641       senderSel.format.setBackground(pal.brush(QPalette::Highlight));
642       senderSel.start = 0; senderSel.length = senderFormatted.text.length();
643       senderFormat = calcFormatRanges(senderFormatted, senderSel);
644       textSel.format.setForeground(pal.brush(QPalette::HighlightedText));
645       textSel.format.setBackground(pal.brush(QPalette::Highlight));
646       textSel.start = 0; textSel.length = textFormatted.text.length();
647       textFormat = calcFormatRanges(textFormatted, textSel);
648       break;
649   }
650 }
651
652 QDateTime ChatLine::getTimeStamp() {
653   return msg.timeStamp;
654 }
655
656 QString ChatLine::getSender() {
657   return senderFormatted.text;
658 }
659
660 QString ChatLine::getText() {
661   return textFormatted.text;
662 }
663
664 bool ChatLine::isUrl(int c) {
665   if(c < 0 || c >= charUrlIdx.count()) return false;;
666   return charUrlIdx[c] >= 0;
667 }
668
669 QUrl ChatLine::getUrl(int c) {
670   if(c < 0 || c >= charUrlIdx.count()) return QUrl();
671   int i = charUrlIdx[c];
672   if(i >= 0) return textFormatted.urls[i].url;
673   else return QUrl();
674 }
675
676 //!\brief Return the cursor position for the given coordinate pos.
677 /**
678  * \param pos The position relative to the ChatLine
679  * \return The cursor position, [or -3 for invalid,] or -2 for timestamp, or -1 for sender
680  */
681 int ChatLine::posToCursor(QPointF pos) {
682   if(pos.x() < tsWidth + (int)Style::sepTsSender()/2) return -2;
683   qreal textStart = tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText();
684   if(pos.x() < textStart) return -1;
685   int x = (int)(pos.x() - textStart);
686   for(int l = lineLayouts.count() - 1; l >=0; l--) {
687     LineLayout line = lineLayouts[l];
688     if(pos.y() >= line.y) {
689       int offset = charPos[line.start]; x += offset;
690       for(int i = line.start + line.length - 1; i >= line.start; i--) {
691         if((charPos[i] + charPos[i+1])/2 <= x) return i+1; // FIXME: Optimize this!
692       }
693       return line.start;
694     }
695   }
696 }
697
698 void ChatLine::precomputeLine() {
699   tsFormat = calcFormatRanges(tsFormatted);
700   senderFormat = calcFormatRanges(senderFormatted);
701   textFormat = calcFormatRanges(textFormatted);
702
703   minHeight = 0;
704   foreach(FormatRange fr, tsFormat) minHeight = qMax(minHeight, fr.height);
705   foreach(FormatRange fr, senderFormat) minHeight = qMax(minHeight, fr.height);
706
707   words.clear();
708   charPos.resize(textFormatted.text.length() + 1);
709   charHeights.resize(textFormatted.text.length());
710   charUrlIdx.fill(-1, textFormatted.text.length());
711   for(int i = 0; i < textFormatted.urls.count(); i++) {
712     Style::UrlInfo url = textFormatted.urls[i];
713     for(int j = url.start; j < url.end; j++) charUrlIdx[j] = i;
714   }
715   if(!textFormat.count()) return;
716   int idx = 0; int cnt = 0; int w = 0; int h = 0;
717   QFontMetrics metrics(textFormat[0].format.font());
718   Word wr;
719   wr.start = -1; wr.trailing = -1;
720   for(int i = 0; i < textFormatted.text.length(); ) {
721     charPos[i] = w; charHeights[i] = textFormat[idx].height;
722     w += metrics.charWidth(textFormatted.text, i);
723     if(!textFormatted.text[i].isSpace()) {
724       if(wr.trailing >= 0) {
725         // new word after space
726         words.append(wr);
727         wr.start = -1;
728       }
729       if(wr.start < 0) {
730         wr.start = i; wr.length = 1; wr.trailing = -1; wr.height = textFormat[idx].height;
731       } else {
732         wr.length++; wr.height = qMax(wr.height, textFormat[idx].height);
733       }
734     } else {
735       if(wr.start < 0) {
736         wr.start = i; wr.length = 0; wr.trailing = 1; wr.height = 0;
737       } else {
738         wr.trailing++;
739       }
740     }
741     if(++i < textFormatted.text.length() && ++cnt >= textFormat[idx].length) {
742       cnt = 0; idx++;
743       Q_ASSERT(idx < textFormat.count());
744       metrics = QFontMetrics(textFormat[idx].format.font());
745     }
746   }
747   charPos[textFormatted.text.length()] = w;
748   if(wr.start >= 0) words.append(wr);
749 }
750
751 qreal ChatLine::layout(qreal tsw, qreal senderw, qreal textw) {
752   tsWidth = tsw; senderWidth = senderw; textWidth = textw;
753   if(textw <= 0) return minHeight;
754   lineLayouts.clear(); LineLayout line;
755   int h = 0;
756   int offset = 0; int numWords = 0;
757   line.y = 0;
758   line.start = 0;
759   line.height = minHeight;  // first line needs room for ts and sender
760   for(int i = 0; i < words.count(); i++) {
761     int lastpos = charPos[words[i].start + words[i].length]; // We use charPos[lastchar + 1], 'coz last char needs to fit
762     if(lastpos - offset <= textw) {
763       line.height = qMax(line.height, words[i].height);
764       line.length = words[i].start + words[i].length - line.start;
765       numWords++;
766     } else {
767       // we need to wrap!
768       if(numWords > 0) {
769         // ok, we had some words before, so store the layout and start a new line
770         h += line.height;
771         line.length = words[i-1].start + words[i-1].length - line.start;
772         lineLayouts.append(line);
773         line.y += line.height;
774         line.start = words[i].start;
775         line.height = words[i].height;
776         offset = charPos[words[i].start];
777       }
778       numWords = 1;
779       // check if the word fits into the current line
780       if(lastpos - offset <= textw) {
781         line.length = words[i].length;
782       } else {
783         // we need to break a word in the middle
784         int border = (int)textw + offset; // save some additions
785         line.start = words[i].start;
786         line.length = 1;
787         line.height = charHeights[line.start];
788         int j = line.start + 1;
789         for(int l = 1; l < words[i].length; j++, l++) {
790           if(charPos[j+1] < border) {
791             line.length++;
792             line.height = qMax(line.height, charHeights[j]);
793             continue;
794           } else {
795             h += line.height;
796             lineLayouts.append(line);
797             line.y += line.height;
798             line.start = j;
799             line.height = charHeights[j];
800             line.length = 1;
801             offset = charPos[j];
802             border = (int)textw + offset;
803           }
804         }
805       }
806     }
807   }
808   h += line.height;
809   if(numWords > 0) {
810     lineLayouts.append(line);
811   }
812   hght = h;
813   return hght;
814 }
815
816 //!\brief Draw ChatLine on the given QPainter at the given position.
817 void ChatLine::draw(QPainter *p, const QPointF &pos) {
818   QPalette pal = QApplication::palette();
819
820   if(selectionMode == Full) {
821     p->setPen(Qt::NoPen);
822     p->setBrush(pal.brush(QPalette::Highlight));
823     p->drawRect(QRectF(pos, QSizeF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText() + textWidth, height())));
824   } else if(selectionMode == Partial) {
825
826   } /*
827   p->setClipRect(QRectF(pos, QSizeF(tsWidth, height())));
828   tsLayout.draw(p, pos, tsFormat);
829   p->setClipRect(QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, height())));
830   senderLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender(), 0), senderFormat);
831   p->setClipping(false);
832   textLayout.draw(p, pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0), textFormat);
833   */
834   //p->setClipRect(QRectF(pos, QSizeF(tsWidth, 15)));
835   //p->drawRect(QRectF(pos, QSizeF(tsWidth, minHeight)));
836   p->setBackgroundMode(Qt::OpaqueMode);
837   QPointF tp = pos;
838   QRectF rect(pos, QSizeF(tsWidth, minHeight));
839   QRectF brect;
840   foreach(FormatRange fr, tsFormat) {
841     p->setFont(fr.format.font());
842     p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
843     p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, tsFormatted.text.mid(fr.start, fr.length), &brect);
844     rect.setLeft(brect.right());
845   }
846   rect = QRectF(pos + QPointF(tsWidth + Style::sepTsSender(), 0), QSizeF(senderWidth, minHeight));
847   for(int i = senderFormat.count() - 1; i >= 0; i--) {
848     FormatRange fr = senderFormat[i];
849     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
850     p->drawText(rect, Qt::AlignRight|Qt::TextSingleLine, senderFormatted.text.mid(fr.start, fr.length), &brect);
851     rect.setRight(brect.left());
852   }
853   QPointF tpos = pos + QPointF(tsWidth + Style::sepTsSender() + senderWidth + Style::sepSenderText(), 0);
854   qreal h = 0; int l = 0;
855   rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
856   int offset = 0;
857   foreach(FormatRange fr, textFormat) {
858     if(l >= lineLayouts.count()) break;
859     p->setFont(fr.format.font()); p->setPen(QPen(fr.format.foreground(), 0)); p->setBackground(fr.format.background());
860     int start, end, frend, llend;
861     do {
862       frend = fr.start + fr.length;
863       if(frend <= lineLayouts[l].start) break;
864       llend = lineLayouts[l].start + lineLayouts[l].length;
865       start = qMax(fr.start, lineLayouts[l].start); end = qMin(frend, llend);
866       rect.setLeft(tpos.x() + charPos[start] - offset);
867       p->drawText(rect, Qt::AlignLeft|Qt::TextSingleLine, textFormatted.text.mid(start, end - start), &brect);
868       if(llend <= end) {
869         h += lineLayouts[l].height;
870         l++;
871         if(l < lineLayouts.count()) {
872           rect = QRectF(tpos + QPointF(0, h), QSizeF(textWidth, lineLayouts[l].height));
873           offset = charPos[lineLayouts[l].start];
874         }
875       }
876     } while(end < frend && l < lineLayouts.count());
877   }
878 }
879
880 /******************************************************************************************************************/
881
882 LayoutThread::LayoutThread() : QThread() {
883   mutex.lock();
884   abort = false;
885   mutex.unlock();
886
887 }
888
889 LayoutThread::~LayoutThread() {
890   mutex.lock();
891   abort = true;
892   mutex.unlock();
893   condition.wakeOne();
894   wait();
895 }
896
897 void LayoutThread::processTask(LayoutTask task) {
898   if(!isRunning()) start();
899   Q_ASSERT(isRunning());
900   mutex.lock();
901   queue.append(task);
902   condition.wakeOne();
903   mutex.unlock();
904 }
905
906 void LayoutThread::run() {
907   forever {
908     mutex.lock();
909     if(!queue.count()) {
910       condition.wait(&mutex);
911     }
912     if(abort) {
913       mutex.unlock(); return;
914     }
915     Q_ASSERT(queue.count()); //qDebug() << "process";
916     LayoutTask task = queue.takeFirst();
917     mutex.unlock();
918         /*
919     foreach(Message msg, task.messages) {
920       //qDebug() << msg.text;
921       ChatLine *line = new ChatLine(msg, task.net, task.buf);
922       task.lines.append(line);
923     }
924     emit taskProcessed(task);
925         */
926     //msleep(500);
927   }
928 }