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