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

#include "loggingviewer.h"

#include "actionmanager/actionmanager.h"
#include "coreicons.h"
#include "coreplugintr.h"
#include "icore.h"
#include "loggingmanager.h"

#include <utils/algorithm.h>
#include <utils/basetreeview.h>
#include <utils/fileutils.h>
#include <utils/listmodel.h>
#include <utils/qtcassert.h>
#include <utils/theme/theme.h>
#include <utils/utilsicons.h>

#include <QAction>
#include <QClipboard>
#include <QColorDialog>
#include <QComboBox>
#include <QDialog>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLoggingCategory>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QRegularExpression>
#include <QScopeGuard>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>

namespace Core {
namespace Internal {

class LoggingCategoryItem
{
public:
    QString name;
    LoggingCategoryEntry entry;

    static LoggingCategoryItem fromJson(const QJsonObject &object, bool *ok);
};

LoggingCategoryItem LoggingCategoryItem::fromJson(const QJsonObject &object, bool *ok)
{
    if (!object.contains("name")) {
        *ok = false;
        return {};
    }
    const QJsonValue entryVal = object.value("entry");
    if (entryVal.isUndefined()) {
        *ok = false;
        return {};
    }
    const QJsonObject entryObj = entryVal.toObject();
    if (!entryObj.contains("level")) {
        *ok = false;
        return {};
    }

    LoggingCategoryEntry entry;
    entry.level = QtMsgType(entryObj.value("level").toInt());
    entry.enabled = true;
    if (entryObj.contains("color"))
        entry.color = QColor(entryObj.value("color").toString());
    LoggingCategoryItem item {object.value("name").toString(), entry};
    *ok = true;
    return item;
}

class LoggingCategoryModel : public QAbstractListModel
{
    Q_OBJECT
public:
    LoggingCategoryModel() = default;
    ~LoggingCategoryModel() override;

    bool append(const QString &category, const LoggingCategoryEntry &entry = {});
    bool update(const QString &category, const LoggingCategoryEntry &entry);
    int columnCount(const QModelIndex &) const final { return 3; }
    int rowCount(const QModelIndex & = QModelIndex()) const final { return m_categories.count(); }
    QVariant data(const QModelIndex &index, int role) const final;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) final;
    Qt::ItemFlags flags(const QModelIndex &index) const final;
    QVariant headerData(int section, Qt::Orientation orientation,
                        int role = Qt::DisplayRole) const final;
    void reset();
    void setFromManager(LoggingViewManager *manager);
    QList<LoggingCategoryItem> enabledCategories() const;
    void disableAll();

signals:
    void categoryChanged(const QString &category, bool enabled);
    void colorChanged(const QString &category, const QColor &color);
    void logLevelChanged(const QString &category, QtMsgType logLevel);

private:
    QList<LoggingCategoryItem *> m_categories;
};

LoggingCategoryModel::~LoggingCategoryModel()
{
    reset();
}

bool LoggingCategoryModel::append(const QString &category, const LoggingCategoryEntry &entry)
{
    // no check?
    beginInsertRows(QModelIndex(), m_categories.size(), m_categories.size());
    m_categories.append(new LoggingCategoryItem{category, entry});
    endInsertRows();
    return true;
}

bool LoggingCategoryModel::update(const QString &category, const LoggingCategoryEntry &entry)
{
    if (m_categories.size() == 0) // should not happen
        return false;

    int row = 0;
    for (int end = m_categories.size(); row < end; ++row) {
        if (m_categories.at(row)->name == category)
            break;
    }
    if (row == m_categories.size()) // should not happen
        return false;

    setData(index(row, 0), Qt::Checked, Qt::CheckStateRole);
    setData(index(row, 1), LoggingViewManager::messageTypeToString(entry.level), Qt::EditRole);
    setData(index(row, 2), entry.color, Qt::DecorationRole);
    return true;
}

QVariant LoggingCategoryModel::data(const QModelIndex &index, int role) const
{
    static const QColor defaultColor = Utils::creatorTheme()->palette().text().color();
    if (!index.isValid())
        return {};
    if (role == Qt::DisplayRole) {
        if (index.column() == 0)
            return m_categories.at(index.row())->name;
        if (index.column() == 1) {
            return LoggingViewManager::messageTypeToString(
                        m_categories.at(index.row())->entry.level);
        }
    }
    if (role == Qt::DecorationRole && index.column() == 2) {
        const QColor color = m_categories.at(index.row())->entry.color;
        if (color.isValid())
            return color;
        return defaultColor;
    }
    if (role == Qt::CheckStateRole && index.column() == 0) {
        const LoggingCategoryEntry entry = m_categories.at(index.row())->entry;
        return entry.enabled ? Qt::Checked : Qt::Unchecked;
    }
    return {};
}

bool LoggingCategoryModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid())
        return false;

    if (role == Qt::CheckStateRole && index.column() == 0) {
        LoggingCategoryItem *item = m_categories.at(index.row());
        const Qt::CheckState current = item->entry.enabled ? Qt::Checked : Qt::Unchecked;
        if (current != value.toInt()) {
            item->entry.enabled = !item->entry.enabled;
            emit categoryChanged(item->name, item->entry.enabled);
            return true;
        }
    } else if (role == Qt::DecorationRole && index.column() == 2) {
        LoggingCategoryItem *item = m_categories.at(index.row());
        QColor color = value.value<QColor>();
        if (color.isValid() && color != item->entry.color) {
            item->entry.color = color;
            emit colorChanged(item->name, color);
            return true;
        }
    } else if (role == Qt::EditRole && index.column() == 1) {
        LoggingCategoryItem *item = m_categories.at(index.row());
        item->entry.level = LoggingViewManager::messageTypeFromString(value.toString());
        emit logLevelChanged(item->name, item->entry.level);
        return true;
    }

    return false;
}

