Make X11 selection work correctly (marked text in the ChatWidget now goes into XSelec...
[quassel.git] / src / qtui / chatwidget.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 "util.h"
22 #include "chatwidget.h"
23 #include "chatline-old.h"
24 #include "qtui.h"
25 #include "uisettings.h"
26 #include "client.h"
27 #include "buffer.h"
28 #include "clientbacklogmanager.h"
29
30 ChatWidget::ChatWidget(BufferId bufid, QWidget *parent) : QAbstractScrollArea(parent), AbstractChatView(),
31     lastBacklogOffset(0),
32     lastBacklogSize(0)
33 {
34   //setAutoFillBackground(false);
35   //QPalette palette;
36   //palette.setColor(backgroundRole(), QColor(0, 0, 0, 50));
37   //setPalette(palette);
38   scrollTimer = new QTimer(this);
39   scrollTimer->setSingleShot(false);
40   scrollTimer->setInterval(100);
41   // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
42   setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
43   setMinimumSize(QSize(20,20));
44   setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
45   setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
46   bottomLine = -1;
47   height = 0;
48   ycoords.append(0);
49   pointerPosition = QPoint(0,0);
50   connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(scrollBarAction(int)));
51   connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrollBarValChanged(int)));
52
53   init(bufid);
54 }
55
56 void ChatWidget::init(BufferId id) {
57   bufferId = id;
58   setBackgroundRole(QPalette::Base);
59   setFont(QFont("Fixed"));
60   UiSettings s;
61   QVariant tsDef = s.value("DefaultTimestampColumnWidth", 90);
62   QVariant senderDef = s.value("DefaultSenderColumnWidth", 100);
63   tsWidth = s.value(QString("%1/TimestampColumnWidth").arg(bufferId.toInt()), tsDef).toInt();
64   senderWidth = s.value(QString("%1/SenderColumnWidth").arg(bufferId.toInt()), senderDef).toInt();
65   computePositions();
66   adjustScrollBar();
67   verticalScrollBar()->setValue(verticalScrollBar()->maximum());
68   //verticalScrollBar()->setPageStep(viewport()->height());
69   //verticalScrollBar()->setSingleStep(20);
70   //verticalScrollBar()->setMinimum(0);
71   //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
72
73   // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
74   setMouseTracking(true);
75   mouseMode = Normal;
76   selectionMode = NoSelection;
77   connect(scrollTimer, SIGNAL(timeout()), this, SLOT(handleScrollTimer()));
78
79   if(bufferId.isValid())
80     connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(viewportChanged(int)));
81 }
82
83 ChatWidget::~ChatWidget() {
84   //qDebug() << "destroying chatwidget" << bufferName;
85   //foreach(ChatLineOld *l, lines) {
86   //  delete l;
87   //}
88   UiSettings s;
89   s.setValue("DefaultTimestampColumnWidth", tsWidth);  // FIXME stupid dirty quicky
90   s.setValue("DefaultSenderColumnWidth", senderWidth);
91   s.setValue(QString("%1/TimestampColumnWidth").arg(bufferId.toInt()), tsWidth);
92   s.setValue(QString("%1/SenderColumnWidth").arg(bufferId.toInt()), senderWidth);
93 }
94
95 QSize ChatWidget::minimumSizeHint() const {
96   return QSize(20, 20);
97 }
98
99 QSize ChatWidget::sizeHint() const {
100   return QSize(400, 100);
101 }
102
103 // QSize ChatWidget::sizeHint() const {
104 //   //qDebug() << size();
105 //   return size();
106 // }
107
108 void ChatWidget::adjustScrollBar() {
109   verticalScrollBar()->setPageStep(viewport()->height());
110   verticalScrollBar()->setSingleStep(20);
111   verticalScrollBar()->setMinimum(0);
112   verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
113   //qDebug() << height << viewport()->height() << verticalScrollBar()->pageStep();
114   //if(bottomLine < 0) {
115   //  verticalScrollBar()->setValue(verticalScrollBar()->maximum());
116   //} else {
117     //int bot = verticalScrollBar()->value() + viewport()->height(); //qDebug() << bottomLine;
118     //verticalScrollBar()->setValue(qMax(0, (int)ycoords[bottomLine+1] - viewport()->height()));
119   //}
120 }
121
122 void ChatWidget::scrollBarValChanged(int /*val*/) {
123   /*
124   if(val >= verticalScrollBar()->maximum()) bottomLine = -1;
125   else {
126     int bot = val + viewport()->height();
127     int line = yToLineIdx(bot);
128     //bottomLine = line;
129   }
130   */
131 }
132
133 void ChatWidget::scrollBarAction(int action) {
134   switch(action) {
135     case QScrollBar::SliderSingleStepAdd:
136       // More elaborate. But what with loooong lines?
137       // verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value() + viewport()->height()) + 1] - viewport()->height());
138       break;
139     case QScrollBar::SliderSingleStepSub:
140       //verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value())]);
141       break;
142
143   }
144
145 }
146
147 void ChatWidget::handleScrollTimer() {
148   if(mouseMode == MarkText || mouseMode == MarkLines) {
149     if(pointerPosition.y() > viewport()->height()) {
150       verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y() - viewport()->height());
151       handleMouseMoveEvent(QPoint(pointerPosition.x(), viewport()->height()));
152     } else if(pointerPosition.y() < 0) {
153       verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y());
154       handleMouseMoveEvent(QPoint(pointerPosition.x(), 0));
155     }
156   }
157 }
158
159 void ChatWidget::ensureVisible(int line) {
160   int top = verticalScrollBar()->value();
161   int bot = top + viewport()->height();
162   if(ycoords[line+1] > bot) {
163     verticalScrollBar()->setValue(qMax(0, (int)ycoords[line+1] - viewport()->height()));
164   } else if(ycoords[line] < top) {
165     verticalScrollBar()->setValue((int)ycoords[line]);
166   }
167
168 }
169
170 void ChatWidget::clear() {
171   //contents->clear();
172 }
173
174 void ChatWidget::prependMsg(AbstractUiMsg *msg) {
175   ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
176   Q_ASSERT(line);
177   prependChatLine(line);
178 }
179
180 void ChatWidget::prependChatLine(ChatLineOld *line) {
181   qreal h = line->layout(tsWidth, senderWidth, textWidth);
182   for(int i = 1; i < ycoords.count(); i++) ycoords[i] += h;
183   ycoords.insert(1, h);
184   lines.prepend(line);
185   height += h;
186   // Fix all variables containing line numbers
187   dragStartLine ++;
188   curLine ++;
189   selectionStart ++; selectionEnd ++;
190   adjustScrollBar();
191   verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
192   viewport()->update();
193 }
194
195 void ChatWidget::prependChatLines(QList<ChatLineOld *> clist) {
196   QList<qreal> tmpy; tmpy.append(0);
197   qreal h = 0;
198   foreach(ChatLineOld *l, clist) {
199     h += l->layout(tsWidth, senderWidth, textWidth);
200     tmpy.append(h);
201   }
202   ycoords.removeFirst();
203   for(int i = 0; i < ycoords.count(); i++) ycoords[i] += h;
204   ycoords = tmpy + ycoords;
205   lines = clist + lines;
206   height += h;
207   // Fix all variables containing line numbers
208   int i = clist.count();
209   dragStartLine += i;
210   curLine += i;
211   selectionStart += i; selectionEnd += i; //? selectionEnd += i;
212   //if(bottomLine >= 0) bottomLine += i;
213   adjustScrollBar();
214   //verticalScrollBar()->setPageStep(viewport()->height());
215   //verticalScrollBar()->setSingleStep(20);
216   //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
217   verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
218   viewport()->update();
219 }
220
221 void ChatWidget::appendMsg(AbstractUiMsg *msg) {
222   ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
223   Q_ASSERT(line);
224   appendChatLine(line);
225 }
226
227 void ChatWidget::appendChatLine(ChatLineOld *line) {
228   qreal h = line->layout(tsWidth, senderWidth, textWidth);
229   ycoords.append(h + ycoords[ycoords.count() - 1]);
230   height += h;
231   bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
232   adjustScrollBar();
233   if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
234   lines.append(line);
235   viewport()->update();
236 }
237
238
239 void ChatWidget::appendChatLines(QList<ChatLineOld *> list) {
240   foreach(ChatLineOld *line, list) {
241     qreal h = line->layout(tsWidth, senderWidth, textWidth);
242     ycoords.append(h + ycoords[ycoords.count() - 1]);
243     height += h;
244     lines.append(line);
245   }
246   bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
247   adjustScrollBar();
248   if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
249   viewport()->update();
250 }
251
252 void ChatWidget::setContents(const QList<AbstractUiMsg *> &list) {
253   ycoords.clear();
254   ycoords.append(0);
255   height = 0;
256   lines.clear();
257   QList<ChatLineOld *> cl;
258   foreach(AbstractUiMsg *msg, list) cl << dynamic_cast<ChatLineOld *>(msg);
259   appendChatLines(cl);
260 }
261
262 //!\brief Computes the different x position vars for given tsWidth and senderWidth.
263 void ChatWidget::computePositions() {
264   senderX = tsWidth + QtUi::style()->sepTsSender();
265   textX = senderX + senderWidth + QtUi::style()->sepSenderText();
266   tsGrabPos = tsWidth + (int)QtUi::style()->sepTsSender()/2;
267   senderGrabPos = senderX + senderWidth + (int)QtUi::style()->sepSenderText()/2;
268   textWidth = viewport()->size().width() - textX;
269 }
270
271 void ChatWidget::resizeEvent(QResizeEvent *event) {
272   //qDebug() << bufferName << isVisible() << event->size() << event->oldSize();
273   /*if(event->oldSize().isValid())*/
274   //contents->setWidth(event->size().width());
275   //setAlignment(Qt::AlignBottom);
276   if(event->size() != event->oldSize()) {
277     computePositions();
278     layout();
279   }
280   //adjustScrollBar();
281   //qDebug() << viewport()->size() << viewport()->height();
282   //QAbstractScrollArea::resizeEvent(event);
283   //qDebug() << viewport()->size() << viewport()->geometry();
284 }
285
286 void ChatWidget::paintEvent(QPaintEvent *event) {
287   QPainter painter(viewport());
288
289   //qDebug() <<  verticalScrollBar()->value();
290   painter.translate(0, -verticalScrollBar()->value());
291   int top = event->rect().top() + verticalScrollBar()->value();
292   int bot = top + event->rect().height();
293   int idx = yToLineIdx(top);
294   if(idx < 0) return;
295   for(int i = idx; i < lines.count() ; i++) {
296     lines[i]->draw(&painter, QPointF(0, ycoords[i]));
297     if(ycoords[i+1] > bot) return;
298   }
299 }
300
301 //!\brief Layout the widget.
302 void ChatWidget::layout() {
303   // TODO fix scrollbars
304   //int botLine = yToLineIdx(verticalScrollBar()->value() + 
305   for(int i = 0; i < lines.count(); i++) {
306     qreal h = lines[i]->layout(tsWidth, senderWidth, textWidth);
307     ycoords[i+1] = h + ycoords[i];
308   }
309   height = ycoords[ycoords.count()-1];
310   adjustScrollBar();
311   verticalScrollBar()->setValue(verticalScrollBar()->maximum());
312   viewport()->update();
313 }
314
315 int ChatWidget::yToLineIdx(qreal y) {
316   if(y >= ycoords[ycoords.count()-1]) return ycoords.count()-2;
317   if(ycoords.count() <= 1) return 0;
318   int uidx = 0;
319   int oidx = ycoords.count() - 1;
320   int idx;
321   while(1) {
322     if(uidx == oidx - 1) return uidx;
323     idx = (uidx + oidx) / 2;
324     if(ycoords[idx] > y) oidx = idx;
325     else uidx = idx;
326   }
327 }
328
329 void ChatWidget::mousePressEvent(QMouseEvent *event) {
330   if(lines.isEmpty()) return;
331   QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
332   if(event->button() == Qt::LeftButton) {
333     dragStartPos = pos;
334     dragStartMode = Normal;
335     switch(mouseMode) {
336       case Normal:
337         if(mousePos == OverTsSep) {
338           dragStartMode = DragTsSep;
339           setCursor(Qt::ClosedHandCursor);
340         } else if(mousePos == OverTextSep) {
341           dragStartMode = DragTextSep;
342           setCursor(Qt::ClosedHandCursor);
343         } else {
344           dragStartLine = yToLineIdx(pos.y());
345           dragStartCursor = lines[dragStartLine]->posToCursor(QPointF(pos.x(), pos.y()-ycoords[dragStartLine]));
346         }
347         mouseMode = Pressed;
348         break;
349       default:
350         break;
351     }
352   }
353 }
354
355 void ChatWidget::mouseDoubleClickEvent(QMouseEvent *event) {
356   // dirty and fast hack to make http:// urls klickable
357   if(lines.isEmpty())
358     return;
359
360   QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
361   int x = pos.x();
362   int y = pos.y();
363   int l = yToLineIdx(y);
364   if(lines.count() <= l)
365     return;
366
367   ChatLineOld *line = lines[l];
368   QString text = line->text();
369   int cursorAt = qMax(0, line->posToCursor(QPointF(x, y - ycoords[l])) - 1);
370
371   int start = 0;
372   if(cursorAt > 0) {
373     for(int i = cursorAt; i > 0; i--) {
374       if(text[i] == ' ') {
375         start = i + 1;
376         break;
377       }
378     }
379   }
380
381   int end = text.indexOf(" ", start);
382   int len = -1;
383   if(end != -1) {
384     len = end - start;
385   }
386   QString word = text.mid(start, len);
387   QRegExp regex("^(h|f)t{1,2}ps?:\\/\\/");
388   if(regex.indexIn(word) != -1) {
389     QDesktopServices::openUrl(QUrl(word));
390   }
391   
392 }
393
394 void ChatWidget::mouseReleaseEvent(QMouseEvent *event) {
395   //QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
396
397   if(event->button() == Qt::LeftButton) {
398     dragStartPos = QPoint();
399     if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
400     else setCursor(Qt::ArrowCursor);
401
402     switch(mouseMode) {
403       case Pressed:
404         mouseMode = Normal;
405         clearSelection();
406         break;
407       case MarkText:
408         mouseMode = Normal;
409         selectionMode = TextSelected;
410         selectionLine = dragStartLine;
411         selectionStart = qMin(dragStartCursor, curCursor);
412         selectionEnd = qMax(dragStartCursor, curCursor);
413         // TODO Make X11SelectionMode configurable!
414 #ifdef Q_WS_X11
415         QApplication::clipboard()->setText(selectionToString(), QClipboard::Selection);
416 #else
417         QApplication::clipboard()->setText(selectionToString());
418 #endif
419         break;
420       case MarkLines:
421         mouseMode = Normal;
422         selectionMode = LinesSelected;
423         selectionStart = qMin(dragStartLine, curLine);
424         selectionEnd = qMax(dragStartLine, curLine);
425         // TODO Make X11SelectionMode configurable!
426         QApplication::clipboard()->setText(selectionToString());
427         break;
428       default:
429         mouseMode = Normal;
430     }
431   }
432 }
433
434 //!\brief React to mouse movements over the ChatWidget.
435 /** This is called by Qt whenever the mouse moves. Here we have to do most of the mouse handling,
436  * such as changing column widths, marking text or initiating drag & drop.
437  */
438 void ChatWidget::mouseMoveEvent(QMouseEvent *event) {
439   QPoint pos = event->pos(); pointerPosition = pos;
440   // Scroll if mouse pointer leaves widget while dragging
441   if((mouseMode == MarkText || mouseMode == MarkLines) && (pos.y() > viewport()->height() || pos.y() < 0)) {
442     if(!scrollTimer->isActive()) {
443       scrollTimer->start();
444     }
445   } else {
446     if(scrollTimer->isActive()) {
447       scrollTimer->stop();
448     }
449   }
450   handleMouseMoveEvent(pos);
451 }
452
453 void ChatWidget::handleMouseMoveEvent(const QPoint &_pos) {
454   // FIXME
455   if(lines.count() <= 0) return;
456   // Set some basic properties of the current position
457   QPoint pos = _pos + QPoint(0, verticalScrollBar()->value());
458   int x = pos.x();
459   int y = pos.y();
460   //MousePos oldpos = mousePos;
461   if(x >= tsGrabPos - 3 && x <= tsGrabPos + 3) mousePos = OverTsSep;
462   else if(x >= senderGrabPos - 3 && x <= senderGrabPos + 3) mousePos = OverTextSep;
463   else mousePos = None;
464
465   // Pass 1: Do whatever we can before switching mouse mode (if at all).
466   switch(mouseMode) {
467     // No special mode. Set mouse cursor if appropriate.
468     case Normal:
469     {
470       //if(oldpos != mousePos) {
471       if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
472       else {
473         int l = yToLineIdx(y);
474         int c = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
475         if(c >= 0 && lines[l]->isUrl(c)) {
476           setCursor(Qt::PointingHandCursor);
477         } else {
478           setCursor(Qt::ArrowCursor);
479         }
480       }
481     }
482       break;
483     // Left button pressed. Might initiate marking or drag & drop if we moved past the drag distance.
484     case Pressed:
485       if(!dragStartPos.isNull() && (dragStartPos - pos).manhattanLength() >= QApplication::startDragDistance()) {
486         // Moving a column separator?
487         if(dragStartMode == DragTsSep) mouseMode = DragTsSep;
488         else if(dragStartMode == DragTextSep) mouseMode = DragTextSep;
489         // Nope. Check if we are over a selection to start drag & drop.
490         else if(dragStartMode == Normal) {
491           bool dragdrop = false;
492           if(selectionMode == TextSelected) {
493             int l = yToLineIdx(y);
494             if(selectionLine == l) {
495               int p = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
496               if(p >= selectionStart && p <= selectionEnd) dragdrop = true;
497             }
498           } else if(selectionMode == LinesSelected) {
499             int l = yToLineIdx(y);
500             if(l >= selectionStart && l <= selectionEnd) dragdrop = true;
501           }
502           // Ok, so just start drag & drop if appropriate.
503           if(dragdrop) {
504             QDrag *drag = new QDrag(this);
505             QMimeData *mimeData = new QMimeData;
506             mimeData->setText(selectionToString());
507             drag->setMimeData(mimeData);
508             drag->start();
509             mouseMode = Normal;
510           // Otherwise, clear the selection and start text marking!
511           } else {
512             setCursor(Qt::ArrowCursor);
513             clearSelection();
514             if(dragStartCursor < 0) { mouseMode = MarkLines; curLine = -1; }
515             else mouseMode = MarkText;
516           }
517         }
518       }
519       break;
520     case DragTsSep:
521       break;
522     case DragTextSep:
523       break;
524     default:
525       break;
526   }
527   // Pass 2: Some mouse modes need work after being set...
528   if(mouseMode == DragTsSep && x < size().width() - QtUi::style()->sepSenderText() - senderWidth - 10) {
529     // Drag first column separator
530     int foo = QtUi::style()->sepTsSender()/2;
531     tsWidth = qMax(x, foo) - foo;
532     computePositions();
533     layout();
534   } else if(mouseMode == DragTextSep && x < size().width() - 10) {
535     // Drag second column separator
536     int foo = tsWidth + QtUi::style()->sepTsSender() + QtUi::style()->sepSenderText()/2;
537     senderWidth = qMax(x, foo) - foo;
538     computePositions();
539     layout();
540   } else if(mouseMode == MarkText) {
541     // Change currently marked text
542     curLine = yToLineIdx(y);
543     int c = lines[curLine]->posToCursor(QPointF(x, y - ycoords[curLine]));
544     if(curLine == dragStartLine && c >= 0) {
545       if(c != curCursor) {
546         curCursor = c;
547         lines[curLine]->setSelection(ChatLineOld::Partial, dragStartCursor, c);
548         viewport()->update();
549       }
550     } else {
551       mouseMode = MarkLines;
552       selectionStart = qMin(curLine, dragStartLine); selectionEnd = qMax(curLine, dragStartLine);
553       for(int i = selectionStart; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
554       viewport()->update();
555     }
556   } else if(mouseMode == MarkLines) {
557     // Line marking
558     int l = yToLineIdx(y);
559     if(l != curLine) {
560       selectionStart = qMin(l, dragStartLine); selectionEnd = qMax(l, dragStartLine);
561       if(curLine < 0) {
562         Q_ASSERT(selectionStart == selectionEnd);
563         lines[l]->setSelection(ChatLineOld::Full);
564       } else {
565         if(curLine < selectionStart) {
566           for(int i = curLine; i < selectionStart; i++) lines[i]->setSelection(ChatLineOld::None);
567         } else if(curLine > selectionEnd) {
568           for(int i = selectionEnd+1; i <= curLine; i++) lines[i]->setSelection(ChatLineOld::None);
569         } else if(selectionStart < curLine && l < curLine) {
570           for(int i = selectionStart; i < curLine; i++) lines[i]->setSelection(ChatLineOld::Full);
571         } else if(curLine < selectionEnd && l > curLine) {
572           for(int i = curLine+1; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
573         }
574       }
575       curLine = l;
576       //ensureVisible(l);
577       viewport()->update();
578     }
579   }
580 }
581
582 //!\brief Clear current text selection.
583 void ChatWidget::clearSelection() {
584   if(selectionMode == TextSelected) {
585     lines[selectionLine]->setSelection(ChatLineOld::None);
586   } else if(selectionMode == LinesSelected) {
587     for(int i = selectionStart; i <= selectionEnd; i++) {
588       lines[i]->setSelection(ChatLineOld::None);
589     }
590   }
591   selectionMode = NoSelection;
592   viewport()->update();
593 }
594
595 //!\brief Convert current selection to human-readable string.
596 QString ChatWidget::selectionToString() {
597   //TODO Make selection format configurable!
598   if(selectionMode == NoSelection) return "";
599   if(selectionMode == LinesSelected) {
600     QString result;
601     for(int l = selectionStart; l <= selectionEnd; l++) {
602       result += QString("[%1] %2 %3\n").arg(lines[l]->timestamp().toLocalTime().toString("hh:mm:ss"))
603   .        arg(lines[l]->sender()).arg(lines[l]->text());
604     }
605     return result;
606   }
607   // selectionMode == TextSelected
608   return lines[selectionLine]->text().mid(selectionStart, selectionEnd - selectionStart);
609 }
610
611 void ChatWidget::viewportChanged(int newPos) {
612   const int REQUEST_COUNT = 50;
613   QAbstractSlider *vbar = verticalScrollBar();
614   if(!vbar)
615     return;
616
617   int relativePos = 100;
618   if(vbar->maximum() - vbar->minimum() != 0)
619     relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
620
621   if(relativePos < 20) {
622     Buffer *buffer = Client::buffer(bufferId);
623     Q_CHECK_PTR(buffer);
624     if(buffer->contents().isEmpty())
625       return;
626     MsgId msgId = buffer->contents().first()->msgId();
627     if(!lastBacklogOffset.isValid() || msgId < lastBacklogOffset && lastBacklogSize + REQUEST_COUNT <= buffer->contents().count()) {
628       Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
629       lastBacklogOffset = msgId;
630       lastBacklogSize = buffer->contents().size();
631     }
632   }
633 }