summaryrefslogtreecommitdiffstats
path: root/src/widgets/widgets/qtextbrowser.cpp
blob: 3e493903151d7b58c3167b3252fb42b257780a91 (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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtextbrowser.h"
#include "qtextedit_p.h"

#include <qstack.h>
#include <qapplication.h>
#include <private/qapplication_p.h>
#include <qevent.h>
#include <qdesktopwidget.h>
#include <qdebug.h>
#include <qabstracttextdocumentlayout.h>
#include "private/qtextdocumentlayout_p.h"
#if QT_CONFIG(textcodec)
#include <qtextcodec.h>
#endif
#include <qpainter.h>
#include <qdir.h>
#if QT_CONFIG(whatsthis)
#include <qwhatsthis.h>
#endif
#include <qtextobject.h>
#include <qdesktopservices.h>

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcBrowser, "qt.text.browser")

class QTextBrowserPrivate : public QTextEditPrivate
{
    Q_DECLARE_PUBLIC(QTextBrowser)
public:
    inline QTextBrowserPrivate()
        : textOrSourceChanged(false), forceLoadOnSourceChange(false), openExternalLinks(false),
          openLinks(true)
#ifdef QT_KEYPAD_NAVIGATION
        , lastKeypadScrollValue(-1)
#endif
    {}

    void init();

    struct HistoryEntry {
        inline HistoryEntry()
            : hpos(0), vpos(0), focusIndicatorPosition(-1),
              focusIndicatorAnchor(-1) {}
        QUrl url;
        QString title;
        int hpos;
        int vpos;
        int focusIndicatorPosition, focusIndicatorAnchor;
        QTextDocument::ResourceType type = QTextDocument::UnknownResource;
    };

    HistoryEntry history(int i) const
    {
        if (i <= 0)
            if (-i < stack.count())
                return stack[stack.count()+i-1];
            else
                return HistoryEntry();
        else
            if (i <= forwardStack.count())
                return forwardStack[forwardStack.count()-i];
            else
                return HistoryEntry();
    }


    HistoryEntry createHistoryEntry() const;
    void restoreHistoryEntry(const HistoryEntry &entry);

    QStack<HistoryEntry> stack;
    QStack<HistoryEntry> forwardStack;
    QUrl home;
    QUrl currentURL;

    QStringList searchPaths;

    /*flag necessary to give the linkClicked() signal some meaningful
      semantics when somebody connected to it calls setText() or
      setSource() */
    bool textOrSourceChanged;
    bool forceLoadOnSourceChange;

    bool openExternalLinks;
    bool openLinks;

    QTextDocument::ResourceType currentType;

#ifndef QT_NO_CURSOR
    QCursor oldCursor;
#endif

    QString findFile(const QUrl &name) const;

    inline void _q_documentModified()
    {
        textOrSourceChanged = true;
        forceLoadOnSourceChange = !currentURL.path().isEmpty();
    }

    void _q_activateAnchor(const QString &href);
    void _q_highlightLink(const QString &href);

    void setSource(const QUrl &url, QTextDocument::ResourceType type);

    // re-imlemented from QTextEditPrivate
    virtual QUrl resolveUrl(const QUrl &url) const override;
    inline QUrl resolveUrl(const QString &url) const
    { return resolveUrl(QUrl(url)); }

#ifdef QT_KEYPAD_NAVIGATION
    void keypadMove(bool next);
    QTextCursor prevFocus;
    int lastKeypadScrollValue;
#endif
};
Q_DECLARE_TYPEINFO(QTextBrowserPrivate::HistoryEntry, Q_MOVABLE_TYPE);

QString QTextBrowserPrivate::findFile(const QUrl &name) const
{
    QString fileName;
    if (name.scheme() == QLatin1String("qrc")) {
        fileName = QLatin1String(":/") + name.path();
    } else if (name.scheme().isEmpty()) {
        fileName = name.path();
    } else {
#if defined(Q_OS_ANDROID)
        if (name.scheme() == QLatin1String("assets"))
            fileName = QLatin1String("assets:") + name.path();
        else
#endif
            fileName = name.toLocalFile();
    }

    if (fileName.isEmpty())
        return fileName;

    if (QFileInfo(fileName).isAbsolute())
        return fileName;

    for (QString path : qAsConst(searchPaths)) {
        if (!path.endsWith(QLatin1Char('/')))
            path.append(QLatin1Char('/'));
        path.append(fileName);
        if (QFileInfo(path).isReadable())
            return path;
    }

    return fileName;
}

QUrl QTextBrowserPrivate::resolveUrl(const QUrl &url) const
{
    if (!url.isRelative())
        return url;

    // For the second case QUrl can merge "#someanchor" with "foo.html"
    // correctly to "foo.html#someanchor"
    if (!(currentURL.isRelative()
          || (currentURL.scheme() == QLatin1String("file")
              && !QFileInfo(currentURL.toLocalFile()).isAbsolute()))
          || (url.hasFragment() && url.path().isEmpty())) {
        return currentURL.resolved(url);
    }

    // this is our last resort when current url and new url are both relative
    // we try to resolve against the current working directory in the local
    // file system.
    QFileInfo fi(currentURL.toLocalFile());
    if (fi.exists()) {
        return QUrl::fromLocalFile(fi.absolutePath() + QDir::separator()).resolved(url);
    }

    return url;
}