Qt::ItemFlags LoggingCategoryModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    // ItemIsEnabled should depend on availability (Qt logging enabled?)
    if (index.column() == 0)
        return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    if (index.column() == 1)
        return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QVariant LoggingCategoryModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section >= 0 && section < 3) {
        switch (section) {
        case 0: return Tr::tr("Category");
        case 1: return Tr::tr("Type");
        case 2: return Tr::tr("Color");
        }
    }
    return {};
}

void LoggingCategoryModel::reset()
{
    beginResetModel();
    qDeleteAll(m_categories);
    m_categories.clear();
    endResetModel();
}

void LoggingCategoryModel::setFromManager(LoggingViewManager *manager)
{
    beginResetModel();
    qDeleteAll(m_categories);
    m_categories.clear();
    const QMap<QString, LoggingCategoryEntry> categories = manager->categories();
    auto it = categories.begin();
    for (auto end = categories.end() ; it != end; ++it)
        m_categories.append(new LoggingCategoryItem{it.key(), it.value()});
    endResetModel();
}

QList<LoggingCategoryItem> LoggingCategoryModel::enabledCategories() const
{
    QList<LoggingCategoryItem> result;
    for (auto item : m_categories) {
        if (item->entry.enabled)
            result.append({item->name, item->entry});
    }
    return result;
}

void LoggingCategoryModel::disableAll()
{
    for (int row = 0, end = m_categories.count(); row < end; ++row)
        setData(index(row, 0), Qt::Unchecked, Qt::CheckStateRole);
}

class LoggingLevelDelegate : public QStyledItemDelegate
{
public:
    explicit LoggingLevelDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
    ~LoggingLevelDelegate() = default;

protected:
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const override;
    void setEditorData(QWidget *editor, const QModelIndex &index) const override;
    void setModelData(QWidget *editor, QAbstractItemModel *model,
                      const QModelIndex &index) const override;
};

QWidget *LoggingLevelDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/,
                                            const QModelIndex &index) const
{
    if (!index.isValid() || index.column() != 1)
        return nullptr;
    QComboBox *combo = new QComboBox(parent);
    combo->addItems({ {"Critical"}, {"Warning"}, {"Debug"}, {"Info"} });
    return combo;
}

void LoggingLevelDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (!combo)
        return;

    const int i = combo->findText(index.data().toString());
    if (i >= 0)
        combo->setCurrentIndex(i);
}

void LoggingLevelDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                        const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (combo)
        model->setData(index, combo->currentText());
}

class LogEntry
{
public:
    QString timestamp;
    QString category;
    QString type;
    QString message;

    QString outputLine(bool printTimestamp, bool printType) const
    {
        QString line;
        if (printTimestamp)
            line.append(timestamp + ' ');
        line.append(category);
        if (printType)
            line.append('.' + type.toLower());
        line.append(": ");
        line.append(message);
        line.append('\n');
        return line;
    }
};

