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"
27 #include "support/lassert.h"
28 #include "support/debug.h"
30 #include <QApplication>
31 #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
114 return list_->size();
118 QVariant data(const QModelIndex & index, int role) const
123 if (index.row() < 0 || index.row() >= rowCount())
126 if (role != Qt::DisplayRole && role != Qt::EditRole)
129 if (index.column() == 0)
130 return toqstr(list_->data(index.row()));
132 if (index.column() != 1)
135 // get icon from cache
137 QString const name = ":" + toqstr(list_->icon(index.row()));
138 if (!QPixmapCache::find("completion" + name, scaled)) {
139 // load icon from disk
140 QPixmap p = QPixmap(name);
142 // scale it to 16x16 or smaller
143 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
144 Qt::KeepAspectRatio, Qt::SmoothTransformation);
146 QPixmapCache::insert("completion" + name, scaled);
153 CompletionList const * list_;
157 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
158 : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
159 inlineVisible_(false), popupVisible_(false),
162 // Setup the completion popup
163 model_ = new GuiCompletionModel(this, 0);
165 setCompletionMode(QCompleter::PopupCompletion);
166 setCaseSensitivity(Qt::CaseSensitive);
170 QTreeView *listView = new QTreeView;
171 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
172 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
173 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
174 listView->setSelectionMode(QAbstractItemView::SingleSelection);
175 listView->header()->hide();
176 listView->setIndentation(0);
177 listView->setUniformRowHeights(true);
180 itemDelegate_ = new CompleterItemDelegate(this);
181 popup()->setItemDelegate(itemDelegate_);
183 // create timeout timers
184 popup_timer_.setSingleShot(true);
185 inline_timer_.setSingleShot(true);
186 connect(this, SIGNAL(highlighted(const QString &)),
187 this, SLOT(popupHighlighted(const QString &)));
188 connect(this, SIGNAL(activated(const QString &)),
189 this, SLOT(popupActivated(const QString &)));
190 connect(&popup_timer_, SIGNAL(timeout()),
191 this, SLOT(showPopup()));
192 connect(&inline_timer_, SIGNAL(timeout()),
193 this, SLOT(showInline()));
197 GuiCompleter::~GuiCompleter()
203 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
205 // hijack back the tab key from the popup
206 // (which stole it from the workspace before)
207 if (e->type() == QEvent::KeyPress && popupVisible()) {
208 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
218 return QCompleter::eventFilter(watched, e);
222 bool GuiCompleter::popupPossible(Cursor const & cur) const
224 return QApplication::activeWindow()
226 && cur.inset().completionSupported(cur);
230 bool GuiCompleter::inlinePossible(Cursor const & cur) const
232 return cur.inset().inlineCompletionSupported(cur);
236 bool GuiCompleter::uniqueCompletionAvailable() const
241 size_t n = popup()->model()->rowCount();
245 // if there is exactly one, we have to check whether it is a
246 // real completion, i.e. longer than the current prefix.
247 if (completionPrefix() == currentCompletion())
254 bool GuiCompleter::completionAvailable() const
259 size_t n = popup()->model()->rowCount();
261 // if there is exactly one, we have to check whether it is a
262 // real completion, i.e. longer than the current prefix.
263 if (n == 1 && completionPrefix() == currentCompletion())
270 bool GuiCompleter::popupVisible() const
272 return popupVisible_;
276 bool GuiCompleter::inlineVisible() const
278 // In fact using BufferView::inlineCompletionPos.empty() should be
279 // here. But unfortunately this information is not good enough
280 // because destructive operations like backspace might invalidate
281 // inlineCompletionPos. But then the completion should stay visible
282 // (i.e. reshown on the next update). Hence be keep this information
283 // in the inlineVisible_ variable.
284 return inlineVisible_;
288 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep)
290 // parameters which affect the completion
291 bool moved = cur != old_cursor_;
295 bool const possiblePopupState = popupPossible(cur);
296 bool const possibleInlineState = inlinePossible(cur);
298 // we moved or popup state is not ok for popup?
299 if ((moved && !keep) || !possiblePopupState)
302 // we moved or inline state is not ok for inline completion?
303 if ((moved && !keep) || !possibleInlineState)
306 // we inserted something and are in a possible popup state?
307 if (!popupVisible() && possiblePopupState && start
308 && cur.inset().automaticPopupCompletion())
309 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
311 // we inserted something and are in a possible inline completion state?
312 if (!inlineVisible() && possibleInlineState && start
313 && cur.inset().automaticInlineCompletion())
314 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
315 else if (cur.inMathed() && !lyxrc.completion_inline_math) {
316 // no inline completion, hence a metrics update is needed
317 if (!(cur.result().screenUpdate() & Update::Force))
318 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
321 // update prefix if any completion is possible
322 bool modelActive = modelActive_ && model()->rowCount() > 0;
323 if (possiblePopupState || possibleInlineState) {
327 updateAvailability();
332 void GuiCompleter::updateVisibility(bool start, bool keep)
334 Cursor cur = gui_->bufferView().cursor();
335 cur.screenUpdateFlags(Update::None);
337 updateVisibility(cur, start, keep);
339 if (cur.result().screenUpdate())
340 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
344 void GuiCompleter::updatePrefix(Cursor const & cur)
346 // get new prefix. Do nothing if unchanged
347 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
348 if (newPrefix == completionPrefix())
351 // value which should be kept selected
352 QString old = currentCompletion();
353 if (old.length() == 0)
354 old = last_selection_;
356 // update completer to new prefix
357 setCompletionPrefix(newPrefix);
359 // update popup because its size might have changed
363 // restore old selection
364 setCurrentCompletion(old);
366 // if popup is not empty, the new selection will
367 // be our last valid one
368 QString const & s = currentCompletion();
369 if (popupVisible() || inlineVisible()) {
373 last_selection_ = old;
376 // update inline completion because the default
377 // completion string might have changed
379 updateInline(cur, s);
383 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
385 if (!cur.inset().inlineCompletionSupported(cur))
389 docstring prefix = cur.inset().completionPrefix(cur);
390 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
392 // shorten it if necessary
393 if (lyxrc.completion_inline_dots != -1
394 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
395 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
397 // set inline completion at cursor position
398 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
399 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
400 inlineVisible_ = true;
404 void GuiCompleter::updatePopup(Cursor const & cur)
406 if (!cur.inset().completionSupported(cur))
409 popupVisible_ = true;
411 if (completionCount() == 0) {
412 QTimer::singleShot(0, popup(), SLOT(hide()));
416 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
420 void GuiCompleter::asyncUpdatePopup()
422 Cursor cur = gui_->bufferView().cursor();
423 if (!cur.inset().completionSupported(cur)
424 || !cur.bv().paragraphVisible(cur)) {
425 popupVisible_ = false;
429 // get dimensions of completion prefix
433 cur.inset().completionPosAndDim(cur, x, y, dim);
435 // and calculate the rect of the popup
437 if (popup()->layoutDirection() == Qt::RightToLeft)
438 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
440 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
442 // Resize the columns in the popup.
443 // This should really be in the constructor. But somehow the treeview
444 // has a bad memory about it and we have to tell him again and again.
445 QTreeView * listView = static_cast<QTreeView *>(popup());
446 listView->header()->setStretchLastSection(false);
447 listView->header()->setResizeMode(0, QHeaderView::Stretch);
448 listView->header()->setResizeMode(1, QHeaderView::Fixed);
449 listView->header()->resizeSection(1, 22);
456 void GuiCompleter::updateAvailability()
458 // this should really only be of interest if no completion is
459 // visible yet, i.e. especially if automatic completion is disabled.
460 if (inlineVisible() || popupVisible())
462 Cursor const & cur = gui_->bufferView().cursor();
463 if (!popupPossible(cur) && !inlinePossible(cur))
466 updateModel(cur, false, false);
470 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
472 // value which should be kept selected
473 QString old = currentCompletion();
474 if (old.length() == 0)
475 old = last_selection_;
479 if (cur.inTexted()) {
480 Paragraph const & par = cur.paragraph();
482 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
483 rtl = font.isVisibleRightToLeft();
485 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
488 CompletionList const * list = cur.inset().createCompletionList(cur);
489 model_->setList(list);
492 setModelSorting(QCompleter::CaseSensitivelySortedModel);
494 setModelSorting(QCompleter::UnsortedModel);
497 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
498 if (newPrefix != completionPrefix())
499 setCompletionPrefix(newPrefix);
505 // restore old selection
506 setCurrentCompletion(old);
508 // if popup is not empty, the new selection will
509 // be our last valid one
510 if (popupVisible() || inlineVisible()) {
511 QString const & s = currentCompletion();
515 last_selection_ = old;
518 // show inline completion
520 updateInline(cur, currentCompletion());
524 void GuiCompleter::showPopup(Cursor const & cur)
526 if (!popupPossible(cur))
529 updateModel(cur, true, inlineVisible());
533 void GuiCompleter::asyncHidePopup()
536 if (!inlineVisible())
541 void GuiCompleter::showInline(Cursor const & cur)
543 if (!inlinePossible(cur))
546 updateModel(cur, popupVisible(), true);
550 void GuiCompleter::hideInline(Cursor const & cur)
552 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
553 inlineVisible_ = false;
555 if (inline_timer_.isActive())
556 inline_timer_.stop();
558 // Trigger asynchronous part of hideInline. We might be
559 // in a dispatcher here and the setModel call might
560 // trigger focus events which is are not healthy here.
561 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
563 // mark that the asynchronous part will reset the model
565 modelActive_ = false;
569 void GuiCompleter::asyncHideInline()
576 void GuiCompleter::showPopup()
578 Cursor cur = gui_->bufferView().cursor();
579 cur.screenUpdateFlags(Update::None);
584 if (cur.result().screenUpdate())
585 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
589 void GuiCompleter::showInline()
591 Cursor cur = gui_->bufferView().cursor();
592 cur.screenUpdateFlags(Update::None);
597 if (cur.result().screenUpdate())
598 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
602 void GuiCompleter::hidePopup()
604 popupVisible_ = false;
606 if (popup_timer_.isActive())
609 // hide popup asynchronously because we might be here inside of
610 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
611 // workarea which then redisplays the cursor. But the metrics are not
612 // yet up to date such that the coord cache has not all insets yet. The
613 // cursorPos methods would triggers asserts in the coord cache then.
614 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
616 // mark that the asynchronous part will reset the model
617 if (!inlineVisible())
618 modelActive_ = false;
622 void GuiCompleter::hideInline()
624 Cursor cur = gui_->bufferView().cursor();
625 cur.screenUpdateFlags(Update::None);
630 if (cur.result().screenUpdate())
631 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
635 void GuiCompleter::activate()
637 if (!popupVisible() && !inlineVisible())
640 popupActivated(currentCompletion());
644 void GuiCompleter::tab()
646 BufferView * bv = &gui_->bufferView();
647 Cursor cur = bv->cursor();
648 cur.screenUpdateFlags(Update::None);
650 // check that inline completion is active
651 if (!inlineVisible() && !uniqueCompletionAvailable()) {
652 // try to activate the inline completion
653 if (cur.inset().inlineCompletionSupported(cur)) {
656 // show popup without delay because the completion was not unique
657 if (lyxrc.completion_popup_after_complete
659 && popup()->model()->rowCount() > 1)
660 popup_timer_.start(0);
665 if (!popupVisible() && cur.inset().completionSupported(cur)) {
673 // Make undo possible
674 cur.beginUndoGroup();
677 // If completion is active, at least complete by one character
678 docstring prefix = cur.inset().completionPrefix(cur);
679 docstring completion = qstring_to_ucs4(currentCompletion());
680 if (completion.size() <= prefix.size()) {
681 // finalize completion
682 cur.inset().insertCompletion(cur, docstring(), true);
684 // hide popup and inline completion
687 updateVisibility(false, false);
691 docstring nextchar = completion.substr(prefix.size(), 1);
692 if (!cur.inset().insertCompletion(cur, nextchar, false)) {
698 // try to complete as far as it is unique
699 docstring longestCompletion = longestUniqueCompletion();
700 prefix = cur.inset().completionPrefix(cur);
701 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
702 cur.inset().insertCompletion(cur, postfix, false);
703 old_cursor_ = bv->cursor();
706 // show popup without delay because the completion was not unique
707 if (lyxrc.completion_popup_after_complete
709 && popup()->model()->rowCount() > 1)
710 popup_timer_.start(0);
713 if (cur.result().screenUpdate())
714 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
719 QString GuiCompleter::currentCompletion() const
721 if (!popup()->selectionModel()->hasSelection())
724 // Not sure if this is bug in Qt: currentIndex() always
725 // return the first element in the list.
726 QModelIndex idx = popup()->currentIndex();
727 return popup()->model()->data(idx, Qt::EditRole).toString();
731 void GuiCompleter::setCurrentCompletion(QString const & s)
733 QAbstractItemModel const & model = *popup()->model();
734 size_t n = model.rowCount();
738 // select the first if s is empty
739 if (s.length() == 0) {
741 popup()->setCurrentIndex(model.index(0, 0));
746 // find old selection in model
748 if (modelSorting() == QCompleter::UnsortedModel) {
749 // In unsorted models, iterate through list until the s is found
750 for (i = 0; i < n; ++i) {
752 = model.data(model.index(i, 0), Qt::EditRole).toString();
757 // In sorted models, do binary search for s.
760 while (r >= l && l < int(n)) {
761 size_t mid = (r + l) / 2;
763 = model.data(model.index(mid, 0),
764 Qt::EditRole).toString();
767 // FIXME: is this really the same order that the docstring
768 // from the CompletionList has?
769 int c = s.compare(mids, Qt::CaseSensitive);
777 // middle is not far enough
784 // loop was left without finding anything
789 LASSERT(i <= n, /**/);
792 // select the first if none was found
797 popup()->setCurrentIndex(model.index(i, 0));
802 size_t commonPrefix(QString const & s1, QString const & s2)
804 // find common prefix
806 size_t n1 = s1.length();
807 size_t n2 = s2.length();
808 for (j = 0; j < n1 && j < n2; ++j) {
809 if (s1.at(j) != s2.at(j))
816 docstring GuiCompleter::longestUniqueCompletion() const
818 QAbstractItemModel const & model = *popup()->model();
819 size_t n = model.rowCount();
822 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
824 if (modelSorting() == QCompleter::UnsortedModel) {
825 // For unsorted model we cannot do more than iteration.
826 // Iterate through the completions and cut off where s differs
827 for (size_t i = 0; i < n && s.length() > 0; ++i) {
829 = model.data(model.index(i, 0), Qt::EditRole).toString();
831 s = s.left(commonPrefix(is, s));
834 // For sorted models we can do binary search multiple times,
835 // each time to find the first string which has s not as prefix.
837 while (i < n && s.length() > 0) {
838 // find first string that does not have s as prefix
839 // via binary search in [i,n-1]
842 // get common prefix with the middle string
843 size_t mid = (r + i) / 2;
845 = model.data(model.index(mid, 0),
846 Qt::EditRole).toString();
847 size_t oldLen = s.length();
848 size_t len = commonPrefix(mids, s);
853 // middle is not far enough
856 // middle is maybe too far
859 } while (r - i > 0 && i < n);
863 return qstring_to_ucs4(s);
867 void GuiCompleter::popupActivated(const QString & completion)
869 Cursor cur = gui_->bufferView().cursor();
870 cur.screenUpdateFlags(Update::None);
872 cur.beginUndoGroup();
875 docstring prefix = cur.inset().completionPrefix(cur);
876 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
877 cur.inset().insertCompletion(cur, postfix, true);
881 if (cur.result().screenUpdate())
882 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
887 void GuiCompleter::popupHighlighted(const QString & completion)
892 Cursor cur = gui_->bufferView().cursor();
893 cur.screenUpdateFlags(Update::None);
896 updateInline(cur, completion);
898 if (cur.result().screenUpdate())
899 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
902 } // namespace frontend
905 #include "moc_GuiCompleter.cpp"