void QTextBrowserPrivate::_q_activateAnchor(const QString &href)
{
    if (href.isEmpty())
        return;
    Q_Q(QTextBrowser);

#ifndef QT_NO_CURSOR
    viewport->setCursor(oldCursor);
#endif

    const QUrl url = resolveUrl(href);

    if (!openLinks) {
        emit q->anchorClicked(url);
        return;
    }

    textOrSourceChanged = false;

#ifndef QT_NO_DESKTOPSERVICES
    bool isFileScheme =
            url.scheme() == QLatin1String("file")
#if defined(Q_OS_ANDROID)
            || url.scheme() == QLatin1String("assets")
#endif
            || url.scheme() == QLatin1String("qrc");
    if ((openExternalLinks && !isFileScheme && !url.isRelative())
        || (url.isRelative() && !currentURL.isRelative() && !isFileScheme)) {
        QDesktopServices::openUrl(url);
        return;
    }
#endif

    emit q->anchorClicked(url);

    if (textOrSourceChanged)
        return;

    q->setSource(url);
}

void QTextBrowserPrivate::_q_highlightLink(const QString &anchor)
{
    Q_Q(QTextBrowser);
    if (anchor.isEmpty()) {
#ifndef QT_NO_CURSOR
        if (viewport->cursor().shape() != Qt::PointingHandCursor)
            oldCursor = viewport->cursor();
        viewport->setCursor(oldCursor);
#endif
        emit q->highlighted(QUrl());
        emit q->highlighted(QString());
    } else {
#ifndef QT_NO_CURSOR
        viewport->setCursor(Qt::PointingHandCursor);
#endif

        const QUrl url = resolveUrl(anchor);
        emit q->highlighted(url);
        // convenience to ease connecting to QStatusBar::showMessage(const QString &)
        emit q->highlighted(url.toString());
    }
}

void QTextBrowserPrivate::setSource(const QUrl &url, QTextDocument::ResourceType type)
{
    Q_Q(QTextBrowser);
#ifndef QT_NO_CURSOR
    if (q->isVisible())
        QGuiApplication::setOverrideCursor(Qt::WaitCursor);
#endif
    textOrSourceChanged = true;

    QString txt;

    bool doSetText = false;

    QUrl currentUrlWithoutFragment = currentURL;
    currentUrlWithoutFragment.setFragment(QString());
    QUrl newUrlWithoutFragment = currentURL.resolved(url);
    newUrlWithoutFragment.setFragment(QString());
    QString fileName = url.fileName();
    if (type == QTextDocument::UnknownResource) {
#if QT_CONFIG(textmarkdownreader)
        if (fileName.endsWith(QLatin1String(".md")) ||
                fileName.endsWith(QLatin1String(".mkd")) ||
                fileName.endsWith(QLatin1String(".markdown")))
            type = QTextDocument::MarkdownResource;
        else
#endif
            type = QTextDocument::HtmlResource;
    }
    currentType = type;

    if (url.isValid()
        && (newUrlWithoutFragment != currentUrlWithoutFragment || forceLoadOnSourceChange)) {
        QVariant data = q->loadResource(type, resolveUrl(url));
        if (data.type() == QVariant::String) {
            txt = data.toString();
        } else if (data.type() == QVariant::ByteArray) {
            if (type == QTextDocument::HtmlResource) {
#if QT_CONFIG(textcodec)
                QByteArray ba = data.toByteArray();
                QTextCodec *codec = Qt::codecForHtml(ba);
                txt = codec->toUnicode(ba);
#else
                txt = data.toString();
#endif
            } else {
                txt = QString::fromUtf8(data.toByteArray());
            }
        }
        if (Q_UNLIKELY(txt.isEmpty()))
            qWarning("QTextBrowser: No document for %s", url.toString().toLatin1().constData());

        if (q->isVisible()) {
            const QStringRef firstTag = txt.leftRef(txt.indexOf(QLatin1Char('>')) + 1);
            if (firstTag.startsWith(QLatin1String("<qt")) && firstTag.contains(QLatin1String("type")) && firstTag.contains(QLatin1String("detail"))) {
#ifndef QT_NO_CURSOR
                QGuiApplication::restoreOverrideCursor();
#endif
#if QT_CONFIG(whatsthis)
                QWhatsThis::showText(QCursor::pos(), txt, q);
#endif
                return;
            }
        }

        currentURL = resolveUrl(url);
        doSetText = true;
    }

    if (!home.isValid())
        home = url;

    if (doSetText) {
        // Setting the base URL helps QTextDocument::resource() to find resources with relative paths.
        // But don't set it unless it contains the document's path, because QTextBrowserPrivate::resolveUrl()
        // can already deal with local files on the filesystem in case the base URL was not set.
        QUrl baseUrl = currentURL.adjusted(QUrl::RemoveFilename);
        if (!baseUrl.path().isEmpty())
            q->document()->setBaseUrl(baseUrl);
        q->document()->setMetaInformation(QTextDocument::DocumentUrl, currentURL.toString());
        qCDebug(lcBrowser) << "loading" << currentURL << "base" << q->document()->baseUrl() << "type" << type << txt.size() << "chars";
#if QT_CONFIG(textmarkdownreader)
        if (type == QTextDocument::MarkdownResource)
            q->QTextEdit::setMarkdown(txt);
        else
#endif
#ifndef QT_NO_TEXTHTMLPARSER
        q->QTextEdit::setHtml(txt);
#else
        q->QTextEdit::setPlainText(txt);
#endif

#ifdef QT_KEYPAD_NAVIGATION
        prevFocus.movePosition(QTextCursor::Start);
#endif
    }

    forceLoadOnSourceChange = false;

    if (!url.fragment().isEmpty()) {
        q->scrollToAnchor(url.fragment());
    } else {
        hbar->setValue(0);
        vbar->setValue(0);
    }
#ifdef QT_KEYPAD_NAVIGATION
    lastKeypadScrollValue = vbar->value();
    emit q->highlighted(QUrl());
    emit q->highlighted(QString());
#endif

#ifndef QT_NO_CURSOR
    if (q->isVisible())
        QGuiApplication::restoreOverrideCursor();
#endif
    emit q->sourceChanged(url);
}

