aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/axivion/axivionplugin.cpp
blob: e212a661c5d6fad8fa22a1f3e8abc2cc5ebd049e (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "axivionplugin.h"

#include "axivionperspective.h"
#include "axivionsettings.h"
#include "axiviontr.h"
#include "dashboard/dto.h"
#include "dashboard/error.h"
#include "localbuild.h"

#include <coreplugin/credentialquery.h>
#include <coreplugin/dialogs/ioptionspage.h>
#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/session.h>

#include <extensionsystem/iplugin.h>

#include <projectexplorer/project.h>
#include <projectexplorer/projectmanager.h>

#include <solutions/tasking/networkquery.h>
#include <solutions/tasking/tasktreerunner.h>

#include <texteditor/textdocument.h>
#include <texteditor/textmark.h>

#include <utils/algorithm.h>
#include <utils/async.h>
#include <utils/environment.h>
#include <utils/fileinprojectfinder.h>
#include <utils/networkaccessmanager.h>
#include <utils/qtcassert.h>
#include <utils/utilsicons.h>

#include <QAction>
#include <QInputDialog>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkCookieJar>
#include <QNetworkReply>
#include <QUrlQuery>

#include <cmath>
#include <memory>

constexpr char s_axivionTextMarkId[] = "AxivionTextMark";

using namespace Core;
using namespace ProjectExplorer;
using namespace Tasking;
using namespace TextEditor;
using namespace Utils;

namespace Axivion::Internal {

QIcon iconForIssue(const std::optional<Dto::IssueKind> &issueKind)
{
    if (!issueKind)
        return {};

    static QHash<Dto::IssueKind, QIcon> prefixToIcon;

    auto it = prefixToIcon.constFind(*issueKind);
    if (it != prefixToIcon.constEnd())
        return *it;

    const QLatin1String prefix = Dto::IssueKindMeta::enumToStr(*issueKind);
    const Icon icon({{FilePath::fromString(":/axivion/images/button-" + prefix + ".png"),
                      Theme::PaletteButtonText}}, Icon::Tint);
    return prefixToIcon.insert(*issueKind, icon.icon()).value();
}

static QString anyToString(const Dto::Any &any)
{
   if (any.isNull() || !any.isString())
        return {};
    return any.getString();
}

static QString anyToPathString(const Dto::Any &any)
{
    const QString pathStr = anyToString(any);
    if (pathStr.isEmpty())
        return {};
    const FilePath fp = FilePath::fromUserInput(pathStr);
    return fp.contains("/") ? QString("%1 [%2]").arg(fp.fileName(), fp.path()) : fp.fileName();
}

// only the first found innerKey is used to add its value to the list
static QString anyListOfMapToString(const Dto::Any &any, const QStringList &innerKeys)
{
    if (any.isNull() || !any.isList())
        return {};
    const std::vector<Dto::Any> anyList = any.getList();
    QStringList list;
    for (const Dto::Any &inner : anyList) {
        if (!inner.isMap())
            continue;
        const std::map<QString, Dto::Any> innerMap = inner.getMap();
        for (const QString &innerKey : innerKeys) {
            auto value = innerMap.find(innerKey);
            if (value == innerMap.end())
                continue;
            list << anyToString(value->second);
            break;
        }
    }
    return list.join(", ");
}

static QString anyToNumberString(const Dto::Any &any)
{
    if (any.isNull())
        return {};
    if (any.isString()) // handle Infinity/NaN/...
        return any.getString();

    const double value = any.getDouble();
    double intPart;
    const double frac = std::modf(value, &intPart);
    if (frac != 0)
        return QString::number(value, 'f');
    return QString::number(value, 'f', 0);
}

QString anyToSimpleString(const Dto::Any &any, const QString &type,
                          const std::optional<std::vector<Dto::ColumnTypeOptionDto>> &options)
{
    if (type == "path")
        return anyToPathString(any);
    if (type == "string" || type == "state")
        return anyToString(any);
    if (type == "tags")
        return anyListOfMapToString(any, {"tag"});
    if (type == "number")
        return anyToNumberString(any);
    if (type == "owners") {
        return anyListOfMapToString(any, {"displayName", "name"});
    }
    if (type == "boolean") {
        if (!any.isBool())
            return {};
        if (options && options->size() == 2)
            return any.getBool() ? options->at(1).key : options->at(0).key;
        return any.getBool() ? QString("true") : QString("false");
    }

    QTC_ASSERT(false, qDebug() << "unhandled" << type);
    return {};
}

static QString apiTokenDescription()
{
    const QString ua = "Axivion" + QCoreApplication::applicationName() + "Plugin/"
                       + QCoreApplication::applicationVersion();
    QString user = Utils::qtcEnvironmentVariable("USERNAME");
    if (user.isEmpty())
        user = Utils::qtcEnvironmentVariable("USER");
    return "Automatically created by " + ua + " on " + user + "@" + QSysInfo::machineHostName();
}

template <typename DtoType>
struct GetDtoStorage
{
    QUrl url;
    std::optional<QByteArray> credential;
    std::optional<DtoType> dtoData;
};

template <typename DtoType>
struct PostDtoStorage
{
    QUrl url;
    std::optional<QByteArray> credential;
    QByteArray csrfToken;
    QByteArray writeData;
    std::optional<DtoType> dtoData;
};

static DashboardInfo toDashboardInfo(const GetDtoStorage<Dto::DashboardInfoDto> &dashboardStorage)
{
    const Dto::DashboardInfoDto &infoDto = *dashboardStorage.dtoData;
    const QVersionNumber versionNumber = infoDto.dashboardVersionNumber
        ? QVersionNumber::fromString(*infoDto.dashboardVersionNumber) : QVersionNumber();

    QStringList projects;
    QHash<QString, QUrl> projectUrls;

    if (infoDto.projects) {
        for (const Dto::ProjectReferenceDto &project : *infoDto.projects) {
            projects.push_back(project.name);
            projectUrls.insert(project.name, project.url);
        }
    }
    return {
        dashboardStorage.url,
        versionNumber,
        projects,
        projectUrls,
        infoDto.checkCredentialsUrl,
        infoDto.namedFiltersUrl,
        infoDto.userNamedFiltersUrl
    };
}

QUrlQuery IssueListSearch::toUrlQuery(QueryMode mode) const
{
    QUrlQuery query;
    QTC_ASSERT(!kind.isEmpty(), return query);
    query.addQueryItem("kind", kind);
    if (!versionStart.isEmpty())
        query.addQueryItem("start", versionStart);
    if (!versionEnd.isEmpty())
        query.addQueryItem("end", versionEnd);
    if (mode == QueryMode::SimpleQuery)
        return query;

    if (!owner.isEmpty())
        query.addQueryItem("user", owner);
    if (!filter_path.isEmpty())
        query.addQueryItem("filter_any path", filter_path);
    if (!state.isEmpty())
        query.addQueryItem("state", state);
    if (mode == QueryMode::FilterQuery)
        return query;

    QTC_CHECK(mode == QueryMode::FullQuery);
    query.addQueryItem("offset", QString::number(offset));
    if (limit)
        query.addQueryItem("limit", QString::number(limit));
    if (computeTotalRowCount)
        query.addQueryItem("computeTotalRowCount", "true");
    if (!sort.isEmpty())
        query.addQueryItem("sort", sort);
    if (!filter.isEmpty()) {
        for (auto f = filter.cbegin(), end = filter.cend(); f != end; ++f)
            query.addQueryItem(f.key(), f.value());
    }
    return query;
}

enum class ServerAccess { Unknown, NoAuthorization, WithAuthorization };

class AxivionPluginPrivate : public QObject
{
    Q_OBJECT
public:
    AxivionPluginPrivate();
    void handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors);
    void onStartupProjectChanged(Project *project);
    void fetchDashboardAndProjectInfo(const DashboardInfoHandler &handler,
                                      const QString &projectName);
    void handleOpenedDocs();
    void onDocumentOpened(IDocument *doc);
    void onDocumentClosed(IDocument * doc);
    void clearAllMarks();
    void updateExistingMarks();
    void handleIssuesForFile(const Dto::FileViewDto &fileView);
    void enableInlineIssues(bool enable);
    void fetchIssueInfo(const QString &id);
    void fetchNamedFilters();

    void onSessionLoaded(const QString &sessionName);
    void onAboutToSaveSession();

public:
    // active id used for any network communication, defaults to settings' default
    // set to projects settings' dashboard id on open project
    Id m_dashboardServerId;
    // TODO: Should be set to Unknown on server address change in settings.
    ServerAccess m_serverAccess = ServerAccess::Unknown;
    // TODO: Should be cleared on username change in settings.
    std::optional<QByteArray> m_apiToken;
    NetworkAccessManager m_networkAccessManager;
    std::optional<DashboardInfo> m_dashboardInfo;
    std::optional<Dto::ProjectInfoDto> m_currentProjectInfo;
    std::optional<QString> m_analysisVersion;
    QList<Dto::NamedFilterInfoDto> m_globalNamedFilters;
    QList<Dto::NamedFilterInfoDto> m_userNamedFilters;
    Project *m_project = nullptr;
    bool m_runningQuery = false;
    TaskTreeRunner m_taskTreeRunner;
    std::unordered_map<IDocument *, std::unique_ptr<TaskTree>> m_docMarksTrees;
    TaskTreeRunner m_issueInfoRunner;
    TaskTreeRunner m_namedFilterRunner;
    FileInProjectFinder m_fileFinder; // FIXME maybe obsolete when path mapping is implemented
    QMetaObject::Connection m_fileFinderConnection;
    QHash<FilePath, QSet<TextMark *>> m_allMarks;
    bool m_inlineIssuesEnabled = true;
};

static AxivionPluginPrivate *dd = nullptr;

class AxivionTextMark : public TextMark
{
public:
    AxivionTextMark(const FilePath &filePath, const Dto::LineMarkerDto &issue,
                    std::optional<Theme::Color> color)
        : TextMark(filePath, issue.startLine, {"Axivion", s_axivionTextMarkId})
    {
        const QString markText = issue.description;
        const QString id = issue.kind + QString::number(issue.id.value_or(-1));
        setToolTip(id + '\n' + markText);
        setIcon(iconForIssue(issue.getOptionalKindEnum()));
        if (color)
            setColor(*color);
        setPriority(TextMark::NormalPriority);
        setLineAnnotation(markText);
        setActionsProvider([id] {
            auto action = new QAction;
            action->setIcon(Icons::INFO.icon());
            action->setToolTip(Tr::tr("Show Issue Properties"));
            QObject::connect(action, &QAction::triggered, dd, [id] { dd->fetchIssueInfo(id); });
            return QList{action};
        });
    }
};

void fetchDashboardAndProjectInfo(const DashboardInfoHandler &handler, const QString &projectName)
{
    QTC_ASSERT(dd, return);
    dd->fetchDashboardAndProjectInfo(handler, projectName);
}

std::optional<Dto::ProjectInfoDto> projectInfo()
{
    QTC_ASSERT(dd, return {});
    return dd->m_currentProjectInfo;
}

void fetchNamedFilters()
{
    QTC_ASSERT(dd, return);
    dd->fetchNamedFilters();
}

static QList<Dto::NamedFilterInfoDto> withoutRestricted(const QString &kind, const QList<Dto::NamedFilterInfoDto> &f)
{
    return Utils::filtered(f, [kind](const Dto::NamedFilterInfoDto &dto) {
        if (dto.supportsAllIssueKinds)
            return true;
        return !dto.issueKindRestrictions || dto.issueKindRestrictions->contains(kind)
               || dto.issueKindRestrictions->contains("UNIVERSAL");
    });
};

// TODO: Introduce FilterScope enum { Global, User } and use it instead of bool global.
QList<NamedFilter> knownNamedFiltersFor(const QString &issueKind, bool global)
{
    QTC_ASSERT(dd, return {});

    if (issueKind.isEmpty()) // happens after initial dashboad and filters fetch
        return {};

    return Utils::transform(withoutRestricted(issueKind, global ? dd->m_globalNamedFilters : dd->m_userNamedFilters),
                               [global](const Dto::NamedFilterInfoDto &dto) {
        return NamedFilter{dto.key, dto.displayName, global};
    });
}

std::optional<Dto::NamedFilterInfoDto> namedFilterInfoForKey(const QString &key, bool global)
{
    QTC_ASSERT(dd, return std::nullopt);

    const auto findFilter = [](const QList<Dto::NamedFilterInfoDto> filters, const QString &key)
            -> std::optional<Dto::NamedFilterInfoDto> {
        const int index = Utils::indexOf(filters, [key](const Dto::NamedFilterInfoDto &dto) {
            return dto.key == key;
        });
        if (index == -1)
            return std::nullopt;
        return filters.at(index);
    };

    if (global)
        return findFilter(dd->m_globalNamedFilters, key);
    else
        return findFilter(dd->m_userNamedFilters, key);
}

// FIXME: extend to give some details?
// FIXME: move when curl is no more in use?
bool handleCertificateIssue(const Utils::Id &serverId)
{
    QTC_ASSERT(dd, return false);
    const QString serverHost = QUrl(settings().serverForId(serverId).dashboard).host();
    if (QMessageBox::question(ICore::dialogParent(), Tr::tr("Certificate Error"),
                              Tr::tr("Server certificate for %1 cannot be authenticated.\n"
                                     "Do you want to disable SSL verification for this server?\n"
                                     "Note: This can expose you to man-in-the-middle attack.")
                              .arg(serverHost))
            != QMessageBox::Yes) {
        return false;
    }
    settings().disableCertificateValidation(serverId);
    settings().apply();

    return true;
}

AxivionPluginPrivate::AxivionPluginPrivate()
{
#if QT_CONFIG(ssl)
    connect(&m_networkAccessManager, &QNetworkAccessManager::sslErrors,
            this, &AxivionPluginPrivate::handleSslErrors);
#endif // ssl
    connect(&settings().highlightMarks, &BoolAspect::changed,
            this, &AxivionPluginPrivate::updateExistingMarks);
    connect(SessionManager::instance(), &SessionManager::sessionLoaded,
            this, &AxivionPluginPrivate::onSessionLoaded);
    connect(SessionManager::instance(), &SessionManager::aboutToSaveSession,
            this, &AxivionPluginPrivate::onAboutToSaveSession);

}

void AxivionPluginPrivate::handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
    QTC_ASSERT(dd, return);
#if QT_CONFIG(ssl)
    const QList<QSslError::SslError> accepted{
        QSslError::CertificateNotYetValid, QSslError::CertificateExpired,
        QSslError::InvalidCaCertificate, QSslError::CertificateUntrusted,
        QSslError::HostNameMismatch
    };
    if (Utils::allOf(errors,
                     [&accepted](const QSslError &e) { return accepted.contains(e.error()); })) {
        const bool shouldValidate = settings().serverForId(dd->m_dashboardServerId).validateCert;
        if (!shouldValidate || handleCertificateIssue(dd->m_dashboardServerId))
            reply->ignoreSslErrors(errors);
    }
#else // ssl
    Q_UNUSED(reply)
    Q_UNUSED(errors)
#endif // ssl
}

