1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include <QApplication>
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 "iconloader.h"
38 #include "qtuistyle.h"
40 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
41 : QGraphicsItem(parent),
43 _boundingRect(0, 0, width, height),
44 _selectionMode(NoSelection),
47 setAcceptHoverEvents(true);
52 ChatItem::~ChatItem() {
56 QVariant ChatItem::data(int role) const {
57 QModelIndex index = model()->index(row(), column());
58 if(!index.isValid()) {
59 qWarning() << "ChatItem::data(): model index is invalid!" << index;
62 return model()->data(index, role);
65 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
66 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
69 option.setWrapMode(wrapMode);
70 option.setAlignment(alignment);
71 layout->setTextOption(option);
73 QList<QTextLayout::FormatRange> formatRanges
74 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
75 layout->setAdditionalFormats(formatRanges);
79 void ChatItem::doLayout() {
80 QTextLayout *layout_ = layout();
81 layout_->beginLayout();
82 QTextLine line = layout_->createLine();
84 line.setLineWidth(width());
85 line.setPosition(QPointF(0,0));
90 void ChatItem::clearLayout() {
95 ChatItemPrivate *ChatItem::privateData() const {
97 ChatItem *that = const_cast<ChatItem *>(this);
98 that->_data = that->newPrivateData();
104 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
105 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
106 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
107 Q_UNUSED(option); Q_UNUSED(widget);
108 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
109 QVector<QTextLayout::FormatRange> formats = additionalFormats();
110 QTextLayout::FormatRange selectFmt = selectionFormat();
111 if(selectFmt.format.isValid()) formats.append(selectFmt);
112 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
115 // uncomment partially or all of the following stuff:
117 // 0) alternativ painter color for debug stuff
119 // painter->setPen(Qt::red);
121 // painter->setPen(Qt::blue);
122 // 1) draw wordwrap points in the first line
123 // if(column() == 2) {
124 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
125 // foreach(ChatLineModel::Word word, wrapList) {
126 // if(word.endX > width())
128 // painter->drawLine(word.endX, 0, word.endX, height());
131 // 2) draw MsgId over the time column
132 // if(column() == 0) {
133 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
134 // QPointF bottomPoint = boundingRect().bottomLeft();
135 // bottomPoint.ry() -= 2;
136 // painter->drawText(bottomPoint, msgIdString);
138 // 3) draw bounding rect
139 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
142 qint16 ChatItem::posToCursor(const QPointF &pos) const {
143 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
144 if(pos.y() < 0) return 0;
145 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
146 QTextLine line = layout()->lineAt(l);
147 if(pos.y() >= line.y()) {
148 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
154 bool ChatItem::hasSelection() const {
155 if(_selectionMode == NoSelection)
157 if(_selectionMode == FullSelection)
160 return _selectionStart != _selectionEnd;
163 QString ChatItem::selection() const {
164 if(_selectionMode == FullSelection)
165 return data(MessageModel::DisplayRole).toString();
166 if(_selectionMode == PartialSelection)
167 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
171 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
172 _selectionMode = mode;
173 _selectionStart = start;
178 void ChatItem::setFullSelection() {
179 if(_selectionMode != FullSelection) {
180 _selectionMode = FullSelection;
185 void ChatItem::clearSelection() {
186 if(_selectionMode != NoSelection) {
187 _selectionMode = NoSelection;
192 void ChatItem::continueSelecting(const QPointF &pos) {
193 _selectionMode = PartialSelection;
194 _selectionEnd = posToCursor(pos);
198 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
199 if(_selectionMode == FullSelection)
201 if(_selectionMode == PartialSelection) {
202 int cursor = posToCursor(pos);
203 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
208 QTextLayout::FormatRange ChatItem::selectionFormat() const {
209 QTextLayout::FormatRange selectFmt;
210 if(_selectionMode != NoSelection) {
211 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
212 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
213 if(_selectionMode == PartialSelection) {
214 selectFmt.start = qMin(_selectionStart, _selectionEnd);
215 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
216 } else { // FullSelection
218 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
221 selectFmt.start = -1;
222 selectFmt.length = 0;
227 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
228 QList<QRectF> resultList;
229 const QAbstractItemModel *model_ = model();
233 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
234 QList<int> indexList;
235 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
236 while(searchIdx != -1) {
237 indexList << searchIdx;
238 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
241 bool hadPrivateData = hasPrivateData();
243 foreach(int idx, indexList) {
244 QTextLine line = layout()->lineForTextPosition(idx);
245 qreal x = line.cursorToX(idx);
246 qreal width = line.cursorToX(idx + searchWord.count()) - x;
247 qreal height = line.height();
248 qreal y = height * line.lineNumber();
249 resultList << QRectF(x, y, width, height);
257 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
258 // single clicks are already handled by the scene (for clearing the selection)
259 if(clickMode == ChatScene::DragStartClick) {
260 chatScene()->setSelectingItem(this);
261 _selectionStart = _selectionEnd = posToCursor(pos);
262 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
267 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
268 if(event->buttons() == Qt::LeftButton) {
269 if(contains(event->pos())) {
270 qint16 end = posToCursor(event->pos());
271 if(end != _selectionEnd) {
273 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
278 chatScene()->startGlobalSelection(this, event->pos());
286 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
287 if(event->buttons() == Qt::LeftButton)
293 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
294 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
295 chatScene()->selectionToClipboard(QClipboard::Selection);
301 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
307 // ************************************************************
309 // ************************************************************
311 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
312 Q_UNUSED(option); Q_UNUSED(widget);
314 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
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)
365 const QAbstractItemModel *model_ = model();
366 QModelIndex index = model_->index(row(), column());
367 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
369 setGeometryByWidth(width);
372 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
374 prepareGeometryChange();
378 WrapColumnFinder finder(this);
379 while(finder.nextWrapColumn() > 0)
381 setHeight(lines * fontMetrics()->lineSpacing());
386 void ContentsChatItem::doLayout() {
387 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
388 if(!wrapList.count()) return; // empty chatitem
391 WrapColumnFinder finder(this);
392 layout()->beginLayout();
394 QTextLine line = layout()->createLine();
398 int col = finder.nextWrapColumn();
399 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
400 line.setPosition(QPointF(0, h));
401 h += fontMetrics()->lineSpacing();
403 layout()->endLayout();
406 // NOTE: This method is not threadsafe and not reentrant!
407 // (RegExps are not constant while matching, and they are static here for efficiency)
408 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
410 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
411 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
413 static QRegExp regExp[] = {
415 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
416 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|gopher://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
419 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
420 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
422 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
425 static const int regExpCount = 2; // number of regexps in the array above
427 qint16 matches[] = { 0, 0, 0 };
428 qint16 matchEnd[] = { 0, 0, 0 };
430 QString str = data(ChatLineModel::DisplayRole).toString();
432 QList<Clickable> result;
439 minidx = str.length();
440 for(int i = 0; i < regExpCount; i++) {
441 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
442 if(idx >= matchEnd[i]) {
443 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
444 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
446 if(matches[i] >= 0 && matches[i] < minidx) {
452 idx = matchEnd[type];
453 QString match = str.mid(matches[type], matchEnd[type] - matches[type]);
454 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
455 if(!match.contains('(')) {
460 if(type == Clickable::Channel) {
461 // don't make clickable if it could be a #number
462 if(QRegExp("^#\\d+$").exactMatch(match))
465 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
470 if(!result.isEmpty()) qDebug() << str;
471 foreach(Clickable click, result) {
472 qDebug() << str.mid(click.start, click.length);
478 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
479 qint16 idx = posToCursor(pos);
480 for(int i = 0; i < privateData()->clickables.count(); i++) {
481 Clickable click = privateData()->clickables.at(i);
482 if(idx >= click.start && idx < click.start + click.length)
488 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
489 // mark a clickable if hovered upon
490 QVector<QTextLayout::FormatRange> fmt;
491 if(privateData()->currentClickable.isValid()) {
492 Clickable click = privateData()->currentClickable;
493 QTextLayout::FormatRange f;
494 f.start = click.start;
495 f.length = click.length;
496 f.format.setFontUnderline(true);
502 void ContentsChatItem::endHoverMode() {
503 if(hasPrivateData()) {
504 if(privateData()->currentClickable.isValid()) {
505 setCursor(Qt::ArrowCursor);
506 privateData()->currentClickable = Clickable();
513 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
514 if(clickMode == ChatScene::SingleClick) {
515 Clickable click = clickableAt(pos);
516 if(click.isValid()) {
517 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
520 if(!str.contains("://"))
521 str = "http://" + str;
522 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
524 case Clickable::Channel: {
525 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
526 BufferId bufId = Client::networkModel()->bufferId(networkId, str);
527 if(bufId.isValid()) {
528 QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
529 Client::bufferModel()->switchToBuffer(bufId);
530 if(!targetIdx.data(NetworkModel::ItemActiveRole).toBool())
531 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
533 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
540 } else if(clickMode == ChatScene::DoubleClick) {
541 chatScene()->setSelectingItem(this);
542 setSelectionMode(PartialSelection);
543 Clickable click = clickableAt(pos);
544 if(click.isValid()) {
545 setSelectionStart(click.start);
546 setSelectionEnd(click.start + click.length);
548 // find word boundary
549 QString str = data(ChatLineModel::DisplayRole).toString();
550 qint16 cursor = posToCursor(pos);
551 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
552 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
553 if(end < 0) end = str.length();
554 setSelectionStart(start);
555 setSelectionEnd(end);
558 } else if(clickMode == ChatScene::TripleClick) {
559 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
561 ChatItem::handleClick(pos, clickMode);
564 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
565 // mouse move events always mean we're not hovering anymore...
567 ChatItem::mouseMoveEvent(event);
570 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
575 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
576 bool onClickable = false;
577 Clickable click = clickableAt(event->pos());
578 if(click.isValid()) {
579 if(click.type == Clickable::Url) {
581 showWebPreview(click);
582 } else if(click.type == Clickable::Channel) {
583 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
584 // don't make clickable if it's our own name
585 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
586 if(Client::networkModel()->bufferName(myId) != name)
590 setCursor(Qt::PointingHandCursor);
591 privateData()->currentClickable = click;
596 if(!onClickable) endHoverMode();
600 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
601 Q_UNUSED(pos); // we assume that the current mouse cursor pos is the point of invocation
603 if(privateData()->currentClickable.isValid()) {
604 Clickable click = privateData()->currentClickable;
607 privateData()->activeClickable = click;
608 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
609 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
611 case Clickable::Channel: {
612 // Hide existing menu actions, they confuse us when right-clicking on a clickable
613 foreach(QAction *action, menu->actions())
614 action->setVisible(false);
615 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
616 Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
624 // Buffer-specific actions
625 Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
629 void ContentsChatItem::copyLinkToClipboard() {
630 Clickable click = privateData()->activeClickable;
631 if(click.isValid() && click.type == Clickable::Url) {
632 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
633 if(!url.contains("://"))
634 url = "http://" + url;
635 chatScene()->stringToClipboard(url);
639 /******** WEB PREVIEW *****************************************************************************/
641 void ContentsChatItem::showWebPreview(const Clickable &click) {
645 QTextLine line = layout()->lineForTextPosition(click.start);
646 qreal x = line.cursorToX(click.start);
647 qreal width = line.cursorToX(click.start + click.length) - x;
648 qreal height = line.height();
649 qreal y = height * line.lineNumber();
651 QPointF topLeft = scenePos() + QPointF(x, y);
652 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
654 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
655 if(!url.contains("://"))
656 url = "http://" + url;
657 chatScene()->loadWebPreview(this, url, urlRect);
661 void ContentsChatItem::clearWebPreview() {
663 chatScene()->clearWebPreview(this);
667 /*************************************************************************************************/
669 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
672 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
679 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
683 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
684 if(wordidx >= wrapList.count())
688 qreal targetWidth = lineCount * item->width() + choppedTrailing;
690 qint16 start = wordidx;
691 qint16 end = wrapList.count() - 1;
693 // check if the whole line fits
694 if(wrapList.at(end).endX <= targetWidth) // || start == end)
697 // check if we have a very long word that needs inter word wrap
698 if(wrapList.at(start).endX > targetWidth) {
699 if(!line.isValid()) {
700 layout = item->createLayout(QTextOption::NoWrap);
701 layout->beginLayout();
702 line = layout->createLine();
705 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
709 if(start + 1 == end) {
711 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
713 // both cases should be cought preliminary
714 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
715 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
717 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
718 return wrapList.at(wordidx).start;
721 qint16 pivot = (end + start) / 2;
722 if(wrapList.at(pivot).endX > targetWidth) {
732 /*************************************************************************************************/