#ifdef QT_KEYPAD_NAVIGATION
void QTextBrowserPrivate::keypadMove(bool next)
{
    Q_Q(QTextBrowser);

    const int height = viewport->height();
    const int overlap = qBound(20, height / 5, 40); // XXX arbitrary, but a good balance
    const int visibleLinkAmount = overlap; // consistent, but maybe not the best choice (?)
    int yOffset = vbar->value();
    int scrollYOffset = qBound(0, next ? yOffset + height - overlap : yOffset - height + overlap, vbar->maximum());

    bool foundNextAnchor = false;
    bool focusIt = false;
    int focusedPos = -1;

    QTextCursor anchorToFocus;

    QRectF viewRect = QRectF(0, yOffset, control->size().width(), height);
    QRectF newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
    QRectF bothViewRects = viewRect.united(newViewRect);

    // If we don't have a previous anchor, pretend that we had the first/last character
    // on the screen selected.
    if (prevFocus.isNull()) {
        if (next)
            prevFocus = control->cursorForPosition(QPointF(0, yOffset));
        else
            prevFocus = control->cursorForPosition(QPointF(control->size().width(), yOffset + height));
    }

    // First, check to see if someone has moved the scroll bars independently
    if (lastKeypadScrollValue != yOffset) {
        // Someone (user or programmatically) has moved us, so we might
        // need to start looking from the current position instead of prevFocus

        bool findOnScreen = true;

        // If prevFocus is on screen at all, we just use it.
        if (prevFocus.hasSelection()) {
            QRectF prevRect = control->selectionRect(prevFocus);
            if (viewRect.intersects(prevRect))
                findOnScreen = false;
        }

        // Otherwise, we find a new anchor that's on screen.
        // Basically, create a cursor with the last/first character
        // on screen
        if (findOnScreen) {
            if (next)
                prevFocus = control->cursorForPosition(QPointF(0, yOffset));
            else
                prevFocus = control->cursorForPosition(QPointF(control->size().width(), yOffset + height));
        }
        foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
    } else if (prevFocus.hasSelection()) {
        // Check the pathological case that the current anchor is higher
        // than the screen, and just scroll through it in that case
        QRectF prevRect = control->selectionRect(prevFocus);
        if ((next && prevRect.bottom() > (yOffset + height)) ||
                (!next && prevRect.top() < yOffset)) {
            anchorToFocus = prevFocus;
            focusedPos = scrollYOffset;
            focusIt = true;
        } else {
            // This is the "normal" case - no scroll bar adjustments, no large anchors,
            // and no wrapping.
            foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
        }
    }

    // If not found yet, see if we need to wrap
    if (!focusIt && !foundNextAnchor) {
        if (next) {
            if (yOffset == vbar->maximum()) {
                prevFocus.movePosition(QTextCursor::Start);
                yOffset = scrollYOffset = 0;

                // Refresh the rectangles
                viewRect = QRectF(0, yOffset, control->size().width(), height);
                newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
                bothViewRects = viewRect.united(newViewRect);
            }
        } else {
            if (yOffset == 0) {
                prevFocus.movePosition(QTextCursor::End);
                yOffset = scrollYOffset = vbar->maximum();

                // Refresh the rectangles
                viewRect = QRectF(0, yOffset, control->size().width(), height);
                newViewRect = QRectF(0, scrollYOffset, control->size().width(), height);
                bothViewRects = viewRect.united(newViewRect);
            }
        }

        // Try looking now
        foundNextAnchor = control->findNextPrevAnchor(prevFocus, next, anchorToFocus);
    }

    // If we did actually find an anchor to use...
    if (foundNextAnchor) {
        QRectF desiredRect = control->selectionRect(anchorToFocus);

        // XXX This is an arbitrary heuristic
        // Decide to focus an anchor if it will be at least be
        // in the middle region of the screen after a scroll.
        // This can result in partial anchors with focus, but
        // insisting on links being completely visible before
        // selecting them causes disparities between links that
        // take up 90% of the screen height and those that take
        // up e.g. 110%
        // Obviously if a link is entirely visible, we still
        // focus it.
        if(bothViewRects.contains(desiredRect)
                || bothViewRects.adjusted(0, visibleLinkAmount, 0, -visibleLinkAmount).intersects(desiredRect)) {
            focusIt = true;

            // We aim to put the new link in the middle of the screen,
            // unless the link is larger than the screen (we just move to
            // display the first page of the link)
            if (desiredRect.height() > height) {
                if (next)
                    focusedPos = (int) desiredRect.top();
                else
                    focusedPos = (int) desiredRect.bottom() - height;
            } else
                focusedPos = (int) ((desiredRect.top() + desiredRect.bottom()) / 2 - (height / 2));

            // and clamp it to make sure we don't skip content.
            if (next)
                focusedPos = qBound(yOffset, focusedPos, scrollYOffset);
            else
                focusedPos = qBound(scrollYOffset, focusedPos, yOffset);
        }
    }

    // If we didn't get a new anchor, check if the old one is still on screen when we scroll
    // Note that big (larger than screen height) anchors also have some handling at the
    // start of this function.
    if (!focusIt && prevFocus.hasSelection()) {
        QRectF desiredRect = control->selectionRect(prevFocus);
        // XXX this may be better off also using the visibleLinkAmount value
        if(newViewRect.intersects(desiredRect)) {
            focusedPos = scrollYOffset;
            focusIt = true;
            anchorToFocus = prevFocus;
        }
    }

    // setTextCursor ensures that the cursor is visible. save & restore
    // the scroll bar values therefore
    const int savedXOffset = hbar->value();

    // Now actually process our decision
    if (focusIt && control->setFocusToAnchor(anchorToFocus)) {
        // Save the focus for next time
        prevFocus = control->textCursor();

        // Scroll
        vbar->setValue(focusedPos);
        lastKeypadScrollValue = focusedPos;
        hbar->setValue(savedXOffset);

        // Ensure that the new selection is highlighted.
        const QString href = control->anchorAtCursor();
        QUrl url = resolveUrl(href);
        emit q->highlighted(url);
        emit q->highlighted(url.toString());
    } else {
        // Scroll
        vbar->setValue(scrollYOffset);
        lastKeypadScrollValue = scrollYOffset;

        // now make sure we don't have a focused anchor
        QTextCursor cursor = control->textCursor();
        cursor.clearSelection();

        control->setTextCursor(cursor);

        hbar->setValue(savedXOffset);
        vbar->setValue(scrollYOffset);

        emit q->highlighted(QUrl());
        emit q->highlighted(QString());
    }
}
#endif