void AxivionPluginPrivate::onStartupProjectChanged(Project *project)
{
    if (project == m_project)
        return;

    if (m_project)
        disconnect(m_fileFinderConnection);

    m_project = project;

    if (!m_project) {
        m_fileFinder.setProjectDirectory({});
        m_fileFinder.setProjectFiles({});
        return;
    }

    m_fileFinder.setProjectDirectory(m_project->projectDirectory());
    m_fileFinderConnection = connect(m_project, &Project::fileListChanged, this, [this] {
        m_fileFinder.setProjectFiles(m_project->files(Project::AllFiles));
        handleOpenedDocs();
    });
}

static QUrl constructUrl(const QString &projectName, const QString &subPath, const QUrlQuery &query)
{
    if (!dd->m_dashboardInfo)
        return {};
    const QByteArray encodedProjectName = QUrl::toPercentEncoding(projectName);
    const QUrl path(QString{"api/projects/" + QString::fromUtf8(encodedProjectName) + '/'});
    QUrl url = resolveDashboardInfoUrl(path);
    if (!subPath.isEmpty() && QTC_GUARD(!subPath.startsWith('/')))
        url = url.resolved(subPath);
    if (!query.isEmpty())
        url.setQuery(query);
    return url;
}

static constexpr int httpStatusCodeOk = 200;
constexpr char s_htmlContentType[] = "text/html";
constexpr char s_plaintextContentType[] = "text/plain";
constexpr char s_svgContentType[] = "image/svg+xml";
constexpr char s_jsonContentType[] = "application/json";

