File: outputmodel.cpp

package info (click to toggle)
kdevelop 4%3A22.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 70,096 kB
  • sloc: cpp: 284,635; javascript: 3,558; python: 3,422; sh: 1,319; ansic: 685; xml: 331; php: 95; lisp: 66; makefile: 39; sed: 12
file content (475 lines) | stat: -rw-r--r-- 13,065 bytes parent folder | download
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
/*
    SPDX-FileCopyrightText: 2007 Andreas Pakulat <apaku@gmx.de>
    SPDX-FileCopyrightText: 2010 Aleix Pol Gonzalez <aleixpol@kde.org>
    SPDX-FileCopyrightText: 2012 Morten Danielsen Volden <mvolden2@gmail.com>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "outputmodel.h"
#include "filtereditem.h"
#include "outputfilteringstrategies.h"
#include "debug.h"

#include <interfaces/icore.h>
#include <interfaces/idocumentcontroller.h>
#include <util/kdevstringhandler.h>

#include <QStringList>
#include <QTimer>
#include <QThread>
#include <QFont>
#include <QFontDatabase>

#include <functional>
#include <set>

namespace KDevelop
{

/**
 * Number of lines that are processed in one go before we notify the GUI thread
 * about the result. It is generally faster to add multiple items to a model
 * in one go compared to adding each item independently.
 */
static const int BATCH_SIZE = 50;

/**
 * Time in ms that we wait in the parse worker for new incoming lines before
 * actually processing them. If we already have enough for one batch though
 * we process immediately.
 */
static const int BATCH_AGGREGATE_TIME_DELAY = 50;

class ParseWorker : public QObject
{
    Q_OBJECT
public:
    ParseWorker()
        : QObject(nullptr)
        , m_filter(new NoFilterStrategy)
        , m_timer(new QTimer(this))
    {
        m_timer->setInterval(BATCH_AGGREGATE_TIME_DELAY);
        m_timer->setSingleShot(true);
        connect(m_timer, &QTimer::timeout, this, &ParseWorker::process);
    }

public Q_SLOTS:
    void changeFilterStrategy( KDevelop::IFilterStrategy* newFilterStrategy )
    {
        m_filter = QSharedPointer<IFilterStrategy>( newFilterStrategy );
    }

    void addLines( const QStringList& lines )
    {
        m_cachedLines << lines;

        if (m_cachedLines.size() >= BATCH_SIZE) {
            // if enough lines were added, process immediately
            m_timer->stop();
            process();
        } else if (!m_timer->isActive()) {
            m_timer->start();
        }
    }

    void flushBuffers()
    {
        m_timer->stop();
        process();
        emit allDone();
    }

Q_SIGNALS:
    void parsedBatch(const QVector<KDevelop::FilteredItem>& filteredItems);
    void progress(const KDevelop::IFilterStrategy::Progress& progress);
    void allDone();

private Q_SLOTS:
    /**
     * Process *all* cached lines, emit parsedBatch for each batch
     */
    void process()
    {
        QVector<KDevelop::FilteredItem> filteredItems;
        filteredItems.reserve(qMin(BATCH_SIZE, m_cachedLines.size()));

        // apply pre-filtering functions
        std::transform(m_cachedLines.constBegin(), m_cachedLines.constEnd(),
                       m_cachedLines.begin(), &KDevelop::stripAnsiSequences);

        // apply filtering strategy
        for (const QString& line : qAsConst(m_cachedLines)) {
            FilteredItem item = m_filter->errorInLine(line);
            if( item.type == FilteredItem::InvalidItem ) {
                item = m_filter->actionInLine(line);
            }

            filteredItems << item;

            auto progress = m_filter->progressInLine(line);
            if (progress.percent >= 0 && m_progress.percent != progress.percent) {
                m_progress = progress;
                emit this->progress(m_progress);
            }

            if( filteredItems.size() == BATCH_SIZE ) {
                emit parsedBatch(filteredItems);
                filteredItems.clear();
                filteredItems.reserve(qMin(BATCH_SIZE, m_cachedLines.size()));
            }
        }

        // Make sure to emit the rest as well
        if( !filteredItems.isEmpty() ) {
            emit parsedBatch(filteredItems);
        }
        m_cachedLines.clear();
    }

private:
    QSharedPointer<IFilterStrategy> m_filter;
    QStringList m_cachedLines;

    QTimer* m_timer;
    IFilterStrategy::Progress m_progress;
};

class ParsingThread
{
public:
    ParsingThread()
    {
        m_thread.setObjectName(QStringLiteral("OutputFilterThread"));
    }
    virtual ~ParsingThread()
    {
        if (m_thread.isRunning()) {
            m_thread.quit();
            m_thread.wait();
        }
    }
    void addWorker(ParseWorker* worker)
    {
        if (!m_thread.isRunning()) {
            m_thread.start();
        }
        worker->moveToThread(&m_thread);
    }
private:
    QThread m_thread;
};