QTextBrowserPrivate::HistoryEntry QTextBrowserPrivate::createHistoryEntry() const
{
    HistoryEntry entry;
    entry.url = q_func()->source();
    entry.type = q_func()->sourceType();
    entry.title = q_func()->documentTitle();
    entry.hpos = hbar->value();
    entry.vpos = vbar->value();

    const QTextCursor cursor = control->textCursor();
    if (control->cursorIsFocusIndicator()
        && cursor.hasSelection()) {

        entry.focusIndicatorPosition = cursor.position();
        entry.focusIndicatorAnchor = cursor.anchor();
    }
    return entry;
}

void QTextBrowserPrivate::restoreHistoryEntry(const HistoryEntry &entry)
{
    setSource(entry.url, entry.type);
    hbar->setValue(entry.hpos);
    vbar->setValue(entry.vpos);
    if (entry.focusIndicatorAnchor != -1 && entry.focusIndicatorPosition != -1) {
        QTextCursor cursor(control->document());
        cursor.setPosition(entry.focusIndicatorAnchor);
        cursor.setPosition(entry.focusIndicatorPosition, QTextCursor::KeepAnchor);
        control->setTextCursor(cursor);
        control->setCursorIsFocusIndicator(true);
    }
#ifdef QT_KEYPAD_NAVIGATION
    lastKeypadScrollValue = vbar->value();
    prevFocus = control->textCursor();

    Q_Q(QTextBrowser);
    const QString href = prevFocus.charFormat().anchorHref();
    QUrl url = resolveUrl(href);
    emit q->highlighted(url);
    emit q->highlighted(url.toString());
#endif
}