class LoggingViewManagerWidget : public QDialog
{
public:
    explicit LoggingViewManagerWidget(QWidget *parent);
    ~LoggingViewManagerWidget()
    {
        setEnabled(false);
        delete m_manager;
    }

    static QColor colorForCategory(const QString &category);
private:
    void showLogViewContextMenu(const QPoint &pos) const;
    void showLogCategoryContextMenu(const QPoint &pos) const;
    void saveLoggingsToFile() const;
    void saveEnabledCategoryPreset() const;
    void loadAndUpdateFromPreset();
    LoggingViewManager *m_manager = nullptr;
    void setCategoryColor(const QString &category, const QColor &color);
    // should category model be owned directly by the manager? or is this duplication of
    // categories in manager and widget beneficial?
    LoggingCategoryModel *m_categoryModel = nullptr;
    Utils::BaseTreeView *m_logView = nullptr;
    Utils::BaseTreeView *m_categoryView = nullptr;
    Utils::ListModel<LogEntry> *m_logModel = nullptr;
    QToolButton *m_timestamps = nullptr;
    QToolButton *m_messageTypes = nullptr;
    static QHash<QString, QColor> m_categoryColor;
};

QHash<QString, QColor> LoggingViewManagerWidget::m_categoryColor;

static QVariant logEntryDataAccessor(const LogEntry &entry, int column, int role)
{
    if (column >= 0 && column <= 3 && (role == Qt::DisplayRole || role == Qt::ToolTipRole)) {
        switch (column) {
        case 0: return entry.timestamp;
        case 1: return entry.category;
        case 2: return entry.type;
        case 3: {
            if (role == Qt::ToolTipRole)
                return entry.message;
            return entry.message.left(1000);
        }
        }
    }
    if (role == Qt::TextAlignmentRole)
        return Qt::AlignTop;
    if (column == 1 && role == Qt::ForegroundRole)
        return LoggingViewManagerWidget::colorForCategory(entry.category);
    return {};
}

