forked from cristianadam/llama.qtcreator
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathllamachatinput.cpp
More file actions
511 lines (425 loc) · 15.1 KB
/
llamachatinput.cpp
File metadata and controls
511 lines (425 loc) · 15.1 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#include <QDesktopServices>
#include <QDragEnterEvent>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QMimeData>
#include <QTabBar>
#include <QTabWidget>
#include <QTextEdit>
#include <QToolButton>
#include <projectexplorer/projectnodes.h>
#include <utils/algorithm.h>
#include <utils/dropsupport.h>
#include <utils/filepath.h>
#include <utils/fsengine/fileiconprovider.h>
#include "llamachatinput.h"
#include "llamasettings.h"
#include "llamatheme.h"
#include "llamatr.h"
using namespace ProjectExplorer;
using namespace Utils;
namespace LlamaCpp {
static bool isImageFile(const QString &fileName)
{
QString ext = QFileInfo(fileName).suffix().toLower();
return ext == "png" || ext == "jpg" || ext == "jpeg" || ext == "webp" || ext == "svg";
}
static bool isAudioFile(const QString &fileName)
{
QString ext = QFileInfo(fileName).suffix().toLower();
return ext == "wav" || ext == "mp3";
}
static QString mimeNameFromExtension(const QString &ext)
{
if (ext == "png")
return "image/png";
if (ext == "jpg" || ext == "jpeg")
return "image/jpeg";
if (ext == "webp")
return "image/webp";
if (ext == "svg")
return "image/svg+xml";
if (ext == "wav")
return "audio/wav";
if (ext == "mp3")
return "audio/mpeg";
return "application/octet-stream";
}
ChatInput::ChatInput(QWidget *parent)
: QWidget(parent)
{
setObjectName("ChatInput");
setAcceptDrops(true);
buildUI();
applyStyleSheet();
}
void ChatInput::buildUI()
{
auto main = new QVBoxLayout(this);
main->setContentsMargins(0, 0, 0, 0);
auto textAndButtonLayout = new QHBoxLayout;
textAndButtonLayout->setContentsMargins(10, 10, 10, 10);
m_txt = new QTextEdit(this);
m_txt->setPlaceholderText(Tr::tr("Type a message (Shift+Enter for new line)"));
m_txt->setAcceptRichText(false);
m_txt->setAcceptDrops(false);
m_txt->installEventFilter(this);
installEventFilter(this);
QHBoxLayout *btnLayout = new QHBoxLayout;
btnLayout->setContentsMargins(0, 0, 0, 0);
m_toolsButton = new QToolButton(this);
m_toolsButton->setText("O");
m_toolsButton->setCheckable(true);
const bool toolsInitiallyEnabled = settings().toolsEnabled();
m_toolsButton->setChecked(toolsInitiallyEnabled);
m_toolsButton->setToolTip(toolsInitiallyEnabled
? Tr::tr("Disable Tools usage")
: Tr::tr("Enable Tools usage"));
connect(m_toolsButton, &QToolButton::clicked, this, [this](bool checked) {
settings().toolsEnabled.setValue(checked);
settings().writeSettings();
m_toolsButton->setToolTip(checked ? Tr::tr("Disable Tools usage")
: Tr::tr("Enable Tools usage"));
});
m_attachButton = new QToolButton(this);
m_attachButton->setText("G");
m_attachButton->setToolTip(Tr::tr("Attach file"));
connect(m_attachButton, &QToolButton::clicked, [this]() {
const QStringList files = QFileDialog::getOpenFileNames(this);
if (!files.isEmpty())
addFilesFromLocalPaths(files);
});
m_sendStopButton = new QToolButton(this);
connect(m_sendStopButton, &QToolButton::clicked, this, [this] {
if (!m_isGenerating)
onSendClicked();
else
onStopClicked();
});
btnLayout->addWidget(m_toolsButton);
btnLayout->addWidget(m_attachButton);
btnLayout->addWidget(m_sendStopButton);
textAndButtonLayout->addWidget(m_txt);
textAndButtonLayout->addLayout(btnLayout);
m_attachedFilesBar = new QTabBar(this);
m_attachedFilesBar->setAcceptDrops(false);
m_attachedFilesBar->setVisible(false);
m_attachedFilesBar->setTabsClosable(true);
m_attachedFilesBar->setDocumentMode(true);
m_attachedFilesBar->setExpanding(false);
m_attachedFilesBar->setDrawBase(false);
m_attachedFilesBar->setElideMode(Qt::ElideMiddle);
QSizePolicy sp(QSizePolicy::Preferred, QSizePolicy::Fixed);
sp.setHorizontalStretch(1);
sp.setVerticalStretch(0);
sp.setHeightForWidth(sizePolicy().hasHeightForWidth());
m_attachedFilesBar->setSizePolicy(sp);
connect(m_attachedFilesBar, &QTabBar::tabCloseRequested, this, [this](int index) {
m_attachedFilesBar->removeTab(index);
m_attachedFiles.removeAt(index);
if (m_attachedFilesBar->count() == 0) {
m_attachedFilesBar->setVisible(false);
updateMaximumHeight();
}
});
main->addLayout(textAndButtonLayout);
main->addWidget(m_attachedFilesBar);
updateUI();
}
void ChatInput::updateUI()
{
if (m_isGenerating) {
m_sendStopButton->setToolTip(Tr::tr("Stop assistant answer generation"));
m_sendStopButton->setText("I");
} else {
m_sendStopButton->setToolTip(Tr::tr("Send message to assistant"));
m_sendStopButton->setText("B");
}
}
void ChatInput::applyStyleSheet()
{
setAttribute(Qt::WA_StyledBackground, true);
setStyleSheet(replaceThemeColorNamesWithRGBNames(R"(
QWidget#ChatInput {
background-color: Token_Background_Muted;
border: 1px solid Token_Foreground_Muted;
border-radius: 8px;
}
QWidget#ChatInput:hover {
border: 1px solid Token_Foreground_Default;
}
QTextEdit {
background-color: Token_Background_Muted;
border: 0px
}
QToolButton {
border: 1px solid Token_Foreground_Muted;
font-family: heroicons_outline;
font-size: 18px;
border-radius: 6px;
padding: 6px -2px;
}
QToolButton:hover {
background-color: Token_Foreground_Muted;
}
QToolButton:checked {
color: Token_Text_Accent;
}
QToolButton:unchecked {
color: Token_Text_Default;
}
QTabBar {
background-color: Token_Background_Muted;
height: 22px;
margin-left: 10px;
margin-right: 10px;
margin-bottom: 1px;
}
QTabBar::tear {
width: 0px;
}
QTabBar::close-button {
subcontrol-position: right;
}
QTabBar::tab {
background-color: Token_Background_Muted;
color: Token_Text_Default;
border: 1px solid Token_Foreground_Muted;
border-radius: 6px;
height: 20px;
min-width: 5ex;
margin-top: 4px;
margin-bottom: 4px;
margin-left: 4px;
}
QTabBar::tab:hover {
background-color: Token_Foreground_Muted;
}
)"));
}
void ChatInput::cleanUp()
{
m_txt->clear();
while (m_attachedFilesBar->count() > 0) {
m_attachedFilesBar->removeTab(0);
}
m_attachedFilesBar->setVisible(false);
m_attachedFiles.clear();
updateMaximumHeight();
}
void ChatInput::onSendClicked()
{
QString message = m_txt->toPlainText().trimmed();
if (!message.isEmpty())
emit sendRequested(message, getExtraFromAttachedFiles());
cleanUp();
}
void ChatInput::onStopClicked()
{
emit stopRequested();
}
void ChatInput::addFilesFromLocalPaths(const QStringList &filePaths)
{
for (const QString &path : filePaths) {
FilePath localFile = FilePath::fromString(path);
if (!localFile.isLocal())
continue; // skip non‑local files
const QString fileName = localFile.fileName();
// If a file with the same name already exists, just replace its
// contents – we don't want duplicate tabs.
auto existing = std::ranges::find_if(m_attachedFiles, [fileName](const auto &pair) {
return pair.first == fileName;
});
if (existing != m_attachedFiles.end()) {
existing->second = localFile.fileContents().value_or("");
continue;
}
const QIcon icon = FileIconProvider::icon(localFile);
m_attachedFilesBar->addTab(icon, localFile.fileName());
m_attachedFiles.append({localFile.fileName(), localFile.fileContents().value_or("")});
}
if (!filePaths.isEmpty()) {
m_attachedFilesBar->setVisible(true);
updateMaximumHeight();
}
}
void ChatInput::dragEnterEvent(QDragEnterEvent *e)
{
const auto *dropData = dynamic_cast<const DropMimeData *>(e->mimeData());
if (dropData)
e->acceptProposedAction();
if (e->mimeData()->hasUrls())
e->acceptProposedAction();
}
static bool isSourceFileType(FileType type)
{
return type == FileType::Header || type == FileType::Source || type == FileType::Form
|| type == FileType::QML || type == FileType::StateChart || type == FileType::Project;
}
static bool isInterestingFileNode(const FileNode *node)
{
return node->listInProject() && !node->isGenerated() && isSourceFileType(node->fileType());
}
static void collectFilesFromFolderNode(const FolderNode *folderNode, QStringList &outPaths)
{
if (!folderNode)
return;
// Skip the resource files for now.
if (folderNode->displayName().endsWith(".qrc"))
return;
// Use the existing forEachFileNode method to iterate through all file nodes in this folder
folderNode->forEachFileNode([&outPaths](FileNode *fileNode) {
if (isInterestingFileNode(fileNode)) {
FilePath fp = fileNode->filePath();
if (fp.isLocal())
outPaths.append(fp.toFSPathString());
}
});
folderNode->forEachFolderNode([&outPaths](FolderNode *childFolderNode) {
collectFilesFromFolderNode(childFolderNode, outPaths);
});
}
static void collectFilesFromProjectNode(const ProjectNode *projectNode, QStringList &outPaths)
{
if (!projectNode)
return;
projectNode->forEachFileNode([&outPaths](FileNode *fileNode) {
if (isInterestingFileNode(fileNode)) {
FilePath fp = fileNode->filePath();
if (fp.isLocal())
outPaths.append(fp.toFSPathString());
}
});
projectNode->forEachFolderNode(
[&outPaths](FolderNode *folderNode) { collectFilesFromFolderNode(folderNode, outPaths); });
}
void ChatInput::dropEvent(QDropEvent *e)
{
QStringList localPaths;
const auto *dropData = dynamic_cast<const DropMimeData *>(e->mimeData());
if (dropData) {
using NodesList = QList<const Node *>;
NodesList nodes = transform<QList<const Node *>>(dropData->values(), [](const QVariant &v) {
return v.value<Node *>();
});
// Filter to only file nodes (not directories or project nodes)
NodesList fileNodes = filtered(nodes, [](const Node *n) {
return n->asFileNode() && isInterestingFileNode(n->asFileNode());
});
for (const Node *node : fileNodes) {
FilePath fp = node->filePath();
if (fp.isLocal())
localPaths.append(fp.toFSPathString());
}
for (const Node *node : nodes) {
if (auto projectNode = node->asProjectNode())
collectFilesFromProjectNode(projectNode, localPaths);
else if (auto folderNode = node->asFolderNode())
collectFilesFromFolderNode(folderNode, localPaths);
}
} else {
// Fallback to URL-based handling
for (const QUrl &url : e->mimeData()->urls()) {
FilePath fp = FilePath::fromUrl(url);
if (fp.isLocal())
localPaths.append(fp.toFSPathString());
}
}
addFilesFromLocalPaths(localPaths);
e->acceptProposedAction();
}
bool ChatInput::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::ShortcutOverride) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Escape) {
emit editingCancelled();
return true;
}
}
if (obj == m_txt && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->modifiers() == Qt::NoModifier
&& (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)) {
onSendClicked();
return true;
}
}
if (obj == this && event->type() == QEvent::FocusIn) {
m_txt->setFocus();
return true;
}
return QWidget::eventFilter(obj, event);
}
bool ChatInput::isGenerating() const
{
return m_isGenerating;
}
void ChatInput::setIsGenerating(bool newIsGenerating)
{
m_isGenerating = newIsGenerating;
updateUI();
}
void ChatInput::setEditingText(const QString &editingText, const QList<QVariantMap> &extra)
{
cleanUp();
for (const QVariantMap &e : extra) {
if (e.value("type").toString() == "textFile") {
const QString fileName = e.value("name").toString();
m_attachedFiles.append({fileName, e.value("content").toByteArray()});
const QIcon icon = FileIconProvider::icon(FilePath::fromString(fileName));
m_attachedFilesBar->addTab(icon, fileName);
} else if (e.value("type").toString() == "imageFile") {
const QString fileName = e.value("name").toString();
m_attachedFiles.append({fileName, e.value("content").toByteArray()});
const QIcon icon = FileIconProvider::icon(FilePath::fromString(fileName));
m_attachedFilesBar->addTab(icon, fileName);
} else if (e.value("type").toString() == "audioFile") {
const QString fileName = e.value("name").toString();
m_attachedFiles.append({fileName, e.value("content").toByteArray()});
const QIcon icon = FileIconProvider::icon(FilePath::fromString(fileName));
m_attachedFilesBar->addTab(icon, fileName);
}
}
m_attachedFilesBar->setVisible(m_attachedFilesBar->count() > 0);
updateMaximumHeight();
m_txt->setText(editingText);
m_txt->setFocus();
}
void ChatInput::updateMaximumHeight()
{
int maximumHeight = 80;
if (m_attachedFilesBar->isVisible())
maximumHeight += 20;
setMaximumHeight(maximumHeight);
}
QList<QVariantMap> ChatInput::getExtraFromAttachedFiles()
{
QList<QVariantMap> extraList;
for (const auto &fileAndContent : std::as_const(m_attachedFiles)) {
QVariantMap extra;
const QString fileName = fileAndContent.first;
const QByteArray content = fileAndContent.second;
QString ext = QFileInfo(fileName).suffix().toLower();
if (isImageFile(fileName)) {
QString base64Url = "data:" + mimeNameFromExtension(ext) + ";base64,"
+ content.toBase64();
extra["type"] = "imageFile";
extra["name"] = fileName;
extra["base64Url"] = base64Url;
} else if (isAudioFile(fileName)) {
QString base64Url = "data:" + mimeNameFromExtension(ext) + ";base64,"
+ content.toBase64();
extra["type"] = "audioFile";
extra["name"] = fileName;
extra["base64Url"] = base64Url;
} else {
extra["type"] = "textFile";
extra["name"] = fileName;
extra["content"] = content;
}
extraList << extra;
}
return extraList;
}
} // namespace LlamaCpp