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

#include "taskhandlers.h"

#include "projectexplorerconstants.h"
#include "projectexplorertr.h"
#include "taskhub.h"

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/customlanguagemodels.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/vcsmanager.h>
#include <utils/algorithm.h>
#include <utils/aspects.h>
#include <utils/qtcprocess.h>
#include <utils/stringutils.h>

#include <QHash>
#include <QTimer>

#include <memory>
#include <vector>

using namespace Core;
using namespace Utils;

namespace ProjectExplorer {
namespace {
static QPointer<QObject> g_actionParent;
static Core::Context g_cmdContext;
static Internal::RegisterHandlerAction g_onCreateAction;
static Internal::GetHandlerTasks g_getTasks;
static QList<ITaskHandler *> g_toRegister;
static QList<ITaskHandler *> g_taskHandlers;
} // namespace

ITaskHandler::ITaskHandler(QAction *action, const Id &actionId, bool isMultiHandler)
    : m_action(action), m_actionId(actionId), m_isMultiHandler(isMultiHandler)
{
    if (g_actionParent)
        registerHandler();
    else
        g_toRegister << this;
}

ITaskHandler::~ITaskHandler()
{
    g_toRegister.removeOne(this);
    deregisterHandler();
    delete m_action;
}

void ITaskHandler::handle(const Task &task)
{
    QTC_ASSERT(m_isMultiHandler, return);
    handle(Tasks{task});
}

void ITaskHandler::handle(const Tasks &tasks)
{
    QTC_ASSERT(canHandle(tasks), return);
    QTC_ASSERT(!m_isMultiHandler, return);
    handle(tasks.first());
}

bool ITaskHandler::canHandle(const Tasks &tasks) const
{
    if (tasks.isEmpty())
        return false;
    if (m_isMultiHandler)
        return true;
    if (tasks.size() > 1)
        return false;
    return canHandle(tasks.first());
}

void ITaskHandler::registerHandler()
{
    g_taskHandlers.append(this);

    m_action->setParent(g_actionParent);
    QAction *action = m_action;
    connect(m_action, &QAction::triggered, this, [this] { handle(g_getTasks()); });
    if (m_actionId.isValid()) {
        Core::Command *cmd =
            Core::ActionManager::registerAction(m_action, m_actionId, g_cmdContext, true);
        action = cmd->action();
    }
    g_onCreateAction(action);
}

void ITaskHandler::deregisterHandler()
{
    g_taskHandlers.removeOne(this);
}

namespace Internal {
namespace {

class ConfigTaskHandler : public ITaskHandler
{
public:
    ConfigTaskHandler(const Task &pattern, Id page)
        : ITaskHandler(createAction())
        , m_pattern(pattern)
        , m_targetPage(page)
    {}

private:
    bool canHandle(const Task &task) const override
    {
        return task.description() == m_pattern.description()
               && task.category() == m_pattern.category();
    }

    void handle(const Task &task) override
    {
        Q_UNUSED(task)
        ICore::showOptionsDialog(m_targetPage);
    }

    QAction *createAction() const
    {
        auto action = new QAction(ICore::msgShowOptionsDialog());
        action->setToolTip(ICore::msgShowOptionsDialogToolTip());
        return action;
    }

private:
    const Task m_pattern;
    const Id m_targetPage;
};

class CopyTaskHandler : public ITaskHandler
{
public:
    CopyTaskHandler() : ITaskHandler(new Action, Core::Constants::COPY, true) {}

private:
    void handle(const Tasks &tasks) override
    {
        QStringList lines;
        for (const Task &task : tasks) {
            QString type;
            switch (task.type()) {
            case Task::Error:
                //: Task is of type: error
                type = Tr::tr("error:") + QLatin1Char(' ');
                break;
            case Task::Warning:
                //: Task is of type: warning
                type = Tr::tr("warning:") + QLatin1Char(' ');
                break;
            default:
                break;
            }
            lines << task.file().toUserOutput() + ':' + QString::number(task.line())
                         + ": " + type + task.description();
        }
        setClipboardAndSelection(lines.join('\n'));
    }
};

class RemoveTaskHandler : public ITaskHandler
{
public:
    RemoveTaskHandler() : ITaskHandler(createAction(), {}, true) {}

private:
    void handle(const Tasks &tasks) override
    {
        for (const Task &task : tasks)
            TaskHub::removeTask(task);
    }

