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 ChatLine *ChatItem::chatLine() const {
55 ChatScene *ChatItem::chatScene() const {
56 return chatLine()->chatScene();
59 const QAbstractItemModel *ChatItem::model() const {
60 return chatLine()->model();
63 int ChatItem::row() const {
64 return chatLine()->row();
67 QPointF ChatItem::mapToLine(const QPointF &p) const {
71 QPointF ChatItem::mapFromLine(const QPointF &p) const {
75 // relative to the ChatLine
76 QPointF ChatItem::mapToScene(const QPointF &p) const {
77 return chatLine()->mapToScene(p /* + pos() */);
80 QPointF ChatItem::mapFromScene(const QPointF &p) const {
81 return chatLine()->mapFromScene(p) /* - pos() */;
84 QVariant ChatItem::data(int role) const {
85 QModelIndex index = model()->index(row(), column());
86 if(!index.isValid()) {
87 qWarning() << "ChatItem::data(): model index is invalid!" << index;
90 return model()->data(index, role);
93 qint16 ChatItem::posToCursor(const QPointF &posInLine) const {
94 QPointF pos = mapFromLine(posInLine);
95 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
96 if(pos.y() < 0) return 0;
100 for(int l = layout.lineCount() - 1; l >= 0; l--) {
101 QTextLine line = layout.lineAt(l);
102 if(pos.y() >= line.y()) {
103 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
109 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
112 layout->setText(data(MessageModel::DisplayRole).toString());
115 option.setWrapMode(wrapMode);
116 option.setAlignment(alignment);
117 layout->setTextOption(option);
119 QList<QTextLayout::FormatRange> formatRanges
120 = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
121 layout->setAdditionalFormats(formatRanges);
124 UiStyle::FormatList ChatItem::formatList() const {
125 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
128 void ChatItem::doLayout(QTextLayout *layout) const {
129 layout->beginLayout();
130 QTextLine line = layout->createLine();
132 line.setLineWidth(width());
133 line.setPosition(QPointF(0,0));
138 void ChatItem::paintBackground(QPainter *painter) {
140 if(_selectionMode == FullSelection)
141 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
143 bgBrush = data(ChatLineModel::BackgroundRole);
144 if(bgBrush.isValid())
145 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
148 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
149 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
150 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
151 Q_UNUSED(option); Q_UNUSED(widget);
153 painter->setClipRect(boundingRect());
154 paintBackground(painter);
158 layout.draw(painter, pos(), additionalFormats(), boundingRect());
160 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
163 // uncomment partially or all of the following stuff:
165 // 0) alternativ painter color for debug stuff
167 // painter->setPen(Qt::red);
169 // painter->setPen(Qt::blue);
170 // 1) draw wordwrap points in the first line
171 // if(column() == 2) {
172 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
173 // foreach(ChatLineModel::Word word, wrapList) {
174 // if(word.endX > width())
176 // painter->drawLine(word.endX, 0, word.endX, height());
179 // 2) draw MsgId over the time column
180 // if(column() == 0) {
181 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
182 // QPointF bottomPoint = boundingRect().bottomLeft();
183 // bottomPoint.ry() -= 2;
184 // painter->drawText(bottomPoint, msgIdString);
186 // 3) draw bounding rect
187 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
192 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, int start, int end, quint32 overlayFmt) const {
193 for(int i = 0; i < fmtList.count(); i++) {
194 int fmtStart = fmtList.at(i).first;
195 int fmtEnd = (i < fmtList.count()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
202 // split the format if necessary
203 if(fmtStart < start) {
204 fmtList.insert(i, fmtList.at(i));
205 fmtList[++i].first = start;
208 fmtList.insert(i, fmtList.at(i));
209 fmtList[i+1].first = end;
212 fmtList[i].second |= overlayFmt;
216 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
217 return selectionFormats();
220 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
222 return QVector<QTextLayout::FormatRange>();
225 if(_selectionMode == FullSelection) {
227 end = data(MessageModel::DisplayRole).toString().length();
229 start = qMin(_selectionStart, _selectionEnd);
230 end = qMax(_selectionStart, _selectionEnd);
233 UiStyle::FormatList fmtList = formatList();
235 while(fmtList.count() > 1 && fmtList.at(1).first <= start)
236 fmtList.removeFirst();
238 fmtList.first().first = start;
240 while(fmtList.count() > 1 && fmtList.last().first >= end)
241 fmtList.removeLast();
243 return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
246 bool ChatItem::hasSelection() const {
247 if(_selectionMode == NoSelection)
249 if(_selectionMode == FullSelection)
252 return _selectionStart != _selectionEnd;
255 QString ChatItem::selection() const {
256 if(_selectionMode == FullSelection)
257 return data(MessageModel::DisplayRole).toString();
258 if(_selectionMode == PartialSelection)
259 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
263 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
264 _selectionMode = mode;
265 _selectionStart = start;
267 chatLine()->update();
270 void ChatItem::setFullSelection() {
271 if(_selectionMode != FullSelection) {
272 _selectionMode = FullSelection;
273 chatLine()->update();
277 void ChatItem::clearSelection() {
278 if(_selectionMode != NoSelection) {
279 _selectionMode = NoSelection;
280 chatLine()->update();
284 void ChatItem::continueSelecting(const QPointF &pos) {
285 _selectionMode = PartialSelection;
286 _selectionEnd = posToCursor(pos);
287 chatLine()->update();
290 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
291 if(_selectionMode == FullSelection)
293 if(_selectionMode == PartialSelection) {
294 int cursor = posToCursor(pos);
295 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
300 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
301 QList<QRectF> resultList;
302 const QAbstractItemModel *model_ = model();
306 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
307 QList<int> indexList;
308 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
309 while(searchIdx != -1) {
310 indexList << searchIdx;
311 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
316 foreach(int idx, indexList) {
317 QTextLine line = layout.lineForTextPosition(idx);
318 qreal x = line.cursorToX(idx);
319 qreal width = line.cursorToX(idx + searchWord.count()) - x;
320 qreal height = line.height();
321 qreal y = height * line.lineNumber();
322 resultList << QRectF(x, y, width, height);
328 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
329 // single clicks are already handled by the scene (for clearing the selection)
330 if(clickMode == ChatScene::DragStartClick) {
331 chatScene()->setSelectingItem(this);
332 _selectionStart = _selectionEnd = posToCursor(pos);
333 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
334 chatLine()->update();
338 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
339 if(event->buttons() == Qt::LeftButton) {
340 if(boundingRect().contains(event->pos())) {
341 qint16 end = posToCursor(event->pos());
342 if(end != _selectionEnd) {
344 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
345 chatLine()->update();
349 chatScene()->startGlobalSelection(this, event->pos());
357 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
358 if(event->buttons() == Qt::LeftButton)
364 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
365 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
366 chatScene()->selectionToClipboard(QClipboard::Selection);
372 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
375 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
378 // ************************************************************
380 // ************************************************************
382 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
383 Q_UNUSED(option); Q_UNUSED(widget);
385 painter->setClipRect(boundingRect());
386 paintBackground(painter);
390 qreal layoutWidth = layout.minimumWidth();
392 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
393 offset = qMin(width() - layoutWidth, (qreal)0);
395 offset = qMax(layoutWidth - width(), (qreal)0);
397 if(layoutWidth > width()) {
398 // Draw a nice gradient for longer items
399 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
400 QPixmap pixmap(layout.boundingRect().toRect().size());
401 pixmap.fill(Qt::transparent);
402 QPainter pixPainter(&pixmap);
403 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
406 // Create alpha channel mask
407 QPixmap mask(pixmap.size());
408 QPainter maskPainter(&mask);
409 QLinearGradient gradient;
411 gradient.setStart(0, 0);
412 gradient.setFinalStop(12, 0);
413 gradient.setColorAt(0, Qt::black);
414 gradient.setColorAt(1, Qt::white);
416 gradient.setStart(width()-10, 0);
417 gradient.setFinalStop(width(), 0);
418 gradient.setColorAt(0, Qt::white);
419 gradient.setColorAt(1, Qt::black);
421 maskPainter.fillRect(0, 0, pixmap.width(), pixmap.height(), gradient);
422 pixmap.setAlphaChannel(mask);
423 painter->drawPixmap(pos(), pixmap);
425 layout.draw(painter, pos(), additionalFormats(), boundingRect());
430 void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
431 if(clickMode == ChatScene::DoubleClick) {
432 BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
433 QString nick = data(MessageModel::EditRole).toString();
434 // check if the nick is a valid ircUser
435 if(!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
436 Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
439 ChatItem::handleClick(pos, clickMode);
442 // ************************************************************
444 // ************************************************************
446 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
448 ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
449 : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
453 setGeometryByWidth(width);
456 QFontMetricsF *ContentsChatItem::fontMetrics() const {
457 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
460 ContentsChatItem::~ContentsChatItem() {
464 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
466 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
467 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
472 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
473 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
477 WrapColumnFinder finder(this);
478 while(finder.nextWrapColumn(w) > 0)
480 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
481 qreal h = lines * spacing;
485 if(w != width() || h != height())
491 void ContentsChatItem::doLayout(QTextLayout *layout) const {
492 // QString t = data(Qt::DisplayRole).toString(); bool d = t.contains("protien");
493 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
494 if(!wrapList.count()) return; // empty chatitem
497 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
498 WrapColumnFinder finder(this);
499 layout->beginLayout();
501 QTextLine line = layout->createLine();
505 int col = finder.nextWrapColumn(width());
507 col = layout->text().length();
508 int num = col - line.textStart();
510 line.setNumColumns(num);
512 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
513 // We verify this and try setting the width again, making it shorter each time until the lengths match.
514 // Dead fugly, but seems to work…
515 for(int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
516 line.setNumColumns(i);
518 if(num != line.textLength()) {
519 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
520 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
523 line.setPosition(QPointF(0, h));
529 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
530 return privateData()->clickables.atCursorPos(posToCursor(pos));
533 UiStyle::FormatList ContentsChatItem::formatList() const {
534 UiStyle::FormatList fmtList = ChatItem::formatList();
535 for(int i = 0; i < privateData()->clickables.count(); i++) {
536 Clickable click = privateData()->clickables.at(i);
537 if(click.type() == Clickable::Url) {
538 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
544 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
545 QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
546 // mark a clickable if hovered upon
547 if(privateData()->currentClickable.isValid()) {
548 Clickable click = privateData()->currentClickable;
549 QTextLayout::FormatRange f;
550 f.start = click.start();
551 f.length = click.length();
552 f.format.setFontUnderline(true);
558 void ContentsChatItem::endHoverMode() {
560 if(privateData()->currentClickable.isValid()) {
561 chatLine()->setCursor(Qt::ArrowCursor);
562 privateData()->currentClickable = Clickable();
565 chatLine()->update();
569 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
570 if(clickMode == ChatScene::SingleClick) {
571 qint16 idx = posToCursor(pos);
572 Clickable foo = privateData()->clickables.atCursorPos(idx);
574 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
575 QString text = data(ChatLineModel::DisplayRole).toString();
576 foo.activate(networkId, text);
578 } else if(clickMode == ChatScene::DoubleClick) {
579 chatScene()->setSelectingItem(this);
580 setSelectionMode(PartialSelection);
581 Clickable click = clickableAt(pos);
582 if(click.isValid()) {
583 setSelectionStart(click.start());
584 setSelectionEnd(click.start() + click.length());
586 // find word boundary
587 QString str = data(ChatLineModel::DisplayRole).toString();
588 qint16 cursor = posToCursor(pos);
589 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
590 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
591 if(end < 0) end = str.length();
592 setSelectionStart(start);
593 setSelectionEnd(end);
595 chatLine()->update();
596 } else if(clickMode == ChatScene::TripleClick) {
597 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
599 ChatItem::handleClick(pos, clickMode);
602 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
603 // mouse move events always mean we're not hovering anymore...
605 ChatItem::mouseMoveEvent(event);
608 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
613 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
614 bool onClickable = false;
615 Clickable click = clickableAt(event->pos());
616 if(click.isValid()) {
617 if(click.type() == Clickable::Url) {
619 showWebPreview(click);
620 } else if(click.type() == Clickable::Channel) {
621 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
622 // don't make clickable if it's our own name
623 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
624 if(Client::networkModel()->bufferName(myId) != name)
628 chatLine()->setCursor(Qt::PointingHandCursor);
629 privateData()->currentClickable = click;
630 chatLine()->update();
634 if(!onClickable) endHoverMode();
638 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
639 if(privateData()->currentClickable.isValid()) {
640 Clickable click = privateData()->currentClickable;
641 switch(click.type()) {
643 privateData()->activeClickable = click;
644 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
645 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
647 case Clickable::Channel: {
648 // Hide existing menu actions, they confuse us when right-clicking on a clickable
649 foreach(QAction *action, menu->actions())
650 action->setVisible(false);
651 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
652 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
659 // Buffer-specific actions
660 ChatItem::addActionsToMenu(menu, pos);
664 void ContentsChatItem::copyLinkToClipboard() {
665 Clickable click = privateData()->activeClickable;
666 if(click.isValid() && click.type() == Clickable::Url) {
667 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
668 if(!url.contains("://"))
669 url = "http://" + url;
670 chatScene()->stringToClipboard(url);
674 /******** WEB PREVIEW *****************************************************************************/
676 void ContentsChatItem::showWebPreview(const Clickable &click) {
682 QTextLine line = layout.lineForTextPosition(click.start());
683 qreal x = line.cursorToX(click.start());
684 qreal width = line.cursorToX(click.start() + click.length()) - x;
685 qreal height = line.height();
686 qreal y = height * line.lineNumber();
688 QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
689 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
691 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
692 if(!urlstr.contains("://"))
693 urlstr= "http://" + urlstr;
694 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
695 chatScene()->loadWebPreview(this, url, urlRect);
699 void ContentsChatItem::clearWebPreview() {
701 chatScene()->clearWebPreview(this);
705 /*************************************************************************************************/
707 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
709 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
716 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
719 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
720 if(wordidx >= wrapList.count())
724 qreal targetWidth = lineCount * width + choppedTrailing;
726 qint16 start = wordidx;
727 qint16 end = wrapList.count() - 1;
729 // check if the whole line fits
730 if(wrapList.at(end).endX <= targetWidth) // || start == end)
733 // check if we have a very long word that needs inter word wrap
734 if(wrapList.at(start).endX > targetWidth) {
735 if(!line.isValid()) {
736 item->initLayoutHelper(&layout, QTextOption::NoWrap);
737 layout.beginLayout();
738 line = layout.createLine();
741 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
745 if(start + 1 == end) {
747 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
749 // both cases should be cought preliminary
750 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
751 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
753 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
754 return wrapList.at(wordidx).start;
757 qint16 pivot = (end + start) / 2;
758 if(wrapList.at(pivot).endX > targetWidth) {
768 /*************************************************************************************************/