static bool isServerAccessEstablished()
{
    return dd->m_serverAccess == ServerAccess::NoAuthorization
           || (dd->m_serverAccess == ServerAccess::WithAuthorization && dd->m_apiToken);
}

static QByteArray contentTypeData(ContentType contentType)
{
    switch (contentType) {
    case ContentType::Html:      return s_htmlContentType;
    case ContentType::Json:      return s_jsonContentType;
    case ContentType::PlainText: return s_plaintextContentType;
    case ContentType::Svg:       return s_svgContentType;
    }
    return {};
}

QUrl resolveDashboardInfoUrl(const QUrl &resource)
{
    QTC_ASSERT(dd, return {});
    QTC_ASSERT(dd->m_dashboardInfo, return {});
    return dd->m_dashboardInfo->source.resolved(resource);
}

Group downloadDataRecipe(const Storage<DownloadData> &storage)
{
    const auto onQuerySetup = [storage](NetworkQuery &query) {
        if (!isServerAccessEstablished())
            return SetupResult::StopWithError; // TODO: start authorizationRecipe()?

        QNetworkRequest request(storage->inputUrl);
        request.setRawHeader("Accept", contentTypeData(storage->expectedContentType));
        if (dd->m_serverAccess == ServerAccess::WithAuthorization && dd->m_apiToken)
            request.setRawHeader("Authorization", "AxToken " + *dd->m_apiToken);
        const QByteArray ua = "Axivion" + QCoreApplication::applicationName().toUtf8() +
                              "Plugin/" + QCoreApplication::applicationVersion().toUtf8();
        request.setRawHeader("X-Axivion-User-Agent", ua);
        query.setRequest(request);
        query.setNetworkAccessManager(&dd->m_networkAccessManager);
        return SetupResult::Continue;
    };
    const auto onQueryDone = [storage](const NetworkQuery &query, DoneWith doneWith) {
        QNetworkReply *reply = query.reply();
        const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader)
                                        .toString()
                                        .split(';')
                                        .constFirst()
                                        .trimmed()
                                        .toLower();
        if (doneWith == DoneWith::Success && statusCode == httpStatusCodeOk
            && contentType == QString::fromUtf8(contentTypeData(storage->expectedContentType))) {
            storage->outputData = reply->readAll();
            return DoneResult::Success;
        }
        return DoneResult::Error;
    };
    return {NetworkQueryTask(onQuerySetup, onQueryDone)};
}

