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(BufferId bufid, QWidget *parent) : QAbstractScrollArea(parent), AbstractChatView(),
34 //setAutoFillBackground(false);
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);
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)));
56 void ChatWidget::init(BufferId id) {
58 setBackgroundRole(QPalette::Base);
59 setFont(QFont("Fixed"));
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();
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());
73 // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
74 setMouseTracking(true);
76 selectionMode = NoSelection;
77 connect(scrollTimer, SIGNAL(timeout()), this, SLOT(handleScrollTimer()));
79 if(bufferId.isValid())
80 connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(viewportChanged(int)));
83 ChatWidget::~ChatWidget() {
84 //qDebug() << "destroying chatwidget" << bufferName;
85 //foreach(ChatLineOld *l, lines) {
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);
95 QSize ChatWidget::minimumSizeHint() const {
99 QSize ChatWidget::sizeHint() const {
100 return QSize(400, 100);
103 // QSize ChatWidget::sizeHint() const {
104 // //qDebug() << size();
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());
117 //int bot = verticalScrollBar()->value() + viewport()->height(); //qDebug() << bottomLine;
118 //verticalScrollBar()->setValue(qMax(0, (int)ycoords[bottomLine+1] - viewport()->height()));
122 void ChatWidget::scrollBarValChanged(int /*val*/) {
124 if(val >= verticalScrollBar()->maximum()) bottomLine = -1;
126 int bot = val + viewport()->height();
127 int line = yToLineIdx(bot);
133 void ChatWidget::scrollBarAction(int 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());
139 case QScrollBar::SliderSingleStepSub:
140 //verticalScrollBar()->setValue((int)ycoords[yToLineIdx(verticalScrollBar()->value())]);
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));
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]);
170 void ChatWidget::clear() {
174 void ChatWidget::prependMsg(AbstractUiMsg *msg) {
175 ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
177 prependChatLine(line);
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);
186 // Fix all variables containing line numbers
189 selectionStart ++; selectionEnd ++;
191 verticalScrollBar()->setValue(verticalScrollBar()->value() + (int)h);
192 viewport()->update();
195 void ChatWidget::prependChatLines(QList<ChatLineOld *> clist) {
196 QList<qreal> tmpy; tmpy.append(0);
198 foreach(ChatLineOld *l, clist) {
199 h += l->layout(tsWidth, senderWidth, textWidth);
202 ycoords.removeFirst();
203 for(int i = 0; i < ycoords.count(); i++) ycoords[i] += h;
204 ycoords = tmpy + ycoords;
205 lines = clist + lines;
207 // Fix all variables containing line numbers
208 int i = clist.count();
211 selectionStart += i; selectionEnd += i; //? selectionEnd += i;
212 //if(bottomLine >= 0) bottomLine += i;
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();
221 void ChatWidget::appendMsg(AbstractUiMsg *msg) {
222 ChatLineOld *line = dynamic_cast<ChatLineOld*>(msg);
224 appendChatLine(line);
227 void ChatWidget::appendChatLine(ChatLineOld *line) {
228 qreal h = line->layout(tsWidth, senderWidth, textWidth);
229 ycoords.append(h + ycoords[ycoords.count() - 1]);
231 bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
233 if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
235 viewport()->update();
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]);
246 bool flg = (verticalScrollBar()->value() == verticalScrollBar()->maximum());
248 if(flg) verticalScrollBar()->setValue(verticalScrollBar()->maximum());
249 viewport()->update();
252 void ChatWidget::setContents(const QList<AbstractUiMsg *> &list) {
257 QList<ChatLineOld *> cl;
258 foreach(AbstractUiMsg *msg, list) cl << dynamic_cast<ChatLineOld *>(msg);
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;
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()) {
281 //qDebug() << viewport()->size() << viewport()->height();
282 //QAbstractScrollArea::resizeEvent(event);
283 //qDebug() << viewport()->size() << viewport()->geometry();
286 void ChatWidget::paintEvent(QPaintEvent *event) {
287 QPainter painter(viewport());
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);
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;
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];
309 height = ycoords[ycoords.count()-1];
311 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
312 viewport()->update();
315 int ChatWidget::yToLineIdx(qreal y) {
316 if(y >= ycoords[ycoords.count()-1]) return ycoords.count()-2;
317 if(ycoords.count() <= 1) return 0;
319 int oidx = ycoords.count() - 1;
322 if(uidx == oidx - 1) return uidx;
323 idx = (uidx + oidx) / 2;
324 if(ycoords[idx] > y) oidx = idx;
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) {
334 dragStartMode = Normal;
337 if(mousePos == OverTsSep) {
338 dragStartMode = DragTsSep;
339 setCursor(Qt::ClosedHandCursor);
340 } else if(mousePos == OverTextSep) {
341 dragStartMode = DragTextSep;
342 setCursor(Qt::ClosedHandCursor);
344 dragStartLine = yToLineIdx(pos.y());
345 dragStartCursor = lines[dragStartLine]->posToCursor(QPointF(pos.x(), pos.y()-ycoords[dragStartLine]));
355 void ChatWidget::mouseDoubleClickEvent(QMouseEvent *event) {
356 // dirty and fast hack to make http:// urls klickable
360 QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
363 int l = yToLineIdx(y);
364 if(lines.count() <= l)
367 ChatLineOld *line = lines[l];
368 QString text = line->text();
369 int cursorAt = qMax(0, line->posToCursor(QPointF(x, y - ycoords[l])) - 1);
373 for(int i = cursorAt; i > 0; i--) {
381 int end = text.indexOf(" ", start);
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));
394 void ChatWidget::mouseReleaseEvent(QMouseEvent *event) {
395 //QPoint pos = event->pos() + QPoint(0, verticalScrollBar()->value());
397 if(event->button() == Qt::LeftButton) {
398 dragStartPos = QPoint();
399 if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
400 else setCursor(Qt::ArrowCursor);
409 selectionMode = TextSelected;
410 selectionLine = dragStartLine;
411 selectionStart = qMin(dragStartCursor, curCursor);
412 selectionEnd = qMax(dragStartCursor, curCursor);
413 // TODO Make X11SelectionMode configurable!
415 QApplication::clipboard()->setText(selectionToString(), QClipboard::Selection);
417 QApplication::clipboard()->setText(selectionToString());
422 selectionMode = LinesSelected;
423 selectionStart = qMin(dragStartLine, curLine);
424 selectionEnd = qMax(dragStartLine, curLine);
425 // TODO Make X11SelectionMode configurable!
427 QApplication::clipboard()->setText(selectionToString(), QClipboard::Selection);
429 QApplication::clipboard()->setText(selectionToString());
438 //!\brief React to mouse movements over the ChatWidget.
439 /** This is called by Qt whenever the mouse moves. Here we have to do most of the mouse handling,
440 * such as changing column widths, marking text or initiating drag & drop.
442 void ChatWidget::mouseMoveEvent(QMouseEvent *event) {
443 QPoint pos = event->pos(); pointerPosition = pos;
444 // Scroll if mouse pointer leaves widget while dragging
445 if((mouseMode == MarkText || mouseMode == MarkLines) && (pos.y() > viewport()->height() || pos.y() < 0)) {
446 if(!scrollTimer->isActive()) {
447 scrollTimer->start();
450 if(scrollTimer->isActive()) {
454 handleMouseMoveEvent(pos);
457 void ChatWidget::handleMouseMoveEvent(const QPoint &_pos) {
459 if(lines.count() <= 0) return;
460 // Set some basic properties of the current position
461 QPoint pos = _pos + QPoint(0, verticalScrollBar()->value());
464 //MousePos oldpos = mousePos;
465 if(x >= tsGrabPos - 3 && x <= tsGrabPos + 3) mousePos = OverTsSep;
466 else if(x >= senderGrabPos - 3 && x <= senderGrabPos + 3) mousePos = OverTextSep;
467 else mousePos = None;
469 // Pass 1: Do whatever we can before switching mouse mode (if at all).
471 // No special mode. Set mouse cursor if appropriate.
474 //if(oldpos != mousePos) {
475 if(mousePos == OverTsSep || mousePos == OverTextSep) setCursor(Qt::OpenHandCursor);
477 int l = yToLineIdx(y);
478 int c = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
479 if(c >= 0 && lines[l]->isUrl(c)) {
480 setCursor(Qt::PointingHandCursor);
482 setCursor(Qt::ArrowCursor);
487 // Left button pressed. Might initiate marking or drag & drop if we moved past the drag distance.
489 if(!dragStartPos.isNull() && (dragStartPos - pos).manhattanLength() >= QApplication::startDragDistance()) {
490 // Moving a column separator?
491 if(dragStartMode == DragTsSep) mouseMode = DragTsSep;
492 else if(dragStartMode == DragTextSep) mouseMode = DragTextSep;
493 // Nope. Check if we are over a selection to start drag & drop.
494 else if(dragStartMode == Normal) {
495 bool dragdrop = false;
496 if(selectionMode == TextSelected) {
497 int l = yToLineIdx(y);
498 if(selectionLine == l) {
499 int p = lines[l]->posToCursor(QPointF(x, y - ycoords[l]));
500 if(p >= selectionStart && p <= selectionEnd) dragdrop = true;
502 } else if(selectionMode == LinesSelected) {
503 int l = yToLineIdx(y);
504 if(l >= selectionStart && l <= selectionEnd) dragdrop = true;
506 // Ok, so just start drag & drop if appropriate.
508 QDrag *drag = new QDrag(this);
509 QMimeData *mimeData = new QMimeData;
510 mimeData->setText(selectionToString());
511 drag->setMimeData(mimeData);
514 // Otherwise, clear the selection and start text marking!
516 setCursor(Qt::ArrowCursor);
518 if(dragStartCursor < 0) { mouseMode = MarkLines; curLine = -1; }
519 else mouseMode = MarkText;
531 // Pass 2: Some mouse modes need work after being set...
532 if(mouseMode == DragTsSep && x < size().width() - QtUi::style()->sepSenderText() - senderWidth - 10) {
533 // Drag first column separator
534 int foo = QtUi::style()->sepTsSender()/2;
535 tsWidth = qMax(x, foo) - foo;
538 } else if(mouseMode == DragTextSep && x < size().width() - 10) {
539 // Drag second column separator
540 int foo = tsWidth + QtUi::style()->sepTsSender() + QtUi::style()->sepSenderText()/2;
541 senderWidth = qMax(x, foo) - foo;
544 } else if(mouseMode == MarkText) {
545 // Change currently marked text
546 curLine = yToLineIdx(y);
547 int c = lines[curLine]->posToCursor(QPointF(x, y - ycoords[curLine]));
548 if(curLine == dragStartLine && c >= 0) {
551 lines[curLine]->setSelection(ChatLineOld::Partial, dragStartCursor, c);
552 viewport()->update();
555 mouseMode = MarkLines;
556 selectionStart = qMin(curLine, dragStartLine); selectionEnd = qMax(curLine, dragStartLine);
557 for(int i = selectionStart; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
558 viewport()->update();
560 } else if(mouseMode == MarkLines) {
562 int l = yToLineIdx(y);
564 selectionStart = qMin(l, dragStartLine); selectionEnd = qMax(l, dragStartLine);
566 Q_ASSERT(selectionStart == selectionEnd);
567 lines[l]->setSelection(ChatLineOld::Full);
569 if(curLine < selectionStart) {
570 for(int i = curLine; i < selectionStart; i++) lines[i]->setSelection(ChatLineOld::None);
571 } else if(curLine > selectionEnd) {
572 for(int i = selectionEnd+1; i <= curLine; i++) lines[i]->setSelection(ChatLineOld::None);
573 } else if(selectionStart < curLine && l < curLine) {
574 for(int i = selectionStart; i < curLine; i++) lines[i]->setSelection(ChatLineOld::Full);
575 } else if(curLine < selectionEnd && l > curLine) {
576 for(int i = curLine+1; i <= selectionEnd; i++) lines[i]->setSelection(ChatLineOld::Full);
581 viewport()->update();
586 //!\brief Clear current text selection.
587 void ChatWidget::clearSelection() {
588 if(selectionMode == TextSelected) {
589 lines[selectionLine]->setSelection(ChatLineOld::None);
590 } else if(selectionMode == LinesSelected) {
591 for(int i = selectionStart; i <= selectionEnd; i++) {
592 lines[i]->setSelection(ChatLineOld::None);
595 selectionMode = NoSelection;
596 viewport()->update();
599 //!\brief Convert current selection to human-readable string.
600 QString ChatWidget::selectionToString() {
601 //TODO Make selection format configurable!
602 if(selectionMode == NoSelection) return "";
603 if(selectionMode == LinesSelected) {
605 for(int l = selectionStart; l <= selectionEnd; l++) {
606 result += QString("[%1] %2 %3\n").arg(lines[l]->timestamp().toLocalTime().toString("hh:mm:ss"))
607 . arg(lines[l]->sender()).arg(lines[l]->text());
611 // selectionMode == TextSelected
612 return lines[selectionLine]->text().mid(selectionStart, selectionEnd - selectionStart);
615 void ChatWidget::viewportChanged(int newPos) {
616 const int REQUEST_COUNT = 50;
617 QAbstractSlider *vbar = verticalScrollBar();
621 int relativePos = 100;
622 if(vbar->maximum() - vbar->minimum() != 0)
623 relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
625 if(relativePos < 20) {
626 Buffer *buffer = Client::buffer(bufferId);
628 if(buffer->contents().isEmpty())
630 MsgId msgId = buffer->contents().first()->msgId();
631 if(!lastBacklogOffset.isValid() || msgId < lastBacklogOffset && lastBacklogSize + REQUEST_COUNT <= buffer->contents().count()) {
632 Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
633 lastBacklogOffset = msgId;
634 lastBacklogSize = buffer->contents().size();