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(), data(ChatLineModel::MsgLabelRole).toUInt());
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
93 QVariant bgBrush = data(ChatLineModel::BackgroundRole);
95 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
97 QVector<QTextLayout::FormatRange> formats = additionalFormats();
98 QTextLayout::FormatRange selectFmt = selectionFormat();
99 if(selectFmt.format.isValid()) formats.append(selectFmt);
102 layout.draw(painter, QPointF(0,0), formats, boundingRect());
104 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
107 // uncomment partially or all of the following stuff:
109 // 0) alternativ painter color for debug stuff
111 // painter->setPen(Qt::red);
113 // painter->setPen(Qt::blue);
114 // 1) draw wordwrap points in the first line
115 // if(column() == 2) {
116 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
117 // foreach(ChatLineModel::Word word, wrapList) {
118 // if(word.endX > width())
120 // painter->drawLine(word.endX, 0, word.endX, height());
123 // 2) draw MsgId over the time column
124 // if(column() == 0) {
125 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
126 // QPointF bottomPoint = boundingRect().bottomLeft();
127 // bottomPoint.ry() -= 2;
128 // painter->drawText(bottomPoint, msgIdString);
130 // 3) draw bounding rect
131 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
134 qint16 ChatItem::posToCursor(const QPointF &pos) const {
135 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
136 if(pos.y() < 0) return 0;
140 for(int l = layout.lineCount() - 1; l >= 0; l--) {
141 QTextLine line = layout.lineAt(l);
142 if(pos.y() >= line.y()) {
143 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
149 bool ChatItem::hasSelection() const {
150 if(_selectionMode == NoSelection)
152 if(_selectionMode == FullSelection)
155 return _selectionStart != _selectionEnd;
158 QString ChatItem::selection() const {
159 if(_selectionMode == FullSelection)
160 return data(MessageModel::DisplayRole).toString();
161 if(_selectionMode == PartialSelection)
162 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
166 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
167 _selectionMode = mode;
168 _selectionStart = start;
173 void ChatItem::setFullSelection() {
174 if(_selectionMode != FullSelection) {
175 _selectionMode = FullSelection;
180 void ChatItem::clearSelection() {
181 if(_selectionMode != NoSelection) {
182 _selectionMode = NoSelection;
187 void ChatItem::continueSelecting(const QPointF &pos) {
188 _selectionMode = PartialSelection;
189 _selectionEnd = posToCursor(pos);
193 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
194 if(_selectionMode == FullSelection)
196 if(_selectionMode == PartialSelection) {
197 int cursor = posToCursor(pos);
198 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
203 QTextLayout::FormatRange ChatItem::selectionFormat() const {
204 QTextLayout::FormatRange selectFmt;
205 if(_selectionMode != NoSelection) {
206 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
207 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
208 if(_selectionMode == PartialSelection) {
209 selectFmt.start = qMin(_selectionStart, _selectionEnd);
210 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
211 } else { // FullSelection
213 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
216 selectFmt.start = -1;
217 selectFmt.length = 0;
222 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
223 QList<QRectF> resultList;
224 const QAbstractItemModel *model_ = model();
228 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
229 QList<int> indexList;
230 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
231 while(searchIdx != -1) {
232 indexList << searchIdx;
233 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
238 foreach(int idx, indexList) {
239 QTextLine line = layout.lineForTextPosition(idx);
240 qreal x = line.cursorToX(idx);
241 qreal width = line.cursorToX(idx + searchWord.count()) - x;
242 qreal height = line.height();
243 qreal y = height * line.lineNumber();
244 resultList << QRectF(x, y, width, height);
250 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
251 // single clicks are already handled by the scene (for clearing the selection)
252 if(clickMode == ChatScene::DragStartClick) {
253 chatScene()->setSelectingItem(this);
254 _selectionStart = _selectionEnd = posToCursor(pos);
255 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
260 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
261 if(event->buttons() == Qt::LeftButton) {
262 if(contains(event->pos())) {
263 qint16 end = posToCursor(event->pos());
264 if(end != _selectionEnd) {
266 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
271 chatScene()->startGlobalSelection(this, event->pos());
279 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
280 if(event->buttons() == Qt::LeftButton)
286 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
287 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
288 chatScene()->selectionToClipboard(QClipboard::Selection);
294 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
297 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
300 // ************************************************************
302 // ************************************************************
304 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
305 Q_UNUSED(option); Q_UNUSED(widget);
307 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
309 QVariant bgBrush = data(ChatLineModel::BackgroundRole);
310 if(bgBrush.isValid())
311 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
315 qreal layoutWidth = layout.minimumWidth();
317 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
318 offset = qMin(width() - layoutWidth, (qreal)0);
320 offset = qMax(layoutWidth - width(), (qreal)0);
322 QTextLayout::FormatRange selectFmt = selectionFormat();
324 if(layoutWidth > width()) {
325 // Draw a nice gradient for longer items
326 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
327 QPixmap pixmap(layout.boundingRect().toRect().size());
328 pixmap.fill(Qt::transparent);
329 QPainter pixPainter(&pixmap);
330 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
333 // Create alpha channel mask
334 QPixmap mask(pixmap.size());
335 QPainter maskPainter(&mask);
336 QLinearGradient gradient;
338 gradient.setStart(0, 0);
339 gradient.setFinalStop(12, 0);
340 gradient.setColorAt(0, Qt::black);
341 gradient.setColorAt(1, Qt::white);
343 gradient.setStart(width()-10, 0);
344 gradient.setFinalStop(width(), 0);
345 gradient.setColorAt(0, Qt::white);
346 gradient.setColorAt(1, Qt::black);
348 maskPainter.fillRect(boundingRect(), gradient);
349 pixmap.setAlphaChannel(mask);
350 painter->drawPixmap(0, 0, pixmap);
352 layout.draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
356 // ************************************************************
358 // ************************************************************
360 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
362 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
363 : ChatItem(0, 0, pos, parent),
366 const QAbstractItemModel *model_ = model();
367 QModelIndex index = model_->index(row(), column());
368 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
370 setGeometryByWidth(width);
373 ContentsChatItem::~ContentsChatItem() {
377 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
379 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
380 that->_data = new ContentsChatItemPrivate(findClickables(), that);
385 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
387 prepareGeometryChange();
391 WrapColumnFinder finder(this);
392 while(finder.nextWrapColumn() > 0)
394 setHeight(lines * fontMetrics()->lineSpacing());
401 void ContentsChatItem::doLayout(QTextLayout *layout) const {
402 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
403 if(!wrapList.count()) return; // empty chatitem
406 WrapColumnFinder finder(this);
407 layout->beginLayout();
409 QTextLine line = layout->createLine();
413 int col = finder.nextWrapColumn();
414 line.setNumColumns(col >= 0 ? col - line.textStart() : layout->text().length());
415 line.setPosition(QPointF(0, h));
416 h += fontMetrics()->lineSpacing();
421 // NOTE: This method is not threadsafe and not reentrant!
422 // (RegExps are not constant while matching, and they are static here for efficiency)
423 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
425 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
426 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]'^])");
428 static QRegExp regExp[] = {
430 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
431 QRegExp(QString("((?:(?:mailto:|\\w+://)|www\\.)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
434 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
435 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
437 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
440 static const int regExpCount = 2; // number of regexps in the array above
442 qint16 matches[] = { 0, 0, 0 };
443 qint16 matchEnd[] = { 0, 0, 0 };
445 QString str = data(ChatLineModel::DisplayRole).toString();
447 QList<Clickable> result;
454 minidx = str.length();
455 for(int i = 0; i < regExpCount; i++) {
456 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
457 if(idx >= matchEnd[i]) {
458 matches[i] = regExp[i].indexIn(str, qMax(matchEnd[i], idx));
459 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
461 if(matches[i] >= 0 && matches[i] < minidx) {
467 idx = matchEnd[type];
468 QString match = str.mid(matches[type], matchEnd[type] - matches[type]);
469 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
470 if(!match.contains('(')) {
475 if(type == Clickable::Channel) {
476 // don't make clickable if it could be a #number
477 if(QRegExp("^#\\d+$").exactMatch(match))
480 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
485 if(!result.isEmpty()) qDebug() << str;
486 foreach(Clickable click, result) {
487 qDebug() << str.mid(click.start, click.length);
493 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
494 qint16 idx = posToCursor(pos);
495 for(int i = 0; i < privateData()->clickables.count(); i++) {
496 Clickable click = privateData()->clickables.at(i);
497 if(idx >= click.start && idx < click.start + click.length)
503 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
504 // mark a clickable if hovered upon
505 QVector<QTextLayout::FormatRange> fmt;
506 if(privateData()->currentClickable.isValid()) {
507 Clickable click = privateData()->currentClickable;
508 QTextLayout::FormatRange f;
509 f.start = click.start;
510 f.length = click.length;
511 f.format.setFontUnderline(true);
517 void ContentsChatItem::endHoverMode() {
519 if(privateData()->currentClickable.isValid()) {
520 setCursor(Qt::ArrowCursor);
521 privateData()->currentClickable = Clickable();
528 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
529 if(clickMode == ChatScene::SingleClick) {
530 Clickable click = clickableAt(pos);
531 if(click.isValid()) {
532 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
535 if(!str.contains("://"))
536 str = "http://" + str;
537 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
539 case Clickable::Channel: {
540 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
541 BufferId bufId = Client::networkModel()->bufferId(networkId, str);
542 if(bufId.isValid()) {
543 QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
544 Client::bufferModel()->switchToBuffer(bufId);
545 if(!targetIdx.data(NetworkModel::ItemActiveRole).toBool())
546 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
548 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
555 } else if(clickMode == ChatScene::DoubleClick) {
556 chatScene()->setSelectingItem(this);
557 setSelectionMode(PartialSelection);
558 Clickable click = clickableAt(pos);
559 if(click.isValid()) {
560 setSelectionStart(click.start);
561 setSelectionEnd(click.start + click.length);
563 // find word boundary
564 QString str = data(ChatLineModel::DisplayRole).toString();
565 qint16 cursor = posToCursor(pos);
566 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
567 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
568 if(end < 0) end = str.length();
569 setSelectionStart(start);
570 setSelectionEnd(end);
573 } else if(clickMode == ChatScene::TripleClick) {
574 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
576 ChatItem::handleClick(pos, clickMode);
579 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
580 // mouse move events always mean we're not hovering anymore...
582 ChatItem::mouseMoveEvent(event);
585 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
590 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
591 bool onClickable = false;
592 Clickable click = clickableAt(event->pos());
593 if(click.isValid()) {
594 if(click.type == Clickable::Url) {
596 showWebPreview(click);
597 } else if(click.type == Clickable::Channel) {
598 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
599 // don't make clickable if it's our own name
600 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
601 if(Client::networkModel()->bufferName(myId) != name)
605 setCursor(Qt::PointingHandCursor);
606 privateData()->currentClickable = click;
611 if(!onClickable) endHoverMode();
615 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
616 if(privateData()->currentClickable.isValid()) {
617 Clickable click = privateData()->currentClickable;
620 privateData()->activeClickable = click;
621 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
622 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
624 case Clickable::Channel: {
625 // Hide existing menu actions, they confuse us when right-clicking on a clickable
626 foreach(QAction *action, menu->actions())
627 action->setVisible(false);
628 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
629 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
636 // Buffer-specific actions
637 ChatItem::addActionsToMenu(menu, pos);
641 void ContentsChatItem::copyLinkToClipboard() {
642 Clickable click = privateData()->activeClickable;
643 if(click.isValid() && click.type == Clickable::Url) {
644 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
645 if(!url.contains("://"))
646 url = "http://" + url;
647 chatScene()->stringToClipboard(url);
651 /******** WEB PREVIEW *****************************************************************************/
653 void ContentsChatItem::showWebPreview(const Clickable &click) {
659 QTextLine line = layout.lineForTextPosition(click.start);
660 qreal x = line.cursorToX(click.start);
661 qreal width = line.cursorToX(click.start + click.length) - x;
662 qreal height = line.height();
663 qreal y = height * line.lineNumber();
665 QPointF topLeft = scenePos() + QPointF(x, y);
666 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
668 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
669 if(!url.contains("://"))
670 url = "http://" + url;
671 chatScene()->loadWebPreview(this, url, urlRect);
675 void ContentsChatItem::clearWebPreview() {
677 chatScene()->clearWebPreview(this);
681 /*************************************************************************************************/
683 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
685 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
692 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
695 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
696 if(wordidx >= wrapList.count())
700 qreal targetWidth = lineCount * item->width() + choppedTrailing;
702 qint16 start = wordidx;
703 qint16 end = wrapList.count() - 1;
705 // check if the whole line fits
706 if(wrapList.at(end).endX <= targetWidth) // || start == end)
709 // check if we have a very long word that needs inter word wrap
710 if(wrapList.at(start).endX > targetWidth) {
711 if(!line.isValid()) {
712 item->initLayoutHelper(&layout, QTextOption::NoWrap);
713 layout.beginLayout();
714 line = layout.createLine();
717 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
721 if(start + 1 == end) {
723 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
725 // both cases should be cought preliminary
726 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
727 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
729 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
730 return wrapList.at(wordidx).start;
733 qint16 pivot = (end + start) / 2;
734 if(wrapList.at(pivot).endX > targetWidth) {
744 /*************************************************************************************************/