LoggingViewManagerWidget::LoggingViewManagerWidget(QWidget *parent)
    : QDialog(parent)
    , m_manager(new LoggingViewManager)
{
    setWindowTitle(Tr::tr("Logging Category Viewer"));
    setModal(false);

    auto mainLayout = new QVBoxLayout;

    auto buttonsLayout = new QHBoxLayout;
    buttonsLayout->setSpacing(0);
    // add further buttons..
    auto save = new QToolButton;
    save->setIcon(Utils::Icons::SAVEFILE.icon());
    save->setToolTip(Tr::tr("Save Log"));
    buttonsLayout->addWidget(save);
    auto clean = new QToolButton;
    clean->setIcon(Utils::Icons::CLEAN.icon());
    clean->setToolTip(Tr::tr("Clear"));
    buttonsLayout->addWidget(clean);
    auto stop = new QToolButton;
    stop->setIcon(Utils::Icons::STOP_SMALL.icon());
    stop->setToolTip(Tr::tr("Stop Logging"));
    buttonsLayout->addWidget(stop);
    auto qtInternal = new QToolButton;
    qtInternal->setIcon(Core::Icons::QTLOGO.icon());
    qtInternal->setToolTip(Tr::tr("Toggle Qt Internal Logging"));
    qtInternal->setCheckable(true);
    qtInternal->setChecked(false);
    buttonsLayout->addWidget(qtInternal);
    auto autoScroll = new QToolButton;
    autoScroll->setIcon(Utils::Icons::ARROW_DOWN.icon());
    autoScroll->setToolTip(Tr::tr("Auto Scroll"));
    autoScroll->setCheckable(true);
    autoScroll->setChecked(true);
    buttonsLayout->addWidget(autoScroll);
    m_timestamps = new QToolButton;
    auto icon = Utils::Icon({{":/utils/images/stopwatch.png", Utils::Theme::PanelTextColorMid}},
                            Utils::Icon::Tint);
    m_timestamps->setIcon(icon.icon());
    m_timestamps->setToolTip(Tr::tr("Timestamps"));
    m_timestamps->setCheckable(true);
    m_timestamps->setChecked(true);
    buttonsLayout->addWidget(m_timestamps);
    m_messageTypes = new QToolButton;
    icon = Utils::Icon({{":/utils/images/message.png", Utils::Theme::PanelTextColorMid}},
                       Utils::Icon::Tint);
    m_messageTypes->setIcon(icon.icon());
    m_messageTypes->setToolTip(Tr::tr("Message Types"));
    m_messageTypes->setCheckable(true);
    m_messageTypes->setChecked(false);
    buttonsLayout->addWidget(m_messageTypes);

    buttonsLayout->addSpacerItem(new QSpacerItem(10, 10, QSizePolicy::Expanding));
    mainLayout->addLayout(buttonsLayout);

    auto horizontal = new QHBoxLayout;
    m_logView = new Utils::BaseTreeView;
    m_logModel = new Utils::ListModel<LogEntry>;
    m_logModel->setHeader({Tr::tr("Timestamp"), Tr::tr("Category"), Tr::tr("Type"), Tr::tr("Message")});
    m_logModel->setDataAccessor(&logEntryDataAccessor);
    m_logView->setModel(m_logModel);
    horizontal->addWidget(m_logView);
    m_logView->setUniformRowHeights(true);
    m_logView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_logView->setFrameStyle(QFrame::Box);
    m_logView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_logView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    m_logView->setColumnHidden(2, true);
    m_logView->setContextMenuPolicy(Qt::CustomContextMenu);

    m_categoryView = new Utils::BaseTreeView;
    m_categoryView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_categoryView->setUniformRowHeights(true);
    m_categoryView->setFrameStyle(QFrame::Box);
    m_categoryView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_categoryView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_categoryView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_categoryModel = new LoggingCategoryModel;
    m_categoryModel->setFromManager(m_manager);
    auto sortFilterModel = new QSortFilterProxyModel(this);
    sortFilterModel->setSourceModel(m_categoryModel);
    sortFilterModel->sort(0);
    m_categoryView->setModel(sortFilterModel);
    m_categoryView->setItemDelegateForColumn(1, new LoggingLevelDelegate(this));
    horizontal->addWidget(m_categoryView);
    horizontal->setStretch(0, 5);
    horizontal->setStretch(1, 3);

    mainLayout->addLayout(horizontal);
    setLayout(mainLayout);
    resize(800, 300);

    connect(m_manager, &LoggingViewManager::receivedLog,
        this, [this](const QString &timestamp,
                     const QString &type,
                     const QString &category,
                     const QString &msg) {
            if (m_logModel->rowCount() >= 1000000) // limit log to 1000000 items
                m_logModel->destroyItem(m_logModel->itemForIndex(m_logModel->index(0, 0)));
            m_logModel->appendItem(LogEntry{timestamp, type, category, msg});
        }, Qt::QueuedConnection);
    connect(m_logModel, &QAbstractItemModel::rowsInserted, this, [this, autoScroll] {
            if (autoScroll->isChecked())
                m_logView->scrollToBottom();
        }, Qt::QueuedConnection);
    connect(m_manager, &LoggingViewManager::foundNewCategory,
            m_categoryModel, &LoggingCategoryModel::append, Qt::QueuedConnection);
    connect(m_manager, &LoggingViewManager::updatedCategory,
            m_categoryModel, &LoggingCategoryModel::update, Qt::QueuedConnection);
    connect(m_categoryModel, &LoggingCategoryModel::categoryChanged,
            m_manager, &LoggingViewManager::setCategoryEnabled);
    connect(m_categoryModel, &LoggingCategoryModel::colorChanged,
            this, &LoggingViewManagerWidget::setCategoryColor);
    connect(m_categoryModel, &LoggingCategoryModel::logLevelChanged,
            m_manager, &LoggingViewManager::setLogLevel);
    connect(m_categoryView, &Utils::BaseTreeView::activated,
            this, [this, sortFilterModel](const QModelIndex &index) {
        const QModelIndex modelIndex = sortFilterModel->mapToSource(index);
        const QVariant value = m_categoryModel->data(modelIndex, Qt::DecorationRole);
        if (!value.isValid())
            return;
        const QColor original = value.value<QColor>();
        if (!original.isValid())
            return;
        QColor changed = QColorDialog::getColor(original, this);
        if (!changed.isValid())
            return;
        if (original != changed)
            m_categoryModel->setData(modelIndex, changed, Qt::DecorationRole);
    });
    connect(save, &QToolButton::clicked,
            this, &LoggingViewManagerWidget::saveLoggingsToFile);
    connect(m_logView, &Utils::BaseTreeView::customContextMenuRequested,
            this, &LoggingViewManagerWidget::showLogViewContextMenu);
    connect(m_categoryView, &Utils::BaseTreeView::customContextMenuRequested,
            this, &LoggingViewManagerWidget::showLogCategoryContextMenu);
    connect(clean, &QToolButton::clicked, m_logModel, &Utils::ListModel<LogEntry>::clear);
    connect(stop, &QToolButton::clicked, this, [this, stop] {
        if (m_manager->isEnabled()) {
            m_manager->setEnabled(false);
            stop->setIcon(Utils::Icons::RUN_SMALL.icon());
            stop->setToolTip(Tr::tr("Start Logging"));
        } else {
            m_manager->setEnabled(true);
            stop->setIcon(Utils::Icons::STOP_SMALL.icon());
            stop->setToolTip(Tr::tr("Stop Logging"));
        }
    });
    connect(qtInternal, &QToolButton::toggled, m_manager, &LoggingViewManager::setListQtInternal);
    connect(m_timestamps, &QToolButton::toggled, this, [this](bool checked){
        m_logView->setColumnHidden(0, !checked);
    });
    connect(m_messageTypes, &QToolButton::toggled, this, [this](bool checked){
        m_logView->setColumnHidden(2, !checked);
    });
}

