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 "GuiWorkArea.h"
24 #include "Paragraph.h"
25 #include "qt_helpers.h"
28 #include "support/lassert.h"
29 #include "support/lstrings.h"
30 #include "support/debug.h"
32 #include <QApplication>
33 #include <QHeaderView>
36 #include <QPixmapCache>
38 #include <QItemDelegate>
43 using namespace lyx::support;
48 class CompleterItemDelegate : public QItemDelegate
51 explicit CompleterItemDelegate(QObject * parent)
52 : QItemDelegate(parent)
55 ~CompleterItemDelegate()
59 void paint(QPainter *painter, const QStyleOptionViewItem &option,
60 const QModelIndex &index) const
62 if (index.column() == 0) {
63 QItemDelegate::paint(painter, option, index);
66 QStyleOptionViewItem opt = setOptions(index, option);
67 QVariant value = index.data(Qt::DisplayRole);
68 QPixmap pixmap = qvariant_cast<QPixmap>(value);
72 drawBackground(painter, opt, index);
73 if (!pixmap.isNull()) {
74 const QSize size = pixmap.size();
75 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
76 option.rect.top() + (option.rect.height() - size.height()) / 2,
79 drawFocus(painter, opt, option.rect);
84 class GuiCompletionModel : public QAbstractListModel
88 GuiCompletionModel(QObject * parent, CompletionList const * l)
89 : QAbstractListModel(parent), list_(l)
92 ~GuiCompletionModel() { delete list_; }
94 void setList(CompletionList const * l) {
104 return list_->sorted();
108 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
113 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
117 return list_->size();
121 QVariant data(const QModelIndex & index, int role) const
126 if (index.row() < 0 || index.row() >= rowCount())
129 if (role != Qt::DisplayRole && role != Qt::EditRole)
132 if (index.column() == 0)
133 return toqstr(list_->data(index.row()));
135 if (index.column() != 1)
138 // get icon from cache
140 QString const name = ":" + toqstr(list_->icon(index.row()));
143 if (!QPixmapCache::find("completion" + name, scaled)) {
144 // load icon from disk
145 QPixmap p = QPixmap(name);
147 // scale it to 16x16 or smaller
148 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
149 Qt::KeepAspectRatio, Qt::SmoothTransformation);
151 QPixmapCache::insert("completion" + name, scaled);
158 CompletionList const * list_;
162 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
163 : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
164 inlineVisible_(false), popupVisible_(false),
167 // Setup the completion popup
168 model_ = new GuiCompletionModel(this, 0);
170 setCompletionMode(QCompleter::PopupCompletion);
171 setCaseSensitivity(Qt::CaseSensitive);
175 QTreeView *listView = new QTreeView;
176 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
177 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
178 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
179 listView->setSelectionMode(QAbstractItemView::SingleSelection);
180 listView->header()->hide();
181 listView->setIndentation(0);
182 listView->setUniformRowHeights(true);
185 itemDelegate_ = new CompleterItemDelegate(this);
186 popup()->setItemDelegate(itemDelegate_);
188 // create timeout timers
189 popup_timer_.setSingleShot(true);
190 inline_timer_.setSingleShot(true);
191 connect(this, SIGNAL(highlighted(const QString &)),
192 this, SLOT(popupHighlighted(const QString &)));
193 connect(this, SIGNAL(activated(const QString &)),
194 this, SLOT(popupActivated(const QString &)));
195 connect(&popup_timer_, SIGNAL(timeout()),
196 this, SLOT(showPopup()));
197 connect(&inline_timer_, SIGNAL(timeout()),
198 this, SLOT(showInline()));
202 GuiCompleter::~GuiCompleter()
208 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
210 // hijack back the tab key from the popup
211 // (which stole it from the workspace before)
212 if (e->type() == QEvent::KeyPress && popupVisible()) {
213 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
222 updateVisibility(false, false);
228 return QCompleter::eventFilter(watched, e);
232 bool GuiCompleter::popupPossible(Cursor const & cur) const
234 return QApplication::activeWindow()
236 && cur.inset().completionSupported(cur);
240 bool GuiCompleter::inlinePossible(Cursor const & cur) const
242 return cur.inset().inlineCompletionSupported(cur);
246 bool GuiCompleter::uniqueCompletionAvailable() const
251 size_t n = popup()->model()->rowCount();
255 // if there is exactly one, we have to check whether it is a
256 // real completion, i.e. longer than the current prefix.
257 if (completionPrefix() == currentCompletion())
264 bool GuiCompleter::completionAvailable() const
269 size_t n = popup()->model()->rowCount();
271 // if there is exactly one, we have to check whether it is a
272 // real completion, i.e. longer than the current prefix.
273 if (n == 1 && completionPrefix() == currentCompletion())
280 bool GuiCompleter::popupVisible() const
282 return popupVisible_;
286 bool GuiCompleter::inlineVisible() const
288 // In fact using BufferView::inlineCompletionPos.empty() should be
289 // here. But unfortunately this information is not good enough
290 // because destructive operations like backspace might invalidate
291 // inlineCompletionPos. But then the completion should stay visible
292 // (i.e. reshown on the next update). Hence be keep this information
293 // in the inlineVisible_ variable.
294 return inlineVisible_;
298 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep)
300 // parameters which affect the completion
301 bool moved = cur != old_cursor_;
305 bool const possiblePopupState = popupPossible(cur);
306 bool const possibleInlineState = inlinePossible(cur);
308 // we moved or popup state is not ok for popup?
309 if ((moved && !keep) || !possiblePopupState)
312 // we moved or inline state is not ok for inline completion?
313 if ((moved && !keep) || !possibleInlineState)
316 // we inserted something and are in a possible popup state?
317 if (!popupVisible() && possiblePopupState && start
318 && cur.inset().automaticPopupCompletion())
319 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
321 // we inserted something and are in a possible inline completion state?
322 if (!inlineVisible() && possibleInlineState && start
323 && cur.inset().automaticInlineCompletion())
324 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
325 else if (cur.inMathed() && !lyxrc.completion_inline_math) {
326 // no inline completion, hence a metrics update is needed
327 if (!(cur.result().screenUpdate() & Update::Force))
328 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
331 // update prefix if any completion is possible
332 bool modelActive = modelActive_ && model()->rowCount() > 0;
333 if (possiblePopupState || possibleInlineState) {
337 updateAvailability();
342 void GuiCompleter::updateVisibility(bool start, bool keep)
344 Cursor cur = gui_->bufferView().cursor();
345 cur.screenUpdateFlags(Update::None);
347 updateVisibility(cur, start, keep);
349 if (cur.result().screenUpdate())
350 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
354 void GuiCompleter::updatePrefix(Cursor const & cur)
356 // get new prefix. Do nothing if unchanged
357 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
358 if (newPrefix == completionPrefix())
361 // value which should be kept selected
362 QString old = currentCompletion();
363 if (old.length() == 0)
364 old = last_selection_;
366 // update completer to new prefix
367 setCompletionPrefix(newPrefix);
369 // update popup because its size might have changed
373 // restore old selection
374 setCurrentCompletion(old);
376 // if popup is not empty, the new selection will
377 // be our last valid one
378 QString const & s = currentCompletion();
379 if (popupVisible() || inlineVisible()) {
383 last_selection_ = old;
386 // update inline completion because the default
387 // completion string might have changed
389 updateInline(cur, s);
393 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
395 if (!cur.inset().inlineCompletionSupported(cur))
399 docstring prefix = cur.inset().completionPrefix(cur);
400 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
402 // shorten it if necessary
403 if (lyxrc.completion_inline_dots != -1)
404 support::truncateWithEllipsis(postfix,
405 unsigned(lyxrc.completion_inline_dots));
407 // set inline completion at cursor position
408 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
409 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
410 inlineVisible_ = true;
414 void GuiCompleter::updatePopup(Cursor const & cur)
416 if (!cur.inset().completionSupported(cur))
419 popupVisible_ = true;
421 if (completionCount() == 0) {
422 QTimer::singleShot(0, popup(), SLOT(hide()));
426 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
430 void GuiCompleter::asyncUpdatePopup()
432 Cursor cur = gui_->bufferView().cursor();
433 if (!cur.inset().completionSupported(cur)
434 || !cur.bv().paragraphVisible(cur)) {
435 popupVisible_ = false;
439 // get dimensions of completion prefix
443 cur.inset().completionPosAndDim(cur, x, y, dim);
445 // and calculate the rect of the popup
447 if (popup()->layoutDirection() == Qt::RightToLeft)
448 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
450 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
452 // Resize the columns in the popup.
453 // This should really be in the constructor. But somehow the treeview
454 // has a bad memory about it and we have to tell him again and again.
455 QTreeView * listView = static_cast<QTreeView *>(popup());
456 listView->header()->setStretchLastSection(false);
457 setSectionResizeMode(listView->header(), 0, QHeaderView::Stretch);
458 setSectionResizeMode(listView->header(), 1, QHeaderView::Fixed);
459 listView->header()->resizeSection(1, 22);
466 void GuiCompleter::updateAvailability()
468 // this should really only be of interest if no completion is
469 // visible yet, i.e. especially if automatic completion is disabled.
470 if (inlineVisible() || popupVisible())
472 Cursor const & cur = gui_->bufferView().cursor();
473 if (!popupPossible(cur) && !inlinePossible(cur))
476 updateModel(cur, false, false);
480 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
482 // value which should be kept selected
483 QString old = currentCompletion();
484 if (old.length() == 0)
485 old = last_selection_;
489 if (cur.inTexted()) {
490 Paragraph const & par = cur.paragraph();
492 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
493 rtl = font.isVisibleRightToLeft();
495 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
498 CompletionList const * list = cur.inset().createCompletionList(cur);
499 model_->setList(list);
502 setModelSorting(QCompleter::CaseSensitivelySortedModel);
504 setModelSorting(QCompleter::UnsortedModel);
507 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
508 if (newPrefix != completionPrefix())
509 setCompletionPrefix(newPrefix);
515 // restore old selection
516 setCurrentCompletion(old);
518 // if popup is not empty, the new selection will
519 // be our last valid one
520 if (popupVisible() || inlineVisible()) {
521 QString const & s = currentCompletion();
525 last_selection_ = old;
528 // show inline completion
530 updateInline(cur, currentCompletion());
534 void GuiCompleter::showPopup(Cursor const & cur)
536 if (!popupPossible(cur))
539 updateModel(cur, true, inlineVisible());
543 void GuiCompleter::asyncHidePopup()
546 // do not clear model if it has been set by an event before the
547 // timeout got triggered.
548 if (!modelActive_ && !inlineVisible())
553 void GuiCompleter::showInline(Cursor const & cur)
555 if (!inlinePossible(cur))
558 updateModel(cur, popupVisible(), true);
562 void GuiCompleter::hideInline(Cursor const & cur)
564 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
565 inlineVisible_ = false;
567 if (inline_timer_.isActive())
568 inline_timer_.stop();
570 // Trigger asynchronous part of hideInline. We might be
571 // in a dispatcher here and the setModel call might
572 // trigger focus events which is are not healthy here.
573 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
575 // mark that the asynchronous part will reset the model
577 modelActive_ = false;
581 void GuiCompleter::asyncHideInline()
583 // do not clear model if it has been set by an event before the
584 // timeout got triggered.
585 if (!modelActive_ && !popupVisible())
590 void GuiCompleter::showPopup()
592 Cursor cur = gui_->bufferView().cursor();
593 cur.screenUpdateFlags(Update::None);
598 if (cur.result().screenUpdate())
599 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
603 void GuiCompleter::showInline()
605 Cursor cur = gui_->bufferView().cursor();
606 cur.screenUpdateFlags(Update::None);
611 if (cur.result().screenUpdate())
612 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
616 void GuiCompleter::hidePopup()
618 popupVisible_ = false;
620 if (popup_timer_.isActive())
623 // hide popup asynchronously because we might be here inside of
624 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
625 // workarea which then redisplays the cursor. But the metrics are not
626 // yet up to date such that the coord cache has not all insets yet. The
627 // cursorPos methods would triggers asserts in the coord cache then.
628 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
630 // mark that the asynchronous part will reset the model
631 if (!inlineVisible())
632 modelActive_ = false;
636 void GuiCompleter::hideInline()
638 Cursor cur = gui_->bufferView().cursor();
639 cur.screenUpdateFlags(Update::None);
644 if (cur.result().screenUpdate())
645 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
649 void GuiCompleter::activate()
651 if (!popupVisible() && !inlineVisible())
654 popupActivated(currentCompletion());
658 void GuiCompleter::tab()
660 BufferView * bv = &gui_->bufferView();
661 Cursor cur = bv->cursor();
662 cur.screenUpdateFlags(Update::None);
664 // check that inline completion is active
665 if (!inlineVisible() && !uniqueCompletionAvailable()) {
666 // try to activate the inline completion
667 if (cur.inset().inlineCompletionSupported(cur)) {
670 // show popup without delay because the completion was not unique
671 if (lyxrc.completion_popup_after_complete
673 && popup()->model()->rowCount() > 1)
674 popup_timer_.start(0);
679 if (!popupVisible() && cur.inset().completionSupported(cur)) {
687 // 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().screenUpdate())
725 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
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 // we can try to recover
800 LASSERT(i <= n, i = 0);
803 // select the first if none was found
808 popup()->setCurrentIndex(model.index(i, 0));
813 size_t commonPrefix(QString const & s1, QString const & s2)
815 // find common prefix
817 size_t n1 = s1.length();
818 size_t n2 = s2.length();
819 for (j = 0; j < n1 && j < n2; ++j) {
820 if (s1.at(j) != s2.at(j))
827 docstring GuiCompleter::longestUniqueCompletion() const
829 QAbstractItemModel const & model = *popup()->model();
830 size_t n = model.rowCount();
833 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
835 if (modelSorting() == QCompleter::UnsortedModel) {
836 // For unsorted model we cannot do more than iteration.
837 // Iterate through the completions and cut off where s differs
838 for (size_t i = 0; i < n && s.length() > 0; ++i) {
840 = model.data(model.index(i, 0), Qt::EditRole).toString();
842 s = s.left(commonPrefix(is, s));
845 // For sorted models we can do binary search multiple times,
846 // each time to find the first string which has s not as prefix.
848 while (i < n && s.length() > 0) {
849 // find first string that does not have s as prefix
850 // via binary search in [i,n-1]
853 // get common prefix with the middle string
854 size_t mid = (r + i) / 2;
856 = model.data(model.index(mid, 0),
857 Qt::EditRole).toString();
858 size_t oldLen = s.length();
859 size_t len = commonPrefix(mids, s);
864 // middle is not far enough
867 // middle is maybe too far
870 } while (r - i > 0 && i < n);
874 return qstring_to_ucs4(s);
878 void GuiCompleter::popupActivated(const QString & completion)
880 Cursor cur = gui_->bufferView().cursor();
881 cur.screenUpdateFlags(Update::None);
883 cur.beginUndoGroup();
886 docstring prefix = cur.inset().completionPrefix(cur);
887 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
888 cur.inset().insertCompletion(cur, postfix, true);
892 if (cur.result().screenUpdate())
893 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
898 void GuiCompleter::popupHighlighted(const QString & completion)
903 Cursor cur = gui_->bufferView().cursor();
904 cur.screenUpdateFlags(Update::None);
907 updateInline(cur, completion);
909 if (cur.result().screenUpdate())
910 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
913 } // namespace frontend
916 #include "moc_GuiCompleter.cpp"