aboutsummaryrefslogtreecommitdiff
path: root/src/renderers/geminirenderer.cpp
blob: be364a0298f393c3fb1efc5499fde585673177b5 (plain) (blame)
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
#include "geminirenderer.hpp"
#include "renderhelpers.hpp"

#include <QTextList>
#include <QTextBlock>
#include <QList>
#include <QStringList>
#include <QDebug>
#include <QTextTable>
#include <QRegularExpression>

#include "kristall.hpp"

#include "textstyleinstance.hpp"

static QByteArray trim_whitespace(const QByteArray &items)
{
    int start = 0;
    while (start < items.size() and isspace(items.at(start)))
    {
        start += 1;
    }
    int end = items.size() - 1;
    while (end > 0 and isspace(items.at(end)))
    {
        end -= 1;
    }
    return items.mid(start, end - start + 1);
}

static void insertText(QTextCursor&, const QByteArray&, const QTextCharFormat&);

std::unique_ptr<QTextDocument> GeminiRenderer::render(
        const QByteArray &input,
        QUrl const &root_url,
        DocumentStyle const & themed_style,
        DocumentOutlineModel &outline,
        QString & page_title)
{
    TextStyleInstance text_style { themed_style };

    std::unique_ptr<QTextDocument> result = std::make_unique<QTextDocument>();
    renderhelpers::setPageMargins(result.get(), themed_style.margin_h, themed_style.margin_v);
    result->setIndentWidth(themed_style.indent_size);

    QTextCursor cursor{result.get()};

    bool verbatim = false;
    QTextList *current_list = nullptr;
    bool blockquote = false;

    bool centre_first_h1 = themed_style.centre_h1;

    QTextCharFormat preformatted_fmt = text_style.preformatted;

    outline.beginBuild();

    int anchor_id = 0;

    auto unique_anchor_name = [&]() -> QString {
        return QString("auto-title-%1").arg(++anchor_id);
    };

    QList<QByteArray> lines = input.split('\n');
    for (auto &line : lines)
    {
        line.replace("\r", "");

        if (verbatim)
        {
            if (line.startsWith("```"))
            {
                // Set the last line of the preformatted block to have
                // standard line height.
                QTextBlockFormat fmt = text_style.preformatted_format;
                fmt.setLineHeight(themed_style.line_height_p, QTextBlockFormat::LineDistanceHeight);
                cursor.movePosition(QTextCursor::PreviousBlock);
                cursor.setBlockFormat(fmt);

                cursor.movePosition(QTextCursor::NextBlock);
                cursor.setBlockFormat(text_style.standard_format);
                verbatim = false;
            }
            else
            {
                cursor.setBlockFormat(text_style.preformatted_format);
                renderhelpers::renderEscapeCodes(line, preformatted_fmt, text_style.preformatted, cursor);
                cursor.insertText("\n", text_style.preformatted);
            }

            continue;
        }

        // List item
        if (line.startsWith("* "))
        {
            if (current_list == nullptr)
            {
                cursor.deletePreviousChar();
                cursor.insertBlock();
                cursor.setBlockFormat(text_style.standard_format);
                current_list = cursor.createList(text_style.list_format);
            }
            else
            {
                cursor.insertBlock();
            }

            renderhelpers::replace_quotes(line);
            insertText(cursor, trim_whitespace(line.mid(1)), text_style.standard);
            continue;
        }

        // End of list
        if (current_list != nullptr)
        {
            cursor.insertBlock();
            cursor.setBlockFormat(text_style.standard_format);
        }
        current_list = nullptr;

        // Block quote
        if(line.startsWith(">"))
        {
            if(!blockquote)
            {
                // Start blockquote
                QTextTable *table = cursor.insertTable(1, 1, text_style.blockquote_tableformat);
                cursor.setBlockFormat(text_style.blockquote_format);
                QTextTableCell cell = table->cellAt(0, 0);
                cell.setFormat(text_style.blockquote);
                blockquote = true;
            }

            renderhelpers::replace_quotes(line);
            insertText(cursor, trim_whitespace(line.mid(1)), text_style.blockquote);
            cursor.insertText("\n", text_style.standard);
            continue;
        }

        // End of blockquote
        if (blockquote)
        {
            cursor.deletePreviousChar();
            cursor.movePosition(QTextCursor::NextBlock);
            cursor.setBlockFormat(text_style.standard_format);
        }
        blockquote = false;

        // Headings, etc.
        if (line.startsWith("###"))
        {
            auto heading = trim_whitespace(line.mid(3));

            auto id = unique_anchor_name();
            auto fmt = text_style.standard_h3;
            fmt.setAnchor(true);
            fmt.setAnchorNames(QStringList { id });

            outline.appendH3(heading, id);

            cursor.setBlockFormat(text_style.heading_format);
            insertText(cursor, renderhelpers::replace_quotes(heading), fmt);
            cursor.insertText("\n", text_style.standard);
        }
        else if (line.startsWith("##"))
        {
            auto heading = trim_whitespace(line.mid(2));

            auto id = unique_anchor_name();
            auto fmt = text_style.standard_h2;
            fmt.setAnchor(true);
            fmt.setAnchorNames(QStringList { id });

            outline.appendH2(heading, id);

            cursor.setBlockFormat(text_style.heading_format);
            insertText(cursor, renderhelpers::replace_quotes(heading), fmt);
            cursor.insertText("\n", text_style.standard);
        }
        else if (line.startsWith("#"))
        {
            auto heading = trim_whitespace(line.mid(1));

            auto id = unique_anchor_name();
            auto fmt = text_style.standard_h1;
            fmt.setAnchor(true);
            fmt.setAnchorNames(QStringList { id });

            outline.appendH1(heading, id);

            // Use first heading as the page's title.
            if (page_title.isEmpty())
            {
                    page_title = heading;
            }

            // Centre the first heading. We can't use the above code block
            // for this because it doesn't get run on every re-render of the page
            if (centre_first_h1)
            {
                auto f = text_style.heading_format;
                f.setAlignment(Qt::AlignCenter);
                cursor.setBlockFormat(f);
                centre_first_h1 = false;
            }
            else
            {
                cursor.setBlockFormat(text_style.heading_format);
            }

            insertText(cursor, renderhelpers::replace_quotes(heading), fmt);
            cursor.insertText("\n", text_style.standard);
        }
        else if (line.startsWith("=>"))
        {
            auto const part = line.mid(2).trimmed();

            QByteArray link, title;

            int index = -1;
            for (int i = 0; i < part.size(); i++)
            {
                if (isspace(part[i]))
                {
                    index = i;
                    break;
                }
            }

            if (index > 0)
            {
                link = trim_whitespace(part.mid(0, index));
                title = trim_whitespace(part.mid(index + 1));
            }
            else
            {
                link = trim_whitespace(part);
                title = trim_whitespace(part);
            }
            renderhelpers::replace_quotes(title);

            auto local_url = QUrl(link);

            // Makes relative URLs with scheme provided (e.g gemini:///relative) work
            // From RFC 1630: "If the scheme parts are different, the whole absolute URI must be given"
            // therefor the schemes must be same for this to be allowed.
            if (local_url.scheme() == root_url.scheme() &&
                local_url.authority().isEmpty() &&
                local_url.scheme() != "about" &&
                local_url.scheme() != "file")
            {
                // qDebug() << "Adjusting local url: " << local_url;
                local_url = local_url.adjusted(QUrl::RemoveScheme | QUrl::RemoveAuthority);
            }
            auto absolute_url = root_url.resolved(local_url);

            // qDebug() << link << title;

            auto fmt = text_style.standard_link;

            QString prefix;
            if (absolute_url.host() == root_url.host())
            {
                prefix = themed_style.internal_link_prefix;
                fmt = text_style.standard_link;
            }
            else
            {
                prefix = themed_style.external_link_prefix;
                fmt = text_style.external_link;
            }

            QString suffix = "";
            if (absolute_url.scheme() != root_url.scheme())
            {
                if(absolute_url.scheme() != "kristall+ctrl") {
                    suffix = " [" + absolute_url.scheme().toUpper() + "]";
                    fmt = text_style.cross_protocol_link;
                }
            }

            fmt.setAnchor(true);
            fmt.setAnchorHref(absolute_url.toString());
            cursor.setBlockFormat(text_style.link_format);
            insertText(cursor, (prefix + title + suffix).toUtf8(), fmt);
            cursor.insertText("\n", text_style.standard);
        }
        else if (line.startsWith("```"))
        {
            verbatim = true;
            preformatted_fmt = text_style.preformatted;
        }
        else
        {
            cursor.setBlockFormat(text_style.standard_format);

            renderhelpers::replace_quotes(line);
            insertText(cursor, line, text_style.standard);
            cursor.insertText("\n", text_style.standard);
        }
    }

    outline.endBuild();
    return result;
}

