1af7e850f40d37295056d5d44812a66b7dac4a73
[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 = 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   if(curRow > _selectionEnd && curRow > _selectionStart) {  // select further towards bottom
210     for(int l = _selectionEnd + 1; l <= curRow; l++) {
211       _lines[l]->setSelected(true, minColumn);
212     }
213   } else if(curRow > _selectionEnd && curRow <= _selectionStart) { // deselect towards bottom
214     for(int l = _selectionEnd; l < curRow; l++) {
215       _lines[l]->setSelected(false);
216     }
217   } else if(curRow < _selectionEnd && curRow >= _selectionStart) {
218     for(int l = _selectionEnd; l > curRow; l--) {
219       _lines[l]->setSelected(false);
220     }
221   } else if(curRow < _selectionEnd && curRow < _selectionStart) {
222     for(int l = _selectionEnd - 1; l >= curRow; l--) {
223       _lines[l]->setSelected(true, minColumn);
224     }
225   }
226   _selectionEnd = curRow;
227
228   if(curRow == _selectionStart && minColumn == ChatLineModel::ContentsColumn) {
229     _lines[curRow]->setSelected(false);
230     _isSelecting = false;
231     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
232   }
233 }
234
235 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
236   if(_isSelecting && event->buttons() == Qt::LeftButton) {
237     updateSelection(event->scenePos());
238     event->accept();
239   } else {
240     QGraphicsScene::mouseMoveEvent(event);
241   }
242 }
243
244 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
245   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
246     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
247       _lines[l]->setSelected(false);
248     }
249     _selectionStart = -1;
250     event->accept();
251   } else {
252     QGraphicsScene::mousePressEvent(event);
253   }
254 }
255
256 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
257   if(_isSelecting && event->buttons() == Qt::LeftButton) {
258 #   ifdef Q_WS_X11
259       QApplication::clipboard()->setText(selectionToString(), QClipboard::Selection);
260 #   endif
261 //# else
262       QApplication::clipboard()->setText(selectionToString());
263 //# endif
264     _isSelecting = false;
265     event->accept();
266   } else {
267     QGraphicsScene::mouseReleaseEvent(event);
268   }
269 }
270
271 //!\brief Convert current selection to human-readable string.
272 QString ChatScene::selectionToString() const {
273   //TODO Make selection format configurable!
274   if(!_isSelecting) return QString();
275   int start = qMin(_selectionStart, _selectionEnd);
276   int end = qMax(_selectionStart, _selectionEnd);
277   if(start < 0 || end >= _lines.count()) {
278     qDebug() << "Invalid selection range:" << start << end;
279     return QString();
280   }
281   QString result;
282   for(int l = start; l <= end; l++) {
283     if(_selectionMinCol == ChatLineModel::TimestampColumn)
284       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
285     if(_selectionMinCol <= ChatLineModel::SenderColumn)
286       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
287     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
288   }
289   return result;
290 }
291
292 void ChatScene::setIsFetchingBacklog(bool fetch) {
293   if(!isBacklogFetchingEnabled()) return;
294
295   if(!fetch) {
296     _fetchingBacklog = false;
297   } else {
298     _fetchingBacklog = true;
299     requestBacklogIfNeeded();
300   }
301 }
302
303 void ChatScene::requestBacklogIfNeeded() {
304   const int REQUEST_COUNT = 50;
305
306   if(!isBacklogFetchingEnabled() || !isFetchingBacklog() || !model()->rowCount()) return;
307
308   MsgId msgId = model()->data(model()->index(0, 0), ChatLineModel::MsgIdRole).value<MsgId>();
309   if(!_lastBacklogOffset.isValid() || (msgId < _lastBacklogOffset && _lastBacklogSize + REQUEST_COUNT <= model()->rowCount())) {
310     Client::backlogManager()->requestBacklog(bufferForBacklogFetching(), REQUEST_COUNT, msgId.toInt());
311     _lastBacklogOffset = msgId;
312     _lastBacklogSize = model()->rowCount();
313   }
314 }
315
316 int ChatScene::sectionByScenePos(int x) {
317   if(x < firstColHandlePos)
318     return ChatLineModel::TimestampColumn;
319   if(x < secondColHandlePos)
320     return ChatLineModel::SenderColumn;
321
322   return ChatLineModel::ContentsColumn;
323 }