1 /***************************************************************************
2 * Copyright (C) 2005-09 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 qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
43 : QGraphicsItem(parent),
44 _boundingRect(0, 0, width, height),
45 _selectionMode(NoSelection),
48 setAcceptHoverEvents(true);
53 const QAbstractItemModel *ChatItem::model() const {
54 return static_cast<ChatLine *>(parentItem())->model();
57 int ChatItem::row() const {
58 return static_cast<ChatLine *>(parentItem())->row();
61 QVariant ChatItem::data(int role) const {
62 QModelIndex index = model()->index(row(), column());
63 if(!index.isValid()) {
64 qWarning() << "ChatItem::data(): model index is invalid!" << index;
67 return model()->data(index, role);
70 qint16 ChatItem::posToCursor(const QPointF &pos) const {
71 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
72 if(pos.y() < 0) return 0;
76 for(int l = layout.lineCount() - 1; l >= 0; l--) {
77 QTextLine line = layout.lineAt(l);
78 if(pos.y() >= line.y()) {
79 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
85 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
88 layout->setText(data(MessageModel::DisplayRole).toString());
91 option.setWrapMode(wrapMode);
92 option.setAlignment(alignment);
93 layout->setTextOption(option);
95 QList<QTextLayout::FormatRange> formatRanges
96 = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
97 layout->setAdditionalFormats(formatRanges);
100 UiStyle::FormatList ChatItem::formatList() const {
101 return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
104 void ChatItem::doLayout(QTextLayout *layout) const {
105 layout->beginLayout();
106 QTextLine line = layout->createLine();
108 line.setLineWidth(width());
109 line.setPosition(QPointF(0,0));
114 void ChatItem::paintBackground(QPainter *painter) {
115 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
118 if(_selectionMode == FullSelection)
119 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
121 bgBrush = data(ChatLineModel::BackgroundRole);
122 if(bgBrush.isValid())
123 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
126 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
127 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
128 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
129 Q_UNUSED(option); Q_UNUSED(widget);
130 paintBackground(painter);
134 layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
136 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
139 // uncomment partially or all of the following stuff:
141 // 0) alternativ painter color for debug stuff
143 // painter->setPen(Qt::red);
145 // painter->setPen(Qt::blue);
146 // 1) draw wordwrap points in the first line
147 // if(column() == 2) {
148 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
149 // foreach(ChatLineModel::Word word, wrapList) {
150 // if(word.endX > width())
152 // painter->drawLine(word.endX, 0, word.endX, height());
155 // 2) draw MsgId over the time column
156 // if(column() == 0) {
157 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
158 // QPointF bottomPoint = boundingRect().bottomLeft();
159 // bottomPoint.ry() -= 2;
160 // painter->drawText(bottomPoint, msgIdString);
162 // 3) draw bounding rect
163 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
166 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, int start, int end, quint32 overlayFmt) const {
167 for(int i = 0; i < fmtList.count(); i++) {
168 int fmtStart = fmtList.at(i).first;
169 int fmtEnd = (i < fmtList.count()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
176 // split the format if necessary
177 if(fmtStart < start) {
178 fmtList.insert(i, fmtList.at(i));
179 fmtList[++i].first = start;
182 fmtList.insert(i, fmtList.at(i));
183 fmtList[i+1].first = end;
186 fmtList[i].second |= overlayFmt;
190 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
191 return selectionFormats();
194 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
196 return QVector<QTextLayout::FormatRange>();
199 if(_selectionMode == FullSelection) {
201 end = data(MessageModel::DisplayRole).toString().length();
203 start = qMin(_selectionStart, _selectionEnd);
204 end = qMax(_selectionStart, _selectionEnd);
207 UiStyle::FormatList fmtList = formatList();
209 while(fmtList.count() > 1 && fmtList.at(1).first <= start)
210 fmtList.removeFirst();
212 fmtList.first().first = start;
214 while(fmtList.count() > 1 && fmtList.last().first >= end)
215 fmtList.removeLast();
217 return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
220 bool ChatItem::hasSelection() const {
221 if(_selectionMode == NoSelection)
223 if(_selectionMode == FullSelection)
226 return _selectionStart != _selectionEnd;
229 QString ChatItem::selection() const {
230 if(_selectionMode == FullSelection)
231 return data(MessageModel::DisplayRole).toString();
232 if(_selectionMode == PartialSelection)
233 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
237 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
238 _selectionMode = mode;
239 _selectionStart = start;
244 void ChatItem::setFullSelection() {
245 if(_selectionMode != FullSelection) {
246 _selectionMode = FullSelection;
251 void ChatItem::clearSelection() {
252 if(_selectionMode != NoSelection) {
253 _selectionMode = NoSelection;
258 void ChatItem::continueSelecting(const QPointF &pos) {
259 _selectionMode = PartialSelection;
260 _selectionEnd = posToCursor(pos);
264 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
265 if(_selectionMode == FullSelection)
267 if(_selectionMode == PartialSelection) {
268 int cursor = posToCursor(pos);
269 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
274 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
275 QList<QRectF> resultList;
276 const QAbstractItemModel *model_ = model();
280 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
281 QList<int> indexList;
282 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
283 while(searchIdx != -1) {
284 indexList << searchIdx;
285 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
290 foreach(int idx, indexList) {
291 QTextLine line = layout.lineForTextPosition(idx);
292 qreal x = line.cursorToX(idx);
293 qreal width = line.cursorToX(idx + searchWord.count()) - x;
294 qreal height = line.height();
295 qreal y = height * line.lineNumber();
296 resultList << QRectF(x, y, width, height);
302 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
303 // single clicks are already handled by the scene (for clearing the selection)
304 if(clickMode == ChatScene::DragStartClick) {
305 chatScene()->setSelectingItem(this);
306 _selectionStart = _selectionEnd = posToCursor(pos);
307 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
312 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
313 if(event->buttons() == Qt::LeftButton) {
314 if(contains(event->pos())) {
315 qint16 end = posToCursor(event->pos());
316 if(end != _selectionEnd) {
318 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
323 chatScene()->startGlobalSelection(this, event->pos());
331 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
332 if(event->buttons() == Qt::LeftButton)
338 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
339 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
340 chatScene()->selectionToClipboard(QClipboard::Selection);
346 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
349 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
352 // ************************************************************
354 // ************************************************************
356 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
357 Q_UNUSED(option); Q_UNUSED(widget);
358 paintBackground(painter);
362 qreal layoutWidth = layout.minimumWidth();
364 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
365 offset = qMin(width() - layoutWidth, (qreal)0);
367 offset = qMax(layoutWidth - width(), (qreal)0);
369 if(layoutWidth > width()) {
370 // Draw a nice gradient for longer items
371 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
372 QPixmap pixmap(layout.boundingRect().toRect().size());
373 pixmap.fill(Qt::transparent);
374 QPainter pixPainter(&pixmap);
375 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
378 // Create alpha channel mask
379 QPixmap mask(pixmap.size());
380 QPainter maskPainter(&mask);
381 QLinearGradient gradient;
383 gradient.setStart(0, 0);
384 gradient.setFinalStop(12, 0);
385 gradient.setColorAt(0, Qt::black);
386 gradient.setColorAt(1, Qt::white);
388 gradient.setStart(width()-10, 0);
389 gradient.setFinalStop(width(), 0);
390 gradient.setColorAt(0, Qt::white);
391 gradient.setColorAt(1, Qt::black);
393 maskPainter.fillRect(boundingRect(), gradient);
394 pixmap.setAlphaChannel(mask);
395 painter->drawPixmap(0, 0, pixmap);
397 layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
401 // ************************************************************
403 // ************************************************************
405 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
407 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
408 : ChatItem(0, 0, pos, parent),
411 setGeometryByWidth(width);
414 QFontMetricsF *ContentsChatItem::fontMetrics() const {
415 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
418 ContentsChatItem::~ContentsChatItem() {
422 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
424 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
425 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
430 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
431 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
435 WrapColumnFinder finder(this);
436 while(finder.nextWrapColumn(w) > 0)
438 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
439 qreal h = lines * spacing;
443 if(w != width() || h != height()) {
444 prepareGeometryChange();
450 void ContentsChatItem::doLayout(QTextLayout *layout) const {
451 // QString t = data(Qt::DisplayRole).toString(); bool d = t.contains("protien");
452 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
453 if(!wrapList.count()) return; // empty chatitem
456 qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
457 WrapColumnFinder finder(this);
458 layout->beginLayout();
460 QTextLine line = layout->createLine();
464 int col = finder.nextWrapColumn(width());
466 col = layout->text().length();
467 int num = col - line.textStart();
469 line.setNumColumns(num);
471 // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
472 // We verify this and try setting the width again, making it shorter each time until the lengths match.
473 // Dead fugly, but seems to work…
474 for(int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
475 line.setNumColumns(i);
477 if(num != line.textLength()) {
478 qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
479 // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
482 line.setPosition(QPointF(0, h));
488 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
489 return privateData()->clickables.atCursorPos(posToCursor(pos));
492 UiStyle::FormatList ContentsChatItem::formatList() const {
493 UiStyle::FormatList fmtList = ChatItem::formatList();
494 for(int i = 0; i < privateData()->clickables.count(); i++) {
495 Clickable click = privateData()->clickables.at(i);
496 if(click.type() == Clickable::Url) {
497 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
503 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
504 QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
505 // mark a clickable if hovered upon
506 if(privateData()->currentClickable.isValid()) {
507 Clickable click = privateData()->currentClickable;
508 QTextLayout::FormatRange f;
509 f.start = click.start();
510 f.length = click.length();
511 f.format.setFontUnderline(true);
517 void ContentsChatItem::endHoverMode() {
519 if(privateData()->currentClickable.isValid()) {
520 setCursor(Qt::ArrowCursor);
521 privateData()->currentClickable = Clickable();
528 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
529 if(clickMode == ChatScene::SingleClick) {
530 qint16 idx = posToCursor(pos);
531 Clickable foo = privateData()->clickables.atCursorPos(idx);
533 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
534 QString text = data(ChatLineModel::DisplayRole).toString();
535 foo.activate(networkId, text);
537 } else if(clickMode == ChatScene::DoubleClick) {
538 chatScene()->setSelectingItem(this);
539 setSelectionMode(PartialSelection);
540 Clickable click = clickableAt(pos);
541 if(click.isValid()) {
542 setSelectionStart(click.start());
543 setSelectionEnd(click.start() + click.length());
545 // find word boundary
546 QString str = data(ChatLineModel::DisplayRole).toString();
547 qint16 cursor = posToCursor(pos);
548 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
549 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
550 if(end < 0) end = str.length();
551 setSelectionStart(start);
552 setSelectionEnd(end);
555 } else if(clickMode == ChatScene::TripleClick) {
556 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
558 ChatItem::handleClick(pos, clickMode);
561 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
562 // mouse move events always mean we're not hovering anymore...
564 ChatItem::mouseMoveEvent(event);
567 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
572 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
573 bool onClickable = false;
574 Clickable click = clickableAt(event->pos());
575 if(click.isValid()) {
576 if(click.type() == Clickable::Url) {
578 showWebPreview(click);
579 } else if(click.type() == Clickable::Channel) {
580 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
581 // don't make clickable if it's our own name
582 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
583 if(Client::networkModel()->bufferName(myId) != name)
587 setCursor(Qt::PointingHandCursor);
588 privateData()->currentClickable = click;
593 if(!onClickable) endHoverMode();
597 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
598 if(privateData()->currentClickable.isValid()) {
599 Clickable click = privateData()->currentClickable;
600 switch(click.type()) {
602 privateData()->activeClickable = click;
603 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
604 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
606 case Clickable::Channel: {
607 // Hide existing menu actions, they confuse us when right-clicking on a clickable
608 foreach(QAction *action, menu->actions())
609 action->setVisible(false);
610 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
611 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
618 // Buffer-specific actions
619 ChatItem::addActionsToMenu(menu, pos);
623 void ContentsChatItem::copyLinkToClipboard() {
624 Clickable click = privateData()->activeClickable;
625 if(click.isValid() && click.type() == Clickable::Url) {
626 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
627 if(!url.contains("://"))
628 url = "http://" + url;
629 chatScene()->stringToClipboard(url);
633 /******** WEB PREVIEW *****************************************************************************/
635 void ContentsChatItem::showWebPreview(const Clickable &click) {
641 QTextLine line = layout.lineForTextPosition(click.start());
642 qreal x = line.cursorToX(click.start());
643 qreal width = line.cursorToX(click.start() + click.length()) - x;
644 qreal height = line.height();
645 qreal y = height * line.lineNumber();
647 QPointF topLeft = scenePos() + QPointF(x, y);
648 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
650 QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
651 if(!urlstr.contains("://"))
652 urlstr= "http://" + urlstr;
653 QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
654 chatScene()->loadWebPreview(this, url, urlRect);
658 void ContentsChatItem::clearWebPreview() {
660 chatScene()->clearWebPreview(this);
664 /*************************************************************************************************/
666 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
668 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
675 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
678 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
679 if(wordidx >= wrapList.count())
683 qreal targetWidth = lineCount * width + choppedTrailing;
685 qint16 start = wordidx;
686 qint16 end = wrapList.count() - 1;
688 // check if the whole line fits
689 if(wrapList.at(end).endX <= targetWidth) // || start == end)
692 // check if we have a very long word that needs inter word wrap
693 if(wrapList.at(start).endX > targetWidth) {
694 if(!line.isValid()) {
695 item->initLayoutHelper(&layout, QTextOption::NoWrap);
696 layout.beginLayout();
697 line = layout.createLine();
700 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
704 if(start + 1 == end) {
706 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
708 // both cases should be cought preliminary
709 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
710 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
712 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
713 return wrapList.at(wordidx).start;
716 qint16 pivot = (end + start) / 2;
717 if(wrapList.at(pivot).endX > targetWidth) {
727 /*************************************************************************************************/