cpphoverhandler.cpp 10.3 KB
Newer Older
con's avatar
con committed
1
2
3
4
/***************************************************************************
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
32
**
***************************************************************************/
hjk's avatar
hjk committed
33

con's avatar
con committed
34
#include "cpphoverhandler.h"
35
36
#include "cppeditor.h"
#include "cppplugin.h"
con's avatar
con committed
37
38
39

#include <coreplugin/icore.h>
#include <coreplugin/uniqueidmanager.h>
40
41
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
42
#include <extensionsystem/pluginmanager.h>
con's avatar
con committed
43
#include <texteditor/itexteditor.h>
Roberto Raggi's avatar
Roberto Raggi committed
44
#include <texteditor/basetexteditor.h>
con's avatar
con committed
45
46
47
48
49
50
51
52
53
54
55
56
#include <debugger/debuggerconstants.h>

#include <CoreTypes.h>
#include <FullySpecifiedType.h>
#include <Literals.h>
#include <Names.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
57
#include <cplusplus/SimpleLexer.h>
con's avatar
con committed
58

59
60
61
62
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>
con's avatar
con committed
63
64
65
66
67
#include <QtGui/QToolTip>
#include <QtGui/QTextCursor>
#include <QtGui/QTextBlock>
#include <QtHelp/QHelpEngineCore>

68
using namespace CppEditor::Internal;
Roberto Raggi's avatar
Roberto Raggi committed
69
using namespace CPlusPlus;
70
using namespace Core;
con's avatar
con committed
71

72
73
74
CppHoverHandler::CppHoverHandler(QObject *parent)
    : QObject(parent)
    , m_helpEngineNeedsSetup(false)
con's avatar
con committed
75
{
76
    m_modelManager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
77

78
79
    ICore *core = ICore::instance();
    QFileInfo fi(core->settings()->fileName());
80
81
82
83
84
85
    // FIXME shouldn't the help engine create the directory if it doesn't exist?
    QDir directory(fi.absolutePath()+"/qtcreator");
    if (!directory.exists())
        directory.mkpath(directory.absolutePath());

    m_helpEngine = new QHelpEngineCore(directory.absolutePath()
con's avatar
con committed
86
87
                                       + QLatin1String("/helpcollection.qhc"), this);
    //m_helpEngine->setAutoSaveFilter(false);
88
89
    if (!m_helpEngine->setupData())
        qWarning() << "Could not initialize help engine:" << m_helpEngine->error();
con's avatar
con committed
90
    m_helpEngine->setCurrentFilter(tr("Unfiltered"));
91
    m_helpEngineNeedsSetup = m_helpEngine->registeredDocumentations().count() == 0;
92
93

    // Listen for editor opened events in order to connect to tooltip/helpid requests
94
    connect(core->editorManager(), SIGNAL(editorOpened(Core::IEditor *)),
95
            this, SLOT(editorOpened(Core::IEditor *)));
con's avatar
con committed
96
97
98
99
100
101
102
}

void CppHoverHandler::updateContextHelpId(TextEditor::ITextEditor *editor, int pos)
{
    updateHelpIdAndTooltip(editor, pos);
}

103
void CppHoverHandler::editorOpened(IEditor *editor)
con's avatar
con committed
104
{
105
106
107
108
109
110
111
112
113
114
    CPPEditorEditable *cppEditor = qobject_cast<CPPEditorEditable *>(editor);
    if (!cppEditor)
        return;

    connect(cppEditor, SIGNAL(tooltipRequested(TextEditor::ITextEditor*, QPoint, int)),
            this, SLOT(showToolTip(TextEditor::ITextEditor*, QPoint, int)));

    connect(cppEditor, SIGNAL(contextHelpIdRequested(TextEditor::ITextEditor*, int)),
            this, SLOT(updateContextHelpId(TextEditor::ITextEditor*, int)));
}
con's avatar
con committed
115

116
117
118
void CppHoverHandler::showToolTip(TextEditor::ITextEditor *editor, const QPoint &point, int pos)
{
    if (!editor)
con's avatar
con committed
119
120
        return;

121
122
    ICore *core = ICore::instance();
    const int dbgcontext = core->uniqueIDManager()->uniqueIdentifier(Debugger::Constants::C_GDBDEBUGGER);
123

124
    if (core->hasContext(dbgcontext))
con's avatar
con committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        return;

    updateHelpIdAndTooltip(editor, pos);

    if (m_toolTip.isEmpty())
        QToolTip::hideText();
    else {
        const QPoint pnt = point - QPoint(0,
#ifdef Q_WS_WIN
        24
#else
        16
#endif
        );

        QToolTip::showText(pnt, m_toolTip);
    }
}

Roberto Raggi's avatar
Roberto Raggi committed
144
145
static QString buildHelpId(const FullySpecifiedType &type,
                           const Symbol *symbol)
con's avatar
con committed
146
147
148
149
{
    Name *name = 0;
    Scope *scope = 0;

150
    if (const Function *f = type->asFunctionType()) {
con's avatar
con committed
151
152
        name = f->name();
        scope = f->scope();
153
    } else if (const Class *c = type->asClassType()) {
con's avatar
con committed
154
155
        name = c->name();
        scope = c->scope();
156
    } else if (const Enum *e = type->asEnumType()) {
con's avatar
con committed
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
        name = e->name();
        scope = e->scope();
    } else if (const NamedType *t = type->asNamedType()) {
        name = t->name();
    } else if (const Declaration *d = symbol->asDeclaration()) {
        if (d->scope() && d->scope()->owner()->isEnum()) {
            name = d->name();
            scope = d->scope();
        }
    }

    Overview overview;
    overview.setShowArgumentNames(false);
    overview.setShowReturnTypes(false);

    QStringList qualifiedNames;
    qualifiedNames.prepend(overview.prettyName(name));

    for (; scope; scope = scope->enclosingScope()) {
        if (scope->owner() && scope->owner()->name() && !scope->isEnumScope()) {
            Name *name = scope->owner()->name();
            Identifier *id = 0;
            if (NameId *nameId = name->asNameId()) {
                id = nameId->identifier();
            } else if (TemplateNameId *nameId = name->asTemplateNameId()) {
                id = nameId->identifier();
            }
            if (id)
                qualifiedNames.prepend(QString::fromLatin1(id->chars(), id->size()));
        }
    }

    return qualifiedNames.join(QLatin1String("::"));
}

