1 /***************************************************************************
2 * Copyright (C) 2005-2010 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 "buffermodel.h"
32 #include "bufferview.h"
35 #include "chatlinemodel.h"
36 #include "contextmenuactionprovider.h"
37 #include "iconloader.h"
40 #include "qtuistyle.h"
42 ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent)
44 _boundingRect(boundingRect),
45 _selectionMode(NoSelection),
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 qint16 ChatItem::posToCursor(const QPointF &posInLine) const {
61 QPointF pos = mapFromLine(posInLine);
62 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
63 if(pos.y() < 0) return 0;
67 for(int l = layout.lineCount() - 1; l >= 0; l--) {
68 QTextLine line = layout.lineAt(l);
69 if(pos.y() >= line.y()) {
70 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
76 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
79 layout->setText(data(MessageModel::DisplayRole).toString());
82 option.setWrapMode(wrapMode);
83 option.setAlignment(alignment);
84 layout->setTextOption(option);
86 QList<QTextLayout::FormatRange> formatRanges
87 = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
88 layout->setAdditionalFormats(formatRanges);
91 UiStyle::FormatList ChatItem::formatList() const {
92 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
95 void ChatItem::doLayout(QTextLayout *layout) const {
96 layout->beginLayout();
97 QTextLine line = layout->createLine();
99 line.setLineWidth(width());
100 line.setPosition(QPointF(0,0));
105 void ChatItem::paintBackground(QPainter *painter) {
107 if(_selectionMode == FullSelection)
108 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
110 bgBrush = data(ChatLineModel::BackgroundRole);
111 if(bgBrush.isValid())
112 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
115 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
116 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
117 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
118 Q_UNUSED(option); Q_UNUSED(widget);
119 paintBackground(painter);
123 layout.draw(painter, pos(), additionalFormats(), boundingRect());
125 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
128 // uncomment partially or all of the following stuff:
130 // 0) alternativ painter color for debug stuff
132 // painter->setPen(Qt::red);
134 // painter->setPen(Qt::blue);
135 // 1) draw wordwrap points in the first line
136 // if(column() == 2) {
137 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
138 // foreach(ChatLineModel::Word word, wrapList) {
139 // if(word.endX > width())
141 // painter->drawLine(word.endX, 0, word.endX, height());
144 // 2) draw MsgId over the time column
145 // if(column() == 0) {
146 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
147 // QPointF bottomPoint = boundingRect().bottomLeft();
148 // bottomPoint.ry() -= 2;
149 // painter->drawText(bottomPoint, msgIdString);
151 // 3) draw bounding rect
152 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
155 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, int start, int end, quint32 overlayFmt) const {
156 for(int i = 0; i < fmtList.count(); i++) {
157 int fmtStart = fmtList.at(i).first;
158 int fmtEnd = (i < fmtList.count()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
165 // split the format if necessary
166 if(fmtStart < start) {
167 fmtList.insert(i, fmtList.at(i));
168 fmtList[++i].first = start;
171 fmtList.insert(i, fmtList.at(i));
172 fmtList[i+1].first = end;
175 fmtList[i].second |= overlayFmt;
179 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
180 return selectionFormats();
183 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
185 return QVector<QTextLayout::FormatRange>();
188 if(_selectionMode == FullSelection) {
190 end = data(MessageModel::DisplayRole).toString().length();
192 start = qMin(_selectionStart, _selectionEnd);
193 end = qMax(_selectionStart, _selectionEnd);
196 UiStyle::FormatList fmtList = formatList();
198 while(fmtList.count() > 1 && fmtList.at(1).first <= start)
199 fmtList.removeFirst();
201 fmtList.first().first = start;
203 while(fmtList.count() > 1 && fmtList.last().first >= end)
204 fmtList.removeLast();
206 return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
209 bool ChatItem::hasSelection() const {
210 if(_selectionMode == NoSelection)
212 if(_selectionMode == FullSelection)
215 return _selectionStart != _selectionEnd;
218 QString ChatItem::selection() const {
219 if(_selectionMode == FullSelection)
220 return data(MessageModel::DisplayRole).toString();
221 if(_selectionMode == PartialSelection)
222 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
226 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
227 _selectionMode = mode;
228 _selectionStart = start;
230 chatLine()->update();
233 void ChatItem::setFullSelection() {
234 if(_selectionMode != FullSelection) {
235 _selectionMode = FullSelection;
236 chatLine()->update();
240 void ChatItem::clearSelection() {
241 if(_selectionMode != NoSelection) {
242 _selectionMode = NoSelection;
243 chatLine()->update();
247 void ChatItem::continueSelecting(const QPointF &pos) {
248 _selectionMode = PartialSelection;
249 _selectionEnd = posToCursor(pos);
250 chatLine()->update();
253 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
254 if(_selectionMode == FullSelection)
256 if(_selectionMode == PartialSelection) {
257 int cursor = posToCursor(pos);
258 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
263 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
264 QList<QRectF> resultList;
265 const QAbstractItemModel *model_ = model();
269 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
270 QList<int> indexList;
271 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
272 while(searchIdx != -1) {
273 indexList << searchIdx;
274 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
279 foreach(int idx, indexList) {
280 QTextLine line = layout.lineForTextPosition(idx);
281 qreal x = line.cursorToX(idx);
282 qreal width = line.cursorToX(idx + searchWord.count()) - x;
283 qreal height = line.height();
284 qreal y = height * line.lineNumber();
285 resultList << QRectF(x, y, width, height);
291 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
292 // single clicks are already handled by the scene (for clearing the selection)
293 if(clickMode == ChatScene::DragStartClick) {
294 chatScene()->setSelectingItem(this);
295 _selectionStart = _selectionEnd = posToCursor(pos);
296 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
297 chatLine()->update();
301 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
302 if(event->buttons() == Qt::LeftButton) {
303 if(boundingRect().contains(event->pos())) {
304 qint16 end = posToCursor(event->pos());
305 if(end != _selectionEnd) {
307 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
308 chatLine()->update();
312 chatScene()->startGlobalSelection(this, event->pos());
320 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
321 if(event->buttons() == Qt::LeftButton)
327 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
328 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
329 chatScene()->selectionToClipboard(QClipboard::Selection);
335 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
338 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
341 // ************************************************************
343 // ************************************************************
345 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
346 Q_UNUSED(option); Q_UNUSED(widget);
347 paintBackground(painter);
351 qreal layoutWidth = layout.minimumWidth();
353 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
354 offset = qMin(width() - layoutWidth, (qreal)0);
356 offset = qMax(layoutWidth - width(), (qreal)0);
358 if(layoutWidth > width()) {
359 // Draw a nice gradient for longer items
360 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
361 QPixmap pixmap(layout.boundingRect().toRect().size());
362 pixmap.fill(Qt::transparent);
363 QPainter pixPainter(&pixmap);
364 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
367 // Create alpha channel mask
368 QPixmap mask(pixmap.size());
369 QPainter maskPainter(&mask);
370 QLinearGradient gradient;
372 gradient.setStart(0, 0);
373 gradient.setFinalStop(12, 0);
374 gradient.setColorAt(0, Qt::black);
375 gradient.setColorAt(1, Qt::white);
377 gradient.setStart(width()-10, 0);
378 gradient.setFinalStop(width(), 0);
379 gradient.setColorAt(0, Qt::white);
380 gradient.setColorAt(1, Qt::black);
382 maskPainter.fillRect(0, 0, pixmap.width(), pixmap.height(), gradient);
383 pixmap.setAlphaChannel(mask);
384 painter->drawPixmap(pos(), pixmap);
386 layout.draw(painter, pos(), additionalFormats(), boundingRect());
390 void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
391 if(clickMode == ChatScene::DoubleClick) {
392 BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
393 QString nick = data(MessageModel::EditRole).toString();
394 // check if the nick is a valid ircUser
395 if(!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
396 Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
399 ChatItem::handleClick(pos, clickMode);
402 // ************************************************************
404 // ************************************************************
406 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
408 ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
409 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
413 setGeometryByWidth(width);
416 QFontMetricsF *ContentsChatItem::fontMetrics() const {
417 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
420 ContentsChatItem::~ContentsChatItem() {
424 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
426 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
427 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
432 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
433 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
437 WrapColumnFinder finder(this);
438 while(finder.nextWrapColumn(w) > 0)
440 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
441 qreal h = lines * spacing;
445 if(w != width() || h != height())
451 void ContentsChatItem::doLayout(QTextLayout *layout) const {
452 // QString t = data(Qt::DisplayRole).toString(); bool d = t.contains("protien");
453 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
454 if(!wrapList.count()) return; // empty chatitem
457 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
458 WrapColumnFinder finder(this);
459 layout->beginLayout();
461 QTextLine line = layout->createLine();
465 int col = finder.nextWrapColumn(width());
467 col = layout->text().length();
468 int num = col - line.textStart();
470 line.setNumColumns(num);
472 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
473 // We verify this and try setting the width again, making it shorter each time until the lengths match.
474 // Dead fugly, but seems to work…
475 for(int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
476 line.setNumColumns(i);
478 if(num != line.textLength()) {
479 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
480 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
483 line.setPosition(QPointF(0, h));
489 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
490 return privateData()->clickables.atCursorPos(posToCursor(pos));
493 UiStyle::FormatList ContentsChatItem::formatList() const {
494 UiStyle::FormatList fmtList = ChatItem::formatList();
495 for(int i = 0; i < privateData()->clickables.count(); i++) {
496 Clickable click = privateData()->clickables.at(i);
497 if(click.type() == Clickable::Url) {
498 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
504 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
505 QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
506 // mark a clickable if hovered upon
507 if(privateData()->currentClickable.isValid()) {
508 Clickable click = privateData()->currentClickable;
509 QTextLayout::FormatRange f;
510 f.start = click.start();
511 f.length = click.length();
512 f.format.setFontUnderline(true);
518 void ContentsChatItem::endHoverMode() {
520 if(privateData()->currentClickable.isValid()) {
521 chatLine()->setCursor(Qt::ArrowCursor);
522 privateData()->currentClickable = Clickable();
525 chatLine()->update();
529 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
530 if(clickMode == ChatScene::SingleClick) {
531 qint16 idx = posToCursor(pos);
532 Clickable foo = privateData()->clickables.atCursorPos(idx);
534 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
535 QString text = data(ChatLineModel::DisplayRole).toString();
536 foo.activate(networkId, text);
538 } else if(clickMode == ChatScene::DoubleClick) {
539 chatScene()->setSelectingItem(this);
540 setSelectionMode(PartialSelection);
541 Clickable click = clickableAt(pos);
542 if(click.isValid()) {
543 setSelectionStart(click.start());
544 setSelectionEnd(click.start() + click.length());
546 // find word boundary
547 QString str = data(ChatLineModel::DisplayRole).toString();
548 qint16 cursor = posToCursor(pos);
549 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
550 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
551 if(end < 0) end = str.length();
552 setSelectionStart(start);
553 setSelectionEnd(end);
555 chatLine()->update();
556 } else if(clickMode == ChatScene::TripleClick) {
557 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
559 ChatItem::handleClick(pos, clickMode);
562 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
563 // mouse move events always mean we're not hovering anymore...
565 ChatItem::mouseMoveEvent(event);
568 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
573 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
574 bool onClickable = false;
575 Clickable click = clickableAt(event->pos());
576 if(click.isValid()) {
577 if(click.type() == Clickable::Url) {
579 showWebPreview(click);
580 } else if(click.type() == Clickable::Channel) {
581 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
582 // don't make clickable if it's our own name
583 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
584 if(Client::networkModel()->bufferName(myId) != name)
588 chatLine()->setCursor(Qt::PointingHandCursor);
589 privateData()->currentClickable = click;
590 chatLine()->update();
594 if(!onClickable) endHoverMode();
598 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
599 if(privateData()->currentClickable.isValid()) {
600 Clickable click = privateData()->currentClickable;
601 switch(click.type()) {
603 privateData()->activeClickable = click;
604 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
605 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
607 case Clickable::Channel: {
608 // Hide existing menu actions, they confuse us when right-clicking on a clickable
609 foreach(QAction *action, menu->actions())
610 action->setVisible(false);
611 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
612 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
619 // Buffer-specific actions
620 ChatItem::addActionsToMenu(menu, pos);
624 void ContentsChatItem::copyLinkToClipboard() {
625 Clickable click = privateData()->activeClickable;
626 if(click.isValid() && click.type() == Clickable::Url) {
627 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
628 if(!url.contains("://"))
629 url = "http://" + url;
630 chatScene()->stringToClipboard(url);
634 /******** WEB PREVIEW *****************************************************************************/
636 void ContentsChatItem::showWebPreview(const Clickable &click) {
642 QTextLine line = layout.lineForTextPosition(click.start());
643 qreal x = line.cursorToX(click.start());
644 qreal width = line.cursorToX(click.start() + click.length()) - x;
645 qreal height = line.height();
646 qreal y = height * line.lineNumber();
648 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
649 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
651 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
652 if(!urlstr.contains("://"))
653 urlstr= "http://" + urlstr;
654 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
655 chatScene()->loadWebPreview(this, url, urlRect);
659 void ContentsChatItem::clearWebPreview() {
661 chatScene()->clearWebPreview(this);
665 /*************************************************************************************************/
667 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
669 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
676 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
679 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
680 if(wordidx >= wrapList.count())
684 qreal targetWidth = lineCount * width + choppedTrailing;
686 qint16 start = wordidx;
687 qint16 end = wrapList.count() - 1;
689 // check if the whole line fits
690 if(wrapList.at(end).endX <= targetWidth) // || start == end)
693 // check if we have a very long word that needs inter word wrap
694 if(wrapList.at(start).endX > targetWidth) {
695 if(!line.isValid()) {
696 item->initLayoutHelper(&layout, QTextOption::NoWrap);
697 layout.beginLayout();
698 line = layout.createLine();
701 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
705 if(start + 1 == end) {
707 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
709 // both cases should be cought preliminary
710 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
711 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
713 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
714 return wrapList.at(wordidx).start;
717 qint16 pivot = (end + start) / 2;
718 if(wrapList.at(pivot).endX > targetWidth) {
728 /*************************************************************************************************/