Qt 4.8
qdeclarativestyledtext.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtDeclarative module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 
42 #include <QStack>
43 #include <QVector>
44 #include <QPainter>
45 #include <QTextLayout>
46 #include <QDebug>
47 #include <qmath.h>
48 #include "private/qdeclarativestyledtext_p.h"
49 
50 /*
51  QDeclarativeStyledText supports few tags:
52 
53  <b></b> - bold
54  <i></i> - italic
55  <br> - new line
56  <font color="color_name" size="1-7"></font>
57 
58  The opening and closing tags must be correctly nested.
59 */
60 
62 
64 {
65 public:
67 
68  void parse();
69  bool parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format);
70  bool parseCloseTag(const QChar *&ch, const QString &textIn);
71  void parseEntity(const QChar *&ch, const QString &textIn, QString &textOut);
72  bool parseFontAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format);
73  QPair<QStringRef,QStringRef> parseAttribute(const QChar *&ch, const QString &textIn);
74  QStringRef parseValue(const QChar *&ch, const QString &textIn);
75 
76  inline void skipSpace(const QChar *&ch) {
77  while (ch->isSpace() && !ch->isNull())
78  ++ch;
79  }
80 
84 
85  static const QChar lessThan;
86  static const QChar greaterThan;
87  static const QChar equals;
88  static const QChar singleQuote;
89  static const QChar doubleQuote;
90  static const QChar slash;
91  static const QChar ampersand;
92 };
93 
101 
103 : d(new QDeclarativeStyledTextPrivate(string, layout))
104 {
105 }
106 
108 {
109  delete d;
110 }
111 
113 {
114  if (string.isEmpty())
115  return;
116  QDeclarativeStyledText styledText(string, layout);
117  styledText.d->parse();
118 }
119 
121 {
123  QStack<QTextCharFormat> formatStack;
124 
125  QString drawText;
126  drawText.reserve(text.count());
127 
128  int textStart = 0;
129  int textLength = 0;
130  int rangeStart = 0;
131  const QChar *ch = text.constData();
132  while (!ch->isNull()) {
133  if (*ch == lessThan) {
134  if (textLength)
135  drawText.append(QStringRef(&text, textStart, textLength));
136  if (rangeStart != drawText.length() && formatStack.count()) {
137  QTextLayout::FormatRange formatRange;
138  formatRange.format = formatStack.top();
139  formatRange.start = rangeStart;
140  formatRange.length = drawText.length() - rangeStart;
141  ranges.append(formatRange);
142  }
143  rangeStart = drawText.length();
144  ++ch;
145  if (*ch == slash) {
146  ++ch;
147  if (parseCloseTag(ch, text)) {
148  if (formatStack.count())
149  formatStack.pop();
150  }
151  } else {
153  if (formatStack.count())
154  format = formatStack.top();
155  if (parseTag(ch, text, drawText, format))
156  formatStack.push(format);
157  }
158  textStart = ch - text.constData() + 1;
159  textLength = 0;
160  } else if (*ch == ampersand) {
161  ++ch;
162  drawText.append(QStringRef(&text, textStart, textLength));
163  parseEntity(ch, text, drawText);
164  textStart = ch - text.constData() + 1;
165  textLength = 0;
166  } else {
167  ++textLength;
168  }
169  if (!ch->isNull())
170  ++ch;
171  }
172  if (textLength)
173  drawText.append(QStringRef(&text, textStart, textLength));
174  if (rangeStart != drawText.length() && formatStack.count()) {
175  QTextLayout::FormatRange formatRange;
176  formatRange.format = formatStack.top();
177  formatRange.start = rangeStart;
178  formatRange.length = drawText.length() - rangeStart;
179  ranges.append(formatRange);
180  }
181 
182  layout.setText(drawText);
183  layout.setAdditionalFormats(ranges);
184 }
185 
187 {
188  skipSpace(ch);
189 
190  int tagStart = ch - textIn.constData();
191  int tagLength = 0;
192  while (!ch->isNull()) {
193  if (*ch == greaterThan) {
194  QStringRef tag(&textIn, tagStart, tagLength);
195  const QChar char0 = tag.at(0);
196  if (char0 == QLatin1Char('b')) {
197  if (tagLength == 1)
198  format.setFontWeight(QFont::Bold);
199  else if (tagLength == 2 && tag.at(1) == QLatin1Char('r')) {
201  return false;
202  }
203  } else if (char0 == QLatin1Char('i')) {
204  if (tagLength == 1)
205  format.setFontItalic(true);
206  }
207  return true;
208  } else if (ch->isSpace()) {
209  // may have params.
210  QStringRef tag(&textIn, tagStart, tagLength);
211  if (tag == QLatin1String("font"))
212  return parseFontAttributes(ch, textIn, format);
213  if (*ch == greaterThan || ch->isNull())
214  continue;
215  } else if (*ch != slash){
216  tagLength++;
217  }
218  ++ch;
219  }
220 
221  return false;
222 }
223 
225 {
226  skipSpace(ch);
227 
228  int tagStart = ch - textIn.constData();
229  int tagLength = 0;
230  while (!ch->isNull()) {
231  if (*ch == greaterThan) {
232  QStringRef tag(&textIn, tagStart, tagLength);
233  const QChar char0 = tag.at(0);
234  if (char0 == QLatin1Char('b')) {
235  if (tagLength == 1)
236  return true;
237  else if (tag.at(1) == QLatin1Char('r') && tagLength == 2)
238  return true;
239  } else if (char0 == QLatin1Char('i')) {
240  if (tagLength == 1)
241  return true;
242  } else if (tag == QLatin1String("font")) {
243  return true;
244  }
245  return false;
246  } else if (!ch->isSpace()){
247  tagLength++;
248  }
249  ++ch;
250  }
251 
252  return false;
253 }
254 
255 void QDeclarativeStyledTextPrivate::parseEntity(const QChar *&ch, const QString &textIn, QString &textOut)
256 {
257  int entityStart = ch - textIn.constData();
258  int entityLength = 0;
259  while (!ch->isNull()) {
260  if (*ch == QLatin1Char(';')) {
261  QStringRef entity(&textIn, entityStart, entityLength);
262  if (entity == QLatin1String("gt"))
263  textOut += QChar(62);
264  else if (entity == QLatin1String("lt"))
265  textOut += QChar(60);
266  else if (entity == QLatin1String("amp"))
267  textOut += QChar(38);
268  return;
269  }
270  ++entityLength;
271  ++ch;
272  }
273 }
274 
276 {
277  bool valid = false;
279  do {
280  attr = parseAttribute(ch, textIn);
281  if (attr.first == QLatin1String("color")) {
282  valid = true;
283  format.setForeground(QColor(attr.second.toString()));
284  } else if (attr.first == QLatin1String("size")) {
285  valid = true;
286  int size = attr.second.toString().toInt();
287  if (attr.second.at(0) == QLatin1Char('-') || attr.second.at(0) == QLatin1Char('+'))
288  size += 3;
289  if (size >= 1 && size <= 7) {
290  static const qreal scaling[] = { 0.7, 0.8, 1.0, 1.2, 1.5, 2.0, 2.4 };
291  format.setFontPointSize(baseFont.pointSize() * scaling[size-1]);
292  }
293  }
294  } while (!ch->isNull() && !attr.first.isEmpty());
295 
296  return valid;
297 }
298 
300 {
301  skipSpace(ch);
302 
303  int attrStart = ch - textIn.constData();
304  int attrLength = 0;
305  while (!ch->isNull()) {
306  if (*ch == greaterThan) {
307  break;
308  } else if (*ch == equals) {
309  ++ch;
310  if (*ch != singleQuote && *ch != doubleQuote) {
311  while (*ch != greaterThan && !ch->isNull())
312  ++ch;
313  break;
314  }
315  ++ch;
316  if (!attrLength)
317  break;
318  QStringRef attr(&textIn, attrStart, attrLength);
319  QStringRef val = parseValue(ch, textIn);
320  if (!val.isEmpty())
321  return QPair<QStringRef,QStringRef>(attr,val);
322  break;
323  } else {
324  ++attrLength;
325  }
326  ++ch;
327  }
328 
330 }
331 
333 {
334  int valStart = ch - textIn.constData();
335  int valLength = 0;
336  while (*ch != singleQuote && *ch != doubleQuote && !ch->isNull()) {
337  ++valLength;
338  ++ch;
339  }
340  if (ch->isNull())
341  return QStringRef();
342  ++ch; // skip quote
343 
344  return QStringRef(&textIn, valStart, valLength);
345 }
346 
The QColor class provides colors based on RGB, HSV or CMYK values.
Definition: qcolor.h:67
double d
Definition: qnumeric_p.h:62
QString toString() const
Returns a copy of the string reference as a QString object.
Definition: qstring.cpp:8653
The QTextLayout::FormatRange structure is used to apply extra formatting information for a specified ...
Definition: qtextlayout.h:128
void setFontItalic(bool italic)
If italic is true, sets the text format&#39;s font to be italic; otherwise the font will be non-italic...
Definition: qtextformat.h:415
The QTextCharFormat class provides formatting information for characters in a QTextDocument.
Definition: qtextformat.h:372
double qreal
Definition: qglobal.h:1193
#define QT_END_NAMESPACE
This macro expands to.
Definition: qglobal.h:90
static void parse(const QString &string, QTextLayout &layout)
static bool greaterThan(const QString &s1, const QString &s2)
int toInt(bool *ok=0, int base=10) const
Returns the string converted to an int using base base, which is 10 by default and must be between 2 ...
Definition: qstring.cpp:6090
bool isNull() const
Returns true if the character is the Unicode character 0x0000 (&#39;\0&#39;); otherwise returns false...
Definition: qchar.h:262
int count(const T &t) const
Returns the number of occurrences of value in the vector.
Definition: qvector.h:742
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
QPair< QStringRef, QStringRef > parseAttribute(const QChar *&ch, const QString &textIn)
T1 first
Definition: qpair.h:65
T2 second
Definition: qpair.h:66
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QStack class is a template class that provides a stack.
Definition: qcontainerfwd.h:63
int start
Specifies the beginning of the format range within the text layout&#39;s text.
Definition: qtextlayout.h:129
QDeclarativeStyledTextPrivate(const QString &t, QTextLayout &l)
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool parseTag(const QChar *&ch, const QString &textIn, QString &textOut, QTextCharFormat &format)
The QChar class provides a 16-bit Unicode character.
Definition: qchar.h:72
bool parseCloseTag(const QChar *&ch, const QString &textIn)
bool isSpace() const
Returns true if the character is a separator character (Separator_* categories); otherwise returns fa...
Definition: qchar.cpp:609
void setFontWeight(int weight)
Sets the text format&#39;s font weight to weight.
Definition: qtextformat.h:411
T pop()
Removes the top item from the stack and returns it.
Definition: qstack.h:67
void reserve(int size)
Attempts to allocate memory for at least size characters.
Definition: qstring.h:881
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
#define QT_BEGIN_NAMESPACE
This macro expands to.
Definition: qglobal.h:89
static bool isEmpty(const char *str)
static bool lessThan(const QChar *a, int l, const char *c)
Definition: qurl.cpp:3253
const char * layout
void parseEntity(const QChar *&ch, const QString &textIn, QString &textOut)
bool isEmpty() const
Returns true if the string reference has no characters; otherwise returns false.
Definition: qstring.h:1169
void setFontPointSize(qreal size)
Sets the text format&#39;s font size.
Definition: qtextformat.h:406
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
void push(const T &t)
Adds element t to the top of the stack.
Definition: qstack.h:60
The QStringRef class provides a thin wrapper around QString substrings.
Definition: qstring.h:1099
The QTextLayout class is used to lay out and render text.
Definition: qtextlayout.h:105
QString & append(QChar c)
Definition: qstring.cpp:1777
The QFont class specifies a font used for drawing text.
Definition: qfont.h:64
QDeclarativeStyledTextPrivate * d
QDeclarativeStyledText(const QString &string, QTextLayout &layout)
QFactoryLoader * l
bool parseFontAttributes(const QChar *&ch, const QString &textIn, QTextCharFormat &format)
int length
Specifies the numer of characters the format range spans.
Definition: qtextlayout.h:130
QTextCharFormat format
Specifies the format to apply.
Definition: qtextlayout.h:131
void setForeground(const QBrush &brush)
Sets the foreground brush to the specified brush.
Definition: qtextformat.h:350
QStringRef parseValue(const QChar *&ch, const QString &textIn)
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
const QChar * constData() const
Returns a pointer to the data stored in the QString.
Definition: qstring.h:712
const QChar at(int i) const
Returns the character at the given index position in the string reference.
Definition: qstring.h:1174
#define text
Definition: qobjectdefs.h:80
T & top()
Returns a reference to the stack&#39;s top item.
Definition: qstack.h:72