2 * \file GuiCompleter.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Stefan Schimanski
8 * Full author contact details are available in file CREDITS.
13 #include "GuiWorkArea.h"
16 #include "BufferView.h"
18 #include "Dimension.h"
19 #include "FuncRequest.h"
25 #include "support/debug.h"
27 #include <QApplication>
28 #include <QAbstractListModel>
29 #include <QHeaderView>
31 #include <QPixmapCache>
33 #include <QItemDelegate>
38 using namespace lyx::support;
44 class PixmapItemDelegate : public QItemDelegate {
46 explicit PixmapItemDelegate(QObject *parent = 0)
47 : QItemDelegate(parent) {}
50 void paint(QPainter *painter, const QStyleOptionViewItem &option,
51 const QModelIndex &index) const
53 QStyleOptionViewItemV3 opt = setOptions(index, option);
54 QVariant value = index.data(Qt::DisplayRole);
55 QPixmap pixmap = qvariant_cast<QPixmap>(value);
56 const QSize size = pixmap.size();
60 drawBackground(painter, opt, index);
61 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
62 option.rect.top() + (option.rect.height() - size.height()) / 2,
64 drawFocus(painter, opt, option.rect);
70 class GuiCompletionModel : public QAbstractListModel {
73 GuiCompletionModel(QObject * parent, Inset::CompletionListPtr l)
74 : QAbstractListModel(parent), list(l) {}
76 int columnCount(const QModelIndex & parent = QModelIndex()) const
81 int rowCount(const QModelIndex & parent = QModelIndex()) const
90 QVariant data(const QModelIndex & index, int role) const
95 if (index.row() < 0 || index.row() >= rowCount())
98 if (role != Qt::DisplayRole && role != Qt::EditRole)
101 if (index.column() == 0)
102 return toqstr(list->data(index.row()));
103 else if (index.column() == 1) {
104 // get icon from cache
106 QString const name = ":" + toqstr(list->icon(index.row()));
107 if (!QPixmapCache::find("completion" + name, scaled)) {
108 // load icon from disk
109 QPixmap p = QPixmap(name);
111 // scale it to 16x16 or smaller
112 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
113 Qt::KeepAspectRatio, Qt::SmoothTransformation);
114 QPixmapCache::insert("completion" + name, scaled);
123 Inset::CompletionListPtr list;
127 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
128 : QCompleter(parent), gui_(gui), updateLock_(0)
130 // Setup the completion popup
131 setModel(new GuiCompletionModel(this, Inset::CompletionListPtr()));
132 setCompletionMode(QCompleter::PopupCompletion);
136 QTreeView *listView = new QTreeView;
137 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
138 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
139 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
140 listView->setSelectionMode(QAbstractItemView::SingleSelection);
141 listView->header()->hide();
142 listView->setIndentation(0);
144 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(popup()));
146 // create timeout timers
147 popup_timer_.setSingleShot(true);
148 inline_timer_.setSingleShot(true);
149 connect(this, SIGNAL(highlighted(const QString &)),
150 this, SLOT(popupHighlighted(const QString &)));
151 connect(this, SIGNAL(activated(const QString &)),
152 this, SLOT(popupActivated(const QString &)));
153 connect(&popup_timer_, SIGNAL(timeout()),
154 this, SLOT(showPopup()));
155 connect(&inline_timer_, SIGNAL(timeout()),
156 this, SLOT(showInline()));
160 GuiCompleter::~GuiCompleter()
166 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
168 // hijack back the tab key from the popup
169 // (which stole it from the workspace before)
170 if (e->type() == QEvent::KeyPress && popupVisible()) {
171 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
181 return QCompleter::eventFilter(watched, e);
185 bool GuiCompleter::popupPossible(Cursor const & cur) const
187 return QApplication::activeWindow()
189 && cur.inset().completionSupported(cur);
193 bool GuiCompleter::inlinePossible(Cursor const & cur) const
195 return cur.inset().inlineCompletionSupported(cur);
199 bool GuiCompleter::popupVisible() const
201 return popup()->isVisible();
205 bool GuiCompleter::inlineVisible() const
207 return !gui_->bufferView().inlineCompletionPos().empty();
211 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
213 // parameters which affect the completion
214 bool moved = cur != old_cursor_;
218 bool possiblePopupState = popupPossible(cur) && cursorInView;
219 bool possibleInlineState = inlinePossible(cur) && cursorInView;
221 // we moved or popup state is not ok for popup?
222 if ((moved && !keep) || !possiblePopupState) {
223 // stop an old completion timer
224 if (popup_timer_.isActive())
232 // we moved or inline state is not ok for inline completion?
233 if ((moved && !keep) || !possibleInlineState) {
234 // stop an old completion timer
235 if (inline_timer_.isActive())
236 inline_timer_.stop();
238 // hide old inline completion
240 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
243 // we inserted something and are in a possible popup state?
244 if (!popupVisible() && possiblePopupState && start
245 && cur.inset().automaticPopupCompletion())
246 popup_timer_.start(lyxrc.completion_popup_delay * 1000.0);
248 // we inserted something and are in a possible inline completion state?
249 if (!inlineVisible() && possibleInlineState && start
250 && cur.inset().automaticInlineCompletion())
251 inline_timer_.start(lyxrc.completion_inline_delay * 1000.0);
253 // update prefix if popup is visible or if it will be visible soon
254 if (popupVisible() || inlineVisible()
255 || popup_timer_.isActive() || inline_timer_.isActive())
260 void GuiCompleter::updateVisibility(bool start, bool keep)
262 Cursor cur = gui_->bufferView().cursor();
263 cur.updateFlags(Update::None);
265 updateVisibility(cur, start, keep);
267 if (cur.disp_.update())
268 gui_->bufferView().processUpdateFlags(cur.disp_.update());
272 void GuiCompleter::updatePrefix(Cursor & cur)
274 // get new prefix. Do nothing if unchanged
275 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
276 if (newPrefix == completionPrefix())
279 // value which should be kept selected
280 QString old = currentCompletion();
281 if (old.length() == 0)
282 old = last_selection_;
284 // update completer to new prefix
285 setCompletionPrefix(newPrefix);
287 // update popup because its size might have changed
291 // restore old selection
292 setCurrentCompletion(old);
294 // if popup is not empty, the new selection will
295 // be our last valid one
296 QString const & s = currentCompletion();
300 last_selection_ = old;
302 // update inline completion because the default
303 // completion string might have changed
305 updateInline(cur, s);
309 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
311 if (!cur.inset().inlineCompletionSupported(cur))
315 docstring prefix = cur.inset().completionPrefix(cur);
316 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
318 // shorten it if necessary
319 if (lyxrc.completion_inline_dots != -1
320 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
321 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
323 // set inline completion at cursor position
324 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
325 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
329 void GuiCompleter::updatePopup(Cursor & cur)
331 if (!cur.inset().completionSupported(cur))
334 if (completionCount() == 0)
337 // get dimensions of completion prefix
341 cur.inset().completionPosAndDim(cur, x, y, dim);
342 QRect insetRect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
346 QTreeView * p = static_cast<QTreeView *>(popup());
347 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
351 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
353 // value which should be kept selected
354 QString old = currentCompletion();
355 if (old.length() == 0)
356 old = last_selection_;
359 setModel(new GuiCompletionModel(this, cur.inset().completionList(cur)));
365 // restore old selection
366 setCurrentCompletion(old);
368 // if popup is not empty, the new selection will
369 // be our last valid one
370 QString const & s = currentCompletion();
374 last_selection_ = old;
376 // show inline completion
378 updateInline(cur, currentCompletion());
382 void GuiCompleter::showPopup(Cursor & cur)
384 if (!popupPossible(cur))
387 updateModel(cur, true, inlineVisible());
392 void GuiCompleter::showInline(Cursor & cur)
394 if (!inlinePossible(cur))
397 updateModel(cur, popupVisible(), true);
402 void GuiCompleter::showPopup()
404 Cursor cur = gui_->bufferView().cursor();
405 cur.updateFlags(Update::None);
410 if (cur.disp_.update())
411 gui_->bufferView().processUpdateFlags(cur.disp_.update());
415 void GuiCompleter::showInline()
417 Cursor cur = gui_->bufferView().cursor();
418 cur.updateFlags(Update::None);
423 if (cur.disp_.update())
424 gui_->bufferView().processUpdateFlags(cur.disp_.update());
428 void GuiCompleter::activate()
430 if (!popupVisible() && !inlineVisible())
433 // Complete with current selection in the popup.
434 QString s = currentCompletion();
440 void GuiCompleter::tab()
442 BufferView * bv = &gui_->bufferView();
443 Cursor cur = bv->cursor();
444 cur.updateFlags(Update::None);
446 // check that inline completion is active
447 if (!inlineVisible()) {
448 // try to activate the inline completion
449 if (cur.inset().inlineCompletionSupported(cur)) {
454 if (!popupVisible() && cur.inset().completionSupported(cur)) {
462 // If completion is active, at least complete by one character
463 docstring prefix = cur.inset().completionPrefix(cur);
464 docstring completion = from_utf8(fromqstr(currentCompletion()));
465 if (completion.size() <= prefix.size()) {
466 // finalize completion
467 cur.inset().insertCompletion(cur, docstring(), true);
469 updateVisibility(false, false);
472 docstring nextchar = completion.substr(prefix.size(), 1);
473 if (!cur.inset().insertCompletion(cur, nextchar, false))
477 // try to complete as far as it is unique
478 docstring longestCompletion = longestUniqueCompletion();
479 prefix = cur.inset().completionPrefix(cur);
480 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
481 cur.inset().insertCompletion(cur, postfix, false);
482 old_cursor_ = bv->cursor();
485 // show popup without delay because the completion was not unique
486 if (lyxrc.completion_popup_after_complete
488 && popup()->model()->rowCount() > 1)
489 popup_timer_.start(0);
492 if (cur.disp_.update())
493 gui_->bufferView().processUpdateFlags(cur.disp_.update());
497 QString GuiCompleter::currentCompletion() const
499 if (!popup()->selectionModel()->hasSelection())
502 // Not sure if this is bug in Qt: currentIndex() always
503 // return the first element in the list.
504 QModelIndex idx = popup()->currentIndex();
505 return popup()->model()->data(idx, Qt::EditRole).toString();
509 void GuiCompleter::setCurrentCompletion(QString const & s)
511 QAbstractItemModel const & model = *popup()->model();
512 size_t n = model.rowCount();
516 // select the first if s is empty
517 if (s.length() == 0) {
519 popup()->setCurrentIndex(model.index(0, 0));
524 // iterate through list until the s is found
525 // FIXME: there must be a better way than this iteration
527 for (i = 0; i < n; ++i) {
529 = model.data(model.index(i, 0), Qt::EditRole).toString();
534 // select the first if none was found
539 popup()->setCurrentIndex(model.index(i, 0));
544 docstring GuiCompleter::longestUniqueCompletion() const {
545 QAbstractItemModel const & model = *popup()->model();
546 QString s = currentCompletion();
547 size_t n = model.rowCount();
549 // iterate through the completions and cut off where s differs
550 for (size_t i = 0; i < n && s.length() > 0; ++i) {
552 = model.data(model.index(i, 0), Qt::EditRole).toString();
554 // find common prefix
556 size_t isn = is.length();
557 size_t sn = s.length();
558 for (j = 0; j < isn && j < sn; ++j) {
559 if (s.at(j) != is.at(j))
565 return from_utf8(fromqstr(s));
569 void GuiCompleter::popupActivated(const QString & completion)
571 Cursor cur = gui_->bufferView().cursor();
572 cur.updateFlags(Update::None);
574 docstring prefix = cur.inset().completionPrefix(cur);
575 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
576 cur.inset().insertCompletion(cur, postfix, true);
577 updateVisibility(cur, false);
579 if (cur.disp_.update())
580 gui_->bufferView().processUpdateFlags(cur.disp_.update());
584 void GuiCompleter::popupHighlighted(const QString & completion)
589 Cursor cur = gui_->bufferView().cursor();
590 cur.updateFlags(Update::None);
592 updateInline(cur, completion);
594 if (cur.disp_.update())
595 gui_->bufferView().processUpdateFlags(cur.disp_.update());
598 } // namespace frontend
601 #include "GuiCompleter_moc.cpp"