fixing speed up aftermath
[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 "qtuistyle.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 // PRIVATE DATA FOR CHATLINE MODEL ITEM
41 class ChatLineModelItemPrivate {
42   struct ChatLinePart {
43     QString plainText;
44     UiStyle::FormatList formatList;
45     inline ChatLinePart(const QString &pT, const UiStyle::FormatList &fL) : plainText(pT), formatList(fL) {}
46   };
47
48 public:
49   inline ChatLineModelItemPrivate(const Message &msg) : _msgBuffer(new Message(msg)), timestamp(0), sender(0), contents(0) {}
50   inline ~ChatLineModelItemPrivate() {
51     if(_msgBuffer) {
52       delete _msgBuffer;
53     } else {
54       delete timestamp;
55       delete sender;
56       delete contents;
57     }
58   }
59
60   inline bool needsStyling() { return (bool)_msgBuffer; }
61
62   inline ChatLinePart *partByColumn(MessageModel::ColumnType column) {
63     switch(column) {
64     case ChatLineModel::TimestampColumn:
65       return timestamp;
66     case ChatLineModel::SenderColumn:
67       return sender;
68     case ChatLineModel::ContentsColumn:
69       return contents;
70     default:
71       Q_ASSERT(false);
72       return 0;
73     }
74   }
75
76   inline const QString &plainText(MessageModel::ColumnType column) {
77     if(needsStyling())
78       style();
79     return partByColumn(column)->plainText;
80   }
81
82   inline const UiStyle::FormatList &formatList(MessageModel::ColumnType column) {
83     if(needsStyling())
84       style();
85     return partByColumn(column)->formatList;
86   }
87
88   inline const ChatLineModel::WrapList &wrapList() {
89     if(needsStyling())
90       style();
91     if(_wrapList.isEmpty())
92       computeWrapList();
93     return _wrapList;
94   }
95
96 private:
97   inline void style() {
98     QtUiStyle::StyledMessage m = QtUi::style()->styleMessage(*_msgBuffer);
99
100     timestamp = new ChatLinePart(m.timestamp.plainText, m.timestamp.formatList);
101     sender = new ChatLinePart(m.sender.plainText, m.sender.formatList);
102     contents = new ChatLinePart(m.contents.plainText, m.contents.formatList);
103
104     delete _msgBuffer;
105     _msgBuffer = 0;
106   }
107
108   inline void computeWrapList() {
109     if(contents->plainText.isEmpty())
110       return;
111
112     enum Mode { SearchStart, SearchEnd };
113
114     QList<ChatLineModel::Word> wplist;  // use a temp list which we'll later copy into a QVector for efficiency
115     QTextBoundaryFinder finder(QTextBoundaryFinder::Word, contents->plainText.unicode(), contents->plainText.length(), TextBoundaryFinderBuffer, TextBoundaryFinderBufferSize);
116
117     int idx;
118     int oldidx = 0;
119     bool wordStart = false;
120     bool wordEnd = false;
121     Mode mode = SearchEnd;
122     ChatLineModel::Word word;
123     word.start = 0;
124     qreal wordstartx = 0;
125
126     QTextLayout layout(contents->plainText);
127     QTextOption option;
128     option.setWrapMode(QTextOption::NoWrap);
129     layout.setTextOption(option);
130
131     layout.setAdditionalFormats(QtUi::style()->toTextLayoutList(contents->formatList, contents->plainText.length()));
132     layout.beginLayout();
133     QTextLine line = layout.createLine();
134     line.setNumColumns(contents->plainText.length());
135     layout.endLayout();
136
137     do {
138       idx = finder.toNextBoundary();
139       if(idx < 0) {
140         idx = contents->plainText.length();
141         wordStart = false;
142         wordEnd = false;
143         mode = SearchStart;
144       } else {
145         wordStart = finder.boundaryReasons().testFlag(QTextBoundaryFinder::StartWord);
146         wordEnd = finder.boundaryReasons().testFlag(QTextBoundaryFinder::EndWord);
147       }
148
149       //if(flg) qDebug() << idx << mode << wordStart << wordEnd << contents->plainText.left(idx) << contents->plainText.mid(idx);
150
151       if(mode == SearchEnd || (!wordStart && wordEnd)) {
152         if(wordStart || !wordEnd) continue;
153         oldidx = idx;
154         mode = SearchStart;
155         continue;
156       }
157       qreal wordendx = line.cursorToX(oldidx);
158       qreal trailingendx = line.cursorToX(idx);
159       word.endX = wordendx;
160       word.width = wordendx - wordstartx;
161       word.trailing = trailingendx - wordendx;
162       wordstartx = trailingendx;
163       wplist.append(word);
164
165       if(wordStart) {
166         word.start = idx;
167         mode = SearchEnd;
168       }
169       // the part " || (finder.position() == contents->plainText.length())" shouldn't be necessary
170       // but in rare and indeterministic cases Qt states that the end of the text is not a boundary o_O
171     } while(finder.isAtBoundary() || (finder.position() == contents->plainText.length()));
172
173     // A QVector needs less space than a QList
174     _wrapList.resize(wplist.count());
175     for(int i = 0; i < wplist.count(); i++) {
176       _wrapList[i] = wplist.at(i);
177     }
178   }
179
180   ChatLineModel::WrapList _wrapList;
181   Message *_msgBuffer;
182   ChatLinePart *timestamp, *sender, *contents;
183
184   static unsigned char *TextBoundaryFinderBuffer;
185   static int TextBoundaryFinderBufferSize;
186 };
187
188 unsigned char *ChatLineModelItemPrivate::TextBoundaryFinderBuffer = (unsigned char *)malloc(512 * sizeof(HB_CharAttributes_Dummy));
189 int ChatLineModelItemPrivate::TextBoundaryFinderBufferSize = 512 * (sizeof(HB_CharAttributes_Dummy) / sizeof(unsigned char));
190
191
192 // ****************************************
193 // the actual ChatLineModelItem
194 // ****************************************
195 ChatLineModelItem::ChatLineModelItem(const Message &msg)
196   : MessageModelItem(msg),
197     _data(new ChatLineModelItemPrivate(msg))
198 {
199 }
200
201 ChatLineModelItem::~ChatLineModelItem() {
202   delete _data;
203 }
204
205 QVariant ChatLineModelItem::data(int column, int role) const {
206   if(column < ChatLineModel::TimestampColumn || column > ChatLineModel::ContentsColumn)
207     return MessageModelItem::data(column, role);
208   MessageModel::ColumnType columnType = (MessageModel::ColumnType)column;
209
210   switch(role) {
211   case ChatLineModel::DisplayRole:
212     return _data->plainText(columnType);
213   case ChatLineModel::FormatRole:
214     return QVariant::fromValue<UiStyle::FormatList>(_data->formatList(columnType));
215   case ChatLineModel::WrapListRole:
216     if(columnType != ChatLineModel::ContentsColumn)
217       return QVariant();
218     return QVariant::fromValue<ChatLineModel::WrapList>(_data->wrapList());
219   }
220   return MessageModelItem::data(column, role);
221 }
222