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"
15 #include "GuiApplication.h"
16 #include "GuiWorkArea.h"
18 #include "qt_helpers.h"
21 #include "BufferView.h"
22 #include "CompletionList.h"
24 #include "Dimension.h"
27 #include "Paragraph.h"
30 #include "support/debug.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/qstring_helpers.h"
35 #include <QHeaderView>
38 #include <QPixmapCache>
40 #include <QItemDelegate>
45 using namespace lyx::support;
50 class CompleterItemDelegate : public QItemDelegate
53 explicit CompleterItemDelegate(QObject * parent)
54 : QItemDelegate(parent)
57 ~CompleterItemDelegate()
61 void paint(QPainter *painter, const QStyleOptionViewItem &option,
62 const QModelIndex &index) const override
64 if (index.column() == 0) {
65 QItemDelegate::paint(painter, option, index);
68 QStyleOptionViewItem opt = setOptions(index, option);
69 QVariant value = index.data(Qt::DisplayRole);
70 QPixmap pixmap = qvariant_cast<QPixmap>(value);
74 drawBackground(painter, opt, index);
75 if (!pixmap.isNull()) {
76 const QSize size = pixmap.size();
77 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
78 option.rect.top() + (option.rect.height() - size.height()) / 2,
81 drawFocus(painter, opt, option.rect);
86 class GuiCompletionModel : public QAbstractListModel
90 GuiCompletionModel(QObject * parent, CompletionList const * l)
91 : QAbstractListModel(parent), list_(l)
94 ~GuiCompletionModel() { delete list_; }
96 void setList(CompletionList const * l) {
106 return list_->sorted();
110 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const override
115 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const override
119 return list_->size();
123 QVariant data(const QModelIndex & index, int role) const override
128 if (index.row() < 0 || index.row() >= rowCount())
131 if (role != Qt::DisplayRole && role != Qt::EditRole)
134 if (index.column() == 0)
135 return toqstr(list_->data(index.row()));
137 if (index.column() != 1)
140 // get icon from cache
142 QString const name = toqstr(list_->icon(index.row()));
145 if (!QPixmapCache::find("completion:" + name, &scaled)) {
146 // load icon from disk
147 QPixmap p = getPixmap("images", name, "svgz,png");
149 // scale it to 16x16 or smaller
150 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
151 Qt::KeepAspectRatio, Qt::SmoothTransformation);
153 QPixmapCache::insert("completion:" + name, scaled);
160 CompletionList const * list_;
164 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
165 : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
166 inlineVisible_(false), popupVisible_(false),
169 // Setup the completion popup
170 model_ = new GuiCompletionModel(this, 0);
172 setCompletionMode(QCompleter::PopupCompletion);
173 setCaseSensitivity(Qt::CaseSensitive);
177 QTreeView *listView = new QTreeView;
178 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
179 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
180 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
181 listView->setSelectionMode(QAbstractItemView::SingleSelection);
182 listView->header()->hide();
183 listView->setIndentation(0);
184 listView->setUniformRowHeights(true);
187 itemDelegate_ = new CompleterItemDelegate(this);
188 popup()->setItemDelegate(itemDelegate_);
190 // create timeout timers
191 popup_timer_.setSingleShot(true);
192 inline_timer_.setSingleShot(true);
193 connect(this, SIGNAL(highlighted(const QString &)),
194 this, SLOT(popupHighlighted(const QString &)));
195 connect(this, SIGNAL(activated(const QString &)),
196 this, SLOT(popupActivated(const QString &)));
197 connect(&popup_timer_, SIGNAL(timeout()),
198 this, SLOT(showPopup()));
199 connect(&inline_timer_, SIGNAL(timeout()),
200 this, SLOT(showInline()));
204 GuiCompleter::~GuiCompleter()
210 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
212 // hijack back the tab key from the popup
213 // (which stole it from the workspace before)
214 if (e->type() == QEvent::KeyPress && popupVisible()) {
215 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
224 updateVisibility(false, false);
230 return QCompleter::eventFilter(watched, e);
234 bool GuiCompleter::popupPossible(Cursor const & cur) const
236 return QApplication::activeWindow()
238 && cur.inset().completionSupported(cur);
242 bool GuiCompleter::inlinePossible(Cursor const & cur) const
244 return cur.inset().inlineCompletionSupported(cur);
248 bool GuiCompleter::uniqueCompletionAvailable() const
253 size_t n = popup()->model()->rowCount();
257 // if there is exactly one, we have to check whether it is a
258 // real completion, i.e. longer than the current prefix.
259 if (completionPrefix() == currentCompletion())
266 bool GuiCompleter::completionAvailable() const
271 size_t n = popup()->model()->rowCount();
273 // if there is exactly one, we have to check whether it is a
274 // real completion, i.e. longer than the current prefix.
275 if (n == 1 && completionPrefix() == currentCompletion())
282 bool GuiCompleter::popupVisible() const
284 return popupVisible_;
288 bool GuiCompleter::inlineVisible() const
290 // In fact using BufferView::inlineCompletionPos.empty() should be
291 // here. But unfortunately this information is not good enough
292 // because destructive operations like backspace might invalidate
293 // inlineCompletionPos. But then the completion should stay visible
294 // (i.e. reshown on the next update). Hence be keep this information
295 // in the inlineVisible_ variable.
296 return inlineVisible_;
300 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep)
302 // parameters which affect the completion
303 bool moved = cur != old_cursor_;
307 bool const possiblePopupState = popupPossible(cur);
308 bool const possibleInlineState = inlinePossible(cur);
310 // we moved or popup state is not ok for popup?
311 if ((moved && !keep) || !possiblePopupState)
314 // we moved or inline state is not ok for inline completion?
315 if ((moved && !keep) || !possibleInlineState)
318 // we inserted something and are in a possible popup state?
319 if (!popupVisible() && possiblePopupState && start
320 && cur.inset().automaticPopupCompletion())
321 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
323 // we inserted something and are in a possible inline completion state?
324 if (!inlineVisible() && possibleInlineState && start
325 && cur.inset().automaticInlineCompletion())
326 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
327 else if (cur.inMathed() && !lyxrc.completion_inline_math) {
328 // no inline completion, hence a metrics update is needed
329 if (!(cur.result().screenUpdate() & Update::Force))
330 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
333 // update prefix if any completion is possible
334 bool modelActive = modelActive_ && model()->rowCount() > 0;
335 if (possiblePopupState || possibleInlineState) {
339 updateAvailability();
344 void GuiCompleter::updateVisibility(bool start, bool keep)
346 Cursor cur = gui_->bufferView().cursor();
347 cur.screenUpdateFlags(Update::None);
349 updateVisibility(cur, start, keep);
351 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
355 void GuiCompleter::updatePrefix(Cursor const & cur)
357 // get new prefix. Do nothing if unchanged
358 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
359 if (newPrefix == completionPrefix())
362 // value which should be kept selected
363 QString old = currentCompletion();
364 if (old.length() == 0)
365 old = last_selection_;
367 // update completer to new prefix
368 setCompletionPrefix(newPrefix);
370 // update popup because its size might have changed
374 // restore old selection
375 setCurrentCompletion(old);
377 // if popup is not empty, the new selection will
378 // be our last valid one
379 QString const & s = currentCompletion();
380 if (popupVisible() || inlineVisible()) {
384 last_selection_ = old;
387 // update inline completion because the default
388 // completion string might have changed
390 updateInline(cur, s);
394 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
396 if (!cur.inset().inlineCompletionSupported(cur))
400 docstring prefix = cur.inset().completionPrefix(cur);
401 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
403 // shorten it if necessary
404 if (lyxrc.completion_inline_dots != -1)
405 support::truncateWithEllipsis(postfix,
406 unsigned(lyxrc.completion_inline_dots));
408 // set inline completion at cursor position
409 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
410 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
411 inlineVisible_ = true;
415 void GuiCompleter::updatePopup(Cursor const & cur)
417 if (!cur.inset().completionSupported(cur))
420 popupVisible_ = true;
422 if (completionCount() == 0) {
423 QTimer::singleShot(0, popup(), SLOT(hide()));
427 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
431 void GuiCompleter::asyncUpdatePopup()
433 Cursor cur = gui_->bufferView().cursor();
434 if (!cur.inset().completionSupported(cur)
435 || !cur.bv().paragraphVisible(cur)) {
436 popupVisible_ = false;
440 // get dimensions of completion prefix
444 cur.inset().completionPosAndDim(cur, x, y, dim);
446 // and calculate the rect of the popup
448 if (popup()->layoutDirection() == Qt::RightToLeft)
449 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
451 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
453 // Resize the columns in the popup.
454 // This should really be in the constructor. But somehow the treeview
455 // has a bad memory about it and we have to tell him again and again.
456 QTreeView * listView = static_cast<QTreeView *>(popup());
457 listView->header()->setStretchLastSection(false);
458 setSectionResizeMode(listView->header(), 0, QHeaderView::Stretch);
459 setSectionResizeMode(listView->header(), 1, QHeaderView::Fixed);
460 listView->header()->resizeSection(1, 22);
467 void GuiCompleter::updateAvailability()
469 // this should really only be of interest if no completion is
470 // visible yet, i.e. especially if automatic completion is disabled.
471 if (inlineVisible() || popupVisible())
473 Cursor const & cur = gui_->bufferView().cursor();
474 if (!popupPossible(cur) && !inlinePossible(cur))
477 updateModel(cur, false, false);
481 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
483 // value which should be kept selected
484 QString old = currentCompletion();
485 if (old.length() == 0)
486 old = last_selection_;
490 if (cur.inTexted()) {
491 Paragraph const & par = cur.paragraph();
493 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
494 rtl = font.isVisibleRightToLeft();
496 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
499 CompletionList const * list = cur.inset().createCompletionList(cur);
500 model_->setList(list);
503 setModelSorting(QCompleter::CaseSensitivelySortedModel);
505 setModelSorting(QCompleter::UnsortedModel);
508 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
509 if (newPrefix != completionPrefix())
510 setCompletionPrefix(newPrefix);
516 // restore old selection
517 setCurrentCompletion(old);
519 // if popup is not empty, the new selection will
520 // be our last valid one
521 if (popupVisible() || inlineVisible()) {
522 QString const & s = currentCompletion();
526 last_selection_ = old;
529 // show inline completion
531 updateInline(cur, currentCompletion());
535 void GuiCompleter::showPopup(Cursor const & cur)
537 if (!popupPossible(cur))
540 updateModel(cur, true, inlineVisible());
544 void GuiCompleter::asyncHidePopup()
547 // do not clear model if it has been set by an event before the
548 // timeout got triggered.
549 if (!modelActive_ && !inlineVisible())
554 void GuiCompleter::showInline(Cursor const & cur)
556 if (!inlinePossible(cur))
559 updateModel(cur, popupVisible(), true);
563 void GuiCompleter::hideInline(Cursor const & cur)
565 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
566 inlineVisible_ = false;
568 if (inline_timer_.isActive())
569 inline_timer_.stop();
571 // Trigger asynchronous part of hideInline. We might be
572 // in a dispatcher here and the setModel call might
573 // trigger focus events which is are not healthy here.
574 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
576 // mark that the asynchronous part will reset the model
578 modelActive_ = false;
582 void GuiCompleter::asyncHideInline()
584 // do not clear model if it has been set by an event before the
585 // timeout got triggered.
586 if (!modelActive_ && !popupVisible())
591 void GuiCompleter::showPopup()
593 Cursor cur = gui_->bufferView().cursor();
594 cur.screenUpdateFlags(Update::None);
599 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
603 void GuiCompleter::showInline()
605 Cursor cur = gui_->bufferView().cursor();
606 cur.screenUpdateFlags(Update::None);
611 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
615 void GuiCompleter::hidePopup()
617 popupVisible_ = false;
619 if (popup_timer_.isActive())
622 // hide popup asynchronously because we might be here inside of
623 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
624 // workarea which then redisplays the cursor. But the metrics are not
625 // yet up to date such that the coord cache has not all insets yet. The
626 // cursorPos methods would triggers asserts in the coord cache then.
627 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
629 // mark that the asynchronous part will reset the model
630 if (!inlineVisible())
631 modelActive_ = false;
635 void GuiCompleter::hideInline()
637 Cursor cur = gui_->bufferView().cursor();
638 cur.screenUpdateFlags(Update::None);
643 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
647 void GuiCompleter::activate()
649 if (!popupVisible() && !inlineVisible())
652 popupActivated(currentCompletion());
656 void GuiCompleter::tab()
658 BufferView & bv = gui_->bufferView();
659 Cursor cur = bv.cursor();
660 cur.screenUpdateFlags(Update::None);
662 // check that inline completion is active
663 if (!inlineVisible() && !uniqueCompletionAvailable()) {
664 // try to activate the inline completion
665 if (cur.inset().inlineCompletionSupported(cur)) {
668 // show popup without delay because the completion was not unique
669 if (lyxrc.completion_popup_after_complete
671 && popup()->model()->rowCount() > 1)
672 popup_timer_.start(0);
677 if (!popupVisible() && cur.inset().completionSupported(cur)) {
685 // Prepare for undo (recordUndo is invoked in the insets' insertCompletion methods)
686 UndoGroupHelper ugh(cur.buffer());
688 // If completion is active, at least complete by one character
689 docstring prefix = cur.inset().completionPrefix(cur);
690 docstring completion = qstring_to_ucs4(currentCompletion());
691 if (completion.size() <= prefix.size()) {
692 // finalize completion
693 cur.inset().insertCompletion(cur, docstring(), true);
695 // hide popup and inline completion
698 updateVisibility(false, false);
701 bv.processUpdateFlags(cur.result().screenUpdate());
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 bv.processUpdateFlags(cur.result().screenUpdate());
728 QString GuiCompleter::currentCompletion() const
730 if (!popup()->selectionModel()->hasSelection())
733 // Not sure if this is bug in Qt: currentIndex() always
734 // return the first element in the list.
735 QModelIndex idx = popup()->currentIndex();
736 return popup()->model()->data(idx, Qt::EditRole).toString();
740 void GuiCompleter::setCurrentCompletion(QString const & s)
742 QAbstractItemModel const & model = *popup()->model();
743 size_t n = model.rowCount();
747 // select the first if s is empty
748 if (s.length() == 0) {
750 popup()->setCurrentIndex(model.index(0, 0));
755 // find old selection in model
757 if (modelSorting() == QCompleter::UnsortedModel) {
758 // In unsorted models, iterate through list until the s is found
759 for (i = 0; i < n; ++i) {
761 = model.data(model.index(i, 0), Qt::EditRole).toString();
766 // In sorted models, do binary search for s.
769 while (r >= l && l < int(n)) {
770 size_t mid = (r + l) / 2;
772 = model.data(model.index(mid, 0),
773 Qt::EditRole).toString();
776 // FIXME: is this really the same order that the docstring
777 // from the CompletionList has?
778 int c = s.compare(mids, Qt::CaseSensitive);
786 // middle is not far enough
793 // loop was left without finding anything
798 // we can try to recover
799 LASSERT(i <= n, i = 0);
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.screenUpdateFlags(Update::None);
882 cur.beginUndoGroup();
885 docstring prefix = cur.inset().completionPrefix(cur);
886 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
887 cur.inset().insertCompletion(cur, postfix, true);
891 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
896 void GuiCompleter::popupHighlighted(const QString & completion)
901 Cursor cur = gui_->bufferView().cursor();
902 cur.screenUpdateFlags(Update::None);
905 updateInline(cur, completion);
907 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
910 } // namespace frontend
913 #include "moc_GuiCompleter.cpp"