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 paint(QPainter *painter, const QStyleOptionViewItem &option,
58 const QModelIndex &index) const
60 if (index.column() == 0) {
61 QItemDelegate::paint(painter, option, index);
64 QStyleOptionViewItem opt = setOptions(index, option);
65 QVariant value = index.data(Qt::DisplayRole);
66 QPixmap pixmap = qvariant_cast<QPixmap>(value);
70 drawBackground(painter, opt, index);
71 if (!pixmap.isNull()) {
72 const QSize size = pixmap.size();
73 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
74 option.rect.top() + (option.rect.height() - size.height()) / 2,
77 drawFocus(painter, opt, option.rect);
82 class GuiCompletionModel : public QAbstractListModel
86 GuiCompletionModel(QObject * parent, CompletionList const * l)
87 : QAbstractListModel(parent), list_(l)
90 ~GuiCompletionModel() { delete list_; }
92 void setList(CompletionList const * l) {
101 return list_->sorted();
105 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
110 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
115 return list_->size();
119 QVariant data(const QModelIndex & index, int role) const
124 if (index.row() < 0 || index.row() >= rowCount())
127 if (role != Qt::DisplayRole && role != Qt::EditRole)
130 if (index.column() == 0)
131 return toqstr(list_->data(index.row()));
133 if (index.column() == 1) {
134 // get icon from cache
136 QString const name = ":" + toqstr(list_->icon(index.row()));
137 if (!QPixmapCache::find("completion" + name, scaled)) {
138 // load icon from disk
139 QPixmap p = QPixmap(name);
141 // scale it to 16x16 or smaller
142 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
143 Qt::KeepAspectRatio, Qt::SmoothTransformation);
146 QPixmapCache::insert("completion" + name, scaled);
155 CompletionList const * list_;
159 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
160 : QCompleter(parent), gui_(gui), updateLock_(0),
161 inlineVisible_(false), popupVisible_(false),
164 // Setup the completion popup
165 model_ = new GuiCompletionModel(this, 0);
167 setCompletionMode(QCompleter::PopupCompletion);
171 QTreeView *listView = new QTreeView;
172 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
173 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
174 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
175 listView->setSelectionMode(QAbstractItemView::SingleSelection);
176 listView->header()->hide();
177 listView->setIndentation(0);
178 listView->setUniformRowHeights(true);
181 itemDelegate_ = new CompleterItemDelegate(this);
182 popup()->setItemDelegate(itemDelegate_);
184 // create timeout timers
185 popup_timer_.setSingleShot(true);
186 inline_timer_.setSingleShot(true);
187 connect(this, SIGNAL(highlighted(const QString &)),
188 this, SLOT(popupHighlighted(const QString &)));
189 connect(this, SIGNAL(activated(const QString &)),
190 this, SLOT(popupActivated(const QString &)));
191 connect(&popup_timer_, SIGNAL(timeout()),
192 this, SLOT(showPopup()));
193 connect(&inline_timer_, SIGNAL(timeout()),
194 this, SLOT(showInline()));
198 GuiCompleter::~GuiCompleter()
204 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
206 // hijack back the tab key from the popup
207 // (which stole it from the workspace before)
208 if (e->type() == QEvent::KeyPress && popupVisible()) {
209 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
219 return QCompleter::eventFilter(watched, e);
223 bool GuiCompleter::popupPossible(Cursor const & cur) const
225 return QApplication::activeWindow()
227 && cur.inset().completionSupported(cur);
231 bool GuiCompleter::inlinePossible(Cursor const & cur) const
233 return cur.inset().inlineCompletionSupported(cur);
237 bool GuiCompleter::completionAvailable() const
242 size_t n = popup()->model()->rowCount();
244 // if there is exactly one, we have to check whether it is a
245 // real completion, i.e. longer than the current prefix.
246 if (n == 1 && completionPrefix() == currentCompletion())
253 bool GuiCompleter::popupVisible() const
255 return popupVisible_;
259 bool GuiCompleter::inlineVisible() const
261 // In fact using BufferView::inlineCompletionPos.empty() should be
262 // here. But unfortunately this information is not good enough
263 // because destructive operations like backspace might invalidate
264 // inlineCompletionPos. But then the completion should stay visible
265 // (i.e. reshown on the next update). Hence be keep this information
266 // in the inlineVisible_ variable.
267 return inlineVisible_;
271 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
273 // parameters which affect the completion
274 bool moved = cur != old_cursor_;
278 bool possiblePopupState = popupPossible(cur) && cursorInView;
279 bool possibleInlineState = inlinePossible(cur) && cursorInView;
281 // we moved or popup state is not ok for popup?
282 if ((moved && !keep) || !possiblePopupState)
285 // we moved or inline state is not ok for inline completion?
286 if ((moved && !keep) || !possibleInlineState)
289 // we inserted something and are in a possible popup state?
290 if (!popupVisible() && possiblePopupState && start
291 && cur.inset().automaticPopupCompletion())
292 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
294 // we inserted something and are in a possible inline completion state?
295 if (!inlineVisible() && possibleInlineState && start
296 && cur.inset().automaticInlineCompletion())
297 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
299 // update prefix if any completion is possible
300 bool modelActive = modelActive_ && model()->rowCount() > 0;
301 if (possiblePopupState || possibleInlineState) {
305 updateAvailability();
310 void GuiCompleter::updateVisibility(bool start, bool keep)
312 Cursor cur = gui_->bufferView().cursor();
313 cur.updateFlags(Update::None);
315 updateVisibility(cur, start, keep);
317 if (cur.disp_.update())
318 gui_->bufferView().processUpdateFlags(cur.disp_.update());
322 void GuiCompleter::updatePrefix(Cursor & cur)
324 // get new prefix. Do nothing if unchanged
325 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
326 if (newPrefix == completionPrefix())
329 // value which should be kept selected
330 QString old = currentCompletion();
331 if (old.length() == 0)
332 old = last_selection_;
334 // update completer to new prefix
335 setCompletionPrefix(newPrefix);
337 // update popup because its size might have changed
341 // restore old selection
342 setCurrentCompletion(old);
344 // if popup is not empty, the new selection will
345 // be our last valid one
346 QString const & s = currentCompletion();
347 if (popupVisible() || inlineVisible()) {
351 last_selection_ = old;
354 // update inline completion because the default
355 // completion string might have changed
357 updateInline(cur, s);
361 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
363 if (!cur.inset().inlineCompletionSupported(cur))
367 docstring prefix = cur.inset().completionPrefix(cur);
368 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
370 // shorten it if necessary
371 if (lyxrc.completion_inline_dots != -1
372 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
373 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
375 // set inline completion at cursor position
376 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
377 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
378 inlineVisible_ = true;
382 void GuiCompleter::updatePopup(Cursor & cur)
384 if (!cur.inset().completionSupported(cur))
387 popupVisible_ = true;
389 if (completionCount() == 0) {
390 QTimer::singleShot(0, popup(), SLOT(hide()));
394 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
398 void GuiCompleter::asyncUpdatePopup()
400 Cursor cur = gui_->bufferView().cursor();
401 if (!cur.inset().completionSupported(cur)) {
402 popupVisible_ = false;
406 // get dimensions of completion prefix
410 cur.inset().completionPosAndDim(cur, x, y, dim);
412 // and calculate the rect of the popup
414 if (popup()->layoutDirection() == Qt::RightToLeft)
415 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
417 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
419 // Resize the columns in the popup.
420 // This should really be in the constructor. But somehow the treeview
421 // has a bad memory about it and we have to tell him again and again.
422 QTreeView * listView = static_cast<QTreeView *>(popup());
423 listView->header()->setStretchLastSection(false);
424 listView->header()->setResizeMode(0, QHeaderView::Stretch);
425 listView->header()->setResizeMode(1, QHeaderView::Fixed);
426 listView->header()->resizeSection(1, 22);
433 void GuiCompleter::updateAvailability()
435 // this should really only be of interest if no completion is
436 // visible yet, i.e. especially if automatic completion is disabled.
437 if (inlineVisible() || popupVisible())
439 Cursor & cur = gui_->bufferView().cursor();
440 if (!popupPossible(cur) && !inlinePossible(cur))
443 updateModel(cur, false, false);
447 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
449 // value which should be kept selected
450 QString old = currentCompletion();
451 if (old.length() == 0)
452 old = last_selection_;
456 if (cur.inTexted()) {
457 Paragraph const & par = cur.paragraph();
459 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
460 rtl = font.isVisibleRightToLeft();
462 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
465 CompletionList const * list = cur.inset().createCompletionList(cur);
466 model_->setList(list);
469 setModelSorting(QCompleter::CaseSensitivelySortedModel);
471 setModelSorting(QCompleter::UnsortedModel);
474 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
475 if (newPrefix != completionPrefix())
476 setCompletionPrefix(newPrefix);
482 // restore old selection
483 setCurrentCompletion(old);
485 // if popup is not empty, the new selection will
486 // be our last valid one
487 if (popupVisible() || inlineVisible()) {
488 QString const & s = currentCompletion();
492 last_selection_ = old;
495 // show inline completion
497 updateInline(cur, currentCompletion());
501 void GuiCompleter::showPopup(Cursor & cur)
503 if (!popupPossible(cur))
506 updateModel(cur, true, inlineVisible());
510 void GuiCompleter::hidePopup(Cursor &)
512 popupVisible_ = false;
514 if (popup_timer_.isActive())
517 // hide popup asynchronously because we might be here inside of
518 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
519 // workarea which then redisplays the cursor. But the metrics are not
520 // yet up to date such that the coord cache has not all insets yet. The
521 // cursorPos methods would triggers asserts in the coord cache then.
522 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
524 // mark that the asynchronous part will reset the model
525 if (!inlineVisible())
526 modelActive_ = false;
530 void GuiCompleter::asyncHidePopup()
533 if (!inlineVisible())
538 void GuiCompleter::showInline(Cursor & cur)
540 if (!inlinePossible(cur))
543 updateModel(cur, popupVisible(), true);
547 void GuiCompleter::hideInline(Cursor & cur)
549 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
550 inlineVisible_ = false;
552 if (inline_timer_.isActive())
553 inline_timer_.stop();
555 // Trigger asynchronous part of hideInline. We might be
556 // in a dispatcher here and the setModel call might
557 // trigger focus events which is are not healthy here.
558 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
560 // mark that the asynchronous part will reset the model
562 modelActive_ = false;
566 void GuiCompleter::asyncHideInline()
573 void GuiCompleter::showPopup()
575 Cursor cur = gui_->bufferView().cursor();
576 cur.updateFlags(Update::None);
581 if (cur.disp_.update())
582 gui_->bufferView().processUpdateFlags(cur.disp_.update());
586 void GuiCompleter::showInline()
588 Cursor cur = gui_->bufferView().cursor();
589 cur.updateFlags(Update::None);
594 if (cur.disp_.update())
595 gui_->bufferView().processUpdateFlags(cur.disp_.update());
599 void GuiCompleter::hidePopup()
601 Cursor cur = gui_->bufferView().cursor();
602 cur.updateFlags(Update::None);
607 if (cur.disp_.update())
608 gui_->bufferView().processUpdateFlags(cur.disp_.update());
612 void GuiCompleter::hideInline()
614 Cursor cur = gui_->bufferView().cursor();
615 cur.updateFlags(Update::None);
620 if (cur.disp_.update())
621 gui_->bufferView().processUpdateFlags(cur.disp_.update());
625 void GuiCompleter::activate()
627 if (!popupVisible() && !inlineVisible())
630 popupActivated(currentCompletion());
634 void GuiCompleter::tab()
636 BufferView * bv = &gui_->bufferView();
637 Cursor cur = bv->cursor();
638 cur.updateFlags(Update::None);
640 // check that inline completion is active
641 if (!inlineVisible()) {
642 // try to activate the inline completion
643 if (cur.inset().inlineCompletionSupported(cur)) {
646 // show popup without delay because the completion was not unique
647 if (lyxrc.completion_popup_after_complete
649 && popup()->model()->rowCount() > 1)
650 popup_timer_.start(0);
655 if (!popupVisible() && cur.inset().completionSupported(cur)) {
663 // If completion is active, at least complete by one character
664 docstring prefix = cur.inset().completionPrefix(cur);
665 docstring completion = qstring_to_ucs4(currentCompletion());
666 if (completion.size() <= prefix.size()) {
667 // finalize completion
668 cur.inset().insertCompletion(cur, docstring(), true);
670 // hide popup and inline completion
673 updateVisibility(false, false);
676 docstring nextchar = completion.substr(prefix.size(), 1);
677 if (!cur.inset().insertCompletion(cur, nextchar, false))
681 // try to complete as far as it is unique
682 docstring longestCompletion = longestUniqueCompletion();
683 prefix = cur.inset().completionPrefix(cur);
684 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
685 cur.inset().insertCompletion(cur, postfix, false);
686 old_cursor_ = bv->cursor();
689 // show popup without delay because the completion was not unique
690 if (lyxrc.completion_popup_after_complete
692 && popup()->model()->rowCount() > 1)
693 popup_timer_.start(0);
696 if (cur.disp_.update())
697 gui_->bufferView().processUpdateFlags(cur.disp_.update());
701 QString GuiCompleter::currentCompletion() const
703 if (!popup()->selectionModel()->hasSelection())
706 // Not sure if this is bug in Qt: currentIndex() always
707 // return the first element in the list.
708 QModelIndex idx = popup()->currentIndex();
709 return popup()->model()->data(idx, Qt::EditRole).toString();
713 void GuiCompleter::setCurrentCompletion(QString const & s)
715 QAbstractItemModel const & model = *popup()->model();
716 size_t n = model.rowCount();
720 // select the first if s is empty
721 if (s.length() == 0) {
723 popup()->setCurrentIndex(model.index(0, 0));
728 // find old selection in model
730 if (modelSorting() == QCompleter::UnsortedModel) {
731 // In unsorted models, iterate through list until the s is found
732 for (i = 0; i < n; ++i) {
734 = model.data(model.index(i, 0), Qt::EditRole).toString();
739 // In sorted models, do binary search for s.
742 while (r >= l && l < int(n)) {
743 size_t mid = (r + l) / 2;
745 = model.data(model.index(mid, 0),
746 Qt::EditRole).toString();
749 // FIXME: is this really the same order that the docstring
750 // from the CompletionList has?
751 int c = s.compare(mids, Qt::CaseSensitive);
759 // middle is not far enough
766 // loop was left without finding anything
771 LASSERT(i <= n, /**/);
774 // select the first if none was found
779 popup()->setCurrentIndex(model.index(i, 0));
784 size_t commonPrefix(QString const & s1, QString const & s2)
786 // find common prefix
788 size_t n1 = s1.length();
789 size_t n2 = s2.length();
790 for (j = 0; j < n1 && j < n2; ++j) {
791 if (s1.at(j) != s2.at(j))
798 docstring GuiCompleter::longestUniqueCompletion() const
800 QAbstractItemModel const & model = *popup()->model();
801 size_t n = model.rowCount();
804 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
806 if (modelSorting() == QCompleter::UnsortedModel) {
807 // For unsorted model we cannot do more than iteration.
808 // Iterate through the completions and cut off where s differs
809 for (size_t i = 0; i < n && s.length() > 0; ++i) {
811 = model.data(model.index(i, 0), Qt::EditRole).toString();
813 s = s.left(commonPrefix(is, s));
816 // For sorted models we can do binary search multiple times,
817 // each time to find the first string which has s not as prefix.
819 while (i < n && s.length() > 0) {
820 // find first string that does not have s as prefix
821 // via binary search in [i,n-1]
824 // get common prefix with the middle string
825 size_t mid = (r + i) / 2;
827 = model.data(model.index(mid, 0),
828 Qt::EditRole).toString();
829 size_t oldLen = s.length();
830 size_t len = commonPrefix(mids, s);
835 // middle is not far enough
838 // middle is maybe too far
841 } while (r - i > 0 && i < n);
845 return qstring_to_ucs4(s);
849 void GuiCompleter::popupActivated(const QString & completion)
851 Cursor cur = gui_->bufferView().cursor();
852 cur.updateFlags(Update::None);
854 docstring prefix = cur.inset().completionPrefix(cur);
855 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
856 cur.inset().insertCompletion(cur, postfix, true);
860 if (cur.disp_.update())
861 gui_->bufferView().processUpdateFlags(cur.disp_.update());
865 void GuiCompleter::popupHighlighted(const QString & completion)
870 Cursor cur = gui_->bufferView().cursor();
871 cur.updateFlags(Update::None);
874 updateInline(cur, completion);
876 if (cur.disp_.update())
877 gui_->bufferView().processUpdateFlags(cur.disp_.update());
880 } // namespace frontend
883 #include "GuiCompleter_moc.cpp"