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