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);
229 foreach(int idx, indexList) {
230 QTextLine line = layout()->lineForTextPosition(idx);
231 qreal x = line.cursorToX(idx);
232 qreal width = line.cursorToX(idx + searchWord.count()) - x;
233 qreal height = fontMetrics()->lineSpacing();
234 qreal y = height * line.lineNumber();
235 resultList << QRectF(x, y, width, height);
241 void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
242 if(event->buttons() == Qt::LeftButton) {
243 if(_selectionMode == NoSelection) {
244 chatScene()->setSelectingItem(this); // removes earlier selection if exists
245 _selectionStart = _selectionEnd = posToCursor(event->pos());
246 //_selectionMode = PartialSelection;
248 chatScene()->setSelectingItem(0);
249 _selectionMode = NoSelection;
258 void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
259 if(event->buttons() == Qt::LeftButton) {
260 if(contains(event->pos())) {
261 qint16 end = posToCursor(event->pos());
262 if(end != _selectionEnd) {
264 if(_selectionStart != _selectionEnd) _selectionMode = PartialSelection;
265 else _selectionMode = NoSelection;
270 chatScene()->startGlobalSelection(this, event->pos());
278 void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
279 if(_selectionMode != NoSelection && !event->buttons() & Qt::LeftButton) {
280 _selectionEnd = posToCursor(event->pos());
282 = data(MessageModel::DisplayRole).toString().mid(qMin(_selectionStart, _selectionEnd), qAbs(_selectionStart - _selectionEnd));
283 chatScene()->putToClipboard(selection);
290 void ChatItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
291 // FIXME dirty and fast hack to make http:// urls klickable
293 QRegExp regex("\\b([hf]t{1,2}ps?://[^\\s]+)\\b");
294 QString str = data(ChatLineModel::DisplayRole).toString();
295 int idx = posToCursor(event->pos());
298 mi = regex.indexIn(str, mi);
300 if(idx >= mi && idx < mi + regex.matchedLength()) {
301 QDesktopServices::openUrl(QUrl(regex.capturedTexts()[1]));
304 mi += regex.matchedLength();
309 void ChatItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
310 //qDebug() << (void*)this << "entering";
314 void ChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
315 //qDebug() << (void*)this << "leaving";
319 void ChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) {
320 //qDebug() << (void*)this << event->pos();
325 /*************************************************************************************************/
327 ChatItem::WrapColumnFinder::WrapColumnFinder(ChatItem *_item) : item(_item) {
328 wrapList = item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
336 ChatItem::WrapColumnFinder::~WrapColumnFinder() {
340 qint16 ChatItem::WrapColumnFinder::nextWrapColumn() {
341 while(wordidx < wrapList.count()) {
342 w += wrapList.at(wordidx).width;
343 if(w >= item->width()) {
344 if(lastwrapcol >= wrapList.at(wordidx).start) {
345 // first word, and it doesn't fit
346 if(!line.isValid()) {
347 layout = item->createLayout(QTextOption::NoWrap);
348 layout->beginLayout();
349 line = layout->createLine();
350 line.setLineWidth(item->width());
353 int idx = line.xToCursor(lastwrappos + item->width(), QTextLine::CursorOnCharacter);
354 qreal x = line.cursorToX(idx, QTextLine::Trailing);
355 w = w - wrapList.at(wordidx).width - (x - lastwrappos);
360 // not the first word, so just wrap before this
361 lastwrapcol = wrapList.at(wordidx).start;
362 lastwrappos = lastwrappos + w - wrapList.at(wordidx).width;
366 w += wrapList.at(wordidx).trailing;