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