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
|
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0
#include "copilotclient.h"
#include "copilotsettings.h"
#include "copilotsuggestion.h"
#include "copilottr.h"
#include <languageclient/languageclientinterface.h>
#include <languageclient/languageclientmanager.h>
#include <languageclient/languageclientsettings.h>
#include <languageserverprotocol/lsptypes.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <projectexplorer/projectmanager.h>
#include <texteditor/textdocumentlayout.h>
#include <texteditor/texteditor.h>
#include <utils/checkablemessagebox.h>
#include <utils/filepath.h>
#include <utils/passworddialog.h>
#include <QGuiApplication>
#include <QInputDialog>
#include <QLoggingCategory>
#include <QTimer>
#include <QToolButton>
using namespace LanguageServerProtocol;
using namespace TextEditor;
using namespace Utils;
using namespace ProjectExplorer;
using namespace Core;
Q_LOGGING_CATEGORY(copilotClientLog, "qtc.copilot.client", QtWarningMsg)
namespace Copilot::Internal {
static LanguageClient::BaseClientInterface *clientInterface(const FilePath &nodePath,
const FilePath &distPath)
{
CommandLine cmd{nodePath, {distPath.toFSPathString()}};
const auto interface = new LanguageClient::StdIOClientInterface;
interface->setCommandLine(cmd);
return interface;
}
CopilotClient::CopilotClient(const FilePath &nodePath, const FilePath &distPath)
: LanguageClient::Client(clientInterface(nodePath, distPath))
{
setName("Copilot");
LanguageClient::LanguageFilter langFilter;
langFilter.filePattern = {"*"};
setSupportedLanguage(langFilter);
registerCustomMethod("LogMessage", [this](const LanguageServerProtocol::JsonRpcMessage &message) {
QString msg = message.toJsonObject().value("params").toObject().value("message").toString();
qCDebug(copilotClientLog) << message.toJsonObject()
.value("params")
.toObject()
.value("message")
.toString();
if (msg.contains("Socket Connect returned status code,407")) {
qCWarning(copilotClientLog) << "Proxy authentication required";
QMetaObject::invokeMethod(this,
&CopilotClient::proxyAuthenticationFailed,
Qt::QueuedConnection);
}
});
start();
auto openDoc = [this](IDocument *document) {
if (auto *textDocument = qobject_cast<TextDocument *>(document))
openDocument(textDocument);
};
connect(EditorManager::instance(), &EditorManager::documentOpened, this, openDoc);
connect(EditorManager::instance(),
&EditorManager::documentClosed,
this,
[this](IDocument *document) {
if (auto textDocument = qobject_cast<TextDocument *>(document))
closeDocument(textDocument);
});
connect(this, &LanguageClient::Client::initialized, this, &CopilotClient::requestSetEditorInfo);
for (IDocument *doc : DocumentModel::openedDocuments())
openDoc(doc);
}
CopilotClient::~CopilotClient()
{
for (IEditor *editor : DocumentModel::editorsForOpenedDocuments()) {
if (auto textEditor = qobject_cast<BaseTextEditor *>(editor))
textEditor->editorWidget()->removeHoverHandler(&m_hoverHandler);
}
}
void CopilotClient::openDocument(TextDocument *document)
{
auto project = ProjectManager::projectForFile(document->filePath());
if (!isEnabled(project))
return;
Client::openDocument(document);
connect(document,
&TextDocument::contentsChangedWithPosition,
this,
[this, document](int position, int charsRemoved, int charsAdded) {
Q_UNUSED(charsRemoved)
if (!settings().autoComplete())
return;
auto project = ProjectManager::projectForFile(document->filePath());
if (!isEnabled(project))
return;
auto textEditor = BaseTextEditor::currentTextEditor();
if (!textEditor || textEditor->document() != document)
return;
TextEditorWidget *widget = textEditor->editorWidget();
if (widget->isReadOnly() || widget->multiTextCursor().hasMultipleCursors())
return;
const int cursorPosition = widget->textCursor().position();
if (cursorPosition < position || cursorPosition > position + charsAdded)
return;
scheduleRequest(widget);
});
}
void CopilotClient::scheduleRequest(TextEditorWidget *editor)
{
cancelRunningRequest(editor);
auto it = m_scheduledRequests.find(editor);
if (it == m_scheduledRequests.end()) {
auto timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, &QTimer::timeout, this, [this, editor]() {
if (m_scheduledRequests[editor].cursorPosition == editor->textCursor().position())
requestCompletions(editor);
});
connect(editor, &TextEditorWidget::destroyed, this, [this, editor]() {
delete m_scheduledRequests.take(editor).timer;
cancelRunningRequest(editor);
});
connect(editor, &TextEditorWidget::cursorPositionChanged, this, [this, editor] {
cancelRunningRequest(editor);
});
it = m_scheduledRequests.insert(editor, {editor->textCursor().position(), timer});
} else {
it->cursorPosition = editor->textCursor().position();
}
it->timer->start(500);
}
void CopilotClient::requestCompletions(TextEditorWidget *editor)
{
auto project = ProjectManager::projectForFile(editor->textDocument()->filePath());
if (!isEnabled(project))
return;
MultiTextCursor cursor = editor->multiTextCursor();
if (cursor.hasMultipleCursors() || cursor.hasSelection() || editor->suggestionVisible())
return;
const FilePath filePath = editor->textDocument()->filePath();
GetCompletionRequest request{
{TextDocumentIdentifier(hostPathToServerUri(filePath)),
documentVersion(filePath),
Position(cursor.mainCursor())}};
request.setResponseCallback([this, editor = QPointer<TextEditorWidget>(editor)](
const GetCompletionRequest::Response &response) {
QTC_ASSERT(editor, return);
handleCompletions(response, editor);
});
m_runningRequests[editor] = request;
sendMessage(request);
}
void CopilotClient::handleCompletions(const GetCompletionRequest::Response &response,
TextEditorWidget *editor)
{
if (response.error())
log(*response.error());
int requestPosition = -1;
if (const auto requestParams = m_runningRequests.take(editor).params())
requestPosition = requestParams->position().toPositionInDocument(editor->document());
const MultiTextCursor cursors = editor->multiTextCursor();
if (cursors.hasMultipleCursors())
return;
if (cursors.hasSelection() || cursors.mainCursor().position() != requestPosition)
return;
if (const std::optional<GetCompletionResponse> result = response.result()) {
auto isValidCompletion = [](const Completion &completion) {
return completion.isValid() && !completion.text().trimmed().isEmpty();
};
QList<Completion> completions = Utils::filtered(result->completions().toListOrEmpty(),
isValidCompletion);
// remove trailing whitespaces from the end of the completions
for (Completion &completion : completions) {
const LanguageServerProtocol::Range range = completion.range();
if (range.start().line() != range.end().line())
continue; // do not remove trailing whitespaces for multi-line replacements
const QString completionText = completion.text();
const int end = int(completionText.size()) - 1; // empty strings have been removed above
int delta = 0;
while (delta <= end && completionText[end - delta].isSpace())
++delta;
if (delta > 0)
completion.setText(completionText.chopped(delta));
}
if (completions.isEmpty())
return;
editor->insertSuggestion(
std::make_unique<CopilotSuggestion>(completions, editor->document()));
editor->addHoverHandler(&m_hoverHandler);
}
}
void CopilotClient::cancelRunningRequest(TextEditor::TextEditorWidget *editor)
{
const auto it = m_runningRequests.constFind(editor);
if (it == m_runningRequests.constEnd())
return;
cancelRequest(it->id());
m_runningRequests.erase(it);
}
static QString currentProxyPassword;
void CopilotClient::requestSetEditorInfo()
{
if (settings().saveProxyPassword())
currentProxyPassword = settings().proxyPassword();
const EditorInfo editorInfo{QCoreApplication::applicationVersion(),
QGuiApplication::applicationDisplayName()};
const EditorPluginInfo editorPluginInfo{QCoreApplication::applicationVersion(),
"Qt Creator Copilot plugin"};
SetEditorInfoParams params(editorInfo, editorPluginInfo);
if (settings().useProxy()) {
params.setNetworkProxy(
Copilot::NetworkProxy{settings().proxyHost(),
static_cast<int>(settings().proxyPort()),
settings().proxyUser(),
currentProxyPassword,
settings().proxyRejectUnauthorized()});
}
SetEditorInfoRequest request(params);
sendMessage(request);
}
void CopilotClient::requestCheckStatus(
bool localChecksOnly, std::function<void(const CheckStatusRequest::Response &response)> callback)
{
CheckStatusRequest request{localChecksOnly};
request.setResponseCallback(callback);
sendMessage(request);
}
void CopilotClient::requestSignOut(
std::function<void(const SignOutRequest::Response &response)> callback)
{
SignOutRequest request;
request.setResponseCallback(callback);
sendMessage(request);
}
void CopilotClient::requestSignInInitiate(
std::function<void(const SignInInitiateRequest::Response &response)> callback)
{
SignInInitiateRequest request;
request.setResponseCallback(callback);
sendMessage(request);
}
void CopilotClient::requestSignInConfirm(
const QString &userCode,
std::function<void(const SignInConfirmRequest::Response &response)> callback)
{
SignInConfirmRequest request(userCode);
request.setResponseCallback(callback);
sendMessage(request);
}
bool CopilotClient::canOpenProject(Project *project)
{
return isEnabled(project);
}
bool CopilotClient::isEnabled(Project *project)
{
if (!project)
return settings().enableCopilot();
CopilotProjectSettings settings(project);
return settings.isEnabled();
}
void CopilotClient::proxyAuthenticationFailed()
{
static bool doNotAskAgain = false;
if (m_isAskingForPassword || !settings().enableCopilot())
return;
m_isAskingForPassword = true;
auto answer = PasswordDialog::getUserAndPassword(
Tr::tr("Copilot"),
Tr::tr("Proxy username and password required:"),
Tr::tr("Do not ask again. This will disable Copilot for now."),
settings().proxyUser(),
&doNotAskAgain,
Core::ICore::dialogParent());
if (answer) {
settings().proxyUser.setValue(answer->first);
currentProxyPassword = answer->second;
} else {
settings().enableCopilot.setValue(false);
}
if (settings().saveProxyPassword())
settings().proxyPassword.setValue(currentProxyPassword);
settings().apply();
m_isAskingForPassword = false;
}
} // namespace Copilot::Internal
|