1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include <QApplication>
23 #include <QDesktopServices>
24 #include <QFontMetrics>
25 #include <QGraphicsSceneMouseEvent>
28 #include <QTextLayout>
31 #include "chatlinemodel.h"
34 ChatItem::ChatItem(int col, QAbstractItemModel *model, QGraphicsItem *parent)
35 : QGraphicsItem(parent),
40 _selectionMode(NoSelection),
44 QModelIndex index = model->index(row(), col);
45 _fontMetrics = QtUi::style()->fontMetrics(model->data(index, ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second);
46 setAcceptHoverEvents(true);
50 ChatItem::~ChatItem() {
54 QVariant ChatItem::data(int role) const {
55 QModelIndex index = model()->index(row(), column());
56 if(!index.isValid()) {
57 qWarning() << "ChatItem::data(): model index is invalid!" << index;
60 return model()->data(index, role);
63 qreal ChatItem::setGeometry(qreal w, qreal h) {
64 if(w == _boundingRect.width()) return _boundingRect.height();
65 prepareGeometryChange();
66 _boundingRect.setWidth(w);
67 if(h < 0) h = computeHeight();
68 _boundingRect.setHeight(h);
69 if(haveLayout()) updateLayout();
73 qreal ChatItem::computeHeight() {
74 if(data(ChatLineModel::ColumnTypeRole).toUInt() != ChatLineModel::ContentsColumn)
75 return fontMetrics()->lineSpacing(); // only contents can be multi-line
78 WrapColumnFinder finder(this);
79 while(finder.nextWrapColumn() > 0) _lines++;
80 return _lines * fontMetrics()->lineSpacing();
83 QTextLayout *ChatItem::createLayout(QTextOption::WrapMode wrapMode, Qt::Alignment alignment) {
84 QTextLayout *layout = new QTextLayout(data(MessageModel::DisplayRole).toString());
87 option.setWrapMode(wrapMode);
88 option.setAlignment(alignment);
89 layout->setTextOption(option);
91 QList<QTextLayout::FormatRange> formatRanges
92 = QtUi::style()->toTextLayoutList(data(MessageModel::FormatRole).value<UiStyle::FormatList>(), layout->text().length());
93 layout->setAdditionalFormats(formatRanges);
97 void ChatItem::setLayout(QTextLayout *layout) {
99 _layoutData = new LayoutData;
100 _layoutData->layout = layout;
103 void ChatItem::updateLayout() {
104 switch(data(ChatLineModel::ColumnTypeRole).toUInt()) {
105 case ChatLineModel::TimestampColumn:
106 if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignLeft));
108 case ChatLineModel::SenderColumn:
109 if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere, Qt::AlignRight));
110 layout()->beginLayout();
112 QTextLine line = layout()->createLine();
114 line.setLineWidth(width());
115 line.setPosition(QPointF(0,0));
117 layout()->endLayout();
120 case ChatLineModel::ContentsColumn: {
121 if(!haveLayout()) setLayout(createLayout(QTextOption::WrapAnywhere));
124 ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
125 if(!wrapList.count()) return; // empty chatitem
128 WrapColumnFinder finder(this);
129 layout()->beginLayout();
131 QTextLine line = layout()->createLine();
135 int col = finder.nextWrapColumn();
136 line.setNumColumns(col >= 0 ? col - line.textStart() : layout()->text().length());
137 line.setPosition(QPointF(0, h));
138 h += line.height() + fontMetrics()->leading();
140 layout()->endLayout();
146 void ChatItem::clearLayoutData() {
151 // NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
152 // This is a deliberate trade-off. (-> selectFmt creation, data() call)
153 void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
154 Q_UNUSED(option); Q_UNUSED(widget);
155 if(!haveLayout()) updateLayout();
156 painter->setClipRect(boundingRect()); // no idea why QGraphicsItem clipping won't work
157 //if(_selectionMode == FullSelection) {
159 //painter->fillRect(boundingRect(), QApplication::palette().brush(QPalette::Highlight));
160 //painter->restore();
162 QVector<QTextLayout::FormatRange> formats;
163 if(_selectionMode != NoSelection) {
164 QTextLayout::FormatRange selectFmt;
165 selectFmt.format.setForeground(QApplication::palette().brush(QPalette::HighlightedText));
166 selectFmt.format.setBackground(QApplication::palette().brush(QPalette::Highlight));
167 if(_selectionMode == PartialSelection) {
168 selectFmt.start = qMin(_selectionStart, _selectionEnd);
169 selectFmt.length = qAbs(_selectionStart - _selectionEnd);
170 } else { // FullSelection
172 selectFmt.length = data(MessageModel::DisplayRole).toString().length();
174 formats.append(selectFmt);
176 layout()->draw(painter, QPointF(0,0), formats, boundingRect());
179 qint16 ChatItem::posToCursor(const QPointF &pos) {
180 if(pos.y() > height()) return data(MessageModel::DisplayRole).toString().length();
181 if(pos.y() < 0) return 0;
182 if(!haveLayout()) updateLayout();
183 for(int l = layout()->lineCount() - 1; l >= 0; l--) {
184 QTextLine line = layout()->lineAt(l);
185 if(pos.y() >= line.y()) {
186 return line.xToCursor(pos.x(), QTextLine::CursorOnCharacter);
192 void ChatItem::setFullSelection() {
193 if(_selectionMode != FullSelection) {
194 _selectionMode = FullSelection;
199 void ChatItem::clearSelection() {
200 if(_selectionMode != NoSelection) {
201 _selectionMode = NoSelection;
206 void ChatItem::continueSelecting(const QPointF &pos) {
207 _selectionMode = PartialSelection;
208 _selectionEnd = posToCursor(pos);
212 QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive) {
213 QList<QRectF> resultList;
214 const QAbstractItemModel *model_ = model();
218 QString plainText = model_->data(model_->index(row(), column()), MessageModel::DisplayRole).toString();
219 QList<int> indexList;
220 int searchIdx = plainText.indexOf(searchWord, 0, caseSensitive);
221 while(searchIdx != -1) {
222 indexList << searchIdx;
223 searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
230 foreach(int idx, indexList) {
231 QTextLine line = _layout->lineForTextPosition(idx);
232 qreal x = line.cursorToX(idx);
233 qreal width = line.cursorToX(idx + searchWord.count()) - x;
234 qreal height = fontMetrics()->lineSpacing();
235 qreal y = height * line.lineNumber();
236 resultList << QRectF(x, y, width, height);
242 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
243 if(event->buttons() == Qt::LeftButton) {
244 if(_selectionMode == NoSelection) {
245 chatScene()->setSelectingItem(this); // removes earlier selection if exists
246 _selectionStart = _selectionEnd = posToCursor(event->pos());
247 //_selectionMode = PartialSelection;
249 chatScene()->setSelectingItem(0);
250 _selectionMode = NoSelection;
259 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
260 if(event->buttons() == Qt::LeftButton) {
261 if(contains(event->pos())) {
262 qint16 end = posToCursor(event->pos());
263 if(end != _selectionEnd) {
265 if(_selectionStart != _selectionEnd) _selectionMode = PartialSelection;
266 else _selectionMode = NoSelection;
271 chatScene()->startGlobalSelection(this, event->pos());
279 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
280 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
281 _selectionEnd = posToCursor(event->pos());
283 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
284 chatScene()->putToClipboard(selection);
291 void ChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
292 // FIXME dirty and fast hack to make http:// urls klickable
294 QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
295 QString str = data(ChatLineModel::DisplayRole).toString();
296 int idx = posToCursor(event->pos());
299 mi = regex.indexIn(str, mi);
301 if(idx >= mi && idx < mi + regex.matchedLength()) {
302 QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
305 mi += regex.matchedLength();
310 void ChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
311 //qDebug() << (void*)this << "entering";
315 void ChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
316 //qDebug() << (void*)this << "leaving";
320 void ChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
321 //qDebug() << (void*)this << event->pos();
326 /*************************************************************************************************/
328 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
329 wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
337 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
341 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
342 while(wordidx < wrapList.count()) {
343 w += wrapList.at(wordidx).width;
344 if(w >= item->width()) {
345 if(lastwrapcol >= wrapList.at(wordidx).start) {
346 // first word, and it doesn't fit
347 if(!line.isValid()) {
348 layout = item->createLayout(QTextOption::NoWrap);
349 layout->beginLayout();
350 line = layout->createLine();
351 line.setLineWidth(item->width());
354 int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
355 qreal x = line.cursorToX(idx, QTextLine::Trailing);
356 w = w - wrapList.at(wordidx).width - (x - lastwrappos);
361 // not the first word, so just wrap before this
362 lastwrapcol = wrapList.at(wordidx).start;
363 lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
367 w += wrapList.at(wordidx).trailing;