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

#include "executefilter.h"

#include "../coreplugintr.h"
#include "../icore.h"
#include "../editormanager/editormanager.h"
#include "../messagemanager.h"

#include <utils/algorithm.h>
#include <utils/environment.h>
#include <utils/macroexpander.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>

#include <QJsonArray>
#include <QJsonObject>
#include <QMessageBox>

using namespace Utils;

namespace Core::Internal {

ExecuteFilter::ExecuteFilter()
{
    setId("Execute custom commands");
    setDisplayName(Tr::tr("Execute Custom Commands"));
    setDescription(Tr::tr(
        "Runs an arbitrary command with arguments. The command is searched for in the PATH "
        "environment variable if needed. Note that the command is run directly, not in a shell."));
    setDefaultShortcutString("!");
    setPriority(High);
    setDefaultIncludedByDefault(false);
}

ExecuteFilter::~ExecuteFilter()
{
    removeProcess();
}

LocatorMatcherTasks ExecuteFilter::matchers()
{
    using namespace Tasking;

    TreeStorage<LocatorStorage> storage;

    const auto onSetup = [=] {
        const QString input = storage->input();
        LocatorFilterEntries entries;
        if (!input.isEmpty()) { // avoid empty entry
            LocatorFilterEntry entry;
            entry.displayName = input;
            entry.acceptor = [this, input] { acceptCommand(input); return AcceptResult(); };
            entries.append(entry);
        }
        LocatorFilterEntries others;
        const Qt::CaseSensitivity entryCaseSensitivity = caseSensitivity(input);
        for (const QString &cmd : std::as_const(m_commandHistory)) {
            if (cmd == input) // avoid repeated entry
                continue;
            LocatorFilterEntry entry;
            entry.displayName = cmd;
            entry.acceptor = [this, cmd] { acceptCommand(cmd); return AcceptResult(); };
            const int index = cmd.indexOf(input, 0, entryCaseSensitivity);
            if (index >= 0) {
                entry.highlightInfo = {index, int(input.length())};
                entries.append(entry);
            } else {
                others.append(entry);
            }
        }
        storage->reportOutput(entries + others);
    };
    return {{Sync(onSetup), storage}};
}

void ExecuteFilter::acceptCommand(const QString &cmd)
{
    const QString displayName = cmd.trimmed();
    const int index = m_commandHistory.indexOf(displayName);
    if (index != -1 && index != 0)
        m_commandHistory.removeAt(index);
    if (index != 0)
        m_commandHistory.prepend(displayName);
    static const int maxHistory = 100;
    while (m_commandHistory.size() > maxHistory)
        m_commandHistory.removeLast();

    bool found;
    QString workingDirectory = globalMacroExpander()->value("CurrentDocument:Path", &found);
    if (!found || workingDirectory.isEmpty())
        workingDirectory = globalMacroExpander()->value("CurrentDocument:Project:Path", &found);

    const ExecuteData data{CommandLine::fromUserInput(displayName, globalMacroExpander()),
                           FilePath::fromString(workingDirectory)};
    if (m_process) {
        const QString info(Tr::tr("Previous command is still running (\"%1\").\n"
                                  "Do you want to kill it?").arg(headCommand()));
        const auto result = QMessageBox::question(ICore::dialogParent(),
                                                  Tr::tr("Kill Previous Process?"), info,
                                                  QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
                                                  QMessageBox::Yes);
        if (result == QMessageBox::Cancel)
            return;
        if (result == QMessageBox::No) {
            m_taskQueue.enqueue(data);
            return;
        }
        removeProcess();
    }
    m_taskQueue.enqueue(data);
    runHeadCommand();
}

QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future,
                                                    const QString &entry)
{
    QList<LocatorFilterEntry> results;
    if (!entry.isEmpty()) { // avoid empty entry
        LocatorFilterEntry filterEntry;
        filterEntry.displayName = entry;
        filterEntry.acceptor = [this, entry] { acceptCommand(entry); return AcceptResult(); };
        results.append(filterEntry);
    }
    QList<LocatorFilterEntry> others;
    const Qt::CaseSensitivity entryCaseSensitivity = caseSensitivity(entry);
    for (const QString &cmd : std::as_const(m_commandHistory)) {
        if (future.isCanceled())
            break;
        if (cmd == entry) // avoid repeated entry
            continue;
        LocatorFilterEntry filterEntry;
        filterEntry.displayName = cmd;
        filterEntry.acceptor = [this, cmd] { acceptCommand(cmd); return AcceptResult(); };
        const int index = cmd.indexOf(entry, 0, entryCaseSensitivity);
        if (index >= 0) {
            filterEntry.highlightInfo = {index, int(entry.length())};
            results.append(filterEntry);
        } else {
            others.append(filterEntry);
        }
    }
    results.append(others);
    return results;
}

void ExecuteFilter::done()
{
    QTC_ASSERT(m_process, return);
    MessageManager::writeFlashing(m_process->exitMessage());
    EditorManager::updateWindowTitles(); // Refresh VCS topic if needed

    removeProcess();
    runHeadCommand();
}

void ExecuteFilter::readStandardOutput()
{
    QTC_ASSERT(m_process, return);
    const QByteArray data = m_process->readAllRawStandardOutput();
    MessageManager::writeSilently(
        QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stdoutState));
}

void ExecuteFilter::readStandardError()
{
    QTC_ASSERT(m_process, return);
    const QByteArray data = m_process->readAllRawStandardError();
    MessageManager::writeSilently(
        QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stderrState));
}

void ExecuteFilter::runHeadCommand()
{
    if (!m_taskQueue.isEmpty()) {
        const ExecuteData &d = m_taskQueue.head();
        if (d.command.executable().isEmpty()) {
            MessageManager::writeDisrupting(
                Tr::tr("Could not find executable for \"%1\".").arg(d.command.executable().toUserOutput()));
            m_taskQueue.dequeue();
            runHeadCommand();
            return;
        }
        MessageManager::writeDisrupting(Tr::tr("Starting command \"%1\".").arg(headCommand()));
        QTC_CHECK(!m_process);
        createProcess();
        m_process->setWorkingDirectory(d.workingDirectory);
        m_process->setCommand(d.command);
        m_process->start();
    }
}

void ExecuteFilter::createProcess()
{
    if (m_process)
        return;

    m_process = new Process;
    m_process->setEnvironment(Environment::systemEnvironment());
    connect(m_process, &Process::done, this, &ExecuteFilter::done);
    connect(m_process, &Process::readyReadStandardOutput, this, &ExecuteFilter::readStandardOutput);
    connect(m_process, &Process::readyReadStandardError, this, &ExecuteFilter::readStandardError);
}

void ExecuteFilter::removeProcess()
{
    if (!m_process)
        return;

    m_taskQueue.dequeue();
    m_process->deleteLater();
    m_process = nullptr;
}

const char historyKey[] = "history";

void ExecuteFilter::saveState(QJsonObject &object) const
{
    if (!m_commandHistory.isEmpty())
        object.insert(historyKey, QJsonArray::fromStringList(m_commandHistory));
}

void ExecuteFilter::restoreState(const QJsonObject &object)
{
    m_commandHistory = Utils::transform(object.value(historyKey).toArray().toVariantList(),
                                        &QVariant::toString);
}

QString ExecuteFilter::headCommand() const
{
    if (m_taskQueue.isEmpty())
        return QString();
    const ExecuteData &data = m_taskQueue.head();
    return data.command.toUserOutput();
}

} // Core::Internal