1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
10 ** GNU Lesser General Public License Usage
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
31 **************************************************************************/
33 #include "completionwidget.h"
34 #include "completionsupport.h"
35 #include "icompletioncollector.h"
37 #include <texteditor/itexteditor.h>
39 #include <utils/faketooltip.h>
40 #include <utils/qtcassert.h>
42 #include <QtCore/QEvent>
43 #include <QtGui/QApplication>
44 #include <QtGui/QDesktopWidget>
45 #include <QtGui/QKeyEvent>
46 #include <QtGui/QVBoxLayout>
47 #include <QtGui/QScrollBar>
48 #include <QtGui/QLabel>
49 #include <QtGui/QStylePainter>
50 #include <QtGui/QToolTip>
54 using namespace TextEditor;
55 using namespace TextEditor::Internal;
57 #define NUMBER_OF_VISIBLE_ITEMS 10
59 namespace TextEditor {
62 class AutoCompletionModel : public QAbstractListModel
65 AutoCompletionModel(QObject *parent);
67 inline const CompletionItem &itemAt(const QModelIndex &index) const
68 { return m_items.at(index.row()); }
70 void setItems(const QList<CompletionItem> &items);
72 int rowCount(const QModelIndex &parent = QModelIndex()) const;
73 QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
76 QList<CompletionItem> m_items;
80 class CompletionInfoFrame : public Utils::FakeToolTip
83 CompletionInfoFrame(QWidget *parent = 0) :
84 Utils::FakeToolTip(parent),
85 m_label(new QLabel(this))
87 QVBoxLayout *layout = new QVBoxLayout(this);
89 layout->setSpacing(0);
90 layout->addWidget(m_label);
92 m_label->setForegroundRole(QPalette::ToolTipText);
93 m_label->setBackgroundRole(QPalette::ToolTipBase);
96 void setText(const QString &text)
98 m_label->setText(text);
106 } // namespace Internal
107 } // namespace TextEditor
110 AutoCompletionModel::AutoCompletionModel(QObject *parent)
111 : QAbstractListModel(parent)
115 void AutoCompletionModel::setItems(const QList<CompletionItem> &items)
121 int AutoCompletionModel::rowCount(const QModelIndex &) const
123 return m_items.count();
126 QVariant AutoCompletionModel::data(const QModelIndex &index, int role) const
128 if (index.row() >= m_items.count())
131 if (role == Qt::DisplayRole) {
132 return itemAt(index).text;
133 } else if (role == Qt::DecorationRole) {
134 return itemAt(index).icon;
135 } else if (role == Qt::WhatsThisRole) {
136 return itemAt(index).details;
143 CompletionWidget::CompletionWidget(CompletionSupport *support,
145 : QFrame(0, Qt::Popup),
148 m_completionListView(new CompletionListView(support, editor, this))
150 // We disable the frame on this list view and use a QFrame around it instead.
151 // This improves the look with QGTKStyle.
153 setFrameStyle(m_completionListView->frameStyle());
155 m_completionListView->setFrameStyle(QFrame::NoFrame);
157 setObjectName(QLatin1String("m_popupFrame"));
158 setAttribute(Qt::WA_DeleteOnClose);
159 setMinimumSize(1, 1);
160 setFont(editor->widget()->font());
162 QVBoxLayout *layout = new QVBoxLayout(this);
163 layout->setMargin(0);
165 layout->addWidget(m_completionListView);
166 setFocusProxy(m_completionListView);
168 connect(m_completionListView, SIGNAL(itemSelected(TextEditor::CompletionItem)),
169 this, SIGNAL(itemSelected(TextEditor::CompletionItem)));
170 connect(m_completionListView, SIGNAL(completionListClosed()),
171 this, SIGNAL(completionListClosed()));
172 connect(m_completionListView, SIGNAL(activated(QModelIndex)),
173 SLOT(closeList(QModelIndex)));
174 connect(editor, SIGNAL(contentsChangedBecauseOfUndo()),
175 this, SLOT(closeList()));
178 CompletionWidget::~CompletionWidget()
182 void CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionitems)
184 m_completionListView->setCompletionItems(completionitems);
187 void CompletionWidget::closeList(const QModelIndex &index)
189 m_completionListView->closeList(index);
193 void CompletionWidget::showCompletions(int startPos)
196 updatePositionAndSize(startPos);
201 QChar CompletionWidget::typedChar() const
203 return m_completionListView->m_typedChar;
206 CompletionItem CompletionWidget::currentCompletionItem() const
208 return m_completionListView->currentCompletionItem();
211 bool CompletionWidget::explicitlySelected() const
213 return m_completionListView->explicitlySelected();
216 void CompletionWidget::setCurrentIndex(int index)
218 m_completionListView->setCurrentIndex(m_completionListView->model()->index(index, 0));
221 void CompletionWidget::updatePositionAndSize(int startPos)
223 // Determine size by calculating the space of the visible items
224 QAbstractItemModel *model = m_completionListView->model();
225 int visibleItems = model->rowCount();
226 if (visibleItems > NUMBER_OF_VISIBLE_ITEMS)
227 visibleItems = NUMBER_OF_VISIBLE_ITEMS;
229 const QStyleOptionViewItem &option = m_completionListView->viewOptions();
232 for (int i = 0; i < visibleItems; ++i) {
233 QSize tmp = m_completionListView->itemDelegate()->sizeHint(option, model->index(i, 0));
234 if (shint.width() < tmp.width())
238 const int fw = frameWidth();
239 const int width = shint.width() + fw * 2 + 30;
240 const int height = shint.height() * visibleItems + fw * 2;
242 // Determine the position, keeping the popup on the screen
243 const QRect cursorRect = m_editor->cursorRect(startPos);
244 const QDesktopWidget *desktop = QApplication::desktop();
246 QWidget *editorWidget = m_editor->widget();
249 const QRect screen = desktop->availableGeometry(desktop->screenNumber(editorWidget));
251 const QRect screen = desktop->screenGeometry(desktop->screenNumber(editorWidget));
254 QPoint pos = cursorRect.bottomLeft();
255 pos.rx() -= 16 + fw; // Space for the icons
257 if (pos.y() + height > screen.bottom())
258 pos.setY(cursorRect.top() - height);
260 if (pos.x() + width > screen.right())
261 pos.setX(screen.right() - width);
263 setGeometry(pos.x(), pos.y(), width, height);
266 CompletionListView::CompletionListView(CompletionSupport *support,
267 ITextEditor *editor, CompletionWidget *completionWidget)
268 : QListView(completionWidget),
269 m_blockFocusOut(false),
271 m_editorWidget(editor->widget()),
272 m_completionWidget(completionWidget),
273 m_model(new AutoCompletionModel(this)),
275 m_explicitlySelected(false)
277 QTC_ASSERT(m_editorWidget, return);
279 m_infoTimer.setInterval(1000);
280 m_infoTimer.setSingleShot(true);
281 connect(&m_infoTimer, SIGNAL(timeout()), SLOT(maybeShowInfoTip()));
283 setAttribute(Qt::WA_MacShowFocusRect, false);
284 setUniformItemSizes(true);
285 setSelectionBehavior(QAbstractItemView::SelectItems);
286 setSelectionMode(QAbstractItemView::SingleSelection);
287 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
288 setMinimumSize(1, 1);
291 if (horizontalScrollBar())
292 horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
293 if (verticalScrollBar())
294 verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
298 CompletionListView::~CompletionListView()
302 CompletionItem CompletionListView::currentCompletionItem() const
304 int row = currentIndex().row();
305 if (row >= 0 && row < m_model->rowCount())
306 return m_model->itemAt(currentIndex());
308 return CompletionItem();
311 bool CompletionListView::explicitlySelected() const
313 return m_explicitlySelected;
316 void CompletionListView::maybeShowInfoTip()
318 QModelIndex current = currentIndex();
319 if (!current.isValid())
321 QString infoTip = current.data(Qt::WhatsThisRole).toString();
323 if (infoTip.isEmpty()) {
324 delete m_infoFrame.data();
325 m_infoTimer.setInterval(200);
329 if (m_infoFrame.isNull())
330 m_infoFrame = new CompletionInfoFrame(this);
333 QRect r = rectForIndex(current);
335 (parentWidget()->mapToGlobal(
336 parentWidget()->rect().topRight())).x() + 3,
337 mapToGlobal(r.topRight()).y() - verticalOffset()
339 m_infoFrame->setText(infoTip);
340 m_infoFrame->adjustSize();
342 m_infoFrame->raise();
344 m_infoTimer.setInterval(0);
347 void CompletionListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
349 QListView::currentChanged(current, previous);
354 bool CompletionListView::event(QEvent *e)
357 return QListView::event(e);
359 bool forwardKeys = true;
360 if (e->type() == QEvent::FocusOut) {
362 #if defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA)
363 QFocusEvent *fe = static_cast<QFocusEvent *>(e);
364 if (fe->reason() == Qt::OtherFocusReason) {
365 // Qt/carbon workaround
366 // focus out is received before the key press event.
367 index = currentIndex();
370 m_completionWidget->closeList(index);
372 m_infoFrame->close();
374 } else if (e->type() == QEvent::ShortcutOverride) {
375 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
379 // select next/previous completion
380 if (ke->modifiers() == Qt::ControlModifier)
383 int change = (ke->key() == Qt::Key_N) ? 1 : -1;
384 int nrows = model()->rowCount();
385 int row = currentIndex().row();
386 int newRow = (row + change + nrows) % nrows;
387 if (newRow == row + change || !ke->isAutoRepeat())
388 setCurrentIndex(m_model->index(newRow));
392 } else if (e->type() == QEvent::KeyPress) {
393 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
397 // select next/previous completion - so don't pass on to editor
398 if (ke->modifiers() == Qt::ControlModifier)
403 m_completionWidget->closeList();
410 // We want these navigation keys to work in the editor, so forward them
415 //independently from style, accept current entry if return is pressed
416 if (qApp->focusWidget() == this)
417 m_completionWidget->closeList(currentIndex());
421 m_explicitlySelected = true;
422 if (!ke->isAutoRepeat()
423 && currentIndex().row() == 0) {
424 setCurrentIndex(model()->index(model()->rowCount()-1, 0));
431 m_explicitlySelected = true;
432 if (!ke->isAutoRepeat()
433 && currentIndex().row() == model()->rowCount()-1) {
434 setCurrentIndex(model()->index(0, 0));
441 case Qt::Key_PageDown:
447 // if a key is forwarded, completion widget is re-opened and selected item is reset to first,
448 // so only forward keys that insert text and refine the completed item
449 forwardKeys = !ke->text().isEmpty();
453 const CompletionPolicy policy = m_support->policy();
454 if (forwardKeys && policy != QuickFixCompletion) {
455 if (ke->text().length() == 1 && currentIndex().isValid() && qApp->focusWidget() == this) {
456 QChar typedChar = ke->text().at(0);
457 const CompletionItem &item = m_model->itemAt(currentIndex());
458 if (item.collector->typedCharCompletes(item, typedChar)) {
459 m_typedChar = typedChar;
460 m_completionWidget->closeList(currentIndex());
465 m_blockFocusOut = true;
466 QApplication::sendEvent(m_editorWidget, e);
467 m_blockFocusOut = false;
469 // Have the completion support update the list of items
470 m_support->complete(m_editor, policy, false);
475 return QListView::event(e);
478 void CompletionListView::keyboardSearch(const QString &search)
483 void CompletionListView::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems)
485 m_model->setItems(completionItems);
486 setCurrentIndex(m_model->index(0)); // Select the first item
489 void CompletionListView::closeList(const QModelIndex &index)
491 m_blockFocusOut = true;
494 emit itemSelected(m_model->itemAt(index));
496 emit completionListClosed();
498 m_blockFocusOut = false;