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 "bufferview.h"
33 #include "chatlinemodel.h"
34 #include "iconloader.h"
37 #include "qtuistyle.h"
39 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
40 : QGraphicsItem(parent),
42 _boundingRect(0, 0, width, height),
43 _selectionMode(NoSelection),
46 setAcceptHoverEvents(true);
51 ChatItem::~ChatItem() {
55 QVariant ChatItem::data(int role) const {
56 QModelIndex index = model()->index(row(), column());
57 if(!index.isValid()) {
58 qWarning() << "ChatItem::data(): model index is invalid!" << index;
61 return model()->data(index, role);
64 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
65 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
68 option.setWrapMode(wrapMode);
69 option.setAlignment(alignment);
70 layout->setTextOption(option);
72 QList<QTextLayout::FormatRange> formatRanges
73 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
74 layout->setAdditionalFormats(formatRanges);
78 void ChatItem::doLayout() {
79 QTextLayout *layout_ = layout();
80 layout_->beginLayout();
81 QTextLine line = layout_->createLine();
83 line.setLineWidth(width());
84 line.setPosition(QPointF(0,0));
89 void ChatItem::clearLayout() {
94 ChatItemPrivate *ChatItem::privateData() const {
96 ChatItem *that = const_cast<ChatItem *>(this);
97 that->_data = that->newPrivateData();
103 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
104 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
105 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
106 Q_UNUSED(option); Q_UNUSED(widget);
107 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
108 QVector<QTextLayout::FormatRange> formats = additionalFormats();
109 QTextLayout::FormatRange selectFmt = selectionFormat();
110 if(selectFmt.format.isValid()) formats.append(selectFmt);
111 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
114 // uncomment partially or all of the following stuff:
116 // 0) alternativ painter color for debug stuff
118 // painter->setPen(Qt::red);
120 // painter->setPen(Qt::blue);
121 // 1) draw wordwrap points in the first line
122 // if(column() == 2) {
123 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
124 // foreach(ChatLineModel::Word word, wrapList) {
125 // if(word.endX > width())
127 // painter->drawLine(word.endX, 0, word.endX, height());
130 // 2) draw MsgId over the time column
131 // if(column() == 0) {
132 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
133 // QPointF bottomPoint = boundingRect().bottomLeft();
134 // bottomPoint.ry() -= 2;
135 // painter->drawText(bottomPoint, msgIdString);
137 // 3) draw bounding rect
138 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
141 qint16 ChatItem::posToCursor(const QPointF &pos) const {
142 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
143 if(pos.y() < 0) return 0;
144 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
145 QTextLine line = layout()->lineAt(l);
146 if(pos.y() >= line.y()) {
147 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
153 bool ChatItem::hasSelection() const {
154 if(_selectionMode == NoSelection)
156 if(_selectionMode == FullSelection)
159 return _selectionStart != _selectionEnd;
162 QString ChatItem::selection() const {
163 if(_selectionMode == FullSelection)
164 return data(MessageModel::DisplayRole).toString();
165 if(_selectionMode == PartialSelection)
166 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
170 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
171 _selectionMode = mode;
172 _selectionStart = start;
177 void ChatItem::setFullSelection() {
178 if(_selectionMode != FullSelection) {
179 _selectionMode = FullSelection;
184 void ChatItem::clearSelection() {
185 if(_selectionMode != NoSelection) {
186 _selectionMode = NoSelection;
191 void ChatItem::continueSelecting(const QPointF &pos) {
192 _selectionMode = PartialSelection;
193 _selectionEnd = posToCursor(pos);
197 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
198 if(_selectionMode == FullSelection)
200 if(_selectionMode == PartialSelection) {
201 int cursor = posToCursor(pos);
202 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
207 QTextLayout::FormatRange ChatItem::selectionFormat() const {
208 QTextLayout::FormatRange selectFmt;
209 if(_selectionMode != NoSelection) {
210 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
211 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
212 if(_selectionMode == PartialSelection) {
213 selectFmt.start = qMin(_selectionStart, _selectionEnd);
214 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
215 } else { // FullSelection
217 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
220 selectFmt.start = -1;
221 selectFmt.length = 0;
226 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
227 QList<QRectF> resultList;
228 const QAbstractItemModel *model_ = model();
232 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
233 QList<int> indexList;
234 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
235 while(searchIdx != -1) {
236 indexList << searchIdx;
237 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
240 bool hadPrivateData = hasPrivateData();
242 foreach(int idx, indexList) {
243 QTextLine line = layout()->lineForTextPosition(idx);
244 qreal x = line.cursorToX(idx);
245 qreal width = line.cursorToX(idx + searchWord.count()) - x;
246 qreal height = line.height();
247 qreal y = height * line.lineNumber();
248 resultList << QRectF(x, y, width, height);
256 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
257 // single clicks are already handled by the scene (for clearing the selection)
258 if(clickMode == ChatScene::DragStartClick) {
259 chatScene()->setSelectingItem(this);
260 _selectionStart = _selectionEnd = posToCursor(pos);
261 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
266 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
267 if(event->buttons() == Qt::LeftButton) {
268 if(contains(event->pos())) {
269 qint16 end = posToCursor(event->pos());
270 if(end != _selectionEnd) {
272 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
277 chatScene()->startGlobalSelection(this, event->pos());
285 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
286 if(event->buttons() == Qt::LeftButton)
292 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
293 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
294 chatScene()->selectionToClipboard(QClipboard::Selection);
300 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
306 // ************************************************************
308 // ************************************************************
310 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
311 Q_UNUSED(option); Q_UNUSED(widget);
313 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
314 qreal layoutWidth = layout()->minimumWidth();
316 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
317 offset = qMin(width() - layoutWidth, (qreal)0);
319 offset = qMax(layoutWidth - width(), (qreal)0);
321 QTextLayout::FormatRange selectFmt = selectionFormat();
323 if(layoutWidth > width()) {
324 // Draw a nice gradient for longer items
325 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
326 QPixmap pixmap(layout()->boundingRect().toRect().size());
327 pixmap.fill(Qt::transparent);
328 QPainter pixPainter(&pixmap);
329 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
332 // Create alpha channel mask
333 QPixmap mask(pixmap.size());
334 QPainter maskPainter(&mask);
335 QLinearGradient gradient;
337 gradient.setStart(0, 0);
338 gradient.setFinalStop(12, 0);
339 gradient.setColorAt(0, Qt::black);
340 gradient.setColorAt(1, Qt::white);
342 gradient.setStart(width()-10, 0);
343 gradient.setFinalStop(width(), 0);
344 gradient.setColorAt(0, Qt::white);
345 gradient.setColorAt(1, Qt::black);
347 maskPainter.fillRect(boundingRect(), gradient);
348 pixmap.setAlphaChannel(mask);
349 painter->drawPixmap(0, 0, pixmap);
351 layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
355 // ************************************************************
357 // ************************************************************
359 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
361 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
362 : ChatItem(0, 0, pos, parent)
364 const QAbstractItemModel *model_ = model();
365 QModelIndex index = model_->index(row(), column());
366 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
368 setGeometryByWidth(width);
371 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
373 prepareGeometryChange();
377 WrapColumnFinder finder(this);
378 while(finder.nextWrapColumn() > 0)
380 setHeight(lines * fontMetrics()->lineSpacing());
385 void ContentsChatItem::doLayout() {
386 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
387 if(!wrapList.count()) return; // empty chatitem
390 WrapColumnFinder finder(this);
391 layout()->beginLayout();
393 QTextLine line = layout()->createLine();
397 int col = finder.nextWrapColumn();
398 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
399 line.setPosition(QPointF(0, h));
400 h += fontMetrics()->lineSpacing();
402 layout()->endLayout();
405 // NOTE: This method is not threadsafe and not reentrant!
406 // (RegExps are not constant while matching, and they are static here for efficiency)
407 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
409 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
410 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
412 static QRegExp regExp[] = {
414 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
415 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|gopher://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
418 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
419 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
421 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
424 static const int regExpCount = 2; // number of regexps in the array above
426 qint16 matches[] = { 0, 0, 0 };
427 qint16 matchEnd[] = { 0, 0, 0 };
429 QString str = data(ChatLineModel::DisplayRole).toString();
431 QList<Clickable> result;
438 minidx = str.length();
439 for(int i = 0; i < regExpCount; i++) {
440 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
441 if(idx >= matchEnd[i]) {
442 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
443 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
445 if(matches[i] >= 0 && matches[i] < minidx) {
451 idx = matchEnd[type];
452 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
453 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
455 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
460 if(!result.isEmpty()) qDebug() << str;
461 foreach(Clickable click, result) {
462 qDebug() << str.mid(click.start, click.length);
468 ContentsChatItem::Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
469 qint16 idx = posToCursor(pos);
470 for(int i = 0; i < privateData()->clickables.count(); i++) {
471 Clickable click = privateData()->clickables.at(i);
472 if(idx >= click.start && idx < click.start + click.length)
478 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
479 // mark a clickable if hovered upon
480 QVector<QTextLayout::FormatRange> fmt;
481 if(privateData()->currentClickable.isValid()) {
482 Clickable click = privateData()->currentClickable;
483 QTextLayout::FormatRange f;
484 f.start = click.start;
485 f.length = click.length;
486 f.format.setFontUnderline(true);
492 void ContentsChatItem::endHoverMode() {
493 if(hasPrivateData()) {
494 if(privateData()->currentClickable.isValid()) {
495 setCursor(Qt::ArrowCursor);
496 privateData()->currentClickable = Clickable();
503 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
504 if(clickMode == ChatScene::SingleClick) {
505 Clickable click = clickableAt(pos);
506 if(click.isValid()) {
507 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
510 if(!str.contains("://"))
511 str = "http://" + str;
512 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
514 case Clickable::Channel:
515 // TODO join or whatever...
521 } else if(clickMode == ChatScene::DoubleClick) {
522 chatScene()->setSelectingItem(this);
523 setSelectionMode(PartialSelection);
524 Clickable click = clickableAt(pos);
525 if(click.isValid()) {
526 setSelectionStart(click.start);
527 setSelectionEnd(click.start + click.length);
529 // find word boundary
530 QString str = data(ChatLineModel::DisplayRole).toString();
531 qint16 cursor = posToCursor(pos);
532 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
533 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
534 if(end < 0) end = str.length();
535 setSelectionStart(start);
536 setSelectionEnd(end);
539 } else if(clickMode == ChatScene::TripleClick) {
540 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
542 ChatItem::handleClick(pos, clickMode);
545 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
546 // mouse move events always mean we're not hovering anymore...
548 ChatItem::mouseMoveEvent(event);
551 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
556 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
557 bool onClickable = false;
558 Clickable click = clickableAt(event->pos());
559 if(click.isValid()) {
560 if(click.type == Clickable::Url) {
562 showWebPreview(click);
563 } else if(click.type == Clickable::Channel) {
564 // don't make clickable if it's our own name
565 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
566 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
567 if(Client::networkModel()->bufferName(myId) != name)
571 setCursor(Qt::PointingHandCursor);
572 privateData()->currentClickable = click;
577 if(!onClickable) endHoverMode();
581 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
582 Q_UNUSED(pos); // we assume that the current mouse cursor pos is the point of invocation
584 if(privateData()->currentClickable.isValid()) {
585 Clickable click = privateData()->currentClickable;
588 privateData()->activeClickable = click;
589 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
590 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
592 case Clickable::Channel: {
593 // Hide existing menu actions, they confuse us when right-clicking on a clickable
594 foreach(QAction *action, menu->actions())
595 action->setVisible(false);
596 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
597 Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
605 // Buffer-specific actions
606 Client::mainUi()->actionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
610 void ContentsChatItem::copyLinkToClipboard() {
611 Clickable click = privateData()->activeClickable;
612 if(click.isValid() && click.type == Clickable::Url) {
613 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
614 if(!url.contains("://"))
615 url = "http://" + url;
616 chatScene()->stringToClipboard(url);
620 /******** WEB PREVIEW *****************************************************************************/
622 void ContentsChatItem::showWebPreview(const Clickable &click) {
626 QTextLine line = layout()->lineForTextPosition(click.start);
627 qreal x = line.cursorToX(click.start);
628 qreal width = line.cursorToX(click.start + click.length) - x;
629 qreal height = line.height();
630 qreal y = height * line.lineNumber();
632 QPointF topLeft = scenePos() + QPointF(x, y);
633 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
635 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
636 if(!url.contains("://"))
637 url = "http://" + url;
638 chatScene()->loadWebPreview(this, url, urlRect);
642 void ContentsChatItem::clearWebPreview() {
644 chatScene()->clearWebPreview(this);
648 /*************************************************************************************************/
650 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
653 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
660 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
664 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
665 if(wordidx >= wrapList.count())
669 qreal targetWidth = lineCount * item->width() + choppedTrailing;
671 qint16 start = wordidx;
672 qint16 end = wrapList.count() - 1;
674 // check if the whole line fits
675 if(wrapList.at(end).endX <= targetWidth) // || start == end)
678 // check if we have a very long word that needs inter word wrap
679 if(wrapList.at(start).endX > targetWidth) {
680 if(!line.isValid()) {
681 layout = item->createLayout(QTextOption::NoWrap);
682 layout->beginLayout();
683 line = layout->createLine();
686 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
690 if(start + 1 == end) {
692 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
694 // both cases should be cought preliminary
695 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
696 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
698 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
699 return wrapList.at(wordidx).start;
702 qint16 pivot = (end + start) / 2;
703 if(wrapList.at(pivot).endX > targetWidth) {
713 /*************************************************************************************************/