aboutsummaryrefslogtreecommitdiffstats
path: root/SQLiteStudio3/coreSQLiteStudio/services/codeformatter.cpp
blob: e17032b49ca552e0f6b35ad38ec44629919a5e7b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "codeformatter.h"
#include "parser/parser.h"
#include "plugins/codeformatterplugin.h"
#include "services/pluginmanager.h"
#include "common/compatibility.h"
#include <QDebug>

void CodeFormatter::setFormatter(const QString& lang, CodeFormatterPlugin *formatterPlugin)
{
    currentFormatter[lang] = formatterPlugin;
}

CodeFormatterPlugin* CodeFormatter::getFormatter(const QString& lang)
{
    if (hasFormatter(lang))
        return currentFormatter[lang];

    return nullptr;
}

bool CodeFormatter::hasFormatter(const QString& lang)
{
    return currentFormatter.contains(lang);
}

void CodeFormatter::fullUpdate()
{
    availableFormatters.clear();
    QList<CodeFormatterPlugin*> formatterPlugins = PLUGINS->getLoadedPlugins<CodeFormatterPlugin>();
    for (CodeFormatterPlugin* plugin : formatterPlugins)
        availableFormatters[plugin->getLanguage()][plugin->getName()] = plugin;

    updateCurrent();
}

void CodeFormatter::updateCurrent()
{
    if (modifyingConfig)
        return;

    modifyingConfig = true;

    bool modified = false;
    currentFormatter.clear();
    QHash<QString,QVariant> config = CFG_CORE.General.ActiveCodeFormatter.get();
    QString name;
    QStringList names = availableFormatters.keys();
    sSort(names);
    for (const QString& lang : names)
    {
        name = config[lang].toString();
        if (config.contains(lang) && availableFormatters[lang].contains(name))
        {
            currentFormatter[lang] = availableFormatters[lang][name];
        }
        else
        {
            currentFormatter[lang] = availableFormatters[lang].begin().value();
            config[lang] = currentFormatter[lang]->getName();
            modified = true;
        }
    }

    if (modified)
        CFG_CORE.General.ActiveCodeFormatter.set(config);

    modifyingConfig = false;
}

void CodeFormatter::storeCurrentSettings()
{
    QHash<QString,QVariant> config = CFG_CORE.General.ActiveCodeFormatter.get();
    QHashIterator<QString,CodeFormatterPlugin*> it(currentFormatter);
    while (it.hasNext())
    {
        it.next();
        config[it.key()] = it.value()->getName();
    }

    CFG_CORE.General.ActiveCodeFormatter.set(config);
}

QString CodeFormatter::format(const QString& lang, const QString& code, Db* contextDb)
{
    if (!hasFormatter(lang))
    {
        qWarning() << "No formatter plugin defined for CodeFormatter for language:" << lang;
        return code;
    }

    return currentFormatter[lang]->format(code, contextDb);
}