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