Source

pynoto / src / PythonEditor / ComplititionList.cpp

Full commit
#include <QDebug>
#include <QScrollBar>
#include <QKeyEvent>
#include <QStandardItemModel>
#include "Include/PynotoApplication.h"
#include "Include/IIconProvider.h"
#include "ComplititionList.h"
#include "PythonEditorWidget.h"

namespace PythonEditor {

ComplititionList::ComplititionList(PythonEditorWidget * editor, QWidget* parent):
    QCompleter(parent),
    _editor(editor)
{
    setWidget(_editor);
    setCompletionMode(QCompleter::PopupCompletion);
    setWrapAround(false);
    connect(_editor, SIGNAL(cursorPositionChanged()), SLOT(onEditorCursorChanged()));
    connect(this, SIGNAL(activated(QString)), SLOT(onInsertCompletion(QString)));
    _icons[PythonCode::IPythonCode::Function] = Aux::icons()->icon("method");
    _icons[PythonCode::IPythonCode::Module] = Aux::icons()->icon("module");
    _icons[PythonCode::IPythonCode::Class] = Aux::icons()->icon("class");
    _icons[PythonCode::IPythonCode::Instance] = Aux::icons()->icon("attribute");
}

void ComplititionList::complete(int pos, const QString& word,  const QList<PythonCode::IPythonCode::Completition>& items)
{
    _pos = pos;
    _word = word;
    QStandardItemModel *mod = new QStandardItemModel(0, 1);
    foreach(PythonCode::IPythonCode::Completition it, items){
        QStandardItem *item = new QStandardItem(_icons[it.type], it.name);
        mod->appendRow(item);
    }
    setModel(mod);
    setCompletionPrefix(_word);
    QPoint p = _editor->pointForPosition(_pos);
    QRect rc = QRect(p, QSize(200, 300));
    rc.setWidth(popup()->sizeHintForColumn(0) + popup()->verticalScrollBar()->sizeHint().width());
    QCompleter::complete(rc);
    QRect drc = QRect(_editor->viewport()->mapToGlobal(rc.topLeft()), popup()->size());
    drc.setTop(drc.top()-5);
    popup()->setGeometry(drc);
    _editor->setFocus(Qt::MouseFocusReason);
}

void ComplititionList::onEditorCursorChanged()
{
    if (!popup()->isVisible())
        return;

    int newPos = _editor->textCursor().position();
    if (newPos < _pos){
        popup()->hide();
    }
    QString text = _editor->text(_pos, newPos);
    setCompletionPrefix(_word+text);
    if (completionCount() == 0)
        popup()->hide();
}

void ComplititionList::onInsertCompletion(const QString& text)
{
    QTextCursor tc = _editor->textCursor();
    int extra = text.length() - completionPrefix().length();
    tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    tc.insertText(text.right(extra));
    _editor->setTextCursor(tc);
}

}