9e7e1eb687f41cf14d2e2e0fd1702b659bd99130
[quassel.git] / src / qtui / chatitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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
32 #include "chatitem.h"
33 #include "chatlinemodel.h"
34 #include "qtui.h"
35 #include "qtuistyle.h"
36
37 ChatItem::ChatItem(const qreal &width, const qreal &height, const QPointF &pos, QGraphicsItem *parent)
38   : QGraphicsItem(parent),
39     _data(0),
40     _boundingRect(0, 0, width, height),
41     _selectionMode(NoSelection),
42     _selectionStart(-1)
43 {
44   setAcceptHoverEvents(true);
45   setZValue(20);
46   setPos(pos);
47 }
48
49 ChatItem::~ChatItem() {
50   delete _data;
51 }
52
53 QVariant ChatItem::data(int role) const {
54   QModelIndex index = model()->index(row(), column());
55   if(!index.isValid()) {
56     qWarning() << "ChatItem::data(): model index is invalid!" << index;
57     return QVariant();
58   }
59   return model()->data(index, role);
60 }
61
62 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const {
63   QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
64
65   QTextOption option;
66   option.setWrapMode(wrapMode);
67   option.setAlignment(alignment);
68   layout->setTextOption(option);
69
70   QList<QTextLayout::FormatRange> formatRanges
71          = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
72   layout->setAdditionalFormats(formatRanges);
73   return layout;
74 }
75
76 void ChatItem::doLayout() {
77   QTextLayout *layout_ = layout();
78   layout_->beginLayout();
79   QTextLine line = layout_->createLine();
80   if(line.isValid()) {
81     line.setLineWidth(width());
82     line.setPosition(QPointF(0,0));
83   }
84   layout_->endLayout();
85 }
86
87 void ChatItem::clearLayout() {
88   delete _data;
89   _data = 0;
90 }
91
92 ChatItemPrivate *ChatItem::privateData() const {
93   if(!_data) {
94     ChatItem *that = const_cast<ChatItem *>(this);
95     that->_data = that->newPrivateData();
96     that->doLayout();
97   }
98   return _data;
99 }
100
101 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
102 //       This is a deliberate trade-off. (-> selectFmt creation, data() call)
103 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
104   Q_UNUSED(option); Q_UNUSED(widget);
105   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
106   QVector<QTextLayout::FormatRange> formats = additionalFormats();
107   QTextLayout::FormatRange selectFmt = selectionFormat();
108   if(selectFmt.format.isValid()) formats.append(selectFmt);
109   layout()->draw(painter, QPointF(0,0), formats, boundingRect());
110
111   // Debuging Stuff
112   // uncomment partially or all of the following stuff:
113   //
114   // 0) alternativ painter color for debug stuff
115 //   if(row() % 2)
116 //     painter->setPen(Qt::red);
117 //   else
118 //     painter->setPen(Qt::blue);
119   // 1) draw wordwrap points in the first line
120 //   if(column() == 2) {
121 //     ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
122 //     foreach(ChatLineModel::Word word, wrapList) {
123 //       if(word.endX > width())
124 //      break;
125 //       painter->drawLine(word.endX, 0, word.endX, height());
126 //     }
127 //   }
128   // 2) draw MsgId over the time column
129 //   if(column() == 0) {
130 //     QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toInt());
131 //     QPointF bottomPoint = boundingRect().bottomLeft();
132 //     bottomPoint.ry() -= 2;
133 //     painter->drawText(bottomPoint, msgIdString);
134 //   }
135   // 3) draw bounding rect
136 //   painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
137 }
138
139 qint16 ChatItem::posToCursor(const QPointF &pos) const {
140   if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
141   if(pos.y() < 0) return 0;
142   for(int l = layout()->lineCount() - 1; l >= 0; l--) {
143     QTextLine line = layout()->lineAt(l);
144     if(pos.y() >= line.y()) {
145       return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
146     }
147   }
148   return 0;
149 }
150
151 bool ChatItem::hasSelection() const {
152   if(_selectionMode == NoSelection)
153     return false;
154   if(_selectionMode == FullSelection)
155     return true;
156   // partial
157   return _selectionStart != _selectionEnd;
158 }
159
160 QString ChatItem::selection() const {
161   if(_selectionMode == FullSelection)
162     return data(MessageModel::DisplayRole).toString();
163   if(_selectionMode == PartialSelection)
164     return data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
165   return QString();
166 }
167
168 void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end) {
169   _selectionMode = mode;
170   _selectionStart = start;
171   _selectionEnd = end;
172   update();
173 }
174
175 void ChatItem::setFullSelection() {
176   if(_selectionMode != FullSelection) {
177     _selectionMode = FullSelection;
178     update();
179   }
180 }
181
182 void ChatItem::clearSelection() {
183   if(_selectionMode != NoSelection) {
184     _selectionMode = NoSelection;
185     update();
186   }
187 }
188
189 void ChatItem::continueSelecting(const QPointF &pos) {
190   _selectionMode = PartialSelection;
191   _selectionEnd = posToCursor(pos);
192   update();
193 }
194
195 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
196   if(_selectionMode == FullSelection)
197     return true;
198   if(_selectionMode == PartialSelection) {
199     int cursor = posToCursor(pos);
200     return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
201   }
202   return false;
203 }
204
205 QTextLayout::FormatRange ChatItem::selectionFormat() const {
206   QTextLayout::FormatRange selectFmt;
207   if(_selectionMode != NoSelection) {
208     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
209     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
210     if(_selectionMode == PartialSelection) {
211       selectFmt.start = qMin(_selectionStart, _selectionEnd);
212       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
213     } else { // FullSelection
214       selectFmt.start = 0;
215       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
216     }
217   } else {
218     selectFmt.start = -1;
219     selectFmt.length = 0;
220   }
221   return selectFmt;
222 }
223
224 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
225   QList<QRectF> resultList;
226   const QAbstractItemModel *model_ = model();
227   if(!model_)
228     return resultList;
229
230   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
231   QList<int> indexList;
232   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
233   while(searchIdx != -1) {
234     indexList << searchIdx;
235     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
236   }
237
238   bool hadPrivateData = hasPrivateData();
239
240   foreach(int idx, indexList) {
241     QTextLine line = layout()->lineForTextPosition(idx);
242     qreal x = line.cursorToX(idx);
243     qreal width = line.cursorToX(idx + searchWord.count()) - x;
244     qreal height = line.height();
245     qreal y = height * line.lineNumber();
246     resultList << QRectF(x, y, width, height);
247   }
248
249   if(!hadPrivateData)
250     clearLayout();
251   return resultList;
252 }
253
254 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
255   // single clicks are already handled by the scene (for clearing the selection)
256   if(clickMode == ChatScene::DragStartClick) {
257     chatScene()->setSelectingItem(this);
258     _selectionStart = _selectionEnd = posToCursor(pos);
259     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
260     update();
261   }
262 }
263
264 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
265   if(event->buttons() == Qt::LeftButton) {
266     if(contains(event->pos())) {
267       qint16 end = posToCursor(event->pos());
268       if(end != _selectionEnd) {
269         _selectionEnd = end;
270         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
271         update();
272       }
273     } else {
274       setFullSelection();
275       chatScene()->startGlobalSelection(this, event->pos());
276     }
277     event->accept();
278   } else {
279     event->ignore();
280   }
281 }
282
283 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
284   if(event->buttons() == Qt::LeftButton)
285     event->accept();
286   else
287     event->ignore();
288 }
289
290 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
291   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
292     chatScene()->selectionToClipboard(QClipboard::Selection);
293     event->accept();
294   } else
295     event->ignore();
296 }
297
298 // ************************************************************
299 // SenderChatItem
300 // ************************************************************
301
302 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
303   Q_UNUSED(option); Q_UNUSED(widget);
304
305   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
306   qreal layoutWidth = layout()->minimumWidth();
307   qreal offset = 0;
308   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
309     offset = qMin(width() - layoutWidth, (qreal)0);
310   else
311     offset = qMax(layoutWidth - width(), (qreal)0);
312
313   QTextLayout::FormatRange selectFmt = selectionFormat();
314
315   if(layoutWidth > width()) {
316     // Draw a nice gradient for longer items
317     // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
318     QPixmap pixmap(layout()->boundingRect().toRect().size());
319     pixmap.fill(Qt::transparent);
320     QPainter pixPainter(&pixmap);
321     layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
322     pixPainter.end();
323
324     // Create alpha channel mask
325     QPixmap mask(pixmap.size());
326     QPainter maskPainter(&mask);
327     QLinearGradient gradient;
328     if(offset < 0) {
329       gradient.setStart(0, 0);
330       gradient.setFinalStop(12, 0);
331       gradient.setColorAt(0, Qt::black);
332       gradient.setColorAt(1, Qt::white);
333     } else {
334       gradient.setStart(width()-10, 0);
335       gradient.setFinalStop(width(), 0);
336       gradient.setColorAt(0, Qt::white);
337       gradient.setColorAt(1, Qt::black);
338     }
339     maskPainter.fillRect(boundingRect(), gradient);
340     pixmap.setAlphaChannel(mask);
341     painter->drawPixmap(0, 0, pixmap);
342   } else {
343     layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
344   }
345 }
346
347 // ************************************************************
348 // ContentsChatItem
349 // ************************************************************
350 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
351   : ChatItem(0, 0, pos, parent)
352 {
353   const QAbstractItemModel *model_ = model();
354   QModelIndex index = model_->index(row(), column());
355   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
356
357   setGeometryByWidth(width);
358 }
359
360 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
361   if(w != width()) {
362     prepareGeometryChange();
363     setWidth(w);
364     // compute height
365     int lines = 1;
366     WrapColumnFinder finder(this);
367     while(finder.nextWrapColumn() > 0)
368       lines++;
369     setHeight(lines * fontMetrics()->lineSpacing());
370   }
371   return height();
372 }
373
374 void ContentsChatItem::doLayout() {
375   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
376   if(!wrapList.count()) return; // empty chatitem
377
378   qreal h = 0;
379   WrapColumnFinder finder(this);
380   layout()->beginLayout();
381   forever {
382     QTextLine line = layout()->createLine();
383     if(!line.isValid())
384       break;
385
386     int col = finder.nextWrapColumn();
387     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
388     line.setPosition(QPointF(0, h));
389     h += fontMetrics()->lineSpacing();
390   }
391   layout()->endLayout();
392 }
393
394 // NOTE: This method is not threadsafe and not reentrant!
395 //       (RegExps are not constant while matching, and they are static here for efficiency)
396 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
397   // For matching URLs
398   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
399   static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
400
401   static QRegExp regExp[] = {
402     // URL
403     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
404     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
405
406     // Channel name
407     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
408     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
409
410     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
411   };
412
413   static const int regExpCount = 2;  // number of regexps in the array above
414
415   qint16 matches[] = { 0, 0, 0 };
416   qint16 matchEnd[] = { 0, 0, 0 };
417
418   QString str = data(ChatLineModel::DisplayRole).toString();
419
420   QList<Clickable> result;
421   qint16 idx = 0;
422   qint16 minidx;
423   int type = -1;
424
425   do {
426     type = -1;
427     minidx = str.length();
428     for(int i = 0; i < regExpCount; i++) {
429       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
430       if(idx >= matchEnd[i]) {
431         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
432         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
433       }
434       if(matches[i] >= 0 && matches[i] < minidx) {
435         minidx = matches[i];
436         type = i;
437       }
438     }
439     if(type >= 0) {
440       idx = matchEnd[type];
441       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
442         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
443       }
444       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
445     }
446   } while(type >= 0);
447
448   /* testing
449   if(!result.isEmpty()) qDebug() << str;
450   foreach(Clickable click, result) {
451     qDebug() << str.mid(click.start, click.length);
452   }
453   */
454   return result;
455 }
456
457 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
458   // mark a clickable if hovered upon
459   QVector<QTextLayout::FormatRange> fmt;
460   if(privateData()->currentClickable.isValid()) {
461     Clickable click = privateData()->currentClickable;
462     QTextLayout::FormatRange f;
463     f.start = click.start;
464     f.length = click.length;
465     f.format.setFontUnderline(true);
466     fmt.append(f);
467   }
468   return fmt;
469 }
470
471 void ContentsChatItem::endHoverMode() {
472   if(hasPrivateData()) {
473     if(privateData()->currentClickable.isValid()) {
474       setCursor(Qt::ArrowCursor);
475       privateData()->currentClickable = Clickable();
476     }
477     clearWebPreview();
478     update();
479   }
480 }
481
482 void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
483   if(clickMode == ChatScene::SingleClick) {
484     Clickable click = privateData()->currentClickable;
485     if(click.isValid()) {
486       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
487       switch(click.type) {
488         case Clickable::Url:
489           if(!str.contains("://"))
490             str = "http://" + str;
491           QDesktopServices::openUrl(QUrl::fromEncoded(str.toAscii()));
492           break;
493         case Clickable::Channel:
494           // TODO join or whatever...
495           break;
496         default:
497           break;
498       }
499     }
500   } else if(clickMode == ChatScene::DoubleClick) {
501     chatScene()->setSelectingItem(this);
502     setSelectionMode(PartialSelection);
503     Clickable click = privateData()->currentClickable;
504     if(click.isValid()) {
505       setSelectionStart(click.start);
506       setSelectionEnd(click.start + click.length);
507     } else {
508       // find word boundary
509       QString str = data(ChatLineModel::DisplayRole).toString();
510       qint16 cursor = posToCursor(pos);
511       qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
512       qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
513       if(end < 0) end = str.length();
514       setSelectionStart(start);
515       setSelectionEnd(end);
516     }
517     update();
518   } else if(clickMode == ChatScene::TripleClick) {
519     setSelection(PartialSelection, 0, data(ChatLineModel::DisplayRole).toString().length());
520   }
521   ChatItem::handleClick(pos, clickMode);
522 }
523
524 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
525   // mouse move events always mean we're not hovering anymore...
526   endHoverMode();
527   ChatItem::mouseMoveEvent(event);
528 }
529
530 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
531   endHoverMode();
532   event->accept();
533 }
534
535 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
536   bool onClickable = false;
537   qint16 idx = posToCursor(event->pos());
538   for(int i = 0; i < privateData()->clickables.count(); i++) {
539     Clickable click = privateData()->clickables.at(i);
540     if(idx >= click.start && idx < click.start + click.length) {
541       if(click.type == Clickable::Url) {
542         onClickable = true;
543         showWebPreview(click);
544       } else if(click.type == Clickable::Channel) {
545         // TODO: don't make clickable if it's our own name
546         // onClickable = true; //FIXME disabled for now
547       }
548       if(onClickable) {
549         setCursor(Qt::PointingHandCursor);
550         privateData()->currentClickable = click;
551         update();
552         break;
553       }
554     }
555   }
556   if(!onClickable) endHoverMode();
557   event->accept();
558 }
559
560 /*
561 void ContentsChatItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
562   qint16 idx = posToCursor(event->pos());
563   for(int i = 0; i < privateData()->clickables.count(); i++) {
564     Clickable click = privateData()->clickables.at(i);
565     if(idx >= click.start && idx < click.start + click.length) {
566       if(click.type == Clickable::Url) {
567         QMenu menu;
568         QAction *copyToClipboard = menu.addAction(QObject::tr("Copy to Clipboard"));
569         QAction *selected = menu.exec(event->screenPos());
570         if(selected == copyToClipboard) {
571           QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
572 #   ifdef Q_WS_X11
573           QApplication::clipboard()->setText(url, QClipboard::Selection);
574 #   endif
575 //# else
576           QApplication::clipboard()->setText(url);
577 //# endif
578         }
579       }
580     }
581   }
582 }
583 */
584
585 void ContentsChatItem::showWebPreview(const Clickable &click) {
586 #ifndef HAVE_WEBKIT
587   Q_UNUSED(click);
588 #else
589   QTextLine line = layout()->lineForTextPosition(click.start);
590   qreal x = line.cursorToX(click.start);
591   qreal width = line.cursorToX(click.start + click.length) - x;
592   qreal height = line.height();
593   qreal y = height * line.lineNumber();
594
595   QPointF topLeft = scenePos() + QPointF(x, y);
596   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
597
598   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
599   if(!url.contains("://"))
600     url = "http://" + url;
601   chatScene()->loadWebPreview(this, url, urlRect);
602 #endif
603 }
604
605 void ContentsChatItem::clearWebPreview() {
606 #ifdef HAVE_WEBKIT
607   chatScene()->clearWebPreview(this);
608 #endif
609 }
610
611 /*************************************************************************************************/
612
613 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
614   : item(_item),
615     layout(0),
616     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
617     wordidx(0),
618     lineCount(0),
619     choppedTrailing(0)
620 {
621 }
622
623 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
624   delete layout;
625 }
626
627 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
628   if(wordidx >= wrapList.count())
629     return -1;
630
631   lineCount++;
632   qreal targetWidth = lineCount * item->width() + choppedTrailing;
633
634   qint16 start = wordidx;
635   qint16 end = wrapList.count() - 1;
636
637   // check if the whole line fits
638   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
639     return -1;
640
641   // check if we have a very long word that needs inter word wrap
642   if(wrapList.at(start).endX > targetWidth) {
643     if(!line.isValid()) {
644       layout = item->createLayout(QTextOption::NoWrap);
645       layout->beginLayout();
646       line = layout->createLine();
647       layout->endLayout();
648     }
649     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
650   }
651
652   while(true) {
653     if(start + 1 == end) {
654       wordidx = end;
655       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
656
657       // both cases should be cought preliminary
658       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
659       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
660
661       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
662       return wrapList.at(wordidx).start;
663     }
664
665     qint16 pivot = (end + start) / 2;
666     if(wrapList.at(pivot).endX > targetWidth) {
667       end = pivot;
668     } else {
669       start = pivot;
670     }
671   }
672   Q_ASSERT(false);
673   return -1;
674 }
675