Introducing lazy word wrap calc.
[quassel.git] / src / qtui / chatlinemodelitem.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 <QFontMetrics>
22 #include <QTextBoundaryFinder>
23
24 #include "chatlinemodelitem.h"
25 #include "chatlinemodel.h"
26 #include "qtui.h"
27 #include "uistyle.h"
28
29 // This Struct is taken from Harfbuzz. We use it only to calc it's size.
30 // we use a shared memory region so we do not have to malloc a buffer area for every line
31 typedef struct {
32     /*HB_LineBreakType*/ unsigned lineBreakType  :2;
33     /*HB_Bool*/ unsigned whiteSpace              :1;     /* A unicode whitespace character, except NBSP, ZWNBSP */
34     /*HB_Bool*/ unsigned charStop                :1;     /* Valid cursor position (for left/right arrow) */
35     /*HB_Bool*/ unsigned wordBoundary            :1;
36     /*HB_Bool*/ unsigned sentenceBoundary        :1;
37     unsigned unused                  :2;
38 } HB_CharAttributes_Dummy;
39
40 unsigned char *ChatLineModelItem::TextBoundaryFinderBuffer = (unsigned char *)malloc(512 * sizeof(HB_CharAttributes_Dummy));
41 int ChatLineModelItem::TextBoundaryFinderBufferSize = 512 * (sizeof(HB_CharAttributes_Dummy) / sizeof(unsigned char));
42
43 struct ChatLineModelItemPrivate {
44   ChatLineModel::WrapList wrapList;
45 };
46
47 ChatLineModelItem::ChatLineModelItem(const Message &msg)
48   : MessageModelItem(msg),
49     _data(new ChatLineModelItemPrivate)
50 {
51   QtUiStyle::StyledMessage m = QtUi::style()->styleMessage(msg);
52
53   _timestamp.plainText = m.timestamp.plainText;
54   _sender.plainText = m.sender.plainText;
55   _contents.plainText = m.contents.plainText;
56
57   _timestamp.formatList = m.timestamp.formatList;
58   _sender.formatList = m.sender.formatList;
59   _contents.formatList = m.contents.formatList;
60 }
61
62 QVariant ChatLineModelItem::data(int column, int role) const {
63   const ChatLinePart *part = 0;
64
65   switch(column) {
66   case ChatLineModel::TimestampColumn:
67     part = &_timestamp;
68     break;
69   case ChatLineModel::SenderColumn:
70     part = &_sender;
71     break;
72   case ChatLineModel::ContentsColumn:
73     part = &_contents;
74     break;
75   default:
76     return MessageModelItem::data(column, role);
77   }
78
79   switch(role) {
80   case ChatLineModel::DisplayRole:
81     return part->plainText;
82   case ChatLineModel::FormatRole:
83     return QVariant::fromValue<UiStyle::FormatList>(part->formatList);
84   case ChatLineModel::WrapListRole:
85     if(column != ChatLineModel::ContentsColumn)
86       return QVariant();
87     if(_data->wrapList.isEmpty())
88       computeWrapList();
89     return QVariant::fromValue<ChatLineModel::WrapList>(_data->wrapList);
90   }
91   return MessageModelItem::data(column, role);
92 }
93
94 void ChatLineModelItem::computeWrapList() const {
95   if(_contents.plainText.isEmpty())
96     return;
97
98   enum Mode { SearchStart, SearchEnd };
99
100   QList<ChatLineModel::Word> wplist;  // use a temp list which we'll later copy into a QVector for efficiency
101   QTextBoundaryFinder finder(QTextBoundaryFinder::Word, _contents.plainText.unicode(), _contents.plainText.length(), TextBoundaryFinderBuffer, TextBoundaryFinderBufferSize);
102
103   int idx;
104   int oldidx = 0;
105   bool wordStart = false;
106   bool wordEnd = false;
107   Mode mode = SearchEnd;
108   ChatLineModel::Word word;
109   word.start = 0;
110   int wordstartx = 0;
111
112   QTextLayout layout(_contents.plainText);
113   QTextOption option;
114   option.setWrapMode(QTextOption::NoWrap);
115   layout.setTextOption(option);
116
117   layout.setAdditionalFormats(QtUi::style()->toTextLayoutList(_contents.formatList, _contents.plainText.length()));
118   layout.beginLayout();
119   QTextLine line = layout.createLine();
120   line.setNumColumns(_contents.plainText.length());
121   layout.endLayout();
122
123   do {
124     idx = finder.toNextBoundary();
125     if(idx < 0) {
126       idx = _contents.plainText.length();
127       wordStart = false;
128       wordEnd = false;
129       mode = SearchStart;
130     } else {
131       wordStart = finder.boundaryReasons().testFlag(QTextBoundaryFinder::StartWord);
132       wordEnd = finder.boundaryReasons().testFlag(QTextBoundaryFinder::EndWord);
133     }
134
135     //if(flg) qDebug() << idx << mode << wordStart << wordEnd << _contents.plainText.left(idx) << _contents.plainText.mid(idx);
136
137     if(mode == SearchEnd || (!wordStart && wordEnd)) {
138       if(wordStart || !wordEnd) continue;
139       oldidx = idx;
140       mode = SearchStart;
141       continue;
142     }
143     int wordendx = line.cursorToX(oldidx);
144     int trailingendx = line.cursorToX(idx);
145     word.width = wordendx - wordstartx;
146     word.trailing = trailingendx - wordendx;
147     wordstartx = trailingendx;
148     wplist.append(word);
149
150     if(wordStart) {
151       word.start = idx;
152       mode = SearchEnd;
153     }
154     // the part " || (finder.position() == _contents.plainText.length())" shouldn't be necessary
155     // but in rare and indeterministic cases Qt states that the end of the text is not a boundary o_O
156   } while(finder.isAtBoundary() || (finder.position() == _contents.plainText.length()));
157
158   // A QVector needs less space than a QList
159   _data->wrapList.resize(wplist.count());
160   for(int i = 0; i < wplist.count(); i++) {
161     _data->wrapList[i] = wplist.at(i);
162   }
163 }
164