Q_GLOBAL_STATIC(ParsingThread, s_parsingThread)

class OutputModelPrivate
{
public:
    explicit OutputModelPrivate( OutputModel* model, const QUrl& builddir = QUrl() );
    ~OutputModelPrivate();
    bool isValidIndex( const QModelIndex&, int currentRowCount ) const;

    OutputModel* model;
    ParseWorker* worker;

    QVector<FilteredItem> m_filteredItems;
    // We use std::set because that is ordered
    std::set<int> m_errorItems; // Indices of all items that we want to move to using previous and next
    QUrl m_buildDir;

    void linesParsed(const QVector<KDevelop::FilteredItem>& items)
    {
        model->beginInsertRows( QModelIndex(), model->rowCount(), model->rowCount() + items.size() -  1);

        m_filteredItems.reserve(m_filteredItems.size() + items.size());
        for (const FilteredItem& item : items) {
            if( item.type == FilteredItem::ErrorItem ) {
                m_errorItems.insert(m_filteredItems.size());
            }
            m_filteredItems << item;
        }

        model->endInsertRows();
    }
};

OutputModelPrivate::OutputModelPrivate( OutputModel* model_, const QUrl& builddir)
: model(model_)
, worker(new ParseWorker )
, m_buildDir( builddir )
{
    qRegisterMetaType<QVector<KDevelop::FilteredItem> >();
    qRegisterMetaType<KDevelop::IFilterStrategy*>();
    qRegisterMetaType<KDevelop::IFilterStrategy::Progress>();

    s_parsingThread->addWorker(worker);
    model->connect(worker, &ParseWorker::parsedBatch,
                   model, [=] (const QVector<KDevelop::FilteredItem>& items) { linesParsed(items); });
    model->connect(worker, &ParseWorker::allDone,
                   model, &OutputModel::allDone);
    model->connect(worker, &ParseWorker::progress,
                   model, &OutputModel::progress);
}

bool OutputModelPrivate::isValidIndex( const QModelIndex& idx, int currentRowCount ) const
{
    return ( idx.isValid() && idx.row() >= 0 && idx.row() < currentRowCount && idx.column() == 0 );
}

OutputModelPrivate::~OutputModelPrivate()
{
    worker->deleteLater();
}

OutputModel::OutputModel( const QUrl& builddir, QObject* parent )
: QAbstractListModel(parent)
, d_ptr(new OutputModelPrivate(this, builddir))
{
}

OutputModel::OutputModel( QObject* parent )
    : QAbstractListModel(parent)
    , d_ptr(new OutputModelPrivate(this))
{
}

OutputModel::~OutputModel() = default;

QVariant OutputModel::data(const QModelIndex& idx , int role ) const
{
    Q_D(const OutputModel);

    if( d->isValidIndex(idx, rowCount()) )
    {
        switch( role )
        {
            case Qt::DisplayRole:
                return d->m_filteredItems.at( idx.row() ).originalLine;
            case OutputModel::OutputItemTypeRole:
                return static_cast<int>(d->m_filteredItems.at( idx.row() ).type);
            case Qt::FontRole:
                return QFontDatabase::systemFont(QFontDatabase::FixedFont);
        }
    }
    return QVariant();
}

int OutputModel::rowCount( const QModelIndex& parent ) const
{
    Q_D(const OutputModel);

    if( !parent.isValid() )
        return d->m_filteredItems.count();
    return 0;
}

QVariant OutputModel::headerData( int, Qt::Orientation, int ) const
{
    return QVariant();
}

void OutputModel::activate( const QModelIndex& index )
{
    Q_D(OutputModel);

    if( index.model() != this || !d->isValidIndex(index, rowCount()) )
    {
        return;
    }
    qCDebug(OUTPUTVIEW) << "Model activated" << index.row();


    FilteredItem item = d->m_filteredItems.at( index.row() );
    if( item.isActivatable )
    {
        qCDebug(OUTPUTVIEW) << "activating:" << item.lineNo << item.url;
        KTextEditor::Cursor range( item.lineNo, item.columnNo );
        KDevelop::IDocumentController *docCtrl = KDevelop::ICore::self()->documentController();
        QUrl url = item.url;
        if (item.url.isEmpty()) {
            qCWarning(OUTPUTVIEW) << "trying to open empty url";
            return;
        }
        if(url.isRelative()) {
            url = d->m_buildDir.resolved(url);
        }
        Q_ASSERT(!url.isRelative());
        docCtrl->openDocument( url, range );
    } else {
        qCDebug(OUTPUTVIEW) << "not an activateable item";
    }
}