/*!
    \class QTextBrowser
    \brief The QTextBrowser class provides a rich text browser with hypertext navigation.

    \ingroup richtext-processing
    \inmodule QtWidgets

    This class extends QTextEdit (in read-only mode), adding some navigation
    functionality so that users can follow links in hypertext documents.

    If you want to provide your users with an editable rich text editor,
    use QTextEdit. If you want a text browser without hypertext navigation
    use QTextEdit, and use QTextEdit::setReadOnly() to disable
    editing. If you just need to display a small piece of rich text
    use QLabel.

    \section1 Document Source and Contents

    The contents of QTextEdit are set with setHtml() or setPlainText(),
    but QTextBrowser also implements the setSource() function, making it
    possible to use a named document as the source text. The name is looked
    up in a list of search paths and in the directory of the current document
    factory.

    If a document name ends with
    an anchor (for example, "\c #anchor"), the text browser automatically
    scrolls to that position (using scrollToAnchor()). When the user clicks
    on a hyperlink, the browser will call setSource() itself with the link's
    \c href value as argument. You can track the current source by connecting
    to the sourceChanged() signal.

    \section1 Navigation

    QTextBrowser provides backward() and forward() slots which you can
    use to implement Back and Forward buttons. The home() slot sets
    the text to the very first document displayed. The anchorClicked()
    signal is emitted when the user clicks an anchor. To override the
    default navigation behavior of the browser, call the setSource()
    function to supply new document text in a slot connected to this
    signal.

    If you want to load documents stored in the Qt resource system use
    \c{qrc} as the scheme in the URL to load. For example, for the document
    resource path \c{:/docs/index.html} use \c{qrc:/docs/index.html} as
    the URL with setSource().

    \sa QTextEdit, QTextDocument
*/

/*!
    \property QTextBrowser::modified
    \brief whether the contents of the text browser have been modified
*/

/*!
    \property QTextBrowser::readOnly
    \brief whether the text browser is read-only

    By default, this property is \c true.
*/

/*!
    \property QTextBrowser::undoRedoEnabled
    \brief whether the text browser supports undo/redo operations

    By default, this property is \c false.
*/

void QTextBrowserPrivate::init()
{
    Q_Q(QTextBrowser);
    control->setTextInteractionFlags(Qt::TextBrowserInteraction);
#ifndef QT_NO_CURSOR
    viewport->setCursor(oldCursor);
#endif
    q->setAttribute(Qt::WA_InputMethodEnabled, !q->isReadOnly());
    q->setUndoRedoEnabled(false);
    viewport->setMouseTracking(true);
    QObject::connect(q->document(), SIGNAL(contentsChanged()), q, SLOT(_q_documentModified()));
    QObject::connect(control, SIGNAL(linkActivated(QString)),
                     q, SLOT(_q_activateAnchor(QString)));
    QObject::connect(control, SIGNAL(linkHovered(QString)),
                     q, SLOT(_q_highlightLink(QString)));
}

/*!
    Constructs an empty QTextBrowser with parent \a parent.
*/
QTextBrowser::QTextBrowser(QWidget *parent)
    : QTextEdit(*new QTextBrowserPrivate, parent)
{
    Q_D(QTextBrowser);
    d->init();
}


/*!
    \internal
*/
QTextBrowser::~QTextBrowser()
{
}

/*!
    \property QTextBrowser::source
    \brief the name of the displayed document.

    This is a an invalid url if no document is displayed or if the
    source is unknown.

    When setting this property QTextBrowser tries to find a document
    with the specified name in the paths of the searchPaths property
    and directory of the current source, unless the value is an absolute
    file path. It also checks for optional anchors and scrolls the document
    accordingly

    If the first tag in the document is \c{<qt type=detail>}, the
    document is displayed as a popup rather than as new document in
    the browser window itself. Otherwise, the document is displayed
    normally in the text browser with the text set to the contents of
    the named document with \l QTextDocument::setHtml() or
    \l QTextDocument::setMarkdown(), depending on whether the filename ends
    with any of the known Markdown file extensions.

    If you would like to avoid automatic type detection
    and specify the type explicitly, call setSource() rather than
    setting this property.

    By default, this property contains an empty URL.
*/
QUrl QTextBrowser::source() const
{
    Q_D(const QTextBrowser);
    if (d->stack.isEmpty())
        return QUrl();
    else
        return d->stack.top().url;
}

/*!
    \property QTextBrowser::sourceType
    \brief the type of the displayed document

    This is QTextDocument::UnknownResource if no document is displayed or if
    the type of the source is unknown. Otherwise it holds the type that was
    detected, or the type that was specified when setSource() was called.
*/
QTextDocument::ResourceType QTextBrowser::sourceType() const
{
    Q_D(const QTextBrowser);
    if (d->stack.isEmpty())
        return QTextDocument::UnknownResource;
    else
        return d->stack.top().type;
}

/*!
    \property QTextBrowser::searchPaths
    \brief the search paths used by the text browser to find supporting
    content

    QTextBrowser uses this list to locate images and documents.

    By default, this property contains an empty string list.
*/

QStringList QTextBrowser::searchPaths() const
{
    Q_D(const QTextBrowser);
    return d->searchPaths;
}

