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