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);
223 return QCompleter::eventFilter(watched, e);
227 bool GuiCompleter::popupPossible(Cursor const & cur) const
229 return QApplication::activeWindow()
231 && cur.inset().completionSupported(cur);
235 bool GuiCompleter::inlinePossible(Cursor const & cur) const
237 return cur.inset().inlineCompletionSupported(cur);
241 bool GuiCompleter::uniqueCompletionAvailable() const
246 size_t n = popup()->model()->rowCount();
250 // if there is exactly one, we have to check whether it is a
251 // real completion, i.e. longer than the current prefix.
252 if (completionPrefix() == currentCompletion())
259 bool GuiCompleter::completionAvailable() const
264 size_t n = popup()->model()->rowCount();
266 // if there is exactly one, we have to check whether it is a
267 // real completion, i.e. longer than the current prefix.
268 if (n == 1 && completionPrefix() == currentCompletion())
275 bool GuiCompleter::popupVisible() const
277 return popupVisible_;
281 bool GuiCompleter::inlineVisible() const
283 // In fact using BufferView::inlineCompletionPos.empty() should be
284 // here. But unfortunately this information is not good enough
285 // because destructive operations like backspace might invalidate
286 // inlineCompletionPos. But then the completion should stay visible
287 // (i.e. reshown on the next update). Hence be keep this information
288 // in the inlineVisible_ variable.
289 return inlineVisible_;
293 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep)
295 // parameters which affect the completion
296 bool moved = cur != old_cursor_;
300 bool const possiblePopupState = popupPossible(cur);
301 bool const possibleInlineState = inlinePossible(cur);
303 // we moved or popup state is not ok for popup?
304 if ((moved && !keep) || !possiblePopupState)
307 // we moved or inline state is not ok for inline completion?
308 if ((moved && !keep) || !possibleInlineState)
311 // we inserted something and are in a possible popup state?
312 if (!popupVisible() && possiblePopupState && start
313 && cur.inset().automaticPopupCompletion())
314 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
316 // we inserted something and are in a possible inline completion state?
317 if (!inlineVisible() && possibleInlineState && start
318 && cur.inset().automaticInlineCompletion())
319 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
320 else if (cur.inMathed() && !lyxrc.completion_inline_math) {
321 // no inline completion, hence a metrics update is needed
322 if (!(cur.result().screenUpdate() & Update::Force))
323 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
326 // update prefix if any completion is possible
327 bool modelActive = modelActive_ && model()->rowCount() > 0;
328 if (possiblePopupState || possibleInlineState) {
332 updateAvailability();
337 void GuiCompleter::updateVisibility(bool start, bool keep)
339 Cursor cur = gui_->bufferView().cursor();
340 cur.screenUpdateFlags(Update::None);
342 updateVisibility(cur, start, keep);
344 if (cur.result().screenUpdate())
345 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
349 void GuiCompleter::updatePrefix(Cursor const & cur)
351 // get new prefix. Do nothing if unchanged
352 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
353 if (newPrefix == completionPrefix())
356 // value which should be kept selected
357 QString old = currentCompletion();
358 if (old.length() == 0)
359 old = last_selection_;
361 // update completer to new prefix
362 setCompletionPrefix(newPrefix);
364 // update popup because its size might have changed
368 // restore old selection
369 setCurrentCompletion(old);
371 // if popup is not empty, the new selection will
372 // be our last valid one
373 QString const & s = currentCompletion();
374 if (popupVisible() || inlineVisible()) {
378 last_selection_ = old;
381 // update inline completion because the default
382 // completion string might have changed
384 updateInline(cur, s);
388 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
390 if (!cur.inset().inlineCompletionSupported(cur))
394 docstring prefix = cur.inset().completionPrefix(cur);
395 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
397 // shorten it if necessary
398 if (lyxrc.completion_inline_dots != -1)
399 support::truncateWithEllipsis(postfix,
400 unsigned(lyxrc.completion_inline_dots));
402 // set inline completion at cursor position
403 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
404 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
405 inlineVisible_ = true;
409 void GuiCompleter::updatePopup(Cursor const & cur)
411 if (!cur.inset().completionSupported(cur))
414 popupVisible_ = true;
416 if (completionCount() == 0) {
417 QTimer::singleShot(0, popup(), SLOT(hide()));
421 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
425 void GuiCompleter::asyncUpdatePopup()
427 Cursor cur = gui_->bufferView().cursor();
428 if (!cur.inset().completionSupported(cur)
429 || !cur.bv().paragraphVisible(cur)) {
430 popupVisible_ = false;
434 // get dimensions of completion prefix
438 cur.inset().completionPosAndDim(cur, x, y, dim);
440 // and calculate the rect of the popup
442 if (popup()->layoutDirection() == Qt::RightToLeft)
443 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
445 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
447 // Resize the columns in the popup.
448 // This should really be in the constructor. But somehow the treeview
449 // has a bad memory about it and we have to tell him again and again.
450 QTreeView * listView = static_cast<QTreeView *>(popup());
451 listView->header()->setStretchLastSection(false);
452 setSectionResizeMode(listView->header(), 0, QHeaderView::Stretch);
453 setSectionResizeMode(listView->header(), 1, QHeaderView::Fixed);
454 listView->header()->resizeSection(1, 22);
461 void GuiCompleter::updateAvailability()
463 // this should really only be of interest if no completion is
464 // visible yet, i.e. especially if automatic completion is disabled.
465 if (inlineVisible() || popupVisible())
467 Cursor const & cur = gui_->bufferView().cursor();
468 if (!popupPossible(cur) && !inlinePossible(cur))
471 updateModel(cur, false, false);
475 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
477 // value which should be kept selected
478 QString old = currentCompletion();
479 if (old.length() == 0)
480 old = last_selection_;
484 if (cur.inTexted()) {
485 Paragraph const & par = cur.paragraph();
487 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
488 rtl = font.isVisibleRightToLeft();
490 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
493 CompletionList const * list = cur.inset().createCompletionList(cur);
494 model_->setList(list);
497 setModelSorting(QCompleter::CaseSensitivelySortedModel);
499 setModelSorting(QCompleter::UnsortedModel);
502 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
503 if (newPrefix != completionPrefix())
504 setCompletionPrefix(newPrefix);
510 // restore old selection
511 setCurrentCompletion(old);
513 // if popup is not empty, the new selection will
514 // be our last valid one
515 if (popupVisible() || inlineVisible()) {
516 QString const & s = currentCompletion();
520 last_selection_ = old;
523 // show inline completion
525 updateInline(cur, currentCompletion());
529 void GuiCompleter::showPopup(Cursor const & cur)
531 if (!popupPossible(cur))
534 updateModel(cur, true, inlineVisible());
538 void GuiCompleter::asyncHidePopup()
541 // do not clear model if it has been set by an event before the
542 // timeout got triggered.
543 if (!modelActive_ && !inlineVisible())
548 void GuiCompleter::showInline(Cursor const & cur)
550 if (!inlinePossible(cur))
553 updateModel(cur, popupVisible(), true);
557 void GuiCompleter::hideInline(Cursor const & cur)
559 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
560 inlineVisible_ = false;
562 if (inline_timer_.isActive())
563 inline_timer_.stop();
565 // Trigger asynchronous part of hideInline. We might be
566 // in a dispatcher here and the setModel call might
567 // trigger focus events which is are not healthy here.
568 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
570 // mark that the asynchronous part will reset the model
572 modelActive_ = false;
576 void GuiCompleter::asyncHideInline()
578 // do not clear model if it has been set by an event before the
579 // timeout got triggered.
580 if (!modelActive_ && !popupVisible())
585 void GuiCompleter::showPopup()
587 Cursor cur = gui_->bufferView().cursor();
588 cur.screenUpdateFlags(Update::None);
593 if (cur.result().screenUpdate())
594 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
598 void GuiCompleter::showInline()
600 Cursor cur = gui_->bufferView().cursor();
601 cur.screenUpdateFlags(Update::None);
606 if (cur.result().screenUpdate())
607 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
611 void GuiCompleter::hidePopup()
613 popupVisible_ = false;
615 if (popup_timer_.isActive())
618 // hide popup asynchronously because we might be here inside of
619 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
620 // workarea which then redisplays the cursor. But the metrics are not
621 // yet up to date such that the coord cache has not all insets yet. The
622 // cursorPos methods would triggers asserts in the coord cache then.
623 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
625 // mark that the asynchronous part will reset the model
626 if (!inlineVisible())
627 modelActive_ = false;
631 void GuiCompleter::hideInline()
633 Cursor cur = gui_->bufferView().cursor();
634 cur.screenUpdateFlags(Update::None);
639 if (cur.result().screenUpdate())
640 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
644 void GuiCompleter::activate()
646 if (!popupVisible() && !inlineVisible())
649 popupActivated(currentCompletion());
653 void GuiCompleter::tab()
655 BufferView * bv = &gui_->bufferView();
656 Cursor cur = bv->cursor();
657 cur.screenUpdateFlags(Update::None);
659 // check that inline completion is active
660 if (!inlineVisible() && !uniqueCompletionAvailable()) {
661 // try to activate the inline completion
662 if (cur.inset().inlineCompletionSupported(cur)) {
665 // show popup without delay because the completion was not unique
666 if (lyxrc.completion_popup_after_complete
668 && popup()->model()->rowCount() > 1)
669 popup_timer_.start(0);
674 if (!popupVisible() && cur.inset().completionSupported(cur)) {
682 // Make undo possible
683 cur.beginUndoGroup();
686 // If completion is active, at least complete by one character
687 docstring prefix = cur.inset().completionPrefix(cur);
688 docstring completion = qstring_to_ucs4(currentCompletion());
689 if (completion.size() <= prefix.size()) {
690 // finalize completion
691 cur.inset().insertCompletion(cur, docstring(), true);
693 // hide popup and inline completion
696 updateVisibility(false, false);
700 docstring nextchar = completion.substr(prefix.size(), 1);
701 if (!cur.inset().insertCompletion(cur, nextchar, false)) {
707 // try to complete as far as it is unique
708 docstring longestCompletion = longestUniqueCompletion();
709 prefix = cur.inset().completionPrefix(cur);
710 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
711 cur.inset().insertCompletion(cur, postfix, false);
712 old_cursor_ = bv->cursor();
715 // show popup without delay because the completion was not unique
716 if (lyxrc.completion_popup_after_complete
718 && popup()->model()->rowCount() > 1)
719 popup_timer_.start(0);
722 if (cur.result().screenUpdate())
723 gui_->bufferView().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 if (cur.result().screenUpdate())
892 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
897 void GuiCompleter::popupHighlighted(const QString & completion)
902 Cursor cur = gui_->bufferView().cursor();
903 cur.screenUpdateFlags(Update::None);
906 updateInline(cur, completion);
908 if (cur.result().screenUpdate())
909 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
912 } // namespace frontend
915 #include "moc_GuiCompleter.cpp"