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>
26 #include <QPersistentModelIndex>
34 #include "chatlinemodelitem.h"
35 #include "chatscene.h"
38 #include "clientbacklogmanager.h"
39 #include "columnhandleitem.h"
40 #include "contextmenuactionprovider.h"
41 #include "iconloader.h"
42 #include "messagefilter.h"
44 #include "qtuistyle.h"
45 #include "chatviewsettings.h"
46 #include "webpreviewitem.h"
48 const qreal minContentsWidth = 200;
50 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, ChatView *parent)
51 : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
55 _singleBufferId(BufferId()),
56 _sceneRect(0, 0, width, 0),
59 _cutoffMode(CutoffRight),
65 _leftButtonPressed(false)
67 MessageFilter *filter = qobject_cast<MessageFilter*>(model);
68 if(filter && filter->isSingleBufferFilter()) {
69 _singleBufferId = filter->singleBufferId();
72 ChatViewSettings defaultSettings;
73 int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
74 int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
76 ChatViewSettings viewSettings(this);
77 _firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
78 _secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
80 _firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
81 addItem(_firstColHandle);
82 _firstColHandle->setXPos(_firstColHandlePos);
83 connect(_firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(firstHandlePositionChanged(qreal)));
84 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
86 _secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
87 addItem(_secondColHandle);
88 _secondColHandle->setXPos(_secondColHandlePos);
89 connect(_secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(secondHandlePositionChanged(qreal)));
91 connect(this, SIGNAL(sceneRectChanged(const QRectF &)), _secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
95 if(model->rowCount() > 0)
96 rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
98 connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
99 this, SLOT(rowsInserted(const QModelIndex &, int, int)));
100 connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
101 this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
102 connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(dataChanged(QModelIndex, QModelIndex)));
105 webPreview.timer.setSingleShot(true);
106 connect(&webPreview.timer, SIGNAL(timeout()), this, SLOT(webPreviewNextStep()));
108 _showWebPreview = defaultSettings.showWebPreview();
109 defaultSettings.notify("ShowWebPreview", this, SLOT(showWebPreviewChanged()));
111 _clickTimer.setInterval(QApplication::doubleClickInterval());
112 _clickTimer.setSingleShot(true);
113 connect(&_clickTimer, SIGNAL(timeout()), SLOT(clickTimeout()));
115 setItemIndexMethod(QGraphicsScene::NoIndex);
118 ChatScene::~ChatScene() {
121 ChatView *ChatScene::chatView() const {
125 ColumnHandleItem *ChatScene::firstColumnHandle() const {
126 return _firstColHandle;
129 ColumnHandleItem *ChatScene::secondColumnHandle() const {
130 return _secondColHandle;
133 ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const {
134 QGraphicsItem *item = itemAt(scenePos);
135 return dynamic_cast<ChatItem *>(item);
138 bool ChatScene::containsBuffer(const BufferId &id) const {
139 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
141 return filter->containsBuffer(id);
146 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
150 // QModelIndex sidx = model()->index(start, 2);
151 // QModelIndex eidx = model()->index(end, 2);
152 // qDebug() << "rowsInserted:";
154 // QModelIndex ssidx = model()->index(start - 1, 2);
155 // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
156 // << ssidx.data(Qt::DisplayRole).toString();
158 // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
159 // << sidx.data(Qt::DisplayRole).toString();
160 // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
161 // << eidx.data(Qt::DisplayRole).toString();
162 // if(end + 1 < model()->rowCount()) {
163 // QModelIndex eeidx = model()->index(end + 1, 2);
164 // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
165 // << eeidx.data(Qt::DisplayRole).toString();
170 qreal width = _sceneRect.width();
171 bool atBottom = (start == _lines.count());
172 bool atTop = !atBottom && (start == 0);
174 if(start < _lines.count()) {
175 y = _lines.value(start)->y();
176 } else if(atBottom && !_lines.isEmpty()) {
177 y = _lines.last()->y() + _lines.last()->height();
180 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
181 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
182 qreal timestampWidth = firstColumnHandle()->sceneLeft();
183 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
184 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
187 for(int i = end; i >= start; i--) {
188 ChatLine *line = new ChatLine(i, model(),
190 timestampWidth, senderWidth, contentsWidth,
191 senderPos, contentsPos);
193 line->setPos(0, y-h);
194 _lines.insert(start, line);
198 for(int i = start; i <= end; i++) {
199 ChatLine *line = new ChatLine(i, model(),
201 timestampWidth, senderWidth, contentsWidth,
202 senderPos, contentsPos);
203 line->setPos(0, y+h);
205 _lines.insert(i, line);
210 // update existing items
211 for(int i = end+1; i < _lines.count(); i++) {
212 _lines[i]->setRow(i);
216 if(_selectionStart >= 0) {
217 int offset = end - start + 1;
218 int oldStart = _selectionStart;
219 if(_selectionStart >= start)
220 _selectionStart += offset;
221 if(_selectionEnd >= start) {
222 _selectionEnd += offset;
223 if(_selectionStart == oldStart)
224 for(int i = start; i < start + offset; i++)
225 _lines[i]->setSelected(true);
227 if(_firstSelectionRow >= start)
228 _firstSelectionRow += offset;
231 // neither pre- or append means we have to do dirty work: move items...
232 if(!(atTop || atBottom)) {
234 for(int i = 0; i <= end; i++) {
236 line->setPos(0, line->pos().y() - h);
240 // check if all went right
241 Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
243 // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
244 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
245 // 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();
246 // qDebug() << "line[start]" << _lines.at(start)->pos().y();
247 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
251 Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
252 // if(end + 1 < _lines.count()) {
253 // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
254 // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
255 // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
256 // qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
257 // qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
263 if(start < _firstLineRow) {
264 int prevFirstLineRow = _firstLineRow + (end - start + 1);
265 for(int i = end + 1; i < prevFirstLineRow; i++) {
266 _lines.at(i)->show();
269 // force new search for first proper line
274 emit lastLineChanged(_lines.last(), h);
278 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
281 qreal h = 0; // total height of removed items;
283 bool atTop = (start == 0);
284 bool atBottom = (end == _lines.count() - 1);
285 bool moveTop = false;
289 int row = _selectingItem->row();
290 if(row >= start && row <= end)
294 // remove items from scene
295 QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
296 int lineCount = start;
297 while(lineIter != _lines.end() && lineCount <= end) {
298 h += (*lineIter)->height();
300 lineIter = _lines.erase(lineIter);
304 // update rows of remaining chatlines
305 for(int i = start; i < _lines.count(); i++) {
306 _lines.at(i)->setRow(i);
310 if(_selectionStart >= 0) {
311 int offset = end - start + 1;
312 if(_selectionStart >= start)
313 _selectionStart = qMax(_selectionStart -= offset, start);
314 if(_selectionEnd >= start)
315 _selectionEnd -= offset;
316 if(_firstSelectionRow >= start)
317 _firstSelectionRow -= offset;
319 if(_selectionEnd < _selectionStart) {
320 _isSelecting = false;
321 _selectionStart = -1;
325 // neither removing at bottom or top means we have to move items...
326 if(!(atTop || atBottom)) {
329 int moveEnd = _lines.count() - 1;
330 if(start < _lines.count() - start) {
340 for(int i = moveStart; i <= moveEnd; i++) {
342 line->setPos(0, line->pos().y() + offset);
346 Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
349 // when searching for the first non-date-line we have to take into account that our
350 // model still contains the just removed lines so we cannot simply call updateSceneRect()
351 int numRows = model()->rowCount();
352 QModelIndex firstLineIdx;
354 bool needOffset = false;
357 if(_firstLineRow >= start && _firstLineRow <= end) {
358 _firstLineRow = end + 1;
361 firstLineIdx = model()->index(_firstLineRow, 0);
362 } while((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
365 _firstLineRow -= end - start + 1;
369 void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br) {
370 layout(tl.row(), br.row(), _sceneRect.width());
373 void ChatScene::updateForViewport(qreal width, qreal height) {
374 _viewportHeight = height;
378 void ChatScene::setWidth(qreal width) {
379 if(width == _sceneRect.width())
381 layout(0, _lines.count()-1, width);
384 void ChatScene::layout(int start, int end, qreal width) {
385 // clock_t startT = clock();
387 // disabling the index while doing this complex updates is about
388 // 2 to 10 times faster!
389 //setItemIndexMethod(QGraphicsScene::NoIndex);
393 qreal linePos = _lines.at(row)->scenePos().y() + _lines.at(row)->height();
394 qreal contentsWidth = width - secondColumnHandle()->sceneRight();
395 while(row >= start) {
396 _lines.at(row--)->setGeometryByWidth(width, contentsWidth, linePos);
400 // remaining items don't need geometry changes, but maybe repositioning?
401 ChatLine *line = _lines.at(row);
402 qreal offset = linePos - (line->scenePos().y() + line->height());
405 line = _lines.at(row--);
406 line->setPos(0, line->scenePos().y() + offset);
412 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
414 updateSceneRect(width);
416 emit layoutChanged();
418 // clock_t endT = clock();
419 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
422 void ChatScene::firstHandlePositionChanged(qreal xpos) {
423 if(_firstColHandlePos == xpos)
426 _firstColHandlePos = xpos >= 0 ? xpos : 0;
427 ChatViewSettings viewSettings(this);
428 viewSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
429 ChatViewSettings defaultSettings;
430 defaultSettings.setValue("FirstColumnHandlePos", _firstColHandlePos);
432 // clock_t startT = clock();
434 // disabling the index while doing this complex updates is about
435 // 2 to 10 times faster!
436 //setItemIndexMethod(QGraphicsScene::NoIndex);
438 QList<ChatLine *>::iterator lineIter = _lines.end();
439 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
440 qreal timestampWidth = firstColumnHandle()->sceneLeft();
441 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
442 QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
444 while(lineIter != lineIterBegin) {
446 (*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
448 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
452 // clock_t endT = clock();
453 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
456 void ChatScene::secondHandlePositionChanged(qreal xpos) {
457 if(_secondColHandlePos == xpos)
460 _secondColHandlePos = xpos;
461 ChatViewSettings viewSettings(this);
462 viewSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
463 ChatViewSettings defaultSettings;
464 defaultSettings.setValue("SecondColumnHandlePos", _secondColHandlePos);
466 // clock_t startT = clock();
468 // disabling the index while doing this complex updates is about
469 // 2 to 10 times faster!
470 //setItemIndexMethod(QGraphicsScene::NoIndex);
472 QList<ChatLine *>::iterator lineIter = _lines.end();
473 QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
474 qreal linePos = _sceneRect.y() + _sceneRect.height();
475 qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
476 qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
477 QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
478 while(lineIter != lineIterBegin) {
480 (*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
482 //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
486 emit layoutChanged();
488 // clock_t endT = clock();
489 // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
492 void ChatScene::setHandleXLimits() {
493 _firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
494 _secondColHandle->setXLimits(_firstColHandle->sceneRight(), width() - minContentsWidth);
497 void ChatScene::setSelectingItem(ChatItem *item) {
498 if(_selectingItem) _selectingItem->clearSelection();
499 _selectingItem = item;
502 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
503 _selectionStart = _selectionEnd = _firstSelectionRow = item->row();
504 _selectionStartCol = _selectionMinCol = item->column();
506 _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
507 updateSelection(item->mapToScene(itemPos));
510 void ChatScene::updateSelection(const QPointF &pos) {
511 int curRow = rowByScenePos(pos);
512 if(curRow < 0) return;
513 int curColumn = (int)columnByScenePos(pos);
514 ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
515 if(minColumn != _selectionMinCol) {
516 _selectionMinCol = minColumn;
517 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
518 _lines[l]->setSelected(true, minColumn);
521 int newstart = qMin(curRow, _firstSelectionRow);
522 int newend = qMax(curRow, _firstSelectionRow);
523 if(newstart < _selectionStart) {
524 for(int l = newstart; l < _selectionStart; l++)
525 _lines[l]->setSelected(true, minColumn);
527 if(newstart > _selectionStart) {
528 for(int l = _selectionStart; l < newstart; l++)
529 _lines[l]->setSelected(false);
531 if(newend > _selectionEnd) {
532 for(int l = _selectionEnd+1; l <= newend; l++)
533 _lines[l]->setSelected(true, minColumn);
535 if(newend < _selectionEnd) {
536 for(int l = newend+1; l <= _selectionEnd; l++)
537 _lines[l]->setSelected(false);
540 _selectionStart = newstart;
541 _selectionEnd = newend;
543 if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
544 if(!_selectingItem) {
545 // _selectingItem has been removed already
548 _lines[curRow]->setSelected(false);
549 _isSelecting = false;
550 _selectionStart = -1;
551 _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
555 bool ChatScene::isPosOverSelection(const QPointF &pos) const {
556 ChatItem *chatItem = chatItemAt(pos);
559 if(hasGlobalSelection()) {
560 int row = chatItem->row();
561 if(row >= qMin(_selectionStart, _selectionEnd) && row <= qMax(_selectionStart, _selectionEnd))
562 return columnByScenePos(pos) >= _selectionMinCol;
564 return chatItem->isPosOverSelection(chatItem->mapFromScene(pos));
569 bool ChatScene::isScrollingAllowed() const {
573 // TODO: Handle clicks and single-item selections too
578 /******** MOUSE HANDLING **************************************************************************/
580 void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
581 QPointF pos = event->scenePos();
584 // zoom actions and similar
585 chatView()->addActionsToMenu(&menu, pos);
588 if(isPosOverSelection(pos))
589 menu.addAction(SmallIcon("edit-copy"), tr("Copy Selection"),
590 this, SLOT(selectionToClipboard()),
593 // item-specific options (select link etc)
594 ChatItem *item = chatItemAt(pos);
596 item->addActionsToMenu(&menu, item->mapFromScene(pos));
598 // no item -> default scene actions
599 GraphicalUi::contextMenuActionProvider()->addActions(&menu, filter(), BufferId());
601 menu.exec(event->screenPos());
605 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
606 if(event->buttons() == Qt::LeftButton) {
607 if(!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
608 if(_clickTimer.isActive())
610 if(_clickMode == SingleClick && isPosOverSelection(_clickPos))
611 initiateDrag(event->widget());
613 _clickMode = DragStartClick;
614 handleClick(Qt::LeftButton, _clickPos);
616 _clickMode = NoClick;
619 updateSelection(event->scenePos());
620 emit mouseMoveWhileSelecting(event->scenePos());
622 } else if(_clickHandled && _clickMode < DoubleClick)
623 QGraphicsScene::mouseMoveEvent(event);
625 QGraphicsScene::mouseMoveEvent(event);
628 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
629 if(event->buttons() == Qt::LeftButton) {
630 _leftButtonPressed = true;
631 _clickHandled = false;
632 if(!isPosOverSelection(event->scenePos())) {
633 // immediately clear selection if clicked outside; otherwise, wait for potential drag
636 if(_clickMode != NoClick && _clickTimer.isActive()) {
638 case NoClick: _clickMode = SingleClick; break;
639 case SingleClick: _clickMode = DoubleClick; break;
640 case DoubleClick: _clickMode = TripleClick; break;
641 case TripleClick: _clickMode = DoubleClick; break;
642 case DragStartClick: break;
644 handleClick(Qt::LeftButton, _clickPos);
646 _clickMode = SingleClick;
647 _clickPos = event->scenePos();
651 if(event->type() == QEvent::GraphicsSceneMouseDoubleClick)
652 QGraphicsScene::mouseDoubleClickEvent(event);
654 QGraphicsScene::mousePressEvent(event);
657 void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
658 // we check for doubleclick ourselves, so just call press handler
659 mousePressEvent(event);
662 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
663 if(event->button() == Qt::LeftButton && _leftButtonPressed) {
664 _leftButtonPressed = false;
665 if(_clickMode != NoClick) {
666 if(_clickMode == SingleClick)
669 if(!_clickTimer.isActive())
670 handleClick(Qt::LeftButton, _clickPos);
672 // no click -> drag or selection move
673 if(isGloballySelecting()) {
674 selectionToClipboard(QClipboard::Selection);
675 _isSelecting = false;
681 QGraphicsScene::mouseReleaseEvent(event);
684 void ChatScene::clickTimeout() {
685 if(!_leftButtonPressed && _clickMode == SingleClick)
686 handleClick(Qt::LeftButton, _clickPos);
689 void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos) {
690 if(button == Qt::LeftButton) {
693 // Now send click down to items
694 ChatItem *chatItem = chatItemAt(scenePos);
696 chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
698 _clickHandled = true;
702 void ChatScene::initiateDrag(QWidget *source) {
703 QDrag *drag = new QDrag(source);
704 QMimeData *mimeData = new QMimeData;
705 mimeData->setText(selection());
706 drag->setMimeData(mimeData);
708 drag->exec(Qt::CopyAction);
711 /******** SELECTIONS ******************************************************************************/
713 void ChatScene::selectionToClipboard(QClipboard::Mode mode) {
717 stringToClipboard(selection(), mode);
720 void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode) {
722 // remove trailing linefeeds
723 if(str.endsWith('\n'))
727 case QClipboard::Clipboard:
728 QApplication::clipboard()->setText(str);
730 case QClipboard::Selection:
731 if(QApplication::clipboard()->supportsSelection())
732 QApplication::clipboard()->setText(str, QClipboard::Selection);
739 //!\brief Convert current selection to human-readable string.
740 QString ChatScene::selection() const {
741 //TODO Make selection format configurable!
742 if(hasGlobalSelection()) {
743 int start = qMin(_selectionStart, _selectionEnd);
744 int end = qMax(_selectionStart, _selectionEnd);
745 if(start < 0 || end >= _lines.count()) {
746 qDebug() << "Invalid selection range:" << start << end;
750 for(int l = start; l <= end; l++) {
751 if(_selectionMinCol == ChatLineModel::TimestampColumn)
752 result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
753 if(_selectionMinCol <= ChatLineModel::SenderColumn)
754 result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
755 result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
758 } else if(selectingItem())
759 return selectingItem()->selection();
763 bool ChatScene::hasSelection() const {
764 return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
767 bool ChatScene::hasGlobalSelection() const {
768 return _selectionStart >= 0;
771 bool ChatScene::isGloballySelecting() const {
775 void ChatScene::clearGlobalSelection() {
776 if(hasGlobalSelection()) {
777 for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++)
778 _lines[l]->setSelected(false);
779 _isSelecting = false;
780 _selectionStart = -1;
784 void ChatScene::clearSelection() {
785 clearGlobalSelection();
787 selectingItem()->clearSelection();
790 /******** *************************************************************************************/
792 void ChatScene::requestBacklog() {
793 MessageFilter *filter = qobject_cast<MessageFilter*>(model());
795 return filter->requestBacklog();
799 ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const {
800 if(x < _firstColHandle->x())
801 return ChatLineModel::TimestampColumn;
802 if(x < _secondColHandle->x())
803 return ChatLineModel::SenderColumn;
805 return ChatLineModel::ContentsColumn;
808 int ChatScene::rowByScenePos(qreal y) const {
809 // This is somewhat hacky... we look at the contents item that is at the given y position, since
810 // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
811 // ChatItems cover their ChatLine, so we won't get to the latter directly.
812 ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(_secondColHandle->sceneRight() + 1, y)));
813 if(!contentItem) return -1;
814 return contentItem->row();
817 void ChatScene::updateSceneRect(qreal width) {
818 if(_lines.isEmpty()) {
819 updateSceneRect(QRectF(0, 0, width, 0));
823 // we hide day change messages at the top by making the scene rect smaller
824 // and by calling QGraphicsItem::hide() on all leading day change messages
825 // the first one is needed to ensure proper scrollbar ranges
826 // the second for cases where the viewport is larger then the set scenerect
827 // (in this case the items are shown anyways)
828 if(_firstLineRow == -1) {
829 int numRows = model()->rowCount();
831 QModelIndex firstLineIdx;
832 while(_firstLineRow < numRows) {
833 firstLineIdx = model()->index(_firstLineRow, 0);
834 if((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) != Message::DayChange)
836 _lines.at(_firstLineRow)->hide();
841 // the following call should be safe. If it crashes something went wrong during insert/remove
842 if(_firstLineRow < _lines.count()) {
843 ChatLine *firstLine = _lines.at(_firstLineRow);
844 ChatLine *lastLine = _lines.last();
845 updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
848 updateSceneRect(QRectF(0, 0, width, 0));
852 void ChatScene::updateSceneRect(const QRectF &rect) {
858 bool ChatScene::event(QEvent *e) {
859 if(e->type() == QEvent::ApplicationPaletteChange) {
860 _firstColHandle->setColor(QApplication::palette().windowText().color());
861 _secondColHandle->setColor(QApplication::palette().windowText().color());
863 return QGraphicsScene::event(e);
866 // ========================================
868 // ========================================
870 void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect) {
874 if(webPreview.urlRect != urlRect)
875 webPreview.urlRect = urlRect;
877 if(webPreview.parentItem != parentItem)
878 webPreview.parentItem = parentItem;
880 if(webPreview.url != url) {
881 webPreview.url = url;
882 // prepare to load a different URL
883 if(webPreview.previewItem) {
884 if(webPreview.previewItem->scene())
885 removeItem(webPreview.previewItem);
886 delete webPreview.previewItem;
887 webPreview.previewItem = 0;
889 webPreview.previewState = WebPreview::NoPreview;
892 if(webPreview.url.isEmpty())
895 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
896 switch(webPreview.previewState) {
897 case WebPreview::NoPreview:
898 webPreview.previewState = WebPreview::NewPreview;
899 webPreview.timer.start(500);
901 case WebPreview::NewPreview:
902 case WebPreview::DelayPreview:
903 case WebPreview::ShowPreview:
904 // we're already waiting for the next step or showing the preview
906 case WebPreview::HidePreview:
907 // we still have a valid preview
908 webPreview.previewState = WebPreview::DelayPreview;
909 webPreview.timer.start(1000);
912 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
915 void ChatScene::webPreviewNextStep() {
916 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
917 switch(webPreview.previewState) {
918 case WebPreview::NoPreview:
920 case WebPreview::NewPreview:
921 Q_ASSERT(!webPreview.previewItem);
922 webPreview.previewItem = new WebPreviewItem(webPreview.url);
923 webPreview.previewState = WebPreview::DelayPreview;
924 webPreview.timer.start(1000);
926 case WebPreview::DelayPreview:
927 Q_ASSERT(webPreview.previewItem);
928 // calc position and show
930 qreal previewY = webPreview.urlRect.bottom();
931 qreal previewX = webPreview.urlRect.x();
932 if(previewY + webPreview.previewItem->boundingRect().height() > sceneRect().bottom())
933 previewY = webPreview.urlRect.y() - webPreview.previewItem->boundingRect().height();
935 if(previewX + webPreview.previewItem->boundingRect().width() > sceneRect().width())
936 previewX = sceneRect().right() - webPreview.previewItem->boundingRect().width();
938 webPreview.previewItem->setPos(previewX, previewY);
940 addItem(webPreview.previewItem);
941 webPreview.previewState = WebPreview::ShowPreview;
943 case WebPreview::ShowPreview:
944 qWarning() << "ChatScene::webPreviewNextStep() called while in ShowPreview Step!";
945 qWarning() << "removing preview";
946 if(webPreview.previewItem && webPreview.previewItem->scene())
947 removeItem(webPreview.previewItem);
948 // Fall through to deletion!
949 case WebPreview::HidePreview:
950 if(webPreview.previewItem) {
951 delete webPreview.previewItem;
952 webPreview.previewItem = 0;
954 webPreview.parentItem = 0;
955 webPreview.url = QUrl();
956 webPreview.urlRect = QRectF();
957 webPreview.previewState = WebPreview::NoPreview;
959 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
962 void ChatScene::clearWebPreview(ChatItem *parentItem) {
963 // qDebug() << Q_FUNC_INFO << webPreview.previewState;
964 switch(webPreview.previewState) {
965 case WebPreview::NewPreview:
966 webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
968 case WebPreview::ShowPreview:
969 if(parentItem == 0 || webPreview.parentItem == parentItem) {
970 if(webPreview.previewItem && webPreview.previewItem->scene())
971 removeItem(webPreview.previewItem);
973 // fall through into to set hidden state
974 case WebPreview::DelayPreview:
975 // we're just loading, so haven't shown the preview yet.
976 webPreview.previewState = WebPreview::HidePreview;
977 webPreview.timer.start(5000);
979 case WebPreview::NoPreview:
980 case WebPreview::HidePreview:
983 // qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
987 // ========================================
988 // end of webkit only
989 // ========================================
991 void ChatScene::showWebPreviewChanged() {
992 ChatViewSettings settings;
993 _showWebPreview = settings.showWebPreview();