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 CompleterItemDelegate : public QItemDelegate
49 explicit CompleterItemDelegate(QObject * parent)
50 : QItemDelegate(parent), enabled_(false)
53 ~CompleterItemDelegate()
56 void setEnabled(bool enabled = true)
62 void drawDisplay(QPainter * painter,
63 QStyleOptionViewItem const & option,
64 QRect const & rect, QString const & text) const
67 QItemDelegate::drawDisplay(painter, option, rect, text);
71 // FIXME: do this more elegantly
72 docstring stltext = qstring_to_ucs4(text);
73 reverse(stltext.begin(), stltext.end());
74 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
77 void paint(QPainter *painter, const QStyleOptionViewItem &option,
78 const QModelIndex &index) const
80 if (index.column() == 0) {
81 QItemDelegate::paint(painter, option, index);
84 QStyleOptionViewItem opt = setOptions(index, option);
85 QVariant value = index.data(Qt::DisplayRole);
86 QPixmap pixmap = qvariant_cast<QPixmap>(value);
90 drawBackground(painter, opt, index);
91 if (!pixmap.isNull()) {
92 const QSize size = pixmap.size();
93 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
94 option.rect.top() + (option.rect.height() - size.height()) / 2,
97 drawFocus(painter, opt, option.rect);
105 class GuiCompletionModel : public QAbstractListModel
109 GuiCompletionModel(QObject * parent, CompletionList const * l)
110 : QAbstractListModel(parent), list_(l)
113 ~GuiCompletionModel() { delete list_; }
115 void setList(CompletionList const * l) {
124 return list_->sorted();
128 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
133 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
138 return list_->size();
142 QVariant data(const QModelIndex & index, int role) const
147 if (index.row() < 0 || index.row() >= rowCount())
150 if (role != Qt::DisplayRole && role != Qt::EditRole)
153 if (index.column() == 0)
154 return toqstr(list_->data(index.row()));
156 if (index.column() == 1) {
157 // get icon from cache
159 QString const name = ":" + toqstr(list_->icon(index.row()));
160 if (!QPixmapCache::find("completion" + name, scaled)) {
161 // load icon from disk
162 QPixmap p = QPixmap(name);
164 // scale it to 16x16 or smaller
165 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
166 Qt::KeepAspectRatio, Qt::SmoothTransformation);
169 QPixmapCache::insert("completion" + name, scaled);
178 CompletionList const * list_;
182 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
183 : QCompleter(parent), gui_(gui), updateLock_(0),
184 inlineVisible_(false), popupVisible_(false),
187 // Setup the completion popup
188 model_ = new GuiCompletionModel(this, 0);
190 setCompletionMode(QCompleter::PopupCompletion);
194 QTreeView *listView = new QTreeView;
195 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
196 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
197 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
198 listView->setSelectionMode(QAbstractItemView::SingleSelection);
199 listView->header()->hide();
200 listView->setIndentation(0);
201 listView->setUniformRowHeights(true);
204 itemDelegate_ = new CompleterItemDelegate(this);
205 popup()->setItemDelegate(itemDelegate_);
207 // create timeout timers
208 popup_timer_.setSingleShot(true);
209 inline_timer_.setSingleShot(true);
210 connect(this, SIGNAL(highlighted(const QString &)),
211 this, SLOT(popupHighlighted(const QString &)));
212 connect(this, SIGNAL(activated(const QString &)),
213 this, SLOT(popupActivated(const QString &)));
214 connect(&popup_timer_, SIGNAL(timeout()),
215 this, SLOT(showPopup()));
216 connect(&inline_timer_, SIGNAL(timeout()),
217 this, SLOT(showInline()));
221 GuiCompleter::~GuiCompleter()
227 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
229 // hijack back the tab key from the popup
230 // (which stole it from the workspace before)
231 if (e->type() == QEvent::KeyPress && popupVisible()) {
232 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
242 return QCompleter::eventFilter(watched, e);
246 bool GuiCompleter::popupPossible(Cursor const & cur) const
248 return QApplication::activeWindow()
250 && cur.inset().completionSupported(cur);
254 bool GuiCompleter::inlinePossible(Cursor const & cur) const
256 return cur.inset().inlineCompletionSupported(cur);
260 bool GuiCompleter::completionAvailable() const
265 size_t n = popup()->model()->rowCount();
267 // if there is exactly one, we have to check whether it is a
268 // real completion, i.e. longer than the current prefix.
269 if (n == 1 && completionPrefix() == currentCompletion())
276 bool GuiCompleter::popupVisible() const
278 return popupVisible_;
282 bool GuiCompleter::inlineVisible() const
284 // In fact using BufferView::inlineCompletionPos.empty() should be
285 // here. But unfortunately this information is not good enough
286 // because destructive operations like backspace might invalidate
287 // inlineCompletionPos. But then the completion should stay visible
288 // (i.e. reshown on the next update). Hence be keep this information
289 // in the inlineVisible_ variable.
290 return inlineVisible_;
294 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
296 // parameters which affect the completion
297 bool moved = cur != old_cursor_;
301 bool possiblePopupState = popupPossible(cur) && cursorInView;
302 bool possibleInlineState = inlinePossible(cur) && cursorInView;
304 // we moved or popup state is not ok for popup?
305 if ((moved && !keep) || !possiblePopupState)
308 // we moved or inline state is not ok for inline completion?
309 if ((moved && !keep) || !possibleInlineState)
312 // we inserted something and are in a possible popup state?
313 if (!popupVisible() && possiblePopupState && start
314 && cur.inset().automaticPopupCompletion())
315 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
317 // we inserted something and are in a possible inline completion state?
318 if (!inlineVisible() && possibleInlineState && start
319 && cur.inset().automaticInlineCompletion())
320 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
322 // update prefix if any completion is possible
323 bool modelActive = modelActive_ && model()->rowCount() > 0;
324 if (possiblePopupState || possibleInlineState) {
328 updateAvailability();
333 void GuiCompleter::updateVisibility(bool start, bool keep)
335 Cursor cur = gui_->bufferView().cursor();
336 cur.updateFlags(Update::None);
338 updateVisibility(cur, start, keep);
340 if (cur.disp_.update())
341 gui_->bufferView().processUpdateFlags(cur.disp_.update());
345 void GuiCompleter::updatePrefix(Cursor & cur)
347 // get new prefix. Do nothing if unchanged
348 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
349 if (newPrefix == completionPrefix())
352 // value which should be kept selected
353 QString old = currentCompletion();
354 if (old.length() == 0)
355 old = last_selection_;
357 // update completer to new prefix
358 setCompletionPrefix(newPrefix);
360 // update popup because its size might have changed
364 // restore old selection
365 setCurrentCompletion(old);
367 // if popup is not empty, the new selection will
368 // be our last valid one
369 QString const & s = currentCompletion();
370 if (popupVisible() || inlineVisible()) {
374 last_selection_ = old;
377 // update inline completion because the default
378 // completion string might have changed
380 updateInline(cur, s);
384 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
386 if (!cur.inset().inlineCompletionSupported(cur))
390 docstring prefix = cur.inset().completionPrefix(cur);
391 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
393 // shorten it if necessary
394 if (lyxrc.completion_inline_dots != -1
395 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
396 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
398 // set inline completion at cursor position
399 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
400 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
401 inlineVisible_ = true;
405 void GuiCompleter::updatePopup(Cursor & cur)
407 if (!cur.inset().completionSupported(cur))
410 popupVisible_ = true;
412 if (completionCount() == 0) {
413 QTimer::singleShot(0, popup(), SLOT(hide()));
417 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
421 void GuiCompleter::asyncUpdatePopup()
423 Cursor cur = gui_->bufferView().cursor();
424 if (!cur.inset().completionSupported(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 & cur = gui_->bufferView().cursor();
463 if (!popupPossible(cur) && !inlinePossible(cur))
466 updateModel(cur, false, false);
470 void GuiCompleter::updateModel(Cursor & 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);
487 // turn the direction of the strings in the popup.
488 // Qt does not do that itself.
489 itemDelegate_->setEnabled(rtl);
492 CompletionList const * list = cur.inset().createCompletionList(cur);
493 model_->setList(list);
496 setModelSorting(QCompleter::CaseSensitivelySortedModel);
498 setModelSorting(QCompleter::UnsortedModel);
501 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
502 if (newPrefix != completionPrefix())
503 setCompletionPrefix(newPrefix);
509 // restore old selection
510 setCurrentCompletion(old);
512 // if popup is not empty, the new selection will
513 // be our last valid one
514 if (popupVisible() || inlineVisible()) {
515 QString const & s = currentCompletion();
519 last_selection_ = old;
522 // show inline completion
524 updateInline(cur, currentCompletion());
528 void GuiCompleter::showPopup(Cursor & cur)
530 if (!popupPossible(cur))
533 updateModel(cur, true, inlineVisible());
537 void GuiCompleter::hidePopup(Cursor &)
539 popupVisible_ = false;
541 if (popup_timer_.isActive())
544 // hide popup asynchronously because we might be here inside of
545 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
546 // workarea which then redisplays the cursor. But the metrics are not
547 // yet up to date such that the coord cache has not all insets yet. The
548 // cursorPos methods would triggers asserts in the coord cache then.
549 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
551 // mark that the asynchronous part will reset the model
552 if (!inlineVisible())
553 modelActive_ = false;
557 void GuiCompleter::asyncHidePopup()
560 if (!inlineVisible())
565 void GuiCompleter::showInline(Cursor & cur)
567 if (!inlinePossible(cur))
570 updateModel(cur, popupVisible(), true);
574 void GuiCompleter::hideInline(Cursor & cur)
576 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
577 inlineVisible_ = false;
579 if (inline_timer_.isActive())
580 inline_timer_.stop();
582 // Trigger asynchronous part of hideInline. We might be
583 // in a dispatcher here and the setModel call might
584 // trigger focus events which is are not healthy here.
585 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
587 // mark that the asynchronous part will reset the model
589 modelActive_ = false;
593 void GuiCompleter::asyncHideInline()
600 void GuiCompleter::showPopup()
602 Cursor cur = gui_->bufferView().cursor();
603 cur.updateFlags(Update::None);
608 if (cur.disp_.update())
609 gui_->bufferView().processUpdateFlags(cur.disp_.update());
613 void GuiCompleter::showInline()
615 Cursor cur = gui_->bufferView().cursor();
616 cur.updateFlags(Update::None);
621 if (cur.disp_.update())
622 gui_->bufferView().processUpdateFlags(cur.disp_.update());
626 void GuiCompleter::hidePopup()
628 Cursor cur = gui_->bufferView().cursor();
629 cur.updateFlags(Update::None);
634 if (cur.disp_.update())
635 gui_->bufferView().processUpdateFlags(cur.disp_.update());
639 void GuiCompleter::hideInline()
641 Cursor cur = gui_->bufferView().cursor();
642 cur.updateFlags(Update::None);
647 if (cur.disp_.update())
648 gui_->bufferView().processUpdateFlags(cur.disp_.update());
652 void GuiCompleter::activate()
654 if (!popupVisible() && !inlineVisible())
657 popupActivated(currentCompletion());
661 void GuiCompleter::tab()
663 BufferView * bv = &gui_->bufferView();
664 Cursor cur = bv->cursor();
665 cur.updateFlags(Update::None);
667 // check that inline completion is active
668 if (!inlineVisible()) {
669 // try to activate the inline completion
670 if (cur.inset().inlineCompletionSupported(cur)) {
673 // show popup without delay because the completion was not unique
674 if (lyxrc.completion_popup_after_complete
676 && popup()->model()->rowCount() > 1)
677 popup_timer_.start(0);
682 if (!popupVisible() && cur.inset().completionSupported(cur)) {
690 // If completion is active, at least complete by one character
691 docstring prefix = cur.inset().completionPrefix(cur);
692 docstring completion = qstring_to_ucs4(currentCompletion());
693 if (completion.size() <= prefix.size()) {
694 // finalize completion
695 cur.inset().insertCompletion(cur, docstring(), true);
697 // hide popup and inline completion
700 updateVisibility(false, false);
703 docstring nextchar = completion.substr(prefix.size(), 1);
704 if (!cur.inset().insertCompletion(cur, nextchar, false))
708 // try to complete as far as it is unique
709 docstring longestCompletion = longestUniqueCompletion();
710 prefix = cur.inset().completionPrefix(cur);
711 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
712 cur.inset().insertCompletion(cur, postfix, false);
713 old_cursor_ = bv->cursor();
716 // show popup without delay because the completion was not unique
717 if (lyxrc.completion_popup_after_complete
719 && popup()->model()->rowCount() > 1)
720 popup_timer_.start(0);
723 if (cur.disp_.update())
724 gui_->bufferView().processUpdateFlags(cur.disp_.update());
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 LASSERT(i <= n, /**/);
801 // select the first if none was found
806 popup()->setCurrentIndex(model.index(i, 0));
811 size_t commonPrefix(QString const & s1, QString const & s2)
813 // find common prefix
815 size_t n1 = s1.length();
816 size_t n2 = s2.length();
817 for (j = 0; j < n1 && j < n2; ++j) {
818 if (s1.at(j) != s2.at(j))
825 docstring GuiCompleter::longestUniqueCompletion() const
827 QAbstractItemModel const & model = *popup()->model();
828 size_t n = model.rowCount();
831 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
833 if (modelSorting() == QCompleter::UnsortedModel) {
834 // For unsorted model we cannot do more than iteration.
835 // Iterate through the completions and cut off where s differs
836 for (size_t i = 0; i < n && s.length() > 0; ++i) {
838 = model.data(model.index(i, 0), Qt::EditRole).toString();
840 s = s.left(commonPrefix(is, s));
843 // For sorted models we can do binary search multiple times,
844 // each time to find the first string which has s not as prefix.
846 while (i < n && s.length() > 0) {
847 // find first string that does not have s as prefix
848 // via binary search in [i,n-1]
851 // get common prefix with the middle string
852 size_t mid = (r + i) / 2;
854 = model.data(model.index(mid, 0),
855 Qt::EditRole).toString();
856 size_t oldLen = s.length();
857 size_t len = commonPrefix(mids, s);
862 // middle is not far enough
865 // middle is maybe too far
868 } while (r - i > 0 && i < n);
872 return qstring_to_ucs4(s);
876 void GuiCompleter::popupActivated(const QString & completion)
878 Cursor cur = gui_->bufferView().cursor();
879 cur.updateFlags(Update::None);
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.disp_.update())
888 gui_->bufferView().processUpdateFlags(cur.disp_.update());
892 void GuiCompleter::popupHighlighted(const QString & completion)
897 Cursor cur = gui_->bufferView().cursor();
898 cur.updateFlags(Update::None);
901 updateInline(cur, completion);
903 if (cur.disp_.update())
904 gui_->bufferView().processUpdateFlags(cur.disp_.update());
907 } // namespace frontend
910 #include "GuiCompleter_moc.cpp"