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 qint16 ChatItem::posToCursor(const QPointF &pos) const {
62 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
63 if(pos.y() < 0) return 0;
67 for(int l = layout.lineCount() - 1; l >= 0; l--) {
68 QTextLine line = layout.lineAt(l);
69 if(pos.y() >= line.y()) {
70 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
76 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
79 layout->setText(data(MessageModel::DisplayRole).toString());
82 option.setWrapMode(wrapMode);
83 option.setAlignment(alignment);
84 layout->setTextOption(option);
86 QList<QTextLayout::FormatRange> formatRanges
87 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
88 layout->setAdditionalFormats(formatRanges);
91 void ChatItem::doLayout(QTextLayout *layout) const {
92 layout->beginLayout();
93 QTextLine line = layout->createLine();
95 line.setLineWidth(width());
96 line.setPosition(QPointF(0,0));
101 void ChatItem::paintBackground(QPainter *painter) {
102 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
105 if(_selectionMode == FullSelection)
106 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
108 bgBrush = data(ChatLineModel::BackgroundRole);
109 if(bgBrush.isValid())
110 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
113 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
114 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
115 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
116 Q_UNUSED(option); Q_UNUSED(widget);
117 paintBackground(painter);
121 layout.draw(painter, QPointF(0,0), selectionFormats(), boundingRect());
123 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
126 // uncomment partially or all of the following stuff:
128 // 0) alternativ painter color for debug stuff
130 // painter->setPen(Qt::red);
132 // painter->setPen(Qt::blue);
133 // 1) draw wordwrap points in the first line
134 // if(column() == 2) {
135 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
136 // foreach(ChatLineModel::Word word, wrapList) {
137 // if(word.endX > width())
139 // painter->drawLine(word.endX, 0, word.endX, height());
142 // 2) draw MsgId over the time column
143 // if(column() == 0) {
144 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
145 // QPointF bottomPoint = boundingRect().bottomLeft();
146 // bottomPoint.ry() -= 2;
147 // painter->drawText(bottomPoint, msgIdString);
149 // 3) draw bounding rect
150 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
153 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
155 return QVector<QTextLayout::FormatRange>();
158 if(_selectionMode == FullSelection) {
160 end = data(MessageModel::DisplayRole).toString().length();
162 start = qMin(_selectionStart, _selectionEnd);
163 end = qMax(_selectionStart, _selectionEnd);
166 UiStyle::FormatList fmtList = data(MessageModel::FormatRole).value<UiStyle::FormatList>();
168 while(fmtList.count() >=2 && fmtList.at(1).first <= start)
169 fmtList.removeFirst();
171 fmtList.first().first = start;
173 while(fmtList.count() >= 2 && fmtList.last().first >= end)
174 fmtList.removeLast();
176 return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
179 bool ChatItem::hasSelection() const {
180 if(_selectionMode == NoSelection)
182 if(_selectionMode == FullSelection)
185 return _selectionStart != _selectionEnd;
188 QString ChatItem::selection() const {
189 if(_selectionMode == FullSelection)
190 return data(MessageModel::DisplayRole).toString();
191 if(_selectionMode == PartialSelection)
192 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
196 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
197 _selectionMode = mode;
198 _selectionStart = start;
203 void ChatItem::setFullSelection() {
204 if(_selectionMode != FullSelection) {
205 _selectionMode = FullSelection;
210 void ChatItem::clearSelection() {
211 if(_selectionMode != NoSelection) {
212 _selectionMode = NoSelection;
217 void ChatItem::continueSelecting(const QPointF &pos) {
218 _selectionMode = PartialSelection;
219 _selectionEnd = posToCursor(pos);
223 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
224 if(_selectionMode == FullSelection)
226 if(_selectionMode == PartialSelection) {
227 int cursor = posToCursor(pos);
228 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
233 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
234 QList<QRectF> resultList;
235 const QAbstractItemModel *model_ = model();
239 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
240 QList<int> indexList;
241 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
242 while(searchIdx != -1) {
243 indexList << searchIdx;
244 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
249 foreach(int idx, indexList) {
250 QTextLine line = layout.lineForTextPosition(idx);
251 qreal x = line.cursorToX(idx);
252 qreal width = line.cursorToX(idx + searchWord.count()) - x;
253 qreal height = line.height();
254 qreal y = height * line.lineNumber();
255 resultList << QRectF(x, y, width, height);
261 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
262 // single clicks are already handled by the scene (for clearing the selection)
263 if(clickMode == ChatScene::DragStartClick) {
264 chatScene()->setSelectingItem(this);
265 _selectionStart = _selectionEnd = posToCursor(pos);
266 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
271 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
272 if(event->buttons() == Qt::LeftButton) {
273 if(contains(event->pos())) {
274 qint16 end = posToCursor(event->pos());
275 if(end != _selectionEnd) {
277 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
282 chatScene()->startGlobalSelection(this, event->pos());
290 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
291 if(event->buttons() == Qt::LeftButton)
297 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
298 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
299 chatScene()->selectionToClipboard(QClipboard::Selection);
305 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
308 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
311 // ************************************************************
313 // ************************************************************
315 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
316 Q_UNUSED(option); Q_UNUSED(widget);
317 paintBackground(painter);
321 qreal layoutWidth = layout.minimumWidth();
323 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
324 offset = qMin(width() - layoutWidth, (qreal)0);
326 offset = qMax(layoutWidth - width(), (qreal)0);
328 if(layoutWidth > width()) {
329 // Draw a nice gradient for longer items
330 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
331 QPixmap pixmap(layout.boundingRect().toRect().size());
332 pixmap.fill(Qt::transparent);
333 QPainter pixPainter(&pixmap);
334 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), selectionFormats());
337 // Create alpha channel mask
338 QPixmap mask(pixmap.size());
339 QPainter maskPainter(&mask);
340 QLinearGradient gradient;
342 gradient.setStart(0, 0);
343 gradient.setFinalStop(12, 0);
344 gradient.setColorAt(0, Qt::black);
345 gradient.setColorAt(1, Qt::white);
347 gradient.setStart(width()-10, 0);
348 gradient.setFinalStop(width(), 0);
349 gradient.setColorAt(0, Qt::white);
350 gradient.setColorAt(1, Qt::black);
352 maskPainter.fillRect(boundingRect(), gradient);
353 pixmap.setAlphaChannel(mask);
354 painter->drawPixmap(0, 0, pixmap);
356 layout.draw(painter, QPointF(0,0), selectionFormats(), boundingRect());
360 // ************************************************************
362 // ************************************************************
364 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
366 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
367 : ChatItem(0, 0, pos, parent),
370 setGeometryByWidth(width);
373 QFontMetricsF *ContentsChatItem::fontMetrics() const {
374 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
377 ContentsChatItem::~ContentsChatItem() {
381 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
383 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
384 that->_data = new ContentsChatItemPrivate(findClickables(), that);
389 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
391 //qDebug() << Q_FUNC_INFO << "Geometry change requested with identical width!";
393 // We use this for reloading layout info as well
395 prepareGeometryChange();
399 WrapColumnFinder finder(this);
400 while(finder.nextWrapColumn() > 0)
402 setHeight(lines * fontMetrics()->lineSpacing());
409 void ContentsChatItem::doLayout(QTextLayout *layout) const {
410 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
411 if(!wrapList.count()) return; // empty chatitem
414 WrapColumnFinder finder(this);
415 layout->beginLayout();
417 QTextLine line = layout->createLine();
421 int col = finder.nextWrapColumn();
422 line.setNumColumns(col >= 0 ? col - line.textStart() : layout->text().length());
423 line.setPosition(QPointF(0, h));
424 h += fontMetrics()->lineSpacing();
429 // NOTE: This method is not threadsafe and not reentrant!
430 // (RegExps are not constant while matching, and they are static here for efficiency)
431 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
433 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
434 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]'^])");
436 static QRegExp regExp[] = {
438 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
439 QRegExp(QString("((?:(?:mailto:|\\w+://)|www\\.)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
442 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
443 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
445 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
448 static const int regExpCount = 2; // number of regexps in the array above
450 qint16 matches[] = { 0, 0, 0 };
451 qint16 matchEnd[] = { 0, 0, 0 };
453 QString str = data(ChatLineModel::DisplayRole).toString();
455 QList<Clickable> result;
462 minidx = str.length();
463 for(int i = 0; i < regExpCount; i++) {
464 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
465 if(idx >= matchEnd[i]) {
466 matches[i] = regExp[i].indexIn(str, qMax(matchEnd[i], idx));
467 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
469 if(matches[i] >= 0 && matches[i] < minidx) {
475 idx = matchEnd[type];
476 QString match = str.mid(matches[type], matchEnd[type] - matches[type]);
477 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
478 if(!match.contains('(')) {
483 if(type == Clickable::Channel) {
484 // don't make clickable if it could be a #number
485 if(QRegExp("^#\\d+$").exactMatch(match))
488 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
493 if(!result.isEmpty()) qDebug() << str;
494 foreach(Clickable click, result) {
495 qDebug() << str.mid(click.start, click.length);
501 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
502 qint16 idx = posToCursor(pos);
503 for(int i = 0; i < privateData()->clickables.count(); i++) {
504 Clickable click = privateData()->clickables.at(i);
505 if(idx >= click.start && idx < click.start + click.length)
511 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
512 // mark a clickable if hovered upon
513 QVector<QTextLayout::FormatRange> fmt;
514 if(privateData()->currentClickable.isValid()) {
515 Clickable click = privateData()->currentClickable;
516 QTextLayout::FormatRange f;
517 f.start = click.start;
518 f.length = click.length;
519 f.format.setFontUnderline(true);
525 void ContentsChatItem::endHoverMode() {
527 if(privateData()->currentClickable.isValid()) {
528 setCursor(Qt::ArrowCursor);
529 privateData()->currentClickable = Clickable();
536 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
537 if(clickMode == ChatScene::SingleClick) {
538 Clickable click = clickableAt(pos);
539 if(click.isValid()) {
540 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
543 if(!str.contains("://"))
544 str = "http://" + str;
545 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
547 case Clickable::Channel: {
548 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
549 BufferId bufId = Client::networkModel()->bufferId(networkId, str);
550 if(bufId.isValid()) {
551 QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
552 Client::bufferModel()->switchToBuffer(bufId);
553 if(!targetIdx.data(NetworkModel::ItemActiveRole).toBool())
554 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
556 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
563 } else if(clickMode == ChatScene::DoubleClick) {
564 chatScene()->setSelectingItem(this);
565 setSelectionMode(PartialSelection);
566 Clickable click = clickableAt(pos);
567 if(click.isValid()) {
568 setSelectionStart(click.start);
569 setSelectionEnd(click.start + click.length);
571 // find word boundary
572 QString str = data(ChatLineModel::DisplayRole).toString();
573 qint16 cursor = posToCursor(pos);
574 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
575 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
576 if(end < 0) end = str.length();
577 setSelectionStart(start);
578 setSelectionEnd(end);
581 } else if(clickMode == ChatScene::TripleClick) {
582 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
584 ChatItem::handleClick(pos, clickMode);
587 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
588 // mouse move events always mean we're not hovering anymore...
590 ChatItem::mouseMoveEvent(event);
593 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
598 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
599 bool onClickable = false;
600 Clickable click = clickableAt(event->pos());
601 if(click.isValid()) {
602 if(click.type == Clickable::Url) {
604 showWebPreview(click);
605 } else if(click.type == Clickable::Channel) {
606 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
607 // don't make clickable if it's our own name
608 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
609 if(Client::networkModel()->bufferName(myId) != name)
613 setCursor(Qt::PointingHandCursor);
614 privateData()->currentClickable = click;
619 if(!onClickable) endHoverMode();
623 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
624 if(privateData()->currentClickable.isValid()) {
625 Clickable click = privateData()->currentClickable;
628 privateData()->activeClickable = click;
629 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
630 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
632 case Clickable::Channel: {
633 // Hide existing menu actions, they confuse us when right-clicking on a clickable
634 foreach(QAction *action, menu->actions())
635 action->setVisible(false);
636 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
637 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
644 // Buffer-specific actions
645 ChatItem::addActionsToMenu(menu, pos);
649 void ContentsChatItem::copyLinkToClipboard() {
650 Clickable click = privateData()->activeClickable;
651 if(click.isValid() && click.type == Clickable::Url) {
652 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
653 if(!url.contains("://"))
654 url = "http://" + url;
655 chatScene()->stringToClipboard(url);
659 /******** WEB PREVIEW *****************************************************************************/
661 void ContentsChatItem::showWebPreview(const Clickable &click) {
667 QTextLine line = layout.lineForTextPosition(click.start);
668 qreal x = line.cursorToX(click.start);
669 qreal width = line.cursorToX(click.start + click.length) - x;
670 qreal height = line.height();
671 qreal y = height * line.lineNumber();
673 QPointF topLeft = scenePos() + QPointF(x, y);
674 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
676 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
677 if(!url.contains("://"))
678 url = "http://" + url;
679 chatScene()->loadWebPreview(this, url, urlRect);
683 void ContentsChatItem::clearWebPreview() {
685 chatScene()->clearWebPreview(this);
689 /*************************************************************************************************/
691 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
693 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
700 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
703 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
704 if(wordidx >= wrapList.count())
708 qreal targetWidth = lineCount * item->width() + choppedTrailing;
710 qint16 start = wordidx;
711 qint16 end = wrapList.count() - 1;
713 // check if the whole line fits
714 if(wrapList.at(end).endX <= targetWidth) // || start == end)
717 // check if we have a very long word that needs inter word wrap
718 if(wrapList.at(start).endX > targetWidth) {
719 if(!line.isValid()) {
720 item->initLayoutHelper(&layout, QTextOption::NoWrap);
721 layout.beginLayout();
722 line = layout.createLine();
725 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
729 if(start + 1 == end) {
731 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
733 // both cases should be cought preliminary
734 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
735 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
737 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
738 return wrapList.at(wordidx).start;
741 qint16 pivot = (end + start) / 2;
742 if(wrapList.at(pivot).endX > targetWidth) {
752 /*************************************************************************************************/