template <typename DtoType, template <typename> typename DtoStorageType>
static Group dtoRecipe(const Storage<DtoStorageType<DtoType>> &dtoStorage)
{
    const Storage<std::optional<QByteArray>> storage;

    const auto onNetworkQuerySetup = [dtoStorage](NetworkQuery &query) {
        QNetworkRequest request(dtoStorage->url);
        request.setRawHeader("Accept", s_jsonContentType);
        if (dtoStorage->credential) // Unauthorized access otherwise
            request.setRawHeader("Authorization", *dtoStorage->credential);
        const QByteArray ua = "Axivion" + QCoreApplication::applicationName().toUtf8() +
                              "Plugin/" + QCoreApplication::applicationVersion().toUtf8();
        request.setRawHeader("X-Axivion-User-Agent", ua);

        if constexpr (std::is_same_v<DtoStorageType<DtoType>, PostDtoStorage<DtoType>>) {
            request.setRawHeader("Content-Type", "application/json");
            request.setRawHeader("AX-CSRF-Token", dtoStorage->csrfToken);
            query.setWriteData(dtoStorage->writeData);
            query.setOperation(NetworkOperation::Post);
        }

        query.setRequest(request);
        query.setNetworkAccessManager(&dd->m_networkAccessManager);
    };

    const auto onNetworkQueryDone = [storage, dtoStorage](const NetworkQuery &query,
                                                          DoneWith doneWith) {
        QNetworkReply *reply = query.reply();
        const QNetworkReply::NetworkError error = reply->error();
        const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader)
                                        .toString()
                                        .split(';')
                                        .constFirst()
                                        .trimmed()
                                        .toLower();
        if (doneWith == DoneWith::Success && statusCode == httpStatusCodeOk
            && contentType == s_jsonContentType) {
            *storage = reply->readAll();
            dtoStorage->url = reply->url();
            return DoneResult::Success;
        }

        QString errorString;
        if (contentType == s_jsonContentType) {
            const Result<Dto::ErrorDto> error
                = Dto::ErrorDto::deserializeExpected(reply->readAll());

            if (error) {
                if constexpr (std::is_same_v<DtoType, Dto::DashboardInfoDto>) {
                    // Suppress logging error on unauthorized dashboard fetch
                    if (!dtoStorage->credential && error->type == "UnauthenticatedException") {
                        dtoStorage->url = reply->url();
                        return DoneResult::Success;
                    }
                }

                if (statusCode == 400 && error->type == "InvalidFilterException"
                        && !error->message.isEmpty()) {
                    // handle error..
                    showFilterException(error->message);
                    return DoneResult::Error;
                }
                errorString = Error(DashboardError(reply->url(), statusCode,
                    reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(),
                                     *error)).message();
            } else {
                errorString = error.error();
            }
        } else if (statusCode != 0) {
            errorString = Error(HttpError(reply->url(), statusCode,
                reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(),
                                 QString::fromUtf8(reply->readAll()))).message(); // encoding?
        } else {
            errorString = Error(NetworkError(reply->url(), error, reply->errorString())).message();
        }

        showErrorMessage(errorString);
        return DoneResult::Error;
    };

    const auto onDeserializeSetup = [storage](Async<Result<DtoType>> &task) {
        if (!*storage)
            return SetupResult::StopWithSuccess;

        const auto deserialize = [](QPromise<Result<DtoType>> &promise, const QByteArray &input) {
            promise.addResult(DtoType::deserializeExpected(input));
        };
        task.setConcurrentCallData(deserialize, **storage);
        return SetupResult::Continue;
    };

    const auto onDeserializeDone = [dtoStorage](const Async<Result<DtoType>> &task,
                                                DoneWith doneWith) {
        if (doneWith == DoneWith::Success && task.isResultAvailable()) {
            const auto result = task.result();
            if (result) {
                dtoStorage->dtoData = *result;
                return DoneResult::Success;
            }
            MessageManager::writeFlashing(QString("Axivion: %1").arg(result.error()));
        } else {
            MessageManager::writeFlashing(QString("Axivion: %1")
                .arg(Tr::tr("Unknown Dto structure deserialization error.")));
        }
        return DoneResult::Error;
    };

    return {
        storage,
        NetworkQueryTask(onNetworkQuerySetup, onNetworkQueryDone),
        AsyncTask<Result<DtoType>>(onDeserializeSetup, onDeserializeDone)
    };
}

static QString credentialOperationMessage(CredentialOperation operation)
{
    switch (operation) {
    case CredentialOperation::Get:
        return Tr::tr("The ApiToken cannot be read in a secure way.");
    case CredentialOperation::Set:
        return Tr::tr("The ApiToken cannot be stored in a secure way.");
    case CredentialOperation::Delete:
        return Tr::tr("The ApiToken cannot be deleted in a secure way.");
    }
    return {};
}

static void handleCredentialError(const CredentialQuery &credential)
{
    const QString keyChainMessage = credential.errorString().isEmpty() ? QString()
        : QString(" %1").arg(Tr::tr("Key chain message: \"%1\".").arg(credential.errorString()));
    MessageManager::writeFlashing(QString("Axivion: %1")
        .arg(credentialOperationMessage(credential.operation()) + keyChainMessage));
}

