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