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 "GuiWorkArea.h"
24 #include "Paragraph.h"
27 #include "support/lassert.h"
28 #include "support/debug.h"
30 #include <QApplication>
31 #include <QHeaderView>
33 #include <QPixmapCache>
35 #include <QItemDelegate>
40 using namespace lyx::support;
45 class CompleterItemDelegate : public QItemDelegate
48 explicit CompleterItemDelegate(QObject * parent)
49 : QItemDelegate(parent)
52 ~CompleterItemDelegate()
56 void paint(QPainter *painter, const QStyleOptionViewItem &option,
57 const QModelIndex &index) const
59 if (index.column() == 0) {
60 QItemDelegate::paint(painter, option, index);
63 QStyleOptionViewItem opt = setOptions(index, option);
64 QVariant value = index.data(Qt::DisplayRole);
65 QPixmap pixmap = qvariant_cast<QPixmap>(value);
69 drawBackground(painter, opt, index);
70 if (!pixmap.isNull()) {
71 const QSize size = pixmap.size();
72 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
73 option.rect.top() + (option.rect.height() - size.height()) / 2,
76 drawFocus(painter, opt, option.rect);
81 class GuiCompletionModel : public QAbstractListModel
85 GuiCompletionModel(QObject * parent, CompletionList const * l)
86 : QAbstractListModel(parent), list_(l)
89 ~GuiCompletionModel() { delete list_; }
91 void setList(CompletionList const * l) {
100 return list_->sorted();
104 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
109 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
113 return list_->size();
117 QVariant data(const QModelIndex & index, int role) const
122 if (index.row() < 0 || index.row() >= rowCount())
125 if (role != Qt::DisplayRole && role != Qt::EditRole)
128 if (index.column() == 0)
129 return toqstr(list_->data(index.row()));
131 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);
145 QPixmapCache::insert("completion" + name, scaled);
152 CompletionList const * list_;
156 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
157 : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
158 inlineVisible_(false), popupVisible_(false),
161 // Setup the completion popup
162 model_ = new GuiCompletionModel(this, 0);
164 setCompletionMode(QCompleter::PopupCompletion);
165 setCaseSensitivity(Qt::CaseSensitive);
169 QTreeView *listView = new QTreeView;
170 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
171 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
172 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
173 listView->setSelectionMode(QAbstractItemView::SingleSelection);
174 listView->header()->hide();
175 listView->setIndentation(0);
176 listView->setUniformRowHeights(true);
179 itemDelegate_ = new CompleterItemDelegate(this);
180 popup()->setItemDelegate(itemDelegate_);
182 // create timeout timers
183 popup_timer_.setSingleShot(true);
184 inline_timer_.setSingleShot(true);
185 connect(this, SIGNAL(highlighted(const QString &)),
186 this, SLOT(popupHighlighted(const QString &)));
187 connect(this, SIGNAL(activated(const QString &)),
188 this, SLOT(popupActivated(const QString &)));
189 connect(&popup_timer_, SIGNAL(timeout()),
190 this, SLOT(showPopup()));
191 connect(&inline_timer_, SIGNAL(timeout()),
192 this, SLOT(showInline()));
196 GuiCompleter::~GuiCompleter()
202 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
204 // hijack back the tab key from the popup
205 // (which stole it from the workspace before)
206 if (e->type() == QEvent::KeyPress && popupVisible()) {
207 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
217 return QCompleter::eventFilter(watched, e);
221 bool GuiCompleter::popupPossible(Cursor const & cur) const
223 return QApplication::activeWindow()
225 && cur.inset().completionSupported(cur);
229 bool GuiCompleter::inlinePossible(Cursor const & cur) const
231 return cur.inset().inlineCompletionSupported(cur);
235 bool GuiCompleter::uniqueCompletionAvailable() const
240 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 (completionPrefix() == currentCompletion())
253 bool GuiCompleter::completionAvailable() const
258 size_t n = popup()->model()->rowCount();
260 // if there is exactly one, we have to check whether it is a
261 // real completion, i.e. longer than the current prefix.
262 if (n == 1 && completionPrefix() == currentCompletion())
269 bool GuiCompleter::popupVisible() const
271 return popupVisible_;
275 bool GuiCompleter::inlineVisible() const
277 // In fact using BufferView::inlineCompletionPos.empty() should be
278 // here. But unfortunately this information is not good enough
279 // because destructive operations like backspace might invalidate
280 // inlineCompletionPos. But then the completion should stay visible
281 // (i.e. reshown on the next update). Hence be keep this information
282 // in the inlineVisible_ variable.
283 return inlineVisible_;
287 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
289 // parameters which affect the completion
290 bool moved = cur != old_cursor_;
294 bool possiblePopupState = popupPossible(cur) && cursorInView;
295 bool possibleInlineState = inlinePossible(cur) && cursorInView;
297 // we moved or popup state is not ok for popup?
298 if ((moved && !keep) || !possiblePopupState)
301 // we moved or inline state is not ok for inline completion?
302 if ((moved && !keep) || !possibleInlineState)
305 // we inserted something and are in a possible popup state?
306 if (!popupVisible() && possiblePopupState && start
307 && cur.inset().automaticPopupCompletion())
308 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
310 // we inserted something and are in a possible inline completion state?
311 if (!inlineVisible() && possibleInlineState && start
312 && cur.inset().automaticInlineCompletion())
313 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
315 // no inline completion, hence a metrics update is needed
316 if (!(cur.result().screenUpdate() & Update::Force))
317 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
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.screenUpdateFlags(Update::None);
336 updateVisibility(cur, start, keep);
338 if (cur.result().screenUpdate())
339 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
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 || !cur.bv().paragraphVisible(cur)) {
424 popupVisible_ = false;
428 // get dimensions of completion prefix
432 cur.inset().completionPosAndDim(cur, x, y, dim);
434 // and calculate the rect of the popup
436 if (popup()->layoutDirection() == Qt::RightToLeft)
437 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
439 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
441 // Resize the columns in the popup.
442 // This should really be in the constructor. But somehow the treeview
443 // has a bad memory about it and we have to tell him again and again.
444 QTreeView * listView = static_cast<QTreeView *>(popup());
445 listView->header()->setStretchLastSection(false);
446 listView->header()->setResizeMode(0, QHeaderView::Stretch);
447 listView->header()->setResizeMode(1, QHeaderView::Fixed);
448 listView->header()->resizeSection(1, 22);
455 void GuiCompleter::updateAvailability()
457 // this should really only be of interest if no completion is
458 // visible yet, i.e. especially if automatic completion is disabled.
459 if (inlineVisible() || popupVisible())
461 Cursor & cur = gui_->bufferView().cursor();
462 if (!popupPossible(cur) && !inlinePossible(cur))
465 updateModel(cur, false, false);
469 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
471 // value which should be kept selected
472 QString old = currentCompletion();
473 if (old.length() == 0)
474 old = last_selection_;
478 if (cur.inTexted()) {
479 Paragraph const & par = cur.paragraph();
481 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
482 rtl = font.isVisibleRightToLeft();
484 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
487 CompletionList const * list = cur.inset().createCompletionList(cur);
488 model_->setList(list);
491 setModelSorting(QCompleter::CaseSensitivelySortedModel);
493 setModelSorting(QCompleter::UnsortedModel);
496 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
497 if (newPrefix != completionPrefix())
498 setCompletionPrefix(newPrefix);
504 // restore old selection
505 setCurrentCompletion(old);
507 // if popup is not empty, the new selection will
508 // be our last valid one
509 if (popupVisible() || inlineVisible()) {
510 QString const & s = currentCompletion();
514 last_selection_ = old;
517 // show inline completion
519 updateInline(cur, currentCompletion());
523 void GuiCompleter::showPopup(Cursor & cur)
525 if (!popupPossible(cur))
528 updateModel(cur, true, inlineVisible());
532 void GuiCompleter::hidePopup(Cursor &)
534 popupVisible_ = false;
536 if (popup_timer_.isActive())
539 // hide popup asynchronously because we might be here inside of
540 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
541 // workarea which then redisplays the cursor. But the metrics are not
542 // yet up to date such that the coord cache has not all insets yet. The
543 // cursorPos methods would triggers asserts in the coord cache then.
544 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
546 // mark that the asynchronous part will reset the model
547 if (!inlineVisible())
548 modelActive_ = false;
552 void GuiCompleter::asyncHidePopup()
555 if (!inlineVisible())
560 void GuiCompleter::showInline(Cursor & cur)
562 if (!inlinePossible(cur))
565 updateModel(cur, popupVisible(), true);
569 void GuiCompleter::hideInline(Cursor & cur)
571 gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
572 inlineVisible_ = false;
574 if (inline_timer_.isActive())
575 inline_timer_.stop();
577 // Trigger asynchronous part of hideInline. We might be
578 // in a dispatcher here and the setModel call might
579 // trigger focus events which is are not healthy here.
580 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
582 // mark that the asynchronous part will reset the model
584 modelActive_ = false;
588 void GuiCompleter::asyncHideInline()
595 void GuiCompleter::showPopup()
597 Cursor cur = gui_->bufferView().cursor();
598 cur.screenUpdateFlags(Update::None);
603 if (cur.result().screenUpdate())
604 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
608 void GuiCompleter::showInline()
610 Cursor cur = gui_->bufferView().cursor();
611 cur.screenUpdateFlags(Update::None);
616 if (cur.result().screenUpdate())
617 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
621 void GuiCompleter::hidePopup()
623 Cursor cur = gui_->bufferView().cursor();
624 cur.screenUpdateFlags(Update::None);
629 if (cur.result().screenUpdate())
630 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
634 void GuiCompleter::hideInline()
636 Cursor cur = gui_->bufferView().cursor();
637 cur.screenUpdateFlags(Update::None);
642 if (cur.result().screenUpdate())
643 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
647 void GuiCompleter::activate()
649 if (!popupVisible() && !inlineVisible())
652 popupActivated(currentCompletion());
656 void GuiCompleter::tab()
658 BufferView * bv = &gui_->bufferView();
659 Cursor cur = bv->cursor();
660 cur.screenUpdateFlags(Update::None);
662 // check that inline completion is active
663 if (!inlineVisible() && !uniqueCompletionAvailable()) {
664 // try to activate the inline completion
665 if (cur.inset().inlineCompletionSupported(cur)) {
668 // show popup without delay because the completion was not unique
669 if (lyxrc.completion_popup_after_complete
671 && popup()->model()->rowCount() > 1)
672 popup_timer_.start(0);
677 if (!popupVisible() && cur.inset().completionSupported(cur)) {
685 // Make undo possible
686 cur.beginUndoGroup();
689 // If completion is active, at least complete by one character
690 docstring prefix = cur.inset().completionPrefix(cur);
691 docstring completion = qstring_to_ucs4(currentCompletion());
692 if (completion.size() <= prefix.size()) {
693 // finalize completion
694 cur.inset().insertCompletion(cur, docstring(), true);
696 // hide popup and inline completion
699 updateVisibility(false, false);
703 docstring nextchar = completion.substr(prefix.size(), 1);
704 if (!cur.inset().insertCompletion(cur, nextchar, false)) {
710 // try to complete as far as it is unique
711 docstring longestCompletion = longestUniqueCompletion();
712 prefix = cur.inset().completionPrefix(cur);
713 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
714 cur.inset().insertCompletion(cur, postfix, false);
715 old_cursor_ = bv->cursor();
718 // show popup without delay because the completion was not unique
719 if (lyxrc.completion_popup_after_complete
721 && popup()->model()->rowCount() > 1)
722 popup_timer_.start(0);
725 if (cur.result().screenUpdate())
726 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 LASSERT(i <= n, /**/);
804 // select the first if none was found
809 popup()->setCurrentIndex(model.index(i, 0));
814 size_t commonPrefix(QString const & s1, QString const & s2)
816 // find common prefix
818 size_t n1 = s1.length();
819 size_t n2 = s2.length();
820 for (j = 0; j < n1 && j < n2; ++j) {
821 if (s1.at(j) != s2.at(j))
828 docstring GuiCompleter::longestUniqueCompletion() const
830 QAbstractItemModel const & model = *popup()->model();
831 size_t n = model.rowCount();
834 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
836 if (modelSorting() == QCompleter::UnsortedModel) {
837 // For unsorted model we cannot do more than iteration.
838 // Iterate through the completions and cut off where s differs
839 for (size_t i = 0; i < n && s.length() > 0; ++i) {
841 = model.data(model.index(i, 0), Qt::EditRole).toString();
843 s = s.left(commonPrefix(is, s));
846 // For sorted models we can do binary search multiple times,
847 // each time to find the first string which has s not as prefix.
849 while (i < n && s.length() > 0) {
850 // find first string that does not have s as prefix
851 // via binary search in [i,n-1]
854 // get common prefix with the middle string
855 size_t mid = (r + i) / 2;
857 = model.data(model.index(mid, 0),
858 Qt::EditRole).toString();
859 size_t oldLen = s.length();
860 size_t len = commonPrefix(mids, s);
865 // middle is not far enough
868 // middle is maybe too far
871 } while (r - i > 0 && i < n);
875 return qstring_to_ucs4(s);
879 void GuiCompleter::popupActivated(const QString & completion)
881 Cursor cur = gui_->bufferView().cursor();
882 cur.screenUpdateFlags(Update::None);
884 cur.beginUndoGroup();
887 docstring prefix = cur.inset().completionPrefix(cur);
888 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
889 cur.inset().insertCompletion(cur, postfix, true);
893 if (cur.result().screenUpdate())
894 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
899 void GuiCompleter::popupHighlighted(const QString & completion)
904 Cursor cur = gui_->bufferView().cursor();
905 cur.screenUpdateFlags(Update::None);
908 updateInline(cur, completion);
910 if (cur.result().screenUpdate())
911 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
914 } // namespace frontend
917 #include "moc_GuiCompleter.cpp"