    QAction *createAction() const
    {
        QAction *removeAction = new QAction(
            Tr::tr("Remove", "Name of the action triggering the removetaskhandler"));
        removeAction->setToolTip(Tr::tr("Remove task from the task list."));
        removeAction->setShortcuts({QKeySequence::Delete, QKeySequence::Backspace});
        removeAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        return removeAction;
    }
};

class ShowInEditorTaskHandler : public ITaskHandler
{
public:
    ShowInEditorTaskHandler() : ITaskHandler(createAction()) {}

private:
    bool isDefaultHandler() const override { return true; }

    bool canHandle(const Task &task) const override
    {
        return task.file().isReadableFile();
    }

    void handle(const Task &task) override
    {
        const int column = task.column() ? task.column() - 1 : 0;
        EditorManager::openEditorAt(
            {task.file(), task.line(), column}, {}, EditorManager::SwitchSplitIfAlreadyVisible);
    }

    QAction *createAction() const
    {
        QAction *showAction = new QAction(Tr::tr("Show in Editor"));
        showAction->setToolTip(Tr::tr("Show task location in an editor."));
        showAction->setShortcut(QKeySequence(Qt::Key_Return));
        showAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        return showAction;
    }
};

class VcsAnnotateTaskHandler : public ITaskHandler
{
public:
    VcsAnnotateTaskHandler() : ITaskHandler(createAction()) {}

private:
    bool canHandle(const Task &task) const override
    {
        if (!task.file().isReadableFile())
            return false;
        IVersionControl *vc = VcsManager::findVersionControlForDirectory(task.file().absolutePath());
        if (!vc)
            return false;
        return vc->supportsOperation(IVersionControl::AnnotateOperation);
    }

    void handle(const Task &task) override
    {
        IVersionControl *vc = VcsManager::findVersionControlForDirectory(task.file().absolutePath());
        QTC_ASSERT(vc, return);
        QTC_ASSERT(vc->supportsOperation(IVersionControl::AnnotateOperation), return);
        vc->vcsAnnotate(task.file().absoluteFilePath(), task.line());
    }

    QAction *createAction() const
    {
        QAction *vcsannotateAction = new QAction(Tr::tr("&Annotate"));
        vcsannotateAction->setToolTip(Tr::tr("Annotate using version control system."));
        return vcsannotateAction;
    }
};

class ExplainWithAiHandler : public ITaskHandler
{
public:
    ExplainWithAiHandler(const QString &model)
        : ITaskHandler(createAction(model))
        , m_model(model)
    {}

private:
    bool canHandle(const Task &task) const override
    {
        Q_UNUSED(task)
        return !availableLanguageModels().isEmpty();
    }