void QTextBrowser::setSearchPaths(const QStringList &paths)
{
    Q_D(QTextBrowser);
    d->searchPaths = paths;
}

/*!
    Reloads the current set source.
*/
void QTextBrowser::reload()
{
    Q_D(QTextBrowser);
    QUrl s = d->currentURL;
    d->currentURL = QUrl();
    setSource(s, d->currentType);
}

#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
void QTextBrowser::setSource(const QUrl &url)
{
    setSource(url, QTextDocument::UnknownResource);
}
#endif

/*!
    Attempts to load the document at the given \a url with the specified \a type.

    If \a type is \l {QTextDocument::ResourceType::UnknownResource}{UnknownResource}
    (the default), the document type will be detected: that is, if the url ends
    with an extension of \c{.md}, \c{.mkd} or \c{.markdown}, the document will be
    loaded via \l QTextDocument::setMarkdown(); otherwise it will be loaded via
    \l QTextDocument::setHtml(). This detection can be bypassed by specifying
    the \a type explicitly.
*/
void QTextBrowser::setSource(const QUrl &url, QTextDocument::ResourceType type)
{
    doSetSource(url, type);
}

#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
/*!
    Attempts to load the document at the given \a url with the specified \a type.

    setSource() calls doSetSource.  In Qt 5, setSource(const QUrl &url) was virtual.
    In Qt 6, doSetSource() is virtual instead, so that it can be overridden in subclasses.
*/
#endif
void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type)
{
    Q_D(QTextBrowser);

    const QTextBrowserPrivate::HistoryEntry historyEntry = d->createHistoryEntry();

    d->setSource(url, type);

    if (!url.isValid())
        return;

    // the same url you are already watching?
    if (!d->stack.isEmpty() && d->stack.top().url == url)
        return;

    if (!d->stack.isEmpty())
        d->stack.top() = historyEntry;

    QTextBrowserPrivate::HistoryEntry entry;
    entry.url = url;
    entry.type = d->currentType;
    entry.title = documentTitle();
    entry.hpos = 0;
    entry.vpos = 0;
    d->stack.push(entry);

    emit backwardAvailable(d->stack.count() > 1);

    if (!d->forwardStack.isEmpty() && d->forwardStack.top().url == url) {
        d->forwardStack.pop();
        emit forwardAvailable(d->forwardStack.count() > 0);
    } else {
        d->forwardStack.clear();
        emit forwardAvailable(false);
    }

    emit historyChanged();
}

/*!
    \fn void QTextBrowser::backwardAvailable(bool available)

    This signal is emitted when the availability of backward()
    changes. \a available is false when the user is at home();
    otherwise it is true.
*/

/*!
    \fn void QTextBrowser::forwardAvailable(bool available)

    This signal is emitted when the availability of forward() changes.
    \a available is true after the user navigates backward() and false
    when the user navigates or goes forward().
*/

/*!
    \fn void QTextBrowser::historyChanged()
    \since 4.4

    This signal is emitted when the history changes.

    \sa historyTitle(), historyUrl()
*/

/*!
    \fn void QTextBrowser::sourceChanged(const QUrl &src)

    This signal is emitted when the source has changed, \a src
    being the new source.

    Source changes happen both programmatically when calling
    setSource(), forward(), backword() or home() or when the user
    clicks on links or presses the equivalent key sequences.
*/

/*!  \fn void QTextBrowser::highlighted(const QUrl &link)

    This signal is emitted when the user has selected but not
    activated an anchor in the document. The URL referred to by the
    anchor is passed in \a link.
*/

/*!  \fn void QTextBrowser::highlighted(const QString &link)
     \overload

     Convenience signal that allows connecting to a slot
     that takes just a QString, like for example QStatusBar's
     message().
*/


/*!
    \fn void QTextBrowser::anchorClicked(const QUrl &link)

    This signal is emitted when the user clicks an anchor. The
    URL referred to by the anchor is passed in \a link.

    Note that the browser will automatically handle navigation to the
    location specified by \a link unless the openLinks property
    is set to false or you call setSource() in a slot connected.
    This mechanism is used to override the default navigation features of the browser.
*/

/*!
    Changes the document displayed to the previous document in the
    list of documents built by navigating links. Does nothing if there
    is no previous document.

    \sa forward(), backwardAvailable()
*/
void QTextBrowser::backward()
{
    Q_D(QTextBrowser);
    if (d->stack.count() <= 1)
        return;

    // Update the history entry
    d->forwardStack.push(d->createHistoryEntry());
    d->stack.pop(); // throw away the old version of the current entry
    d->restoreHistoryEntry(d->stack.top()); // previous entry
    emit backwardAvailable(d->stack.count() > 1);
    emit forwardAvailable(true);
    emit historyChanged();
}

