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 if (!inlineVisible())
546 void GuiCompleter::showInline(Cursor const & cur)
548 if (!inlinePossible(cur))
551 updateModel(cur, popupVisible(), true);
555 void GuiCompleter::hideInline(Cursor const & cur)
557 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
558 inlineVisible_ = false;
560 if (inline_timer_.isActive())
561 inline_timer_.stop();
563 // Trigger asynchronous part of hideInline. We might be
564 // in a dispatcher here and the setModel call might
565 // trigger focus events which is are not healthy here.
566 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
568 // mark that the asynchronous part will reset the model
570 modelActive_ = false;
574 void GuiCompleter::asyncHideInline()
581 void GuiCompleter::showPopup()
583 Cursor cur = gui_->bufferView().cursor();
584 cur.screenUpdateFlags(Update::None);
589 if (cur.result().screenUpdate())
590 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
594 void GuiCompleter::showInline()
596 Cursor cur = gui_->bufferView().cursor();
597 cur.screenUpdateFlags(Update::None);
602 if (cur.result().screenUpdate())
603 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
607 void GuiCompleter::hidePopup()
609 popupVisible_ = false;
611 if (popup_timer_.isActive())
614 // hide popup asynchronously because we might be here inside of
615 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
616 // workarea which then redisplays the cursor. But the metrics are not
617 // yet up to date such that the coord cache has not all insets yet. The
618 // cursorPos methods would triggers asserts in the coord cache then.
619 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
621 // mark that the asynchronous part will reset the model
622 if (!inlineVisible())
623 modelActive_ = false;
627 void GuiCompleter::hideInline()
629 Cursor cur = gui_->bufferView().cursor();
630 cur.screenUpdateFlags(Update::None);
635 if (cur.result().screenUpdate())
636 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
640 void GuiCompleter::activate()
642 if (!popupVisible() && !inlineVisible())
645 popupActivated(currentCompletion());
649 void GuiCompleter::tab()
651 BufferView * bv = &gui_->bufferView();
652 Cursor cur = bv->cursor();
653 cur.screenUpdateFlags(Update::None);
655 // check that inline completion is active
656 if (!inlineVisible() && !uniqueCompletionAvailable()) {
657 // try to activate the inline completion
658 if (cur.inset().inlineCompletionSupported(cur)) {
661 // show popup without delay because the completion was not unique
662 if (lyxrc.completion_popup_after_complete
664 && popup()->model()->rowCount() > 1)
665 popup_timer_.start(0);
670 if (!popupVisible() && cur.inset().completionSupported(cur)) {
678 // Make undo possible
679 cur.beginUndoGroup();
682 // If completion is active, at least complete by one character
683 docstring prefix = cur.inset().completionPrefix(cur);
684 docstring completion = qstring_to_ucs4(currentCompletion());
685 if (completion.size() <= prefix.size()) {
686 // finalize completion
687 cur.inset().insertCompletion(cur, docstring(), true);
689 // hide popup and inline completion
692 updateVisibility(false, false);
696 docstring nextchar = completion.substr(prefix.size(), 1);
697 if (!cur.inset().insertCompletion(cur, nextchar, false)) {
703 // try to complete as far as it is unique
704 docstring longestCompletion = longestUniqueCompletion();
705 prefix = cur.inset().completionPrefix(cur);
706 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
707 cur.inset().insertCompletion(cur, postfix, false);
708 old_cursor_ = bv->cursor();
711 // show popup without delay because the completion was not unique
712 if (lyxrc.completion_popup_after_complete
714 && popup()->model()->rowCount() > 1)
715 popup_timer_.start(0);
718 if (cur.result().screenUpdate())
719 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
724 QString GuiCompleter::currentCompletion() const
726 if (!popup()->selectionModel()->hasSelection())
729 // Not sure if this is bug in Qt: currentIndex() always
730 // return the first element in the list.
731 QModelIndex idx = popup()->currentIndex();
732 return popup()->model()->data(idx, Qt::EditRole).toString();
736 void GuiCompleter::setCurrentCompletion(QString const & s)
738 QAbstractItemModel const & model = *popup()->model();
739 size_t n = model.rowCount();
743 // select the first if s is empty
744 if (s.length() == 0) {
746 popup()->setCurrentIndex(model.index(0, 0));
751 // find old selection in model
753 if (modelSorting() == QCompleter::UnsortedModel) {
754 // In unsorted models, iterate through list until the s is found
755 for (i = 0; i < n; ++i) {
757 = model.data(model.index(i, 0), Qt::EditRole).toString();
762 // In sorted models, do binary search for s.
765 while (r >= l && l < int(n)) {
766 size_t mid = (r + l) / 2;
768 = model.data(model.index(mid, 0),
769 Qt::EditRole).toString();
772 // FIXME: is this really the same order that the docstring
773 // from the CompletionList has?
774 int c = s.compare(mids, Qt::CaseSensitive);
782 // middle is not far enough
789 // loop was left without finding anything
794 // we can try to recover
795 LASSERT(i <= n, i = 0);
798 // select the first if none was found
803 popup()->setCurrentIndex(model.index(i, 0));
808 size_t commonPrefix(QString const & s1, QString const & s2)
810 // find common prefix
812 size_t n1 = s1.length();
813 size_t n2 = s2.length();
814 for (j = 0; j < n1 && j < n2; ++j) {
815 if (s1.at(j) != s2.at(j))
822 docstring GuiCompleter::longestUniqueCompletion() const
824 QAbstractItemModel const & model = *popup()->model();
825 size_t n = model.rowCount();
828 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
830 if (modelSorting() == QCompleter::UnsortedModel) {
831 // For unsorted model we cannot do more than iteration.
832 // Iterate through the completions and cut off where s differs
833 for (size_t i = 0; i < n && s.length() > 0; ++i) {
835 = model.data(model.index(i, 0), Qt::EditRole).toString();
837 s = s.left(commonPrefix(is, s));
840 // For sorted models we can do binary search multiple times,
841 // each time to find the first string which has s not as prefix.
843 while (i < n && s.length() > 0) {
844 // find first string that does not have s as prefix
845 // via binary search in [i,n-1]
848 // get common prefix with the middle string
849 size_t mid = (r + i) / 2;
851 = model.data(model.index(mid, 0),
852 Qt::EditRole).toString();
853 size_t oldLen = s.length();
854 size_t len = commonPrefix(mids, s);
859 // middle is not far enough
862 // middle is maybe too far
865 } while (r - i > 0 && i < n);
869 return qstring_to_ucs4(s);
873 void GuiCompleter::popupActivated(const QString & completion)
875 Cursor cur = gui_->bufferView().cursor();
876 cur.screenUpdateFlags(Update::None);
878 cur.beginUndoGroup();
881 docstring prefix = cur.inset().completionPrefix(cur);
882 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
883 cur.inset().insertCompletion(cur, postfix, true);
887 if (cur.result().screenUpdate())
888 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
893 void GuiCompleter::popupHighlighted(const QString & completion)
898 Cursor cur = gui_->bufferView().cursor();
899 cur.screenUpdateFlags(Update::None);
902 updateInline(cur, completion);
904 if (cur.result().screenUpdate())
905 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
908 } // namespace frontend
911 #include "moc_GuiCompleter.cpp"