summaryrefslogtreecommitdiff
path: root/apps/openmw/mwgui/formatting.cpp
blob: f416fbe07c5196821aad2ba32d394f902f87209f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#include "formatting.hpp"

#include <MyGUI_EditText.h>
#include <MyGUI_Gui.h>
#include <MyGUI_EditBox.h>
#include <MyGUI_ImageBox.h>

// correctBookartPath
#include "../mwbase/environment.hpp"
#include "../mwbase/windowmanager.hpp"

#include <components/debug/debuglog.hpp>
#include <components/interpreter/defines.hpp>
#include <components/misc/stringops.hpp>

#include "../mwscript/interpretercontext.hpp"

namespace MWGui::Formatting
    {
        /* BookTextParser */
        BookTextParser::BookTextParser(const std::string & text)
            : mIndex(0), mText(text), mIgnoreNewlineTags(true), mIgnoreLineEndings(true), mClosingTag(false)
        {
            MWScript::InterpreterContext interpreterContext(nullptr, MWWorld::Ptr()); // empty arguments, because there is no locals or actor
            mText = Interpreter::fixDefinesBook(mText, interpreterContext);

            Misc::StringUtils::replaceAll(mText, "\r", "");

            // vanilla game does not show any text after the last EOL tag.
            const std::string lowerText = Misc::StringUtils::lowerCase(mText);
            size_t brIndex = lowerText.rfind("<br>");
            size_t pIndex = lowerText.rfind("<p>");
            mPlainTextEnd = 0;
            if (brIndex != pIndex)
            {
                if (brIndex != std::string::npos && pIndex != std::string::npos)
                    mPlainTextEnd = std::max(brIndex, pIndex);
                else if (brIndex != std::string::npos)
                    mPlainTextEnd = brIndex;
                else
                    mPlainTextEnd = pIndex;
            }

            registerTag("br", Event_BrTag);
            registerTag("p", Event_PTag);
            registerTag("img", Event_ImgTag);
            registerTag("div", Event_DivTag);
            registerTag("font", Event_FontTag);
        }

        void BookTextParser::registerTag(const std::string & tag, BookTextParser::Events type)
        {
            mTagTypes[tag] = type;
        }

        std::string BookTextParser::getReadyText() const
        {
            return mReadyText;
        }

        BookTextParser::Events BookTextParser::next()
        {
            while (mIndex < mText.size())
            {
                char ch = mText[mIndex];
                if (ch == '<')
                {
                    const size_t tagStart = mIndex + 1;
                    const size_t tagEnd = mText.find('>', tagStart);
                    if (tagEnd == std::string::npos)
                        throw std::runtime_error("BookTextParser Error: Tag is not terminated");
                    parseTag(mText.substr(tagStart, tagEnd - tagStart));
                    mIndex = tagEnd;

                    if (mTagTypes.find(mTag) != mTagTypes.end())
                    {
                        Events type = mTagTypes.at(mTag);

                        if (type == Event_BrTag || type == Event_PTag)
                        {
                            if (!mIgnoreNewlineTags)
                            {
                                if (type == Event_BrTag)
                                    mBuffer.push_back('\n');
                                else
                                {
                                    mBuffer.append("\n\n");
                                }
                            }
                            mIgnoreLineEndings = true;
                        }
                        else
                            flushBuffer();

                        if (type == Event_ImgTag)
                        {
                            mIgnoreNewlineTags = false;
                        }

                        ++mIndex;
                        return type;
                    }
                }
                else
                {
                    if (!mIgnoreLineEndings || ch != '\n')
                    {
                        if (mIndex < mPlainTextEnd)
                            mBuffer.push_back(ch);
                        mIgnoreLineEndings = false;
                        mIgnoreNewlineTags = false;
                    }
                }

                ++mIndex;
            }

            flushBuffer();
            return Event_EOF;
        }

        void BookTextParser::flushBuffer()
        {
            mReadyText = mBuffer;
            mBuffer.clear();
        }

        const BookTextParser::Attributes & BookTextParser::getAttributes() const
        {
            return mAttributes;
        }

        bool BookTextParser::isClosingTag() const
        {
            return mClosingTag;
        }

        void BookTextParser::parseTag(std::string tag)
        {
            size_t tagNameEndPos = tag.find(' ');
            mAttributes.clear();
            mTag = tag.substr(0, tagNameEndPos);
            Misc::StringUtils::lowerCaseInPlace(mTag);
            if (mTag.empty())
                return;

            mClosingTag = (mTag[0] == '/');
            if (mClosingTag)
            {
                mTag.erase(mTag.begin());
                return;
            }

            if (tagNameEndPos == std::string::npos)
                return;
            tag.erase(0, tagNameEndPos+1);

            while (!tag.empty())
            {
                size_t sepPos = tag.find('=');
                if (sepPos == std::string::npos)
                    return;

                std::string key = tag.substr(0, sepPos);
                Misc::StringUtils::lowerCaseInPlace(key);
                tag.erase(0, sepPos+1);

                std::string value;

                if (tag.empty())
                    return;

                if (tag[0] == '"')
                {
                    size_t quoteEndPos = tag.find('"', 1);
                    if (quoteEndPos == std::string::npos)
                        throw std::runtime_error("BookTextParser Error: Missing end quote in tag");
                    value = tag.substr(1, quoteEndPos-1);
                    tag.erase(0, quoteEndPos+2);
                }
                else
                {
                    size_t valEndPos = tag.find(' ');
                    if (valEndPos == std::string::npos)
                    {
                        value = tag;
                        tag.erase();
                    }
                    else
                    {
                        value = tag.substr(0, valEndPos);
                        tag.erase(0, valEndPos+1);
                    }
                }

                mAttributes[key] = value;
            }
        }

        /* BookFormatter */
        Paginator::Pages BookFormatter::markupToWidget(MyGUI::Widget * parent, const std::string & markup, const int pageWidth, const int pageHeight)
        {
            Paginator pag(pageWidth, pageHeight);

            while (parent->getChildCount())
            {
                MyGUI::Gui::getInstance().destroyWidget(parent->getChildAt(0));
            }

            mTextStyle = TextStyle();
            mBlockStyle = BlockStyle();

            MyGUI::Widget * paper = parent->createWidget<MyGUI::Widget>("Widget", MyGUI::IntCoord(0, 0, pag.getPageWidth(), pag.getPageHeight()), MyGUI::Align::Left | MyGUI::Align::Top);
            paper->setNeedMouseFocus(false);

            BookTextParser parser(markup);

            bool brBeforeLastTag = false;
            bool isPrevImg = false;
            for (;;)
            {
                BookTextParser::Events event = parser.next();
                if (event == BookTextParser::Event_BrTag || event == BookTextParser::Event_PTag)
                    continue;

                std::string plainText = parser.getReadyText();

                // for cases when linebreaks are used to cause a shift to the next page
                // if the split text block ends in an empty line, proceeding text block(s) should have leading empty lines removed
                if (pag.getIgnoreLeadingEmptyLines())
                {
                    while (!plainText.empty())
                    {
                        if (plainText[0] == '\n')
                            plainText.erase(plainText.begin());
                        else
                        {
                            pag.setIgnoreLeadingEmptyLines(false);
                            break;
                        }
                    }
                }

                if (plainText.empty())
                    brBeforeLastTag = true;
                else
                {
                    // Each block of text (between two tags / boundary and tag) will be displayed in a separate editbox widget,
                    // which means an additional linebreak will be created between them.
                    // ^ This is not what vanilla MW assumes, so we must deal with line breaks around tags appropriately.
                    bool brAtStart = (plainText[0] == '\n');
                    bool brAtEnd = (plainText[plainText.size()-1] == '\n');

                    if (brAtStart && !brBeforeLastTag && !isPrevImg)
                        plainText.erase(plainText.begin());

                    if (plainText.size() && brAtEnd)
                        plainText.erase(plainText.end()-1);

                    if (!plainText.empty() || brBeforeLastTag || isPrevImg)
                    {
                        TextElement elem(paper, pag, mBlockStyle,
                                         mTextStyle, plainText);
                        elem.paginate();
                    }

                    brBeforeLastTag = brAtEnd;
                }

                if (event == BookTextParser::Event_EOF)
                    break;

                isPrevImg = (event == BookTextParser::Event_ImgTag);

                switch (event)
                {
                    case BookTextParser::Event_ImgTag:
                    {
                        const BookTextParser::Attributes & attr = parser.getAttributes();

                        if (attr.find("src") == attr.end() || attr.find("width") == attr.end() || attr.find("height") == attr.end())
                            continue;

                        std::string src = attr.at("src");
                        int width = MyGUI::utility::parseInt(attr.at("width"));
                        int height = MyGUI::utility::parseInt(attr.at("height"));

                        bool exists;
                        std::string correctedSrc = MWBase::Environment::get().getWindowManager()->correctBookartPath(src, width, height, &exists);

                        if (!exists)
                        {
                            Log(Debug::Warning) << "Warning: Could not find \"" << src << "\" referenced by an <img> tag.";
                            break;
                        }

                        pag.setIgnoreLeadingEmptyLines(false);

                        ImageElement elem(paper, pag, mBlockStyle,
                                          correctedSrc, width, height);
                        elem.paginate();
                        break;
                    }
                    case BookTextParser::Event_FontTag:
                        if (parser.isClosingTag())
                            resetFontProperties();
                        else
                            handleFont(parser.getAttributes());
                        break;
                    case BookTextParser::Event_DivTag:
                        handleDiv(parser.getAttributes());
                        break;
                    default:
                        break;
                }
            }

            // insert last page
            if (pag.getStartTop() != pag.getCurrentTop())
                pag << Paginator::Page(pag.getStartTop(), pag.getStartTop() + pag.getPageHeight());

            paper->setSize(paper->getWidth(), pag.getCurrentTop());

            return pag.getPages();
        }

        Paginator::Pages BookFormatter::markupToWidget(MyGUI::Widget * parent, const std::string & markup)
        {
            return markupToWidget(parent, markup, parent->getWidth(), parent->getHeight());
        }

        void BookFormatter::resetFontProperties()
        {
            mTextStyle = TextStyle();
        }

        void BookFormatter::handleDiv(const BookTextParser::Attributes & attr)
        {
            if (attr.find("align") == attr.end())
                return;

            std::string align = attr.at("align");

            if (Misc::StringUtils::ciEqual(align, "center"))
                mBlockStyle.mAlign = MyGUI::Align::HCenter;
            else if (Misc::StringUtils::ciEqual(align, "left"))
                mBlockStyle.mAlign = MyGUI::Align::Left;
            else if (Misc::StringUtils::ciEqual(align, "right"))
                mBlockStyle.mAlign = MyGUI::Align::Right;
        }

        void BookFormatter::handleFont(const BookTextParser::Attributes & attr)
        {
            if (attr.find("color") != attr.end())
            {
                unsigned int color;
                std::stringstream ss;
                ss << attr.at("color");
                ss >> std::hex >> color;

                mTextStyle.mColour = MyGUI::Colour(
                    (color>>16 & 0xFF) / 255.f,
                    (color>>8 & 0xFF) / 255.f,
                    (color & 0xFF) / 255.f);
            }
            if (attr.find("face") != attr.end())
            {
                std::string face = attr.at("face");
                mTextStyle.mFont = "Journalbook "+face;
            }
            if (attr.find("size") != attr.end())
            {
                /// \todo
            }
        }

        /* GraphicElement */
        GraphicElement::GraphicElement(MyGUI::Widget * parent, Paginator & pag, const BlockStyle & blockStyle)
            : mParent(parent), mPaginator(pag), mBlockStyle(blockStyle)
        {
        }

        void GraphicElement::paginate()
        {
            int newTop = mPaginator.getCurrentTop() + getHeight();
            while (newTop-mPaginator.getStartTop() > mPaginator.getPageHeight())
            {
                int newStartTop = pageSplit();
                mPaginator << Paginator::Page(mPaginator.getStartTop(), newStartTop);
                mPaginator.setStartTop(newStartTop);
            }

            mPaginator.setCurrentTop(newTop);
        }

        int GraphicElement::pageSplit()
        {
            return mPaginator.getStartTop() + mPaginator.getPageHeight();
        }

        /* TextElement */
        TextElement::TextElement(MyGUI::Widget * parent, Paginator & pag, const BlockStyle & blockStyle,
                                 const TextStyle & textStyle, const std::string & text)
            : GraphicElement(parent, pag, blockStyle),
              mTextStyle(textStyle)
        {
            Gui::EditBox* box = parent->createWidget<Gui::EditBox>("NormalText",
                MyGUI::IntCoord(0, pag.getCurrentTop(), pag.getPageWidth(), 0), MyGUI::Align::Left | MyGUI::Align::Top,
                parent->getName() + MyGUI::utility::toString(parent->getChildCount()));
            box->setEditStatic(true);
            box->setEditMultiLine(true);
            box->setEditWordWrap(true);
            box->setNeedMouseFocus(false);
            box->setNeedKeyFocus(false);
            box->setMaxTextLength(text.size());
            box->setTextAlign(mBlockStyle.mAlign);
            box->setTextColour(mTextStyle.mColour);
            box->setFontName(mTextStyle.mFont);
            box->setCaption(MyGUI::TextIterator::toTagsString(text));
            box->setSize(box->getSize().width, box->getTextSize().height);
            mEditBox = box;
        }

        int TextElement::getHeight()
        {
            return mEditBox->getTextSize().height;
        }

        int TextElement::pageSplit()
        {
            // split lines
            const int lineHeight = MWBase::Environment::get().getWindowManager()->getFontHeight();
            unsigned int lastLine = (mPaginator.getStartTop() + mPaginator.getPageHeight() - mPaginator.getCurrentTop());
            if (lineHeight > 0)
                lastLine /= lineHeight;
            int ret = mPaginator.getCurrentTop() + lastLine * lineHeight;

            // first empty lines that would go to the next page should be ignored
            mPaginator.setIgnoreLeadingEmptyLines(true);

            const MyGUI::VectorLineInfo & lines = mEditBox->getSubWidgetText()->castType<MyGUI::EditText>()->getLineInfo();
            for (unsigned int i = lastLine; i < lines.size(); ++i)
            {
                if (lines[i].width == 0)
                    ret += lineHeight;
                else
                {
                    mPaginator.setIgnoreLeadingEmptyLines(false);
                    break;
                }
            }
            return ret;
        }

        /* ImageElement */
        ImageElement::ImageElement(MyGUI::Widget * parent, Paginator & pag, const BlockStyle & blockStyle,
                                   const std::string & src, int width, int height)
            : GraphicElement(parent, pag, blockStyle),
              mImageHeight(height)
        {
            int left = 0;
            if (mBlockStyle.mAlign.isHCenter())
                left += (pag.getPageWidth() - width) / 2;
            else if (mBlockStyle.mAlign.isLeft())
                left = 0;
            else if (mBlockStyle.mAlign.isRight())
                left += pag.getPageWidth() - width;

            mImageBox = parent->createWidget<MyGUI::ImageBox> ("ImageBox",
                MyGUI::IntCoord(left, pag.getCurrentTop(), width, mImageHeight), MyGUI::Align::Left | MyGUI::Align::Top,
                parent->getName() + MyGUI::utility::toString(parent->getChildCount()));

            mImageBox->setImageTexture(src);
            mImageBox->setProperty("NeedMouse", "false");
        }

        int ImageElement::getHeight()
        {
            return mImageHeight;
        }

        int ImageElement::pageSplit()
        {
            // if the image is larger than the page, fall back to the default pageSplit implementation
            if (mImageHeight > mPaginator.getPageHeight())
                return GraphicElement::pageSplit();
            return mPaginator.getCurrentTop();
        }
    }