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 "GuiCompleter.h"
16 #include "BufferView.h"
17 #include "CompletionList.h"
19 #include "Dimension.h"
20 #include "FuncRequest.h"
21 #include "GuiWorkArea.h"
25 #include "Paragraph.h"
28 #include "support/lassert.h"
29 #include "support/debug.h"
31 #include <QApplication>
32 #include <QHeaderView>
34 #include <QPixmapCache>
36 #include <QItemDelegate>
41 using namespace lyx::support;
46 class CompleterItemDelegate : public QItemDelegate
49 explicit CompleterItemDelegate(QObject * parent)
50 : QItemDelegate(parent)
53 ~CompleterItemDelegate()
57 void paint(QPainter *painter, const QStyleOptionViewItem &option,
58 const QModelIndex &index) const
60 if (index.column() == 0) {
61 QItemDelegate::paint(painter, option, index);
64 QStyleOptionViewItem opt = setOptions(index, option);
65 QVariant value = index.data(Qt::DisplayRole);
66 QPixmap pixmap = qvariant_cast<QPixmap>(value);
70 drawBackground(painter, opt, index);
71 if (!pixmap.isNull()) {
72 const QSize size = pixmap.size();
73 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
74 option.rect.top() + (option.rect.height() - size.height()) / 2,
77 drawFocus(painter, opt, option.rect);
82 class GuiCompletionModel : public QAbstractListModel
86 GuiCompletionModel(QObject * parent, CompletionList const * l)
87 : QAbstractListModel(parent), list_(l)
90 ~GuiCompletionModel() { delete list_; }
92 void setList(CompletionList const * l) {
101 return list_->sorted();
105 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
110 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
115 return list_->size();
119 QVariant data(const QModelIndex & index, int role) const
124 if (index.row() < 0 || index.row() >= rowCount())
127 if (role != Qt::DisplayRole && role != Qt::EditRole)
130 if (index.column() == 0)
131 return toqstr(list_->data(index.row()));
133 if (index.column() == 1) {
134 // get icon from cache
136 QString const name = ":" + toqstr(list_->icon(index.row()));
137 if (!QPixmapCache::find("completion" + name, scaled)) {
138 // load icon from disk
139 QPixmap p = QPixmap(name);
141 // scale it to 16x16 or smaller
142 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
143 Qt::KeepAspectRatio, Qt::SmoothTransformation);
146 QPixmapCache::insert("completion" + name, scaled);
155 CompletionList const * list_;
159 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
160 : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
161 inlineVisible_(false), popupVisible_(false),
164 // Setup the completion popup
165 model_ = new GuiCompletionModel(this, 0);
167 setCompletionMode(QCompleter::PopupCompletion);
168 setCaseSensitivity(Qt::CaseInsensitive);
172 QTreeView *listView = new QTreeView;
173 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
174 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
175 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
176 listView->setSelectionMode(QAbstractItemView::SingleSelection);
177 listView->header()->hide();
178 listView->setIndentation(0);
179 listView->setUniformRowHeights(true);
182 itemDelegate_ = new CompleterItemDelegate(this);
183 popup()->setItemDelegate(itemDelegate_);
185 // create timeout timers
186 popup_timer_.setSingleShot(true);
187 inline_timer_.setSingleShot(true);
188 connect(this, SIGNAL(highlighted(const QString &)),
189 this, SLOT(popupHighlighted(const QString &)));
190 connect(this, SIGNAL(activated(const QString &)),
191 this, SLOT(popupActivated(const QString &)));
192 connect(&popup_timer_, SIGNAL(timeout()),
193 this, SLOT(showPopup()));
194 connect(&inline_timer_, SIGNAL(timeout()),
195 this, SLOT(showInline()));
199 GuiCompleter::~GuiCompleter()
205 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
207 // hijack back the tab key from the popup
208 // (which stole it from the workspace before)
209 if (e->type() == QEvent::KeyPress && popupVisible()) {
210 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
220 return QCompleter::eventFilter(watched, e);
224 bool GuiCompleter::popupPossible(Cursor const & cur) const
226 return QApplication::activeWindow()
228 && cur.inset().completionSupported(cur);
232 bool GuiCompleter::inlinePossible(Cursor const & cur) const
234 return cur.inset().inlineCompletionSupported(cur);
238 bool GuiCompleter::uniqueCompletionAvailable() const
243 size_t n = popup()->model()->rowCount();
247 // if there is exactly one, we have to check whether it is a
248 // real completion, i.e. longer than the current prefix.
249 if (completionPrefix() == currentCompletion())
256 bool GuiCompleter::completionAvailable() const
261 size_t n = popup()->model()->rowCount();
263 // if there is exactly one, we have to check whether it is a
264 // real completion, i.e. longer than the current prefix.
265 if (n == 1 && completionPrefix() == currentCompletion())
272 bool GuiCompleter::popupVisible() const
274 return popupVisible_;
278 bool GuiCompleter::inlineVisible() const
280 // In fact using BufferView::inlineCompletionPos.empty() should be
281 // here. But unfortunately this information is not good enough
282 // because destructive operations like backspace might invalidate
283 // inlineCompletionPos. But then the completion should stay visible
284 // (i.e. reshown on the next update). Hence be keep this information
285 // in the inlineVisible_ variable.
286 return inlineVisible_;
290 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
292 // parameters which affect the completion
293 bool moved = cur != old_cursor_;
297 bool possiblePopupState = popupPossible(cur) && cursorInView;
298 bool possibleInlineState = inlinePossible(cur) && cursorInView;
300 // we moved or popup state is not ok for popup?
301 if ((moved && !keep) || !possiblePopupState)
304 // we moved or inline state is not ok for inline completion?
305 if ((moved && !keep) || !possibleInlineState)
308 // we inserted something and are in a possible popup state?
309 if (!popupVisible() && possiblePopupState && start
310 && cur.inset().automaticPopupCompletion())
311 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
313 // we inserted something and are in a possible inline completion state?
314 if (!inlineVisible() && possibleInlineState && start
315 && cur.inset().automaticInlineCompletion())
316 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
318 // no inline completion, hence a metrics update is needed
319 if (!(cur.result().update() & Update::Force))
320 cur.updateFlags(cur.result().update() | Update::SinglePar);
323 // update prefix if any completion is possible
324 bool modelActive = modelActive_ && model()->rowCount() > 0;
325 if (possiblePopupState || possibleInlineState) {
329 updateAvailability();
334 void GuiCompleter::updateVisibility(bool start, bool keep)
336 Cursor cur = gui_->bufferView().cursor();
337 cur.updateFlags(Update::None);
339 updateVisibility(cur, start, keep);
341 if (cur.result().update())
342 gui_->bufferView().processUpdateFlags(cur.result().update());
346 void GuiCompleter::updatePrefix(Cursor & cur)
348 // get new prefix. Do nothing if unchanged
349 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
350 if (newPrefix == completionPrefix())
353 // value which should be kept selected
354 QString old = currentCompletion();
355 if (old.length() == 0)
356 old = last_selection_;
358 // update completer to new prefix
359 setCompletionPrefix(newPrefix);
361 // update popup because its size might have changed
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();
371 if (popupVisible() || inlineVisible()) {
375 last_selection_ = old;
378 // update inline completion because the default
379 // completion string might have changed
381 updateInline(cur, s);
385 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
387 if (!cur.inset().inlineCompletionSupported(cur))
391 docstring prefix = cur.inset().completionPrefix(cur);
392 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
394 // shorten it if necessary
395 if (lyxrc.completion_inline_dots != -1
396 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
397 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
399 // set inline completion at cursor position
400 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
401 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
402 inlineVisible_ = true;
406 void GuiCompleter::updatePopup(Cursor & cur)
408 if (!cur.inset().completionSupported(cur))
411 popupVisible_ = true;
413 if (completionCount() == 0) {
414 QTimer::singleShot(0, popup(), SLOT(hide()));
418 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
422 void GuiCompleter::asyncUpdatePopup()
424 Cursor cur = gui_->bufferView().cursor();
425 if (!cur.inset().completionSupported(cur)
426 || !cur.bv().paragraphVisible(cur)) {
427 popupVisible_ = false;
431 // get dimensions of completion prefix
435 cur.inset().completionPosAndDim(cur, x, y, dim);
437 // and calculate the rect of the popup
439 if (popup()->layoutDirection() == Qt::RightToLeft)
440 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
442 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
444 // Resize the columns in the popup.
445 // This should really be in the constructor. But somehow the treeview
446 // has a bad memory about it and we have to tell him again and again.
447 QTreeView * listView = static_cast<QTreeView *>(popup());
448 listView->header()->setStretchLastSection(false);
449 listView->header()->setResizeMode(0, QHeaderView::Stretch);
450 listView->header()->setResizeMode(1, QHeaderView::Fixed);
451 listView->header()->resizeSection(1, 22);
458 void GuiCompleter::updateAvailability()
460 // this should really only be of interest if no completion is
461 // visible yet, i.e. especially if automatic completion is disabled.
462 if (inlineVisible() || popupVisible())
464 Cursor & cur = gui_->bufferView().cursor();
465 if (!popupPossible(cur) && !inlinePossible(cur))
468 updateModel(cur, false, false);
472 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
474 // value which should be kept selected
475 QString old = currentCompletion();
476 if (old.length() == 0)
477 old = last_selection_;
481 if (cur.inTexted()) {
482 Paragraph const & par = cur.paragraph();
484 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
485 rtl = font.isVisibleRightToLeft();
487 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
490 CompletionList const * list = cur.inset().createCompletionList(cur);
491 model_->setList(list);
494 setModelSorting(QCompleter::CaseSensitivelySortedModel);
496 setModelSorting(QCompleter::UnsortedModel);
499 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
500 if (newPrefix != completionPrefix())
501 setCompletionPrefix(newPrefix);
507 // restore old selection
508 setCurrentCompletion(old);
510 // if popup is not empty, the new selection will
511 // be our last valid one
512 if (popupVisible() || inlineVisible()) {
513 QString const & s = currentCompletion();
517 last_selection_ = old;
520 // show inline completion
522 updateInline(cur, currentCompletion());
526 void GuiCompleter::showPopup(Cursor & cur)
528 if (!popupPossible(cur))
531 updateModel(cur, true, inlineVisible());
535 void GuiCompleter::hidePopup(Cursor &)
537 popupVisible_ = false;
539 if (popup_timer_.isActive())
542 // hide popup asynchronously because we might be here inside of
543 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
544 // workarea which then redisplays the cursor. But the metrics are not
545 // yet up to date such that the coord cache has not all insets yet. The
546 // cursorPos methods would triggers asserts in the coord cache then.
547 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
549 // mark that the asynchronous part will reset the model
550 if (!inlineVisible())
551 modelActive_ = false;
555 void GuiCompleter::asyncHidePopup()
558 if (!inlineVisible())
563 void GuiCompleter::showInline(Cursor & cur)
565 if (!inlinePossible(cur))
568 updateModel(cur, popupVisible(), true);
572 void GuiCompleter::hideInline(Cursor & cur)
574 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
575 inlineVisible_ = false;
577 if (inline_timer_.isActive())
578 inline_timer_.stop();
580 // Trigger asynchronous part of hideInline. We might be
581 // in a dispatcher here and the setModel call might
582 // trigger focus events which is are not healthy here.
583 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
585 // mark that the asynchronous part will reset the model
587 modelActive_ = false;
591 void GuiCompleter::asyncHideInline()
598 void GuiCompleter::showPopup()
600 Cursor cur = gui_->bufferView().cursor();
601 cur.updateFlags(Update::None);
606 if (cur.result().update())
607 gui_->bufferView().processUpdateFlags(cur.result().update());
611 void GuiCompleter::showInline()
613 Cursor cur = gui_->bufferView().cursor();
614 cur.updateFlags(Update::None);
619 if (cur.result().update())
620 gui_->bufferView().processUpdateFlags(cur.result().update());
624 void GuiCompleter::hidePopup()
626 Cursor cur = gui_->bufferView().cursor();
627 cur.updateFlags(Update::None);
632 if (cur.result().update())
633 gui_->bufferView().processUpdateFlags(cur.result().update());
637 void GuiCompleter::hideInline()
639 Cursor cur = gui_->bufferView().cursor();
640 cur.updateFlags(Update::None);
645 if (cur.result().update())
646 gui_->bufferView().processUpdateFlags(cur.result().update());
650 void GuiCompleter::activate()
652 if (!popupVisible() && !inlineVisible())
655 popupActivated(currentCompletion());
659 void GuiCompleter::tab()
661 BufferView * bv = &gui_->bufferView();
662 Cursor cur = bv->cursor();
663 cur.updateFlags(Update::None);
665 // check that inline completion is active
666 if (!inlineVisible() && !uniqueCompletionAvailable()) {
667 // try to activate the inline completion
668 if (cur.inset().inlineCompletionSupported(cur)) {
671 // show popup without delay because the completion was not unique
672 if (lyxrc.completion_popup_after_complete
674 && popup()->model()->rowCount() > 1)
675 popup_timer_.start(0);
680 if (!popupVisible() && cur.inset().completionSupported(cur)) {
688 // Make undo possible
691 // If completion is active, at least complete by one character
692 docstring prefix = cur.inset().completionPrefix(cur);
693 docstring completion = qstring_to_ucs4(currentCompletion());
694 if (completion.size() <= prefix.size()) {
695 // finalize completion
696 cur.inset().insertCompletion(cur, docstring(), true);
698 // hide popup and inline completion
701 updateVisibility(false, false);
704 docstring nextchar = completion.substr(prefix.size(), 1);
705 if (!cur.inset().insertCompletion(cur, nextchar, false))
709 // try to complete as far as it is unique
710 docstring longestCompletion = longestUniqueCompletion();
711 prefix = cur.inset().completionPrefix(cur);
712 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
713 cur.inset().insertCompletion(cur, postfix, false);
714 old_cursor_ = bv->cursor();
717 // show popup without delay because the completion was not unique
718 if (lyxrc.completion_popup_after_complete
720 && popup()->model()->rowCount() > 1)
721 popup_timer_.start(0);
724 if (cur.result().update())
725 gui_->bufferView().processUpdateFlags(cur.result().update());
729 QString GuiCompleter::currentCompletion() const
731 if (!popup()->selectionModel()->hasSelection())
734 // Not sure if this is bug in Qt: currentIndex() always
735 // return the first element in the list.
736 QModelIndex idx = popup()->currentIndex();
737 return popup()->model()->data(idx, Qt::EditRole).toString();
741 void GuiCompleter::setCurrentCompletion(QString const & s)
743 QAbstractItemModel const & model = *popup()->model();
744 size_t n = model.rowCount();
748 // select the first if s is empty
749 if (s.length() == 0) {
751 popup()->setCurrentIndex(model.index(0, 0));
756 // find old selection in model
758 if (modelSorting() == QCompleter::UnsortedModel) {
759 // In unsorted models, iterate through list until the s is found
760 for (i = 0; i < n; ++i) {
762 = model.data(model.index(i, 0), Qt::EditRole).toString();
767 // In sorted models, do binary search for s.
770 while (r >= l && l < int(n)) {
771 size_t mid = (r + l) / 2;
773 = model.data(model.index(mid, 0),
774 Qt::EditRole).toString();
777 // FIXME: is this really the same order that the docstring
778 // from the CompletionList has?
779 int c = s.compare(mids, Qt::CaseSensitive);
787 // middle is not far enough
794 // loop was left without finding anything
799 LASSERT(i <= n, /**/);
802 // select the first if none was found
807 popup()->setCurrentIndex(model.index(i, 0));
812 size_t commonPrefix(QString const & s1, QString const & s2)
814 // find common prefix
816 size_t n1 = s1.length();
817 size_t n2 = s2.length();
818 for (j = 0; j < n1 && j < n2; ++j) {
819 if (s1.at(j) != s2.at(j))
826 docstring GuiCompleter::longestUniqueCompletion() const
828 QAbstractItemModel const & model = *popup()->model();
829 size_t n = model.rowCount();
832 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
834 if (modelSorting() == QCompleter::UnsortedModel) {
835 // For unsorted model we cannot do more than iteration.
836 // Iterate through the completions and cut off where s differs
837 for (size_t i = 0; i < n && s.length() > 0; ++i) {
839 = model.data(model.index(i, 0), Qt::EditRole).toString();
841 s = s.left(commonPrefix(is, s));
844 // For sorted models we can do binary search multiple times,
845 // each time to find the first string which has s not as prefix.
847 while (i < n && s.length() > 0) {
848 // find first string that does not have s as prefix
849 // via binary search in [i,n-1]
852 // get common prefix with the middle string
853 size_t mid = (r + i) / 2;
855 = model.data(model.index(mid, 0),
856 Qt::EditRole).toString();
857 size_t oldLen = s.length();
858 size_t len = commonPrefix(mids, s);
863 // middle is not far enough
866 // middle is maybe too far
869 } while (r - i > 0 && i < n);
873 return qstring_to_ucs4(s);
877 void GuiCompleter::popupActivated(const QString & completion)
879 Cursor cur = gui_->bufferView().cursor();
880 cur.updateFlags(Update::None);
884 docstring prefix = cur.inset().completionPrefix(cur);
885 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
886 cur.inset().insertCompletion(cur, postfix, true);
890 if (cur.result().update())
891 gui_->bufferView().processUpdateFlags(cur.result().update());
895 void GuiCompleter::popupHighlighted(const QString & completion)
900 Cursor cur = gui_->bufferView().cursor();
901 cur.updateFlags(Update::None);
904 updateInline(cur, completion);
906 if (cur.result().update())
907 gui_->bufferView().processUpdateFlags(cur.result().update());
910 } // namespace frontend
913 #include "moc_GuiCompleter.cpp"