/*
 * Handles all the fancy text highlighting.
 */
static void insertText(QTextCursor &cursor, const QByteArray &line,
    const QTextCharFormat &format)
{
    if (line.isEmpty() ||

        // Render text normally if text decoration is disabled.
        !kristall::globals().options.enable_text_decoration ||

        // Render lines not containing asterisks/underscores normally.
        // This actually helps reduce the small overhead on large pages to
        // being almost negligable
        (!line.contains("*") && !line.contains("_")))
    {
        // Empty lines must be in standard format.
        cursor.insertText(line, format);
        return;
    }

    // Easier to work on this as an array of QChars
    QString text(line);

    // Whether to hide formatting codes (*, and _). This option
    // is mainly here so that the code which strips these is
    // more understandable.
    static const bool HIDE_FORMATS = true;

    // The first thing we do is convert double-asterisk bolding to single-asterisk.
    // This makes it A LOT easier to bold these things.
    //
    // This is done using this regex. In a simpler, pseudo form, it can be written as:
    // (punctuation/whitespace/line-begin)+\*\*(bolded text)\*\*(punctuation/whitespace/EOL)
    // Just stare at it a bit and you might figure out how it works...
    QRegularExpression BOLD_DBL_REGEX
        = QRegularExpression(R"((^|[\s.,!?[\]()\\-])+\*\*([^\*\s]+[^\*]+[^\*\s]+)\*\*($|[\s.,!?[\]()\\-]))");
    text.replace(BOLD_DBL_REGEX,  QString(R"(\1*\2*\3)"));

    QTextCharFormat fmt = format;
    bool bold = false, underline = false;
    bool was_bold = false, was_underline = false;
    int last = 0;

    // Used to prepare the format before actually drawing the text.
    auto format_text = [&bold, &underline, &was_bold, &was_underline, &last, &text, &fmt](int i) -> QString
    {
        // Makes sure that bold/underline text only gets printed
        // if it has a matching * or _.
        if (bold && !text.mid(i, text.length() - i).contains("*"))
            bold = false;
        if (underline && !text.mid(i, text.length() - i).contains("_"))
            underline = false;

        // Sets format to bold/underline as necessary.
        auto f = fmt.font();
        f.setBold(bold);
        fmt.setFont(f);
        fmt.setUnderlineStyle(underline ?
            QTextCharFormat::SingleUnderline : QTextCharFormat::NoUnderline);

        // Remove formats
        QString span = text.mid(last, i - last);
        if (HIDE_FORMATS &&
            span.length() > 1 &&
            (((bold || was_bold) && span.startsWith("*")) ||
             ((underline || was_underline) && span.startsWith("_"))))
        {
            span = span.mid(1, span.length() - 1);
        }

        return span;
    };

    for (int i = 0; i < text.length(); ++i)
    {
        if (text[i] == '*')
        {
            // Format and insert the text.
            cursor.insertText(format_text(i), fmt);

            // 'Toggle' bold state.
            if (was_bold) was_bold = false;
            if (bold) {
                was_bold = true;
                bold = false;
            } else {
                // Only start bold formatting if this looks like bold formatting:
                // * Previous char must be either whitespace, nothing
                // * Next char must not be: whitespace, comma, full-stop, asterisk, or underscore.
                if ((i == 0 || text[i - 1].isSpace()) &&
                    (i + 1) < text.length() &&
                    !text[i + 1].isSpace() &&
                    text[i + 1] != ',' &&
                    text[i + 1] != '.' &&
                    text[i + 1] != '*' &&
                    text[i + 1] != '_')
                {
                    bold = true;
                }
            }

            last = i;
        }
        else if (text[i] == '_')
        {
            // Insert the text
            cursor.insertText(format_text(i), fmt);

            // 'Toggle' underline state.
            if (was_underline) was_underline = false;
            if (underline) {
                was_underline = true;
                underline = false;
            } else {
                // Only start underline formatting if it looks like an underline.
                // * Previous char must be either whitespace or nothing
                // * Next char must not be: whitespace, comma, full-stop, asterisk, or underscore.
                if ((i == 0 || text[i - 1].isSpace()) &&
                    (i + 1) < text.length() &&
                    !text[i + 1].isSpace() &&
                    text[i + 1] != ',' &&
                    text[i + 1] != '.' &&
                    text[i + 1] != '*' &&
                    text[i + 1] != '_')
                {
                    underline = true;
                }
            }

            last = i;
        }

        if (i == text.length() - 1)
        {
            QString span = text.mid(last, i - last + 1);

            // Skip if the span is just an asterisk/underline
            if (HIDE_FORMATS &&
                ((was_bold && span == "*") ||
                (was_underline && span == "_")))
            {
                break;
            }

            // Strips previous underline/asterisk
            if (HIDE_FORMATS &&
                span.length() > 1 &&
                ((was_bold && span.startsWith("*")) ||
                 (was_underline && span.startsWith("_"))))
            {
                span = span.mid(1, span.length() - 1);
            }

            // Draw ending text normally.
            cursor.insertText(span, format);
            break;
        }
    }
}