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)
53 ~CompleterItemDelegate()
57 void drawDisplay(QPainter * painter,
58 QStyleOptionViewItem const & option,
59 QRect const & rect, QString const & text) const
61 QItemDelegate::drawDisplay(painter, option, rect, text);
64 void paint(QPainter *painter, const QStyleOptionViewItem &option,
65 const QModelIndex &index) const
67 if (index.column() == 0) {
68 QItemDelegate::paint(painter, option, index);
71 QStyleOptionViewItem opt = setOptions(index, option);
72 QVariant value = index.data(Qt::DisplayRole);
73 QPixmap pixmap = qvariant_cast<QPixmap>(value);
77 drawBackground(painter, opt, index);
78 if (!pixmap.isNull()) {
79 const QSize size = pixmap.size();
80 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
81 option.rect.top() + (option.rect.height() - size.height()) / 2,
84 drawFocus(painter, opt, option.rect);
89 class GuiCompletionModel : public QAbstractListModel
93 GuiCompletionModel(QObject * parent, CompletionList const * l)
94 : QAbstractListModel(parent), list_(l)
97 ~GuiCompletionModel() { delete list_; }
99 void setList(CompletionList const * l) {
108 return list_->sorted();
112 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
117 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
122 return list_->size();
126 QVariant data(const QModelIndex & index, int role) const
131 if (index.row() < 0 || index.row() >= rowCount())
134 if (role != Qt::DisplayRole && role != Qt::EditRole)
137 if (index.column() == 0)
138 return toqstr(list_->data(index.row()));
140 if (index.column() == 1) {
141 // get icon from cache
143 QString const name = ":" + toqstr(list_->icon(index.row()));
144 if (!QPixmapCache::find("completion" + name, scaled)) {
145 // load icon from disk
146 QPixmap p = QPixmap(name);
148 // scale it to 16x16 or smaller
149 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
150 Qt::KeepAspectRatio, Qt::SmoothTransformation);
153 QPixmapCache::insert("completion" + name, scaled);
162 CompletionList const * list_;
166 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
167 : QCompleter(parent), gui_(gui), updateLock_(0),
168 inlineVisible_(false), popupVisible_(false),
171 // Setup the completion popup
172 model_ = new GuiCompletionModel(this, 0);
174 setCompletionMode(QCompleter::PopupCompletion);
178 QTreeView *listView = new QTreeView;
179 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
180 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
181 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
182 listView->setSelectionMode(QAbstractItemView::SingleSelection);
183 listView->header()->hide();
184 listView->setIndentation(0);
185 listView->setUniformRowHeights(true);
188 itemDelegate_ = new CompleterItemDelegate(this);
189 popup()->setItemDelegate(itemDelegate_);
191 // create timeout timers
192 popup_timer_.setSingleShot(true);
193 inline_timer_.setSingleShot(true);
194 connect(this, SIGNAL(highlighted(const QString &)),
195 this, SLOT(popupHighlighted(const QString &)));
196 connect(this, SIGNAL(activated(const QString &)),
197 this, SLOT(popupActivated(const QString &)));
198 connect(&popup_timer_, SIGNAL(timeout()),
199 this, SLOT(showPopup()));
200 connect(&inline_timer_, SIGNAL(timeout()),
201 this, SLOT(showInline()));
205 GuiCompleter::~GuiCompleter()
211 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
213 // hijack back the tab key from the popup
214 // (which stole it from the workspace before)
215 if (e->type() == QEvent::KeyPress && popupVisible()) {
216 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
226 return QCompleter::eventFilter(watched, e);
230 bool GuiCompleter::popupPossible(Cursor const & cur) const
232 return QApplication::activeWindow()
234 && cur.inset().completionSupported(cur);
238 bool GuiCompleter::inlinePossible(Cursor const & cur) const
240 return cur.inset().inlineCompletionSupported(cur);
244 bool GuiCompleter::completionAvailable() const
249 size_t n = popup()->model()->rowCount();
251 // if there is exactly one, we have to check whether it is a
252 // real completion, i.e. longer than the current prefix.
253 if (n == 1 && completionPrefix() == currentCompletion())
260 bool GuiCompleter::popupVisible() const
262 return popupVisible_;
266 bool GuiCompleter::inlineVisible() const
268 // In fact using BufferView::inlineCompletionPos.empty() should be
269 // here. But unfortunately this information is not good enough
270 // because destructive operations like backspace might invalidate
271 // inlineCompletionPos. But then the completion should stay visible
272 // (i.e. reshown on the next update). Hence be keep this information
273 // in the inlineVisible_ variable.
274 return inlineVisible_;
278 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
280 // parameters which affect the completion
281 bool moved = cur != old_cursor_;
285 bool possiblePopupState = popupPossible(cur) && cursorInView;
286 bool possibleInlineState = inlinePossible(cur) && cursorInView;
288 // we moved or popup state is not ok for popup?
289 if ((moved && !keep) || !possiblePopupState)
292 // we moved or inline state is not ok for inline completion?
293 if ((moved && !keep) || !possibleInlineState)
296 // we inserted something and are in a possible popup state?
297 if (!popupVisible() && possiblePopupState && start
298 && cur.inset().automaticPopupCompletion())
299 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
301 // we inserted something and are in a possible inline completion state?
302 if (!inlineVisible() && possibleInlineState && start
303 && cur.inset().automaticInlineCompletion())
304 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
306 // update prefix if any completion is possible
307 bool modelActive = modelActive_ && model()->rowCount() > 0;
308 if (possiblePopupState || possibleInlineState) {
312 updateAvailability();
317 void GuiCompleter::updateVisibility(bool start, bool keep)
319 Cursor cur = gui_->bufferView().cursor();
320 cur.updateFlags(Update::None);
322 updateVisibility(cur, start, keep);
324 if (cur.disp_.update())
325 gui_->bufferView().processUpdateFlags(cur.disp_.update());
329 void GuiCompleter::updatePrefix(Cursor & cur)
331 // get new prefix. Do nothing if unchanged
332 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
333 if (newPrefix == completionPrefix())
336 // value which should be kept selected
337 QString old = currentCompletion();
338 if (old.length() == 0)
339 old = last_selection_;
341 // update completer to new prefix
342 setCompletionPrefix(newPrefix);
344 // update popup because its size might have changed
348 // restore old selection
349 setCurrentCompletion(old);
351 // if popup is not empty, the new selection will
352 // be our last valid one
353 QString const & s = currentCompletion();
354 if (popupVisible() || inlineVisible()) {
358 last_selection_ = old;
361 // update inline completion because the default
362 // completion string might have changed
364 updateInline(cur, s);
368 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
370 if (!cur.inset().inlineCompletionSupported(cur))
374 docstring prefix = cur.inset().completionPrefix(cur);
375 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
377 // shorten it if necessary
378 if (lyxrc.completion_inline_dots != -1
379 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
380 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
382 // set inline completion at cursor position
383 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
384 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
385 inlineVisible_ = true;
389 void GuiCompleter::updatePopup(Cursor & cur)
391 if (!cur.inset().completionSupported(cur))
394 popupVisible_ = true;
396 if (completionCount() == 0) {
397 QTimer::singleShot(0, popup(), SLOT(hide()));
401 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
405 void GuiCompleter::asyncUpdatePopup()
407 Cursor cur = gui_->bufferView().cursor();
408 if (!cur.inset().completionSupported(cur)) {
409 popupVisible_ = false;
413 // get dimensions of completion prefix
417 cur.inset().completionPosAndDim(cur, x, y, dim);
419 // and calculate the rect of the popup
421 if (popup()->layoutDirection() == Qt::RightToLeft)
422 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
424 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
426 // Resize the columns in the popup.
427 // This should really be in the constructor. But somehow the treeview
428 // has a bad memory about it and we have to tell him again and again.
429 QTreeView * listView = static_cast<QTreeView *>(popup());
430 listView->header()->setStretchLastSection(false);
431 listView->header()->setResizeMode(0, QHeaderView::Stretch);
432 listView->header()->setResizeMode(1, QHeaderView::Fixed);
433 listView->header()->resizeSection(1, 22);
440 void GuiCompleter::updateAvailability()
442 // this should really only be of interest if no completion is
443 // visible yet, i.e. especially if automatic completion is disabled.
444 if (inlineVisible() || popupVisible())
446 Cursor & cur = gui_->bufferView().cursor();
447 if (!popupPossible(cur) && !inlinePossible(cur))
450 updateModel(cur, false, false);
454 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
456 // value which should be kept selected
457 QString old = currentCompletion();
458 if (old.length() == 0)
459 old = last_selection_;
464 if (cur.inTexted()) {
465 Paragraph const & par = cur.paragraph();
467 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
468 rtl = font.isVisibleRightToLeft();
470 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
473 CompletionList const * list = cur.inset().createCompletionList(cur);
474 model_->setList(list);
477 setModelSorting(QCompleter::CaseSensitivelySortedModel);
479 setModelSorting(QCompleter::UnsortedModel);
482 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
483 if (newPrefix != completionPrefix())
484 setCompletionPrefix(newPrefix);
490 // restore old selection
491 setCurrentCompletion(old);
493 // if popup is not empty, the new selection will
494 // be our last valid one
495 if (popupVisible() || inlineVisible()) {
496 QString const & s = currentCompletion();
500 last_selection_ = old;
503 // show inline completion
505 updateInline(cur, currentCompletion());
509 void GuiCompleter::showPopup(Cursor & cur)
511 if (!popupPossible(cur))
514 updateModel(cur, true, inlineVisible());
518 void GuiCompleter::hidePopup(Cursor &)
520 popupVisible_ = false;
522 if (popup_timer_.isActive())
525 // hide popup asynchronously because we might be here inside of
526 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
527 // workarea which then redisplays the cursor. But the metrics are not
528 // yet up to date such that the coord cache has not all insets yet. The
529 // cursorPos methods would triggers asserts in the coord cache then.
530 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
532 // mark that the asynchronous part will reset the model
533 if (!inlineVisible())
534 modelActive_ = false;
538 void GuiCompleter::asyncHidePopup()
541 if (!inlineVisible())
546 void GuiCompleter::showInline(Cursor & cur)
548 if (!inlinePossible(cur))
551 updateModel(cur, popupVisible(), true);
555 void GuiCompleter::hideInline(Cursor & cur)
557 gui_->bufferView().setInlineCompletion(cur, DocIterator(), 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.updateFlags(Update::None);
589 if (cur.disp_.update())
590 gui_->bufferView().processUpdateFlags(cur.disp_.update());
594 void GuiCompleter::showInline()
596 Cursor cur = gui_->bufferView().cursor();
597 cur.updateFlags(Update::None);
602 if (cur.disp_.update())
603 gui_->bufferView().processUpdateFlags(cur.disp_.update());
607 void GuiCompleter::hidePopup()
609 Cursor cur = gui_->bufferView().cursor();
610 cur.updateFlags(Update::None);
615 if (cur.disp_.update())
616 gui_->bufferView().processUpdateFlags(cur.disp_.update());
620 void GuiCompleter::hideInline()
622 Cursor cur = gui_->bufferView().cursor();
623 cur.updateFlags(Update::None);
628 if (cur.disp_.update())
629 gui_->bufferView().processUpdateFlags(cur.disp_.update());
633 void GuiCompleter::activate()
635 if (!popupVisible() && !inlineVisible())
638 popupActivated(currentCompletion());
642 void GuiCompleter::tab()
644 BufferView * bv = &gui_->bufferView();
645 Cursor cur = bv->cursor();
646 cur.updateFlags(Update::None);
648 // check that inline completion is active
649 if (!inlineVisible()) {
650 // try to activate the inline completion
651 if (cur.inset().inlineCompletionSupported(cur)) {
654 // show popup without delay because the completion was not unique
655 if (lyxrc.completion_popup_after_complete
657 && popup()->model()->rowCount() > 1)
658 popup_timer_.start(0);
663 if (!popupVisible() && cur.inset().completionSupported(cur)) {
671 // If completion is active, at least complete by one character
672 docstring prefix = cur.inset().completionPrefix(cur);
673 docstring completion = qstring_to_ucs4(currentCompletion());
674 if (completion.size() <= prefix.size()) {
675 // finalize completion
676 cur.inset().insertCompletion(cur, docstring(), true);
678 // hide popup and inline completion
681 updateVisibility(false, false);
684 docstring nextchar = completion.substr(prefix.size(), 1);
685 if (!cur.inset().insertCompletion(cur, nextchar, false))
689 // try to complete as far as it is unique
690 docstring longestCompletion = longestUniqueCompletion();
691 prefix = cur.inset().completionPrefix(cur);
692 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
693 cur.inset().insertCompletion(cur, postfix, false);
694 old_cursor_ = bv->cursor();
697 // show popup without delay because the completion was not unique
698 if (lyxrc.completion_popup_after_complete
700 && popup()->model()->rowCount() > 1)
701 popup_timer_.start(0);
704 if (cur.disp_.update())
705 gui_->bufferView().processUpdateFlags(cur.disp_.update());
709 QString GuiCompleter::currentCompletion() const
711 if (!popup()->selectionModel()->hasSelection())
714 // Not sure if this is bug in Qt: currentIndex() always
715 // return the first element in the list.
716 QModelIndex idx = popup()->currentIndex();
717 return popup()->model()->data(idx, Qt::EditRole).toString();
721 void GuiCompleter::setCurrentCompletion(QString const & s)
723 QAbstractItemModel const & model = *popup()->model();
724 size_t n = model.rowCount();
728 // select the first if s is empty
729 if (s.length() == 0) {
731 popup()->setCurrentIndex(model.index(0, 0));
736 // find old selection in model
738 if (modelSorting() == QCompleter::UnsortedModel) {
739 // In unsorted models, iterate through list until the s is found
740 for (i = 0; i < n; ++i) {
742 = model.data(model.index(i, 0), Qt::EditRole).toString();
747 // In sorted models, do binary search for s.
750 while (r >= l && l < int(n)) {
751 size_t mid = (r + l) / 2;
753 = model.data(model.index(mid, 0),
754 Qt::EditRole).toString();
757 // FIXME: is this really the same order that the docstring
758 // from the CompletionList has?
759 int c = s.compare(mids, Qt::CaseSensitive);
767 // middle is not far enough
774 // loop was left without finding anything
779 LASSERT(i <= n, /**/);
782 // select the first if none was found
787 popup()->setCurrentIndex(model.index(i, 0));
792 size_t commonPrefix(QString const & s1, QString const & s2)
794 // find common prefix
796 size_t n1 = s1.length();
797 size_t n2 = s2.length();
798 for (j = 0; j < n1 && j < n2; ++j) {
799 if (s1.at(j) != s2.at(j))
806 docstring GuiCompleter::longestUniqueCompletion() const
808 QAbstractItemModel const & model = *popup()->model();
809 size_t n = model.rowCount();
812 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
814 if (modelSorting() == QCompleter::UnsortedModel) {
815 // For unsorted model we cannot do more than iteration.
816 // Iterate through the completions and cut off where s differs
817 for (size_t i = 0; i < n && s.length() > 0; ++i) {
819 = model.data(model.index(i, 0), Qt::EditRole).toString();
821 s = s.left(commonPrefix(is, s));
824 // For sorted models we can do binary search multiple times,
825 // each time to find the first string which has s not as prefix.
827 while (i < n && s.length() > 0) {
828 // find first string that does not have s as prefix
829 // via binary search in [i,n-1]
832 // get common prefix with the middle string
833 size_t mid = (r + i) / 2;
835 = model.data(model.index(mid, 0),
836 Qt::EditRole).toString();
837 size_t oldLen = s.length();
838 size_t len = commonPrefix(mids, s);
843 // middle is not far enough
846 // middle is maybe too far
849 } while (r - i > 0 && i < n);
853 return qstring_to_ucs4(s);
857 void GuiCompleter::popupActivated(const QString & completion)
859 Cursor cur = gui_->bufferView().cursor();
860 cur.updateFlags(Update::None);
862 docstring prefix = cur.inset().completionPrefix(cur);
863 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
864 cur.inset().insertCompletion(cur, postfix, true);
868 if (cur.disp_.update())
869 gui_->bufferView().processUpdateFlags(cur.disp_.update());
873 void GuiCompleter::popupHighlighted(const QString & completion)
878 Cursor cur = gui_->bufferView().cursor();
879 cur.updateFlags(Update::None);
882 updateInline(cur, completion);
884 if (cur.disp_.update())
885 gui_->bufferView().processUpdateFlags(cur.disp_.update());
888 } // namespace frontend
891 #include "GuiCompleter_moc.cpp"