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 "chatlinemodel.h"
33 #include "qtuistyle.h"
35 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
36 : QGraphicsItem(parent),
38 _boundingRect(0, 0, width, height),
39 _selectionMode(NoSelection),
42 setAcceptHoverEvents(true);
47 ChatItem::~ChatItem() {
51 QVariant ChatItem::data(int role) const {
52 QModelIndex index = model()->index(row(), column());
53 if(!index.isValid()) {
54 qWarning() << "ChatItem::data(): model index is invalid!" << index;
57 return model()->data(index, role);
60 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
61 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
64 option.setWrapMode(wrapMode);
65 option.setAlignment(alignment);
66 layout->setTextOption(option);
68 QList<QTextLayout::FormatRange> formatRanges
69 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
70 layout->setAdditionalFormats(formatRanges);
74 void ChatItem::doLayout() {
75 QTextLayout *layout_ = layout();
76 layout_->beginLayout();
77 QTextLine line = layout_->createLine();
79 line.setLineWidth(width());
80 line.setPosition(QPointF(0,0));
85 void ChatItem::clearLayout() {
90 ChatItemPrivate *ChatItem::privateData() const {
92 ChatItem *that = const_cast<ChatItem *>(this);
93 that->_data = that->newPrivateData();
99 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
100 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
101 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
102 Q_UNUSED(option); Q_UNUSED(widget);
103 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
104 QVector<QTextLayout::FormatRange> formats = additionalFormats();
105 QTextLayout::FormatRange selectFmt = selectionFormat();
106 if(selectFmt.format.isValid()) formats.append(selectFmt);
107 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
110 // uncomment partially or all of the following stuff:
112 // 0) alternativ painter color for debug stuff
114 // painter->setPen(Qt::red);
116 // painter->setPen(Qt::blue);
117 // 1) draw wordwrap points in the first line
118 // if(column() == 2) {
119 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
120 // foreach(ChatLineModel::Word word, wrapList) {
121 // if(word.endX > width())
123 // painter->drawLine(word.endX, 0, word.endX, height());
126 // 2) draw MsgId over the time column
127 // if(column() == 0) {
128 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
129 // QPointF bottomPoint = boundingRect().bottomLeft();
130 // bottomPoint.ry() -= 2;
131 // painter->drawText(bottomPoint, msgIdString);
133 // 3) draw bounding rect
134 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
137 qint16 ChatItem::posToCursor(const QPointF &pos) {
138 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
139 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 void ChatItem::setFullSelection() {
150 if(_selectionMode != FullSelection) {
151 _selectionMode = FullSelection;
156 void ChatItem::clearSelection() {
157 _selectionMode = NoSelection;
161 void ChatItem::continueSelecting(const QPointF &pos) {
162 _selectionMode = PartialSelection;
163 _selectionEnd = posToCursor(pos);
167 QTextLayout::FormatRange ChatItem::selectionFormat() const {
168 QTextLayout::FormatRange selectFmt;
169 if(_selectionMode != NoSelection) {
170 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
171 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
172 if(_selectionMode == PartialSelection) {
173 selectFmt.start = qMin(_selectionStart, _selectionEnd);
174 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
175 } else { // FullSelection
177 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
180 selectFmt.start = -1;
181 selectFmt.length = 0;
186 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
187 QList<QRectF> resultList;
188 const QAbstractItemModel *model_ = model();
192 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
193 QList<int> indexList;
194 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
195 while(searchIdx != -1) {
196 indexList << searchIdx;
197 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
200 bool hadPrivateData = hasPrivateData();
202 foreach(int idx, indexList) {
203 QTextLine line = layout()->lineForTextPosition(idx);
204 qreal x = line.cursorToX(idx);
205 qreal width = line.cursorToX(idx + searchWord.count()) - x;
206 qreal height = line.height();
207 qreal y = height * line.lineNumber();
208 resultList << QRectF(x, y, width, height);
216 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
217 if(event->buttons() == Qt::LeftButton) {
218 chatScene()->setSelectingItem(this);
219 _selectionStart = _selectionEnd = posToCursor(event->pos());
220 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
228 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
229 if(event->buttons() == Qt::LeftButton) {
230 if(contains(event->pos())) {
231 qint16 end = posToCursor(event->pos());
232 if(end != _selectionEnd) {
234 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
239 chatScene()->startGlobalSelection(this, event->pos());
247 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
248 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
249 _selectionEnd = posToCursor(event->pos());
251 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
252 chatScene()->putToClipboard(selection);
259 // ************************************************************
261 // ************************************************************
263 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
264 Q_UNUSED(option); Q_UNUSED(widget);
266 //painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
267 qreal layoutWidth = layout()->minimumWidth();
269 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
270 offset = qMin(width() - layoutWidth, (qreal)0);
272 offset = qMax(layoutWidth - width(), (qreal)0);
274 QTextLayout::FormatRange selectFmt = selectionFormat();
276 if(layoutWidth > width()) {
277 // Draw a nice gradient for longer items
278 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
279 QPixmap pixmap(QSize(layout()->boundingRect().width(), layout()->boundingRect().height()));
280 pixmap.fill(QApplication::palette().brush(QPalette::Base).color());
281 QPainter pixPainter(&pixmap);
282 layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
285 // Create alpha channel mask
286 QPixmap mask(pixmap.size());
287 QPainter maskPainter(&mask);
288 QLinearGradient gradient;
290 gradient.setStart(0, 0);
291 gradient.setFinalStop(12, 0);
292 gradient.setColorAt(0, Qt::black);
293 gradient.setColorAt(1, Qt::white);
295 gradient.setStart(width()-10, 0);
296 gradient.setFinalStop(width(), 0);
297 gradient.setColorAt(0, Qt::white);
298 gradient.setColorAt(1, Qt::black);
300 maskPainter.fillRect(boundingRect(), gradient);
301 pixmap.setAlphaChannel(mask);
302 painter->drawPixmap(0, 0, pixmap);
304 layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
308 // ************************************************************
310 // ************************************************************
311 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
312 : ChatItem(0, 0, pos, parent)
314 const QAbstractItemModel *model_ = model();
315 QModelIndex index = model_->index(row(), column());
316 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
318 setGeometryByWidth(width);
321 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
323 prepareGeometryChange();
327 WrapColumnFinder finder(this);
328 while(finder.nextWrapColumn() > 0)
330 setHeight(lines * fontMetrics()->lineSpacing());
335 void ContentsChatItem::doLayout() {
336 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
337 if(!wrapList.count()) return; // empty chatitem
340 WrapColumnFinder finder(this);
341 layout()->beginLayout();
343 QTextLine line = layout()->createLine();
347 int col = finder.nextWrapColumn();
348 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
349 line.setPosition(QPointF(0, h));
350 h += fontMetrics()->lineSpacing();
352 layout()->endLayout();
355 // NOTE: This method is not threadsafe and not reentrant!
356 // (RegExps are not constant while matching, and they are static here for efficiency)
357 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
359 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
360 static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#])");
362 static QRegExp regExp[] = {
364 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
365 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
368 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
369 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
371 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
374 static const int regExpCount = 2; // number of regexps in the array above
376 qint16 matches[] = { 0, 0, 0 };
377 qint16 matchEnd[] = { 0, 0, 0 };
379 QString str = data(ChatLineModel::DisplayRole).toString();
381 QList<Clickable> result;
388 minidx = str.length();
389 for(int i = 0; i < regExpCount; i++) {
390 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
391 if(idx >= matchEnd[i]) {
392 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
393 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
395 if(matches[i] >= 0 && matches[i] < minidx) {
401 idx = matchEnd[type];
402 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
403 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
405 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
410 if(!result.isEmpty()) qDebug() << str;
411 foreach(Clickable click, result) {
412 qDebug() << str.mid(click.start, click.length);
418 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
419 // mark a clickable if hovered upon
420 QVector<QTextLayout::FormatRange> fmt;
421 if(privateData()->currentClickable.isValid()) {
422 Clickable click = privateData()->currentClickable;
423 QTextLayout::FormatRange f;
424 f.start = click.start;
425 f.length = click.length;
426 f.format.setFontUnderline(true);
432 void ContentsChatItem::endHoverMode() {
433 if(hasPrivateData()) {
434 if(privateData()->currentClickable.isValid()) {
435 setCursor(Qt::ArrowCursor);
436 privateData()->currentClickable = Clickable();
443 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
444 privateData()->hasDragged = false;
445 ChatItem::mousePressEvent(event);
448 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
449 if(!event->buttons() && !privateData()->hasDragged) {
451 Clickable click = privateData()->currentClickable;
452 if(click.isValid()) {
453 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
456 if(!str.contains("://"))
457 str = "http://" + str;
458 QDesktopServices::openUrl(str);
460 case Clickable::Channel:
461 // TODO join or whatever...
468 ChatItem::mouseReleaseEvent(event);
471 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
472 // mouse move events always mean we're not hovering anymore...
474 // also, check if we have dragged the mouse
475 if(hasPrivateData() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
476 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
477 privateData()->hasDragged = true;
478 ChatItem::mouseMoveEvent(event);
481 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
486 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
487 bool onClickable = false;
488 qint16 idx = posToCursor(event->pos());
489 for(int i = 0; i < privateData()->clickables.count(); i++) {
490 Clickable click = privateData()->clickables.at(i);
491 if(idx >= click.start && idx < click.start + click.length) {
492 if(click.type == Clickable::Url) {
494 showWebPreview(click);
495 } else if(click.type == Clickable::Channel) {
496 // TODO: don't make clickable if it's our own name
497 //onClickable = true; //FIXME disabled for now
500 setCursor(Qt::PointingHandCursor);
501 privateData()->currentClickable = click;
507 if(!onClickable) endHoverMode();
511 void ContentsChatItem::showWebPreview(const Clickable &click) {
513 QTextLine line = layout()->lineForTextPosition(click.start);
514 qreal x = line.cursorToX(click.start);
515 qreal width = line.cursorToX(click.start + click.length) - x;
516 qreal height = line.height();
517 qreal y = height * line.lineNumber();
519 QPointF topLeft = scenePos() + QPointF(x, y);
520 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
522 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
523 if(!url.contains("://"))
524 url = "http://" + url;
525 chatScene()->loadWebPreview(this, url, urlRect);
529 void ContentsChatItem::clearWebPreview() {
531 chatScene()->clearWebPreview(this);
535 /*************************************************************************************************/
537 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
540 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
547 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
551 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
552 if(wordidx >= wrapList.count())
556 qreal targetWidth = lineCount * item->width() + choppedTrailing;
558 qint16 start = wordidx;
559 qint16 end = wrapList.count() - 1;
561 // check if the whole line fits
562 if(wrapList.at(end).endX <= targetWidth) // || start == end)
565 // check if we have a very long word that needs inter word wrap
566 if(wrapList.at(start).endX > targetWidth) {
567 if(!line.isValid()) {
568 layout = item->createLayout(QTextOption::NoWrap);
569 layout->beginLayout();
570 line = layout->createLine();
573 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
577 if(start + 1 == end) {
579 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
581 // both cases should be cought preliminary
582 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
583 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
585 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
586 return wrapList.at(wordidx).start;
589 qint16 pivot = (end + start) / 2;
590 if(wrapList.at(pivot).endX > targetWidth) {