1 /***************************************************************************
2 * Copyright (C) 2005-08 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>
26 #include <QPersistentModelIndex>
31 #include "chatlinemodelitem.h"
32 #include "chatscene.h"
35 #include "clientbacklogmanager.h"
36 #include "columnhandleitem.h"
37 #include "iconloader.h"
38 #include "messagefilter.h"
40 #include "qtuistyle.h"
41 #include "chatviewsettings.h"
42 #include "webpreviewitem.h"
44 const qreal minContentsWidth = 200;
46 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
47 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
51 _singleBufferId(BufferId()),
52 _sceneRect(0, 0, width, 0),
55 _cutoffMode(CutoffRight),
61 _leftButtonPressed(false)
63 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
64 if(filter && filter->isSingleBufferFilter()) {
65 _singleBufferId = filter->singleBufferId();
68 ChatViewSettings defaultSettings;
69 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
70 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
72 ChatViewSettings viewSettings(this);
73 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
74 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
76 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
77 addItem(_firstColHandle);
78 _firstColHandle->setXPos(_firstColHandlePos);
79 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
80 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
82 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
83 addItem(_secondColHandle);
84 _secondColHandle->setXPos(_secondColHandlePos);
85 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
87 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
91 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
92 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
93 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
94 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
96 if(model->rowCount() > 0)
97 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
100 webPreview.delayTimer.setSingleShot(true);
101 connect(&webPreview.delayTimer, SIGNAL(timeout()), this, SLOT(showWebPreviewEvent()));
102 //webPreview.deleteTimer.setInterval(600000);
103 webPreview.deleteTimer.setInterval(10000);
104 connect(&webPreview.deleteTimer, SIGNAL(timeout()), this, SLOT(deleteWebPreviewEvent()));
106 _showWebPreview = defaultSettings.showWebPreview();
107 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
109 _clickTimer.setInterval(QApplication::doubleClickInterval());
110 _clickTimer.setSingleShot(true);
111 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
113 setItemIndexMethod(QGraphicsScene::NoIndex);
116 ChatScene::~ChatScene() {
119 ChatView *ChatScene::chatView() const {
123 ColumnHandleItem *ChatScene::firstColumnHandle() const {
124 return _firstColHandle;
127 ColumnHandleItem *ChatScene::secondColumnHandle() const {
128 return _secondColHandle;
131 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
132 QGraphicsItem *item = itemAt(scenePos);
133 return dynamic_cast<ChatItem *>(item);
136 bool ChatScene::containsBuffer(const BufferId &id) const {
137 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
139 return filter->containsBuffer(id);
144 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
148 // QModelIndex sidx = model()->index(start, 2);
149 // QModelIndex eidx = model()->index(end, 2);
150 // qDebug() << "rowsInserted:";
152 // QModelIndex ssidx = model()->index(start - 1, 2);
153 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
154 // << ssidx.data(Qt::DisplayRole).toString();
156 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
157 // << sidx.data(Qt::DisplayRole).toString();
158 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
159 // << eidx.data(Qt::DisplayRole).toString();
160 // if(end + 1 < model()->rowCount()) {
161 // QModelIndex eeidx = model()->index(end + 1, 2);
162 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
163 // << eeidx.data(Qt::DisplayRole).toString();
168 qreal width = _sceneRect.width();
169 bool atBottom = (start == _lines.count());
170 bool atTop = !atBottom && (start == 0);
171 bool moveTop = false;
173 if(start < _lines.count()) {
174 y = _lines.value(start)->y();
175 } else if(atBottom && !_lines.isEmpty()) {
176 y = _lines.last()->y() + _lines.last()->height();
179 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
180 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
181 qreal timestampWidth = firstColumnHandle()->sceneLeft();
182 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
183 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
186 for(int i = end; i >= start; i--) {
187 ChatLine *line = new ChatLine(i, model(),
189 timestampWidth, senderWidth, contentsWidth,
190 senderPos, contentsPos);
192 line->setPos(0, y-h);
193 _lines.insert(start, line);
197 for(int i = start; i <= end; i++) {
198 ChatLine *line = new ChatLine(i, model(),
200 timestampWidth, senderWidth, contentsWidth,
201 senderPos, contentsPos);
202 line->setPos(0, y+h);
204 _lines.insert(i, line);
209 // update existing items
210 for(int i = end+1; i < _lines.count(); i++) {
211 _lines[i]->setRow(i);
215 if(_selectionStart >= 0) {
216 int offset = end - start + 1;
217 int oldStart = _selectionStart;
218 if(_selectionStart >= start)
219 _selectionStart += offset;
220 if(_selectionEnd >= start) {
221 _selectionEnd += offset;
222 if(_selectionStart == oldStart)
223 for(int i = start; i < start + offset; i++)
224 _lines[i]->setSelected(true);
226 if(_firstSelectionRow >= start)
227 _firstSelectionRow += offset;
230 // neither pre- or append means we have to do dirty work: move items...
232 int moveEnd = _lines.count() - 1;
234 if(!(atTop || atBottom)) {
235 // move top means: moving 0 to end (aka: end + 1)
236 // move top means: moving end + 1 to _lines.count() - 1 (aka: _lines.count() - (end + 1)
237 if(end + 1 < _lines.count() - end - 1) {
247 for(int i = moveStart; i <= moveEnd; i++) {
249 line->setPos(0, line->pos().y() + offset);
253 // check if all went right
254 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
256 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
257 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
258 // 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();
259 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
260 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
264 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
265 // if(end + 1 < _lines.count()) {
266 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
267 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
268 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
269 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
270 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
276 if(start < _firstLineRow) {
277 int prevFirstLineRow = _firstLineRow + (end - start + 1);
278 for(int i = end + 1; i < prevFirstLineRow; i++) {
279 _lines.at(i)->show();
282 // force new search for first proper line
286 if(atBottom || (!atTop && !moveTop)) {
287 emit lastLineChanged(_lines.last(), h);
291 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
294 qreal h = 0; // total height of removed items;
296 bool atTop = (start == 0);
297 bool atBottom = (end == _lines.count() - 1);
298 bool moveTop = false;
302 int row = _selectingItem->row();
303 if(row >= start && row <= end)
307 // remove items from scene
308 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
309 int lineCount = start;
310 while(lineIter != _lines.end() && lineCount <= end) {
311 h += (*lineIter)->height();
313 lineIter = _lines.erase(lineIter);
317 // update rows of remaining chatlines
318 for(int i = start; i < _lines.count(); i++) {
319 _lines.at(i)->setRow(i);
323 if(_selectionStart >= 0) {
324 int offset = end - start + 1;
325 if(_selectionStart >= start)
326 _selectionStart = qMax(_selectionStart -= offset, start);
327 if(_selectionEnd >= start)
328 _selectionEnd -= offset;
329 if(_firstSelectionRow >= start)
330 _firstSelectionRow -= offset;
332 if(_selectionEnd < _selectionStart) {
333 _isSelecting = false;
334 _selectionStart = -1;
338 // neither removing at bottom or top means we have to move items...
339 if(!(atTop || atBottom)) {
342 int moveEnd = _lines.count() - 1;
343 if(start < _lines.count() - start) {
353 for(int i = moveStart; i <= moveEnd; i++) {
355 line->setPos(0, line->pos().y() + offset);
359 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
362 // when searching for the first non-date-line we have to take into account that our
363 // model still contains the just removed lines so we cannot simply call updateSceneRect()
364 int numRows = model()->rowCount();
365 QModelIndex firstLineIdx;
367 bool needOffset = false;
370 if(_firstLineRow >= start && _firstLineRow <= end) {
371 _firstLineRow = end + 1;
374 firstLineIdx = model()->index(_firstLineRow, 0);
375 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
378 _firstLineRow -= end - start + 1;
382 void ChatScene::updateForViewport(qreal width, qreal height) {
383 _viewportHeight = height;
387 void ChatScene::setWidth(qreal width) {
388 if(width == _sceneRect.width())
391 // clock_t startT = clock();
393 // disabling the index while doing this complex updates is about
394 // 2 to 10 times faster!
395 //setItemIndexMethod(QGraphicsScene::NoIndex);
397 QList<ChatLine *>::iterator lineIter = _lines.end();
398 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
399 qreal linePos = _sceneRect.y() + _sceneRect.height();
400 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
401 while(lineIter != lineIterBegin) {
403 (*lineIter)->setGeometryByWidth(width, contentsWidth, linePos);
405 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
407 updateSceneRect(width);
409 emit layoutChanged();
411 // clock_t endT = clock();
412 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
415 void ChatScene::firstHandlePositionChanged(qreal xpos) {
416 if(_firstColHandlePos == xpos)
419 _firstColHandlePos = xpos;
420 ChatViewSettings viewSettings(this);
421 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
422 ChatViewSettings defaultSettings;
423 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
425 // clock_t startT = clock();
427 // disabling the index while doing this complex updates is about
428 // 2 to 10 times faster!
429 //setItemIndexMethod(QGraphicsScene::NoIndex);
431 QList<ChatLine *>::iterator lineIter = _lines.end();
432 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
433 qreal timestampWidth = firstColumnHandle()->sceneLeft();
434 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
435 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
437 while(lineIter != lineIterBegin) {
439 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
441 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
445 // clock_t endT = clock();
446 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
449 void ChatScene::secondHandlePositionChanged(qreal xpos) {
450 if(_secondColHandlePos == xpos)
453 _secondColHandlePos = xpos;
454 ChatViewSettings viewSettings(this);
455 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
456 ChatViewSettings defaultSettings;
457 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
459 // clock_t startT = clock();
461 // disabling the index while doing this complex updates is about
462 // 2 to 10 times faster!
463 //setItemIndexMethod(QGraphicsScene::NoIndex);
465 QList<ChatLine *>::iterator lineIter = _lines.end();
466 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
467 qreal linePos = _sceneRect.y() + _sceneRect.height();
468 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
469 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
470 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
471 while(lineIter != lineIterBegin) {
473 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
475 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
479 emit layoutChanged();
481 // clock_t endT = clock();
482 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
485 void ChatScene::setHandleXLimits() {
486 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
487 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
490 void ChatScene::setSelectingItem(ChatItem *item) {
491 if(_selectingItem) _selectingItem->clearSelection();
492 _selectingItem = item;
495 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
496 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
497 _selectionStartCol = _selectionMinCol = item->column();
499 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
500 updateSelection(item->mapToScene(itemPos));
503 void ChatScene::updateSelection(const QPointF &pos) {
504 int curRow = rowByScenePos(pos);
505 if(curRow < 0) return;
506 int curColumn = (int)columnByScenePos(pos);
507 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
508 if(minColumn != _selectionMinCol) {
509 _selectionMinCol = minColumn;
510 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
511 _lines[l]->setSelected(true, minColumn);
514 int newstart = qMin(curRow, _firstSelectionRow);
515 int newend = qMax(curRow, _firstSelectionRow);
516 if(newstart < _selectionStart) {
517 for(int l = newstart; l < _selectionStart; l++)
518 _lines[l]->setSelected(true, minColumn);
520 if(newstart > _selectionStart) {
521 for(int l = _selectionStart; l < newstart; l++)
522 _lines[l]->setSelected(false);
524 if(newend > _selectionEnd) {
525 for(int l = _selectionEnd+1; l <= newend; l++)
526 _lines[l]->setSelected(true, minColumn);
528 if(newend < _selectionEnd) {
529 for(int l = newend+1; l <= _selectionEnd; l++)
530 _lines[l]->setSelected(false);
533 _selectionStart = newstart;
534 _selectionEnd = newend;
536 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
537 if(!_selectingItem) {
538 // _selectingItem has been removed already
541 _lines[curRow]->setSelected(false);
542 _isSelecting = false;
543 _selectionStart = -1;
544 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
548 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
549 ChatItem *chatItem = chatItemAt(pos);
552 if(hasGlobalSelection()) {
553 int row = chatItem->row();
554 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
555 return columnByScenePos(pos) >= _selectionMinCol;
557 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
562 bool ChatScene::isScrollingAllowed() const {
566 // TODO: Handle clicks and single-item selections too
571 /******** MOUSE HANDLING **************************************************************************/
573 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
574 QPointF pos = event->scenePos();
577 // zoom actions and similar
578 chatView()->addActionsToMenu(&menu, pos);
581 if(isPosOverSelection(pos))
582 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
583 this, SLOT(selectionToClipboard()),
586 // item-specific options (select link etc)
587 ChatItem *item = chatItemAt(pos);
589 item->addActionsToMenu(&menu, item->mapFromScene(pos));
591 // no item -> default scene actions
592 Client::mainUi()->actionProvider()->addActions(&menu, filter(), BufferId());
594 menu.exec(event->screenPos());
598 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
599 if(event->buttons() == Qt::LeftButton) {
600 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
601 if(_clickTimer.isActive())
603 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
604 initiateDrag(event->widget());
606 _clickMode = DragStartClick;
607 handleClick(Qt::LeftButton, _clickPos);
609 _clickMode = NoClick;
612 updateSelection(event->scenePos());
613 emit mouseMoveWhileSelecting(event->scenePos());
615 } else if(_clickHandled && _clickMode < DoubleClick)
616 QGraphicsScene::mouseMoveEvent(event);
618 QGraphicsScene::mouseMoveEvent(event);
621 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
622 if(event->buttons() == Qt::LeftButton) {
623 _leftButtonPressed = true;
624 _clickHandled = false;
625 if(!isPosOverSelection(event->scenePos())) {
626 // immediately clear selection if clicked outside; otherwise, wait for potential drag
629 if(_clickMode != NoClick && _clickTimer.isActive()) {
631 case NoClick: _clickMode = SingleClick; break;
632 case SingleClick: _clickMode = DoubleClick; break;
633 case DoubleClick: _clickMode = TripleClick; break;
634 case TripleClick: _clickMode = DoubleClick; break;
635 case DragStartClick: break;
637 handleClick(Qt::LeftButton, _clickPos);
639 _clickMode = SingleClick;
640 _clickPos = event->scenePos();
644 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
645 QGraphicsScene::mouseDoubleClickEvent(event);
647 QGraphicsScene::mousePressEvent(event);
650 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
651 // we check for doubleclick ourselves, so just call press handler
652 mousePressEvent(event);
655 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
656 if(!event->buttons() & Qt::LeftButton) {
657 _leftButtonPressed = false;
658 if(_clickMode != NoClick) {
659 if(_clickMode == SingleClick)
662 if(!_clickTimer.isActive())
663 handleClick(Qt::LeftButton, _clickPos);
665 // no click -> drag or selection move
666 if(isGloballySelecting()) {
667 selectionToClipboard(QClipboard::Selection);
668 _isSelecting = false;
674 QGraphicsScene::mouseReleaseEvent(event);
677 void ChatScene::clickTimeout() {
678 if(!_leftButtonPressed && _clickMode == SingleClick)
679 handleClick(Qt::LeftButton, _clickPos);
682 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
683 if(button == Qt::LeftButton) {
686 // Now send click down to items
687 ChatItem *chatItem = chatItemAt(scenePos);
689 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
691 _clickHandled = true;
695 void ChatScene::initiateDrag(QWidget *source) {
696 QDrag *drag = new QDrag(source);
697 QMimeData *mimeData = new QMimeData;
698 mimeData->setText(selection());
699 drag->setMimeData(mimeData);
701 drag->exec(Qt::CopyAction);
704 /******** SELECTIONS ******************************************************************************/
706 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
710 stringToClipboard(selection(), mode);
713 void ChatScene::stringToClipboard(const QString &str, QClipboard::Mode mode) {
715 case QClipboard::Clipboard:
716 QApplication::clipboard()->setText(str);
718 case QClipboard::Selection:
719 if(QApplication::clipboard()->supportsSelection())
720 QApplication::clipboard()->setText(str, QClipboard::Selection);
727 //!\brief Convert current selection to human-readable string.
728 QString ChatScene::selection() const {
729 //TODO Make selection format configurable!
730 if(hasGlobalSelection()) {
731 int start = qMin(_selectionStart, _selectionEnd);
732 int end = qMax(_selectionStart, _selectionEnd);
733 if(start < 0 || end >= _lines.count()) {
734 qDebug() << "Invalid selection range:" << start << end;
738 for(int l = start; l <= end; l++) {
739 if(_selectionMinCol == ChatLineModel::TimestampColumn)
740 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
741 if(_selectionMinCol <= ChatLineModel::SenderColumn)
742 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
743 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
746 } else if(selectingItem())
747 return selectingItem()->selection();
751 bool ChatScene::hasSelection() const {
752 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
755 bool ChatScene::hasGlobalSelection() const {
756 return _selectionStart >= 0;
759 bool ChatScene::isGloballySelecting() const {
763 void ChatScene::clearGlobalSelection() {
764 if(hasGlobalSelection()) {
765 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
766 _lines[l]->setSelected(false);
767 _isSelecting = false;
768 _selectionStart = -1;
772 void ChatScene::clearSelection() {
773 clearGlobalSelection();
775 selectingItem()->clearSelection();
778 /******** *************************************************************************************/
780 void ChatScene::requestBacklog() {
781 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
783 return filter->requestBacklog();
787 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
788 if(x < _firstColHandle->x())
789 return ChatLineModel::TimestampColumn;
790 if(x < _secondColHandle->x())
791 return ChatLineModel::SenderColumn;
793 return ChatLineModel::ContentsColumn;
796 int ChatScene::rowByScenePos(qreal y) const {
797 // This is somewhat hacky... we look at the contents item that is at the given y position, since
798 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
799 // ChatItems cover their ChatLine, so we won't get to the latter directly.
800 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
801 if(!contentItem) return -1;
802 return contentItem->row();
805 void ChatScene::updateSceneRect(qreal width) {
806 if(_lines.isEmpty()) {
807 updateSceneRect(QRectF(0, 0, width, 0));
811 // we hide day change messages at the top by making the scene rect smaller
812 // and by calling QGraphicsItem::hide() on all leading day change messages
813 // the first one is needed to ensure proper scrollbar ranges
814 // the second for cases where the viewport is larger then the set scenerect
815 // (in this case the items are shown anyways)
816 if(_firstLineRow == -1) {
817 int numRows = model()->rowCount();
819 QModelIndex firstLineIdx;
820 while(_firstLineRow < numRows) {
821 firstLineIdx = model()->index(_firstLineRow, 0);
822 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
824 _lines.at(_firstLineRow)->hide();
829 // the following call should be safe. If it crashes something went wrong during insert/remove
830 if(_firstLineRow < _lines.count()) {
831 ChatLine *firstLine = _lines.at(_firstLineRow);
832 ChatLine *lastLine = _lines.last();
833 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
836 updateSceneRect(QRectF(0, 0, width, 0));
840 void ChatScene::updateSceneRect(const QRectF &rect) {
846 bool ChatScene::event(QEvent *e) {
847 if(e->type() == QEvent::ApplicationPaletteChange) {
848 _firstColHandle->setColor(QApplication::palette().windowText().color());
849 _secondColHandle->setColor(QApplication::palette().windowText().color());
851 return QGraphicsScene::event(e);
854 /******** WEB PREVIEW *****************************************************************************/
856 void ChatScene::loadWebPreview(ChatItem *parentItem, const QString &url, const QRectF &urlRect) {
865 if(webPreview.parentItem != parentItem)
866 webPreview.parentItem = parentItem;
868 if(webPreview.url != url) {
869 webPreview.url = url;
870 // load a new web view and delete the old one (if exists)
871 if(webPreview.previewItem && webPreview.previewItem->scene()) {
872 removeItem(webPreview.previewItem);
873 delete webPreview.previewItem;
875 webPreview.previewItem = new WebPreviewItem(url);
876 webPreview.delayTimer.start(2000);
877 webPreview.deleteTimer.stop();
878 } else if(webPreview.previewItem && !webPreview.previewItem->scene()) {
879 // we just have to readd the item to the scene
880 webPreview.delayTimer.start(2000);
881 webPreview.deleteTimer.stop();
883 if(webPreview.urlRect != urlRect) {
884 webPreview.urlRect = urlRect;
885 qreal previewY = urlRect.bottom();
886 qreal previewX = urlRect.x();
887 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
888 previewY = urlRect.y() - webPreview.previewItem->boundingRect().height();
890 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
891 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
893 webPreview.previewItem->setPos(previewX, previewY);
898 void ChatScene::showWebPreviewEvent() {
900 if(webPreview.previewItem)
901 addItem(webPreview.previewItem);
905 void ChatScene::clearWebPreview(ChatItem *parentItem) {
909 if(parentItem == 0 || webPreview.parentItem == parentItem) {
910 if(webPreview.previewItem && webPreview.previewItem->scene()) {
911 removeItem(webPreview.previewItem);
912 webPreview.deleteTimer.start();
914 webPreview.delayTimer.stop();
919 void ChatScene::deleteWebPreviewEvent() {
921 if(webPreview.previewItem) {
922 delete webPreview.previewItem;
923 webPreview.previewItem = 0;
925 webPreview.parentItem = 0;
926 webPreview.url = QString();
927 webPreview.urlRect = QRectF();
931 void ChatScene::showWebPreviewChanged() {
932 ChatViewSettings settings;
933 _showWebPreview = settings.showWebPreview();