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>
32 #include <QGraphicsProxyWidget>
35 #include "chatlinemodel.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) {
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::updateLayout() {
80 setPrivateData(new ChatItemPrivate(createLayout()));
82 QTextLayout *layout_ = layout();
83 layout_->beginLayout();
84 QTextLine line = layout_->createLine();
86 line.setLineWidth(width());
87 line.setPosition(QPointF(0,0));
92 void ChatItem::clearLayout() {
97 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
98 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
99 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
100 Q_UNUSED(option); Q_UNUSED(widget);
103 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
104 //if(_selectionMode == FullSelection) {
106 //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
107 //painter->restore();
109 QVector<QTextLayout::FormatRange> formats = additionalFormats();
110 if(_selectionMode != NoSelection) {
111 QTextLayout::FormatRange selectFmt;
112 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
113 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
114 if(_selectionMode == PartialSelection) {
115 selectFmt.start = qMin(_selectionStart, _selectionEnd);
116 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
117 } else { // FullSelection
119 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
121 formats.append(selectFmt);
123 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
126 // uncomment the following lines to draw the bounding rect and the row number in alternating colors
128 // painter->setPen(Qt::red);
130 // painter->setPen(Qt::blue);
131 // QString rowString = QString::number(row());
132 // QRect rowRect = painter->fontMetrics().boundingRect(rowString);
133 // QPointF topPoint = _boundingRect.topLeft();
134 // topPoint.ry() += rowRect.height();
135 // painter->drawText(topPoint, rowString);
136 // QPointF bottomPoint = _boundingRect.bottomRight();
137 // bottomPoint.rx() -= rowRect.width();
138 // painter->drawText(bottomPoint, rowString);
139 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
142 qint16 ChatItem::posToCursor(const QPointF &pos) {
143 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
144 if(pos.y() < 0) return 0;
147 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
148 QTextLine line = layout()->lineAt(l);
149 if(pos.y() >= line.y()) {
150 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
156 void ChatItem::setFullSelection() {
157 if(_selectionMode != FullSelection) {
158 _selectionMode = FullSelection;
163 void ChatItem::clearSelection() {
164 _selectionMode = NoSelection;
168 void ChatItem::continueSelecting(const QPointF &pos) {
169 _selectionMode = PartialSelection;
170 _selectionEnd = posToCursor(pos);
174 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
175 QList<QRectF> resultList;
176 const QAbstractItemModel *model_ = model();
180 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
181 QList<int> indexList;
182 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
183 while(searchIdx != -1) {
184 indexList << searchIdx;
185 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
188 bool hadLayout = hasLayout();
192 foreach(int idx, indexList) {
193 QTextLine line = layout()->lineForTextPosition(idx);
194 qreal x = line.cursorToX(idx);
195 qreal width = line.cursorToX(idx + searchWord.count()) - x;
196 qreal height = line.height();
197 qreal y = height * line.lineNumber();
198 resultList << QRectF(x, y, width, height);
206 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
207 if(event->buttons() == Qt::LeftButton) {
208 chatScene()->setSelectingItem(this);
209 _selectionStart = _selectionEnd = posToCursor(event->pos());
210 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
218 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
219 if(event->buttons() == Qt::LeftButton) {
220 if(contains(event->pos())) {
221 qint16 end = posToCursor(event->pos());
222 if(end != _selectionEnd) {
224 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
229 chatScene()->startGlobalSelection(this, event->pos());
237 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
238 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
239 _selectionEnd = posToCursor(event->pos());
241 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
242 chatScene()->putToClipboard(selection);
249 // ************************************************************
251 // ************************************************************
253 // ************************************************************
255 // ************************************************************
256 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
257 : ChatItem(0, 0, pos, parent)
259 const QAbstractItemModel *model_ = model();
260 QModelIndex index = model_->index(row(), column());
261 _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
263 setGeometryByWidth(width);
266 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
271 WrapColumnFinder finder(this);
272 while(finder.nextWrapColumn() > 0)
274 setHeight(lines * fontMetrics()->lineSpacing());
279 void ContentsChatItem::updateLayout() {
281 ContentsChatItemPrivate *data = new ContentsChatItemPrivate(createLayout(QTextOption::WrapAnywhere), findClickables(), this);
282 setPrivateData(data);
286 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
287 if(!wrapList.count()) return; // empty chatitem
290 WrapColumnFinder finder(this);
291 layout()->beginLayout();
293 QTextLine line = layout()->createLine();
297 int col = finder.nextWrapColumn();
298 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
299 line.setPosition(QPointF(0, h));
300 h += fontMetrics()->lineSpacing();
302 layout()->endLayout();
305 // NOTE: This method is not threadsafe and not reentrant!
306 // (RegExps are not constant while matching, and they are static here for efficiency)
307 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
309 static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
310 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
312 static QRegExp regExp[] = {
314 // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
315 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
318 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
319 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
321 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
324 static const int regExpCount = 2; // number of regexps in the array above
326 qint16 matches[] = { 0, 0, 0 };
327 qint16 matchEnd[] = { 0, 0, 0 };
329 QString str = data(ChatLineModel::DisplayRole).toString();
331 QList<Clickable> result;
338 minidx = str.length();
339 for(int i = 0; i < regExpCount; i++) {
340 if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
341 if(idx >= matchEnd[i]) {
342 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
343 if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
345 if(matches[i] >= 0 && matches[i] < minidx) {
351 idx = matchEnd[type];
352 if(type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
353 if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
355 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
360 if(!result.isEmpty()) qDebug() << str;
361 foreach(Clickable click, result) {
362 qDebug() << str.mid(click.start, click.length);
368 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
369 // mark a clickable if hovered upon
370 QVector<QTextLayout::FormatRange> fmt;
371 if(privateData()->currentClickable.isValid()) {
372 Clickable click = privateData()->currentClickable;
373 QTextLayout::FormatRange f;
374 f.start = click.start;
375 f.length = click.length;
376 f.format.setFontUnderline(true);
382 void ContentsChatItem::endHoverMode() {
384 if(privateData()->currentClickable.isValid()) {
385 setCursor(Qt::ArrowCursor);
386 privateData()->currentClickable = Clickable();
395 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
396 privateData()->hasDragged = false;
397 ChatItem::mousePressEvent(event);
400 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
401 if(!event->buttons() && !privateData()->hasDragged) {
403 Clickable click = privateData()->currentClickable;
404 if(click.isValid()) {
405 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
408 if(!str.contains("://"))
409 str = "http://" + str;
410 QDesktopServices::openUrl(str);
412 case Clickable::Channel:
413 // TODO join or whatever...
420 ChatItem::mouseReleaseEvent(event);
423 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
424 // mouse move events always mean we're not hovering anymore...
426 // also, check if we have dragged the mouse
427 if(hasLayout() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
428 && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
429 privateData()->hasDragged = true;
430 ChatItem::mouseMoveEvent(event);
433 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
438 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
439 bool onClickable = false;
440 qint16 idx = posToCursor(event->pos());
441 for(int i = 0; i < privateData()->clickables.count(); i++) {
442 Clickable click = privateData()->clickables.at(i);
443 if(idx >= click.start && idx < click.start + click.length) {
444 if(click.type == Clickable::Url) {
447 showWebPreview(click);
449 } else if(click.type == Clickable::Channel) {
450 // TODO: don't make clickable if it's our own name
451 //onClickable = true; //FIXME disabled for now
454 setCursor(Qt::PointingHandCursor);
455 privateData()->currentClickable = click;
461 if(!onClickable) endHoverMode();
466 void ContentsChatItem::showWebPreview(const Clickable &click) {
470 QTextLine line = layout()->lineForTextPosition(click.start);
471 qreal x = line.cursorToX(click.start);
472 qreal width = line.cursorToX(click.start + click.length) - x;
473 qreal height = line.height();
474 qreal y = height * line.lineNumber();
475 QRectF urlRect(x, y, width, height);
476 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
477 if(!url.contains("://"))
478 url = "http://" + url;
479 privateData()->loadWebPreview(url, urlRect);
482 void ContentsChatItem::clearWebPreview() {
484 privateData()->clearWebPreview();
488 // ****************************************
489 // ContentsChatItemPrivate
490 // ****************************************
492 ContentsChatItemPrivate::~ContentsChatItemPrivate() {
496 void ContentsChatItemPrivate::loadWebPreview(const QString &url, const QRectF &urlRect) {
497 if(url != previewUrl) {
499 // load a new web view and delete the old one (if exists)
501 contentsItem->scene()->removeItem(previewItem);
504 QWebView *view = new QWebView;
506 previewItem = new ContentsChatItemPrivate::PreviewItem(view);
507 contentsItem->scene()->addItem(previewItem);
509 if(urlRect != previewUrlRect) {
510 previewUrlRect = urlRect;
511 QPointF sPos = contentsItem->scenePos();
512 qreal previewY = sPos.y() + urlRect.y() + urlRect.height(); // bottom of url;
513 qreal previewX = sPos.x() + urlRect.x();
514 if(previewY + previewItem->boundingRect().height() > contentsItem->scene()->sceneRect().bottom())
515 previewY = sPos.y() + urlRect.y() - previewItem->boundingRect().height();
517 if(previewX + previewItem->boundingRect().width() > contentsItem->scene()->sceneRect().width())
518 previewX = contentsItem->scene()->sceneRect().right() - previewItem->boundingRect().width();
520 previewItem->setPos(previewX, previewY);
524 void ContentsChatItemPrivate::clearWebPreview() {
526 contentsItem->scene()->removeItem(previewItem);
530 previewUrl = QString();
531 previewUrlRect = QRectF();
534 ContentsChatItemPrivate::PreviewItem::PreviewItem(QWebView *webView)
535 : QGraphicsItem(0), // needs to be a top level item as we otherwise cannot guarantee that it's on top of other chatlines
536 _boundingRect(0, 0, 400, 300)
538 qreal frameWidth = 5;
539 webView->resize(1000, 750);
540 QGraphicsProxyWidget *proxyItem = new QGraphicsProxyWidget(this);
541 proxyItem->setWidget(webView);
542 proxyItem->setAcceptHoverEvents(false);
544 qreal xScale = (_boundingRect.width() - 2 * frameWidth) / webView->width();
545 qreal yScale = (_boundingRect.height() - 2 * frameWidth) / webView->height();
546 proxyItem->scale(xScale, yScale);
547 proxyItem->setPos(frameWidth, frameWidth);
552 void ContentsChatItemPrivate::PreviewItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
553 Q_UNUSED(option); Q_UNUSED(widget);
554 painter->setClipRect(boundingRect());
555 painter->setPen(QPen(Qt::black, 5));
556 painter->setBrush(Qt::black);
557 painter->setRenderHints(QPainter::Antialiasing);
558 painter->drawRoundedRect(boundingRect(), 10, 10);
560 painter->setPen(QPen(Qt::green));
561 QString text = QString::number(zValue());
562 painter->drawText(_boundingRect.center(), text);
564 #endif // #ifdef HAVE_WEBKIT
566 /*************************************************************************************************/
568 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
571 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
578 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
582 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
583 if(wordidx >= wrapList.count())
587 qreal targetWidth = lineCount * item->width() + choppedTrailing;
589 qint16 start = wordidx;
590 qint16 end = wrapList.count() - 1;
592 // check if the whole line fits
593 if(wrapList.at(end).endX <= targetWidth) // || start == end)
596 // check if we have a very long word that needs inter word wrap
597 if(wrapList.at(start).endX > targetWidth) {
598 if(!line.isValid()) {
599 layout = item->createLayout(QTextOption::NoWrap);
600 layout->beginLayout();
601 line = layout->createLine();
604 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
608 if(start + 1 == end) {
610 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
612 // both cases should be cought preliminary
613 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
614 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
616 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
617 return wrapList.at(wordidx).start;
620 qint16 pivot = (end + start) / 2;
621 if(wrapList.at(pivot).endX > targetWidth) {