static Group authorizationRecipe()
{
    const Id serverId = dd->m_dashboardServerId;
    const Storage<QUrl> serverUrlStorage;
    const Storage<GetDtoStorage<Dto::DashboardInfoDto>> unauthorizedDashboardStorage;
    const auto onUnauthorizedGroupSetup = [serverUrlStorage, unauthorizedDashboardStorage] {
        unauthorizedDashboardStorage->url = *serverUrlStorage;
        return isServerAccessEstablished() ? SetupResult::StopWithSuccess : SetupResult::Continue;
    };
    const auto onUnauthorizedDashboard = [unauthorizedDashboardStorage, serverId] {
        if (unauthorizedDashboardStorage->dtoData) {
            const Dto::DashboardInfoDto &dashboardInfo = *unauthorizedDashboardStorage->dtoData;
            const QString &username = settings().serverForId(serverId).username;
            if (username.isEmpty()
                || (dashboardInfo.username && *dashboardInfo.username == username)) {
                dd->m_serverAccess = ServerAccess::NoAuthorization;
                dd->m_dashboardInfo = toDashboardInfo(*unauthorizedDashboardStorage);
                return;
            }
            MessageManager::writeFlashing(QString("Axivion: %1")
                .arg(Tr::tr("Unauthenticated access failed (wrong user), "
                            "using authenticated access...")));
        }
        dd->m_serverAccess = ServerAccess::WithAuthorization;
    };

    const auto onCredentialLoopCondition = [](int) {
        return dd->m_serverAccess == ServerAccess::WithAuthorization && !dd->m_apiToken;
    };
    const auto onGetCredentialSetup = [serverId](CredentialQuery &credential) {
        credential.setOperation(CredentialOperation::Get);
        credential.setService(s_axivionKeychainService);
        credential.setKey(credentialKey(settings().serverForId(serverId)));
    };
    const auto onGetCredentialDone = [](const CredentialQuery &credential, DoneWith result) {
        if (result == DoneWith::Success)
            dd->m_apiToken = credential.data();
        else
            handleCredentialError(credential);
        // TODO: In case of an error we are multiplying the ApiTokens on Axivion server for each
        //       Creator run, but at least things should continue to work OK in the current session.
        return DoneResult::Success;
    };

    const Storage<QString> passwordStorage;
    const Storage<GetDtoStorage<Dto::DashboardInfoDto>> dashboardStorage;
    const auto onPasswordGroupSetup
            = [serverId, serverUrlStorage, passwordStorage, dashboardStorage] {
        if (dd->m_apiToken)
            return SetupResult::StopWithSuccess;

        bool ok = false;
        const AxivionServer server = settings().serverForId(serverId);
        const QString text(Tr::tr("Enter the password for:\nDashboard: %1\nUser: %2")
                               .arg(server.dashboard, server.username));
        *passwordStorage = QInputDialog::getText(ICore::dialogParent(),
            Tr::tr("Axivion Server Password"), text, QLineEdit::Password, {}, &ok);
        if (!ok)
            return SetupResult::StopWithError;

        const QString credential = server.username + ':' + *passwordStorage;
        dashboardStorage->credential = "Basic " + credential.toUtf8().toBase64();
        dashboardStorage->url = *serverUrlStorage;
        return SetupResult::Continue;
    };

    const Storage<PostDtoStorage<Dto::ApiTokenInfoDto>> apiTokenStorage;
    const auto onApiTokenGroupSetup = [passwordStorage, dashboardStorage, apiTokenStorage] {
        if (!dashboardStorage->dtoData)
            return SetupResult::StopWithSuccess;

        dd->m_dashboardInfo = toDashboardInfo(*dashboardStorage);

        const Dto::DashboardInfoDto &dashboardDto = *dashboardStorage->dtoData;
        if (!dashboardDto.userApiTokenUrl)
            return SetupResult::StopWithError;

        apiTokenStorage->credential = dashboardStorage->credential;
        apiTokenStorage->url = resolveDashboardInfoUrl(*dashboardDto.userApiTokenUrl);
        apiTokenStorage->csrfToken = dashboardDto.csrfToken.toUtf8();
        const Dto::ApiTokenCreationRequestDto requestDto{*passwordStorage, "IdePlugin",
                                                         apiTokenDescription(), 0};
        apiTokenStorage->writeData = requestDto.serialize();
        return SetupResult::Continue;
    };

    const auto onSetCredentialSetup = [apiTokenStorage, serverId](CredentialQuery &credential) {
        if (!apiTokenStorage->dtoData || !apiTokenStorage->dtoData->token)
            return SetupResult::StopWithSuccess;

        dd->m_apiToken = apiTokenStorage->dtoData->token->toUtf8();
        credential.setOperation(CredentialOperation::Set);
        credential.setService(s_axivionKeychainService);
        credential.setKey(credentialKey(settings().serverForId(serverId)));
        credential.setData(*dd->m_apiToken);
        return SetupResult::Continue;
    };
    const auto onSetCredentialDone = [](const CredentialQuery &credential) {
        handleCredentialError(credential);
        // TODO: In case of an error we are multiplying the ApiTokens on Axivion server for each
        //       Creator run, but at least things should continue to work OK in the current session.
        return DoneResult::Success;
    };

    const auto onDashboardGroupSetup = [serverUrlStorage, dashboardStorage] {
        if (dd->m_dashboardInfo || dd->m_serverAccess != ServerAccess::WithAuthorization
            || !dd->m_apiToken) {
            return SetupResult::StopWithSuccess; // Unauthorized access should have collect dashboard before
        }
        dashboardStorage->credential = "AxToken " + *dd->m_apiToken;
        dashboardStorage->url = *serverUrlStorage;
        return SetupResult::Continue;
    };
    const auto onDeleteCredentialSetup = [dashboardStorage, serverId](CredentialQuery &credential) {
        if (dashboardStorage->dtoData) {
            dd->m_dashboardInfo = toDashboardInfo(*dashboardStorage);
            return SetupResult::StopWithSuccess;
        }
        dd->m_apiToken = {};
        MessageManager::writeFlashing(QString("Axivion: %1")
            .arg(Tr::tr("The stored ApiToken is not valid anymore, removing it.")));
        credential.setOperation(CredentialOperation::Delete);
        credential.setService(s_axivionKeychainService);
        credential.setKey(credentialKey(settings().serverForId(serverId)));
        return SetupResult::Continue;
    };

    return {
        serverUrlStorage,
        onGroupSetup([serverUrlStorage, serverId] {
            *serverUrlStorage = QUrl(settings().serverForId(serverId).dashboard);
        }),
        Group {
            unauthorizedDashboardStorage,
            onGroupSetup(onUnauthorizedGroupSetup),
            dtoRecipe(unauthorizedDashboardStorage),
            Sync(onUnauthorizedDashboard),
            onGroupDone([serverUrlStorage, unauthorizedDashboardStorage] {
                *serverUrlStorage = unauthorizedDashboardStorage->url;
            }),
        },
        For (LoopUntil(onCredentialLoopCondition)) >> Do {
            CredentialQueryTask(onGetCredentialSetup, onGetCredentialDone),
            Group {
                passwordStorage,
                dashboardStorage,
                onGroupSetup(onPasswordGroupSetup),
                Group { // GET DashboardInfoDto
                    finishAllAndSuccess,
                    dtoRecipe(dashboardStorage)
                },
                Group { // POST ApiTokenCreationRequestDto, GET ApiTokenInfoDto.
                    apiTokenStorage,
                    onGroupSetup(onApiTokenGroupSetup),
                    dtoRecipe(apiTokenStorage),
                    CredentialQueryTask(onSetCredentialSetup, onSetCredentialDone, CallDoneIf::Error)
                }
            },
            Group {
                finishAllAndSuccess,
                dashboardStorage,
                onGroupSetup(onDashboardGroupSetup),
                dtoRecipe(dashboardStorage),
                CredentialQueryTask(onDeleteCredentialSetup)
            }
        }
    };
}

