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 "FuncRequest.h"
21 #include "GuiWorkArea.h"
25 #include "Paragraph.h"
28 #include "support/lassert.h"
29 #include "support/debug.h"
31 #include <QApplication>
32 #include <QHeaderView>
34 #include <QPixmapCache>
36 #include <QItemDelegate>
41 using namespace lyx::support;
46 class RtlItemDelegate : public QItemDelegate
49 explicit RtlItemDelegate(QObject * parent)
50 : QItemDelegate(parent), enabled_(false)
53 void setEnabled(bool enabled = true)
59 void drawDisplay(QPainter * painter,
60 QStyleOptionViewItem const & option,
61 QRect const & rect, QString const & text) const
64 QItemDelegate::drawDisplay(painter, option, rect, text);
68 // FIXME: do this more elegantly
69 docstring stltext = qstring_to_ucs4(text);
70 reverse(stltext.begin(), stltext.end());
71 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
79 class PixmapItemDelegate : public QItemDelegate
82 explicit PixmapItemDelegate(QObject * parent)
83 : QItemDelegate(parent)
87 void paint(QPainter *painter, const QStyleOptionViewItem &option,
88 const QModelIndex &index) const
90 QStyleOptionViewItem opt = setOptions(index, option);
91 QVariant value = index.data(Qt::DisplayRole);
92 QPixmap pixmap = qvariant_cast<QPixmap>(value);
96 drawBackground(painter, opt, index);
97 if (!pixmap.isNull()) {
98 const QSize size = pixmap.size();
99 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
100 option.rect.top() + (option.rect.height() - size.height()) / 2,
103 drawFocus(painter, opt, option.rect);
109 class GuiCompletionModel : public QAbstractListModel
113 GuiCompletionModel(QObject * parent, CompletionList const * l)
114 : QAbstractListModel(parent), list_(l)
117 ~GuiCompletionModel() { delete list_; }
122 return list_->sorted();
126 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
131 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
136 return list_->size();
140 QVariant data(const QModelIndex & index, int role) const
145 if (index.row() < 0 || index.row() >= rowCount())
148 if (role != Qt::DisplayRole && role != Qt::EditRole)
151 if (index.column() == 0)
152 return toqstr(list_->data(index.row()));
154 if (index.column() == 1) {
155 // get icon from cache
157 QString const name = ":" + toqstr(list_->icon(index.row()));
158 if (!QPixmapCache::find("completion" + name, scaled)) {
159 // load icon from disk
160 QPixmap p = QPixmap(name);
162 // scale it to 16x16 or smaller
163 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
164 Qt::KeepAspectRatio, Qt::SmoothTransformation);
167 QPixmapCache::insert("completion" + name, scaled);
176 CompletionList const * list_;
180 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
181 : QCompleter(parent), gui_(gui), updateLock_(0),
182 inlineVisible_(false), popupVisible_(false),
185 // Setup the completion popup
186 setModel(new GuiCompletionModel(this, 0));
187 setCompletionMode(QCompleter::PopupCompletion);
191 QTreeView *listView = new QTreeView;
192 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
193 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
194 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
195 listView->setSelectionMode(QAbstractItemView::SingleSelection);
196 listView->header()->hide();
197 listView->setIndentation(0);
198 listView->setUniformRowHeights(true);
201 rtlItemDelegate_ = new RtlItemDelegate(this);
202 popup()->setItemDelegateForColumn(0, rtlItemDelegate_);
203 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
205 // create timeout timers
206 popup_timer_.setSingleShot(true);
207 inline_timer_.setSingleShot(true);
208 connect(this, SIGNAL(highlighted(const QString &)),
209 this, SLOT(popupHighlighted(const QString &)));
210 connect(this, SIGNAL(activated(const QString &)),
211 this, SLOT(popupActivated(const QString &)));
212 connect(&popup_timer_, SIGNAL(timeout()),
213 this, SLOT(showPopup()));
214 connect(&inline_timer_, SIGNAL(timeout()),
215 this, SLOT(showInline()));
219 GuiCompleter::~GuiCompleter()
225 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
227 // hijack back the tab key from the popup
228 // (which stole it from the workspace before)
229 if (e->type() == QEvent::KeyPress && popupVisible()) {
230 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
240 return QCompleter::eventFilter(watched, e);
244 bool GuiCompleter::popupPossible(Cursor const & cur) const
246 return QApplication::activeWindow()
248 && cur.inset().completionSupported(cur);
252 bool GuiCompleter::inlinePossible(Cursor const & cur) const
254 return cur.inset().inlineCompletionSupported(cur);
258 bool GuiCompleter::completionAvailable() const
263 size_t n = popup()->model()->rowCount();
265 // if there is exactly one, we have to check whether it is a
266 // real completion, i.e. longer than the current prefix.
267 if (n == 1 && completionPrefix() == currentCompletion())
274 bool GuiCompleter::popupVisible() const
276 return popupVisible_;
280 bool GuiCompleter::inlineVisible() const
282 // In fact using BufferView::inlineCompletionPos.empty() should be
283 // here. But unfortunately this information is not good enough
284 // because destructive operations like backspace might invalidate
285 // inlineCompletionPos. But then the completion should stay visible
286 // (i.e. reshown on the next update). Hence be keep this information
287 // in the inlineVisible_ variable.
288 return inlineVisible_;
292 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
294 // parameters which affect the completion
295 bool moved = cur != old_cursor_;
299 bool possiblePopupState = popupPossible(cur) && cursorInView;
300 bool possibleInlineState = inlinePossible(cur) && cursorInView;
302 // we moved or popup state is not ok for popup?
303 if ((moved && !keep) || !possiblePopupState)
306 // we moved or inline state is not ok for inline completion?
307 if ((moved && !keep) || !possibleInlineState)
310 // we inserted something and are in a possible popup state?
311 if (!popupVisible() && possiblePopupState && start
312 && cur.inset().automaticPopupCompletion())
313 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
315 // we inserted something and are in a possible inline completion state?
316 if (!inlineVisible() && possibleInlineState && start
317 && cur.inset().automaticInlineCompletion())
318 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
320 // update prefix if any completion is possible
321 bool modelActive = modelActive_ && model()->rowCount() > 0;
322 if (possiblePopupState || possibleInlineState) {
326 updateAvailability();
331 void GuiCompleter::updateVisibility(bool start, bool keep)
333 Cursor cur = gui_->bufferView().cursor();
334 cur.updateFlags(Update::None);
336 updateVisibility(cur, start, keep);
338 if (cur.disp_.update())
339 gui_->bufferView().processUpdateFlags(cur.disp_.update());
343 void GuiCompleter::updatePrefix(Cursor & cur)
345 // get new prefix. Do nothing if unchanged
346 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
347 if (newPrefix == completionPrefix())
350 // value which should be kept selected
351 QString old = currentCompletion();
352 if (old.length() == 0)
353 old = last_selection_;
355 // update completer to new prefix
356 setCompletionPrefix(newPrefix);
358 // update popup because its size might have changed
362 // restore old selection
363 setCurrentCompletion(old);
365 // if popup is not empty, the new selection will
366 // be our last valid one
367 QString const & s = currentCompletion();
368 if (popupVisible() || inlineVisible()) {
372 last_selection_ = old;
375 // update inline completion because the default
376 // completion string might have changed
378 updateInline(cur, s);
382 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
384 if (!cur.inset().inlineCompletionSupported(cur))
388 docstring prefix = cur.inset().completionPrefix(cur);
389 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
391 // shorten it if necessary
392 if (lyxrc.completion_inline_dots != -1
393 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
394 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
396 // set inline completion at cursor position
397 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
398 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
399 inlineVisible_ = true;
403 void GuiCompleter::updatePopup(Cursor & cur)
405 if (!cur.inset().completionSupported(cur))
408 popupVisible_ = true;
410 if (completionCount() == 0) {
411 QTimer::singleShot(0, popup(), SLOT(hide()));
415 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
419 void GuiCompleter::asyncUpdatePopup()
421 Cursor cur = gui_->bufferView().cursor();
422 if (!cur.inset().completionSupported(cur)) {
423 popupVisible_ = false;
427 // get dimensions of completion prefix
431 cur.inset().completionPosAndDim(cur, x, y, dim);
433 // and calculate the rect of the popup
435 if (popup()->layoutDirection() == Qt::RightToLeft)
436 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
438 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
440 // Resize the columns in the popup.
441 // This should really be in the constructor. But somehow the treeview
442 // has a bad memory about it and we have to tell him again and again.
443 QTreeView * listView = static_cast<QTreeView *>(popup());
444 listView->header()->setStretchLastSection(false);
445 listView->header()->setResizeMode(0, QHeaderView::Stretch);
446 listView->header()->setResizeMode(1, QHeaderView::Fixed);
447 listView->header()->resizeSection(1, 22);
454 void GuiCompleter::updateAvailability()
456 // this should really only be of interest if no completion is
457 // visible yet, i.e. especially if automatic completion is disabled.
458 if (inlineVisible() || popupVisible())
460 Cursor & cur = gui_->bufferView().cursor();
461 if (!popupPossible(cur) && !inlinePossible(cur))
464 updateModel(cur, false, false);
468 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
470 // value which should be kept selected
471 QString old = currentCompletion();
472 if (old.length() == 0)
473 old = last_selection_;
477 if (cur.inTexted()) {
478 Paragraph const & par = cur.paragraph();
480 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
481 rtl = font.isVisibleRightToLeft();
483 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
485 // turn the direction of the strings in the popup.
486 // Qt does not do that itself.
487 rtlItemDelegate_->setEnabled(rtl);
490 CompletionList const * list = cur.inset().createCompletionList(cur);
491 setModel(new GuiCompletionModel(this, list));
494 setModelSorting(QCompleter::CaseSensitivelySortedModel);
496 setModelSorting(QCompleter::UnsortedModel);
499 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
500 if (newPrefix != completionPrefix())
501 setCompletionPrefix(newPrefix);
507 // restore old selection
508 setCurrentCompletion(old);
510 // if popup is not empty, the new selection will
511 // be our last valid one
512 if (popupVisible() || inlineVisible()) {
513 QString const & s = currentCompletion();
517 last_selection_ = old;
520 // show inline completion
522 updateInline(cur, currentCompletion());
526 void GuiCompleter::showPopup(Cursor & cur)
528 if (!popupPossible(cur))
531 updateModel(cur, true, inlineVisible());
535 void GuiCompleter::hidePopup(Cursor &)
537 popupVisible_ = false;
539 if (popup_timer_.isActive())
542 // hide popup asynchronously because we might be here inside of
543 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
544 // workarea which then redisplays the cursor. But the metrics are not
545 // yet up to date such that the coord cache has not all insets yet. The
546 // cursorPos methods would triggers asserts in the coord cache then.
547 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
549 // mark that the asynchronous part will reset the model
550 if (!inlineVisible())
551 modelActive_ = false;
555 void GuiCompleter::asyncHidePopup()
558 if (!inlineVisible())
559 setModel(new GuiCompletionModel(this, 0));
563 void GuiCompleter::showInline(Cursor & cur)
565 if (!inlinePossible(cur))
568 updateModel(cur, popupVisible(), true);
572 void GuiCompleter::hideInline(Cursor & cur)
574 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
575 inlineVisible_ = false;
577 if (inline_timer_.isActive())
578 inline_timer_.stop();
580 // Trigger asynchronous part of hideInline. We might be
581 // in a dispatcher here and the setModel call might
582 // trigger focus events which is are not healthy here.
583 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
585 // mark that the asynchronous part will reset the model
587 modelActive_ = false;
591 void GuiCompleter::asyncHideInline()
594 setModel(new GuiCompletionModel(this, 0));
598 void GuiCompleter::showPopup()
600 Cursor cur = gui_->bufferView().cursor();
601 cur.updateFlags(Update::None);
606 if (cur.disp_.update())
607 gui_->bufferView().processUpdateFlags(cur.disp_.update());
611 void GuiCompleter::showInline()
613 Cursor cur = gui_->bufferView().cursor();
614 cur.updateFlags(Update::None);
619 if (cur.disp_.update())
620 gui_->bufferView().processUpdateFlags(cur.disp_.update());
624 void GuiCompleter::hidePopup()
626 Cursor cur = gui_->bufferView().cursor();
627 cur.updateFlags(Update::None);
632 if (cur.disp_.update())
633 gui_->bufferView().processUpdateFlags(cur.disp_.update());
637 void GuiCompleter::hideInline()
639 Cursor cur = gui_->bufferView().cursor();
640 cur.updateFlags(Update::None);
645 if (cur.disp_.update())
646 gui_->bufferView().processUpdateFlags(cur.disp_.update());
650 void GuiCompleter::activate()
652 if (!popupVisible() && !inlineVisible())
655 popupActivated(currentCompletion());
659 void GuiCompleter::tab()
661 BufferView * bv = &gui_->bufferView();
662 Cursor cur = bv->cursor();
663 cur.updateFlags(Update::None);
665 // check that inline completion is active
666 if (!inlineVisible()) {
667 // try to activate the inline completion
668 if (cur.inset().inlineCompletionSupported(cur)) {
671 // show popup without delay because the completion was not unique
672 if (lyxrc.completion_popup_after_complete
674 && popup()->model()->rowCount() > 1)
675 popup_timer_.start(0);
680 if (!popupVisible() && cur.inset().completionSupported(cur)) {
688 // If completion is active, at least complete by one character
689 docstring prefix = cur.inset().completionPrefix(cur);
690 docstring completion = qstring_to_ucs4(currentCompletion());
691 if (completion.size() <= prefix.size()) {
692 // finalize completion
693 cur.inset().insertCompletion(cur, docstring(), true);
695 // hide popup and inline completion
698 updateVisibility(false, false);
701 docstring nextchar = completion.substr(prefix.size(), 1);
702 if (!cur.inset().insertCompletion(cur, nextchar, false))
706 // try to complete as far as it is unique
707 docstring longestCompletion = longestUniqueCompletion();
708 prefix = cur.inset().completionPrefix(cur);
709 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
710 cur.inset().insertCompletion(cur, postfix, false);
711 old_cursor_ = bv->cursor();
714 // show popup without delay because the completion was not unique
715 if (lyxrc.completion_popup_after_complete
717 && popup()->model()->rowCount() > 1)
718 popup_timer_.start(0);
721 if (cur.disp_.update())
722 gui_->bufferView().processUpdateFlags(cur.disp_.update());
726 QString GuiCompleter::currentCompletion() const
728 if (!popup()->selectionModel()->hasSelection())
731 // Not sure if this is bug in Qt: currentIndex() always
732 // return the first element in the list.
733 QModelIndex idx = popup()->currentIndex();
734 return popup()->model()->data(idx, Qt::EditRole).toString();
738 void GuiCompleter::setCurrentCompletion(QString const & s)
740 QAbstractItemModel const & model = *popup()->model();
741 size_t n = model.rowCount();
745 // select the first if s is empty
746 if (s.length() == 0) {
748 popup()->setCurrentIndex(model.index(0, 0));
753 // find old selection in model
755 if (modelSorting() == QCompleter::UnsortedModel) {
756 // In unsorted models, iterate through list until the s is found
757 for (i = 0; i < n; ++i) {
759 = model.data(model.index(i, 0), Qt::EditRole).toString();
764 // In sorted models, do binary search for s.
767 while (r >= l && l < int(n)) {
768 size_t mid = (r + l) / 2;
770 = model.data(model.index(mid, 0),
771 Qt::EditRole).toString();
774 // FIXME: is this really the same order that the docstring
775 // from the CompletionList has?
776 int c = s.compare(mids, Qt::CaseSensitive);
784 // middle is not far enough
791 // loop was left without finding anything
796 LASSERT(i <= n, /**/);
799 // select the first if none was found
804 popup()->setCurrentIndex(model.index(i, 0));
809 size_t commonPrefix(QString const & s1, QString const & s2)
811 // find common prefix
813 size_t n1 = s1.length();
814 size_t n2 = s2.length();
815 for (j = 0; j < n1 && j < n2; ++j) {
816 if (s1.at(j) != s2.at(j))
823 docstring GuiCompleter::longestUniqueCompletion() const
825 QAbstractItemModel const & model = *popup()->model();
826 size_t n = model.rowCount();
829 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
831 if (modelSorting() == QCompleter::UnsortedModel) {
832 // For unsorted model we cannot do more than iteration.
833 // Iterate through the completions and cut off where s differs
834 for (size_t i = 0; i < n && s.length() > 0; ++i) {
836 = model.data(model.index(i, 0), Qt::EditRole).toString();
838 s = s.left(commonPrefix(is, s));
841 // For sorted models we can do binary search multiple times,
842 // each time to find the first string which has s not as prefix.
844 while (i < n && s.length() > 0) {
845 // find first string that does not have s as prefix
846 // via binary search in [i,n-1]
849 // get common prefix with the middle string
850 size_t mid = (r + i) / 2;
852 = model.data(model.index(mid, 0),
853 Qt::EditRole).toString();
854 size_t oldLen = s.length();
855 size_t len = commonPrefix(mids, s);
860 // middle is not far enough
863 // middle is maybe too far
866 } while (r - i > 0 && i < n);
870 return qstring_to_ucs4(s);
874 void GuiCompleter::popupActivated(const QString & completion)
876 Cursor cur = gui_->bufferView().cursor();
877 cur.updateFlags(Update::None);
879 docstring prefix = cur.inset().completionPrefix(cur);
880 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
881 cur.inset().insertCompletion(cur, postfix, true);
885 if (cur.disp_.update())
886 gui_->bufferView().processUpdateFlags(cur.disp_.update());
890 void GuiCompleter::popupHighlighted(const QString & completion)
895 Cursor cur = gui_->bufferView().cursor();
896 cur.updateFlags(Update::None);
899 updateInline(cur, completion);
901 if (cur.disp_.update())
902 gui_->bufferView().processUpdateFlags(cur.disp_.update());
905 } // namespace frontend
908 #include "GuiCompleter_moc.cpp"