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