1 /***************************************************************************
2 * Copyright (C) 2005-2012 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QApplication>
24 #include <QGraphicsSceneMouseEvent>
28 #include <QPersistentModelIndex>
42 #include "chatlinemodelitem.h"
43 #include "chatscene.h"
46 #include "clientbacklogmanager.h"
47 #include "columnhandleitem.h"
48 #include "contextmenuactionprovider.h"
49 #include "iconloader.h"
51 #include "markerlineitem.h"
52 #include "messagefilter.h"
54 #include "qtuistyle.h"
55 #include "chatviewsettings.h"
56 #include "webpreviewitem.h"
58 const qreal minContentsWidth = 200;
60 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
61 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
65 _singleBufferId(BufferId()),
66 _sceneRect(0, 0, width, 0),
69 _markerLine(new MarkerLineItem(width)),
70 _markerLineVisible(false),
71 _markerLineValid(false),
72 _markerLineJumpPending(false),
73 _cutoffMode(CutoffRight),
79 _leftButtonPressed(false)
81 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
82 if(filter && filter->isSingleBufferFilter()) {
83 _singleBufferId = filter->singleBufferId();
87 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
89 ChatViewSettings defaultSettings;
90 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
91 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
93 ChatViewSettings viewSettings(this);
94 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
95 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
97 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
98 addItem(_firstColHandle);
99 _firstColHandle->setXPos(_firstColHandlePos);
100 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
101 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
103 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
104 addItem(_secondColHandle);
105 _secondColHandle->setXPos(_secondColHandlePos);
106 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
108 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
112 if(model->rowCount() > 0)
113 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
115 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
116 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
117 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
118 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
119 connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
120 this, SLOT(rowsRemoved()));
121 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
124 webPreview.timer.setSingleShot(true);
125 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
127 _showWebPreview = defaultSettings.showWebPreview();
128 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
130 _clickTimer.setInterval(QApplication::doubleClickInterval());
131 _clickTimer.setSingleShot(true);
132 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
134 setItemIndexMethod(QGraphicsScene::NoIndex);
137 ChatScene::~ChatScene() {
140 ChatView *ChatScene::chatView() const {
144 ColumnHandleItem *ChatScene::firstColumnHandle() const {
145 return _firstColHandle;
148 ColumnHandleItem *ChatScene::secondColumnHandle() const {
149 return _secondColHandle;
152 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const {
156 QList<ChatLine*>::ConstIterator start = _lines.begin();
157 QList<ChatLine*>::ConstIterator end = _lines.end();
158 QList<ChatLine*>::ConstIterator middle;
160 int n = int(end - start);
165 middle = start + half;
166 if((*middle)->msgId() < msgId) {
174 if(start != end && (*start)->msgId() == msgId && (ignoreDayChange? (*start)->msgType() != Message::DayChange : true))
180 if(start == _lines.begin()) // not (yet?) in our scene
183 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
185 if(start == end) { // higher than last element
187 return _lines.last();
189 for(int i = _lines.count() -1; i >= 0; i--) {
190 if(_lines.at(i)->msgType() != Message::DayChange)
196 // return the next-lower line
201 if((*(--start))->msgType() != Message::DayChange)
203 } while(start != _lines.begin());
207 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
208 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
209 ChatLine *line = qgraphicsitem_cast<ChatLine*>(item);
211 return line->itemAt(line->mapFromScene(scenePos));
216 bool ChatScene::containsBuffer(const BufferId &id) const {
217 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
219 return filter->containsBuffer(id);
224 void ChatScene::setMarkerLineVisible(bool visible) {
225 _markerLineVisible = visible;
226 if(visible && _markerLineValid)
227 markerLine()->setVisible(true);
229 markerLine()->setVisible(false);
232 void ChatScene::setMarkerLine(MsgId msgId) {
233 if(!isSingleBufferScene())
237 msgId = Client::markerLine(singleBufferId());
239 if(msgId.isValid()) {
240 ChatLine *line = chatLine(msgId, false, true);
242 markerLine()->setChatLine(line);
243 // if this was the last line, we won't see it because it's outside the sceneRect
244 // .. which is exactly what we want :)
245 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
247 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
248 if(markerLine()->pos().y() >= sceneRect().y()) {
249 _markerLineValid = true;
250 if(_markerLineVisible)
251 markerLine()->setVisible(true);
252 if(_markerLineJumpPending) {
253 _markerLineJumpPending = false;
254 if(markerLine()->isVisible()) {
255 markerLine()->ensureVisible(QRectF(), 50, 50);
262 _markerLineValid = false;
263 markerLine()->setVisible(false);
266 void ChatScene::jumpToMarkerLine(bool requestBacklog) {
267 if(!isSingleBufferScene())
270 if(markerLine()->isVisible()) {
271 markerLine()->ensureVisible(QRectF(), 50, 50);
274 if(!_markerLineValid && requestBacklog) {
275 MsgId msgId = Client::markerLine(singleBufferId());
276 if(msgId.isValid()) {
277 _markerLineJumpPending = true;
278 Client::backlogManager()->requestBacklog(singleBufferId(), msgId, -1, -1, 0);
280 // If we filtered out the lastSeenMsg (by changing filters after setting it), we'd never jump because the above request
281 // won't fetch any prior lines. Thus, trigger a dynamic backlog request just in case, so repeated
282 // jump tries will eventually cause enough backlog to be fetched.
283 // This is a bit hackish, but not wasteful, as jumping to the top of the ChatView would trigger a dynamic fetch anyway.
284 this->requestBacklog();
289 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
292 // QModelIndex sidx = model()->index(start, 2);
293 // QModelIndex eidx = model()->index(end, 2);
294 // qDebug() << "rowsInserted:";
296 // QModelIndex ssidx = model()->index(start - 1, 2);
297 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
298 // << ssidx.data(Qt::DisplayRole).toString();
300 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
301 // << sidx.data(Qt::DisplayRole).toString();
302 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
303 // << eidx.data(Qt::DisplayRole).toString();
304 // if(end + 1 < model()->rowCount()) {
305 // QModelIndex eeidx = model()->index(end + 1, 2);
306 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
307 // << eeidx.data(Qt::DisplayRole).toString();
312 qreal width = _sceneRect.width();
313 bool atBottom = (start == _lines.count());
314 bool atTop = !atBottom && (start == 0);
316 if(start < _lines.count()) {
317 y = _lines.value(start)->y();
318 } else if(atBottom && !_lines.isEmpty()) {
319 y = _lines.last()->y() + _lines.last()->height();
322 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
323 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
324 qreal timestampWidth = firstColumnHandle()->sceneLeft();
325 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
326 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
329 for(int i = end; i >= start; i--) {
330 ChatLine *line = new ChatLine(i, model(),
332 timestampWidth, senderWidth, contentsWidth,
333 senderPos, contentsPos);
335 line->setPos(0, y-h);
336 _lines.insert(start, line);
340 for(int i = start; i <= end; i++) {
341 ChatLine *line = new ChatLine(i, model(),
343 timestampWidth, senderWidth, contentsWidth,
344 senderPos, contentsPos);
345 line->setPos(0, y+h);
347 _lines.insert(i, line);
352 // update existing items
353 for(int i = end+1; i < _lines.count(); i++) {
354 _lines[i]->setRow(i);
358 if(_selectionStart >= 0) {
359 int offset = end - start + 1;
360 int oldStart = _selectionStart;
361 if(_selectionStart >= start)
362 _selectionStart += offset;
363 if(_selectionEnd >= start) {
364 _selectionEnd += offset;
365 if(_selectionStart == oldStart)
366 for(int i = start; i < start + offset; i++)
367 _lines[i]->setSelected(true);
369 if(_firstSelectionRow >= start)
370 _firstSelectionRow += offset;
373 // neither pre- or append means we have to do dirty work: move items...
374 if(!(atTop || atBottom)) {
376 for(int i = 0; i <= end; i++) {
378 line->setPos(0, line->pos().y() - h);
379 if(line == markerLine()->chatLine())
380 markerLine()->setPos(line->pos() + QPointF(0, line->height()));
384 // check if all went right
385 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
387 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
388 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
389 // 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();
390 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
391 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
395 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
396 // if(end + 1 < _lines.count()) {
397 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
398 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
399 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
400 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
401 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
407 if(start < _firstLineRow) {
408 int prevFirstLineRow = _firstLineRow + (end - start + 1);
409 for(int i = end + 1; i < prevFirstLineRow; i++) {
410 _lines.at(i)->show();
413 // force new search for first proper line
418 emit lastLineChanged(_lines.last(), h);
421 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
422 if(!_markerLineValid)
426 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
429 qreal h = 0; // total height of removed items;
431 bool atTop = (start == 0);
432 bool atBottom = (end == _lines.count() - 1);
436 int row = _selectingItem->row();
437 if(row >= start && row <= end)
441 // remove items from scene
442 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
443 int lineCount = start;
444 while(lineIter != _lines.end() && lineCount <= end) {
445 if((*lineIter) == markerLine()->chatLine())
446 markerLine()->setChatLine(0);
447 h += (*lineIter)->height();
449 lineIter = _lines.erase(lineIter);
453 // update rows of remaining chatlines
454 for(int i = start; i < _lines.count(); i++) {
455 _lines.at(i)->setRow(i);
459 if(_selectionStart >= 0) {
460 int offset = end - start + 1;
461 if(_selectionStart >= start)
462 _selectionStart = qMax(_selectionStart - offset, start);
463 if(_selectionEnd >= start)
464 _selectionEnd -= offset;
465 if(_firstSelectionRow >= start)
466 _firstSelectionRow -= offset;
468 if(_selectionEnd < _selectionStart) {
469 _isSelecting = false;
470 _selectionStart = -1;
474 // neither removing at bottom or top means we have to move items...
475 if(!(atTop || atBottom)) {
478 int moveEnd = _lines.count() - 1;
479 if(start < _lines.count() - start) {
488 for(int i = moveStart; i <= moveEnd; i++) {
490 line->setPos(0, line->pos().y() + offset);
494 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
497 // when searching for the first non-date-line we have to take into account that our
498 // model still contains the just removed lines so we cannot simply call updateSceneRect()
499 int numRows = model()->rowCount();
500 QModelIndex firstLineIdx;
502 bool needOffset = false;
505 if(_firstLineRow >= start && _firstLineRow <= end) {
506 _firstLineRow = end + 1;
509 firstLineIdx = model()->index(_firstLineRow, 0);
510 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
513 _firstLineRow -= end - start + 1;
517 void ChatScene::rowsRemoved() {
518 // move the marker line if necessary
522 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
523 layout(tl.row(), br.row(), _sceneRect.width());
526 void ChatScene::updateForViewport(qreal width, qreal height) {
527 _viewportHeight = height;
531 void ChatScene::setWidth(qreal width) {
532 if(width == _sceneRect.width())
534 layout(0, _lines.count()-1, width);
537 void ChatScene::layout(int start, int end, qreal width) {
538 // clock_t startT = clock();
540 // disabling the index while doing this complex updates is about
541 // 2 to 10 times faster!
542 //setItemIndexMethod(QGraphicsScene::NoIndex);
546 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
547 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
548 while(row >= start) {
549 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
553 // remaining items don't need geometry changes, but maybe repositioning?
554 ChatLine *line = _lines.at(row);
555 qreal offset = linePos - (line->scenePos().y() + line->height());
558 line = _lines.at(row--);
559 line->setPos(0, line->scenePos().y() + offset);
565 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
567 updateSceneRect(width);
570 emit layoutChanged();
572 // clock_t endT = clock();
573 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
576 void ChatScene::firstHandlePositionChanged(qreal xpos) {
577 if(_firstColHandlePos == xpos)
580 _firstColHandlePos = xpos >= 0 ? xpos : 0;
581 ChatViewSettings viewSettings(this);
582 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
583 ChatViewSettings defaultSettings;
584 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
586 // clock_t startT = clock();
588 // disabling the index while doing this complex updates is about
589 // 2 to 10 times faster!
590 //setItemIndexMethod(QGraphicsScene::NoIndex);
592 QList<ChatLine *>::iterator lineIter = _lines.end();
593 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
594 qreal timestampWidth = firstColumnHandle()->sceneLeft();
595 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
596 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
598 while(lineIter != lineIterBegin) {
600 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
602 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
606 // clock_t endT = clock();
607 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
610 void ChatScene::secondHandlePositionChanged(qreal xpos) {
611 if(_secondColHandlePos == xpos)
614 _secondColHandlePos = xpos;
615 ChatViewSettings viewSettings(this);
616 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
617 ChatViewSettings defaultSettings;
618 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
620 // clock_t startT = clock();
622 // disabling the index while doing this complex updates is about
623 // 2 to 10 times faster!
624 //setItemIndexMethod(QGraphicsScene::NoIndex);
626 QList<ChatLine *>::iterator lineIter = _lines.end();
627 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
628 qreal linePos = _sceneRect.y() + _sceneRect.height();
629 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
630 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
631 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
632 while(lineIter != lineIterBegin) {
634 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
636 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
640 emit layoutChanged();
642 // clock_t endT = clock();
643 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
646 void ChatScene::setHandleXLimits() {
647 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
648 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
652 void ChatScene::setSelectingItem(ChatItem *item) {
653 if(_selectingItem) _selectingItem->clearSelection();
654 _selectingItem = item;
657 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
658 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
659 _selectionStartCol = _selectionMinCol = item->column();
661 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
662 updateSelection(item->mapToScene(itemPos));
665 void ChatScene::updateSelection(const QPointF &pos) {
666 int curRow = rowByScenePos(pos);
667 if(curRow < 0) return;
668 int curColumn = (int)columnByScenePos(pos);
669 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
670 if(minColumn != _selectionMinCol) {
671 _selectionMinCol = minColumn;
672 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
673 _lines[l]->setSelected(true, minColumn);
676 int newstart = qMin(curRow, _firstSelectionRow);
677 int newend = qMax(curRow, _firstSelectionRow);
678 if(newstart < _selectionStart) {
679 for(int l = newstart; l < _selectionStart; l++)
680 _lines[l]->setSelected(true, minColumn);
682 if(newstart > _selectionStart) {
683 for(int l = _selectionStart; l < newstart; l++)
684 _lines[l]->setSelected(false);
686 if(newend > _selectionEnd) {
687 for(int l = _selectionEnd+1; l <= newend; l++)
688 _lines[l]->setSelected(true, minColumn);
690 if(newend < _selectionEnd) {
691 for(int l = newend+1; l <= _selectionEnd; l++)
692 _lines[l]->setSelected(false);
695 _selectionStart = newstart;
696 _selectionEnd = newend;
698 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
699 if(!_selectingItem) {
700 // _selectingItem has been removed already
703 _lines[curRow]->setSelected(false);
704 _isSelecting = false;
705 _selectionStart = -1;
706 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
710 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
711 ChatItem *chatItem = chatItemAt(pos);
714 if(hasGlobalSelection()) {
715 int row = chatItem->row();
716 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
717 return columnByScenePos(pos) >= _selectionMinCol;
719 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
724 bool ChatScene::isScrollingAllowed() const {
728 // TODO: Handle clicks and single-item selections too
733 /******** MOUSE HANDLING **************************************************************************/
735 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
736 QPointF pos = event->scenePos();
739 // zoom actions and similar
740 chatView()->addActionsToMenu(&menu, pos);
743 if(isPosOverSelection(pos))
744 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
745 this, SLOT(selectionToClipboard()),
748 // item-specific options (select link etc)
749 ChatItem *item = chatItemAt(pos);
751 item->addActionsToMenu(&menu, item->mapFromScene(pos));
753 // no item -> default scene actions
754 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
756 if (QtUi::mainWindow()->menuBar()->isHidden())
757 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
759 menu.exec(event->screenPos());
763 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
764 if(event->buttons() == Qt::LeftButton) {
765 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
766 if(_clickTimer.isActive())
768 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
769 initiateDrag(event->widget());
771 _clickMode = DragStartClick;
772 handleClick(Qt::LeftButton, _clickPos);
774 _clickMode = NoClick;
777 updateSelection(event->scenePos());
778 emit mouseMoveWhileSelecting(event->scenePos());
780 } else if(_clickHandled && _clickMode < DoubleClick)
781 QGraphicsScene::mouseMoveEvent(event);
783 QGraphicsScene::mouseMoveEvent(event);
786 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
787 if(event->buttons() == Qt::LeftButton) {
788 _leftButtonPressed = true;
789 _clickHandled = false;
790 if(!isPosOverSelection(event->scenePos())) {
791 // immediately clear selection if clicked outside; otherwise, wait for potential drag
794 if(_clickMode != NoClick && _clickTimer.isActive()) {
796 case NoClick: _clickMode = SingleClick; break;
797 case SingleClick: _clickMode = DoubleClick; break;
798 case DoubleClick: _clickMode = TripleClick; break;
799 case TripleClick: _clickMode = DoubleClick; break;
800 case DragStartClick: break;
802 handleClick(Qt::LeftButton, _clickPos);
804 _clickMode = SingleClick;
805 _clickPos = event->scenePos();
809 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
810 QGraphicsScene::mouseDoubleClickEvent(event);
812 QGraphicsScene::mousePressEvent(event);
815 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
816 // we check for doubleclick ourselves, so just call press handler
817 mousePressEvent(event);
820 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
821 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
822 _leftButtonPressed = false;
823 if(_clickMode != NoClick) {
824 if(_clickMode == SingleClick)
827 if(!_clickTimer.isActive())
828 handleClick(Qt::LeftButton, _clickPos);
830 // no click -> drag or selection move
831 if(isGloballySelecting()) {
832 selectionToClipboard(QClipboard::Selection);
833 _isSelecting = false;
839 QGraphicsScene::mouseReleaseEvent(event);
842 void ChatScene::clickTimeout() {
843 if(!_leftButtonPressed && _clickMode == SingleClick)
844 handleClick(Qt::LeftButton, _clickPos);
847 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
848 if(button == Qt::LeftButton) {
851 // Now send click down to items
852 ChatItem *chatItem = chatItemAt(scenePos);
854 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
856 _clickHandled = true;
860 void ChatScene::initiateDrag(QWidget *source) {
861 QDrag *drag = new QDrag(source);
862 QMimeData *mimeData = new QMimeData;
863 mimeData->setText(selection());
864 drag->setMimeData(mimeData);
866 drag->exec(Qt::CopyAction);
869 /******** SELECTIONS ******************************************************************************/
871 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
875 stringToClipboard(selection(), mode);
878 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
880 // remove trailing linefeeds
881 if(str.endsWith('\n'))
885 case QClipboard::Clipboard:
886 QApplication::clipboard()->setText(str);
888 case QClipboard::Selection:
889 if(QApplication::clipboard()->supportsSelection())
890 QApplication::clipboard()->setText(str, QClipboard::Selection);
897 //!\brief Convert current selection to human-readable string.
898 QString ChatScene::selection() const {
899 //TODO Make selection format configurable!
900 if(hasGlobalSelection()) {
901 int start = qMin(_selectionStart, _selectionEnd);
902 int end = qMax(_selectionStart, _selectionEnd);
903 if(start < 0 || end >= _lines.count()) {
904 qDebug() << "Invalid selection range:" << start << end;
908 for(int l = start; l <= end; l++) {
909 if(_selectionMinCol == ChatLineModel::TimestampColumn)
910 result += _lines[l]->item(ChatLineModel::TimestampColumn)->data(MessageModel::DisplayRole).toString() + " ";
911 if(_selectionMinCol <= ChatLineModel::SenderColumn)
912 result += _lines[l]->item(ChatLineModel::SenderColumn)->data(MessageModel::DisplayRole).toString() + " ";
913 result += _lines[l]->item(ChatLineModel::ContentsColumn)->data(MessageModel::DisplayRole).toString() + "\n";
916 } else if(selectingItem())
917 return selectingItem()->selection();
921 bool ChatScene::hasSelection() const {
922 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
925 bool ChatScene::hasGlobalSelection() const {
926 return _selectionStart >= 0;
929 bool ChatScene::isGloballySelecting() const {
933 void ChatScene::clearGlobalSelection() {
934 if(hasGlobalSelection()) {
935 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
936 _lines[l]->setSelected(false);
937 _isSelecting = false;
938 _selectionStart = -1;
942 void ChatScene::clearSelection() {
943 clearGlobalSelection();
945 selectingItem()->clearSelection();
948 /******** *************************************************************************************/
950 void ChatScene::requestBacklog() {
951 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
953 return filter->requestBacklog();
957 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
958 if(x < _firstColHandle->x())
959 return ChatLineModel::TimestampColumn;
960 if(x < _secondColHandle->x())
961 return ChatLineModel::SenderColumn;
963 return ChatLineModel::ContentsColumn;
966 int ChatScene::rowByScenePos(qreal y) const {
967 QList<QGraphicsItem*> itemList = items(QPointF(0, y));
969 // ChatLine should be at the bottom of the list
970 for(int i = itemList.count()-1; i >= 0; i--) {
971 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
978 void ChatScene::updateSceneRect(qreal width) {
979 if(_lines.isEmpty()) {
980 updateSceneRect(QRectF(0, 0, width, 0));
984 // we hide day change messages at the top by making the scene rect smaller
985 // and by calling QGraphicsItem::hide() on all leading day change messages
986 // the first one is needed to ensure proper scrollbar ranges
987 // the second for cases where the viewport is larger then the set scenerect
988 // (in this case the items are shown anyways)
989 if(_firstLineRow == -1) {
990 int numRows = model()->rowCount();
992 QModelIndex firstLineIdx;
993 while(_firstLineRow < numRows) {
994 firstLineIdx = model()->index(_firstLineRow, 0);
995 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
997 _lines.at(_firstLineRow)->hide();
1002 // the following call should be safe. If it crashes something went wrong during insert/remove
1003 if(_firstLineRow < _lines.count()) {
1004 ChatLine *firstLine = _lines.at(_firstLineRow);
1005 ChatLine *lastLine = _lines.last();
1006 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
1009 updateSceneRect(QRectF(0, 0, width, 0));
1013 void ChatScene::updateSceneRect(const QRectF &rect) {
1019 // ========================================
1020 // Webkit Only stuff
1021 // ========================================
1023 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
1024 if(!_showWebPreview)
1027 if(webPreview.urlRect != urlRect)
1028 webPreview.urlRect = urlRect;
1030 if(webPreview.parentItem != parentItem)
1031 webPreview.parentItem = parentItem;
1033 if(webPreview.url != url) {
1034 webPreview.url = url;
1035 // prepare to load a different URL
1036 if(webPreview.previewItem) {
1037 if(webPreview.previewItem->scene())
1038 removeItem(webPreview.previewItem);
1039 delete webPreview.previewItem;
1040 webPreview.previewItem = 0;
1042 webPreview.previewState = WebPreview::NoPreview;
1045 if(webPreview.url.isEmpty())
1048 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1049 switch(webPreview.previewState) {
1050 case WebPreview::NoPreview:
1051 webPreview.previewState = WebPreview::NewPreview;
1052 webPreview.timer.start(500);
1054 case WebPreview::NewPreview:
1055 case WebPreview::DelayPreview:
1056 case WebPreview::ShowPreview:
1057 // we're already waiting for the next step or showing the preview
1059 case WebPreview::HidePreview:
1060 // we still have a valid preview
1061 webPreview.previewState = WebPreview::DelayPreview;
1062 webPreview.timer.start(1000);
1065 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1068 void ChatScene::webPreviewNextStep() {
1069 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1070 switch(webPreview.previewState) {
1071 case WebPreview::NoPreview:
1073 case WebPreview::NewPreview:
1074 Q_ASSERT(!webPreview.previewItem);
1075 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1076 webPreview.previewState = WebPreview::DelayPreview;
1077 webPreview.timer.start(1000);
1079 case WebPreview::DelayPreview:
1080 Q_ASSERT(webPreview.previewItem);
1081 // calc position and show
1083 qreal previewY = webPreview.urlRect.bottom();
1084 qreal previewX = webPreview.urlRect.x();
1085 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1086 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1088 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1089 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1091 webPreview.previewItem->setPos(previewX, previewY);
1093 addItem(webPreview.previewItem);
1094 webPreview.previewState = WebPreview::ShowPreview;
1096 case WebPreview::ShowPreview:
1097 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1098 qWarning() << "removing preview";
1099 if(webPreview.previewItem && webPreview.previewItem->scene())
1100 removeItem(webPreview.previewItem);
1101 // Fall through to deletion!
1102 case WebPreview::HidePreview:
1103 if(webPreview.previewItem) {
1104 delete webPreview.previewItem;
1105 webPreview.previewItem = 0;
1107 webPreview.parentItem = 0;
1108 webPreview.url = QUrl();
1109 webPreview.urlRect = QRectF();
1110 webPreview.previewState = WebPreview::NoPreview;
1112 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1115 void ChatScene::clearWebPreview(ChatItem *parentItem) {
1116 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1117 switch(webPreview.previewState) {
1118 case WebPreview::NewPreview:
1119 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1121 case WebPreview::ShowPreview:
1122 if(parentItem == 0 || webPreview.parentItem == parentItem) {
1123 if(webPreview.previewItem && webPreview.previewItem->scene())
1124 removeItem(webPreview.previewItem);
1126 // fall through into to set hidden state
1127 case WebPreview::DelayPreview:
1128 // we're just loading, so haven't shown the preview yet.
1129 webPreview.previewState = WebPreview::HidePreview;
1130 webPreview.timer.start(5000);
1132 case WebPreview::NoPreview:
1133 case WebPreview::HidePreview:
1136 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1140 // ========================================
1141 // end of webkit only
1142 // ========================================
1144 void ChatScene::showWebPreviewChanged() {
1145 ChatViewSettings settings;
1146 _showWebPreview = settings.showWebPreview();