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
|
/* KDevelop CMake Support
*
* Copyright 2008 Aleix Pol <aleixpol@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "cmakecodecompletionmodel.h"
#include <QVariant>
#include <QModelIndex>
#include <QMimeDatabase>
#include <QUrl>
#include <language/duchain/duchain.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/ducontext.h>
#include <language/duchain/declaration.h>
#include <language/duchain/types/functiontype.h>
#include <language/duchain/types/delayedtype.h>
#include <cmakeduchaintypes.h>
#include "cmakeutils.h"
#include "icmakedocumentation.h"
#include <KTextEditor/Document>
#include <KTextEditor/View>
#include <KIO/Global>
#include <KLocalizedString>
using namespace KTextEditor;
using namespace KDevelop;
QVector<QString> CMakeCodeCompletionModel::s_commands;
CMakeCodeCompletionModel::CMakeCodeCompletionModel(QObject* parent)
: CodeCompletionModel(parent)
, m_inside(false)
{}
bool isFunction(const Declaration* decl)
{
return decl->abstractType().cast<FunctionType>();
}
bool isPathChar(QChar c)
{
return c.isLetterOrNumber() || c == QLatin1Char('/') || c == QLatin1Char('.');
}
QString escapePath(QString path)
{
// see https://cmake.org/Wiki/CMake/Language_Syntax#Escapes
const QString toBeEscaped = QStringLiteral("\"()#$^");
for(const QChar &ch : toBeEscaped) {
path.replace(ch, QLatin1Char('\\') + ch);
}
return path;
}
void CMakeCodeCompletionModel::completionInvoked(View* view, const Range& range, InvocationType invocationType)
{
beginResetModel();
if(s_commands.isEmpty()) {
ICMakeDocumentation* cmakedoc=CMake::cmakeDocumentation();
if(cmakedoc)
s_commands=cmakedoc->names(ICMakeDocumentation::Command);
}
Q_UNUSED(invocationType);
m_declarations.clear();
DUChainReadLocker lock(DUChain::lock());
KTextEditor::Document* d=view->document();
TopDUContext* ctx = DUChain::self()->chainForDocument( d->url() );
QString line=d->line(range.end().line());
// m_inside=line.lastIndexOf('(', range.end().column())>=0;
m_inside=line.lastIndexOf(QLatin1Char('('), range.end().column()-line.size()-1)>=0;
for(int l=range.end().line(); l>=0 && !m_inside; --l)
{
QString cline=d->line(l);
const QStringRef line = cline.leftRef(cline.indexOf(QLatin1Char('#')));
int close=line.lastIndexOf(QLatin1Char(')')), open=line.indexOf(QLatin1Char('('));
if(close>=0 && open>=0) {
m_inside=open>close;
break;
} else if(open>=0) {
m_inside=true;
break;
} else if(close>=0) {
m_inside=false;
break;
}
}
int numRows = 0;
if(m_inside) {
Cursor start=range.start();
for(; isPathChar(d->characterAt(start)); start-=Cursor(0,1))
{}
start+=Cursor(0,1);
QString tocomplete=d->text(Range(start, range.end()-Cursor(0,1)));
int lastdir=tocomplete.lastIndexOf(QLatin1Char('/'));
QString path = KIO::upUrl(QUrl(d->url())).adjusted(QUrl::StripTrailingSlash).toLocalFile()+QLatin1Char('/');
if(lastdir>=0) {
const QStringRef basePath = tocomplete.midRef(0, lastdir);
path += basePath;
}
QDir dir(path);
const QFileInfoList paths = dir.entryInfoList(QStringList(tocomplete.midRef(lastdir+1)+QLatin1Char('*')),
QDir::AllEntries | QDir::NoDotAndDotDot);
m_paths.clear();
m_paths.reserve(paths.size());
for (const QFileInfo& f : paths) {
QString currentPath = f.fileName();
if(f.isDir())
currentPath += QLatin1Char('/');
m_paths += currentPath;
}
numRows += m_paths.count();
} else
numRows += s_commands.count();
if(ctx)
{
const auto list = ctx->allDeclarations( ctx->transformToLocalRevision(KTextEditor::Cursor(range.start())), ctx );
for (const auto& pair : list) {
bool func=isFunction(pair.first);
if((func && !m_inside) || (!func && m_inside))
m_declarations.append(pair.first);
}
numRows+=m_declarations.count();
}
setRowCount(numRows);
endResetModel();
}
CMakeCodeCompletionModel::Type CMakeCodeCompletionModel::indexType(int row) const
{
if(m_inside)
{
if(row < m_declarations.count()) {
KDevelop::DUChainReadLocker lock;
Declaration* dec = m_declarations.at(row).declaration();
if (dec && dec->type<TargetType>())
return Target;
else
return Variable;
} else
return Path;
}
else
{
if(row<m_declarations.count())
return Macro;
else
return Command;
}
}
QVariant CMakeCodeCompletionModel::data (const QModelIndex & index, int role) const
{
if(!index.isValid())
return QVariant();
Type type=indexType(index.row());
if(role==Qt::DisplayRole && index.column()==CodeCompletionModel::Name)
{
int pos = index.row();
switch(type) {
case Command:
return s_commands[pos-m_declarations.size()];
case Path:
return m_paths[pos-m_declarations.size()];
case Target:
case Variable:
case Macro: {
DUChainReadLocker lock(DUChain::lock());
Declaration* dec=m_declarations[pos].data();
return dec ? dec->identifier().toString() : i18n("INVALID");
}
}
}
else if(role==Qt::DisplayRole && index.column()==CodeCompletionModel::Prefix)
{
switch(type)
{
case Command: return i18nc("@item", "Command");
case Variable: return i18nc("@item", "Variable");
case Macro: return i18nc("@item", "Macro");
case Path: return i18nc("@item", "Path");
case Target: return i18nc("@item", "Target");
}
}
else if(role==Qt::DecorationRole && index.column()==CodeCompletionModel::Icon)
{
switch(type)
{
case Command: return QIcon::fromTheme(QStringLiteral("code-block"));
case Variable: return QIcon::fromTheme(QStringLiteral("code-variable"));
case Macro: return QIcon::fromTheme(QStringLiteral("code-function"));
case Target: return QIcon::fromTheme(QStringLiteral("system-run"));
case Path: {
QUrl url = QUrl::fromUserInput(m_paths[index.row()-m_declarations.size()]);
QString iconName;
if (url.isLocalFile()) {
// don't read contents even if it is a local file
iconName = QMimeDatabase().mimeTypeForFile(url.toLocalFile(), QMimeDatabase::MatchExtension).iconName();
}
else {
// remote always only looks at the extension
iconName = QMimeDatabase().mimeTypeForUrl(url).iconName();
}
return QIcon::fromTheme(iconName);
}
}
}
else if(role==Qt::DisplayRole && index.column()==CodeCompletionModel::Arguments)
{
switch(type) {
case Variable:
case Command:
case Path:
case Target:
break;
case Macro:
{
DUChainReadLocker lock(DUChain::lock());
int pos=index.row();
FunctionType::Ptr func;
if(m_declarations[pos].data())
func = m_declarations[pos].data()->abstractType().cast<FunctionType>();
if(!func)
return QVariant();
QStringList args;
const auto arguments = func->arguments();
args.reserve(arguments.size());
for (const AbstractType::Ptr& t : arguments) {
DelayedType::Ptr delay = t.cast<DelayedType>();
args.append(delay ? delay->identifier().toString() : i18n("wrong"));
}
return QString(QLatin1Char('(') + args.join(QLatin1String(", ")) + QLatin1Char(')'));
}
}
}
return QVariant();
}
void CMakeCodeCompletionModel::executeCompletionItem(View* view, const Range& word, const QModelIndex& idx) const
{
Document* document = view->document();
const int row = idx.row();
switch(indexType(row))
{
case Path: {
Range r=word;
for (QChar c=document->characterAt(r.end()); c.isLetterOrNumber() || c==QLatin1Char('.'); c=document->characterAt(r.end())) {
r.setEnd(KTextEditor::Cursor(r.end().line(), r.end().column()+1));
}
QString path = data(index(row, Name, QModelIndex())).toString();
document->replaceText(r, escapePath(path));
} break;
case Macro:
case Command: {
QString code=data(index(row, Name, QModelIndex())).toString();
if (!document->line(word.start().line()).contains(QLatin1Char('(')))
code.append(QLatin1Char('('));
document->replaceText(word, code);
} break;
case Variable: {
Range r=word, prefix(word.start()-Cursor(0,2), word.start());
QString bef=document->text(prefix);
if(r.start().column()>=2 && bef==QLatin1String("${"))
r.setStart(KTextEditor::Cursor(r.start().line(), r.start().column()-2));
QString code = QLatin1String("${")+data(index(row, Name, QModelIndex())).toString();
if(document->characterAt(word.end())!=QLatin1Char('}'))
code += QLatin1Char('}');
document->replaceText(r, code);
} break;
case Target:
document->replaceText(word, data(index(row, Name, QModelIndex())).toString());
break;
}
}
|