/*!
    Changes the document displayed to the next document in the list of
    documents built by navigating links. Does nothing if there is no
    next document.

    \sa backward(), forwardAvailable()
*/
void QTextBrowser::forward()
{
    Q_D(QTextBrowser);
    if (d->forwardStack.isEmpty())
        return;
    if (!d->stack.isEmpty()) {
        // Update the history entry
        d->stack.top() = d->createHistoryEntry();
    }
    d->stack.push(d->forwardStack.pop());
    d->restoreHistoryEntry(d->stack.top());
    emit backwardAvailable(true);
    emit forwardAvailable(!d->forwardStack.isEmpty());
    emit historyChanged();
}

/*!
    Changes the document displayed to be the first document from
    the history.
*/
void QTextBrowser::home()
{
    Q_D(QTextBrowser);
    if (d->home.isValid())
        setSource(d->home);
}

/*!
    The event \a ev is used to provide the following keyboard shortcuts:
    \table
    \header \li Keypress            \li Action
    \row \li Alt+Left Arrow  \li \l backward()
    \row \li Alt+Right Arrow \li \l forward()
    \row \li Alt+Up Arrow    \li \l home()
    \endtable
*/
void QTextBrowser::keyPressEvent(QKeyEvent *ev)
{
#ifdef QT_KEYPAD_NAVIGATION
    Q_D(QTextBrowser);
    switch (ev->key()) {
    case Qt::Key_Select:
        if (QApplicationPrivate::keypadNavigationEnabled()) {
            if (!hasEditFocus()) {
                setEditFocus(true);
                return;
            } else {
                QTextCursor cursor = d->control->textCursor();
                QTextCharFormat charFmt = cursor.charFormat();
                if (!cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
                    ev->accept();
                    return;
                }
            }
        }
        break;
    case Qt::Key_Back:
        if (QApplicationPrivate::keypadNavigationEnabled()) {
            if (hasEditFocus()) {
                setEditFocus(false);
                ev->accept();
                return;
            }
        }
        QTextEdit::keyPressEvent(ev);
        return;
    default:
        if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
            ev->ignore();
            return;
        }
    }
#endif

    if (ev->modifiers() & Qt::AltModifier) {
        switch (ev->key()) {
        case Qt::Key_Right:
            forward();
            ev->accept();
            return;
        case Qt::Key_Left:
            backward();
            ev->accept();
            return;
        case Qt::Key_Up:
            home();
            ev->accept();
            return;
        }
    }
#ifdef QT_KEYPAD_NAVIGATION
    else {
        if (ev->key() == Qt::Key_Up) {
            d->keypadMove(false);
            return;
        } else if (ev->key() == Qt::Key_Down) {
            d->keypadMove(true);
            return;
        }
    }
#endif
    QTextEdit::keyPressEvent(ev);
}

/*!
    \reimp
*/
void QTextBrowser::mouseMoveEvent(QMouseEvent *e)
{
    QTextEdit::mouseMoveEvent(e);
}

/*!
    \reimp
*/
void QTextBrowser::mousePressEvent(QMouseEvent *e)
{
    QTextEdit::mousePressEvent(e);
}

/*!
    \reimp
*/
void QTextBrowser::mouseReleaseEvent(QMouseEvent *e)
{
    QTextEdit::mouseReleaseEvent(e);
}

/*!
    \reimp
*/
void QTextBrowser::focusOutEvent(QFocusEvent *ev)
{
#ifndef QT_NO_CURSOR
    Q_D(QTextBrowser);
    d->viewport->setCursor((!(d->control->textInteractionFlags() & Qt::TextEditable)) ? d->oldCursor : Qt::IBeamCursor);
#endif
    QTextEdit::focusOutEvent(ev);
}

/*!
    \reimp
*/
bool QTextBrowser::focusNextPrevChild(bool next)
{
    Q_D(QTextBrowser);
    if (d->control->setFocusToNextOrPreviousAnchor(next)) {
#ifdef QT_KEYPAD_NAVIGATION
        // Might need to synthesize a highlight event.
        if (d->prevFocus != d->control->textCursor() && d->control->textCursor().hasSelection()) {
            const QString href = d->control->anchorAtCursor();
            QUrl url = d->resolveUrl(href);
            emit highlighted(url);
            emit highlighted(url.toString());
        }
        d->prevFocus = d->control->textCursor();
#endif
        return true;
    } else {
#ifdef QT_KEYPAD_NAVIGATION
        // We assume we have no highlight now.
        emit highlighted(QUrl());
        emit highlighted(QString());
#endif
    }
    return QTextEdit::focusNextPrevChild(next);
}

/*!
  \reimp
*/
void QTextBrowser::paintEvent(QPaintEvent *e)
{
    Q_D(QTextBrowser);
    QPainter p(d->viewport);
    d->paint(&p, e);
}

