0900c7e2168caed9997bc98a4a492ff910be4fba
[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::setFullSelection() {
169   if(_selectionMode != FullSelection) {
170     _selectionMode = FullSelection;
171     update();
172   }
173 }
174
175 void ChatItem::clearSelection() {
176   _selectionMode = NoSelection;
177   update();
178 }
179
180 void ChatItem::continueSelecting(const QPointF &pos) {
181   _selectionMode = PartialSelection;
182   _selectionEnd = posToCursor(pos);
183   update();
184 }
185
186 bool ChatItem::isPosOverSelection(const QPointF &pos) const {
187   if(_selectionMode == FullSelection)
188     return true;
189   if(_selectionMode == PartialSelection) {
190     int cursor = posToCursor(pos); qDebug() << cursor << _selectionStart << _selectionEnd;
191     return cursor >= qMin(_selectionStart, _selectionEnd) && cursor <= qMax(_selectionStart, _selectionEnd);
192   }
193   return false;
194 }
195
196 QTextLayout::FormatRange ChatItem::selectionFormat() const {
197   QTextLayout::FormatRange selectFmt;
198   if(_selectionMode != NoSelection) {
199     selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
200     selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
201     if(_selectionMode == PartialSelection) {
202       selectFmt.start = qMin(_selectionStart, _selectionEnd);
203       selectFmt.length = qAbs(_selectionStart - _selectionEnd);
204     } else { // FullSelection
205       selectFmt.start = 0;
206       selectFmt.length = data(MessageModel::DisplayRole).toString().length();
207     }
208   } else {
209     selectFmt.start = -1;
210     selectFmt.length = 0;
211   }
212   return selectFmt;
213 }
214
215 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
216   QList<QRectF> resultList;
217   const QAbstractItemModel *model_ = model();
218   if(!model_)
219     return resultList;
220
221   QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
222   QList<int> indexList;
223   int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
224   while(searchIdx != -1) {
225     indexList << searchIdx;
226     searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
227   }
228
229   bool hadPrivateData = hasPrivateData();
230
231   foreach(int idx, indexList) {
232     QTextLine line = layout()->lineForTextPosition(idx);
233     qreal x = line.cursorToX(idx);
234     qreal width = line.cursorToX(idx + searchWord.count()) - x;
235     qreal height = line.height();
236     qreal y = height * line.lineNumber();
237     resultList << QRectF(x, y, width, height);
238   }
239
240   if(!hadPrivateData)
241     clearLayout();
242   return resultList;
243 }
244
245 void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) {
246   if(clickMode == ChatScene::SingleClick) {
247     chatScene()->setSelectingItem(this);
248     _selectionStart = _selectionEnd = posToCursor(pos);
249     _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
250     update();
251   }
252 }
253
254 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
255   if(event->buttons() == Qt::LeftButton) {
256     if(contains(event->pos())) {
257       qint16 end = posToCursor(event->pos());
258       if(end != _selectionEnd) {
259         _selectionEnd = end;
260         _selectionMode = (_selectionStart != _selectionEnd ? PartialSelection : NoSelection);
261         update();
262       }
263     } else {
264       setFullSelection();
265       chatScene()->startGlobalSelection(this, event->pos());
266     }
267     event->accept();
268   } else {
269     event->ignore();
270   }
271 }
272
273 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
274   if(event->buttons() == Qt::LeftButton) {
275     event->accept();
276   } else {
277     event->ignore();
278   }
279 }
280
281 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
282   if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
283     _selectionEnd = posToCursor(event->pos());
284     QString selection
285         = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
286     chatScene()->putToClipboard(selection);
287     event->accept();
288   } else {
289     event->ignore();
290   }
291 }
292
293 // ************************************************************
294 // SenderChatItem
295 // ************************************************************
296
297 void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
298   Q_UNUSED(option); Q_UNUSED(widget);
299
300   painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
301   qreal layoutWidth = layout()->minimumWidth();
302   qreal offset = 0;
303   if(chatScene()->senderCutoffMode() == ChatScene::CutoffLeft)
304     offset = qMin(width() - layoutWidth, (qreal)0);
305   else
306     offset = qMax(layoutWidth - width(), (qreal)0);
307
308   QTextLayout::FormatRange selectFmt = selectionFormat();
309
310   if(layoutWidth > width()) {
311     // Draw a nice gradient for longer items
312     // Qt's text drawing with a gradient brush sucks, so we use an alpha-channeled pixmap instead
313     QPixmap pixmap(layout()->boundingRect().toRect().size());
314     pixmap.fill(Qt::transparent);
315     QPainter pixPainter(&pixmap);
316     layout()->draw(&pixPainter, QPointF(qMax(offset, (qreal)0), 0), QVector<QTextLayout::FormatRange>() << selectFmt);
317     pixPainter.end();
318
319     // Create alpha channel mask
320     QPixmap mask(pixmap.size());
321     QPainter maskPainter(&mask);
322     QLinearGradient gradient;
323     if(offset < 0) {
324       gradient.setStart(0, 0);
325       gradient.setFinalStop(12, 0);
326       gradient.setColorAt(0, Qt::black);
327       gradient.setColorAt(1, Qt::white);
328     } else {
329       gradient.setStart(width()-10, 0);
330       gradient.setFinalStop(width(), 0);
331       gradient.setColorAt(0, Qt::white);
332       gradient.setColorAt(1, Qt::black);
333     }
334     maskPainter.fillRect(boundingRect(), gradient);
335     pixmap.setAlphaChannel(mask);
336     painter->drawPixmap(0, 0, pixmap);
337   } else {
338     layout()->draw(painter, QPointF(0,0), QVector<QTextLayout::FormatRange>() << selectFmt, boundingRect());
339   }
340 }
341
342 // ************************************************************
343 // ContentsChatItem
344 // ************************************************************
345 ContentsChatItem::ContentsChatItem(const qreal &width, const QPointF &pos, QGraphicsItem *parent)
346   : ChatItem(0, 0, pos, parent)
347 {
348   const QAbstractItemModel *model_ = model();
349   QModelIndex index = model_->index(row(), column());
350   _fontMetrics = QtUi::style()->fontMetrics(model_->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
351
352   setGeometryByWidth(width);
353 }
354
355 qreal ContentsChatItem::setGeometryByWidth(qreal w) {
356   if(w != width()) {
357     prepareGeometryChange();
358     setWidth(w);
359     // compute height
360     int lines = 1;
361     WrapColumnFinder finder(this);
362     while(finder.nextWrapColumn() > 0)
363       lines++;
364     setHeight(lines * fontMetrics()->lineSpacing());
365   }
366   return height();
367 }
368
369 void ContentsChatItem::doLayout() {
370   ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
371   if(!wrapList.count()) return; // empty chatitem
372
373   qreal h = 0;
374   WrapColumnFinder finder(this);
375   layout()->beginLayout();
376   forever {
377     QTextLine line = layout()->createLine();
378     if(!line.isValid())
379       break;
380
381     int col = finder.nextWrapColumn();
382     line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
383     line.setPosition(QPointF(0, h));
384     h += fontMetrics()->lineSpacing();
385   }
386   layout()->endLayout();
387 }
388
389 // NOTE: This method is not threadsafe and not reentrant!
390 //       (RegExps are not constant while matching, and they are static here for efficiency)
391 QList<ContentsChatItem::Clickable> ContentsChatItem::findClickables() const {
392   // For matching URLs
393   static QString urlEnd("(?:>|[,.;:\"]*\\s|\\b|$)");
394   static QString urlChars("(?:[,.;:]*[\\w\\-~@/?&=+$()!%#*|{}\\[\\]])");
395
396   static QRegExp regExp[] = {
397     // URL
398     // QRegExp(QString("((?:https?://|s?ftp://|irc://|mailto:|www\\.)%1+|%1+\\.[a-z]{2,4}(?:?=/%1+|\\b))%2").arg(urlChars, urlEnd)),
399     QRegExp(QString("((?:(?:https?://|s?ftp://|irc://|mailto:)|www)%1+)%2").arg(urlChars, urlEnd), Qt::CaseInsensitive),
400
401     // Channel name
402     // We don't match for channel names starting with + or &, because that gives us a lot of false positives.
403     QRegExp("((?:#|![A-Z0-9]{5})[^,:\\s]+(?::[^,:\\s]+)?)\\b", Qt::CaseInsensitive)
404
405     // TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
406   };
407
408   static const int regExpCount = 2;  // number of regexps in the array above
409
410   qint16 matches[] = { 0, 0, 0 };
411   qint16 matchEnd[] = { 0, 0, 0 };
412
413   QString str = data(ChatLineModel::DisplayRole).toString();
414
415   QList<Clickable> result;
416   qint16 idx = 0;
417   qint16 minidx;
418   int type = -1;
419
420   do {
421     type = -1;
422     minidx = str.length();
423     for(int i = 0; i < regExpCount; i++) {
424       if(matches[i] < 0 || matchEnd[i] > str.length()) continue;
425       if(idx >= matchEnd[i]) {
426         matches[i] = str.indexOf(regExp[i], qMax(matchEnd[i], idx));
427         if(matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
428       }
429       if(matches[i] >= 0 && matches[i] < minidx) {
430         minidx = matches[i];
431         type = i;
432       }
433     }
434     if(type >= 0) {
435       idx = matchEnd[type];
436       if(type == Clickable::Url && str.at(idx-1) == ')') {  // special case: closing paren only matches if we had an open one
437         if(!str.mid(matches[type], matchEnd[type]-matches[type]).contains('(')) matchEnd[type]--;
438       }
439       result.append(Clickable((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]));
440     }
441   } while(type >= 0);
442
443   /* testing
444   if(!result.isEmpty()) qDebug() << str;
445   foreach(Clickable click, result) {
446     qDebug() << str.mid(click.start, click.length);
447   }
448   */
449   return result;
450 }
451
452 QVector<QTextLayout::FormatRange> ContentsChatItem::additionalFormats() const {
453   // mark a clickable if hovered upon
454   QVector<QTextLayout::FormatRange> fmt;
455   if(privateData()->currentClickable.isValid()) {
456     Clickable click = privateData()->currentClickable;
457     QTextLayout::FormatRange f;
458     f.start = click.start;
459     f.length = click.length;
460     f.format.setFontUnderline(true);
461     fmt.append(f);
462   }
463   return fmt;
464 }
465
466 void ContentsChatItem::endHoverMode() {
467   if(hasPrivateData()) {
468     if(privateData()->currentClickable.isValid()) {
469       setCursor(Qt::ArrowCursor);
470       privateData()->currentClickable = Clickable();
471     }
472     clearWebPreview();
473     update();
474   }
475 }
476
477 void ContentsChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
478   privateData()->hasDragged = false;
479   ChatItem::mousePressEvent(event);
480 }
481
482 void ContentsChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
483   if(!event->buttons() && !privateData()->hasDragged) {
484     // got a click
485     Clickable click = privateData()->currentClickable;
486     if(click.isValid()) {
487       QString str = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
488       switch(click.type) {
489         case Clickable::Url:
490           if(!str.contains("://"))
491             str = "http://" + str;
492           QDesktopServices::openUrl(QUrl::fromEncoded(str.toAscii()));
493           break;
494         case Clickable::Channel:
495           // TODO join or whatever...
496           break;
497         default:
498           break;
499       }
500     }
501   }
502   ChatItem::mouseReleaseEvent(event);
503 }
504
505 void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
506   // mouse move events always mean we're not hovering anymore...
507   endHoverMode();
508   // also, check if we have dragged the mouse
509   if(hasPrivateData() && !privateData()->hasDragged && event->buttons() & Qt::LeftButton
510     && (event->buttonDownScreenPos(Qt::LeftButton) - event->screenPos()).manhattanLength() >= QApplication::startDragDistance())
511     privateData()->hasDragged = true;
512   ChatItem::mouseMoveEvent(event);
513 }
514
515 void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
516   endHoverMode();
517   event->accept();
518 }
519
520 void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
521   bool onClickable = false;
522   qint16 idx = posToCursor(event->pos());
523   for(int i = 0; i < privateData()->clickables.count(); i++) {
524     Clickable click = privateData()->clickables.at(i);
525     if(idx >= click.start && idx < click.start + click.length) {
526       if(click.type == Clickable::Url) {
527         onClickable = true;
528         showWebPreview(click);
529       } else if(click.type == Clickable::Channel) {
530         // TODO: don't make clickable if it's our own name
531         //onClickable = true; //FIXME disabled for now
532       }
533       if(onClickable) {
534         setCursor(Qt::PointingHandCursor);
535         privateData()->currentClickable = click;
536         update();
537         break;
538       }
539     }
540   }
541   if(!onClickable) endHoverMode();
542   event->accept();
543 }
544
545 void ContentsChatItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) {
546   qint16 idx = posToCursor(event->pos());
547   for(int i = 0; i < privateData()->clickables.count(); i++) {
548     Clickable click = privateData()->clickables.at(i);
549     if(idx >= click.start && idx < click.start + click.length) {
550       if(click.type == Clickable::Url) {
551         QMenu menu;
552         QAction *copyToClipboard = menu.addAction(QObject::tr("Copy to Clipboard"));
553         QAction *selected = menu.exec(event->screenPos());
554         if(selected == copyToClipboard) {
555           QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
556 #   ifdef Q_WS_X11
557           QApplication::clipboard()->setText(url, QClipboard::Selection);
558 #   endif
559 //# else
560           QApplication::clipboard()->setText(url);
561 //# endif
562         }
563       }
564     }
565   }
566 }
567
568 void ContentsChatItem::showWebPreview(const Clickable &click) {
569 #ifndef HAVE_WEBKIT
570   Q_UNUSED(click);
571 #else
572   QTextLine line = layout()->lineForTextPosition(click.start);
573   qreal x = line.cursorToX(click.start);
574   qreal width = line.cursorToX(click.start + click.length) - x;
575   qreal height = line.height();
576   qreal y = height * line.lineNumber();
577
578   QPointF topLeft = scenePos() + QPointF(x, y);
579   QRectF urlRect = QRectF(topLeft.x(), topLeft.y(), width, height);
580
581   QString url = data(ChatLineModel::DisplayRole).toString().mid(click.start, click.length);
582   if(!url.contains("://"))
583     url = "http://" + url;
584   chatScene()->loadWebPreview(this, url, urlRect);
585 #endif
586 }
587
588 void ContentsChatItem::clearWebPreview() {
589 #ifdef HAVE_WEBKIT
590   chatScene()->clearWebPreview(this);
591 #endif
592 }
593
594 /*************************************************************************************************/
595
596 ContentsChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item)
597   : item(_item),
598     layout(0),
599     wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
600     wordidx(0),
601     lineCount(0),
602     choppedTrailing(0)
603 {
604 }
605
606 ContentsChatItem::WrapColumnFinder::~WrapColumnFinder() {
607   delete layout;
608 }
609
610 qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn() {
611   if(wordidx >= wrapList.count())
612     return -1;
613
614   lineCount++;
615   qreal targetWidth = lineCount * item->width() + choppedTrailing;
616
617   qint16 start = wordidx;
618   qint16 end = wrapList.count() - 1;
619
620   // check if the whole line fits
621   if(wrapList.at(end).endX <= targetWidth) //  || start == end)
622     return -1;
623
624   // check if we have a very long word that needs inter word wrap
625   if(wrapList.at(start).endX > targetWidth) {
626     if(!line.isValid()) {
627       layout = item->createLayout(QTextOption::NoWrap);
628       layout->beginLayout();
629       line = layout->createLine();
630       layout->endLayout();
631     }
632     return line.xToCursor(targetWidth, QTextLine::CursorOnCharacter);
633   }
634
635   while(true) {
636     if(start + 1 == end) {
637       wordidx = end;
638       const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
639
640       // both cases should be cought preliminary
641       Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
642       Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
643
644       choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
645       return wrapList.at(wordidx).start;
646     }
647
648     qint16 pivot = (end + start) / 2;
649     if(wrapList.at(pivot).endX > targetWidth) {
650       end = pivot;
651     } else {
652       start = pivot;
653     }
654   }
655   Q_ASSERT(false);
656   return -1;
657 }
658