void LoggingViewManagerWidget::showLogViewContextMenu(const QPoint &pos) const
{
    QMenu m;
    auto copy = new QAction(Tr::tr("Copy Selected Logs"), &m);
    m.addAction(copy);
    auto copyAll = new QAction(Tr::tr("Copy All"), &m);
    m.addAction(copyAll);
    connect(copy, &QAction::triggered, &m, [this] {
        auto selectionModel = m_logView->selectionModel();
        QString copied;
        const bool useTS = m_timestamps->isChecked();
        const bool useLL = m_messageTypes->isChecked();
        for (int row = 0, end = m_logModel->rowCount(); row < end; ++row) {
            if (selectionModel->isRowSelected(row, QModelIndex()))
                copied.append(m_logModel->dataAt(row).outputLine(useTS, useLL));
        }

        QGuiApplication::clipboard()->setText(copied);
    });
    connect(copyAll, &QAction::triggered, &m, [this] {
        QString copied;
        const bool useTS = m_timestamps->isChecked();
        const bool useLL = m_messageTypes->isChecked();

        for (int row = 0, end = m_logModel->rowCount(); row < end; ++row)
            copied.append(m_logModel->dataAt(row).outputLine(useTS, useLL));

        QGuiApplication::clipboard()->setText(copied);
    });
    m.exec(m_logView->mapToGlobal(pos));
}

void LoggingViewManagerWidget::showLogCategoryContextMenu(const QPoint &pos) const
{
    QMenu m;
    // minimal load/save - plugins could later provide presets on their own?
    auto savePreset = new QAction(Tr::tr("Save Enabled as Preset..."), &m);
    m.addAction(savePreset);
    auto loadPreset = new QAction(Tr::tr("Update from Preset..."), &m);
    m.addAction(loadPreset);
    auto uncheckAll = new QAction(Tr::tr("Uncheck All"), &m);
    m.addAction(uncheckAll);
    connect(savePreset, &QAction::triggered,
            this, &LoggingViewManagerWidget::saveEnabledCategoryPreset);
    connect(loadPreset, &QAction::triggered,
            this, &LoggingViewManagerWidget::loadAndUpdateFromPreset);
    connect(uncheckAll, &QAction::triggered,
            m_categoryModel, &LoggingCategoryModel::disableAll);
    m.exec(m_categoryView->mapToGlobal(pos));
}

void LoggingViewManagerWidget::saveLoggingsToFile() const
{
    // should we just let it continue without temporarily disabling?
    const bool enabled = m_manager->isEnabled();
    const QScopeGuard cleanup([this, enabled] { m_manager->setEnabled(enabled); });
    if (enabled)
        m_manager->setEnabled(false);
    const Utils::FilePath fp = Utils::FileUtils::getSaveFilePath(ICore::dialogParent(),
                                                                 Tr::tr("Save Logs As"));
    if (fp.isEmpty())
        return;
    const bool useTS = m_timestamps->isChecked();
    const bool useLL = m_messageTypes->isChecked();
    QFile file(fp.path());
    if (file.open(QIODevice::WriteOnly)) {
        for (int row = 0, end = m_logModel->rowCount(); row < end; ++row) {
            qint64 res = file.write( m_logModel->dataAt(row).outputLine(useTS, useLL).toUtf8());
            if (res == -1) {
                QMessageBox::critical(
                            ICore::dialogParent(), Tr::tr("Error"),
                            Tr::tr("Failed to write logs to \"%1\".").arg(fp.toUserOutput()));
                break;
            }
        }
        file.close();
    } else {
        QMessageBox::critical(
                    ICore::dialogParent(), Tr::tr("Error"),
                    Tr::tr("Failed to open file \"%1\" for writing logs.").arg(fp.toUserOutput()));
    }
}

