add MenuBar toggle to ChatScene context menu
[quassel.git] / src / qtui / chatscene.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 <QDrag>
24 #include <QGraphicsSceneMouseEvent>
25 #include <QMenu>
26 #include <QMenuBar>
27 #include <QPersistentModelIndex>
28
29 #ifdef HAVE_KDE
30 #  include <KMenuBar>
31 #else
32 #  include <QMenuBar>
33 #endif
34
35 #ifdef HAVE_WEBKIT
36 #  include <QWebView>
37 #endif
38
39 #include "chatitem.h"
40 #include "chatline.h"
41 #include "chatlinemodelitem.h"
42 #include "chatscene.h"
43 #include "chatview.h"
44 #include "client.h"
45 #include "clientbacklogmanager.h"
46 #include "columnhandleitem.h"
47 #include "contextmenuactionprovider.h"
48 #include "iconloader.h"
49 #include "messagefilter.h"
50 #include "qtui.h"
51 #include "qtuistyle.h"
52 #include "chatviewsettings.h"
53 #include "webpreviewitem.h"
54
55 const qreal minContentsWidth = 200;
56
57 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
58   : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
59     _chatView(parent),
60     _idString(idString),
61     _model(model),
62     _singleBufferId(BufferId()),
63     _sceneRect(0, 0, width, 0),
64     _firstLineRow(-1),
65     _viewportHeight(0),
66     _cutoffMode(CutoffRight),
67     _selectingItem(0),
68     _selectionStart(-1),
69     _isSelecting(false),
70     _clickMode(NoClick),
71     _clickHandled(true),
72     _leftButtonPressed(false)
73 {
74   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
75   if(filter && filter->isSingleBufferFilter()) {
76     _singleBufferId = filter->singleBufferId();
77   }
78
79   ChatViewSettings defaultSettings;
80   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
81   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
82
83   ChatViewSettings viewSettings(this);
84   _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
85   _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
86
87   _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
88   addItem(_firstColHandle);
89   _firstColHandle->setXPos(_firstColHandlePos);
90   connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
91   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
92
93   _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
94   addItem(_secondColHandle);
95   _secondColHandle->setXPos(_secondColHandlePos);
96   connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
97
98   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
99
100   setHandleXLimits();
101
102   if(model->rowCount() > 0)
103     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
104
105   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
106           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
107   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
108           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
109   connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
110
111 #ifdef HAVE_WEBKIT
112   webPreview.timer.setSingleShot(true);
113   connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
114 #endif
115   _showWebPreview = defaultSettings.showWebPreview();
116   defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
117
118   _clickTimer.setInterval(QApplication::doubleClickInterval());
119   _clickTimer.setSingleShot(true);
120   connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
121
122   setItemIndexMethod(QGraphicsScene::NoIndex);
123 }
124
125 ChatScene::~ChatScene() {
126 }
127
128 ChatView *ChatScene::chatView() const {
129   return _chatView;
130 }
131
132 ColumnHandleItem *ChatScene::firstColumnHandle() const {
133   return _firstColHandle;
134 }
135
136 ColumnHandleItem *ChatScene::secondColumnHandle() const {
137   return _secondColHandle;
138 }
139
140 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
141   QGraphicsItem *item = itemAt(scenePos);
142   return dynamic_cast<ChatItem *>(item);
143 }
144
145 bool ChatScene::containsBuffer(const BufferId &id) const {
146   MessageFilter *filter = qobject_cast<MessageFilter*>(model());
147   if(filter)
148     return filter->containsBuffer(id);
149   else
150     return false;
151 }
152
153 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
154   Q_UNUSED(index);
155
156
157 //   QModelIndex sidx = model()->index(start, 2);
158 //   QModelIndex eidx = model()->index(end, 2);
159 //   qDebug() << "rowsInserted:";
160 //   if(start > 0) {
161 //     QModelIndex ssidx = model()->index(start - 1, 2);
162 //     qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
163 //           << ssidx.data(Qt::DisplayRole).toString();
164 //   }
165 //   qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
166 //         << sidx.data(Qt::DisplayRole).toString();
167 //   qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
168 //         << eidx.data(Qt::DisplayRole).toString();
169 //   if(end + 1 < model()->rowCount()) {
170 //     QModelIndex eeidx = model()->index(end + 1, 2);
171 //     qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
172 //           << eeidx.data(Qt::DisplayRole).toString();
173 //   }
174
175   qreal h = 0;
176   qreal y = 0;
177   qreal width = _sceneRect.width();
178   bool atBottom = (start == _lines.count());
179   bool atTop = !atBottom && (start == 0);
180
181   if(start < _lines.count()) {
182     y = _lines.value(start)->y();
183   } else if(atBottom && !_lines.isEmpty()) {
184     y = _lines.last()->y() + _lines.last()->height();
185   }
186
187   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
188   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
189   qreal timestampWidth = firstColumnHandle()->sceneLeft();
190   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
191   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
192
193   if(atTop) {
194     for(int i = end; i >= start; i--) {
195       ChatLine *line = new ChatLine(i, model(),
196                                     width,
197                                     timestampWidth, senderWidth, contentsWidth,
198                                     senderPos, contentsPos);
199       h += line->height();
200       line->setPos(0, y-h);
201       _lines.insert(start, line);
202       addItem(line);
203     }
204   } else {
205     for(int i = start; i <= end; i++) {
206       ChatLine *line = new ChatLine(i, model(),
207                                     width,
208                                     timestampWidth, senderWidth, contentsWidth,
209                                     senderPos, contentsPos);
210       line->setPos(0, y+h);
211       h += line->height();
212       _lines.insert(i, line);
213       addItem(line);
214     }
215   }
216
217   // update existing items
218   for(int i = end+1; i < _lines.count(); i++) {
219     _lines[i]->setRow(i);
220   }
221
222   // update selection
223   if(_selectionStart >= 0) {
224     int offset = end - start + 1;
225     int oldStart = _selectionStart;
226     if(_selectionStart >= start)
227       _selectionStart += offset;
228     if(_selectionEnd >= start) {
229       _selectionEnd += offset;
230       if(_selectionStart == oldStart)
231         for(int i = start; i < start + offset; i++)
232           _lines[i]->setSelected(true);
233     }
234     if(_firstSelectionRow >= start)
235       _firstSelectionRow += offset;
236   }
237
238   // neither pre- or append means we have to do dirty work: move items...
239   if(!(atTop || atBottom)) {
240     ChatLine *line = 0;
241     for(int i = 0; i <= end; i++) {
242       line = _lines.at(i);
243       line->setPos(0, line->pos().y() - h);
244     }
245   }
246
247   // check if all went right
248   Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
249 //   if(start != 0) {
250 //     if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
251 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
252 //       qDebug() << "line[start - 1]:" << _lines.at(start - 1)->pos().y() << "+" << _lines.at(start - 1)->height() << "=" << _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height();
253 //       qDebug() << "line[start]" << _lines.at(start)->pos().y();
254 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
255 //       Q_ASSERT(false)
256 //     }
257 //   }
258   Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
259 //   if(end + 1 < _lines.count()) {
260 //     if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
261 //       qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
262 //       qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
263 //       qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
264 //       qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
265 //       Q_ASSERT(false);
266 //     }
267 //   }
268
269   if(!atBottom) {
270     if(start < _firstLineRow) {
271       int prevFirstLineRow = _firstLineRow + (end - start + 1);
272       for(int i = end + 1; i < prevFirstLineRow; i++) {
273         _lines.at(i)->show();
274       }
275     }
276     // force new search for first proper line
277     _firstLineRow = -1;
278   }
279   updateSceneRect();
280   if(atBottom) {
281     emit lastLineChanged(_lines.last(), h);
282   }
283 }
284
285 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
286   Q_UNUSED(parent);
287
288   qreal h = 0; // total height of removed items;
289
290   bool atTop = (start == 0);
291   bool atBottom = (end == _lines.count() - 1);
292   bool moveTop = false;
293
294   // clear selection
295   if(_selectingItem) {
296     int row = _selectingItem->row();
297     if(row >= start && row <= end)
298       setSelectingItem(0);
299   }
300
301   // remove items from scene
302   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
303   int lineCount = start;
304   while(lineIter != _lines.end() && lineCount <= end) {
305     h += (*lineIter)->height();
306     delete *lineIter;
307     lineIter = _lines.erase(lineIter);
308     lineCount++;
309   }
310
311   // update rows of remaining chatlines
312   for(int i = start; i < _lines.count(); i++) {
313     _lines.at(i)->setRow(i);
314   }
315
316   // update selection
317   if(_selectionStart >= 0) {
318     int offset = end - start + 1;
319     if(_selectionStart >= start)
320       _selectionStart = qMax(_selectionStart -= offset, start);
321     if(_selectionEnd >= start)
322       _selectionEnd -= offset;
323     if(_firstSelectionRow >= start)
324       _firstSelectionRow -= offset;
325
326     if(_selectionEnd < _selectionStart) {
327       _isSelecting = false;
328       _selectionStart = -1;
329     }
330   }
331
332   // neither removing at bottom or top means we have to move items...
333   if(!(atTop || atBottom)) {
334     qreal offset = h;
335     int moveStart = 0;
336     int moveEnd = _lines.count() - 1;
337     if(start < _lines.count() - start) {
338       // move top part
339       moveTop = true;
340       moveEnd = start - 1;
341     } else {
342       // move bottom part
343       moveStart = start;
344       offset = -offset;
345     }
346     ChatLine *line = 0;
347     for(int i = moveStart; i <= moveEnd; i++) {
348       line = _lines.at(i);
349       line->setPos(0, line->pos().y() + offset);
350     }
351   }
352
353   Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
354
355   // update sceneRect
356   // when searching for the first non-date-line we have to take into account that our
357   // model still contains the just removed lines so we cannot simply call updateSceneRect()
358   int numRows = model()->rowCount();
359   QModelIndex firstLineIdx;
360   _firstLineRow = -1;
361   bool needOffset = false;
362   do {
363     _firstLineRow++;
364     if(_firstLineRow >= start && _firstLineRow <= end) {
365       _firstLineRow = end + 1;
366       needOffset = true;
367     }
368     firstLineIdx = model()->index(_firstLineRow, 0);
369   } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
370
371   if(needOffset)
372     _firstLineRow -= end - start + 1;
373   updateSceneRect();
374 }
375
376 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
377   layout(tl.row(), br.row(), _sceneRect.width());
378 }
379
380 void ChatScene::updateForViewport(qreal width, qreal height) {
381   _viewportHeight = height;
382   setWidth(width);
383 }
384
385 void ChatScene::setWidth(qreal width) {
386   if(width == _sceneRect.width())
387     return;
388   layout(0, _lines.count()-1, width);
389 }
390
391 void ChatScene::layout(int start, int end, qreal width) {
392   // clock_t startT = clock();
393
394   // disabling the index while doing this complex updates is about
395   // 2 to 10 times faster!
396   //setItemIndexMethod(QGraphicsScene::NoIndex);
397
398   if(end >= 0) {
399     int row = end;
400     qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
401     qreal contentsWidth = width - secondColumnHandle()->sceneRight();
402     while(row >= start) {
403       _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
404     }
405
406     if(row >= 0) {
407       // remaining items don't need geometry changes, but maybe repositioning?
408       ChatLine *line = _lines.at(row);
409       qreal offset = linePos - (line->scenePos().y() + line->height());
410       if(offset != 0) {
411         while(row >= 0) {
412           line = _lines.at(row--);
413           line->setPos(0, line->scenePos().y() + offset);
414         }
415       }
416     }
417   }
418
419   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
420
421   updateSceneRect(width);
422   setHandleXLimits();
423   emit layoutChanged();
424
425 //   clock_t endT = clock();
426 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
427 }
428
429 void ChatScene::firstHandlePositionChanged(qreal xpos) {
430   if(_firstColHandlePos == xpos)
431     return;
432
433   _firstColHandlePos = xpos >= 0 ? xpos : 0;
434   ChatViewSettings viewSettings(this);
435   viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
436   ChatViewSettings defaultSettings;
437   defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
438
439   // clock_t startT = clock();
440
441   // disabling the index while doing this complex updates is about
442   // 2 to 10 times faster!
443   //setItemIndexMethod(QGraphicsScene::NoIndex);
444
445   QList<ChatLine *>::iterator lineIter = _lines.end();
446   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
447   qreal timestampWidth = firstColumnHandle()->sceneLeft();
448   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
449   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
450
451   while(lineIter != lineIterBegin) {
452     lineIter--;
453     (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
454   }
455   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
456
457   setHandleXLimits();
458
459 //   clock_t endT = clock();
460 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
461 }
462
463 void ChatScene::secondHandlePositionChanged(qreal xpos) {
464   if(_secondColHandlePos == xpos)
465     return;
466
467   _secondColHandlePos = xpos;
468   ChatViewSettings viewSettings(this);
469   viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
470   ChatViewSettings defaultSettings;
471   defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
472
473   // clock_t startT = clock();
474
475   // disabling the index while doing this complex updates is about
476   // 2 to 10 times faster!
477   //setItemIndexMethod(QGraphicsScene::NoIndex);
478
479   QList<ChatLine *>::iterator lineIter = _lines.end();
480   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
481   qreal linePos = _sceneRect.y() + _sceneRect.height();
482   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
483   qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
484   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
485   while(lineIter != lineIterBegin) {
486     lineIter--;
487     (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
488   }
489   //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
490
491   updateSceneRect();
492   setHandleXLimits();
493   emit layoutChanged();
494
495 //   clock_t endT = clock();
496 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
497 }
498
499 void ChatScene::setHandleXLimits() {
500   _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
501   _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
502 }
503
504 void ChatScene::setSelectingItem(ChatItem *item) {
505   if(_selectingItem) _selectingItem->clearSelection();
506   _selectingItem = item;
507 }
508
509 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
510   _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
511   _selectionStartCol = _selectionMinCol = item->column();
512   _isSelecting = true;
513   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
514   updateSelection(item->mapToScene(itemPos));
515 }
516
517 void ChatScene::updateSelection(const QPointF &pos) {
518   int curRow = rowByScenePos(pos);
519   if(curRow < 0) return;
520   int curColumn = (int)columnByScenePos(pos);
521   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
522   if(minColumn != _selectionMinCol) {
523     _selectionMinCol = minColumn;
524     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
525       _lines[l]->setSelected(true, minColumn);
526     }
527   }
528   int newstart = qMin(curRow, _firstSelectionRow);
529   int newend = qMax(curRow, _firstSelectionRow);
530   if(newstart < _selectionStart) {
531     for(int l = newstart; l < _selectionStart; l++)
532       _lines[l]->setSelected(true, minColumn);
533   }
534   if(newstart > _selectionStart) {
535     for(int l = _selectionStart; l < newstart; l++)
536       _lines[l]->setSelected(false);
537   }
538   if(newend > _selectionEnd) {
539     for(int l = _selectionEnd+1; l <= newend; l++)
540       _lines[l]->setSelected(true, minColumn);
541   }
542   if(newend < _selectionEnd) {
543     for(int l = newend+1; l <= _selectionEnd; l++)
544       _lines[l]->setSelected(false);
545   }
546
547   _selectionStart = newstart;
548   _selectionEnd = newend;
549
550   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
551     if(!_selectingItem) {
552       // _selectingItem has been removed already
553       return;
554     }
555     _lines[curRow]->setSelected(false);
556     _isSelecting = false;
557     _selectionStart = -1;
558     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
559   }
560 }
561
562 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
563   ChatItem *chatItem = chatItemAt(pos);
564   if(!chatItem)
565     return false;
566   if(hasGlobalSelection()) {
567     int row = chatItem->row();
568     if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
569       return columnByScenePos(pos) >= _selectionMinCol;
570   } else {
571     return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
572   }
573   return false;
574 }
575
576 bool ChatScene::isScrollingAllowed() const {
577   if(_isSelecting)
578     return false;
579
580   // TODO: Handle clicks and single-item selections too
581
582   return true;
583 }
584
585 /******** MOUSE HANDLING **************************************************************************/
586
587 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
588   QPointF pos = event->scenePos();
589   QMenu menu;
590
591   // zoom actions and similar
592   chatView()->addActionsToMenu(&menu, pos);
593   menu.addSeparator();
594
595   if(isPosOverSelection(pos))
596     menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
597                     this, SLOT(selectionToClipboard()),
598                     QKeySequence::Copy);
599
600   // item-specific options (select link etc)
601   ChatItem *item = chatItemAt(pos);
602   if(item)
603     item->addActionsToMenu(&menu, item->mapFromScene(pos));
604   else
605     // no item -> default scene actions
606     GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
607
608   if (QtUi::mainWindow()->menuBar()->isHidden())
609     menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
610
611   menu.exec(event->screenPos());
612
613 }
614
615 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
616   if(event->buttons() == Qt::LeftButton) {
617     if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
618       if(_clickTimer.isActive())
619         _clickTimer.stop();
620       if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
621         initiateDrag(event->widget());
622       else {
623         _clickMode = DragStartClick;
624         handleClick(Qt::LeftButton, _clickPos);
625       }
626       _clickMode = NoClick;
627     }
628     if(_isSelecting) {
629       updateSelection(event->scenePos());
630       emit mouseMoveWhileSelecting(event->scenePos());
631       event->accept();
632     } else if(_clickHandled && _clickMode < DoubleClick)
633       QGraphicsScene::mouseMoveEvent(event);
634   } else
635     QGraphicsScene::mouseMoveEvent(event);
636 }
637
638 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
639   if(event->buttons() == Qt::LeftButton) {
640     _leftButtonPressed = true;
641     _clickHandled = false;
642     if(!isPosOverSelection(event->scenePos())) {
643       // immediately clear selection if clicked outside; otherwise, wait for potential drag
644       clearSelection();
645     }
646     if(_clickMode != NoClick && _clickTimer.isActive()) {
647       switch(_clickMode) {
648         case NoClick: _clickMode = SingleClick; break;
649         case SingleClick: _clickMode = DoubleClick; break;
650         case DoubleClick: _clickMode = TripleClick; break;
651         case TripleClick: _clickMode = DoubleClick; break;
652         case DragStartClick: break;
653       }
654       handleClick(Qt::LeftButton, _clickPos);
655     } else {
656       _clickMode = SingleClick;
657       _clickPos = event->scenePos();
658     }
659     _clickTimer.start();
660   }
661   if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
662     QGraphicsScene::mouseDoubleClickEvent(event);
663   else
664     QGraphicsScene::mousePressEvent(event);
665 }
666
667 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
668   // we check for doubleclick ourselves, so just call press handler
669   mousePressEvent(event);
670 }
671
672 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
673   if(event->button() == Qt::LeftButton && _leftButtonPressed) {
674     _leftButtonPressed = false;
675     if(_clickMode != NoClick) {
676       if(_clickMode == SingleClick)
677         clearSelection();
678       event->accept();
679       if(!_clickTimer.isActive())
680         handleClick(Qt::LeftButton, _clickPos);
681     } else {
682       // no click -> drag or selection move
683       if(isGloballySelecting()) {
684         selectionToClipboard(QClipboard::Selection);
685         _isSelecting = false;
686         event->accept();
687         return;
688       }
689     }
690   }
691   QGraphicsScene::mouseReleaseEvent(event);
692 }
693
694 void ChatScene::clickTimeout() {
695   if(!_leftButtonPressed && _clickMode == SingleClick)
696     handleClick(Qt::LeftButton, _clickPos);
697 }
698
699 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
700   if(button == Qt::LeftButton) {
701     clearSelection();
702
703     // Now send click down to items
704     ChatItem *chatItem = chatItemAt(scenePos);
705     if(chatItem) {
706       chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
707     }
708     _clickHandled = true;
709   }
710 }
711
712 void ChatScene::initiateDrag(QWidget *source) {
713   QDrag *drag = new QDrag(source);
714   QMimeData *mimeData = new QMimeData;
715   mimeData->setText(selection());
716   drag->setMimeData(mimeData);
717
718   drag->exec(Qt::CopyAction);
719 }
720
721 /******** SELECTIONS ******************************************************************************/
722
723 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
724   if(!hasSelection())
725     return;
726
727   stringToClipboard(selection(), mode);
728 }
729
730 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
731   QString str = str_;
732   // remove trailing linefeeds
733   if(str.endsWith('\n'))
734     str.chop(1);
735
736   switch(mode) {
737     case QClipboard::Clipboard:
738       QApplication::clipboard()->setText(str);
739       break;
740     case QClipboard::Selection:
741       if(QApplication::clipboard()->supportsSelection())
742         QApplication::clipboard()->setText(str, QClipboard::Selection);
743       break;
744     default:
745       break;
746   };
747 }
748
749 //!\brief Convert current selection to human-readable string.
750 QString ChatScene::selection() const {
751   //TODO Make selection format configurable!
752   if(hasGlobalSelection()) {
753     int start = qMin(_selectionStart, _selectionEnd);
754     int end = qMax(_selectionStart, _selectionEnd);
755     if(start < 0 || end >= _lines.count()) {
756       qDebug() << "Invalid selection range:" << start << end;
757       return QString();
758     }
759     QString result;
760     for(int l = start; l <= end; l++) {
761       if(_selectionMinCol == ChatLineModel::TimestampColumn)
762         result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
763       if(_selectionMinCol <= ChatLineModel::SenderColumn)
764         result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
765       result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
766     }
767     return result;
768   } else if(selectingItem())
769     return selectingItem()->selection();
770   return QString();
771 }
772
773 bool ChatScene::hasSelection() const {
774   return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
775 }
776
777 bool ChatScene::hasGlobalSelection() const {
778   return _selectionStart >= 0;
779 }
780
781 bool ChatScene::isGloballySelecting() const {
782   return _isSelecting;
783 }
784
785 void ChatScene::clearGlobalSelection() {
786   if(hasGlobalSelection()) {
787     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
788       _lines[l]->setSelected(false);
789     _isSelecting = false;
790     _selectionStart = -1;
791   }
792 }
793
794 void ChatScene::clearSelection() {
795   clearGlobalSelection();
796   if(selectingItem())
797     selectingItem()->clearSelection();
798 }
799
800 /******** *************************************************************************************/
801
802 void ChatScene::requestBacklog() {
803   MessageFilter *filter = qobject_cast<MessageFilter*>(model());
804   if(filter)
805     return filter->requestBacklog();
806   return;
807 }
808
809 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
810   if(x < _firstColHandle->x())
811     return ChatLineModel::TimestampColumn;
812   if(x < _secondColHandle->x())
813     return ChatLineModel::SenderColumn;
814
815   return ChatLineModel::ContentsColumn;
816 }
817
818 int ChatScene::rowByScenePos(qreal y) const {
819   // This is somewhat hacky... we look at the contents item that is at the given y position, since
820   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
821   // ChatItems cover their ChatLine, so we won't get to the latter directly.
822   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
823   if(!contentItem) return -1;
824   return contentItem->row();
825 }
826
827 void ChatScene::updateSceneRect(qreal width) {
828   if(_lines.isEmpty()) {
829     updateSceneRect(QRectF(0, 0, width, 0));
830     return;
831   }
832
833   // we hide day change messages at the top by making the scene rect smaller
834   // and by calling QGraphicsItem::hide() on all leading day change messages
835   // the first one is needed to ensure proper scrollbar ranges
836   // the second for cases where the viewport is larger then the set scenerect
837   //  (in this case the items are shown anyways)
838   if(_firstLineRow == -1) {
839     int numRows = model()->rowCount();
840     _firstLineRow = 0;
841     QModelIndex firstLineIdx;
842     while(_firstLineRow < numRows) {
843       firstLineIdx = model()->index(_firstLineRow, 0);
844       if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
845         break;
846       _lines.at(_firstLineRow)->hide();
847       _firstLineRow++;
848     }
849   }
850
851   // the following call should be safe. If it crashes something went wrong during insert/remove
852   if(_firstLineRow < _lines.count()) {
853     ChatLine *firstLine = _lines.at(_firstLineRow);
854     ChatLine *lastLine = _lines.last();
855     updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
856   } else {
857     // empty scene rect
858     updateSceneRect(QRectF(0, 0, width, 0));
859   }
860 }
861
862 void ChatScene::updateSceneRect(const QRectF &rect) {
863   _sceneRect = rect;
864   setSceneRect(rect);
865   update();
866 }
867
868 bool ChatScene::event(QEvent *e) {
869   if(e->type() == QEvent::ApplicationPaletteChange) {
870     _firstColHandle->setColor(QApplication::palette().windowText().color());
871     _secondColHandle->setColor(QApplication::palette().windowText().color());
872   }
873   return QGraphicsScene::event(e);
874 }
875
876 // ========================================
877 //  Webkit Only stuff
878 // ========================================
879 #ifdef HAVE_WEBKIT
880 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
881   if(!_showWebPreview)
882     return;
883
884   if(webPreview.urlRect != urlRect)
885     webPreview.urlRect = urlRect;
886
887   if(webPreview.parentItem != parentItem)
888     webPreview.parentItem = parentItem;
889
890   if(webPreview.url != url) {
891     webPreview.url = url;
892     // prepare to load a different URL
893     if(webPreview.previewItem) {
894       if(webPreview.previewItem->scene())
895         removeItem(webPreview.previewItem);
896       delete webPreview.previewItem;
897       webPreview.previewItem = 0;
898     }
899     webPreview.previewState = WebPreview::NoPreview;
900   }
901
902   if(webPreview.url.isEmpty())
903     return;
904
905   // qDebug() << Q_FUNC_INFO << webPreview.previewState;
906   switch(webPreview.previewState) {
907   case WebPreview::NoPreview:
908     webPreview.previewState = WebPreview::NewPreview;
909     webPreview.timer.start(500);
910     break;
911   case WebPreview::NewPreview:
912   case WebPreview::DelayPreview:
913   case WebPreview::ShowPreview:
914     // we're already waiting for the next step or showing the preview
915     break;
916   case WebPreview::HidePreview:
917     // we still have a valid preview
918     webPreview.previewState = WebPreview::DelayPreview;
919     webPreview.timer.start(1000);
920     break;
921   }
922   // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
923 }
924
925 void ChatScene::webPreviewNextStep() {
926   // qDebug() << Q_FUNC_INFO << webPreview.previewState;
927   switch(webPreview.previewState) {
928   case WebPreview::NoPreview:
929     break;
930   case WebPreview::NewPreview:
931     Q_ASSERT(!webPreview.previewItem);
932     webPreview.previewItem = new WebPreviewItem(webPreview.url);
933     webPreview.previewState = WebPreview::DelayPreview;
934     webPreview.timer.start(1000);
935     break;
936   case WebPreview::DelayPreview:
937     Q_ASSERT(webPreview.previewItem);
938     // calc position and show
939     {
940       qreal previewY = webPreview.urlRect.bottom();
941       qreal previewX = webPreview.urlRect.x();
942       if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
943         previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
944
945       if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
946         previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
947
948       webPreview.previewItem->setPos(previewX, previewY);
949     }
950     addItem(webPreview.previewItem);
951     webPreview.previewState = WebPreview::ShowPreview;
952     break;
953   case WebPreview::ShowPreview:
954     qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
955     qWarning() << "removing preview";
956     if(webPreview.previewItem && webPreview.previewItem->scene())
957       removeItem(webPreview.previewItem);
958     // Fall through to deletion!
959   case WebPreview::HidePreview:
960     if(webPreview.previewItem) {
961       delete webPreview.previewItem;
962       webPreview.previewItem = 0;
963     }
964     webPreview.parentItem = 0;
965     webPreview.url = QUrl();
966     webPreview.urlRect = QRectF();
967     webPreview.previewState = WebPreview::NoPreview;
968   }
969   // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
970 }
971
972 void ChatScene::clearWebPreview(ChatItem *parentItem) {
973   // qDebug() << Q_FUNC_INFO << webPreview.previewState;
974   switch(webPreview.previewState) {
975   case WebPreview::NewPreview:
976     webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
977     break;
978   case WebPreview::ShowPreview:
979     if(parentItem == 0 || webPreview.parentItem == parentItem) {
980       if(webPreview.previewItem && webPreview.previewItem->scene())
981         removeItem(webPreview.previewItem);
982     }
983     // fall through into to set hidden state
984   case WebPreview::DelayPreview:
985     // we're just loading, so haven't shown the preview yet.
986     webPreview.previewState = WebPreview::HidePreview;
987     webPreview.timer.start(5000);
988     break;
989   case WebPreview::NoPreview:
990   case WebPreview::HidePreview:
991     break;
992   }
993   // qDebug() << "  new State:" << webPreview.previewState << webPreview.timer.isActive();
994 }
995 #endif
996
997 // ========================================
998 //  end of webkit only
999 // ========================================
1000
1001 void ChatScene::showWebPreviewChanged() {
1002   ChatViewSettings settings;
1003   _showWebPreview = settings.showWebPreview();
1004 }