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>
23 #include <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
28 #include <QTextLayout>
31 #include "buffermodel.h"
32 #include "bufferview.h"
34 #include "chatlinemodel.h"
35 #include "contextmenuactionprovider.h"
36 #include "iconloader.h"
39 #include "qtuistyle.h"
41 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
42 : QGraphicsItem(parent),
43 _boundingRect(0, 0, width, height),
44 _selectionMode(NoSelection),
47 setAcceptHoverEvents(true);
52 QVariant ChatItem::data(int role) const {
53 QModelIndex index = model()->index(row(), column());
54 if(!index.isValid()) {
55 qWarning() << "ChatItem::data(): model index is invalid!" << index;
58 return model()->data(index, role);
61 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
64 layout->setText(data(MessageModel::DisplayRole).toString());
67 option.setWrapMode(wrapMode);
68 option.setAlignment(alignment);
69 layout->setTextOption(option);
71 QList<QTextLayout::FormatRange> formatRanges
72 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
73 layout->setAdditionalFormats(formatRanges);
76 void ChatItem::doLayout(QTextLayout *layout) const {
77 layout->beginLayout();
78 QTextLine line = layout->createLine();
80 line.setLineWidth(width());
81 line.setPosition(QPointF(0,0));
87 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
88 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
89 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
90 Q_UNUSED(option); Q_UNUSED(widget);
91 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
92 QVector<QTextLayout::FormatRange> formats = additionalFormats();
93 QTextLayout::FormatRange selectFmt = selectionFormat();
94 if(selectFmt.format.isValid()) formats.append(selectFmt);
97 layout.draw(painter, QPointF(0,0), formats, boundingRect());
99 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
102 // uncomment partially or all of the following stuff:
104 // 0) alternativ painter color for debug stuff
106 // painter->setPen(Qt::red);
108 // painter->setPen(Qt::blue);
109 // 1) draw wordwrap points in the first line
110 // if(column() == 2) {
111 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
112 // foreach(ChatLineModel::Word word, wrapList) {
113 // if(word.endX > width())
115 // painter->drawLine(word.endX, 0, word.endX, height());
118 // 2) draw MsgId over the time column
119 // if(column() == 0) {
120 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
121 // QPointF bottomPoint = boundingRect().bottomLeft();
122 // bottomPoint.ry() -= 2;
123 // painter->drawText(bottomPoint, msgIdString);
125 // 3) draw bounding rect
126 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
129 qint16 ChatItem::posToCursor(const QPointF &pos) const {
130 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
131 if(pos.y() < 0) return 0;
135 for(int l = layout.lineCount() - 1; l >= 0; l--) {
136 QTextLine line = layout.lineAt(l);
137 if(pos.y() >= line.y()) {
138 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
144 bool ChatItem::hasSelection() const {
145 if(_selectionMode == NoSelection)
147 if(_selectionMode == FullSelection)
150 return _selectionStart != _selectionEnd;
153 QString ChatItem::selection() const {
154 if(_selectionMode == FullSelection)
155 return data(MessageModel::DisplayRole).toString();
156 if(_selectionMode == PartialSelection)
157 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
161 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
162 _selectionMode = mode;
163 _selectionStart = start;
168 void ChatItem::setFullSelection() {
169 if(_selectionMode != FullSelection) {
170 _selectionMode = FullSelection;
175 void ChatItem::clearSelection() {
176 if(_selectionMode != NoSelection) {
177 _selectionMode = NoSelection;
182 void ChatItem::continueSelecting(const QPointF &pos) {
183 _selectionMode = PartialSelection;
184 _selectionEnd = posToCursor(pos);
188 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
189 if(_selectionMode == FullSelection)
191 if(_selectionMode == PartialSelection) {
192 int cursor = posToCursor(pos);
193 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
198 QTextLayout::FormatRange ChatItem::selectionFormat() const {
199 QTextLayout::FormatRange selectFmt;
200 if(_selectionMode != NoSelection) {
201 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
202 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
203 if(_selectionMode == PartialSelection) {
204 selectFmt.start = qMin(_selectionStart, _selectionEnd);
205 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
206 } else { // FullSelection
208 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
211 selectFmt.start = -1;
212 selectFmt.length = 0;
217 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
218 QList<QRectF> resultList;
219 const QAbstractItemModel *model_ = model();
223 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
224 QList<int> indexList;
225 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
226 while(searchIdx != -1) {
227 indexList << searchIdx;
228 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
233 foreach(int idx, indexList) {
234 QTextLine line = layout.lineForTextPosition(idx);
235 qreal x = line.cursorToX(idx);
236 qreal width = line.cursorToX(idx + searchWord.count()) - x;
237 qreal height = line.height();
238 qreal y = height * line.lineNumber();
239 resultList << QRectF(x, y, width, height);
245 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
246 // single clicks are already handled by the scene (for clearing the selection)
247 if(clickMode == ChatScene::DragStartClick) {
248 chatScene()->setSelectingItem(this);
249 _selectionStart = _selectionEnd = posToCursor(pos);
250 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
255 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
256 if(event->buttons() == Qt::LeftButton) {
257 if(contains(event->pos())) {
258 qint16 end = posToCursor(event->pos());
259 if(end != _selectionEnd) {
261 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
266 chatScene()->startGlobalSelection(this, event->pos());
274 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
275 if(event->buttons() == Qt::LeftButton)
281 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
282 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
283 chatScene()->selectionToClipboard(QClipboard::Selection);
289 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
292 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
295 // ************************************************************
297 // ************************************************************
299 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
300 Q_UNUSED(option); Q_UNUSED(widget);
302 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
305 qreal layoutWidth = layout.minimumWidth();
307 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
308 offset = qMin(width() - layoutWidth, (qreal)0);
310 offset = qMax(layoutWidth - width(), (qreal)0);
312 QTextLayout::FormatRange selectFmt = selectionFormat();
314 if(layoutWidth > width()) {
315 // Draw a nice gradient for longer items
316 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
317 QPixmap pixmap(layout.boundingRect().toRect().size());
318 pixmap.fill(Qt::transparent);
319 QPainter pixPainter(&pixmap);
320 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
323 // Create alpha channel mask
324 QPixmap mask(pixmap.size());
325 QPainter maskPainter(&mask);
326 QLinearGradient gradient;
328 gradient.setStart(0, 0);
329 gradient.setFinalStop(12, 0);
330 gradient.setColorAt(0, Qt::black);
331 gradient.setColorAt(1, Qt::white);
333 gradient.setStart(width()-10, 0);
334 gradient.setFinalStop(width(), 0);
335 gradient.setColorAt(0, Qt::white);
336 gradient.setColorAt(1, Qt::black);
338 maskPainter.fillRect(boundingRect(), gradient);
339 pixmap.setAlphaChannel(mask);
340 painter->drawPixmap(0, 0, pixmap);
342 layout.draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
346 // ************************************************************
348 // ************************************************************
350 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
352 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
353 : ChatItem(0, 0, pos, parent),
356 const QAbstractItemModel *model_ = model();
357 QModelIndex index = model_->index(row(), column());
358 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
360 setGeometryByWidth(width);
363 ContentsChatItem::~ContentsChatItem() {
367 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
369 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
370 that->_data = new ContentsChatItemPrivate(findClickables(), that);
375 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
377 prepareGeometryChange();
381 WrapColumnFinder finder(this);
382 while(finder.nextWrapColumn() > 0)
384 setHeight(lines * fontMetrics()->lineSpacing());
391 void ContentsChatItem::doLayout(QTextLayout *layout) const {
392 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
393 if(!wrapList.count()) return; // empty chatitem
396 WrapColumnFinder finder(this);
397 layout->beginLayout();
399 QTextLine line = layout->createLine();
403 int col = finder.nextWrapColumn();
404 line.setNumColumns(col >= 0 ? col - line.textStart() : layout->text().length());
405 line.setPosition(QPointF(0, h));
406 h += fontMetrics()->lineSpacing();
411 // NOTE: This method is not threadsafe and not reentrant!
412 // (RegExps are not constant while matching, and they are static here for efficiency)
413 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
415 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
416 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]'])");
418 static QRegExp regExp[] = {
420 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
421 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|gopher://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
424 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
425 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
427 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
430 static const int regExpCount = 2; // number of regexps in the array above
432 qint16 matches[] = { 0, 0, 0 };
433 qint16 matchEnd[] = { 0, 0, 0 };
435 QString str = data(ChatLineModel::DisplayRole).toString();
437 QList<Clickable> result;
444 minidx = str.length();
445 for(int i = 0; i < regExpCount; i++) {
446 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
447 if(idx >= matchEnd[i]) {
448 matches[i] = regExp[i].indexIn(str, qMax(matchEnd[i], idx));
449 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
451 if(matches[i] >= 0 && matches[i] < minidx) {
457 idx = matchEnd[type];
458 QString match = str.mid(matches[type], matchEnd[type] - matches[type]);
459 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
460 if(!match.contains('(')) {
465 if(type == Clickable::Channel) {
466 // don't make clickable if it could be a #number
467 if(QRegExp("^#\\d+$").exactMatch(match))
470 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
475 if(!result.isEmpty()) qDebug() << str;
476 foreach(Clickable click, result) {
477 qDebug() << str.mid(click.start, click.length);
483 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
484 qint16 idx = posToCursor(pos);
485 for(int i = 0; i < privateData()->clickables.count(); i++) {
486 Clickable click = privateData()->clickables.at(i);
487 if(idx >= click.start && idx < click.start + click.length)
493 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
494 // mark a clickable if hovered upon
495 QVector<QTextLayout::FormatRange> fmt;
496 if(privateData()->currentClickable.isValid()) {
497 Clickable click = privateData()->currentClickable;
498 QTextLayout::FormatRange f;
499 f.start = click.start;
500 f.length = click.length;
501 f.format.setFontUnderline(true);
507 void ContentsChatItem::endHoverMode() {
509 if(privateData()->currentClickable.isValid()) {
510 setCursor(Qt::ArrowCursor);
511 privateData()->currentClickable = Clickable();
518 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
519 if(clickMode == ChatScene::SingleClick) {
520 Clickable click = clickableAt(pos);
521 if(click.isValid()) {
522 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
525 if(!str.contains("://"))
526 str = "http://" + str;
527 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
529 case Clickable::Channel: {
530 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
531 BufferId bufId = Client::networkModel()->bufferId(networkId, str);
532 if(bufId.isValid()) {
533 QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
534 Client::bufferModel()->switchToBuffer(bufId);
535 if(!targetIdx.data(NetworkModel::ItemActiveRole).toBool())
536 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
538 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
545 } else if(clickMode == ChatScene::DoubleClick) {
546 chatScene()->setSelectingItem(this);
547 setSelectionMode(PartialSelection);
548 Clickable click = clickableAt(pos);
549 if(click.isValid()) {
550 setSelectionStart(click.start);
551 setSelectionEnd(click.start + click.length);
553 // find word boundary
554 QString str = data(ChatLineModel::DisplayRole).toString();
555 qint16 cursor = posToCursor(pos);
556 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
557 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
558 if(end < 0) end = str.length();
559 setSelectionStart(start);
560 setSelectionEnd(end);
563 } else if(clickMode == ChatScene::TripleClick) {
564 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
566 ChatItem::handleClick(pos, clickMode);
569 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
570 // mouse move events always mean we're not hovering anymore...
572 ChatItem::mouseMoveEvent(event);
575 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
580 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
581 bool onClickable = false;
582 Clickable click = clickableAt(event->pos());
583 if(click.isValid()) {
584 if(click.type == Clickable::Url) {
586 showWebPreview(click);
587 } else if(click.type == Clickable::Channel) {
588 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
589 // don't make clickable if it's our own name
590 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
591 if(Client::networkModel()->bufferName(myId) != name)
595 setCursor(Qt::PointingHandCursor);
596 privateData()->currentClickable = click;
601 if(!onClickable) endHoverMode();
605 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
606 if(privateData()->currentClickable.isValid()) {
607 Clickable click = privateData()->currentClickable;
610 privateData()->activeClickable = click;
611 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
612 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
614 case Clickable::Channel: {
615 // Hide existing menu actions, they confuse us when right-clicking on a clickable
616 foreach(QAction *action, menu->actions())
617 action->setVisible(false);
618 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
619 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
626 // Buffer-specific actions
627 ChatItem::addActionsToMenu(menu, pos);
631 void ContentsChatItem::copyLinkToClipboard() {
632 Clickable click = privateData()->activeClickable;
633 if(click.isValid() && click.type == Clickable::Url) {
634 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
635 if(!url.contains("://"))
636 url = "http://" + url;
637 chatScene()->stringToClipboard(url);
641 /******** WEB PREVIEW *****************************************************************************/
643 void ContentsChatItem::showWebPreview(const Clickable &click) {
649 QTextLine line = layout.lineForTextPosition(click.start);
650 qreal x = line.cursorToX(click.start);
651 qreal width = line.cursorToX(click.start + click.length) - x;
652 qreal height = line.height();
653 qreal y = height * line.lineNumber();
655 QPointF topLeft = scenePos() + QPointF(x, y);
656 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
658 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
659 if(!url.contains("://"))
660 url = "http://" + url;
661 chatScene()->loadWebPreview(this, url, urlRect);
665 void ContentsChatItem::clearWebPreview() {
667 chatScene()->clearWebPreview(this);
671 /*************************************************************************************************/
673 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
675 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
682 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
685 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
686 if(wordidx >= wrapList.count())
690 qreal targetWidth = lineCount * item->width() + choppedTrailing;
692 qint16 start = wordidx;
693 qint16 end = wrapList.count() - 1;
695 // check if the whole line fits
696 if(wrapList.at(end).endX <= targetWidth) // || start == end)
699 // check if we have a very long word that needs inter word wrap
700 if(wrapList.at(start).endX > targetWidth) {
701 if(!line.isValid()) {
702 item->initLayoutHelper(&layout, QTextOption::NoWrap);
703 layout.beginLayout();
704 line = layout.createLine();
707 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
711 if(start + 1 == end) {
713 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
715 // both cases should be cought preliminary
716 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
717 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
719 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
720 return wrapList.at(wordidx).start;
723 qint16 pivot = (end + start) / 2;
724 if(wrapList.at(pivot).endX > targetWidth) {
734 /*************************************************************************************************/