Correctly handle selections while new ChatLines are being inserted
[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 "qtuisettings.h"
36
37 const qreal minContentsWidth = 200;
38
39 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, QObject *parent)
40   : QGraphicsScene(parent),
41     _idString(idString),
42     _width(0),
43     _height(0),
44     _model(model),
45     _singleBufferScene(false),
46     _selectingItem(0),
47     _selectionStart(-1),
48     _isSelecting(false),
49     _fetchingBacklog(false)
50 {
51   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
52   if(filter) {
53     _singleBufferScene = filter->isSingleBufferFilter();
54   }
55
56   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(rectChanged(const QRectF &)));
57
58   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(rowsInserted(const QModelIndex &, int, int)));
59   connect(model, SIGNAL(modelAboutToBeReset()), this, SLOT(modelReset()));
60   for(int i = 0; i < model->rowCount(); i++) {
61     ChatLine *line = new ChatLine(i, model);
62     _lines.append(line);
63     addItem(line);
64   }
65
66   QtUiSettings s;
67   int defaultFirstColHandlePos = s.value("ChatView/DefaultFirstColumnHandlePos", 80).toInt();
68   int defaultSecondColHandlePos = s.value("ChatView/DefaultSecondColumnHandlePos", 200).toInt();
69
70   firstColHandlePos = s.value(QString("ChatView/%1/FirstColumnHandlePos").arg(_idString),
71                                defaultFirstColHandlePos).toInt();
72   secondColHandlePos = s.value(QString("ChatView/%1/SecondColumnHandlePos").arg(_idString),
73                                 defaultSecondColHandlePos).toInt();
74
75   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator()); addItem(firstColHandle);
76   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator()); addItem(secondColHandle);
77
78   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
79   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
80
81   firstColHandle->setXPos(firstColHandlePos);
82   firstColHandle->setXLimits(0, secondColHandlePos);
83   secondColHandle->setXPos(secondColHandlePos);
84   secondColHandle->setXLimits(firstColHandlePos, width() - minContentsWidth);
85
86   emit heightChanged(height());
87 }
88
89 ChatScene::~ChatScene() {
90
91 }
92
93 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
94   Q_UNUSED(index);
95   // maybe make this more efficient by prepending stuff with negative yval
96   // dunno if that's worth not guranteeing that 0 is on the top...
97   // TODO bulk inserts, iterators
98   qreal h = 0;
99   qreal y = 0;
100   if(_width && start > 0) y = _lines.value(start - 1)->y() + _lines.value(start - 1)->height();
101   for(int i = start; i <= end; i++) {
102     ChatLine *line = new ChatLine(i, model());
103     _lines.insert(i, line);
104     addItem(line);
105     if(_width > 0) {
106       line->setPos(0, y+h);
107       h += line->setGeometry(_width, firstColHandlePos, secondColHandlePos);
108     }
109   }
110   // update existing items
111   for(int i = end+1; i < _lines.count(); i++) {
112     _lines[i]->setRow(i);
113   }
114
115   // update selection
116   if(_selectionStart >= 0) {
117     int offset = end - start + 1;
118     if(_selectionStart >= start) _selectionStart += offset;
119     if(_selectionEnd >= start) _selectionEnd += offset;
120     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
121     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
122   }
123
124   if(h > 0) {
125     _height += h;
126     for(int i = end+1; i < _lines.count(); i++) {
127       _lines.value(i)->moveBy(0, h);
128     }
129     setSceneRect(QRectF(0, 0, _width, _height));
130     emit heightChanged(_height);
131   }
132
133   requestBacklogIfNeeded();
134 }
135
136 void ChatScene::modelReset() {
137   foreach(ChatLine *line, _lines) {
138     removeItem(line);
139     delete line;
140   }
141   _lines.clear();
142   setSceneRect(QRectF(0, 0, _width, 0));
143 }
144
145 void ChatScene::setWidth(qreal w) {
146   _width = w;
147   _height = 0;
148   foreach(ChatLine *line, _lines) {
149     line->setPos(0, _height);
150     _height += line->setGeometry(_width, firstColHandlePos, secondColHandlePos);
151   }
152   setSceneRect(QRectF(0, 0, w, _height));
153   secondColHandle->setXLimits(firstColHandlePos, width() - minContentsWidth);
154   emit heightChanged(_height);
155 }
156
157 void ChatScene::rectChanged(const QRectF &rect) {
158   firstColHandle->sceneRectChanged(rect);
159   secondColHandle->sceneRectChanged(rect);
160 }
161
162 void ChatScene::handlePositionChanged(qreal xpos) {
163   bool first = (sender() == firstColHandle);
164   qreal oldx;
165   if(first) {
166     oldx = firstColHandlePos;
167     firstColHandlePos = xpos;
168   } else {
169     oldx = secondColHandlePos;
170     secondColHandlePos = xpos;
171   }
172   QtUiSettings s;
173   s.setValue(QString("ChatView/%1/FirstColumnHandlePos").arg(_idString), firstColHandlePos);
174   s.setValue(QString("ChatView/%1/SecondColumnHandlePos").arg(_idString), secondColHandlePos);
175   s.setValue(QString("ChatView/DefaultFirstColumnHandlePos"), firstColHandlePos);
176   s.setValue(QString("ChatView/DefaultSecondColumnHandlePos"), secondColHandlePos);
177
178   setWidth(width());  // readjust all chatlines
179   // we get ugly redraw errors if we don't update this explicitly... :(
180   // width() should be the same for both handles, so just use firstColHandle regardless
181   update(qMin(oldx, xpos) - firstColHandle->width()/2, 0, qMax(oldx, xpos) + firstColHandle->width()/2, height());
182 }
183
184 void ChatScene::setSelectingItem(ChatItem *item) {
185   if(_selectingItem) _selectingItem->clearSelection();
186   _selectingItem = item;
187 }
188
189 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
190   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
191   _selectionStartCol = _selectionMinCol = item->column();
192   _isSelecting = true;
193   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
194   updateSelection(item->mapToScene(itemPos));
195 }
196
197 void ChatScene::updateSelection(const QPointF &pos) {
198   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
199   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
200   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandlePos + secondColHandle->width()/2, pos.y())));
201   if(!contentItem) return;
202
203   int curRow = contentItem->row();
204   int curColumn;
205   if(pos.x() > secondColHandlePos + secondColHandle->width()/2) curColumn = ChatLineModel::ContentsColumn;
206   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
207   else curColumn = ChatLineModel::TimestampColumn;
208
209   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
210   if(minColumn != _selectionMinCol) {
211     _selectionMinCol = minColumn;
212     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
213       _lines[l]->setSelected(true, minColumn);
214     }
215   }
216   int newstart = qMin(curRow, _firstSelectionRow);
217   int newend = qMax(curRow, _firstSelectionRow);
218   if(newstart < _selectionStart) {
219     for(int l = newstart; l < _selectionStart; l++)
220       _lines[l]->setSelected(true, minColumn);
221   }
222   if(newstart > _selectionStart) {
223     for(int l = _selectionStart; l < newstart; l++)
224       _lines[l]->setSelected(false);
225   }
226   if(newend > _selectionEnd) {
227     for(int l = _selectionEnd+1; l <= newend; l++)
228       _lines[l]->setSelected(true, minColumn);
229   }
230   if(newend < _selectionEnd) {
231     for(int l = newend+1; l <= _selectionEnd; l++)
232       _lines[l]->setSelected(false);
233   }
234
235   _selectionStart = newstart;
236   _selectionEnd = newend;
237   _lastSelectionRow = curRow;
238
239   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
240     _lines[curRow]->setSelected(false);
241     _isSelecting = false;
242     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
243   }
244 }
245
246 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
247   if(_isSelecting && event->buttons() == Qt::LeftButton) {
248     updateSelection(event->scenePos());
249     event->accept();
250   } else {
251     QGraphicsScene::mouseMoveEvent(event);
252   }
253 }
254
255 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
256   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
257     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
258       _lines[l]->setSelected(false);
259     }
260     _selectionStart = -1;
261     event->accept();
262   } else {
263     QGraphicsScene::mousePressEvent(event);
264   }
265 }
266
267 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
268   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
269 #   ifdef Q_WS_X11
270       QApplication::clipboard()->setText(selectionToString(), QClipboard::Selection);
271 #   endif
272 //# else
273       QApplication::clipboard()->setText(selectionToString());
274 //# endif
275     _isSelecting = false;
276     event->accept();
277   } else {
278     QGraphicsScene::mouseReleaseEvent(event);
279   }
280 }
281
282 //!\brief Convert current selection to human-readable string.
283 QString ChatScene::selectionToString() const {
284   //TODO Make selection format configurable!
285   if(!_isSelecting) return QString();
286   int start = qMin(_selectionStart, _selectionEnd);
287   int end = qMax(_selectionStart, _selectionEnd);
288   if(start < 0 || end >= _lines.count()) {
289     qDebug() << "Invalid selection range:" << start << end;
290     return QString();
291   }
292   QString result;
293   for(int l = start; l <= end; l++) {
294     if(_selectionMinCol == ChatLineModel::TimestampColumn)
295       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
296     if(_selectionMinCol <= ChatLineModel::SenderColumn)
297       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
298     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
299   }
300   return result;
301 }
302
303 void ChatScene::setIsFetchingBacklog(bool fetch) {
304   if(!isBacklogFetchingEnabled()) return;
305
306   if(!fetch) {
307     _fetchingBacklog = false;
308   } else {
309     _fetchingBacklog = true;
310     requestBacklogIfNeeded();
311   }
312 }
313
314 void ChatScene::requestBacklogIfNeeded() {
315   const int REQUEST_COUNT = 50;
316
317   if(!isBacklogFetchingEnabled() || !isFetchingBacklog() || !model()->rowCount()) return;
318
319   MsgId msgId = model()->data(model()->index(0, 0), ChatLineModel::MsgIdRole).value<MsgId>();
320   if(!_lastBacklogOffset.isValid() || (msgId < _lastBacklogOffset && _lastBacklogSize + REQUEST_COUNT <= model()->rowCount())) {
321     Client::backlogManager()->requestBacklog(bufferForBacklogFetching(), REQUEST_COUNT, msgId.toInt());
322     _lastBacklogOffset = msgId;
323     _lastBacklogSize = model()->rowCount();
324   }
325 }
326
327 int ChatScene::sectionByScenePos(int x) {
328   if(x < firstColHandlePos)
329     return ChatLineModel::TimestampColumn;
330   if(x < secondColHandlePos)
331     return ChatLineModel::SenderColumn;
332
333   return ChatLineModel::ContentsColumn;
334 }