    void handle(const Task &task) override
    {
        const CommandLine cmdLine = commandLineForLanguageModel(m_model);
        QTC_ASSERT(!cmdLine.isEmpty(), return);

        QString prompt;
        if (task.origin().isEmpty())
            prompt += "A software tool has emitted a diagnostic. ";
        else
            prompt += QString("The tool \"%1\" has emitted a diagnostic. ").arg(task.origin());
        prompt += "Please explain what it is about. "
                  "Be as concise and concrete as possible and try to name the root cause."
                  "If you don't know the answer, just say so."
                  "If possible, also provide a solution. "
                  "Do not think for more than a minute. "
                  "Here is the error: ###%1##";
        prompt = prompt.arg(task.description());
        if (task.file().exists()) {
            if (const auto contents = task.file().fileContents()) {
                prompt.append('\n').append(
                    "Ideally, provide your solution in the form of a diff."
                    "Here are the contents of the file that the tool complained about: ###%1###."
                    "The path to the file is ###%2###.");
                prompt = prompt.arg(QString::fromUtf8(*contents), task.file().toUserOutput());
            }
        }
        const auto process = new Process;
        process->setCommand(cmdLine);
        process->setProcessMode(ProcessMode::Writer);
        process->setTextChannelMode(Channel::Output, TextChannelMode::MultiLine);
        process->setTextChannelMode(Channel::Error, TextChannelMode::MultiLine);
        connect(process, &Process::textOnStandardOutput,
                [](const QString &text) { MessageManager::writeFlashing(text); });
        connect(process, &Process::done, [process] {
            MessageManager::writeSilently(
                process->exitMessage(Process::FailureMessageFormat::WithStdErr));
            process->deleteLater();
        });
        connect(process, &Process::started, [process, prompt] {
            process->write(prompt);
            process->closeWriteChannel();
        });
        QTimer::singleShot(60000, process, [process] { process->kill(); });
        MessageManager::writeDisrupting(Tr::tr("Querying %1...").arg(m_model));
        process->start();
    }

    QAction *createAction(const QString &model) const
    {
        const auto action = new QAction(Tr::tr("Get help from %1").arg(model));
        action->setToolTip(Tr::tr("Ask the %1 LLM to help with this issue.").arg(model));
        return action;
    }

    const QString m_model;
};

class AiHandlersManager
{
public:
    AiHandlersManager()
    {
        QObject::connect(&customLanguageModelsContext(), &BaseAspect::changed,
                         g_actionParent, [this] { reset(); });
        reset();
    }

private:
    void reset()
    {
        m_aiTaskHandlers.clear();
        for (const QString &model : availableLanguageModels())
            m_aiTaskHandlers.emplace_back(std::make_unique<ExplainWithAiHandler>(model));
        updateTaskHandlerActionsState();
    }

    std::vector<std::unique_ptr<ExplainWithAiHandler>> m_aiTaskHandlers;
};

} // namespace

void setupTaskHandlers(
    QObject *actionParent,
    const Core::Context &cmdContext,
    const RegisterHandlerAction &onCreateAction,
    const GetHandlerTasks &getTasks)
{
    g_actionParent = actionParent;
    g_cmdContext = cmdContext;
    g_onCreateAction = onCreateAction;
    g_getTasks = getTasks;

    static const ConfigTaskHandler
        configTaskHandler(Task::compilerMissingTask(), Constants::KITS_SETTINGS_PAGE_ID);
    static const CopyTaskHandler copyTaskHandler;
    static const RemoveTaskHandler removeTaskHandler;
    static const ShowInEditorTaskHandler showInEditorTaskHandler;
    static const VcsAnnotateTaskHandler vcsAnnotateTaskHandler;
    static const AiHandlersManager aiHandlersManager;

    registerQueuedTaskHandlers();
}

ITaskHandler *taskHandlerForAction(QAction *action)
{
    return Utils::findOrDefault(g_taskHandlers,
                                [action](ITaskHandler *h) { return h->action() == action; });
}

void updateTaskHandlerActionsState()
{
    const Tasks tasks = g_getTasks();
    for (ITaskHandler * const h : g_taskHandlers)
        h->action()->setEnabled(h->canHandle(tasks));
}

ITaskHandler *defaultTaskHandler()
{
    return Utils::findOrDefault(g_taskHandlers,
                                [](ITaskHandler *h) { return h->isDefaultHandler(); });
}

void registerQueuedTaskHandlers()
{
    for (ITaskHandler * const h : std::as_const(g_toRegister))
        h->registerHandler();
    g_toRegister.clear();
}

} // namespace Internal
} // namespace ProjectExplorer