void LoggingViewManagerWidget::saveEnabledCategoryPreset() const
{
    Utils::FilePath fp = Utils::FileUtils::getSaveFilePath(ICore::dialogParent(),
                                                           Tr::tr("Save Enabled Categories As..."));
    if (fp.isEmpty())
        return;
    const QList<LoggingCategoryItem> enabled = m_categoryModel->enabledCategories();
    // write them to file
    QJsonArray array;
    for (const LoggingCategoryItem &item : enabled) {
        QJsonObject itemObj;
        itemObj.insert("name", item.name);
        QJsonObject entryObj;
        entryObj.insert("level", item.entry.level);
        if (item.entry.color.isValid())
            entryObj.insert("color", item.entry.color.name(QColor::HexArgb));
        itemObj.insert("entry", entryObj);
        array.append(itemObj);
    }
    QJsonDocument doc(array);
    if (!fp.writeFileContents(doc.toJson(QJsonDocument::Compact)))
        QMessageBox::critical(
                    ICore::dialogParent(), Tr::tr("Error"),
                    Tr::tr("Failed to write preset file \"%1\".").arg(fp.toUserOutput()));
}

void LoggingViewManagerWidget::loadAndUpdateFromPreset()
{
    Utils::FilePath fp = Utils::FileUtils::getOpenFilePath(ICore::dialogParent(),
                                                           Tr::tr("Load Enabled Categories From"));
    if (fp.isEmpty())
        return;
    // read file, update categories
    const Utils::expected_str<QByteArray> contents = fp.fileContents();
    if (!contents) {
        QMessageBox::critical(ICore::dialogParent(),
                              Tr::tr("Error"),
                              Tr::tr("Failed to open preset file \"%1\" for reading.")
                                  .arg(fp.toUserOutput()));
        return;
    }
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(*contents, &error);
    if (error.error != QJsonParseError::NoError) {
        QMessageBox::critical(ICore::dialogParent(), Tr::tr("Error"),
                              Tr::tr("Failed to read preset file \"%1\": %2").arg(fp.toUserOutput())
                              .arg(error.errorString()));
        return;
    }
    bool formatError = false;
    QList<LoggingCategoryItem> presetItems;
    if (doc.isArray()) {
        const QJsonArray array = doc.array();
        for (const QJsonValue &value : array) {
            if (!value.isObject()) {
                formatError = true;
                break;
            }
            const QJsonObject itemObj = value.toObject();
            bool ok = true;
            LoggingCategoryItem item = LoggingCategoryItem::fromJson(itemObj, &ok);
            if (!ok) {
                formatError = true;
                break;
            }
            presetItems.append(item);
        }
    } else {
        formatError = true;
    }

    if (formatError) {
        QMessageBox::critical(ICore::dialogParent(), Tr::tr("Error"),
                              Tr::tr("Unexpected preset file format."));
    }
    for (const LoggingCategoryItem &item : presetItems)
        m_manager->appendOrUpdate(item.name, item.entry);
}

QColor LoggingViewManagerWidget::colorForCategory(const QString &category)
{
    auto entry = m_categoryColor.find(category);
    if (entry == m_categoryColor.end())
        return Utils::creatorTheme()->palette().text().color();
    return entry.value();
}

void LoggingViewManagerWidget::setCategoryColor(const QString &category, const QColor &color)
{
    const QColor baseColor = Utils::creatorTheme()->palette().text().color();
    if (color != baseColor)
        m_categoryColor.insert(category, color);
    else
        m_categoryColor.remove(category);
}

void LoggingViewer::showLoggingView()
{
    ActionManager::command(Constants::LOGGER)->action()->setEnabled(false);
    auto widget = new LoggingViewManagerWidget(ICore::dialogParent());
    QObject::connect(widget, &QDialog::finished, widget, [widget] {
        ActionManager::command(Constants::LOGGER)->action()->setEnabled(true);
        // explicitly disable manager again
        widget->deleteLater();
    });
    ICore::registerWindow(widget, Context("Qtc.LogViewer"));
    widget->show();
}

} // namespace Internal
} // namespace Core

#include "loggingviewer.moc"