No longer disable the input widget for inactive buffers
[quassel.git] / src / qtui / chatitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include <QApplication>
22 #include <QClipboard>
23 #include <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
26 #include <QPainter>
27 #include <QPalette>
28 #include <QTextLayout>
29 #include <QMenu>
30
31 #include "buffermodel.h"
32 #include "bufferview.h"
33 #include "chatitem.h"
34 #include "chatline.h"
35 #include "chatlinemodel.h"
36 #include "chatview.h"
37 #include "contextmenuactionprovider.h"
38 #include "iconloader.h"
39 #include "mainwin.h"
40 #include "qtui.h"
41 #include "qtuistyle.h"
42
43 ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent)
44 : _parent(parent),
45   _boundingRect(boundingRect),
46   _selectionMode(NoSelection),
47   _selectionStart(-1),
48   _cachedLayout(0)
49 {
50
51 }
52
53 ChatItem::~ChatItem() {
54   delete _cachedLayout;
55 }
56
57 ChatLine *ChatItem::chatLine() const {
58   return _parent;
59 }
60
61 ChatScene *ChatItem::chatScene() const {
62   return chatLine()->chatScene();
63 }
64
65 ChatView *ChatItem::chatView() const {
66   return chatScene()->chatView();
67 }
68
69 const QAbstractItemModel *ChatItem::model() const {
70   return chatLine()->model();
71 }
72
73 int ChatItem::row() const {
74   return chatLine()->row();
75 }
76
77 QPointF ChatItem::mapToLine(const QPointF &p) const {
78   return p + pos();
79 }
80
81 QPointF ChatItem::mapFromLine(const QPointF &p) const {
82   return p - pos();
83 }
84
85 // relative to the ChatLine
86 QPointF ChatItem::mapToScene(const QPointF &p) const {
87   return chatLine()->mapToScene(p /* + pos() */);
88 }
89
90 QPointF ChatItem::mapFromScene(const QPointF &p) const {
91   return chatLine()->mapFromScene(p) /* - pos() */;
92 }
93
94 QVariant ChatItem::data(int role) const {
95   QModelIndex index = model()->index(row(), column());
96   if(!index.isValid()) {
97     qWarning() << "ChatItem::data(): model index is invalid!" << index;
98     return QVariant();
99   }
100   return model()->data(index, role);
101 }
102
103 QTextLayout *ChatItem::layout() const {
104   if(_cachedLayout)
105     return _cachedLayout;
106
107   _cachedLayout = new QTextLayout;
108   initLayout(_cachedLayout);
109   chatView()->setHasCache(chatLine());
110   return _cachedLayout;
111 }
112
113 void ChatItem::clearCache() {
114   delete _cachedLayout;
115   _cachedLayout = 0;
116 }
117
118 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
119   Q_ASSERT(layout);
120
121   layout->setText(data(MessageModel::DisplayRole).toString());
122
123   QTextOption option;
124   option.setWrapMode(wrapMode);
125   option.setAlignment(alignment);
126   layout->setTextOption(option);
127
128   QList<QTextLayout::FormatRange> formatRanges
129          = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
130   layout->setAdditionalFormats(formatRanges);
131 }
132
133 void ChatItem::initLayout(QTextLayout *layout) const {
134   initLayoutHelper(layout, QTextOption::NoWrap);
135   doLayout(layout);
136 }
137
138 void ChatItem::doLayout(QTextLayout *layout) const {
139   layout->beginLayout();
140   QTextLine line = layout->createLine();
141   if(line.isValid()) {
142     line.setLineWidth(width());
143     line.setPosition(QPointF(0,0));
144   }
145   layout->endLayout();
146 }
147
148 UiStyle::FormatList ChatItem::formatList() const {
149   return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
150 }
151
152 qint16 ChatItem::posToCursor(const QPointF &posInLine) const {
153   QPointF pos = mapFromLine(posInLine);
154   if(pos.y() > height())
155     return data(MessageModel::DisplayRole).toString().length();
156   if(pos.y() < 0)
157     return 0;
158
159   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
160     QTextLine line = layout()->lineAt(l);
161     if(pos.y() >= line.y()) {
162       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
163     }
164   }
165   return 0;
166 }
167
168 void ChatItem::paintBackground(QPainter *painter) {
169   QVariant bgBrush;
170   if(_selectionMode == FullSelection)
171     bgBrush = data(ChatLineModel::SelectedBackgroundRole);
172   else
173     bgBrush = data(ChatLineModel::BackgroundRole);
174   if(bgBrush.isValid())
175     painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
176 }
177
178 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
179 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
180 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
181   Q_UNUSED(option); Q_UNUSED(widget);
182   painter->save();
183   painter->setClipRect(boundingRect());
184   paintBackground(painter);
185
186   layout()->draw(painter, pos(), additionalFormats(), boundingRect());
187
188   //  layout()->draw(painter, QPointF(0,0), formats, boundingRect());
189
190   // Debuging Stuff
191   // uncomment partially or all of the following stuff:
192   //
193   // 0) alternativ painter color for debug stuff
194 //   if(row() % 2)
195 //     painter->setPen(Qt::red);
196 //   else
197 //     painter->setPen(Qt::blue);
198   // 1) draw wordwrap points in the first line
199 //   if(column() == 2) {
200 //     ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
201 //     foreach(ChatLineModel::Word word, wrapList) {
202 //       if(word.endX > width())
203 //      break;
204 //       painter->drawLine(word.endX, 0, word.endX, height());
205 //     }
206 //   }
207   // 2) draw MsgId over the time column
208 //   if(column() == 0) {
209 //     QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
210 //     QPointF bottomPoint = boundingRect().bottomLeft();
211 //     bottomPoint.ry() -= 2;
212 //     painter->drawText(bottomPoint, msgIdString);
213 //   }
214   // 3) draw bounding rect
215 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
216
217   painter->restore();
218 }
219
220 void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, int start, int end, quint32 overlayFmt) const {
221   for(int i = 0; i < fmtList.count(); i++) {
222     int fmtStart = fmtList.at(i).first;
223     int fmtEnd = (i < fmtList.count()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
224
225     if(fmtEnd <= start)
226       continue;
227     if(fmtStart >= end)
228       break;
229
230     // split the format if necessary
231     if(fmtStart < start) {
232       fmtList.insert(i, fmtList.at(i));
233       fmtList[++i].first = start;
234     }
235     if(end < fmtEnd) {
236       fmtList.insert(i, fmtList.at(i));
237       fmtList[i+1].first = end;
238     }
239
240     fmtList[i].second |= overlayFmt;
241   }
242 }
243
244 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
245   return selectionFormats();
246 }
247
248 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
249   if(!hasSelection())
250     return QVector<QTextLayout::FormatRange>();
251
252   int start, end;
253   if(_selectionMode == FullSelection) {
254     start = 0;
255     end = data(MessageModel::DisplayRole).toString().length();
256   } else {
257     start = qMin(_selectionStart, _selectionEnd);
258     end = qMax(_selectionStart, _selectionEnd);
259   }
260
261   UiStyle::FormatList fmtList = formatList();
262
263   while(fmtList.count() > 1 && fmtList.at(1).first <= start)
264     fmtList.removeFirst();
265
266   fmtList.first().first = start;
267
268   while(fmtList.count() > 1 && fmtList.last().first >= end)
269     fmtList.removeLast();
270
271   return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
272 }
273
274 bool ChatItem::hasSelection() const {
275   if(_selectionMode == NoSelection)
276     return false;
277   if(_selectionMode == FullSelection)
278     return true;
279   // partial
280   return _selectionStart != _selectionEnd;
281 }
282
283 QString ChatItem::selection() const {
284   if(_selectionMode == FullSelection)
285     return data(MessageModel::DisplayRole).toString();
286   if(_selectionMode == PartialSelection)
287     return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
288   return QString();
289 }
290
291 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
292   _selectionMode = mode;
293   _selectionStart = start;
294   _selectionEnd = end;
295   chatLine()->update();
296 }
297
298 void ChatItem::setFullSelection() {
299   if(_selectionMode != FullSelection) {
300     _selectionMode = FullSelection;
301     chatLine()->update();
302   }
303 }
304
305 void ChatItem::clearSelection() {
306   if(_selectionMode != NoSelection) {
307     _selectionMode = NoSelection;
308     chatLine()->update();
309   }
310 }
311
312 void ChatItem::continueSelecting(const QPointF &pos) {
313   _selectionMode = PartialSelection;
314   _selectionEnd = posToCursor(pos);
315   chatLine()->update();
316 }
317
318 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
319   if(_selectionMode == FullSelection)
320     return true;
321   if(_selectionMode == PartialSelection) {
322     int cursor = posToCursor(pos);
323     return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
324   }
325   return false;
326 }
327
328 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
329   QList<QRectF> resultList;
330   const QAbstractItemModel *model_ = model();
331   if(!model_)
332     return resultList;
333
334   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
335   QList<int> indexList;
336   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
337   while(searchIdx != -1) {
338     indexList << searchIdx;
339     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
340   }
341
342   foreach(int idx, indexList) {
343     QTextLine line = layout()->lineForTextPosition(idx);
344     qreal x = line.cursorToX(idx);
345     qreal width = line.cursorToX(idx + searchWord.count()) - x;
346     qreal height = line.height();
347     qreal y = height * line.lineNumber();
348     resultList << QRectF(x, y, width, height);
349   }
350
351   return resultList;
352 }
353
354 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
355   // single clicks are already handled by the scene (for clearing the selection)
356   if(clickMode == ChatScene::DragStartClick) {
357     chatScene()->setSelectingItem(this);
358     _selectionStart = _selectionEnd = posToCursor(pos);
359     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
360     chatLine()->update();
361   }
362 }
363
364 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
365   if(event->buttons() == Qt::LeftButton) {
366     if(boundingRect().contains(event->pos())) {
367       qint16 end = posToCursor(event->pos());
368       if(end != _selectionEnd) {
369         _selectionEnd = end;
370         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
371         chatLine()->update();
372       }
373     } else {
374       setFullSelection();
375       chatScene()->startGlobalSelection(this, event->pos());
376     }
377     event->accept();
378   } else {
379     event->ignore();
380   }
381 }
382
383 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
384   if(event->buttons() == Qt::LeftButton)
385     event->accept();
386   else
387     event->ignore();
388 }
389
390 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
391   if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
392     chatScene()->selectionToClipboard(QClipboard::Selection);
393     event->accept();
394   } else
395     event->ignore();
396 }
397
398 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
399   Q_UNUSED(pos);
400
401   GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
402 }
403
404 // ************************************************************
405 // SenderChatItem
406 // ************************************************************
407
408 void SenderChatItem::initLayout(QTextLayout *layout) const {
409   initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
410   doLayout(layout);
411 }
412
413 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
414   Q_UNUSED(option); Q_UNUSED(widget);
415   painter->save();
416   painter->setClipRect(boundingRect());
417   paintBackground(painter);
418
419   qreal layoutWidth = layout()->minimumWidth();
420   qreal offset = 0;
421   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
422     offset = qMin(width() - layoutWidth, (qreal)0);
423   else
424     offset = qMax(layoutWidth - width(), (qreal)0);
425
426   if(layoutWidth > width()) {
427     // Draw a nice gradient for longer items
428     // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
429     QPixmap pixmap(layout()->boundingRect().toRect().size());
430     pixmap.fill(Qt::transparent);
431     QPainter pixPainter(&pixmap);
432     layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), additionalFormats());
433     pixPainter.end();
434
435     // Create alpha channel mask
436     QPixmap mask(pixmap.size());
437     QPainter maskPainter(&mask);
438     QLinearGradient gradient;
439     if(offset < 0) {
440       gradient.setStart(0, 0);
441       gradient.setFinalStop(12, 0);
442       gradient.setColorAt(0, Qt::black);
443       gradient.setColorAt(1, Qt::white);
444     } else {
445       gradient.setStart(width()-10, 0);
446       gradient.setFinalStop(width(), 0);
447       gradient.setColorAt(0, Qt::white);
448       gradient.setColorAt(1, Qt::black);
449     }
450     maskPainter.fillRect(0, 0, pixmap.width(), pixmap.height(), gradient);
451     pixmap.setAlphaChannel(mask);
452     painter->drawPixmap(pos(), pixmap);
453   } else {
454     layout()->draw(painter, pos(), additionalFormats(), boundingRect());
455   }
456   painter->restore();
457 }
458
459 void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
460   if(clickMode == ChatScene::DoubleClick) {
461     BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
462     QString nick = data(MessageModel::EditRole).toString();
463     // check if the nick is a valid ircUser
464     if(!nick.isEmpty() && Client::network(curBufInfo.networkId())->ircUser(nick))
465       Client::bufferModel()->switchToOrStartQuery(curBufInfo.networkId(), nick);
466   }
467   else
468     ChatItem::handleClick(pos, clickMode);
469 }
470
471 // ************************************************************
472 // ContentsChatItem
473 // ************************************************************
474
475 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
476
477 ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
478   : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
479     _data(0)
480 {
481   setPos(pos);
482   setGeometryByWidth(width);
483 }
484
485 QFontMetricsF *ContentsChatItem::fontMetrics() const {
486   return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
487 }
488
489 ContentsChatItem::~ContentsChatItem() {
490   delete _data;
491 }
492
493 void ContentsChatItem::clearCache() {
494   delete _data;
495   _data = 0;
496   ChatItem::clearCache();
497 }
498
499 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
500   if(!_data) {
501     ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
502     that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
503   }
504   return _data;
505 }
506
507 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
508   // We use this for reloading layout info as well, so we can't bail out if the width doesn't change
509
510   // compute height
511   int lines = 1;
512   WrapColumnFinder finder(this);
513   while(finder.nextWrapColumn(w) > 0)
514     lines++;
515   qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height());  // cope with negative leading()
516   qreal h = lines * spacing;
517   delete _data;
518   _data = 0;
519
520   if(w != width() || h != height())
521     setGeometry(w, h);
522
523   return h;
524 }
525
526 void ContentsChatItem::initLayout(QTextLayout *layout) const {
527   initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
528   doLayout(layout);
529 }
530
531 void ContentsChatItem::doLayout(QTextLayout *layout) const {
532   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
533   if(!wrapList.count()) return; // empty chatitem
534
535   qreal h = 0;
536   qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height());  // cope with negative leading()
537   WrapColumnFinder finder(this);
538   layout->beginLayout();
539   forever {
540     QTextLine line = layout->createLine();
541     if(!line.isValid())
542       break;
543
544     int col = finder.nextWrapColumn(width());
545     if(col < 0)
546       col = layout->text().length();
547     int num = col - line.textStart();
548
549     line.setNumColumns(num);
550
551     // Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
552     // We verify this and try setting the width again, making it shorter each time until the lengths match.
553     // Dead fugly, but seems to work…
554     for(int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
555       line.setNumColumns(i);
556     }
557     if(num != line.textLength()) {
558       qWarning() << "WARNING: Layout engine couldn't workaround Qt bug 238249, please report!";
559       // qDebug() << num << line.textLength() << t.mid(line.textStart(), line.textLength()) << t.mid(line.textStart() + line.textLength());
560     }
561
562     line.setPosition(QPointF(0, h));
563     h += spacing;
564   }
565   layout->endLayout();
566 }
567
568 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
569   return privateData()->clickables.atCursorPos(posToCursor(pos));
570 }
571
572 UiStyle::FormatList ContentsChatItem::formatList() const {
573   UiStyle::FormatList fmtList = ChatItem::formatList();
574   for(int i = 0; i < privateData()->clickables.count(); i++) {
575     Clickable click = privateData()->clickables.at(i);
576     if(click.type() == Clickable::Url) {
577       overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
578     }
579   }
580   return fmtList;
581 }
582
583 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
584   QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
585   // mark a clickable if hovered upon
586   if(privateData()->currentClickable.isValid()) {
587     Clickable click = privateData()->currentClickable;
588     QTextLayout::FormatRange f;
589     f.start = click.start();
590     f.length = click.length();
591     f.format.setFontUnderline(true);
592     fmt.append(f);
593   }
594   return fmt;
595 }
596
597 void ContentsChatItem::endHoverMode() {
598   if(privateData()) {
599     if(privateData()->currentClickable.isValid()) {
600       chatLine()->unsetCursor();
601       privateData()->currentClickable = Clickable();
602     }
603     clearWebPreview();
604     chatLine()->update();
605   }
606 }
607
608 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
609   if(clickMode == ChatScene::SingleClick) {
610     qint16 idx = posToCursor(pos);
611     Clickable foo = privateData()->clickables.atCursorPos(idx);
612     if(foo.isValid()) {
613       NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
614       QString text = data(ChatLineModel::DisplayRole).toString();
615       foo.activate(networkId, text);
616     }
617   } else if(clickMode == ChatScene::DoubleClick) {
618     chatScene()->setSelectingItem(this);
619     setSelectionMode(PartialSelection);
620     Clickable click = clickableAt(pos);
621     if(click.isValid()) {
622       setSelectionStart(click.start());
623       setSelectionEnd(click.start() + click.length());
624     } else {
625       // find word boundary
626       QString str = data(ChatLineModel::DisplayRole).toString();
627       qint16 cursor = posToCursor(pos);
628       qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
629       qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
630       if(end < 0) end = str.length();
631       setSelectionStart(start);
632       setSelectionEnd(end);
633     }
634     chatLine()->update();
635   } else if(clickMode == ChatScene::TripleClick) {
636     setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
637   }
638   ChatItem::handleClick(pos, clickMode);
639 }
640
641 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
642   // mouse move events always mean we're not hovering anymore...
643   endHoverMode();
644   ChatItem::mouseMoveEvent(event);
645 }
646
647 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
648   endHoverMode();
649   event->accept();
650 }
651
652 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
653   bool onClickable = false;
654   Clickable click = clickableAt(event->pos());
655   if(click.isValid()) {
656     if(click.type() == Clickable::Url) {
657       onClickable = true;
658       showWebPreview(click);
659     } else if(click.type() == Clickable::Channel) {
660       QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
661       // don't make clickable if it's our own name
662       BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
663       if(Client::networkModel()->bufferName(myId) != name)
664         onClickable = true;
665     }
666     if(onClickable) {
667       chatLine()->setCursor(Qt::PointingHandCursor);
668       privateData()->currentClickable = click;
669       chatLine()->update();
670       return;
671     }
672   }
673   if(!onClickable) endHoverMode();
674   event->accept();
675 }
676
677 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
678   if(privateData()->currentClickable.isValid()) {
679     Clickable click = privateData()->currentClickable;
680     switch(click.type()) {
681       case Clickable::Url:
682         privateData()->activeClickable = click;
683         menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
684                          &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
685         break;
686       case Clickable::Channel: {
687         // Hide existing menu actions, they confuse us when right-clicking on a clickable
688         foreach(QAction *action, menu->actions())
689           action->setVisible(false);
690         QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
691         GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
692         break;
693       }
694       default:
695         break;
696     }
697   } else {
698     // Buffer-specific actions
699     ChatItem::addActionsToMenu(menu, pos);
700   }
701 }
702
703 void ContentsChatItem::copyLinkToClipboard() {
704   Clickable click = privateData()->activeClickable;
705   if(click.isValid() && click.type() == Clickable::Url) {
706     QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
707     if(!url.contains("://"))
708       url = "http://" + url;
709     chatScene()->stringToClipboard(url);
710   }
711 }
712
713 /******** WEB PREVIEW *****************************************************************************/
714
715 void ContentsChatItem::showWebPreview(const Clickable &click) {
716 #ifndef HAVE_WEBKIT
717   Q_UNUSED(click);
718 #else
719   QTextLine line = layout()->lineForTextPosition(click.start());
720   qreal x = line.cursorToX(click.start());
721   qreal width = line.cursorToX(click.start() + click.length()) - x;
722   qreal height = line.height();
723   qreal y = height * line.lineNumber();
724
725   QPointF topLeft = mapToScene(pos()) + QPointF(x, y);
726   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
727
728   QString urlstr = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
729   if(!urlstr.contains("://"))
730     urlstr= "http://" + urlstr;
731   QUrl url = QUrl::fromEncoded(urlstr.toUtf8(), QUrl::TolerantMode);
732   chatScene()->loadWebPreview(this, url, urlRect);
733 #endif
734 }
735
736 void ContentsChatItem::clearWebPreview() {
737 #ifdef HAVE_WEBKIT
738   chatScene()->clearWebPreview(this);
739 #endif
740 }
741
742 /*************************************************************************************************/
743
744 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
745   : item(_item),
746     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
747     wordidx(0),
748     lineCount(0),
749     choppedTrailing(0)
750 {
751 }
752
753 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
754 }
755
756 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
757   if(wordidx >= wrapList.count())
758     return -1;
759
760   lineCount++;
761   qreal targetWidth = lineCount * width + choppedTrailing;
762
763   qint16 start = wordidx;
764   qint16 end = wrapList.count() - 1;
765
766   // check if the whole line fits
767   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
768     return -1;
769
770   // check if we have a very long word that needs inter word wrap
771   if(wrapList.at(start).endX > targetWidth) {
772     if(!line.isValid()) {
773       item->initLayoutHelper(&layout, QTextOption::NoWrap);
774       layout.beginLayout();
775       line = layout.createLine();
776       layout.endLayout();
777     }
778     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
779   }
780
781   while(true) {
782     if(start + 1 == end) {
783       wordidx = end;
784       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
785
786       // both cases should be cought preliminary
787       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
788       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
789
790       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
791       return wrapList.at(wordidx).start;
792     }
793
794     qint16 pivot = (end + start) / 2;
795     if(wrapList.at(pivot).endX > targetWidth) {
796       end = pivot;
797     } else {
798       start = pivot;
799     }
800   }
801   Q_ASSERT(false);
802   return -1;
803 }
804
805 /*************************************************************************************************/
806