5ca0bfe99abb817c717f35f8265438eca34966e3
[quassel.git] / src / qtui / chatscene.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 <QApplication>
22 #include <QClipboard>
23 #include <QGraphicsSceneMouseEvent>
24 #include <QPersistentModelIndex>
25
26 #include "chatitem.h"
27 #include "chatline.h"
28 #include "chatlinemodelitem.h"
29 #include "chatscene.h"
30 #include "client.h"
31 #include "clientbacklogmanager.h"
32 #include "columnhandleitem.h"
33 #include "messagefilter.h"
34 #include "qtui.h"
35 #include "chatviewsettings.h"
36
37 const qreal minContentsWidth = 200;
38
39 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
40   : QGraphicsScene(0, 0, width, 0, parent),
41     _idString(idString),
42     _model(model),
43     _singleBufferScene(false),
44     _selectingItem(0),
45     _selectionStart(-1),
46     _isSelecting(false),
47     _lastBacklogSize(0)
48 {
49   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
50   if(filter) {
51     _singleBufferScene = filter->isSingleBufferFilter();
52   }
53
54   ChatViewSettings defaultSettings;
55   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
56   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
57
58   ChatViewSettings viewSettings(this);
59   firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
60   secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
61
62   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
63   addItem(firstColHandle);
64   firstColHandle->setXPos(firstColHandlePos);
65   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
66   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
67
68   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
69   addItem(secondColHandle);
70   secondColHandle->setXPos(secondColHandlePos);
71   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
72   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
73
74   setHandleXLimits();
75
76   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
77           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
78   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
79           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
80
81   if(model->rowCount() > 0)
82     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
83 }
84
85 ChatScene::~ChatScene() {
86 }
87
88 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
89   Q_UNUSED(index);
90   qreal h = 0;
91   qreal y = sceneRect().y();
92   qreal width = sceneRect().width();
93   bool atTop = true;
94   bool atBottom = false;
95   bool moveTop = false;
96   bool hasWidth = (width != 0);
97
98   if(start > 0) {
99     y = _lines.value(start - 1)->y() + _lines.value(start - 1)->height();
100     atTop = false;
101   }
102   if(start == _lines.count())
103     atBottom = true;
104
105   for(int i = end; i >= start; i--) {
106     ChatLine *line = new ChatLine(i, model());
107     _lines.insert(start, line);
108     addItem(line);
109     if(hasWidth) {
110       if(atTop) {
111         h -= line->setGeometry(width);
112         line->setPos(0, y+h);
113       } else {
114         line->setPos(0, y+h);
115         h += line->setGeometry(width);
116       }
117     }
118   }
119
120   // update existing items
121   for(int i = end+1; i < _lines.count(); i++) {
122     _lines[i]->setRow(i);
123   }
124
125   // update selection
126   if(_selectionStart >= 0) {
127     int offset = end - start + 1;
128     if(_selectionStart >= start) _selectionStart += offset;
129     if(_selectionEnd >= start) _selectionEnd += offset;
130     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
131     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
132   }
133
134   // neither pre- or append means we have to do dirty work: move items...
135   if(!(atTop || atBottom)) {
136     qreal offset = h;
137     int moveStart = 0;
138     int moveEnd = _lines.count() - 1;
139     ChatLine *line = 0;
140     if(end > _lines.count() - end) {
141       // move top part
142       moveTop = true;
143       offset = -offset;
144       moveEnd = end;
145     } else {
146       // move bottom part
147       moveStart = start;
148     }
149     for(int i = moveStart; i <= moveEnd; i++) {
150       line = _lines.at(i);
151       line->setPos(0, line->pos().y() + offset);
152     }
153   }
154   
155   // update sceneRect
156   if(atTop || moveTop) {
157     setSceneRect(sceneRect().adjusted(0, h, 0, 0));
158   } else {
159     setSceneRect(sceneRect().adjusted(0, 0, 0, h));
160     emit sceneHeightChanged(h);
161   }
162
163 }
164
165 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
166   Q_UNUSED(parent);
167
168   qreal h = 0; // total height of removed items;
169
170   bool atTop = (start == 0);
171   bool atBottom = (end == _lines.count() - 1);
172   bool moveTop = false;
173
174   // remove items from scene
175   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
176   int lineCount = start;
177   while(lineIter != _lines.end() && lineCount <= end) {
178     h += (*lineIter)->height();
179     delete *lineIter;
180     lineIter = _lines.erase(lineIter);
181     lineCount++;
182   }
183
184   // update rows of remaining chatlines
185   for(int i = start; i < _lines.count(); i++) {
186     _lines.at(i)->setRow(i);
187   }
188
189   // update selection
190   if(_selectionStart >= 0) {
191     int offset = end - start + 1;
192     if(_selectionStart >= start)
193       _selectionStart -= offset;
194     if(_selectionEnd >= start)
195       _selectionEnd -= offset;
196     if(_firstSelectionRow >= start)
197       _firstSelectionRow -= offset;
198     if(_lastSelectionRow >= start)
199       _lastSelectionRow -= offset;
200   }
201
202   // neither removing at bottom or top means we have to move items...
203   if(!(atTop || atBottom)) {
204     qreal offset = h;
205     int moveStart = 0;
206     int moveEnd = _lines.count() - 1;
207     ChatLine *line = 0;
208     if(start > _lines.count() - end) {
209       // move top part
210       moveTop = true;
211       moveEnd = start - 1;
212     } else {
213       // move bottom part
214       moveStart = start;
215       offset = -offset;
216     }
217     for(int i = moveStart; i <= moveEnd; i++) {
218       line = _lines.at(i);
219       line->setPos(0, line->pos().y() + offset);
220     }
221   }
222
223   // update sceneRect
224   if(atTop || moveTop) {
225     setSceneRect(sceneRect().adjusted(0, h, 0, 0));
226   } else {
227     setSceneRect(sceneRect().adjusted(0, 0, 0, -h));
228   }
229
230 }
231
232 void ChatScene::setWidth(qreal width, bool forceReposition) {
233   if(width == sceneRect().width() && !forceReposition)
234     return;
235
236   qreal oldHeight = sceneRect().height();
237   qreal y = sceneRect().y();
238   qreal linePos = y;
239
240   foreach(ChatLine *line, _lines) {
241     line->setPos(0, linePos);
242     linePos += line->setGeometry(width);
243   }
244
245   qreal height = linePos - y;
246
247   setSceneRect(QRectF(0, y, width, height));
248   setHandleXLimits();
249
250   qreal dh = height - oldHeight;
251   if(dh > 0)
252     emit sceneHeightChanged(dh);
253 }
254
255 void ChatScene::handlePositionChanged(qreal xpos) {
256   bool first = (sender() == firstColHandle);
257   qreal oldx;
258   if(first) {
259     oldx = firstColHandlePos;
260     firstColHandlePos = xpos;
261   } else {
262     oldx = secondColHandlePos;
263     secondColHandlePos = xpos;
264   }
265
266   ChatViewSettings viewSettings(this);
267   viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
268   viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
269
270   ChatViewSettings defaultSettings;
271   defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
272   defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
273
274   setWidth(width(), true);  // readjust all chatlines
275   // we get ugly redraw errors if we don't update this explicitly... :(
276   // width() should be the same for both handles, so just use firstColHandle regardless
277   //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
278 }
279
280 void ChatScene::setHandleXLimits() {
281   firstColHandle->setXLimits(0, secondColumnHandleRect().left());
282   secondColHandle->setXLimits(firstColumnHandleRect().right(), width() - minContentsWidth);
283 }
284
285 void ChatScene::setSelectingItem(ChatItem *item) {
286   if(_selectingItem) _selectingItem->clearSelection();
287   _selectingItem = item;
288 }
289
290 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
291   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
292   _selectionStartCol = _selectionMinCol = item->column();
293   _isSelecting = true;
294   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
295   updateSelection(item->mapToScene(itemPos));
296 }
297
298 void ChatScene::updateSelection(const QPointF &pos) {
299   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
300   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
301   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColumnHandleRect().right() + 1, pos.y())));
302   if(!contentItem) return;
303
304   int curRow = contentItem->row();
305   int curColumn;
306   if(pos.x() > secondColumnHandleRect().right()) curColumn = ChatLineModel::ContentsColumn;
307   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
308   else curColumn = ChatLineModel::TimestampColumn;
309
310   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
311   if(minColumn != _selectionMinCol) {
312     _selectionMinCol = minColumn;
313     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
314       _lines[l]->setSelected(true, minColumn);
315     }
316   }
317   int newstart = qMin(curRow, _firstSelectionRow);
318   int newend = qMax(curRow, _firstSelectionRow);
319   if(newstart < _selectionStart) {
320     for(int l = newstart; l < _selectionStart; l++)
321       _lines[l]->setSelected(true, minColumn);
322   }
323   if(newstart > _selectionStart) {
324     for(int l = _selectionStart; l < newstart; l++)
325       _lines[l]->setSelected(false);
326   }
327   if(newend > _selectionEnd) {
328     for(int l = _selectionEnd+1; l <= newend; l++)
329       _lines[l]->setSelected(true, minColumn);
330   }
331   if(newend < _selectionEnd) {
332     for(int l = newend+1; l <= _selectionEnd; l++)
333       _lines[l]->setSelected(false);
334   }
335
336   _selectionStart = newstart;
337   _selectionEnd = newend;
338   _lastSelectionRow = curRow;
339
340   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
341     if(!_selectingItem) {
342       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
343       return;
344     }
345     _lines[curRow]->setSelected(false);
346     _isSelecting = false;
347     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
348   }
349 }
350
351 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
352   if(_isSelecting && event->buttons() == Qt::LeftButton) {
353     updateSelection(event->scenePos());
354     event->accept();
355   } else {
356     QGraphicsScene::mouseMoveEvent(event);
357   }
358 }
359
360 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
361   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
362     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
363       _lines[l]->setSelected(false);
364     }
365     _selectionStart = -1;
366     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
367   } else {
368     QGraphicsScene::mousePressEvent(event);
369   }
370 }
371
372 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
373   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
374     putToClipboard(selectionToString());
375     _isSelecting = false;
376     event->accept();
377   } else {
378     QGraphicsScene::mouseReleaseEvent(event);
379   }
380 }
381
382 void ChatScene::putToClipboard(const QString &selection) {
383   // TODO Configure clipboards
384 #   ifdef Q_WS_X11
385   QApplication::clipboard()->setText(selection, QClipboard::Selection);
386 #   endif
387 //# else
388   QApplication::clipboard()->setText(selection);
389 //# endif
390 }
391
392 //!\brief Convert current selection to human-readable string.
393 QString ChatScene::selectionToString() const {
394   //TODO Make selection format configurable!
395   if(!_isSelecting) return QString();
396   int start = qMin(_selectionStart, _selectionEnd);
397   int end = qMax(_selectionStart, _selectionEnd);
398   if(start < 0 || end >= _lines.count()) {
399     qDebug() << "Invalid selection range:" << start << end;
400     return QString();
401   }
402   QString result;
403   for(int l = start; l <= end; l++) {
404     if(_selectionMinCol == ChatLineModel::TimestampColumn)
405       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
406     if(_selectionMinCol <= ChatLineModel::SenderColumn)
407       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
408     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
409   }
410   return result;
411 }
412
413 void ChatScene::requestBacklog() {
414   static const int REQUEST_COUNT = 50;
415   int backlogSize = model()->rowCount();
416   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
417     QModelIndex msgIdx = model()->index(0, 0);
418     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
419     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
420     _lastBacklogSize = backlogSize;
421     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
422   }
423 }
424
425 int ChatScene::sectionByScenePos(int x) {
426   if(x < firstColHandle->x())
427     return ChatLineModel::TimestampColumn;
428   if(x < secondColHandle->x())
429     return ChatLineModel::SenderColumn;
430
431   return ChatLineModel::ContentsColumn;
432 }