/*!
    This function is called when the document is loaded and for
    each image in the document. The \a type indicates the type of resource
    to be loaded. An invalid QVariant is returned if the resource cannot be
    loaded.

    The default implementation ignores \a type and tries to locate
    the resources by interpreting \a name as a file name. If it is
    not an absolute path it tries to find the file in the paths of
    the \l searchPaths property and in the same directory as the
    current source. On success, the result is a QVariant that stores
    a QByteArray with the contents of the file.

    If you reimplement this function, you can return other QVariant
    types. The table below shows which variant types are supported
    depending on the resource type:

    \table
    \header \li ResourceType  \li QVariant::Type
    \row    \li QTextDocument::HtmlResource  \li QString or QByteArray
    \row    \li QTextDocument::ImageResource \li QImage, QPixmap or QByteArray
    \row    \li QTextDocument::StyleSheetResource \li QString or QByteArray
    \row    \li QTextDocument::MarkdownResource \li QString or QByteArray
    \endtable
*/
QVariant QTextBrowser::loadResource(int /*type*/, const QUrl &name)
{
    Q_D(QTextBrowser);

    QByteArray data;
    QString fileName = d->findFile(d->resolveUrl(name));
    if (fileName.isEmpty())
        return QVariant();
    QFile f(fileName);
    if (f.open(QFile::ReadOnly)) {
        data = f.readAll();
        f.close();
    } else {
        return QVariant();
    }

    return data;
}

/*!
    \since 4.2

    Returns \c true if the text browser can go backward in the document history
    using backward().

    \sa backwardAvailable(), backward()
*/
bool QTextBrowser::isBackwardAvailable() const
{
    Q_D(const QTextBrowser);
    return d->stack.count() > 1;
}

/*!
    \since 4.2

    Returns \c true if the text browser can go forward in the document history
    using forward().

    \sa forwardAvailable(), forward()
*/
bool QTextBrowser::isForwardAvailable() const
{
    Q_D(const QTextBrowser);
    return !d->forwardStack.isEmpty();
}

/*!
    \since 4.2

    Clears the history of visited documents and disables the forward and
    backward navigation.

    \sa backward(), forward()
*/
void QTextBrowser::clearHistory()
{
    Q_D(QTextBrowser);
    d->forwardStack.clear();
    if (!d->stack.isEmpty()) {
        QTextBrowserPrivate::HistoryEntry historyEntry = d->stack.top();
        d->stack.clear();
        d->stack.push(historyEntry);
        d->home = historyEntry.url;
    }
    emit forwardAvailable(false);
    emit backwardAvailable(false);
    emit historyChanged();
}

/*!
   Returns the url of the HistoryItem.

    \table
    \header \li Input            \li Return
    \row \li \a{i} < 0  \li \l backward() history
    \row \li\a{i} == 0 \li current, see QTextBrowser::source()
    \row \li \a{i} > 0  \li \l forward() history
    \endtable

    \since 4.4
*/
QUrl QTextBrowser::historyUrl(int i) const
{
    Q_D(const QTextBrowser);
    return d->history(i).url;
}

/*!
    Returns the documentTitle() of the HistoryItem.

    \table
    \header \li Input            \li Return
    \row \li \a{i} < 0  \li \l backward() history
    \row \li \a{i} == 0 \li current, see QTextBrowser::source()
    \row \li \a{i} > 0  \li \l forward() history
    \endtable

    \snippet code/src_gui_widgets_qtextbrowser.cpp 0

    \since 4.4
*/
QString QTextBrowser::historyTitle(int i) const
{
    Q_D(const QTextBrowser);
    return d->history(i).title;
}


/*!
    Returns the number of locations forward in the history.

    \since 4.4
*/
int QTextBrowser::forwardHistoryCount() const
{
    Q_D(const QTextBrowser);
    return d->forwardStack.count();
}

/*!
    Returns the number of locations backward in the history.

    \since 4.4
*/
int QTextBrowser::backwardHistoryCount() const
{
    Q_D(const QTextBrowser);
    return d->stack.count()-1;
}

/*!
    \property QTextBrowser::openExternalLinks
    \since 4.2

    Specifies whether QTextBrowser should automatically open links to external
    sources using QDesktopServices::openUrl() instead of emitting the
    anchorClicked signal. Links are considered external if their scheme is
    neither file or qrc.

    The default value is false.
*/
bool QTextBrowser::openExternalLinks() const
{
    Q_D(const QTextBrowser);
    return d->openExternalLinks;
}

void QTextBrowser::setOpenExternalLinks(bool open)
{
    Q_D(QTextBrowser);
    d->openExternalLinks = open;
}

/*!
   \property QTextBrowser::openLinks
   \since 4.3

   This property specifies whether QTextBrowser should automatically open links the user tries to
   activate by mouse or keyboard.

   Regardless of the value of this property the anchorClicked signal is always emitted.

   The default value is true.
*/

bool QTextBrowser::openLinks() const
{
    Q_D(const QTextBrowser);
    return d->openLinks;
}

void QTextBrowser::setOpenLinks(bool open)
{
    Q_D(QTextBrowser);
    d->openLinks = open;
}

/*! \reimp */
bool QTextBrowser::event(QEvent *e)
{
    return QTextEdit::event(e);
}

QT_END_NAMESPACE

#include "moc_qtextbrowser.cpp"