2 * Copyright (C) 2005-2013 Team XBMC
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, or (at your option)
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 XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
21 #include "GUITextLayout.h"
23 #include "GUIControl.h"
24 #include "GUIColorManager.h"
25 #include "utils/CharsetConverter.h"
26 #include "utils/StringUtils.h"
30 #define WORK_AROUND_NEEDED_FOR_LINE_BREAKS
32 CGUIString::CGUIString(iString start, iString end, bool carriageReturn)
34 m_text.assign(start, end);
35 m_carriageReturn = carriageReturn;
38 CStdString CGUIString::GetAsString() const
41 for (unsigned int i = 0; i < m_text.size(); i++)
42 text += (char)(m_text[i] & 0xff);
46 CGUITextLayout::CGUITextLayout(CGUIFont *font, bool wrap, float fHeight, CGUIFont *borderFont)
49 m_borderFont = borderFont;
52 m_maxHeight = fHeight;
57 void CGUITextLayout::SetWrap(bool bWrap)
62 void CGUITextLayout::Render(float x, float y, float angle, color_t color, color_t shadowColor, uint32_t alignment, float maxWidth, bool solid)
67 // set the main text color
71 // render the text at the required location, angle, and size
74 static const float degrees_to_radians = 0.01745329252f;
75 g_graphicsContext.AddTransform(TransformMatrix::CreateZRotation(angle * degrees_to_radians, x, y, g_graphicsContext.GetScalingPixelRatio()));
77 // center our text vertically
78 if (alignment & XBFONT_CENTER_Y)
80 y -= m_font->GetTextHeight(m_lines.size()) * 0.5f;;
81 alignment &= ~XBFONT_CENTER_Y;
84 for (vector<CGUIString>::iterator i = m_lines.begin(); i != m_lines.end(); i++)
86 const CGUIString &string = *i;
87 uint32_t align = alignment;
88 if (align & XBFONT_JUSTIFIED && string.m_carriageReturn)
89 align &= ~XBFONT_JUSTIFIED;
91 m_font->DrawText(x, y, m_colors[0], shadowColor, string.m_text, align, maxWidth);
93 m_font->DrawText(x, y, m_colors, shadowColor, string.m_text, align, maxWidth);
94 y += m_font->GetLineHeight();
98 g_graphicsContext.RemoveTransform();
101 bool CGUITextLayout::UpdateScrollinfo(CScrollInfo &scrollInfo)
108 return m_font->UpdateScrollInfo(m_lines[0].m_text, scrollInfo);
112 void CGUITextLayout::RenderScrolling(float x, float y, float angle, color_t color, color_t shadowColor, uint32_t alignment, float maxWidth, const CScrollInfo &scrollInfo)
117 // set the main text color
121 // render the text at the required location, angle, and size
124 static const float degrees_to_radians = 0.01745329252f;
125 g_graphicsContext.AddTransform(TransformMatrix::CreateZRotation(angle * degrees_to_radians, x, y, g_graphicsContext.GetScalingPixelRatio()));
127 // center our text vertically
128 if (alignment & XBFONT_CENTER_Y)
130 y -= m_font->GetTextHeight(m_lines.size()) * 0.5f;;
131 alignment &= ~XBFONT_CENTER_Y;
134 // NOTE: This workaround is needed as otherwise multi-line text that scrolls
135 // will scroll in proportion to the number of lines. Ideally we should
136 // do the DrawScrollingText calculation here. This probably won't make
137 // any difference to the smoothness of scrolling though which will be
138 // jumpy with this sort of thing. It's not exactly a well used situation
139 // though, so this hack is probably OK.
140 for (vector<CGUIString>::iterator i = m_lines.begin(); i != m_lines.end(); i++)
142 const CGUIString &string = *i;
143 m_font->DrawScrollingText(x, y, m_colors, shadowColor, string.m_text, alignment, maxWidth, scrollInfo);
144 y += m_font->GetLineHeight();
148 g_graphicsContext.RemoveTransform();
151 void CGUITextLayout::RenderOutline(float x, float y, color_t color, color_t outlineColor, uint32_t alignment, float maxWidth)
156 // set the outline color
157 vecColors outlineColors;
159 outlineColors.push_back(outlineColor);
161 // center our text vertically
162 if (alignment & XBFONT_CENTER_Y)
164 y -= m_font->GetTextHeight(m_lines.size()) * 0.5f;;
165 alignment &= ~XBFONT_CENTER_Y;
169 // adjust so the baselines of the fonts align
170 float by = y + m_font->GetTextBaseLine() - m_borderFont->GetTextBaseLine();
171 m_borderFont->Begin();
172 for (vector<CGUIString>::iterator i = m_lines.begin(); i != m_lines.end(); i++)
174 const CGUIString &string = *i;
175 uint32_t align = alignment;
176 if (align & XBFONT_JUSTIFIED && string.m_carriageReturn)
177 align &= ~XBFONT_JUSTIFIED;
178 // text centered horizontally must be computed using the original font, not the bordered
179 // font, as the bordered font will be wider, and thus will end up uncentered.
180 // TODO: We should really have a better way to handle text extent - at the moment we assume
181 // that text is rendered from a posx, posy, width, and height which isn't enough to
182 // accurately position text. We need a vertical and horizontal offset of the baseline
183 // and cursor as well.
185 if (align & XBFONT_CENTER_X)
187 bx -= m_font->GetTextWidth(string.m_text) * 0.5f;
188 align &= ~XBFONT_CENTER_X;
191 // don't pass maxWidth through to the renderer for the same reason above: it will cause clipping
193 m_borderFont->DrawText(bx, by, outlineColors, 0, string.m_text, align, 0);
194 by += m_borderFont->GetLineHeight();
199 // set the main text color
204 for (vector<CGUIString>::iterator i = m_lines.begin(); i != m_lines.end(); i++)
206 const CGUIString &string = *i;
207 uint32_t align = alignment;
208 if (align & XBFONT_JUSTIFIED && string.m_carriageReturn)
209 align &= ~XBFONT_JUSTIFIED;
211 // don't pass maxWidth through to the renderer for the reason above.
212 m_font->DrawText(x, y, m_colors, 0, string.m_text, align, 0);
213 y += m_font->GetLineHeight();
218 bool CGUITextLayout::Update(const CStdString &text, float maxWidth, bool forceUpdate /*= false*/, bool forceLTRReadingOrder /*= false*/)
222 utf8ToW(text, utf16);
225 return UpdateW(utf16, maxWidth, forceUpdate, forceLTRReadingOrder);
228 bool CGUITextLayout::UpdateW(const CStdStringW &text, float maxWidth /*= 0*/, bool forceUpdate /*= false*/, bool forceLTRReadingOrder /*= false*/)
230 if (text.Equals(m_lastText) && !forceUpdate)
233 // parse the text for style information
236 ParseText(text, m_font ? m_font->GetStyle() : 0, m_textColor, colors, parsedText);
239 UpdateStyled(parsedText, colors, maxWidth, forceLTRReadingOrder);
244 void CGUITextLayout::UpdateStyled(const vecText &text, const vecColors &colors, float maxWidth, bool forceLTRReadingOrder)
246 // empty out our previous string
250 // if we need to wrap the text, then do so
251 if (m_wrap && maxWidth > 0)
252 WrapText(text, maxWidth);
254 LineBreakText(text, m_lines);
256 // remove any trailing blank lines
257 while (!m_lines.empty() && m_lines.back().m_text.empty())
260 BidiTransform(m_lines, forceLTRReadingOrder);
262 // and cache the width and height for later reading
266 // BidiTransform is used to handle RTL text flipping in the string
267 void CGUITextLayout::BidiTransform(vector<CGUIString> &lines, bool forceLTRReadingOrder)
269 for (unsigned int i=0; i<lines.size(); i++)
271 CGUIString &line = lines[i];
273 // reserve enough space in the flipped text
275 flippedText.reserve(line.m_text.size());
277 character_t sectionStyle = 0xffff0000; // impossible to achieve
278 CStdStringW sectionText;
279 for (vecText::iterator it = line.m_text.begin(); it != line.m_text.end(); ++it)
281 character_t style = *it & 0xffff0000;
282 if (style != sectionStyle)
284 if (!sectionText.IsEmpty())
285 { // style has changed, bidi flip text
286 CStdStringW sectionFlipped = BidiFlip(sectionText, forceLTRReadingOrder);
287 for (unsigned int j = 0; j < sectionFlipped.size(); j++)
288 flippedText.push_back(sectionStyle | sectionFlipped[j]);
290 sectionStyle = style;
293 sectionText.push_back( (wchar_t)(*it & 0xffff) );
296 // handle the last section
297 if (!sectionText.IsEmpty())
299 CStdStringW sectionFlipped = BidiFlip(sectionText, forceLTRReadingOrder);
300 for (unsigned int j = 0; j < sectionFlipped.size(); j++)
301 flippedText.push_back(sectionStyle | sectionFlipped[j]);
304 // replace the original line with the proccessed one
305 lines[i] = CGUIString(flippedText.begin(), flippedText.end(), line.m_carriageReturn);
309 CStdStringW CGUITextLayout::BidiFlip(const CStdStringW &text, bool forceLTRReadingOrder)
311 CStdStringA utf8text;
312 CStdStringW visualText;
314 // convert to utf8, and back to utf16 with bidi flipping
315 g_charsetConverter.wToUTF8(text, utf8text);
316 g_charsetConverter.utf8ToW(utf8text, visualText, true, forceLTRReadingOrder);
321 void CGUITextLayout::Filter(CStdString &text)
324 utf8ToW(text, utf16);
327 ParseText(utf16, 0, 0xffffffff, colors, parsedText);
329 for (unsigned int i = 0; i < parsedText.size(); i++)
330 utf16 += (wchar_t)(0xffff & parsedText[i]);
331 g_charsetConverter.wToUTF8(utf16, text);
334 void CGUITextLayout::ParseText(const CStdStringW &text, uint32_t defaultStyle, color_t defaultColor, vecColors &colors, vecText &parsedText)
336 // run through the string, searching for:
337 // [B] or [/B] -> toggle bold on and off
338 // [I] or [/I] -> toggle italics on and off
339 // [COLOR ffab007f] or [/COLOR] -> toggle color on and off
340 // [CAPS <option>] or [/CAPS] -> toggle capatilization on and off
342 uint32_t currentStyle = defaultStyle; // start with the default font's style
343 color_t currentColor = 0;
345 colors.push_back(defaultColor);
346 stack<color_t> colorStack;
349 // these aren't independent, but that's probably not too much of an issue
350 // eg [UPPERCASE]Glah[LOWERCASE]FReD[/LOWERCASE]Georeg[/UPPERCASE] will work (lower case >> upper case)
351 // but [LOWERCASE]Glah[UPPERCASE]FReD[/UPPERCASE]Georeg[/LOWERCASE] won't
354 size_t pos = text.Find(L'[');
355 while (pos != CStdString::npos && pos + 1 < text.size())
357 uint32_t newStyle = 0;
358 color_t newColor = currentColor;
359 bool colorTagChange = false;
360 bool newLine = false;
361 // have a [ - check if it's an ON or OFF switch
363 int endPos = pos++; // finish of string
364 if (text[pos] == L'/')
369 // check for each type
370 if (text.Mid(pos,2) == L"B]")
371 { // bold - finish the current text block and assign the bold state
373 if ((on && text.Find(L"[/B]",pos) >= 0) || // check for a matching end point
374 (!on && (currentStyle & FONT_STYLE_BOLD))) // or matching start point
375 newStyle = FONT_STYLE_BOLD;
377 else if (text.Mid(pos,2) == L"I]")
380 if ((on && text.Find(L"[/I]",pos) >= 0) || // check for a matching end point
381 (!on && (currentStyle & FONT_STYLE_ITALICS))) // or matching start point
382 newStyle = FONT_STYLE_ITALICS;
384 else if (text.Mid(pos,10) == L"UPPERCASE]")
387 if ((on && text.Find(L"[/UPPERCASE]",pos) >= 0) || // check for a matching end point
388 (!on && (currentStyle & FONT_STYLE_UPPERCASE))) // or matching start point
389 newStyle = FONT_STYLE_UPPERCASE;
391 else if (text.Mid(pos,10) == L"LOWERCASE]")
394 if ((on && text.Find(L"[/LOWERCASE]",pos) >= 0) || // check for a matching end point
395 (!on && (currentStyle & FONT_STYLE_LOWERCASE))) // or matching start point
396 newStyle = FONT_STYLE_LOWERCASE;
398 else if (text.Mid(pos,3) == L"CR]" && on)
403 else if (text.Mid(pos,5) == L"COLOR")
405 size_t finish = text.Find(L']', pos + 5);
406 if (on && finish != CStdString::npos && (size_t)text.Find(L"[/COLOR]",finish) != CStdString::npos)
408 color_t color = g_colorManager.GetColor(text.Mid(pos + 5, finish - pos - 5));
409 vecColors::const_iterator it = std::find(colors.begin(), colors.end(), color);
410 if (it == colors.end())
411 { // create new color
412 if (colors.size() <= 0xFF)
414 newColor = colors.size();
415 colors.push_back(color);
417 else // we have only 8 bits for color index, fallback to first color if reach max.
421 // reuse existing color
422 newColor = it - colors.begin();
423 colorStack.push(newColor);
424 colorTagChange = true;
426 else if (!on && finish == pos + 5 && colorStack.size() > 1)
427 { // revert to previous color
429 newColor = colorStack.top();
430 colorTagChange = true;
432 if (finish != CStdString::npos)
436 if (newStyle || colorTagChange || newLine)
437 { // we have a new style or a new color, so format up the previous segment
438 CStdStringW subText = text.Mid(startPos, endPos - startPos);
439 if (currentStyle & FONT_STYLE_UPPERCASE)
441 if (currentStyle & FONT_STYLE_LOWERCASE)
443 AppendToUTF32(subText, ((currentStyle & 3) << 24) | (currentColor << 16), parsedText);
445 parsedText.push_back(L'\n');
447 // and switch to the new style
449 currentColor = newColor;
451 currentStyle |= newStyle;
453 currentStyle &= ~newStyle;
455 pos = text.Find(L'[',pos);
457 // now grab the remainder of the string
458 CStdStringW subText = text.Mid(startPos, text.GetLength() - startPos);
459 if (currentStyle & FONT_STYLE_UPPERCASE)
461 if (currentStyle & FONT_STYLE_LOWERCASE)
463 AppendToUTF32(subText, ((currentStyle & 3) << 24) | (currentColor << 16), parsedText);
466 void CGUITextLayout::SetMaxHeight(float fHeight)
468 m_maxHeight = fHeight;
471 void CGUITextLayout::WrapText(const vecText &text, float maxWidth)
476 int nMaxLines = (m_maxHeight > 0 && m_font->GetLineHeight() > 0)?(int)ceilf(m_maxHeight / m_font->GetLineHeight()):-1;
480 vector<CGUIString> lines;
481 LineBreakText(text, lines);
483 for (unsigned int i = 0; i < lines.size(); i++)
485 const CGUIString &line = lines[i];
486 vecText::const_iterator lastSpace = line.m_text.begin();
487 vecText::const_iterator pos = line.m_text.begin();
488 unsigned int lastSpaceInLine = 0;
490 while (pos != line.m_text.end())
492 // Get the current letter in the string
493 character_t letter = *pos;
495 if (CanWrapAtLetter(letter))
497 float width = m_font->GetTextWidth(curLine);
498 if (width > maxWidth)
500 if (lastSpace != line.m_text.begin() && lastSpaceInLine > 0)
502 CGUIString string(curLine.begin(), curLine.begin() + lastSpaceInLine, false);
503 m_lines.push_back(string);
504 // check for exceeding our number of lines
505 if (nMaxLines > 0 && m_lines.size() >= (size_t)nMaxLines)
509 while (pos != line.m_text.end() && IsSpace(*pos))
513 lastSpace = line.m_text.begin();
518 lastSpaceInLine = curLine.size();
520 curLine.push_back(letter);
523 // now add whatever we have left to the string
524 float width = m_font->GetTextWidth(curLine);
525 if (width > maxWidth)
527 // too long - put up to the last space on if we can + remove it from what's left.
528 if (lastSpace != line.m_text.begin() && lastSpaceInLine > 0)
530 CGUIString string(curLine.begin(), curLine.begin() + lastSpaceInLine, false);
531 m_lines.push_back(string);
532 // check for exceeding our number of lines
533 if (nMaxLines > 0 && m_lines.size() >= (size_t)nMaxLines)
535 curLine.erase(curLine.begin(), curLine.begin() + lastSpaceInLine);
536 while (curLine.size() && IsSpace(curLine.at(0)))
537 curLine.erase(curLine.begin());
540 CGUIString string(curLine.begin(), curLine.end(), true);
541 m_lines.push_back(string);
542 // check for exceeding our number of lines
543 if (nMaxLines > 0 && m_lines.size() >= (size_t)nMaxLines)
548 void CGUITextLayout::LineBreakText(const vecText &text, vector<CGUIString> &lines)
550 int nMaxLines = (m_maxHeight > 0 && m_font && m_font->GetLineHeight() > 0)?(int)ceilf(m_maxHeight / m_font->GetLineHeight()):-1;
551 vecText::const_iterator lineStart = text.begin();
552 vecText::const_iterator pos = text.begin();
553 while (pos != text.end() && (nMaxLines <= 0 || lines.size() < (size_t)nMaxLines))
555 // Get the current letter in the string
556 character_t letter = *pos;
558 // Handle the newline character
559 if ((letter & 0xffff) == L'\n' )
560 { // push back everything up till now
561 CGUIString string(lineStart, pos, true);
562 lines.push_back(string);
567 // handle the last line if non-empty
568 if (lineStart < text.end() && (nMaxLines <= 0 || lines.size() < (size_t)nMaxLines))
570 CGUIString string(lineStart, text.end(), true);
571 lines.push_back(string);
575 void CGUITextLayout::GetTextExtent(float &width, float &height) const
578 height = m_textHeight;
581 void CGUITextLayout::CalcTextExtent()
587 for (vector<CGUIString>::iterator i = m_lines.begin(); i != m_lines.end(); i++)
589 const CGUIString &string = *i;
590 float w = m_font->GetTextWidth(string.m_text);
594 m_textHeight = m_font->GetTextHeight(m_lines.size());
597 unsigned int CGUITextLayout::GetTextLength() const
599 unsigned int length = 0;
600 for (vector<CGUIString>::const_iterator i = m_lines.begin(); i != m_lines.end(); i++)
601 length += i->m_text.size();
605 void CGUITextLayout::GetFirstText(vecText &text) const
609 text = m_lines[0].m_text;
612 float CGUITextLayout::GetTextWidth(const CStdStringW &text) const
614 // NOTE: Assumes a single line of text
615 if (!m_font) return 0;
617 AppendToUTF32(text, (m_font->GetStyle() & 3) << 24, utf32);
618 return m_font->GetTextWidth(utf32);
621 void CGUITextLayout::DrawText(CGUIFont *font, float x, float y, color_t color, color_t shadowColor, const CStdString &text, uint32_t align)
625 AppendToUTF32(text, 0, utf32);
626 font->DrawText(x, y, color, shadowColor, utf32, align, 0);
629 void CGUITextLayout::AppendToUTF32(const CStdStringW &utf16, character_t colStyle, vecText &utf32)
631 // NOTE: Assumes a single line of text
632 utf32.reserve(utf32.size() + utf16.size());
633 for (unsigned int i = 0; i < utf16.size(); i++)
634 utf32.push_back(utf16[i] | colStyle);
637 void CGUITextLayout::utf8ToW(const CStdString &utf8, CStdStringW &utf16)
639 #ifdef WORK_AROUND_NEEDED_FOR_LINE_BREAKS
640 // NOTE: This appears to strip \n characters from text. This may be a consequence of incorrect
641 // expression of the \n in utf8 (we just use character code 10) or it might be something
642 // more sinister. For now, we use the workaround below.
643 CStdStringArray multiLines;
644 StringUtils::SplitString(utf8, "\n", multiLines);
645 for (unsigned int i = 0; i < multiLines.size(); i++)
648 // no need to bidiflip here - it's done in BidiTransform above
649 g_charsetConverter.utf8ToW(multiLines[i], line, false);
651 if (i < multiLines.size() - 1)
652 utf16.push_back(L'\n');
655 // no need to bidiflip here - it's done in BidiTransform above
656 g_charsetConverter.utf8ToW(utf8, utf16, false);
660 void CGUITextLayout::AppendToUTF32(const CStdString &utf8, character_t colStyle, vecText &utf32)
663 utf8ToW(utf8, utf16);
664 AppendToUTF32(utf16, colStyle, utf32);
667 void CGUITextLayout::Reset()
671 m_textWidth = m_textHeight = 0;