1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
22 #include "chatwidget.h"
23 #include "chatline-old.h"
25 #include "uisettings.h"
28 #include "clientbacklogmanager.h"
30 ChatWidget::ChatWidget(QWidget *parent)
31 : QAbstractScrollArea(parent),
35 //setAutoFillBackground(false);
37 //palette.setColor(backgroundRole(), QColor(0, 0, 0, 50));
38 //setPalette(palette);
39 scrollTimer = new QTimer(this);
40 scrollTimer->setSingleShot(false);
41 scrollTimer->setInterval(100);
42 // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
43 setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
44 setMinimumSize(QSize(20,20));
45 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
46 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
50 pointerPosition = QPoint(0,0);
51 connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(scrollBarAction(int)));
52 connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(scrollBarValChanged(int)));
55 void ChatWidget::init(BufferId id) {
57 setBackgroundRole(QPalette::Base);
58 setFont(QFont("Fixed"));
60 QVariant tsDef = s.value("DefaultTimestampColumnWidth", 90);
61 QVariant senderDef = s.value("DefaultSenderColumnWidth", 100);
62 tsWidth = s.value(QString("%1/TimestampColumnWidth").arg(bufferId.toInt()), tsDef).toInt();
63 senderWidth = s.value(QString("%1/SenderColumnWidth").arg(bufferId.toInt()), senderDef).toInt();
66 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
67 //verticalScrollBar()->setPageStep(viewport()->height());
68 //verticalScrollBar()->setSingleStep(20);
69 //verticalScrollBar()->setMinimum(0);
70 //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
72 // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
73 setMouseTracking(true);
75 selectionMode = NoSelection;
76 connect(scrollTimer, SIGNAL(timeout()), this, SLOT(handleScrollTimer()));
78 if(bufferId.isValid())
79 connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(viewportChanged(int)));
82 ChatWidget::~ChatWidget() {
83 //qDebug() << "destroying chatwidget" << bufferName;
84 //foreach(ChatLineOld *l, lines) {
88 s.setValue("DefaultTimestampColumnWidth", tsWidth); // FIXME stupid dirty quicky
89 s.setValue("DefaultSenderColumnWidth", senderWidth);
90 s.setValue(QString("%1/TimestampColumnWidth").arg(bufferId.toInt()), tsWidth);
91 s.setValue(QString("%1/SenderColumnWidth").arg(bufferId.toInt()), senderWidth);
94 QSize ChatWidget::minimumSizeHint() const {
98 QSize ChatWidget::sizeHint() const {
99 return QSize(400, 100);
102 // QSize ChatWidget::sizeHint() const {
103 // //qDebug() << size();
107 void ChatWidget::adjustScrollBar() {
108 verticalScrollBar()->setPageStep(viewport()->height());
109 verticalScrollBar()->setSingleStep(20);
110 verticalScrollBar()->setMinimum(0);
111 verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
112 //qDebug() << height << viewport()->height() << verticalScrollBar()->pageStep();
113 //if(bottomLine < 0) {
114 // verticalScrollBar()->setValue(verticalScrollBar()->maximum());
116 //int bot = verticalScrollBar()->value() + viewport()->height(); //qDebug() << bottomLine;
117 //verticalScrollBar()->setValue(qMax(0, (int)ycoords[bottomLine+1] - viewport()->height()));
121 void ChatWidget::scrollBarValChanged(int /*val*/) {
123 if(val >= verticalScrollBar()->maximum()) bottomLine = -1;
125 int bot = val + viewport()->height();
126 int line = yToLineIdx(bot);
132 void ChatWidget::scrollBarAction(int action) {
134 case QScrollBar::SliderSingleStepAdd:
135 // More elaborate. But what with loooong lines?
136 // verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value() + viewport()->height()) + 1] - viewport()->height());
138 case QScrollBar::SliderSingleStepSub:
139 //verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value())]);
146 void ChatWidget::handleScrollTimer() {
147 if(mouseMode == MarkText || mouseMode == MarkLines) {
148 if(pointerPosition.y() > viewport()->height()) {
149 verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y() - viewport()->height());
150 handleMouseMoveEvent(QPoint(pointerPosition.x(), viewport()->height()));
151 } else if(pointerPosition.y() < 0) {
152 verticalScrollBar()->setValue(verticalScrollBar()->value() + pointerPosition.y());
153 handleMouseMoveEvent(QPoint(pointerPosition.x(), 0));
158 void ChatWidget::ensureVisible(int line) {
159 int top = verticalScrollBar()->value();
160 int bot = top + viewport()->height();
161 if(ycoords[line+1] > bot) {
162 verticalScrollBar()->setValue(qMax(0, (int)ycoords[line+1] - viewport()->height()));
163 } else if(ycoords[line] < top) {
164 verticalScrollBar()->setValue((int)ycoords[line]);
169 void ChatWidget::clear() {
173 void ChatWidget::prependMsg(AbstractUiMsg *msg) {
174 ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
176 prependChatLine(line);
179 void ChatWidget::prependChatLine(ChatLineOld *line) {
180 qreal h = line->layout(tsWidth, senderWidth, textWidth);
181 for(int i = 1; i < ycoords.count(); i++) ycoords[i] += h;
182 ycoords.insert(1, h);
185 // Fix all variables containing line numbers
188 selectionStart ++; selectionEnd ++;
190 verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
191 viewport()->update();
194 void ChatWidget::prependChatLines(QList<ChatLineOld *> clist) {
195 QList<qreal> tmpy; tmpy.append(0);
197 foreach(ChatLineOld *l, clist) {
198 h += l->layout(tsWidth, senderWidth, textWidth);
201 ycoords.removeFirst();
202 for(int i = 0; i < ycoords.count(); i++) ycoords[i] += h;
203 ycoords = tmpy + ycoords;
204 lines = clist + lines;
206 // Fix all variables containing line numbers
207 int i = clist.count();
210 selectionStart += i; selectionEnd += i; //? selectionEnd += i;
211 //if(bottomLine >= 0) bottomLine += i;
213 //verticalScrollBar()->setPageStep(viewport()->height());
214 //verticalScrollBar()->setSingleStep(20);
215 //verticalScrollBar()->setMaximum((int)height - verticalScrollBar()->pageStep());
216 verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
217 viewport()->update();
220 void ChatWidget::appendMsg(AbstractUiMsg *msg) {
221 ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
223 appendChatLine(line);
226 void ChatWidget::appendChatLine(ChatLineOld *line) {
227 qreal h = line->layout(tsWidth, senderWidth, textWidth);
228 ycoords.append(h + ycoords[ycoords.count() - 1]);
230 bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
232 if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
234 viewport()->update();
238 void ChatWidget::appendChatLines(QList<ChatLineOld *> list) {
239 foreach(ChatLineOld *line, list) {
240 qreal h = line->layout(tsWidth, senderWidth, textWidth);
241 ycoords.append(h + ycoords[ycoords.count() - 1]);
245 bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
247 if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
248 viewport()->update();
251 void ChatWidget::setContents(QList<ChatLineOld *> list) {
256 appendChatLines(list);
259 //!\brief Computes the different x position vars for given tsWidth and senderWidth.
260 void ChatWidget::computePositions() {
261 senderX = tsWidth + QtUi::style()->sepTsSender();
262 textX = senderX + senderWidth + QtUi::style()->sepSenderText();
263 tsGrabPos = tsWidth + (int)QtUi::style()->sepTsSender()/2;
264 senderGrabPos = senderX + senderWidth + (int)QtUi::style()->sepSenderText()/2;
265 textWidth = viewport()->size().width() - textX;
268 void ChatWidget::resizeEvent(QResizeEvent *event) {
269 //qDebug() << bufferName << isVisible() << event->size() << event->oldSize();
270 /*if(event->oldSize().isValid())*/
271 //contents->setWidth(event->size().width());
272 //setAlignment(Qt::AlignBottom);
273 if(event->size() != event->oldSize()) {
278 //qDebug() << viewport()->size() << viewport()->height();
279 //QAbstractScrollArea::resizeEvent(event);
280 //qDebug() << viewport()->size() << viewport()->geometry();
283 void ChatWidget::paintEvent(QPaintEvent *event) {
284 QPainter painter(viewport());
286 //qDebug() << verticalScrollBar()->value();
287 painter.translate(0, -verticalScrollBar()->value());
288 int top = event->rect().top() + verticalScrollBar()->value();
289 int bot = top + event->rect().height();
290 int idx = yToLineIdx(top);
292 for(int i = idx; i < lines.count() ; i++) {
293 lines[i]->draw(&painter, QPointF(0, ycoords[i]));
294 if(ycoords[i+1] > bot) return;
298 //!\brief Layout the widget.
299 void ChatWidget::layout() {
300 // TODO fix scrollbars
301 //int botLine = yToLineIdx(verticalScrollBar()->value() +
302 for(int i = 0; i < lines.count(); i++) {
303 qreal h = lines[i]->layout(tsWidth, senderWidth, textWidth);
304 ycoords[i+1] = h + ycoords[i];
306 height = ycoords[ycoords.count()-1];
308 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
309 viewport()->update();
312 int ChatWidget::yToLineIdx(qreal y) {
313 if(y >= ycoords[ycoords.count()-1]) return ycoords.count()-2;
314 if(ycoords.count() <= 1) return 0;
316 int oidx = ycoords.count() - 1;
319 if(uidx == oidx - 1) return uidx;
320 idx = (uidx + oidx) / 2;
321 if(ycoords[idx] > y) oidx = idx;
326 void ChatWidget::mousePressEvent(QMouseEvent *event) {
327 if(lines.isEmpty()) return;
328 QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
329 if(event->button() == Qt::LeftButton) {
331 dragStartMode = Normal;
334 if(mousePos == OverTsSep) {
335 dragStartMode = DragTsSep;
336 setCursor(Qt::ClosedHandCursor);
337 } else if(mousePos == OverTextSep) {
338 dragStartMode = DragTextSep;
339 setCursor(Qt::ClosedHandCursor);
341 dragStartLine = yToLineIdx(pos.y());
342 dragStartCursor = lines[dragStartLine]->posToCursor(QPointF(pos.x(), pos.y()-ycoords[dragStartLine]));
352 void ChatWidget::mouseDoubleClickEvent(QMouseEvent *event) {
353 // dirty and fast hack to make http:// urls klickable
357 QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
360 int l = yToLineIdx(y);
361 if(lines.count() <= l)
364 ChatLineOld *line = lines[l];
365 QString text = line->text();
366 int cursorAt = qMax(0, line->posToCursor(QPointF(x, y - ycoords[l])) - 1);
370 for(int i = cursorAt; i > 0; i--) {
378 int end = text.indexOf(" ", start);
383 QString word = text.mid(start, len);
384 if(word.startsWith("http://")) {
385 QDesktopServices::openUrl(QUrl(word));
390 void ChatWidget::mouseReleaseEvent(QMouseEvent *event) {
391 //QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
393 if(event->button() == Qt::LeftButton) {
394 dragStartPos = QPoint();
395 if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
396 else setCursor(Qt::ArrowCursor);
405 selectionMode = TextSelected;
406 selectionLine = dragStartLine;
407 selectionStart = qMin(dragStartCursor, curCursor);
408 selectionEnd = qMax(dragStartCursor, curCursor);
409 // TODO Make X11SelectionMode configurable!
410 QApplication::clipboard()->setText(selectionToString());
414 selectionMode = LinesSelected;
415 selectionStart = qMin(dragStartLine, curLine);
416 selectionEnd = qMax(dragStartLine, curLine);
417 // TODO Make X11SelectionMode configurable!
418 QApplication::clipboard()->setText(selectionToString());
426 //!\brief React to mouse movements over the ChatWidget.
427 /** This is called by Qt whenever the mouse moves. Here we have to do most of the mouse handling,
428 * such as changing column widths, marking text or initiating drag & drop.
430 void ChatWidget::mouseMoveEvent(QMouseEvent *event) {
431 QPoint pos = event->pos(); pointerPosition = pos;
432 // Scroll if mouse pointer leaves widget while dragging
433 if((mouseMode == MarkText || mouseMode == MarkLines) && (pos.y() > viewport()->height() || pos.y() < 0)) {
434 if(!scrollTimer->isActive()) {
435 scrollTimer->start();
438 if(scrollTimer->isActive()) {
442 handleMouseMoveEvent(pos);
445 void ChatWidget::handleMouseMoveEvent(const QPoint &_pos) {
447 if(lines.count() <= 0) return;
448 // Set some basic properties of the current position
449 QPoint pos = _pos + QPoint(0, verticalScrollBar()->value());
452 //MousePos oldpos = mousePos;
453 if(x >= tsGrabPos - 3 && x <= tsGrabPos + 3) mousePos = OverTsSep;
454 else if(x >= senderGrabPos - 3 && x <= senderGrabPos + 3) mousePos = OverTextSep;
455 else mousePos = None;
457 // Pass 1: Do whatever we can before switching mouse mode (if at all).
459 // No special mode. Set mouse cursor if appropriate.
462 //if(oldpos != mousePos) {
463 if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
465 int l = yToLineIdx(y);
466 int c = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
467 if(c >= 0 && lines[l]->isUrl(c)) {
468 setCursor(Qt::PointingHandCursor);
470 setCursor(Qt::ArrowCursor);
475 // Left button pressed. Might initiate marking or drag & drop if we moved past the drag distance.
477 if(!dragStartPos.isNull() && (dragStartPos - pos).manhattanLength() >= QApplication::startDragDistance()) {
478 // Moving a column separator?
479 if(dragStartMode == DragTsSep) mouseMode = DragTsSep;
480 else if(dragStartMode == DragTextSep) mouseMode = DragTextSep;
481 // Nope. Check if we are over a selection to start drag & drop.
482 else if(dragStartMode == Normal) {
483 bool dragdrop = false;
484 if(selectionMode == TextSelected) {
485 int l = yToLineIdx(y);
486 if(selectionLine == l) {
487 int p = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
488 if(p >= selectionStart && p <= selectionEnd) dragdrop = true;
490 } else if(selectionMode == LinesSelected) {
491 int l = yToLineIdx(y);
492 if(l >= selectionStart && l <= selectionEnd) dragdrop = true;
494 // Ok, so just start drag & drop if appropriate.
496 QDrag *drag = new QDrag(this);
497 QMimeData *mimeData = new QMimeData;
498 mimeData->setText(selectionToString());
499 drag->setMimeData(mimeData);
502 // Otherwise, clear the selection and start text marking!
504 setCursor(Qt::ArrowCursor);
506 if(dragStartCursor < 0) { mouseMode = MarkLines; curLine = -1; }
507 else mouseMode = MarkText;
519 // Pass 2: Some mouse modes need work after being set...
520 if(mouseMode == DragTsSep && x < size().width() - QtUi::style()->sepSenderText() - senderWidth - 10) {
521 // Drag first column separator
522 int foo = QtUi::style()->sepTsSender()/2;
523 tsWidth = qMax(x, foo) - foo;
526 } else if(mouseMode == DragTextSep && x < size().width() - 10) {
527 // Drag second column separator
528 int foo = tsWidth + QtUi::style()->sepTsSender() + QtUi::style()->sepSenderText()/2;
529 senderWidth = qMax(x, foo) - foo;
532 } else if(mouseMode == MarkText) {
533 // Change currently marked text
534 curLine = yToLineIdx(y);
535 int c = lines[curLine]->posToCursor(QPointF(x, y - ycoords[curLine]));
536 if(curLine == dragStartLine && c >= 0) {
539 lines[curLine]->setSelection(ChatLineOld::Partial, dragStartCursor, c);
540 viewport()->update();
543 mouseMode = MarkLines;
544 selectionStart = qMin(curLine, dragStartLine); selectionEnd = qMax(curLine, dragStartLine);
545 for(int i = selectionStart; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
546 viewport()->update();
548 } else if(mouseMode == MarkLines) {
550 int l = yToLineIdx(y);
552 selectionStart = qMin(l, dragStartLine); selectionEnd = qMax(l, dragStartLine);
554 Q_ASSERT(selectionStart == selectionEnd);
555 lines[l]->setSelection(ChatLineOld::Full);
557 if(curLine < selectionStart) {
558 for(int i = curLine; i < selectionStart; i++) lines[i]->setSelection(ChatLineOld::None);
559 } else if(curLine > selectionEnd) {
560 for(int i = selectionEnd+1; i <= curLine; i++) lines[i]->setSelection(ChatLineOld::None);
561 } else if(selectionStart < curLine && l < curLine) {
562 for(int i = selectionStart; i < curLine; i++) lines[i]->setSelection(ChatLineOld::Full);
563 } else if(curLine < selectionEnd && l > curLine) {
564 for(int i = curLine+1; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
569 viewport()->update();
574 //!\brief Clear current text selection.
575 void ChatWidget::clearSelection() {
576 if(selectionMode == TextSelected) {
577 lines[selectionLine]->setSelection(ChatLineOld::None);
578 } else if(selectionMode == LinesSelected) {
579 for(int i = selectionStart; i <= selectionEnd; i++) {
580 lines[i]->setSelection(ChatLineOld::None);
583 selectionMode = NoSelection;
584 viewport()->update();
587 //!\brief Convert current selection to human-readable string.
588 QString ChatWidget::selectionToString() {
589 //TODO Make selection format configurable!
590 if(selectionMode == NoSelection) return "";
591 if(selectionMode == LinesSelected) {
593 for(int l = selectionStart; l <= selectionEnd; l++) {
594 result += QString("[%1] %2 %3\n").arg(lines[l]->timestamp().toLocalTime().toString("hh:mm:ss"))
595 . arg(lines[l]->sender()).arg(lines[l]->text());
599 // selectionMode == TextSelected
600 return lines[selectionLine]->text().mid(selectionStart, selectionEnd - selectionStart);
603 void ChatWidget::viewportChanged(int newPos) {
604 const int REQUEST_COUNT = 50;
605 QAbstractSlider *vbar = verticalScrollBar();
609 int relativePos = 100;
610 if(vbar->maximum() - vbar->minimum() != 0)
611 relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
613 if(relativePos < 20) {
614 Buffer *buffer = Client::buffer(bufferId);
616 if(buffer->contents().isEmpty())
618 MsgId msgId = buffer->contents().first()->msgId();
619 if(!lastBacklogOffset.isValid() || msgId < lastBacklogOffset && lastBacklogSize + REQUEST_COUNT <= buffer->contents().count()) {
620 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
621 lastBacklogOffset = msgId;
622 lastBacklogSize = buffer->contents().size();