1 /***************************************************************************
2 * Copyright (C) 2005-2010 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>
27 #include <QPersistentModelIndex>
41 #include "chatlinemodelitem.h"
42 #include "chatscene.h"
45 #include "clientbacklogmanager.h"
46 #include "columnhandleitem.h"
47 #include "contextmenuactionprovider.h"
48 #include "iconloader.h"
50 #include "markerlineitem.h"
51 #include "messagefilter.h"
53 #include "qtuistyle.h"
54 #include "chatviewsettings.h"
55 #include "webpreviewitem.h"
57 const qreal minContentsWidth = 200;
59 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
60 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
64 _singleBufferId(BufferId()),
65 _sceneRect(0, 0, width, 0),
68 _markerLine(new MarkerLineItem(width)),
69 _markerLineValid(false),
70 _markerLineVisible(false),
71 _cutoffMode(CutoffRight),
77 _leftButtonPressed(false)
79 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
80 if(filter && filter->isSingleBufferFilter()) {
81 _singleBufferId = filter->singleBufferId();
85 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _markerLine, SLOT(sceneRectChanged(const QRectF &)));
87 ChatViewSettings defaultSettings;
88 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
89 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
91 ChatViewSettings viewSettings(this);
92 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
93 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
95 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
96 addItem(_firstColHandle);
97 _firstColHandle->setXPos(_firstColHandlePos);
98 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
99 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
101 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
102 addItem(_secondColHandle);
103 _secondColHandle->setXPos(_secondColHandlePos);
104 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
106 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
110 if(model->rowCount() > 0)
111 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
113 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
114 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
115 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
116 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
117 connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
118 this, SLOT(rowsRemoved()));
119 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
122 webPreview.timer.setSingleShot(true);
123 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
125 _showWebPreview = defaultSettings.showWebPreview();
126 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
128 _clickTimer.setInterval(QApplication::doubleClickInterval());
129 _clickTimer.setSingleShot(true);
130 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
132 setItemIndexMethod(QGraphicsScene::NoIndex);
135 ChatScene::~ChatScene() {
138 ChatView *ChatScene::chatView() const {
142 ColumnHandleItem *ChatScene::firstColumnHandle() const {
143 return _firstColHandle;
146 ColumnHandleItem *ChatScene::secondColumnHandle() const {
147 return _secondColHandle;
150 ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact) const {
154 QList<ChatLine*>::ConstIterator start = _lines.begin();
155 QList<ChatLine*>::ConstIterator end = _lines.end();
156 QList<ChatLine*>::ConstIterator middle;
158 int n = int(end - start);
163 middle = start + half;
164 if((*middle)->msgId() < msgId) {
172 if(start != end && (*start)->msgId() == msgId)
178 // if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
179 if(start == end) // higher than last element
180 return _lines.last();
182 if(start == _lines.begin()) // not (yet?) in our scene
185 // return the next-lower line
189 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
190 foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
191 ChatLine *line = qgraphicsitem_cast<ChatLine*>(item);
193 return line->itemAt(line->mapFromScene(scenePos));
198 bool ChatScene::containsBuffer(const BufferId &id) const {
199 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
201 return filter->containsBuffer(id);
206 void ChatScene::setMarkerLineVisible(bool visible) {
207 _markerLineVisible = visible;
208 if(visible && _markerLineValid)
209 _markerLine->setVisible(true);
211 _markerLine->setVisible(false);
214 void ChatScene::setMarkerLine(MsgId msgId) {
215 if(msgId.isValid()) {
216 ChatLine *line = chatLine(msgId, false);
218 // if this was the last line, we won't see it because it's outside the sceneRect
219 // .. which is exactly what we want :)
220 _markerLine->setPos(line->pos() + QPointF(0, line->height()));
222 // DayChange messages might have been hidden outside the scene rect, don't make the markerline visible then!
223 if(_markerLine->pos().y() >= sceneRect().y()) {
224 _markerLineValid = true;
225 if(_markerLineVisible)
226 _markerLine->setVisible(true);
231 _markerLineValid = false;
232 _markerLine->setVisible(false);
235 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
239 // QModelIndex sidx = model()->index(start, 2);
240 // QModelIndex eidx = model()->index(end, 2);
241 // qDebug() << "rowsInserted:";
243 // QModelIndex ssidx = model()->index(start - 1, 2);
244 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
245 // << ssidx.data(Qt::DisplayRole).toString();
247 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
248 // << sidx.data(Qt::DisplayRole).toString();
249 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
250 // << eidx.data(Qt::DisplayRole).toString();
251 // if(end + 1 < model()->rowCount()) {
252 // QModelIndex eeidx = model()->index(end + 1, 2);
253 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
254 // << eeidx.data(Qt::DisplayRole).toString();
259 qreal width = _sceneRect.width();
260 bool atBottom = (start == _lines.count());
261 bool atTop = !atBottom && (start == 0);
263 if(start < _lines.count()) {
264 y = _lines.value(start)->y();
265 } else if(atBottom && !_lines.isEmpty()) {
266 y = _lines.last()->y() + _lines.last()->height();
269 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
270 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
271 qreal timestampWidth = firstColumnHandle()->sceneLeft();
272 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
273 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
276 for(int i = end; i >= start; i--) {
277 ChatLine *line = new ChatLine(i, model(),
279 timestampWidth, senderWidth, contentsWidth,
280 senderPos, contentsPos);
282 line->setPos(0, y-h);
283 _lines.insert(start, line);
287 for(int i = start; i <= end; i++) {
288 ChatLine *line = new ChatLine(i, model(),
290 timestampWidth, senderWidth, contentsWidth,
291 senderPos, contentsPos);
292 line->setPos(0, y+h);
294 _lines.insert(i, line);
299 // update existing items
300 for(int i = end+1; i < _lines.count(); i++) {
301 _lines[i]->setRow(i);
305 if(_selectionStart >= 0) {
306 int offset = end - start + 1;
307 int oldStart = _selectionStart;
308 if(_selectionStart >= start)
309 _selectionStart += offset;
310 if(_selectionEnd >= start) {
311 _selectionEnd += offset;
312 if(_selectionStart == oldStart)
313 for(int i = start; i < start + offset; i++)
314 _lines[i]->setSelected(true);
316 if(_firstSelectionRow >= start)
317 _firstSelectionRow += offset;
320 // neither pre- or append means we have to do dirty work: move items...
321 if(!(atTop || atBottom)) {
323 for(int i = 0; i <= end; i++) {
325 line->setPos(0, line->pos().y() - h);
329 // check if all went right
330 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
332 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
333 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
334 // 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();
335 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
336 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
340 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
341 // if(end + 1 < _lines.count()) {
342 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
343 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
344 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
345 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
346 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
352 if(start < _firstLineRow) {
353 int prevFirstLineRow = _firstLineRow + (end - start + 1);
354 for(int i = end + 1; i < prevFirstLineRow; i++) {
355 _lines.at(i)->show();
358 // force new search for first proper line
363 emit lastLineChanged(_lines.last(), h);
366 // now move the marker line if necessary. we don't need to do anything if we appended lines though...
367 if(isSingleBufferScene()) {
368 if(!_markerLineValid || !atBottom) {
369 MsgId msgId = Client::markerLine(singleBufferId());
370 setMarkerLine(msgId);
375 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
378 qreal h = 0; // total height of removed items;
380 bool atTop = (start == 0);
381 bool atBottom = (end == _lines.count() - 1);
382 bool moveTop = false;
386 int row = _selectingItem->row();
387 if(row >= start && row <= end)
391 // remove items from scene
392 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
393 int lineCount = start;
394 while(lineIter != _lines.end() && lineCount <= end) {
395 h += (*lineIter)->height();
397 lineIter = _lines.erase(lineIter);
401 // update rows of remaining chatlines
402 for(int i = start; i < _lines.count(); i++) {
403 _lines.at(i)->setRow(i);
407 if(_selectionStart >= 0) {
408 int offset = end - start + 1;
409 if(_selectionStart >= start)
410 _selectionStart = qMax(_selectionStart -= offset, start);
411 if(_selectionEnd >= start)
412 _selectionEnd -= offset;
413 if(_firstSelectionRow >= start)
414 _firstSelectionRow -= offset;
416 if(_selectionEnd < _selectionStart) {
417 _isSelecting = false;
418 _selectionStart = -1;
422 // neither removing at bottom or top means we have to move items...
423 if(!(atTop || atBottom)) {
426 int moveEnd = _lines.count() - 1;
427 if(start < _lines.count() - start) {
437 for(int i = moveStart; i <= moveEnd; i++) {
439 line->setPos(0, line->pos().y() + offset);
443 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
446 // when searching for the first non-date-line we have to take into account that our
447 // model still contains the just removed lines so we cannot simply call updateSceneRect()
448 int numRows = model()->rowCount();
449 QModelIndex firstLineIdx;
451 bool needOffset = false;
454 if(_firstLineRow >= start && _firstLineRow <= end) {
455 _firstLineRow = end + 1;
458 firstLineIdx = model()->index(_firstLineRow, 0);
459 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
462 _firstLineRow -= end - start + 1;
466 void ChatScene::rowsRemoved() {
467 // move the marker line if necessary
468 if(isSingleBufferScene()) {
469 MsgId msgId = Client::markerLine(singleBufferId());
470 setMarkerLine(msgId);
474 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
475 layout(tl.row(), br.row(), _sceneRect.width());
478 void ChatScene::updateForViewport(qreal width, qreal height) {
479 _viewportHeight = height;
483 void ChatScene::setWidth(qreal width) {
484 if(width == _sceneRect.width())
486 layout(0, _lines.count()-1, width);
489 void ChatScene::layout(int start, int end, qreal width) {
490 // clock_t startT = clock();
492 // disabling the index while doing this complex updates is about
493 // 2 to 10 times faster!
494 //setItemIndexMethod(QGraphicsScene::NoIndex);
498 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
499 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
500 while(row >= start) {
501 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
505 // remaining items don't need geometry changes, but maybe repositioning?
506 ChatLine *line = _lines.at(row);
507 qreal offset = linePos - (line->scenePos().y() + line->height());
510 line = _lines.at(row--);
511 line->setPos(0, line->scenePos().y() + offset);
517 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
519 updateSceneRect(width);
521 emit layoutChanged();
523 // clock_t endT = clock();
524 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
527 void ChatScene::firstHandlePositionChanged(qreal xpos) {
528 if(_firstColHandlePos == xpos)
531 _firstColHandlePos = xpos >= 0 ? xpos : 0;
532 ChatViewSettings viewSettings(this);
533 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
534 ChatViewSettings defaultSettings;
535 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
537 // clock_t startT = clock();
539 // disabling the index while doing this complex updates is about
540 // 2 to 10 times faster!
541 //setItemIndexMethod(QGraphicsScene::NoIndex);
543 QList<ChatLine *>::iterator lineIter = _lines.end();
544 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
545 qreal timestampWidth = firstColumnHandle()->sceneLeft();
546 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
547 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
549 while(lineIter != lineIterBegin) {
551 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
553 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
557 // clock_t endT = clock();
558 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
561 void ChatScene::secondHandlePositionChanged(qreal xpos) {
562 if(_secondColHandlePos == xpos)
565 _secondColHandlePos = xpos;
566 ChatViewSettings viewSettings(this);
567 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
568 ChatViewSettings defaultSettings;
569 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
571 // clock_t startT = clock();
573 // disabling the index while doing this complex updates is about
574 // 2 to 10 times faster!
575 //setItemIndexMethod(QGraphicsScene::NoIndex);
577 QList<ChatLine *>::iterator lineIter = _lines.end();
578 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
579 qreal linePos = _sceneRect.y() + _sceneRect.height();
580 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
581 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
582 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
583 while(lineIter != lineIterBegin) {
585 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
587 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
591 emit layoutChanged();
593 // clock_t endT = clock();
594 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
597 void ChatScene::setHandleXLimits() {
598 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
599 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
603 void ChatScene::setSelectingItem(ChatItem *item) {
604 if(_selectingItem) _selectingItem->clearSelection();
605 _selectingItem = item;
608 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
609 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
610 _selectionStartCol = _selectionMinCol = item->column();
612 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
613 updateSelection(item->mapToScene(itemPos));
616 void ChatScene::updateSelection(const QPointF &pos) {
617 int curRow = rowByScenePos(pos);
618 if(curRow < 0) return;
619 int curColumn = (int)columnByScenePos(pos);
620 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
621 if(minColumn != _selectionMinCol) {
622 _selectionMinCol = minColumn;
623 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
624 _lines[l]->setSelected(true, minColumn);
627 int newstart = qMin(curRow, _firstSelectionRow);
628 int newend = qMax(curRow, _firstSelectionRow);
629 if(newstart < _selectionStart) {
630 for(int l = newstart; l < _selectionStart; l++)
631 _lines[l]->setSelected(true, minColumn);
633 if(newstart > _selectionStart) {
634 for(int l = _selectionStart; l < newstart; l++)
635 _lines[l]->setSelected(false);
637 if(newend > _selectionEnd) {
638 for(int l = _selectionEnd+1; l <= newend; l++)
639 _lines[l]->setSelected(true, minColumn);
641 if(newend < _selectionEnd) {
642 for(int l = newend+1; l <= _selectionEnd; l++)
643 _lines[l]->setSelected(false);
646 _selectionStart = newstart;
647 _selectionEnd = newend;
649 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
650 if(!_selectingItem) {
651 // _selectingItem has been removed already
654 _lines[curRow]->setSelected(false);
655 _isSelecting = false;
656 _selectionStart = -1;
657 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
661 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
662 ChatItem *chatItem = chatItemAt(pos);
665 if(hasGlobalSelection()) {
666 int row = chatItem->row();
667 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
668 return columnByScenePos(pos) >= _selectionMinCol;
670 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
675 bool ChatScene::isScrollingAllowed() const {
679 // TODO: Handle clicks and single-item selections too
684 /******** MOUSE HANDLING **************************************************************************/
686 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
687 QPointF pos = event->scenePos();
690 // zoom actions and similar
691 chatView()->addActionsToMenu(&menu, pos);
694 if(isPosOverSelection(pos))
695 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
696 this, SLOT(selectionToClipboard()),
699 // item-specific options (select link etc)
700 ChatItem *item = chatItemAt(pos);
702 item->addActionsToMenu(&menu, item->mapFromScene(pos));
704 // no item -> default scene actions
705 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
707 if (QtUi::mainWindow()->menuBar()->isHidden())
708 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
710 menu.exec(event->screenPos());
714 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
715 if(event->buttons() == Qt::LeftButton) {
716 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
717 if(_clickTimer.isActive())
719 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
720 initiateDrag(event->widget());
722 _clickMode = DragStartClick;
723 handleClick(Qt::LeftButton, _clickPos);
725 _clickMode = NoClick;
728 updateSelection(event->scenePos());
729 emit mouseMoveWhileSelecting(event->scenePos());
731 } else if(_clickHandled && _clickMode < DoubleClick)
732 QGraphicsScene::mouseMoveEvent(event);
734 QGraphicsScene::mouseMoveEvent(event);
737 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
738 if(event->buttons() == Qt::LeftButton) {
739 _leftButtonPressed = true;
740 _clickHandled = false;
741 if(!isPosOverSelection(event->scenePos())) {
742 // immediately clear selection if clicked outside; otherwise, wait for potential drag
745 if(_clickMode != NoClick && _clickTimer.isActive()) {
747 case NoClick: _clickMode = SingleClick; break;
748 case SingleClick: _clickMode = DoubleClick; break;
749 case DoubleClick: _clickMode = TripleClick; break;
750 case TripleClick: _clickMode = DoubleClick; break;
751 case DragStartClick: break;
753 handleClick(Qt::LeftButton, _clickPos);
755 _clickMode = SingleClick;
756 _clickPos = event->scenePos();
760 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
761 QGraphicsScene::mouseDoubleClickEvent(event);
763 QGraphicsScene::mousePressEvent(event);
766 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
767 // we check for doubleclick ourselves, so just call press handler
768 mousePressEvent(event);
771 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
772 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
773 _leftButtonPressed = false;
774 if(_clickMode != NoClick) {
775 if(_clickMode == SingleClick)
778 if(!_clickTimer.isActive())
779 handleClick(Qt::LeftButton, _clickPos);
781 // no click -> drag or selection move
782 if(isGloballySelecting()) {
783 selectionToClipboard(QClipboard::Selection);
784 _isSelecting = false;
790 QGraphicsScene::mouseReleaseEvent(event);
793 void ChatScene::clickTimeout() {
794 if(!_leftButtonPressed && _clickMode == SingleClick)
795 handleClick(Qt::LeftButton, _clickPos);
798 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
799 if(button == Qt::LeftButton) {
802 // Now send click down to items
803 ChatItem *chatItem = chatItemAt(scenePos);
805 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
807 _clickHandled = true;
811 void ChatScene::initiateDrag(QWidget *source) {
812 QDrag *drag = new QDrag(source);
813 QMimeData *mimeData = new QMimeData;
814 mimeData->setText(selection());
815 drag->setMimeData(mimeData);
817 drag->exec(Qt::CopyAction);
820 /******** SELECTIONS ******************************************************************************/
822 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
826 stringToClipboard(selection(), mode);
829 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
831 // remove trailing linefeeds
832 if(str.endsWith('\n'))
836 case QClipboard::Clipboard:
837 QApplication::clipboard()->setText(str);
839 case QClipboard::Selection:
840 if(QApplication::clipboard()->supportsSelection())
841 QApplication::clipboard()->setText(str, QClipboard::Selection);
848 //!\brief Convert current selection to human-readable string.
849 QString ChatScene::selection() const {
850 //TODO Make selection format configurable!
851 if(hasGlobalSelection()) {
852 int start = qMin(_selectionStart, _selectionEnd);
853 int end = qMax(_selectionStart, _selectionEnd);
854 if(start < 0 || end >= _lines.count()) {
855 qDebug() << "Invalid selection range:" << start << end;
859 for(int l = start; l <= end; l++) {
860 if(_selectionMinCol == ChatLineModel::TimestampColumn)
861 result += _lines[l]->item(ChatLineModel::TimestampColumn)->data(MessageModel::DisplayRole).toString() + " ";
862 if(_selectionMinCol <= ChatLineModel::SenderColumn)
863 result += _lines[l]->item(ChatLineModel::SenderColumn)->data(MessageModel::DisplayRole).toString() + " ";
864 result += _lines[l]->item(ChatLineModel::ContentsColumn)->data(MessageModel::DisplayRole).toString() + "\n";
867 } else if(selectingItem())
868 return selectingItem()->selection();
872 bool ChatScene::hasSelection() const {
873 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
876 bool ChatScene::hasGlobalSelection() const {
877 return _selectionStart >= 0;
880 bool ChatScene::isGloballySelecting() const {
884 void ChatScene::clearGlobalSelection() {
885 if(hasGlobalSelection()) {
886 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
887 _lines[l]->setSelected(false);
888 _isSelecting = false;
889 _selectionStart = -1;
893 void ChatScene::clearSelection() {
894 clearGlobalSelection();
896 selectingItem()->clearSelection();
899 /******** *************************************************************************************/
901 void ChatScene::requestBacklog() {
902 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
904 return filter->requestBacklog();
908 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
909 if(x < _firstColHandle->x())
910 return ChatLineModel::TimestampColumn;
911 if(x < _secondColHandle->x())
912 return ChatLineModel::SenderColumn;
914 return ChatLineModel::ContentsColumn;
917 int ChatScene::rowByScenePos(qreal y) const {
918 QList<QGraphicsItem*> itemList = items(QPointF(0, y));
920 // ChatLine should be at the bottom of the list
921 for(int i = itemList.count()-1; i >= 0; i--) {
922 ChatLine *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
929 void ChatScene::updateSceneRect(qreal width) {
930 if(_lines.isEmpty()) {
931 updateSceneRect(QRectF(0, 0, width, 0));
935 // we hide day change messages at the top by making the scene rect smaller
936 // and by calling QGraphicsItem::hide() on all leading day change messages
937 // the first one is needed to ensure proper scrollbar ranges
938 // the second for cases where the viewport is larger then the set scenerect
939 // (in this case the items are shown anyways)
940 if(_firstLineRow == -1) {
941 int numRows = model()->rowCount();
943 QModelIndex firstLineIdx;
944 while(_firstLineRow < numRows) {
945 firstLineIdx = model()->index(_firstLineRow, 0);
946 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
948 _lines.at(_firstLineRow)->hide();
953 // the following call should be safe. If it crashes something went wrong during insert/remove
954 if(_firstLineRow < _lines.count()) {
955 ChatLine *firstLine = _lines.at(_firstLineRow);
956 ChatLine *lastLine = _lines.last();
957 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
960 updateSceneRect(QRectF(0, 0, width, 0));
964 void ChatScene::updateSceneRect(const QRectF &rect) {
970 bool ChatScene::event(QEvent *e) {
971 if(e->type() == QEvent::ApplicationPaletteChange) {
972 _firstColHandle->setColor(QApplication::palette().windowText().color());
973 _secondColHandle->setColor(QApplication::palette().windowText().color());
975 return QGraphicsScene::event(e);
978 // ========================================
980 // ========================================
982 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
986 if(webPreview.urlRect != urlRect)
987 webPreview.urlRect = urlRect;
989 if(webPreview.parentItem != parentItem)
990 webPreview.parentItem = parentItem;
992 if(webPreview.url != url) {
993 webPreview.url = url;
994 // prepare to load a different URL
995 if(webPreview.previewItem) {
996 if(webPreview.previewItem->scene())
997 removeItem(webPreview.previewItem);
998 delete webPreview.previewItem;
999 webPreview.previewItem = 0;
1001 webPreview.previewState = WebPreview::NoPreview;
1004 if(webPreview.url.isEmpty())
1007 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1008 switch(webPreview.previewState) {
1009 case WebPreview::NoPreview:
1010 webPreview.previewState = WebPreview::NewPreview;
1011 webPreview.timer.start(500);
1013 case WebPreview::NewPreview:
1014 case WebPreview::DelayPreview:
1015 case WebPreview::ShowPreview:
1016 // we're already waiting for the next step or showing the preview
1018 case WebPreview::HidePreview:
1019 // we still have a valid preview
1020 webPreview.previewState = WebPreview::DelayPreview;
1021 webPreview.timer.start(1000);
1024 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1027 void ChatScene::webPreviewNextStep() {
1028 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1029 switch(webPreview.previewState) {
1030 case WebPreview::NoPreview:
1032 case WebPreview::NewPreview:
1033 Q_ASSERT(!webPreview.previewItem);
1034 webPreview.previewItem = new WebPreviewItem(webPreview.url);
1035 webPreview.previewState = WebPreview::DelayPreview;
1036 webPreview.timer.start(1000);
1038 case WebPreview::DelayPreview:
1039 Q_ASSERT(webPreview.previewItem);
1040 // calc position and show
1042 qreal previewY = webPreview.urlRect.bottom();
1043 qreal previewX = webPreview.urlRect.x();
1044 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
1045 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
1047 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
1048 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
1050 webPreview.previewItem->setPos(previewX, previewY);
1052 addItem(webPreview.previewItem);
1053 webPreview.previewState = WebPreview::ShowPreview;
1055 case WebPreview::ShowPreview:
1056 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
1057 qWarning() << "removing preview";
1058 if(webPreview.previewItem && webPreview.previewItem->scene())
1059 removeItem(webPreview.previewItem);
1060 // Fall through to deletion!
1061 case WebPreview::HidePreview:
1062 if(webPreview.previewItem) {
1063 delete webPreview.previewItem;
1064 webPreview.previewItem = 0;
1066 webPreview.parentItem = 0;
1067 webPreview.url = QUrl();
1068 webPreview.urlRect = QRectF();
1069 webPreview.previewState = WebPreview::NoPreview;
1071 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1074 void ChatScene::clearWebPreview(ChatItem *parentItem) {
1075 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
1076 switch(webPreview.previewState) {
1077 case WebPreview::NewPreview:
1078 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
1080 case WebPreview::ShowPreview:
1081 if(parentItem == 0 || webPreview.parentItem == parentItem) {
1082 if(webPreview.previewItem && webPreview.previewItem->scene())
1083 removeItem(webPreview.previewItem);
1085 // fall through into to set hidden state
1086 case WebPreview::DelayPreview:
1087 // we're just loading, so haven't shown the preview yet.
1088 webPreview.previewState = WebPreview::HidePreview;
1089 webPreview.timer.start(5000);
1091 case WebPreview::NoPreview:
1092 case WebPreview::HidePreview:
1095 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
1099 // ========================================
1100 // end of webkit only
1101 // ========================================
1103 void ChatScene::showWebPreviewChanged() {
1104 ChatViewSettings settings;
1105 _showWebPreview = settings.showWebPreview();