Test our newly acquired shortcut capabilities by finally allowing Ctrl+F to trigger...
[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 "qtuistyle.h"
36 #include "chatviewsettings.h"
37
38 const qreal minContentsWidth = 200;
39
40 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
41   : QGraphicsScene(0, 0, width, 0, parent),
42     _idString(idString),
43     _model(model),
44     _singleBufferScene(false),
45     _sceneRect(0, 0, width, 0),
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   ChatViewSettings defaultSettings;
57   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
58   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
59
60   ChatViewSettings viewSettings(this);
61   firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
62   secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
63
64   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
65   addItem(firstColHandle);
66   firstColHandle->setXPos(firstColHandlePos);
67   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
68   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
69
70   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
71   addItem(secondColHandle);
72   secondColHandle->setXPos(secondColHandlePos);
73   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
74   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
75
76   setHandleXLimits();
77
78   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
79           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
80   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
81           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
82
83   if(model->rowCount() > 0)
84     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
85 }
86
87 ChatScene::~ChatScene() {
88 }
89
90 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
91   Q_UNUSED(index);
92   qreal h = 0;
93   qreal y = _sceneRect.y();
94   qreal width = _sceneRect.width();
95   bool atTop = true;
96   bool atBottom = false;
97   bool moveTop = false;
98   bool hasWidth = (width != 0);
99
100   if(start > 0) {
101     y = _lines.value(start - 1)->y() + _lines.value(start - 1)->height();
102     atTop = false;
103   }
104   if(start == _lines.count())
105     atBottom = true;
106
107   for(int i = end; i >= start; i--) {
108     ChatLine *line = new ChatLine(i, model());
109     _lines.insert(start, line);
110     addItem(line);
111     if(hasWidth) {
112       if(atTop) {
113         h -= line->setGeometry(width);
114         line->setPos(0, y+h);
115       } else {
116         line->setPos(0, y+h);
117         h += line->setGeometry(width);
118       }
119     }
120   }
121
122   // update existing items
123   for(int i = end+1; i < _lines.count(); i++) {
124     _lines[i]->setRow(i);
125   }
126
127   // update selection
128   if(_selectionStart >= 0) {
129     int offset = end - start + 1;
130     if(_selectionStart >= start) _selectionStart += offset;
131     if(_selectionEnd >= start) _selectionEnd += offset;
132     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
133     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
134   }
135
136   // neither pre- or append means we have to do dirty work: move items...
137   if(!(atTop || atBottom)) {
138     qreal offset = h;
139     int moveStart = 0;
140     int moveEnd = _lines.count() - 1;
141     ChatLine *line = 0;
142     if(end > _lines.count() - end) {
143       // move top part
144       moveTop = true;
145       offset = -offset;
146       moveEnd = end;
147     } else {
148       // move bottom part
149       moveStart = start;
150     }
151     for(int i = moveStart; i <= moveEnd; i++) {
152       line = _lines.at(i);
153       line->setPos(0, line->pos().y() + offset);
154     }
155   }
156
157   // update sceneRect
158   if(atTop || moveTop) {
159     updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
160   } else {
161     updateSceneRect(_sceneRect.adjusted(0, 0, 0, h));
162     emit sceneHeightChanged(h);
163   }
164
165 }
166
167 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
168   Q_UNUSED(parent);
169
170   qreal h = 0; // total height of removed items;
171
172   bool atTop = (start == 0);
173   bool atBottom = (end == _lines.count() - 1);
174   bool moveTop = false;
175
176   // remove items from scene
177   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
178   int lineCount = start;
179   while(lineIter != _lines.end() && lineCount <= end) {
180     h += (*lineIter)->height();
181     delete *lineIter;
182     lineIter = _lines.erase(lineIter);
183     lineCount++;
184   }
185
186   // update rows of remaining chatlines
187   for(int i = start; i < _lines.count(); i++) {
188     _lines.at(i)->setRow(i);
189   }
190
191   // update selection
192   if(_selectionStart >= 0) {
193     int offset = end - start + 1;
194     if(_selectionStart >= start)
195       _selectionStart -= offset;
196     if(_selectionEnd >= start)
197       _selectionEnd -= offset;
198     if(_firstSelectionRow >= start)
199       _firstSelectionRow -= offset;
200     if(_lastSelectionRow >= start)
201       _lastSelectionRow -= offset;
202   }
203
204   // neither removing at bottom or top means we have to move items...
205   if(!(atTop || atBottom)) {
206     qreal offset = h;
207     int moveStart = 0;
208     int moveEnd = _lines.count() - 1;
209     ChatLine *line = 0;
210     if(start > _lines.count() - end) {
211       // move top part
212       moveTop = true;
213       moveEnd = start - 1;
214     } else {
215       // move bottom part
216       moveStart = start;
217       offset = -offset;
218     }
219     for(int i = moveStart; i <= moveEnd; i++) {
220       line = _lines.at(i);
221       line->setPos(0, line->pos().y() + offset);
222     }
223   }
224
225   // update sceneRect
226   if(atTop || moveTop) {
227     updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
228   } else {
229     updateSceneRect(_sceneRect.adjusted(0, 0, 0, -h));
230   }
231 }
232
233 void ChatScene::setWidth(qreal width, bool forceReposition) {
234   if(width == _sceneRect.width() && !forceReposition)
235     return;
236
237   // clock_t startT = clock();
238   qreal oldHeight = _sceneRect.height();
239   qreal y = _sceneRect.y();
240   qreal linePos = y;
241
242   foreach(ChatLine *line, _lines) {
243     line->setPos(0, linePos);
244     linePos += line->setGeometry(width);
245   }
246
247   qreal height = linePos - y;
248
249   updateSceneRect(QRectF(0, y, width, height));
250   setHandleXLimits();
251
252   qreal dh = height - oldHeight;
253   if(dh > 0)
254     emit sceneHeightChanged(dh);
255
256   // clock_t endT = clock();
257   // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
258 }
259
260 void ChatScene::handlePositionChanged(qreal xpos) {
261   bool first = (sender() == firstColHandle);
262   qreal oldx;
263   if(first) {
264     oldx = firstColHandlePos;
265     firstColHandlePos = xpos;
266   } else {
267     oldx = secondColHandlePos;
268     secondColHandlePos = xpos;
269   }
270
271   ChatViewSettings viewSettings(this);
272   viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
273   viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
274
275   ChatViewSettings defaultSettings;
276   defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
277   defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
278
279   setWidth(width(), true);  // readjust all chatlines
280   // we get ugly redraw errors if we don't update this explicitly... :(
281   // width() should be the same for both handles, so just use firstColHandle regardless
282   //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
283 }
284
285 void ChatScene::setHandleXLimits() {
286   firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
287   secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
288 }
289
290 void ChatScene::setSelectingItem(ChatItem *item) {
291   if(_selectingItem) _selectingItem->clearSelection();
292   _selectingItem = item;
293 }
294
295 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
296   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
297   _selectionStartCol = _selectionMinCol = item->column();
298   _isSelecting = true;
299   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
300   updateSelection(item->mapToScene(itemPos));
301 }
302
303 void ChatScene::updateSelection(const QPointF &pos) {
304   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
305   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
306   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
307   if(!contentItem) return;
308
309   int curRow = contentItem->row();
310   int curColumn;
311   if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
312   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
313   else curColumn = ChatLineModel::TimestampColumn;
314
315   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
316   if(minColumn != _selectionMinCol) {
317     _selectionMinCol = minColumn;
318     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
319       _lines[l]->setSelected(true, minColumn);
320     }
321   }
322   int newstart = qMin(curRow, _firstSelectionRow);
323   int newend = qMax(curRow, _firstSelectionRow);
324   if(newstart < _selectionStart) {
325     for(int l = newstart; l < _selectionStart; l++)
326       _lines[l]->setSelected(true, minColumn);
327   }
328   if(newstart > _selectionStart) {
329     for(int l = _selectionStart; l < newstart; l++)
330       _lines[l]->setSelected(false);
331   }
332   if(newend > _selectionEnd) {
333     for(int l = _selectionEnd+1; l <= newend; l++)
334       _lines[l]->setSelected(true, minColumn);
335   }
336   if(newend < _selectionEnd) {
337     for(int l = newend+1; l <= _selectionEnd; l++)
338       _lines[l]->setSelected(false);
339   }
340
341   _selectionStart = newstart;
342   _selectionEnd = newend;
343   _lastSelectionRow = curRow;
344
345   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
346     if(!_selectingItem) {
347       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
348       return;
349     }
350     _lines[curRow]->setSelected(false);
351     _isSelecting = false;
352     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
353   }
354 }
355
356 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
357   if(_isSelecting && event->buttons() == Qt::LeftButton) {
358     updateSelection(event->scenePos());
359     event->accept();
360   } else {
361     QGraphicsScene::mouseMoveEvent(event);
362   }
363 }
364
365 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
366   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
367     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
368       _lines[l]->setSelected(false);
369     }
370     _selectionStart = -1;
371     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
372   } else {
373     QGraphicsScene::mousePressEvent(event);
374   }
375 }
376
377 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
378   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
379     putToClipboard(selectionToString());
380     _isSelecting = false;
381     event->accept();
382   } else {
383     QGraphicsScene::mouseReleaseEvent(event);
384   }
385 }
386
387 void ChatScene::putToClipboard(const QString &selection) {
388   // TODO Configure clipboards
389 #   ifdef Q_WS_X11
390   QApplication::clipboard()->setText(selection, QClipboard::Selection);
391 #   endif
392 //# else
393   QApplication::clipboard()->setText(selection);
394 //# endif
395 }
396
397 //!\brief Convert current selection to human-readable string.
398 QString ChatScene::selectionToString() const {
399   //TODO Make selection format configurable!
400   if(!_isSelecting) return QString();
401   int start = qMin(_selectionStart, _selectionEnd);
402   int end = qMax(_selectionStart, _selectionEnd);
403   if(start < 0 || end >= _lines.count()) {
404     qDebug() << "Invalid selection range:" << start << end;
405     return QString();
406   }
407   QString result;
408   for(int l = start; l <= end; l++) {
409     if(_selectionMinCol == ChatLineModel::TimestampColumn)
410       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
411     if(_selectionMinCol <= ChatLineModel::SenderColumn)
412       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
413     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
414   }
415   return result;
416 }
417
418 void ChatScene::requestBacklog() {
419   static const int REQUEST_COUNT = 100;
420   int backlogSize = model()->rowCount();
421   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
422     QModelIndex msgIdx = model()->index(0, 0);
423     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
424     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
425     _lastBacklogSize = backlogSize;
426     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
427   }
428 }
429
430 int ChatScene::sectionByScenePos(int x) {
431   if(x < firstColHandle->x())
432     return ChatLineModel::TimestampColumn;
433   if(x < secondColHandle->x())
434     return ChatLineModel::SenderColumn;
435
436   return ChatLineModel::ContentsColumn;
437 }
438
439 void ChatScene::updateSceneRect(const QRectF &rect) {
440   _sceneRect = rect;
441   setSceneRect(rect);
442 }