template<typename DtoType>
static Group fetchDataRecipe(const QUrl &url, const std::function<void(const DtoType &)> &handler)
{
    const Storage<GetDtoStorage<DtoType>> dtoStorage;

    const auto onDtoSetup = [dtoStorage, url] {
        if (!isServerAccessEstablished())
            return SetupResult::StopWithError;

        if (dd->m_serverAccess == ServerAccess::WithAuthorization && dd->m_apiToken)
            dtoStorage->credential = "AxToken " + *dd->m_apiToken;
        dtoStorage->url = url;
        return SetupResult::Continue;
    };
    const auto onDtoDone = [dtoStorage, handler] {
        if (dtoStorage->dtoData)
            handler(*dtoStorage->dtoData);
    };

    const Group recipe {
        authorizationRecipe(),
        Group {
            dtoStorage,
            onGroupSetup(onDtoSetup),
            dtoRecipe(dtoStorage),
            onGroupDone(onDtoDone)
        }
    };
    return recipe;
}

Group dashboardInfoRecipe(const DashboardInfoHandler &handler)
{
    const auto onSetup = [handler] {
        if (dd->m_dashboardInfo) {
            if (handler)
                handler(*dd->m_dashboardInfo);
            return SetupResult::StopWithSuccess;
        }
        dd->m_networkAccessManager.setCookieJar(new QNetworkCookieJar); // remove old cookies
        return SetupResult::Continue;
    };
    const auto onDone = [handler](DoneWith result) {
        if (result == DoneWith::Success && dd->m_dashboardInfo)
            handler(*dd->m_dashboardInfo);
        else
            handler(ResultError("Error")); // TODO: Collect error message in the storage.
    };

    const Group root {
        onGroupSetup(onSetup), // Stops if cache exists.
        authorizationRecipe(),
        handler ? onGroupDone(onDone) : nullItem
    };
    return root;
}

Group projectInfoRecipe(const QString &projectName)
{
    const auto onSetup = [projectName] {
        dd->clearAllMarks();
        dd->m_currentProjectInfo = {};
        dd->m_analysisVersion = {};
    };

    const auto onTaskTreeSetup = [projectName](TaskTree &taskTree) {
        if (!dd->m_dashboardInfo) {
            MessageManager::writeDisrupting(QString("Axivion: %1")
                                                .arg(Tr::tr("Fetching DashboardInfo error.")));
            return SetupResult::StopWithError;
        }

        if (dd->m_dashboardInfo->projects.isEmpty()) {
            updateDashboard();
            return SetupResult::StopWithSuccess;
        }

        const auto handler = [](const Dto::ProjectInfoDto &data) {
            dd->m_currentProjectInfo = data;
            if (!dd->m_currentProjectInfo->versions.empty())
                setAnalysisVersion(dd->m_currentProjectInfo->versions.back().date);
            updateDashboard();
        };

        const QString targetProjectName = projectName.isEmpty()
                ? dd->m_dashboardInfo->projects.first() : projectName;
        auto it = dd->m_dashboardInfo->projectUrls.constFind(targetProjectName);
        if (it == dd->m_dashboardInfo->projectUrls.constEnd())
            it = dd->m_dashboardInfo->projectUrls.constBegin();
        taskTree.setRecipe(fetchDataRecipe<Dto::ProjectInfoDto>(resolveDashboardInfoUrl(*it),
                                                                handler));
        return SetupResult::Continue;
    };

    return {
        onGroupSetup(onSetup),
        TaskTreeTask(onTaskTreeSetup)
    };
}

Group issueTableRecipe(const IssueListSearch &search, const IssueTableHandler &handler)
{
    QTC_ASSERT(dd->m_currentProjectInfo, return {}); // TODO: Call handler with unexpected?

    const QUrlQuery query = search.toUrlQuery(QueryMode::FullQuery);
    if (query.isEmpty())
        return {}; // TODO: Call handler with unexpected?

    const QUrl url = constructUrl(dd->m_currentProjectInfo->name, "issues", query);
    return fetchDataRecipe<Dto::IssueTableDto>(url, handler);
}

