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
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
115 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
119 return list_->size();
123 QVariant data(const QModelIndex & index, int role) const
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 if (cur.result().screenUpdate())
352 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
356 void GuiCompleter::updatePrefix(Cursor const & cur)
358 // get new prefix. Do nothing if unchanged
359 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
360 if (newPrefix == completionPrefix())
363 // value which should be kept selected
364 QString old = currentCompletion();
365 if (old.length() == 0)
366 old = last_selection_;
368 // update completer to new prefix
369 setCompletionPrefix(newPrefix);
371 // update popup because its size might have changed
375 // restore old selection
376 setCurrentCompletion(old);
378 // if popup is not empty, the new selection will
379 // be our last valid one
380 QString const & s = currentCompletion();
381 if (popupVisible() || inlineVisible()) {
385 last_selection_ = old;
388 // update inline completion because the default
389 // completion string might have changed
391 updateInline(cur, s);
395 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
397 if (!cur.inset().inlineCompletionSupported(cur))
401 docstring prefix = cur.inset().completionPrefix(cur);
402 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
404 // shorten it if necessary
405 if (lyxrc.completion_inline_dots != -1)
406 support::truncateWithEllipsis(postfix,
407 unsigned(lyxrc.completion_inline_dots));
409 // set inline completion at cursor position
410 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
411 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
412 inlineVisible_ = true;
416 void GuiCompleter::updatePopup(Cursor const & cur)
418 if (!cur.inset().completionSupported(cur))
421 popupVisible_ = true;
423 if (completionCount() == 0) {
424 QTimer::singleShot(0, popup(), SLOT(hide()));
428 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
432 void GuiCompleter::asyncUpdatePopup()
434 Cursor cur = gui_->bufferView().cursor();
435 if (!cur.inset().completionSupported(cur)
436 || !cur.bv().paragraphVisible(cur)) {
437 popupVisible_ = false;
441 // get dimensions of completion prefix
445 cur.inset().completionPosAndDim(cur, x, y, dim);
447 // and calculate the rect of the popup
449 if (popup()->layoutDirection() == Qt::RightToLeft)
450 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
452 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
454 // Resize the columns in the popup.
455 // This should really be in the constructor. But somehow the treeview
456 // has a bad memory about it and we have to tell him again and again.
457 QTreeView * listView = static_cast<QTreeView *>(popup());
458 listView->header()->setStretchLastSection(false);
459 setSectionResizeMode(listView->header(), 0, QHeaderView::Stretch);
460 setSectionResizeMode(listView->header(), 1, QHeaderView::Fixed);
461 listView->header()->resizeSection(1, 22);
468 void GuiCompleter::updateAvailability()
470 // this should really only be of interest if no completion is
471 // visible yet, i.e. especially if automatic completion is disabled.
472 if (inlineVisible() || popupVisible())
474 Cursor const & cur = gui_->bufferView().cursor();
475 if (!popupPossible(cur) && !inlinePossible(cur))
478 updateModel(cur, false, false);
482 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
484 // value which should be kept selected
485 QString old = currentCompletion();
486 if (old.length() == 0)
487 old = last_selection_;
491 if (cur.inTexted()) {
492 Paragraph const & par = cur.paragraph();
494 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
495 rtl = font.isVisibleRightToLeft();
497 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
500 CompletionList const * list = cur.inset().createCompletionList(cur);
501 model_->setList(list);
504 setModelSorting(QCompleter::CaseSensitivelySortedModel);
506 setModelSorting(QCompleter::UnsortedModel);
509 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
510 if (newPrefix != completionPrefix())
511 setCompletionPrefix(newPrefix);
517 // restore old selection
518 setCurrentCompletion(old);
520 // if popup is not empty, the new selection will
521 // be our last valid one
522 if (popupVisible() || inlineVisible()) {
523 QString const & s = currentCompletion();
527 last_selection_ = old;
530 // show inline completion
532 updateInline(cur, currentCompletion());
536 void GuiCompleter::showPopup(Cursor const & cur)
538 if (!popupPossible(cur))
541 updateModel(cur, true, inlineVisible());
545 void GuiCompleter::asyncHidePopup()
548 // do not clear model if it has been set by an event before the
549 // timeout got triggered.
550 if (!modelActive_ && !inlineVisible())
555 void GuiCompleter::showInline(Cursor const & cur)
557 if (!inlinePossible(cur))
560 updateModel(cur, popupVisible(), true);
564 void GuiCompleter::hideInline(Cursor const & cur)
566 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
567 inlineVisible_ = false;
569 if (inline_timer_.isActive())
570 inline_timer_.stop();
572 // Trigger asynchronous part of hideInline. We might be
573 // in a dispatcher here and the setModel call might
574 // trigger focus events which is are not healthy here.
575 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
577 // mark that the asynchronous part will reset the model
579 modelActive_ = false;
583 void GuiCompleter::asyncHideInline()
585 // do not clear model if it has been set by an event before the
586 // timeout got triggered.
587 if (!modelActive_ && !popupVisible())
592 void GuiCompleter::showPopup()
594 Cursor cur = gui_->bufferView().cursor();
595 cur.screenUpdateFlags(Update::None);
600 if (cur.result().screenUpdate())
601 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
605 void GuiCompleter::showInline()
607 Cursor cur = gui_->bufferView().cursor();
608 cur.screenUpdateFlags(Update::None);
613 if (cur.result().screenUpdate())
614 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
618 void GuiCompleter::hidePopup()
620 popupVisible_ = false;
622 if (popup_timer_.isActive())
625 // hide popup asynchronously because we might be here inside of
626 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
627 // workarea which then redisplays the cursor. But the metrics are not
628 // yet up to date such that the coord cache has not all insets yet. The
629 // cursorPos methods would triggers asserts in the coord cache then.
630 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
632 // mark that the asynchronous part will reset the model
633 if (!inlineVisible())
634 modelActive_ = false;
638 void GuiCompleter::hideInline()
640 Cursor cur = gui_->bufferView().cursor();
641 cur.screenUpdateFlags(Update::None);
646 if (cur.result().screenUpdate())
647 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
651 void GuiCompleter::activate()
653 if (!popupVisible() && !inlineVisible())
656 popupActivated(currentCompletion());
660 void GuiCompleter::tab()
662 BufferView * bv = &gui_->bufferView();
663 Cursor cur = bv->cursor();
664 cur.screenUpdateFlags(Update::None);
666 // check that inline completion is active
667 if (!inlineVisible() && !uniqueCompletionAvailable()) {
668 // try to activate the inline completion
669 if (cur.inset().inlineCompletionSupported(cur)) {
672 // show popup without delay because the completion was not unique
673 if (lyxrc.completion_popup_after_complete
675 && popup()->model()->rowCount() > 1)
676 popup_timer_.start(0);
681 if (!popupVisible() && cur.inset().completionSupported(cur)) {
689 // Make undo possible
693 // If completion is active, at least complete by one character
694 docstring prefix = cur.inset().completionPrefix(cur);
695 docstring completion = qstring_to_ucs4(currentCompletion());
696 if (completion.size() <= prefix.size()) {
697 // finalize completion
698 cur.inset().insertCompletion(cur, docstring(), true);
700 // hide popup and inline completion
703 updateVisibility(false, false);
706 docstring nextchar = completion.substr(prefix.size(), 1);
707 if (!cur.inset().insertCompletion(cur, nextchar, false))
711 // try to complete as far as it is unique
712 docstring longestCompletion = longestUniqueCompletion();
713 prefix = cur.inset().completionPrefix(cur);
714 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
715 cur.inset().insertCompletion(cur, postfix, false);
716 old_cursor_ = bv->cursor();
719 // show popup without delay because the completion was not unique
720 if (lyxrc.completion_popup_after_complete
722 && popup()->model()->rowCount() > 1)
723 popup_timer_.start(0);
726 if (cur.result().screenUpdate())
727 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
731 QString GuiCompleter::currentCompletion() const
733 if (!popup()->selectionModel()->hasSelection())
736 // Not sure if this is bug in Qt: currentIndex() always
737 // return the first element in the list.
738 QModelIndex idx = popup()->currentIndex();
739 return popup()->model()->data(idx, Qt::EditRole).toString();
743 void GuiCompleter::setCurrentCompletion(QString const & s)
745 QAbstractItemModel const & model = *popup()->model();
746 size_t n = model.rowCount();
750 // select the first if s is empty
751 if (s.length() == 0) {
753 popup()->setCurrentIndex(model.index(0, 0));
758 // find old selection in model
760 if (modelSorting() == QCompleter::UnsortedModel) {
761 // In unsorted models, iterate through list until the s is found
762 for (i = 0; i < n; ++i) {
764 = model.data(model.index(i, 0), Qt::EditRole).toString();
769 // In sorted models, do binary search for s.
772 while (r >= l && l < int(n)) {
773 size_t mid = (r + l) / 2;
775 = model.data(model.index(mid, 0),
776 Qt::EditRole).toString();
779 // FIXME: is this really the same order that the docstring
780 // from the CompletionList has?
781 int c = s.compare(mids, Qt::CaseSensitive);
789 // middle is not far enough
796 // loop was left without finding anything
801 // we can try to recover
802 LASSERT(i <= n, i = 0);
805 // select the first if none was found
810 popup()->setCurrentIndex(model.index(i, 0));
815 size_t commonPrefix(QString const & s1, QString const & s2)
817 // find common prefix
819 size_t n1 = s1.length();
820 size_t n2 = s2.length();
821 for (j = 0; j < n1 && j < n2; ++j) {
822 if (s1.at(j) != s2.at(j))
829 docstring GuiCompleter::longestUniqueCompletion() const
831 QAbstractItemModel const & model = *popup()->model();
832 size_t n = model.rowCount();
835 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
837 if (modelSorting() == QCompleter::UnsortedModel) {
838 // For unsorted model we cannot do more than iteration.
839 // Iterate through the completions and cut off where s differs
840 for (size_t i = 0; i < n && s.length() > 0; ++i) {
842 = model.data(model.index(i, 0), Qt::EditRole).toString();
844 s = s.left(commonPrefix(is, s));
847 // For sorted models we can do binary search multiple times,
848 // each time to find the first string which has s not as prefix.
850 while (i < n && s.length() > 0) {
851 // find first string that does not have s as prefix
852 // via binary search in [i,n-1]
855 // get common prefix with the middle string
856 size_t mid = (r + i) / 2;
858 = model.data(model.index(mid, 0),
859 Qt::EditRole).toString();
860 size_t oldLen = s.length();
861 size_t len = commonPrefix(mids, s);
866 // middle is not far enough
869 // middle is maybe too far
872 } while (r - i > 0 && i < n);
876 return qstring_to_ucs4(s);
880 void GuiCompleter::popupActivated(const QString & completion)
882 Cursor cur = gui_->bufferView().cursor();
883 cur.screenUpdateFlags(Update::None);
885 cur.beginUndoGroup();
888 docstring prefix = cur.inset().completionPrefix(cur);
889 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
890 cur.inset().insertCompletion(cur, postfix, true);
894 if (cur.result().screenUpdate())
895 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
900 void GuiCompleter::popupHighlighted(const QString & completion)
905 Cursor cur = gui_->bufferView().cursor();
906 cur.screenUpdateFlags(Update::None);
909 updateInline(cur, completion);
911 if (cur.result().screenUpdate())
912 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
915 } // namespace frontend
918 #include "moc_GuiCompleter.cpp"