1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#include "codelenstree.h"
6#include "framework.h"
7#include "codelensdelegate.h"
8#include "textedittabwidget/style/stylecolor.h"
9#include <QStandardItem>
10#include <QFile>
11
12QByteArray readLine(const QString &filePath, int line)
13{
14 QByteArray array{};
15 QFile file(filePath);
16 if(!file.open(QFile::ReadOnly)) {
17 return array;
18 }
19
20 for(int i = 0; i <= line; i++) {
21 array = file.readLine();
22 if (i == line)
23 return array;
24 }
25 file.close();
26 return array;
27}
28
29CodeLensTree::CodeLensTree(QWidget *parent)
30 : QTreeView (parent)
31{
32 setModel(new QStandardItemModel);
33 setEnabled(true);
34 setEditTriggers(QAbstractItemView::NoEditTriggers);
35 setItemDelegate(new CodeLensDelegate);
36
37 QObject::connect(this, &QTreeView::doubleClicked, [=](const QModelIndex &index){
38 if (!index.parent().isValid()) { //root return
39 return;
40 }
41 QVariant rangeVar = index.data(CodeLensItemRole::Range);
42 lsp::Range range;
43 if (rangeVar.canConvert<lsp::Range>()){
44 range = rangeVar.value<lsp::Range>();
45 }
46 QModelIndex parentIndex = index;
47 while (parentIndex.parent().isValid()) {
48 parentIndex = index.parent();
49 }
50 QString filePath = parentIndex.data(Qt::DisplayRole).toString();
51 emit CodeLensTree::doubleClicked(filePath, range);
52 });
53}
54
55QString codeDataFormat(int line, const QString &codeText)
56{
57 return QString::number(line) + " " + codeText;
58}
59
60void CodeLensTree::setData(const lsp::References &refs)
61{
62 auto model = qobject_cast<QStandardItemModel*>(CodeLensTree::model());
63 model->clear();
64 QHash<QString, QStandardItem*> cache{};
65 for(auto ref : refs) {
66 QString file = ref.fileUrl.toLocalFile();
67 lsp::Range range = ref.range;
68 if (range.start.line == range.end.line) {
69 QString filePath = ref.fileUrl.toLocalFile();
70 QStandardItem *fileItem = nullptr;
71 if (cache[filePath]) {
72 fileItem = cache[filePath];
73 } else {
74 fileItem = new QStandardItem(filePath);
75 cache[filePath] = fileItem;
76 model->appendRow(fileItem);
77 }
78 QString codeText = readLine(file, range.start.line);
79 QString displayText = codeDataFormat(range.start.line, codeText);
80 QColor hColor = StyleColor::Table::get()->Yellow;
81 QStandardItem *codeChild = new QStandardItem(displayText);
82 codeChild->setData(QVariant::fromValue<lsp::Range>(range), CodeLensItemRole::Range);
83 codeChild->setData(QVariant::fromValue<QString>(codeText), CodeLensItemRole::CodeText);
84 codeChild->setData(QVariant::fromValue<QColor>(hColor), CodeLensItemRole::HeightColor);
85 codeChild->setTextAlignment(Qt::AlignVCenter);
86 fileItem->appendRow(codeChild);
87 }
88 }
89}
90