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"
34 ChatItem::ChatItem(ChatLineModel::ColumnType col, QAbstractItemModel *model, QGraphicsItem *parent)
35 : QGraphicsItem(parent),
37 _selectionMode(NoSelection),
42 QModelIndex index = model->index(row(), col);
43 _fontMetrics = QtUi::style()->fontMetrics(model->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
44 setAcceptHoverEvents(true);
48 ChatItem::~ChatItem() {
52 QVariant ChatItem::data(int role) const {
53 QModelIndex index = model()->index(row(), column());
54 if(!index.isValid()) {
55 qWarning() << "ChatItem::data(): model index is invalid!" << index;
58 return model()->data(index, role);
61 qreal ChatItem::setGeometry(qreal w, qreal h) {
62 if(w == _boundingRect.width()) return _boundingRect.height();
63 prepareGeometryChange();
64 _boundingRect.setWidth(w);
65 if(h < 0) h = computeHeight();
66 //if(h < 0) h = fontMetrics()->lineSpacing(); // only contents can be multi-line
67 _boundingRect.setHeight(h);
68 if(haveLayout()) updateLayout();
72 qreal ChatItem::computeHeight() {
73 return fontMetrics()->lineSpacing(); // only contents can be multi-line
76 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
77 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
80 option.setWrapMode(wrapMode);
81 option.setAlignment(alignment);
82 layout->setTextOption(option);
84 QList<QTextLayout::FormatRange> formatRanges
85 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
86 layout->setAdditionalFormats(formatRanges);
90 void ChatItem::updateLayout() {
92 setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft));
94 layout()->beginLayout();
95 QTextLine line = layout()->createLine();
97 line.setLineWidth(width());
98 line.setPosition(QPointF(0,0));
100 layout()->endLayout();
103 void ChatItem::clearLayout() {
108 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
109 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
110 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
111 Q_UNUSED(option); Q_UNUSED(widget);
112 if(!haveLayout()) updateLayout();
113 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
114 //if(_selectionMode == FullSelection) {
116 //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
117 //painter->restore();
119 QVector<QTextLayout::FormatRange> formats = additionalFormats();
120 if(_selectionMode != NoSelection) {
121 QTextLayout::FormatRange selectFmt;
122 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
123 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
124 if(_selectionMode == PartialSelection) {
125 selectFmt.start = qMin(_selectionStart, _selectionEnd);
126 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
127 } else { // FullSelection
129 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
131 formats.append(selectFmt);
133 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
136 qint16 ChatItem::posToCursor(const QPointF &pos) {
137 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
138 if(pos.y() < 0) return 0;
139 if(!haveLayout()) updateLayout();
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 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
168 QList<QRectF> resultList;
169 const QAbstractItemModel *model_ = model();
173 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
174 QList<int> indexList;
175 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
176 while(searchIdx != -1) {
177 indexList << searchIdx;
178 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
184 foreach(int idx, indexList) {
185 QTextLine line = layout()->lineForTextPosition(idx);
186 qreal x = line.cursorToX(idx);
187 qreal width = line.cursorToX(idx + searchWord.count()) - x;
188 qreal height = fontMetrics()->lineSpacing();
189 qreal y = height * line.lineNumber();
190 resultList << QRectF(x, y, width, height);
195 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
196 if(event->buttons() == Qt::LeftButton) {
197 chatScene()->setSelectingItem(this);
198 _selectionStart = _selectionEnd = posToCursor(event->pos());
199 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
207 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
208 if(event->buttons() == Qt::LeftButton) {
209 if(contains(event->pos())) {
210 qint16 end = posToCursor(event->pos());
211 if(end != _selectionEnd) {
213 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
218 chatScene()->startGlobalSelection(this, event->pos());
226 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
227 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
228 _selectionEnd = posToCursor(event->pos());
230 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
231 chatScene()->putToClipboard(selection);
238 /*************************************************************************************************/
240 /*************************************************************************************************/
242 void SenderChatItem::updateLayout() {
243 if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignRight));
244 ChatItem::updateLayout();
247 /*************************************************************************************************/
249 ContentsChatItem::ContentsChatItem(QAbstractItemModel *model, QGraphicsItem *parent) : ChatItem(column(), model, parent),
255 ContentsChatItem::~ContentsChatItem() {
259 qreal ContentsChatItem::computeHeight() {
261 WrapColumnFinder finder(this);
262 while(finder.nextWrapColumn() > 0) lines++;
263 return lines * fontMetrics()->lineSpacing();
266 void ContentsChatItem::setLayout(QTextLayout *layout) {
268 _layoutData = new LayoutData;
269 _layoutData->clickables = findClickables();
271 delete _layoutData->layout;
273 _layoutData->layout = layout;
276 void ContentsChatItem::clearLayout() {
281 void ContentsChatItem::updateLayout() {
282 if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere));
285 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
286 if(!wrapList.count()) return; // empty chatitem
289 WrapColumnFinder finder(this);
290 layout()->beginLayout();
292 QTextLine line = layout()->createLine();
296 int col = finder.nextWrapColumn();
297 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
298 line.setPosition(QPointF(0, h));
299 h += line.height() + fontMetrics()->leading();
301 layout()->endLayout();
304 // NOTE: This method is not threadsafe and not reentrant!
305 // (RegExps are not constant while matching, and they are static here for efficiency)
306 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() {
308 static QString urlEnd("(?:>|[,.;:]?\\s|\\b)");
309 static QString urlChars("(?:[\\w\\-~@/?&=+$()!%#]|[,.;:]\\w)");
311 static QRegExp regExp[] = {
313 QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd)),
316 // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
317 QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b")
319 // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
322 static const int regExpCount = 2; // number of regexps in the array above
324 qint16 matches[] = { 0, 0, 0 };
325 qint16 matchEnd[] = { 0, 0, 0 };
327 QString str = data(ChatLineModel::DisplayRole).toString();
329 QList<Clickable> result;
336 minidx = str.length();
337 for(int i = 0; i < regExpCount; i++) {
338 if(matches[i] < 0 || idx < matchEnd[i] || matchEnd[i] >= str.length()) continue;
339 matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
340 if(matches[i] >= 0) {
341 matchEnd[i] = matches[i] + regExp[i].cap(1).length();
342 if(matches[i] < minidx) {
349 idx = matchEnd[type];
350 result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
355 if(!result.isEmpty()) qDebug() << str;
356 foreach(Clickable click, result) {
357 qDebug() << str.mid(click.start, click.length);
363 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
364 // mark a clickable if hovered upon
365 QVector<QTextLayout::FormatRange> fmt;
366 if(layoutData()->currentClickable.isValid()) {
367 Clickable click = layoutData()->currentClickable;
368 QTextLayout::FormatRange f;
369 f.start = click.start;
370 f.length = click.length;
371 f.format.setFontUnderline(true);
377 void ContentsChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
378 // FIXME dirty and fast hack to make http:// urls klickable
380 QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
381 QString str = data(ChatLineModel::DisplayRole).toString();
382 int idx = posToCursor(event->pos());
385 mi = regex.indexIn(str, mi);
387 if(idx >= mi && idx < mi + regex.matchedLength()) {
388 QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
391 mi += regex.matchedLength();
396 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
397 // mouse move events always mean we're not hovering anymore...
398 if(layoutData()->currentClickable.isValid()) {
399 layoutData()->currentClickable = Clickable();
402 ChatItem::mouseMoveEvent(event);
405 void ContentsChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
406 //layoutData()->currentClickable = event->pos();
410 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
411 if(layoutData()->currentClickable.isValid()) {
412 layoutData()->currentClickable = Clickable();
418 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
419 qint16 idx = posToCursor(event->pos());
420 for(int i = 0; i < layoutData()->clickables.count(); i++) {
421 Clickable click = layoutData()->clickables.at(i);
422 if(idx >= click.start && idx < click.start + click.length) {
423 layoutData()->currentClickable = click;
430 /*************************************************************************************************/
432 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
435 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
443 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
447 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
448 while(wordidx < wrapList.count()) {
449 w += wrapList.at(wordidx).width;
450 if(w >= item->width()) {
451 if(lastwrapcol >= wrapList.at(wordidx).start) {
452 // first word, and it doesn't fit
453 if(!line.isValid()) {
454 layout = item->createLayout(QTextOption::NoWrap);
455 layout->beginLayout();
456 line = layout->createLine();
457 line.setLineWidth(item->width());
460 int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
461 qreal x = line.cursorToX(idx, QTextLine::Trailing);
462 w = w - wrapList.at(wordidx).width - (x - lastwrappos);
467 // not the first word, so just wrap before this
468 lastwrapcol = wrapList.at(wordidx).start;
469 lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
473 w += wrapList.at(wordidx).trailing;