QModelIndex OutputModel::firstHighlightIndex()
{
    Q_D(OutputModel);

    if( !d->m_errorItems.empty() ) {
        return index( *d->m_errorItems.begin(), 0, QModelIndex() );
    }

    for( int row = 0; row < rowCount(); ++row ) {
        if( d->m_filteredItems.at( row ).isActivatable ) {
            return index( row, 0, QModelIndex() );
        }
    }

    return QModelIndex();
}

QModelIndex OutputModel::nextHighlightIndex( const QModelIndex &currentIdx )
{
    Q_D(OutputModel);

    int startrow = d->isValidIndex(currentIdx, rowCount()) ? currentIdx.row() + 1 : 0;

    if( !d->m_errorItems.empty() )
    {
        qCDebug(OUTPUTVIEW) << "searching next error";
        // Jump to the next error item
        auto next = d->m_errorItems.lower_bound( startrow );
        if( next == d->m_errorItems.end() )
            next = d->m_errorItems.begin();

        return index( *next, 0, QModelIndex() );
    }

    for( int row = 0; row < rowCount(); ++row )
    {
        int currow = (startrow + row) % rowCount();
        if( d->m_filteredItems.at( currow ).isActivatable )
        {
            return index( currow, 0, QModelIndex() );
        }
    }
    return QModelIndex();
}

QModelIndex OutputModel::previousHighlightIndex( const QModelIndex &currentIdx )
{
    Q_D(OutputModel);

    //We have to ensure that startrow is >= rowCount - 1 to get a positive value from the % operation.
    int startrow = rowCount() + (d->isValidIndex(currentIdx, rowCount()) ? currentIdx.row() : rowCount()) - 1;

    if(!d->m_errorItems.empty())
    {
        qCDebug(OUTPUTVIEW) << "searching previous error";

        // Jump to the previous error item
        auto previous = d->m_errorItems.lower_bound( currentIdx.row() );

        if( previous == d->m_errorItems.begin() )
            previous = d->m_errorItems.end();

        --previous;

        return index( *previous, 0, QModelIndex() );
    }

    for ( int row = 0; row < rowCount(); ++row )
    {
        int currow = (startrow - row) % rowCount();
        if( d->m_filteredItems.at( currow ).isActivatable )
        {
            return index( currow, 0, QModelIndex() );
        }
    }
    return QModelIndex();
}

QModelIndex OutputModel::lastHighlightIndex()
{
    Q_D(OutputModel);

    if( !d->m_errorItems.empty() ) {
        return index( *d->m_errorItems.rbegin(), 0, QModelIndex() );
    }

    for( int row = rowCount()-1; row >=0; --row ) {
        if( d->m_filteredItems.at( row ).isActivatable ) {
            return index( row, 0, QModelIndex() );
        }
    }

    return QModelIndex();
}

void OutputModel::setFilteringStrategy(const OutputFilterStrategy& currentStrategy)
{
    Q_D(OutputModel);

    // TODO: Turn into factory, decouple from OutputModel
    IFilterStrategy* filter = nullptr;
    switch( currentStrategy )
    {
        case NoFilter:
            filter = new NoFilterStrategy;
            break;
        case CompilerFilter:
            filter = new CompilerFilterStrategy( d->m_buildDir );
            break;
        case ScriptErrorFilter:
            filter = new ScriptErrorFilterStrategy;
            break;
        case NativeAppErrorFilter:
            filter = new NativeAppErrorFilterStrategy;
            break;
        case StaticAnalysisFilter:
            filter = new StaticAnalysisFilterStrategy;
            break;
    }
    if (!filter) {
        filter = new NoFilterStrategy;
    }

    QMetaObject::invokeMethod(d->worker, "changeFilterStrategy",
                              Q_ARG(KDevelop::IFilterStrategy*, filter));
}

void OutputModel::setFilteringStrategy(IFilterStrategy* filterStrategy)
{
    Q_D(OutputModel);

    QMetaObject::invokeMethod(d->worker, "changeFilterStrategy",
                              Q_ARG(KDevelop::IFilterStrategy*, filterStrategy));
}

void OutputModel::appendLines( const QStringList& lines )
{
    Q_D(OutputModel);

    if( lines.isEmpty() )
        return;

    QMetaObject::invokeMethod(d->worker, "addLines",
                              Q_ARG(QStringList, lines));
}

void OutputModel::appendLine( const QString& line )
{
    appendLines( QStringList() << line );
}

void OutputModel::ensureAllDone()
{
    Q_D(OutputModel);

    QMetaObject::invokeMethod(d->worker, "flushBuffers");
}

void OutputModel::clear()
{
    Q_D(OutputModel);

    ensureAllDone();
    beginResetModel();
    d->m_filteredItems.clear();
    endResetModel();
}

}

#include "outputmodel.moc"
#include "moc_outputmodel.cpp"