void CppHoverHandler::updateHelpIdAndTooltip(TextEditor::ITextEditor *editor, int pos)
{
    m_helpId.clear();
    m_toolTip.clear();

197
198
199
    if (!m_modelManager)
        return;

Roberto Raggi's avatar
Roberto Raggi committed
200
    TextEditor::BaseTextEditor *edit = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
con's avatar
con committed
201
202
203
    if (!edit)
        return;

204
205
206
207
208
209
    const Snapshot documents = m_modelManager->snapshot();
    const QString fileName = editor->file()->fileName();
    Document::Ptr doc = documents.value(fileName);
    if (! doc)
        return; // nothing to do

con's avatar
con committed
210
211
    QTextCursor tc(edit->document());
    tc.setPosition(pos);
212
    const unsigned lineNumber = tc.block().blockNumber() + 1;
con's avatar
con committed
213

214
215
216
217
    // Find the last symbol up to the cursor position
    int line = 0, column = 0;
    editor->convertPosition(tc.position(), &line, &column);
    Symbol *lastSymbol = doc->findSymbolAt(line, column);
218

219
220
221
222
223
224
225
    TypeOfExpression typeOfExpression;
    typeOfExpression.setSnapshot(documents);

    foreach (Document::DiagnosticMessage m, doc->diagnosticMessages()) {
        if (m.line() == lineNumber) {
            m_toolTip = m.text();
            break;
con's avatar
con committed
226
        }
227
    }
con's avatar
con committed
228

229
230
231
232
233
    if (m_toolTip.isEmpty()) {
        foreach (const Document::Include &incl, doc->includes()) {
            if (incl.line() == lineNumber) {
                m_toolTip = incl.fileName();
                break;
234
235
236
237
            }
        }
    }

con's avatar
con committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    if (m_toolTip.isEmpty()) {
        // Move to the end of a qualified name
        bool stop = false;
        while (!stop) {
            const QChar ch = editor->characterAt(tc.position());
            if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
                tc.setPosition(tc.position() + 1);
            else if (ch == QLatin1Char(':') && editor->characterAt(tc.position() + 1) == QLatin1Char(':')) {
                tc.setPosition(tc.position() + 2);
            } else {
                stop = true;
            }
        }

        // Fetch the expression's code.
        ExpressionUnderCursor expressionUnderCursor;
        const QString expression = expressionUnderCursor(tc);

256
257
258
        const QList<TypeOfExpression::Result> types =
                typeOfExpression(expression, doc, lastSymbol);

259
        if (!types.isEmpty() && types.first().first) {
260
            FullySpecifiedType firstType = types.first().first;
261
            Symbol *symbol = types.first().second;
262
263
264
265
266
267
268
269
            FullySpecifiedType docType = firstType;

            if (const PointerType *pt = firstType->asPointerType()) {
                docType = pt->elementType();
            } else if (const ReferenceType *rt = firstType->asReferenceType()) {
                docType = rt->elementType();
            }

270
271
            m_helpId = buildHelpId(docType, symbol);
            QString displayName = buildHelpId(firstType, symbol);
272

273
            if (!firstType->isClassType() && !firstType->isNamedType()) {
274
275
276
277
278
279
                Overview overview;
                overview.setShowArgumentNames(true);
                overview.setShowReturnTypes(true);
                m_toolTip = overview.prettyType(firstType, displayName);
            } else {
                m_toolTip = m_helpId;
con's avatar
con committed
280
281
282
283
            }
        }
    }

284
    if (m_toolTip.isEmpty()) {
285
286
        foreach (const Document::MacroUse &use, doc->macroUses()) {
            if (use.contains(pos)) {
287
288
289
                const Macro m = use.macro();
                m_toolTip = m.toString();
                m_helpId = m.name();
290
291
292
293
294
                break;
            }
        }
    }

295
296
297
298
299
300
    if (m_helpEngineNeedsSetup
        && m_helpEngine->registeredDocumentations().count() > 0) {
        m_helpEngine->setupData();
        m_helpEngineNeedsSetup = false;
    }

301
    if (!m_toolTip.isEmpty())
302
303
        m_toolTip = Qt::escape(m_toolTip);

con's avatar
con committed
304
305
    if (!m_helpId.isEmpty() && !m_helpEngine->linksForIdentifier(m_helpId).isEmpty()) {
        m_toolTip = QString(QLatin1String("<table><tr><td valign=middle><nobr>%1</td>"
306
                                          "<td><img src=\":/cppeditor/images/f1.svg\"></td></tr></table>"))
307
                    .arg(m_toolTip);
con's avatar
con committed
308
309
        editor->setContextHelpId(m_helpId);
    } else if (!m_toolTip.isEmpty()) {
310
        m_toolTip = QString(QLatin1String("<nobr>%1")).arg(m_toolTip);
con's avatar
con committed
311
312
    }
}