1 /***************************************************************************
2 * Copyright (C) 2005-09 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"
49 #include "messagefilter.h"
51 #include "qtuistyle.h"
52 #include "chatviewsettings.h"
53 #include "webpreviewitem.h"
55 const qreal minContentsWidth = 200;
57 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
58 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
62 _singleBufferId(BufferId()),
63 _sceneRect(0, 0, width, 0),
66 _cutoffMode(CutoffRight),
72 _leftButtonPressed(false)
74 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
75 if(filter && filter->isSingleBufferFilter()) {
76 _singleBufferId = filter->singleBufferId();
79 ChatViewSettings defaultSettings;
80 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
81 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
83 ChatViewSettings viewSettings(this);
84 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
85 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
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 &)));
93 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
94 addItem(_secondColHandle);
95 _secondColHandle->setXPos(_secondColHandlePos);
96 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
98 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
102 if(model->rowCount() > 0)
103 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
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)));
112 webPreview.timer.setSingleShot(true);
113 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
115 _showWebPreview = defaultSettings.showWebPreview();
116 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
118 _clickTimer.setInterval(QApplication::doubleClickInterval());
119 _clickTimer.setSingleShot(true);
120 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
122 setItemIndexMethod(QGraphicsScene::NoIndex);
125 ChatScene::~ChatScene() {
128 ChatView *ChatScene::chatView() const {
132 ColumnHandleItem *ChatScene::firstColumnHandle() const {
133 return _firstColHandle;
136 ColumnHandleItem *ChatScene::secondColumnHandle() const {
137 return _secondColHandle;
140 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
141 QGraphicsItem *item = itemAt(scenePos);
142 return dynamic_cast<ChatItem *>(item);
145 bool ChatScene::containsBuffer(const BufferId &id) const {
146 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
148 return filter->containsBuffer(id);
153 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
157 // QModelIndex sidx = model()->index(start, 2);
158 // QModelIndex eidx = model()->index(end, 2);
159 // qDebug() << "rowsInserted:";
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();
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();
177 qreal width = _sceneRect.width();
178 bool atBottom = (start == _lines.count());
179 bool atTop = !atBottom && (start == 0);
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();
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);
194 for(int i = end; i >= start; i--) {
195 ChatLine *line = new ChatLine(i, model(),
197 timestampWidth, senderWidth, contentsWidth,
198 senderPos, contentsPos);
200 line->setPos(0, y-h);
201 _lines.insert(start, line);
205 for(int i = start; i <= end; i++) {
206 ChatLine *line = new ChatLine(i, model(),
208 timestampWidth, senderWidth, contentsWidth,
209 senderPos, contentsPos);
210 line->setPos(0, y+h);
212 _lines.insert(i, line);
217 // update existing items
218 for(int i = end+1; i < _lines.count(); i++) {
219 _lines[i]->setRow(i);
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);
234 if(_firstSelectionRow >= start)
235 _firstSelectionRow += offset;
238 // neither pre- or append means we have to do dirty work: move items...
239 if(!(atTop || atBottom)) {
241 for(int i = 0; i <= end; i++) {
243 line->setPos(0, line->pos().y() - h);
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());
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;
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;
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();
276 // force new search for first proper line
281 emit lastLineChanged(_lines.last(), h);
285 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
288 qreal h = 0; // total height of removed items;
290 bool atTop = (start == 0);
291 bool atBottom = (end == _lines.count() - 1);
292 bool moveTop = false;
296 int row = _selectingItem->row();
297 if(row >= start && row <= end)
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();
307 lineIter = _lines.erase(lineIter);
311 // update rows of remaining chatlines
312 for(int i = start; i < _lines.count(); i++) {
313 _lines.at(i)->setRow(i);
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;
326 if(_selectionEnd < _selectionStart) {
327 _isSelecting = false;
328 _selectionStart = -1;
332 // neither removing at bottom or top means we have to move items...
333 if(!(atTop || atBottom)) {
336 int moveEnd = _lines.count() - 1;
337 if(start < _lines.count() - start) {
347 for(int i = moveStart; i <= moveEnd; i++) {
349 line->setPos(0, line->pos().y() + offset);
353 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
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;
361 bool needOffset = false;
364 if(_firstLineRow >= start && _firstLineRow <= end) {
365 _firstLineRow = end + 1;
368 firstLineIdx = model()->index(_firstLineRow, 0);
369 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
372 _firstLineRow -= end - start + 1;
376 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
377 layout(tl.row(), br.row(), _sceneRect.width());
380 void ChatScene::updateForViewport(qreal width, qreal height) {
381 _viewportHeight = height;
385 void ChatScene::setWidth(qreal width) {
386 if(width == _sceneRect.width())
388 layout(0, _lines.count()-1, width);
391 void ChatScene::layout(int start, int end, qreal width) {
392 // clock_t startT = clock();
394 // disabling the index while doing this complex updates is about
395 // 2 to 10 times faster!
396 //setItemIndexMethod(QGraphicsScene::NoIndex);
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);
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());
412 line = _lines.at(row--);
413 line->setPos(0, line->scenePos().y() + offset);
419 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
421 updateSceneRect(width);
423 emit layoutChanged();
425 // clock_t endT = clock();
426 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
429 void ChatScene::firstHandlePositionChanged(qreal xpos) {
430 if(_firstColHandlePos == xpos)
433 _firstColHandlePos = xpos >= 0 ? xpos : 0;
434 ChatViewSettings viewSettings(this);
435 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
436 ChatViewSettings defaultSettings;
437 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
439 // clock_t startT = clock();
441 // disabling the index while doing this complex updates is about
442 // 2 to 10 times faster!
443 //setItemIndexMethod(QGraphicsScene::NoIndex);
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);
451 while(lineIter != lineIterBegin) {
453 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
455 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
459 // clock_t endT = clock();
460 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
463 void ChatScene::secondHandlePositionChanged(qreal xpos) {
464 if(_secondColHandlePos == xpos)
467 _secondColHandlePos = xpos;
468 ChatViewSettings viewSettings(this);
469 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
470 ChatViewSettings defaultSettings;
471 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
473 // clock_t startT = clock();
475 // disabling the index while doing this complex updates is about
476 // 2 to 10 times faster!
477 //setItemIndexMethod(QGraphicsScene::NoIndex);
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) {
487 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
489 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
493 emit layoutChanged();
495 // clock_t endT = clock();
496 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
499 void ChatScene::setHandleXLimits() {
500 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
501 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
504 void ChatScene::setSelectingItem(ChatItem *item) {
505 if(_selectingItem) _selectingItem->clearSelection();
506 _selectingItem = item;
509 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
510 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
511 _selectionStartCol = _selectionMinCol = item->column();
513 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
514 updateSelection(item->mapToScene(itemPos));
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);
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);
534 if(newstart > _selectionStart) {
535 for(int l = _selectionStart; l < newstart; l++)
536 _lines[l]->setSelected(false);
538 if(newend > _selectionEnd) {
539 for(int l = _selectionEnd+1; l <= newend; l++)
540 _lines[l]->setSelected(true, minColumn);
542 if(newend < _selectionEnd) {
543 for(int l = newend+1; l <= _selectionEnd; l++)
544 _lines[l]->setSelected(false);
547 _selectionStart = newstart;
548 _selectionEnd = newend;
550 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
551 if(!_selectingItem) {
552 // _selectingItem has been removed already
555 _lines[curRow]->setSelected(false);
556 _isSelecting = false;
557 _selectionStart = -1;
558 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
562 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
563 ChatItem *chatItem = chatItemAt(pos);
566 if(hasGlobalSelection()) {
567 int row = chatItem->row();
568 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
569 return columnByScenePos(pos) >= _selectionMinCol;
571 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
576 bool ChatScene::isScrollingAllowed() const {
580 // TODO: Handle clicks and single-item selections too
585 /******** MOUSE HANDLING **************************************************************************/
587 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
588 QPointF pos = event->scenePos();
591 // zoom actions and similar
592 chatView()->addActionsToMenu(&menu, pos);
595 if(isPosOverSelection(pos))
596 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
597 this, SLOT(selectionToClipboard()),
600 // item-specific options (select link etc)
601 ChatItem *item = chatItemAt(pos);
603 item->addActionsToMenu(&menu, item->mapFromScene(pos));
605 // no item -> default scene actions
606 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
608 if (QtUi::mainWindow()->menuBar()->isHidden())
609 menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
611 menu.exec(event->screenPos());
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())
620 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
621 initiateDrag(event->widget());
623 _clickMode = DragStartClick;
624 handleClick(Qt::LeftButton, _clickPos);
626 _clickMode = NoClick;
629 updateSelection(event->scenePos());
630 emit mouseMoveWhileSelecting(event->scenePos());
632 } else if(_clickHandled && _clickMode < DoubleClick)
633 QGraphicsScene::mouseMoveEvent(event);
635 QGraphicsScene::mouseMoveEvent(event);
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
646 if(_clickMode != NoClick && _clickTimer.isActive()) {
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;
654 handleClick(Qt::LeftButton, _clickPos);
656 _clickMode = SingleClick;
657 _clickPos = event->scenePos();
661 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
662 QGraphicsScene::mouseDoubleClickEvent(event);
664 QGraphicsScene::mousePressEvent(event);
667 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
668 // we check for doubleclick ourselves, so just call press handler
669 mousePressEvent(event);
672 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
673 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
674 _leftButtonPressed = false;
675 if(_clickMode != NoClick) {
676 if(_clickMode == SingleClick)
679 if(!_clickTimer.isActive())
680 handleClick(Qt::LeftButton, _clickPos);
682 // no click -> drag or selection move
683 if(isGloballySelecting()) {
684 selectionToClipboard(QClipboard::Selection);
685 _isSelecting = false;
691 QGraphicsScene::mouseReleaseEvent(event);
694 void ChatScene::clickTimeout() {
695 if(!_leftButtonPressed && _clickMode == SingleClick)
696 handleClick(Qt::LeftButton, _clickPos);
699 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
700 if(button == Qt::LeftButton) {
703 // Now send click down to items
704 ChatItem *chatItem = chatItemAt(scenePos);
706 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
708 _clickHandled = true;
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);
718 drag->exec(Qt::CopyAction);
721 /******** SELECTIONS ******************************************************************************/
723 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
727 stringToClipboard(selection(), mode);
730 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
732 // remove trailing linefeeds
733 if(str.endsWith('\n'))
737 case QClipboard::Clipboard:
738 QApplication::clipboard()->setText(str);
740 case QClipboard::Selection:
741 if(QApplication::clipboard()->supportsSelection())
742 QApplication::clipboard()->setText(str, QClipboard::Selection);
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;
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";
768 } else if(selectingItem())
769 return selectingItem()->selection();
773 bool ChatScene::hasSelection() const {
774 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
777 bool ChatScene::hasGlobalSelection() const {
778 return _selectionStart >= 0;
781 bool ChatScene::isGloballySelecting() const {
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;
794 void ChatScene::clearSelection() {
795 clearGlobalSelection();
797 selectingItem()->clearSelection();
800 /******** *************************************************************************************/
802 void ChatScene::requestBacklog() {
803 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
805 return filter->requestBacklog();
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;
815 return ChatLineModel::ContentsColumn;
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();
827 void ChatScene::updateSceneRect(qreal width) {
828 if(_lines.isEmpty()) {
829 updateSceneRect(QRectF(0, 0, width, 0));
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();
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)
846 _lines.at(_firstLineRow)->hide();
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()));
858 updateSceneRect(QRectF(0, 0, width, 0));
862 void ChatScene::updateSceneRect(const QRectF &rect) {
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());
873 return QGraphicsScene::event(e);
876 // ========================================
878 // ========================================
880 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
884 if(webPreview.urlRect != urlRect)
885 webPreview.urlRect = urlRect;
887 if(webPreview.parentItem != parentItem)
888 webPreview.parentItem = parentItem;
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;
899 webPreview.previewState = WebPreview::NoPreview;
902 if(webPreview.url.isEmpty())
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);
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
916 case WebPreview::HidePreview:
917 // we still have a valid preview
918 webPreview.previewState = WebPreview::DelayPreview;
919 webPreview.timer.start(1000);
922 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
925 void ChatScene::webPreviewNextStep() {
926 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
927 switch(webPreview.previewState) {
928 case WebPreview::NoPreview:
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);
936 case WebPreview::DelayPreview:
937 Q_ASSERT(webPreview.previewItem);
938 // calc position and show
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();
945 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
946 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
948 webPreview.previewItem->setPos(previewX, previewY);
950 addItem(webPreview.previewItem);
951 webPreview.previewState = WebPreview::ShowPreview;
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;
964 webPreview.parentItem = 0;
965 webPreview.url = QUrl();
966 webPreview.urlRect = QRectF();
967 webPreview.previewState = WebPreview::NoPreview;
969 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
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
978 case WebPreview::ShowPreview:
979 if(parentItem == 0 || webPreview.parentItem == parentItem) {
980 if(webPreview.previewItem && webPreview.previewItem->scene())
981 removeItem(webPreview.previewItem);
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);
989 case WebPreview::NoPreview:
990 case WebPreview::HidePreview:
993 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
997 // ========================================
998 // end of webkit only
999 // ========================================
1001 void ChatScene::showWebPreviewChanged() {
1002 ChatViewSettings settings;
1003 _showWebPreview = settings.showWebPreview();