Group lineMarkerRecipe(const FilePath &filePath, const LineMarkerHandler &handler)
{
    QTC_ASSERT(dd->m_currentProjectInfo, return {}); // TODO: Call handler with unexpected?
    QTC_ASSERT(!filePath.isEmpty(), return {}); // TODO: Call handler with unexpected?

    const QString fileName = QString::fromUtf8(QUrl::toPercentEncoding(filePath.path()));
    const QUrlQuery query({{"filename", fileName}});
    const QUrl url = constructUrl(dd->m_currentProjectInfo->name, "files", query);
    return fetchDataRecipe<Dto::FileViewDto>(url, handler);
}

void AxivionPluginPrivate::fetchDashboardAndProjectInfo(const DashboardInfoHandler &handler,
                                                        const QString &projectName)
{
    m_taskTreeRunner.start({dashboardInfoRecipe(handler), projectInfoRecipe(projectName)});
}

Group tableInfoRecipe(const QString &prefix, const TableInfoHandler &handler)
{
    const QUrlQuery query({{"kind", prefix}});
    const QUrl url = constructUrl(dd->m_currentProjectInfo->name, "issues_meta", query);
    return fetchDataRecipe<Dto::TableInfoDto>(url, handler);
}

void AxivionPluginPrivate::fetchIssueInfo(const QString &id)
{
    if (!m_currentProjectInfo || !dd->m_analysisVersion)
        return;

    const QUrl url = constructUrl(dd->m_currentProjectInfo->name,
                                  QString("issues/" + id + "/properties/"),
                                  {{"version", *dd->m_analysisVersion}});

    const Storage<DownloadData> storage;

    const auto onSetup = [storage, url] { storage->inputUrl = url; };

    const auto onDone = [storage] {
        QByteArray fixedHtml = storage->outputData;
        const int idx = fixedHtml.indexOf("<div class=\"ax-issuedetails-table-container\">");
        if (idx >= 0)
            fixedHtml = "<html><body>" + fixedHtml.mid(idx);
        updateIssueDetails(QString::fromUtf8(fixedHtml));
    };

    m_issueInfoRunner.start({
        storage,
        onGroupSetup(onSetup),
        downloadDataRecipe(storage),
        onGroupDone(onDone, CallDoneIf::Success)
    });
}

static QList<Dto::NamedFilterInfoDto> extractNamedFiltersFromJsonArray(const QByteArray &json)
{
    QList<Dto::NamedFilterInfoDto> result;
    QJsonParseError error;
    const QJsonDocument doc = QJsonDocument::fromJson(json, &error);
    if (error.error != QJsonParseError::NoError)
        return result;
    if (!doc.isArray())
        return result;
    const QJsonArray array = doc.array();
    for (const QJsonValue &value : array) {
        if (!value.isObject())
            continue;
        const QJsonDocument objDocument(value.toObject());
        const auto filter = Dto::NamedFilterInfoDto::deserializeExpected(objDocument.toJson());
        if (filter)
            result.append(*filter);
    }
    return result;
}

void AxivionPluginPrivate::fetchNamedFilters()
{
    QTC_ASSERT(m_dashboardInfo, return);

    // use simple downloadDatarecipe() as we cannot handle an array of a dto at the moment
    const Storage<DownloadData> globalStorage;
    const Storage<DownloadData> userStorage;

    const auto onSetup = [this, globalStorage, userStorage] {
        QTC_ASSERT(m_dashboardInfo, return);
        globalStorage->inputUrl = m_dashboardInfo->source.resolved(
                    *m_dashboardInfo->globalNamedFilters);
        globalStorage->expectedContentType = ContentType::Json;
        userStorage->inputUrl = m_dashboardInfo->source.resolved(
                    *m_dashboardInfo->userNamedFilters);
        userStorage->expectedContentType = ContentType::Json;
    };
    const auto onDone = [this, globalStorage, userStorage] {
        m_globalNamedFilters = extractNamedFiltersFromJsonArray(globalStorage->outputData);
        m_userNamedFilters = extractNamedFiltersFromJsonArray(userStorage->outputData);
        updateNamedFilters();
    };

    Group namedFiltersGroup = Group {
            globalStorage,
            userStorage,
            onGroupSetup(onSetup),
            downloadDataRecipe(globalStorage) || successItem,
            downloadDataRecipe(userStorage) || successItem,
            onGroupDone(onDone)
    };

    m_namedFilterRunner.start(namedFiltersGroup);
}

void AxivionPluginPrivate::handleOpenedDocs()
{
    const QList<IDocument *> openDocuments = DocumentModel::openedDocuments();
    for (IDocument *doc : openDocuments)
        onDocumentOpened(doc);
}

void AxivionPluginPrivate::clearAllMarks()
{
    for (const QSet<TextMark *> &marks : std::as_const(m_allMarks))
       qDeleteAll(marks);
    m_allMarks.clear();
}

void AxivionPluginPrivate::updateExistingMarks() // update whether highlight marks or not
{
    static Theme::Color color = Theme::Color(Theme::Bookmarks_TextMarkColor); // FIXME!
    const bool colored = settings().highlightMarks();

    auto changeColor = colored ? [](TextMark *mark) { mark->setColor(color); }
                               : [](TextMark *mark) { mark->unsetColor(); };

    for (const QSet<TextMark *> &marksForFile : std::as_const(m_allMarks)) {
        for (auto mark : marksForFile)
            changeColor(mark);
    }
}

void AxivionPluginPrivate::onDocumentOpened(IDocument *doc)
{
    if (!m_inlineIssuesEnabled)
        return;
    if (!doc || !m_currentProjectInfo || !m_project || !m_project->isKnownFile(doc->filePath()))
        return;

    const FilePath filePath = doc->filePath().relativeChildPath(m_project->projectDirectory());
    if (filePath.isEmpty())
        return; // Empty is fine
    if (m_allMarks.contains(filePath))
        return;

    const auto handler = [this](const Dto::FileViewDto &data) {
        if (data.lineMarkers.empty())
            return;
        handleIssuesForFile(data);
    };
    TaskTree *taskTree = new TaskTree;
    taskTree->setRecipe(lineMarkerRecipe(filePath, handler));
    m_docMarksTrees.insert_or_assign(doc, std::unique_ptr<TaskTree>(taskTree));
    connect(taskTree, &TaskTree::done, this, [this, doc] {
        const auto it = m_docMarksTrees.find(doc);
        QTC_ASSERT(it != m_docMarksTrees.end(), return);
        it->second.release()->deleteLater();
        m_docMarksTrees.erase(it);
    });
    taskTree->start();
}

