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>
33 #include "chatlinemodel.h"
35 #include "qtuistyle.h"
37 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
38 : QGraphicsItem(parent),
40 _boundingRect(0, 0, width, height),
41 _selectionMode(NoSelection),
44 setAcceptHoverEvents(true);
49 ChatItem::~ChatItem() {
53 QVariant ChatItem::data(int role) const {
54 QModelIndex index = model()->index(row(), column());
55 if(!index.isValid()) {
56 qWarning() << "ChatItem::data(): model index is invalid!" << index;
59 return model()->data(index, role);
62 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
63 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
66 option.setWrapMode(wrapMode);
67 option.setAlignment(alignment);
68 layout->setTextOption(option);
70 QList<QTextLayout::FormatRange> formatRanges
71 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
72 layout->setAdditionalFormats(formatRanges);
76 void ChatItem::doLayout() {
77 QTextLayout *layout_ = layout();
78 layout_->beginLayout();
79 QTextLine line = layout_->createLine();
81 line.setLineWidth(width());
82 line.setPosition(QPointF(0,0));
87 void ChatItem::clearLayout() {
92 ChatItemPrivate *ChatItem::privateData() const {
94 ChatItem *that = const_cast<ChatItem *>(this);
95 that->_data = that->newPrivateData();
101 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
102 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
103 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
104 Q_UNUSED(option); Q_UNUSED(widget);
105 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
106 QVector<QTextLayout::FormatRange> formats = additionalFormats();
107 QTextLayout::FormatRange selectFmt = selectionFormat();
108 if(selectFmt.format.isValid()) formats.append(selectFmt);
109 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
112 // uncomment partially or all of the following stuff:
114 // 0) alternativ painter color for debug stuff
116 // painter->setPen(Qt::red);
118 // painter->setPen(Qt::blue);
119 // 1) draw wordwrap points in the first line
120 // if(column() == 2) {
121 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
122 // foreach(ChatLineModel::Word word, wrapList) {
123 // if(word.endX > width())
125 // painter->drawLine(word.endX, 0, word.endX, height());
128 // 2) draw MsgId over the time column
129 // if(column() == 0) {
130 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
131 // QPointF bottomPoint = boundingRect().bottomLeft();
132 // bottomPoint.ry() -= 2;
133 // painter->drawText(bottomPoint, msgIdString);
135 // 3) draw bounding rect
136 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
139 qint16 ChatItem::posToCursor(const QPointF &pos) const {
140 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
141 if(pos.y() < 0) return 0;
142 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
143 QTextLine line = layout()->lineAt(l);
144 if(pos.y() >= line.y()) {
145 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
151 bool ChatItem::hasSelection() const {
152 if(_selectionMode == NoSelection)
154 if(_selectionMode == FullSelection)
157 return _selectionStart != _selectionEnd;
160 QString ChatItem::selection() const {
161 if(_selectionMode == FullSelection)
162 return data(MessageModel::DisplayRole).toString();
163 if(_selectionMode == PartialSelection)
164 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
168 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
169 _selectionMode = mode;
170 _selectionStart = start;
175 void ChatItem::setFullSelection() {
176 if(_selectionMode != FullSelection) {
177 _selectionMode = FullSelection;
182 void ChatItem::clearSelection() {
183 if(_selectionMode != NoSelection) {
184 _selectionMode = NoSelection;
189 void ChatItem::continueSelecting(const QPointF &pos) {
190 _selectionMode = PartialSelection;
191 _selectionEnd = posToCursor(pos);
195 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
196 if(_selectionMode == FullSelection)
198 if(_selectionMode == PartialSelection) {
199 int cursor = posToCursor(pos);
200 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
205 QTextLayout::FormatRange ChatItem::selectionFormat() const {
206 QTextLayout::FormatRange selectFmt;
207 if(_selectionMode != NoSelection) {
208 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
209 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
210 if(_selectionMode == PartialSelection) {
211 selectFmt.start = qMin(_selectionStart, _selectionEnd);
212 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
213 } else { // FullSelection
215 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
218 selectFmt.start = -1;
219 selectFmt.length = 0;
224 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
225 QList<QRectF> resultList;
226 const QAbstractItemModel *model_ = model();
230 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
231 QList<int> indexList;
232 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
233 while(searchIdx != -1) {
234 indexList << searchIdx;
235 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
238 bool hadPrivateData = hasPrivateData();
240 foreach(int idx, indexList) {
241 QTextLine line = layout()->lineForTextPosition(idx);
242 qreal x = line.cursorToX(idx);
243 qreal width = line.cursorToX(idx + searchWord.count()) - x;
244 qreal height = line.height();
245 qreal y = height * line.lineNumber();
246 resultList << QRectF(x, y, width, height);
254 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
255 // single clicks are already handled by the scene (for clearing the selection)
256 if(clickMode == ChatScene::DragStartClick) {
257 chatScene()->setSelectingItem(this);
258 _selectionStart = _selectionEnd = posToCursor(pos);
259 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
264 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
265 if(event->buttons() == Qt::LeftButton) {
266 if(contains(event->pos())) {
267 qint16 end = posToCursor(event->pos());
268 if(end != _selectionEnd) {
270 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
275 chatScene()->startGlobalSelection(this, event->pos());
283 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
284 if(event->buttons() == Qt::LeftButton)
290 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
291 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
292 chatScene()->selectionToClipboard(QClipboard::Selection);
298 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
304 // ************************************************************
306 // ************************************************************
308 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
309 Q_UNUSED(option); Q_UNUSED(widget);
311 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
312 qreal layoutWidth = layout()->minimumWidth();
314 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
315 offset = qMin(width() - layoutWidth, (qreal)0);
317 offset = qMax(layoutWidth - width(), (qreal)0);
319 QTextLayout::FormatRange selectFmt = selectionFormat();
321 if(layoutWidth > width()) {
322 // Draw a nice gradient for longer items
323 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
324 QPixmap pixmap(layout()->boundingRect().toRect().size());
325 pixmap.fill(Qt::transparent);
326 QPainter pixPainter(&pixmap);
327 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
330 // Create alpha channel mask
331 QPixmap mask(pixmap.size());
332 QPainter maskPainter(&mask);
333 QLinearGradient gradient;
335 gradient.setStart(0, 0);
336 gradient.setFinalStop(12, 0);
337 gradient.setColorAt(0, Qt::black);
338 gradient.setColorAt(1, Qt::white);
340 gradient.setStart(width()-10, 0);
341 gradient.setFinalStop(width(), 0);
342 gradient.setColorAt(0, Qt::white);
343 gradient.setColorAt(1, Qt::black);
345 maskPainter.fillRect(boundingRect(), gradient);
346 pixmap.setAlphaChannel(mask);
347 painter->drawPixmap(0, 0, pixmap);
349 layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
353 // ************************************************************
355 // ************************************************************
357 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
359 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
360 : ChatItem(0, 0, pos, parent)
362 const QAbstractItemModel *model_ = model();
363 QModelIndex index = model_->index(row(), column());
364 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
366 setGeometryByWidth(width);
369 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
371 prepareGeometryChange();
375 WrapColumnFinder finder(this);
376 while(finder.nextWrapColumn() > 0)
378 setHeight(lines * fontMetrics()->lineSpacing());
383 void ContentsChatItem::doLayout() {
384 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
385 if(!wrapList.count()) return; // empty chatitem
388 WrapColumnFinder finder(this);
389 layout()->beginLayout();
391 QTextLine line = layout()->createLine();
395 int col = finder.nextWrapColumn();
396 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
397 line.setPosition(QPointF(0, h));
398 h += fontMetrics()->lineSpacing();
400 layout()->endLayout();
403 // NOTE: This method is not threadsafe and not reentrant!
404 // (RegExps are not constant while matching, and they are static here for efficiency)
405 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
407 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
408 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
410 static QRegExp regExp[] = {
412 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
413 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|gopher://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
416 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
417 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
419 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
422 static const int regExpCount = 2; // number of regexps in the array above
424 qint16 matches[] = { 0, 0, 0 };
425 qint16 matchEnd[] = { 0, 0, 0 };
427 QString str = data(ChatLineModel::DisplayRole).toString();
429 QList<Clickable> result;
436 minidx = str.length();
437 for(int i = 0; i < regExpCount; i++) {
438 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
439 if(idx >= matchEnd[i]) {
440 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
441 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
443 if(matches[i] >= 0 && matches[i] < minidx) {
449 idx = matchEnd[type];
450 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
451 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
453 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
458 if(!result.isEmpty()) qDebug() << str;
459 foreach(Clickable click, result) {
460 qDebug() << str.mid(click.start, click.length);
466 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
467 qint16 idx = posToCursor(pos);
468 for(int i = 0; i < privateData()->clickables.count(); i++) {
469 Clickable click = privateData()->clickables.at(i);
470 if(idx >= click.start && idx < click.start + click.length)
476 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
477 // mark a clickable if hovered upon
478 QVector<QTextLayout::FormatRange> fmt;
479 if(privateData()->currentClickable.isValid()) {
480 Clickable click = privateData()->currentClickable;
481 QTextLayout::FormatRange f;
482 f.start = click.start;
483 f.length = click.length;
484 f.format.setFontUnderline(true);
490 void ContentsChatItem::endHoverMode() {
491 if(hasPrivateData()) {
492 if(privateData()->currentClickable.isValid()) {
493 setCursor(Qt::ArrowCursor);
494 privateData()->currentClickable = Clickable();
501 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
502 if(clickMode == ChatScene::SingleClick) {
503 Clickable click = clickableAt(pos);
504 if(click.isValid()) {
505 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
508 if(!str.contains("://"))
509 str = "http://" + str;
510 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
512 case Clickable::Channel:
513 // TODO join or whatever...
519 } else if(clickMode == ChatScene::DoubleClick) {
520 chatScene()->setSelectingItem(this);
521 setSelectionMode(PartialSelection);
522 Clickable click = clickableAt(pos);
523 if(click.isValid()) {
524 setSelectionStart(click.start);
525 setSelectionEnd(click.start + click.length);
527 // find word boundary
528 QString str = data(ChatLineModel::DisplayRole).toString();
529 qint16 cursor = posToCursor(pos);
530 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
531 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
532 if(end < 0) end = str.length();
533 setSelectionStart(start);
534 setSelectionEnd(end);
537 } else if(clickMode == ChatScene::TripleClick) {
538 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
540 ChatItem::handleClick(pos, clickMode);
543 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
544 // mouse move events always mean we're not hovering anymore...
546 ChatItem::mouseMoveEvent(event);
549 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
554 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
555 bool onClickable = false;
556 Clickable click = clickableAt(event->pos());
557 if(click.isValid()) {
558 if(click.type == Clickable::Url) {
560 showWebPreview(click);
561 } else if(click.type == Clickable::Channel) {
562 // TODO: don't make clickable if it's our own name
563 // onClickable = true; //FIXME disabled for now
566 setCursor(Qt::PointingHandCursor);
567 privateData()->currentClickable = click;
572 if(!onClickable) endHoverMode();
576 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
577 Q_UNUSED(pos); // we assume that the current mouse cursor pos is the point of invocation
579 if(privateData()->currentClickable.isValid()) {
580 switch(privateData()->currentClickable.type) {
582 privateData()->activeClickable = privateData()->currentClickable;
583 menu->addAction(tr("Copy Link Address"), &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
592 void ContentsChatItem::copyLinkToClipboard() {
593 Clickable click = privateData()->activeClickable;
594 if(click.isValid() && click.type == Clickable::Url) {
595 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
596 if(!url.contains("://"))
597 url = "http://" + url;
598 chatScene()->stringToClipboard(url);
602 /******** WEB PREVIEW *****************************************************************************/
604 void ContentsChatItem::showWebPreview(const Clickable &click) {
608 QTextLine line = layout()->lineForTextPosition(click.start);
609 qreal x = line.cursorToX(click.start);
610 qreal width = line.cursorToX(click.start + click.length) - x;
611 qreal height = line.height();
612 qreal y = height * line.lineNumber();
614 QPointF topLeft = scenePos() + QPointF(x, y);
615 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
617 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
618 if(!url.contains("://"))
619 url = "http://" + url;
620 chatScene()->loadWebPreview(this, url, urlRect);
624 void ContentsChatItem::clearWebPreview() {
626 chatScene()->clearWebPreview(this);
630 /*************************************************************************************************/
632 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
635 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
642 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
646 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
647 if(wordidx >= wrapList.count())
651 qreal targetWidth = lineCount * item->width() + choppedTrailing;
653 qint16 start = wordidx;
654 qint16 end = wrapList.count() - 1;
656 // check if the whole line fits
657 if(wrapList.at(end).endX <= targetWidth) // || start == end)
660 // check if we have a very long word that needs inter word wrap
661 if(wrapList.at(start).endX > targetWidth) {
662 if(!line.isValid()) {
663 layout = item->createLayout(QTextOption::NoWrap);
664 layout->beginLayout();
665 line = layout->createLine();
668 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
672 if(start + 1 == end) {
674 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
676 // both cases should be cought preliminary
677 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
678 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
680 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
681 return wrapList.at(wordidx).start;
684 qint16 pivot = (end + start) / 2;
685 if(wrapList.at(pivot).endX > targetWidth) {
695 /*************************************************************************************************/