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"
34 #include "chatlinemodel.h"
35 #include "contextmenuactionprovider.h"
36 #include "iconloader.h"
39 #include "qtuistyle.h"
41 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
42 : QGraphicsItem(parent),
43 _boundingRect(0, 0, width, height),
44 _selectionMode(NoSelection),
47 setAcceptHoverEvents(true);
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 qint16 ChatItem::posToCursor(const QPointF &pos) const {
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) {
106 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
109 if(_selectionMode == FullSelection)
110 bgBrush = data(ChatLineModel::SelectedBackgroundRole);
112 bgBrush = data(ChatLineModel::BackgroundRole);
113 if(bgBrush.isValid())
114 painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
117 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
118 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
119 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
120 Q_UNUSED(option); Q_UNUSED(widget);
121 paintBackground(painter);
125 layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
127 // layout()->draw(painter, QPointF(0,0), formats, boundingRect());
130 // uncomment partially or all of the following stuff:
132 // 0) alternativ painter color for debug stuff
134 // painter->setPen(Qt::red);
136 // painter->setPen(Qt::blue);
137 // 1) draw wordwrap points in the first line
138 // if(column() == 2) {
139 // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
140 // foreach(ChatLineModel::Word word, wrapList) {
141 // if(word.endX > width())
143 // painter->drawLine(word.endX, 0, word.endX, height());
146 // 2) draw MsgId over the time column
147 // if(column() == 0) {
148 // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
149 // QPointF bottomPoint = boundingRect().bottomLeft();
150 // bottomPoint.ry() -= 2;
151 // painter->drawText(bottomPoint, msgIdString);
153 // 3) draw bounding rect
154 // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
157 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, int start, int end, quint32 overlayFmt) const {
158 for(int i = 0; i < fmtList.count(); i++) {
159 int fmtStart = fmtList.at(i).first;
160 int fmtEnd = (i < fmtList.count()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
167 // split the format if necessary
168 if(fmtStart < start) {
169 fmtList.insert(i, fmtList.at(i));
170 fmtList[++i].first = start;
173 fmtList.insert(i, fmtList.at(i));
174 fmtList[i+1].first = end;
177 fmtList[i].second |= overlayFmt;
181 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
182 return selectionFormats();
185 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
187 return QVector<QTextLayout::FormatRange>();
190 if(_selectionMode == FullSelection) {
192 end = data(MessageModel::DisplayRole).toString().length();
194 start = qMin(_selectionStart, _selectionEnd);
195 end = qMax(_selectionStart, _selectionEnd);
198 UiStyle::FormatList fmtList = formatList();
200 while(fmtList.count() > 1 && fmtList.at(1).first <= start)
201 fmtList.removeFirst();
203 fmtList.first().first = start;
205 while(fmtList.count() > 1 && fmtList.last().first >= end)
206 fmtList.removeLast();
208 return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
211 bool ChatItem::hasSelection() const {
212 if(_selectionMode == NoSelection)
214 if(_selectionMode == FullSelection)
217 return _selectionStart != _selectionEnd;
220 QString ChatItem::selection() const {
221 if(_selectionMode == FullSelection)
222 return data(MessageModel::DisplayRole).toString();
223 if(_selectionMode == PartialSelection)
224 return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
228 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
229 _selectionMode = mode;
230 _selectionStart = start;
235 void ChatItem::setFullSelection() {
236 if(_selectionMode != FullSelection) {
237 _selectionMode = FullSelection;
242 void ChatItem::clearSelection() {
243 if(_selectionMode != NoSelection) {
244 _selectionMode = NoSelection;
249 void ChatItem::continueSelecting(const QPointF &pos) {
250 _selectionMode = PartialSelection;
251 _selectionEnd = posToCursor(pos);
255 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
256 if(_selectionMode == FullSelection)
258 if(_selectionMode == PartialSelection) {
259 int cursor = posToCursor(pos);
260 return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
265 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
266 QList<QRectF> resultList;
267 const QAbstractItemModel *model_ = model();
271 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
272 QList<int> indexList;
273 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
274 while(searchIdx != -1) {
275 indexList << searchIdx;
276 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
281 foreach(int idx, indexList) {
282 QTextLine line = layout.lineForTextPosition(idx);
283 qreal x = line.cursorToX(idx);
284 qreal width = line.cursorToX(idx + searchWord.count()) - x;
285 qreal height = line.height();
286 qreal y = height * line.lineNumber();
287 resultList << QRectF(x, y, width, height);
293 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
294 // single clicks are already handled by the scene (for clearing the selection)
295 if(clickMode == ChatScene::DragStartClick) {
296 chatScene()->setSelectingItem(this);
297 _selectionStart = _selectionEnd = posToCursor(pos);
298 _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
303 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
304 if(event->buttons() == Qt::LeftButton) {
305 if(contains(event->pos())) {
306 qint16 end = posToCursor(event->pos());
307 if(end != _selectionEnd) {
309 _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
314 chatScene()->startGlobalSelection(this, event->pos());
322 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
323 if(event->buttons() == Qt::LeftButton)
329 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
330 if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
331 chatScene()->selectionToClipboard(QClipboard::Selection);
337 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
340 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
343 // ************************************************************
345 // ************************************************************
347 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
348 Q_UNUSED(option); Q_UNUSED(widget);
349 paintBackground(painter);
353 qreal layoutWidth = layout.minimumWidth();
355 if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
356 offset = qMin(width() - layoutWidth, (qreal)0);
358 offset = qMax(layoutWidth - width(), (qreal)0);
360 if(layoutWidth > width()) {
361 // Draw a nice gradient for longer items
362 // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
363 QPixmap pixmap(layout.boundingRect().toRect().size());
364 pixmap.fill(Qt::transparent);
365 QPainter pixPainter(&pixmap);
366 layout.draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
369 // Create alpha channel mask
370 QPixmap mask(pixmap.size());
371 QPainter maskPainter(&mask);
372 QLinearGradient gradient;
374 gradient.setStart(0, 0);
375 gradient.setFinalStop(12, 0);
376 gradient.setColorAt(0, Qt::black);
377 gradient.setColorAt(1, Qt::white);
379 gradient.setStart(width()-10, 0);
380 gradient.setFinalStop(width(), 0);
381 gradient.setColorAt(0, Qt::white);
382 gradient.setColorAt(1, Qt::black);
384 maskPainter.fillRect(boundingRect(), gradient);
385 pixmap.setAlphaChannel(mask);
386 painter->drawPixmap(0, 0, pixmap);
388 layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
392 // ************************************************************
394 // ************************************************************
396 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
398 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
399 : ChatItem(0, 0, pos, parent),
402 setGeometryByWidth(width);
405 QFontMetricsF *ContentsChatItem::fontMetrics() const {
406 return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
409 ContentsChatItem::~ContentsChatItem() {
413 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
415 ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
416 that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
421 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
422 // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
426 WrapColumnFinder finder(this);
427 while(finder.nextWrapColumn(w) > 0)
429 qreal h = lines * fontMetrics()->lineSpacing();
433 if(w != width() || h != height()) {
434 prepareGeometryChange();
440 void ContentsChatItem::doLayout(QTextLayout *layout) const {
441 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
442 if(!wrapList.count()) return; // empty chatitem
445 WrapColumnFinder finder(this);
446 layout->beginLayout();
448 QTextLine line = layout->createLine();
452 int col = finder.nextWrapColumn(width());
453 line.setNumColumns(col >= 0 ? col - line.textStart() : layout->text().length());
454 line.setPosition(QPointF(0, h));
455 h += fontMetrics()->lineSpacing();
460 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
461 qint16 idx = posToCursor(pos);
462 for(int i = 0; i < privateData()->clickables.count(); i++) {
463 Clickable click = privateData()->clickables.at(i);
464 if(idx >= click.start() && idx < click.start() + click.length())
470 UiStyle::FormatList ContentsChatItem::formatList() const {
471 UiStyle::FormatList fmtList = ChatItem::formatList();
472 for(int i = 0; i < privateData()->clickables.count(); i++) {
473 Clickable click = privateData()->clickables.at(i);
474 if(click.type() == Clickable::Url) {
475 overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
481 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
482 QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
483 // mark a clickable if hovered upon
484 if(privateData()->currentClickable.isValid()) {
485 Clickable click = privateData()->currentClickable;
486 QTextLayout::FormatRange f;
487 f.start = click.start();
488 f.length = click.length();
489 f.format.setFontUnderline(true);
495 void ContentsChatItem::endHoverMode() {
497 if(privateData()->currentClickable.isValid()) {
498 setCursor(Qt::ArrowCursor);
499 privateData()->currentClickable = Clickable();
506 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
507 if(clickMode == ChatScene::SingleClick) {
508 Clickable click = clickableAt(pos);
509 if(click.isValid()) {
510 QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
511 switch(click.type()) {
513 if(!str.contains("://"))
514 str = "http://" + str;
515 QDesktopServices::openUrl(QUrl::fromEncoded(str.toUtf8(), QUrl::TolerantMode));
517 case Clickable::Channel: {
518 NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
519 BufferId bufId = Client::networkModel()->bufferId(networkId, str);
520 if(bufId.isValid()) {
521 QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
522 Client::bufferModel()->switchToBuffer(bufId);
523 if(!targetIdx.data(NetworkModel::ItemActiveRole).toBool())
524 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
526 Client::userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(str));
533 } else if(clickMode == ChatScene::DoubleClick) {
534 chatScene()->setSelectingItem(this);
535 setSelectionMode(PartialSelection);
536 Clickable click = clickableAt(pos);
537 if(click.isValid()) {
538 setSelectionStart(click.start());
539 setSelectionEnd(click.start() + click.length());
541 // find word boundary
542 QString str = data(ChatLineModel::DisplayRole).toString();
543 qint16 cursor = posToCursor(pos);
544 qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
545 qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
546 if(end < 0) end = str.length();
547 setSelectionStart(start);
548 setSelectionEnd(end);
551 } else if(clickMode == ChatScene::TripleClick) {
552 setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
554 ChatItem::handleClick(pos, clickMode);
557 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
558 // mouse move events always mean we're not hovering anymore...
560 ChatItem::mouseMoveEvent(event);
563 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
568 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
569 bool onClickable = false;
570 Clickable click = clickableAt(event->pos());
571 if(click.isValid()) {
572 if(click.type() == Clickable::Url) {
574 showWebPreview(click);
575 } else if(click.type() == Clickable::Channel) {
576 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
577 // don't make clickable if it's our own name
578 BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
579 if(Client::networkModel()->bufferName(myId) != name)
583 setCursor(Qt::PointingHandCursor);
584 privateData()->currentClickable = click;
589 if(!onClickable) endHoverMode();
593 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
594 if(privateData()->currentClickable.isValid()) {
595 Clickable click = privateData()->currentClickable;
596 switch(click.type()) {
598 privateData()->activeClickable = click;
599 menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
600 &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
602 case Clickable::Channel: {
603 // Hide existing menu actions, they confuse us when right-clicking on a clickable
604 foreach(QAction *action, menu->actions())
605 action->setVisible(false);
606 QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
607 GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
614 // Buffer-specific actions
615 ChatItem::addActionsToMenu(menu, pos);
619 void ContentsChatItem::copyLinkToClipboard() {
620 Clickable click = privateData()->activeClickable;
621 if(click.isValid() && click.type() == Clickable::Url) {
622 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
623 if(!url.contains("://"))
624 url = "http://" + url;
625 chatScene()->stringToClipboard(url);
629 /******** WEB PREVIEW *****************************************************************************/
631 void ContentsChatItem::showWebPreview(const Clickable &click) {
637 QTextLine line = layout.lineForTextPosition(click.start());
638 qreal x = line.cursorToX(click.start());
639 qreal width = line.cursorToX(click.start() + click.length()) - x;
640 qreal height = line.height();
641 qreal y = height * line.lineNumber();
643 QPointF topLeft = scenePos() + QPointF(x, y);
644 QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
646 QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
647 if(!url.contains("://"))
648 url = "http://" + url;
649 chatScene()->loadWebPreview(this, url, urlRect);
653 void ContentsChatItem::clearWebPreview() {
655 chatScene()->clearWebPreview(this);
659 /*************************************************************************************************/
661 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
663 wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
670 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
673 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
674 if(wordidx >= wrapList.count())
678 qreal targetWidth = lineCount * width + choppedTrailing;
680 qint16 start = wordidx;
681 qint16 end = wrapList.count() - 1;
683 // check if the whole line fits
684 if(wrapList.at(end).endX <= targetWidth) // || start == end)
687 // check if we have a very long word that needs inter word wrap
688 if(wrapList.at(start).endX > targetWidth) {
689 if(!line.isValid()) {
690 item->initLayoutHelper(&layout, QTextOption::NoWrap);
691 layout.beginLayout();
692 line = layout.createLine();
695 return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
699 if(start + 1 == end) {
701 const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
703 // both cases should be cought preliminary
704 Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
705 Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
707 choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
708 return wrapList.at(wordidx).start;
711 qint16 pivot = (end + start) / 2;
712 if(wrapList.at(pivot).endX > targetWidth) {
722 /*************************************************************************************************/