void AxivionPluginPrivate::onDocumentClosed(IDocument *doc)
{
    const auto document = qobject_cast<TextDocument *>(doc);
    if (!document)
        return;

    const auto it = m_docMarksTrees.find(doc);
    if (it != m_docMarksTrees.end())
        m_docMarksTrees.erase(it);

    qDeleteAll(m_allMarks.take(document->filePath()));
}

void AxivionPluginPrivate::handleIssuesForFile(const Dto::FileViewDto &fileView)
{
    if (fileView.lineMarkers.empty())
        return;

    Project *project = ProjectManager::startupProject();
    if (!project)
        return;

    const FilePath filePath = project->projectDirectory().pathAppended(fileView.fileName);
    std::optional<Theme::Color> color = std::nullopt;
    if (settings().highlightMarks())
        color.emplace(Theme::Color(Theme::Bookmarks_TextMarkColor)); // FIXME!
    for (const Dto::LineMarkerDto &marker : std::as_const(fileView.lineMarkers)) {
        // FIXME the line location can be wrong (even the whole issue could be wrong)
        // depending on whether this line has been changed since the last axivion run and the
        // current state of the file - some magic has to happen here
        m_allMarks[filePath] << new AxivionTextMark(filePath, marker, color);
    }
}

void AxivionPluginPrivate::enableInlineIssues(bool enable)
{
    if (m_inlineIssuesEnabled == enable)
        return;
    m_inlineIssuesEnabled = enable;

    if (enable && m_dashboardServerId.isValid())
        handleOpenedDocs();
    else
        clearAllMarks();
}

static constexpr char SV_PROJECTNAME[] = "Axivion.ProjectName";
static constexpr char SV_DASHBOARDID[] = "Axivion.DashboardId";

void AxivionPluginPrivate::onSessionLoaded(const QString &sessionName)
{
    // explicitly ignore default session to avoid triggering dialogs at startup
    if (sessionName == "default")
        return;

    const QString projectName = SessionManager::sessionValue(SV_PROJECTNAME).toString();
    const Id dashboardId = Id::fromSetting(SessionManager::sessionValue(SV_DASHBOARDID));
    if (!dashboardId.isValid())
        switchActiveDashboardId({});
    else if (activeDashboardId() != dashboardId)
        switchActiveDashboardId(dashboardId);
    reinitDashboard(projectName);
}

void AxivionPluginPrivate::onAboutToSaveSession()
{
    // explicitly ignore default session
    if (SessionManager::startupSession() == "default")
        return;

    SessionManager::setSessionValue(SV_DASHBOARDID, activeDashboardId().toSetting());
    const QString projectName = m_currentProjectInfo ? m_currentProjectInfo->name : QString();
    SessionManager::setSessionValue(SV_PROJECTNAME, projectName);
}

class AxivionPlugin final : public ExtensionSystem::IPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "Axivion.json")

    ~AxivionPlugin() final
    {
        delete dd;
        dd = nullptr;
    }

    void initialize() final
    {
        IOptionsPage::registerCategory(
            "XY.Axivion", Tr::tr("Axivion"), ":/axivion/images/axivion.png");

        setupAxivionPerspective();

        dd = new AxivionPluginPrivate;

        connect(ProjectManager::instance(), &ProjectManager::startupProjectChanged,
                dd, &AxivionPluginPrivate::onStartupProjectChanged);
        connect(EditorManager::instance(), &EditorManager::documentOpened,
                dd, &AxivionPluginPrivate::onDocumentOpened);
        connect(EditorManager::instance(), &EditorManager::documentClosed,
                dd, &AxivionPluginPrivate::onDocumentClosed);
    }

    ShutdownFlag aboutToShutdown() final
    {
        if (shutdownAllLocalDashboards([this] { emit asynchronousShutdownFinished(); }))
            return AsynchronousShutdown;
        else
            return SynchronousShutdown;
    }
};

void fetchIssueInfo(const QString &id)
{
    QTC_ASSERT(dd, return);
    dd->fetchIssueInfo(id);
}

void switchActiveDashboardId(const Id &toDashboardId)
{
    QTC_ASSERT(dd, return);
    dd->m_dashboardServerId = toDashboardId;
    dd->m_serverAccess = ServerAccess::Unknown;
    dd->m_apiToken.reset();
    dd->m_dashboardInfo.reset();
    dd->m_currentProjectInfo.reset();
    dd->m_globalNamedFilters.clear();
    dd->m_userNamedFilters.clear();
    updateNamedFilters();
}

const std::optional<DashboardInfo> currentDashboardInfo()
{
    QTC_ASSERT(dd, return std::nullopt);
    return dd->m_dashboardInfo;
}

const Id activeDashboardId()
{
    QTC_ASSERT(dd, return {});
    return dd->m_dashboardServerId;
}

void setAnalysisVersion(const QString &version)
{
    QTC_ASSERT(dd, return);
    if (dd->m_analysisVersion.value_or("") == version)
        return;
    dd->m_analysisVersion = version;
}

void enableInlineIssues(bool enable)
{
    QTC_ASSERT(dd, return);
    dd->enableInlineIssues(enable);
}

Utils::FilePath findFileForIssuePath(const Utils::FilePath &issuePath)
{
    QTC_ASSERT(dd, return {});
    if (!dd->m_project || !dd->m_currentProjectInfo)
        return {};
    const FilePaths result = dd->m_fileFinder.findFile(issuePath.toUrl());
    if (result.size() == 1)
        return dd->m_project->projectDirectory().resolvePath(result.first());
    return {};
}

} // Axivion::Internal

#include "axivionplugin.moc"