Introduce Clickable::activate() to put handling clicks in a single place
[quassel.git] / src / qtui / chatitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "chatlinemodel.h"
35 #include "contextmenuactionprovider.h"
36 #include "iconloader.h"
37 #include "mainwin.h"
38 #include "qtui.h"
39 #include "qtuistyle.h"
40
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),
45     _selectionStart(-1)
46 {
47   setAcceptHoverEvents(true);
48   setZValue(20);
49   setPos(pos);
50 }
51
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;
56     return QVariant();
57   }
58   return model()->data(index, role);
59 }
60
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;
64
65   QTextLayout layout;
66   initLayout(&layout);
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);
71     }
72   }
73   return 0;
74 }
75
76 void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
77   Q_ASSERT(layout);
78
79   layout->setText(data(MessageModel::DisplayRole).toString());
80
81   QTextOption option;
82   option.setWrapMode(wrapMode);
83   option.setAlignment(alignment);
84   layout->setTextOption(option);
85
86   QList<QTextLayout::FormatRange> formatRanges
87          = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).toUInt());
88   layout->setAdditionalFormats(formatRanges);
89 }
90
91 UiStyle::FormatList ChatItem::formatList() const {
92   return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
93 }
94
95 void ChatItem::doLayout(QTextLayout *layout) const {
96   layout->beginLayout();
97   QTextLine line = layout->createLine();
98   if(line.isValid()) {
99     line.setLineWidth(width());
100     line.setPosition(QPointF(0,0));
101   }
102   layout->endLayout();
103 }
104
105 void ChatItem::paintBackground(QPainter *painter) {
106   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
107
108   QVariant bgBrush;
109   if(_selectionMode == FullSelection)
110     bgBrush = data(ChatLineModel::SelectedBackgroundRole);
111   else
112     bgBrush = data(ChatLineModel::BackgroundRole);
113   if(bgBrush.isValid())
114     painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
115 }
116
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);
122
123   QTextLayout layout;
124   initLayout(&layout);
125   layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
126
127   //  layout()->draw(painter, QPointF(0,0), formats, boundingRect());
128
129   // Debuging Stuff
130   // uncomment partially or all of the following stuff:
131   //
132   // 0) alternativ painter color for debug stuff
133 //   if(row() % 2)
134 //     painter->setPen(Qt::red);
135 //   else
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())
142 //      break;
143 //       painter->drawLine(word.endX, 0, word.endX, height());
144 //     }
145 //   }
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);
152 //   }
153   // 3) draw bounding rect
154 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
155 }
156
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());
161
162     if(fmtEnd <= start)
163       continue;
164     if(fmtStart >= end)
165       break;
166
167     // split the format if necessary
168     if(fmtStart < start) {
169       fmtList.insert(i, fmtList.at(i));
170       fmtList[++i].first = start;
171     }
172     if(end < fmtEnd) {
173       fmtList.insert(i, fmtList.at(i));
174       fmtList[i+1].first = end;
175     }
176
177     fmtList[i].second |= overlayFmt;
178   }
179 }
180
181 QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const {
182   return selectionFormats();
183 }
184
185 QVector<QTextLayout::FormatRange> ChatItem::selectionFormats() const {
186   if(!hasSelection())
187     return QVector<QTextLayout::FormatRange>();
188
189   int start, end;
190   if(_selectionMode == FullSelection) {
191     start = 0;
192     end = data(MessageModel::DisplayRole).toString().length();
193   } else {
194     start = qMin(_selectionStart, _selectionEnd);
195     end = qMax(_selectionStart, _selectionEnd);
196   }
197
198   UiStyle::FormatList fmtList = formatList();
199
200   while(fmtList.count() > 1 && fmtList.at(1).first <= start)
201     fmtList.removeFirst();
202
203   fmtList.first().first = start;
204
205   while(fmtList.count() > 1 && fmtList.last().first >= end)
206     fmtList.removeLast();
207
208   return QtUi::style()->toTextLayoutList(fmtList, end, UiStyle::Selected|data(ChatLineModel::MsgLabelRole).toUInt()).toVector();
209 }
210
211 bool ChatItem::hasSelection() const {
212   if(_selectionMode == NoSelection)
213     return false;
214   if(_selectionMode == FullSelection)
215     return true;
216   // partial
217   return _selectionStart != _selectionEnd;
218 }
219
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));
225   return QString();
226 }
227
228 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
229   _selectionMode = mode;
230   _selectionStart = start;
231   _selectionEnd = end;
232   update();
233 }
234
235 void ChatItem::setFullSelection() {
236   if(_selectionMode != FullSelection) {
237     _selectionMode = FullSelection;
238     update();
239   }
240 }
241
242 void ChatItem::clearSelection() {
243   if(_selectionMode != NoSelection) {
244     _selectionMode = NoSelection;
245     update();
246   }
247 }
248
249 void ChatItem::continueSelecting(const QPointF &pos) {
250   _selectionMode = PartialSelection;
251   _selectionEnd = posToCursor(pos);
252   update();
253 }
254
255 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
256   if(_selectionMode == FullSelection)
257     return true;
258   if(_selectionMode == PartialSelection) {
259     int cursor = posToCursor(pos);
260     return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
261   }
262   return false;
263 }
264
265 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
266   QList<QRectF> resultList;
267   const QAbstractItemModel *model_ = model();
268   if(!model_)
269     return resultList;
270
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);
277   }
278
279   QTextLayout layout;
280   initLayout(&layout);
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);
288   }
289
290   return resultList;
291 }
292
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
299     update();
300   }
301 }
302
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) {
308         _selectionEnd = end;
309         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
310         update();
311       }
312     } else {
313       setFullSelection();
314       chatScene()->startGlobalSelection(this, event->pos());
315     }
316     event->accept();
317   } else {
318     event->ignore();
319   }
320 }
321
322 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
323   if(event->buttons() == Qt::LeftButton)
324     event->accept();
325   else
326     event->ignore();
327 }
328
329 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
330   if(_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
331     chatScene()->selectionToClipboard(QClipboard::Selection);
332     event->accept();
333   } else
334     event->ignore();
335 }
336
337 void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
338   Q_UNUSED(pos);
339
340   GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
341 }
342
343 // ************************************************************
344 // SenderChatItem
345 // ************************************************************
346
347 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
348   Q_UNUSED(option); Q_UNUSED(widget);
349   paintBackground(painter);
350
351   QTextLayout layout;
352   initLayout(&layout);
353   qreal layoutWidth = layout.minimumWidth();
354   qreal offset = 0;
355   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
356     offset = qMin(width() - layoutWidth, (qreal)0);
357   else
358     offset = qMax(layoutWidth - width(), (qreal)0);
359
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());
367     pixPainter.end();
368
369     // Create alpha channel mask
370     QPixmap mask(pixmap.size());
371     QPainter maskPainter(&mask);
372     QLinearGradient gradient;
373     if(offset < 0) {
374       gradient.setStart(0, 0);
375       gradient.setFinalStop(12, 0);
376       gradient.setColorAt(0, Qt::black);
377       gradient.setColorAt(1, Qt::white);
378     } else {
379       gradient.setStart(width()-10, 0);
380       gradient.setFinalStop(width(), 0);
381       gradient.setColorAt(0, Qt::white);
382       gradient.setColorAt(1, Qt::black);
383     }
384     maskPainter.fillRect(boundingRect(), gradient);
385     pixmap.setAlphaChannel(mask);
386     painter->drawPixmap(0, 0, pixmap);
387   } else {
388     layout.draw(painter, QPointF(0,0), additionalFormats(), boundingRect());
389   }
390 }
391
392 // ************************************************************
393 // ContentsChatItem
394 // ************************************************************
395
396 ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
397
398 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
399   : ChatItem(0, 0, pos, parent),
400     _data(0)
401 {
402   setGeometryByWidth(width);
403 }
404
405 QFontMetricsF *ContentsChatItem::fontMetrics() const {
406   return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second, 0);
407 }
408
409 ContentsChatItem::~ContentsChatItem() {
410   delete _data;
411 }
412
413 ContentsChatItemPrivate *ContentsChatItem::privateData() const {
414   if(!_data) {
415     ContentsChatItem *that = const_cast<ContentsChatItem *>(this);
416     that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
417   }
418   return _data;
419 }
420
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
423
424   // compute height
425   int lines = 1;
426   WrapColumnFinder finder(this);
427   while(finder.nextWrapColumn(w) > 0)
428     lines++;
429   qreal h = lines * fontMetrics()->lineSpacing();
430   delete _data;
431   _data = 0;
432
433   if(w != width() || h != height()) {
434     prepareGeometryChange();
435     setGeometry(w, h);
436   }
437   return h;
438 }
439
440 void ContentsChatItem::doLayout(QTextLayout *layout) const {
441   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
442   if(!wrapList.count()) return; // empty chatitem
443
444   qreal h = 0;
445   WrapColumnFinder finder(this);
446   layout->beginLayout();
447   forever {
448     QTextLine line = layout->createLine();
449     if(!line.isValid())
450       break;
451
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();
456   }
457   layout->endLayout();
458 }
459
460 Clickable ContentsChatItem::clickableAt(const QPointF &pos) const {
461   return privateData()->clickables.atCursorPos(posToCursor(pos));
462 }
463
464 UiStyle::FormatList ContentsChatItem::formatList() const {
465   UiStyle::FormatList fmtList = ChatItem::formatList();
466   for(int i = 0; i < privateData()->clickables.count(); i++) {
467     Clickable click = privateData()->clickables.at(i);
468     if(click.type() == Clickable::Url) {
469       overlayFormat(fmtList, click.start(), click.start() + click.length(), UiStyle::Url);
470     }
471   }
472   return fmtList;
473 }
474
475 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
476   QVector<QTextLayout::FormatRange> fmt = ChatItem::additionalFormats();
477   // mark a clickable if hovered upon
478   if(privateData()->currentClickable.isValid()) {
479     Clickable click = privateData()->currentClickable;
480     QTextLayout::FormatRange f;
481     f.start = click.start();
482     f.length = click.length();
483     f.format.setFontUnderline(true);
484     fmt.append(f);
485   }
486   return fmt;
487 }
488
489 void ContentsChatItem::endHoverMode() {
490   if(privateData()) {
491     if(privateData()->currentClickable.isValid()) {
492       setCursor(Qt::ArrowCursor);
493       privateData()->currentClickable = Clickable();
494     }
495     clearWebPreview();
496     update();
497   }
498 }
499
500 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
501   if(clickMode == ChatScene::SingleClick) {
502     qint16 idx = posToCursor(pos);
503     Clickable foo = privateData()->clickables.atCursorPos(idx);
504     if(foo.isValid()) {
505       NetworkId networkId = Client::networkModel()->networkId(data(MessageModel::BufferIdRole).value<BufferId>());
506       QString text = data(ChatLineModel::DisplayRole).toString();
507       foo.activate(networkId, text);
508     }
509   } else if(clickMode == ChatScene::DoubleClick) {
510     chatScene()->setSelectingItem(this);
511     setSelectionMode(PartialSelection);
512     Clickable click = clickableAt(pos);
513     if(click.isValid()) {
514       setSelectionStart(click.start());
515       setSelectionEnd(click.start() + click.length());
516     } else {
517       // find word boundary
518       QString str = data(ChatLineModel::DisplayRole).toString();
519       qint16 cursor = posToCursor(pos);
520       qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
521       qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
522       if(end < 0) end = str.length();
523       setSelectionStart(start);
524       setSelectionEnd(end);
525     }
526     update();
527   } else if(clickMode == ChatScene::TripleClick) {
528     setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
529   }
530   ChatItem::handleClick(pos, clickMode);
531 }
532
533 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
534   // mouse move events always mean we're not hovering anymore...
535   endHoverMode();
536   ChatItem::mouseMoveEvent(event);
537 }
538
539 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
540   endHoverMode();
541   event->accept();
542 }
543
544 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
545   bool onClickable = false;
546   Clickable click = clickableAt(event->pos());
547   if(click.isValid()) {
548     if(click.type() == Clickable::Url) {
549       onClickable = true;
550       showWebPreview(click);
551     } else if(click.type() == Clickable::Channel) {
552       QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
553       // don't make clickable if it's our own name
554       BufferId myId = data(MessageModel::BufferIdRole).value<BufferId>();
555       if(Client::networkModel()->bufferName(myId) != name)
556         onClickable = true;
557     }
558     if(onClickable) {
559       setCursor(Qt::PointingHandCursor);
560       privateData()->currentClickable = click;
561       update();
562       return;
563     }
564   }
565   if(!onClickable) endHoverMode();
566   event->accept();
567 }
568
569 void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos) {
570   if(privateData()->currentClickable.isValid()) {
571     Clickable click = privateData()->currentClickable;
572     switch(click.type()) {
573       case Clickable::Url:
574         privateData()->activeClickable = click;
575         menu->addAction(SmallIcon("edit-copy"), tr("Copy Link Address"),
576                          &_actionProxy, SLOT(copyLinkToClipboard()))->setData(QVariant::fromValue<void *>(this));
577         break;
578       case Clickable::Channel: {
579         // Hide existing menu actions, they confuse us when right-clicking on a clickable
580         foreach(QAction *action, menu->actions())
581           action->setVisible(false);
582         QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
583         GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
584         break;
585       }
586       default:
587         break;
588     }
589   } else {
590     // Buffer-specific actions
591     ChatItem::addActionsToMenu(menu, pos);
592   }
593 }
594
595 void ContentsChatItem::copyLinkToClipboard() {
596   Clickable click = privateData()->activeClickable;
597   if(click.isValid() && click.type() == Clickable::Url) {
598     QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
599     if(!url.contains("://"))
600       url = "http://" + url;
601     chatScene()->stringToClipboard(url);
602   }
603 }
604
605 /******** WEB PREVIEW *****************************************************************************/
606
607 void ContentsChatItem::showWebPreview(const Clickable &click) {
608 #ifndef HAVE_WEBKIT
609   Q_UNUSED(click);
610 #else
611   QTextLayout layout;
612   initLayout(&layout);
613   QTextLine line = layout.lineForTextPosition(click.start());
614   qreal x = line.cursorToX(click.start());
615   qreal width = line.cursorToX(click.start() + click.length()) - x;
616   qreal height = line.height();
617   qreal y = height * line.lineNumber();
618
619   QPointF topLeft = scenePos() + QPointF(x, y);
620   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
621
622   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
623   if(!url.contains("://"))
624     url = "http://" + url;
625   chatScene()->loadWebPreview(this, url, urlRect);
626 #endif
627 }
628
629 void ContentsChatItem::clearWebPreview() {
630 #ifdef HAVE_WEBKIT
631   chatScene()->clearWebPreview(this);
632 #endif
633 }
634
635 /*************************************************************************************************/
636
637 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
638   : item(_item),
639     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
640     wordidx(0),
641     lineCount(0),
642     choppedTrailing(0)
643 {
644 }
645
646 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
647 }
648
649 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width) {
650   if(wordidx >= wrapList.count())
651     return -1;
652
653   lineCount++;
654   qreal targetWidth = lineCount * width + choppedTrailing;
655
656   qint16 start = wordidx;
657   qint16 end = wrapList.count() - 1;
658
659   // check if the whole line fits
660   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
661     return -1;
662
663   // check if we have a very long word that needs inter word wrap
664   if(wrapList.at(start).endX > targetWidth) {
665     if(!line.isValid()) {
666       item->initLayoutHelper(&layout, QTextOption::NoWrap);
667       layout.beginLayout();
668       line = layout.createLine();
669       layout.endLayout();
670     }
671     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
672   }
673
674   while(true) {
675     if(start + 1 == end) {
676       wordidx = end;
677       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
678
679       // both cases should be cought preliminary
680       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
681       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
682
683       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
684       return wrapList.at(wordidx).start;
685     }
686
687     qint16 pivot = (end + start) / 2;
688     if(wrapList.at(pivot).endX > targetWidth) {
689       end = pivot;
690     } else {
691       start = pivot;
692     }
693   }
694   Q_ASSERT(false);
695   return -1;
696 }
697
698 /*************************************************************************************************/
699