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_;
463 if (cur.inTexted()) {
464 Paragraph const & par = cur.paragraph();
466 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
467 rtl = font.isVisibleRightToLeft();
469 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
472 CompletionList const * list = cur.inset().createCompletionList(cur);
473 model_->setList(list);
476 setModelSorting(QCompleter::CaseSensitivelySortedModel);
478 setModelSorting(QCompleter::UnsortedModel);
481 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
482 if (newPrefix != completionPrefix())
483 setCompletionPrefix(newPrefix);
489 // restore old selection
490 setCurrentCompletion(old);
492 // if popup is not empty, the new selection will
493 // be our last valid one
494 if (popupVisible() || inlineVisible()) {
495 QString const & s = currentCompletion();
499 last_selection_ = old;
502 // show inline completion
504 updateInline(cur, currentCompletion());
508 void GuiCompleter::showPopup(Cursor & cur)
510 if (!popupPossible(cur))
513 updateModel(cur, true, inlineVisible());
517 void GuiCompleter::hidePopup(Cursor &)
519 popupVisible_ = false;
521 if (popup_timer_.isActive())
524 // hide popup asynchronously because we might be here inside of
525 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
526 // workarea which then redisplays the cursor. But the metrics are not
527 // yet up to date such that the coord cache has not all insets yet. The
528 // cursorPos methods would triggers asserts in the coord cache then.
529 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
531 // mark that the asynchronous part will reset the model
532 if (!inlineVisible())
533 modelActive_ = false;
537 void GuiCompleter::asyncHidePopup()
540 if (!inlineVisible())
545 void GuiCompleter::showInline(Cursor & cur)
547 if (!inlinePossible(cur))
550 updateModel(cur, popupVisible(), true);
554 void GuiCompleter::hideInline(Cursor & cur)
556 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
557 inlineVisible_ = false;
559 if (inline_timer_.isActive())
560 inline_timer_.stop();
562 // Trigger asynchronous part of hideInline. We might be
563 // in a dispatcher here and the setModel call might
564 // trigger focus events which is are not healthy here.
565 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
567 // mark that the asynchronous part will reset the model
569 modelActive_ = false;
573 void GuiCompleter::asyncHideInline()
580 void GuiCompleter::showPopup()
582 Cursor cur = gui_->bufferView().cursor();
583 cur.updateFlags(Update::None);
588 if (cur.disp_.update())
589 gui_->bufferView().processUpdateFlags(cur.disp_.update());
593 void GuiCompleter::showInline()
595 Cursor cur = gui_->bufferView().cursor();
596 cur.updateFlags(Update::None);
601 if (cur.disp_.update())
602 gui_->bufferView().processUpdateFlags(cur.disp_.update());
606 void GuiCompleter::hidePopup()
608 Cursor cur = gui_->bufferView().cursor();
609 cur.updateFlags(Update::None);
614 if (cur.disp_.update())
615 gui_->bufferView().processUpdateFlags(cur.disp_.update());
619 void GuiCompleter::hideInline()
621 Cursor cur = gui_->bufferView().cursor();
622 cur.updateFlags(Update::None);
627 if (cur.disp_.update())
628 gui_->bufferView().processUpdateFlags(cur.disp_.update());
632 void GuiCompleter::activate()
634 if (!popupVisible() && !inlineVisible())
637 popupActivated(currentCompletion());
641 void GuiCompleter::tab()
643 BufferView * bv = &gui_->bufferView();
644 Cursor cur = bv->cursor();
645 cur.updateFlags(Update::None);
647 // check that inline completion is active
648 if (!inlineVisible()) {
649 // try to activate the inline completion
650 if (cur.inset().inlineCompletionSupported(cur)) {
653 // show popup without delay because the completion was not unique
654 if (lyxrc.completion_popup_after_complete
656 && popup()->model()->rowCount() > 1)
657 popup_timer_.start(0);
662 if (!popupVisible() && cur.inset().completionSupported(cur)) {
670 // If completion is active, at least complete by one character
671 docstring prefix = cur.inset().completionPrefix(cur);
672 docstring completion = qstring_to_ucs4(currentCompletion());
673 if (completion.size() <= prefix.size()) {
674 // finalize completion
675 cur.inset().insertCompletion(cur, docstring(), true);
677 // hide popup and inline completion
680 updateVisibility(false, false);
683 docstring nextchar = completion.substr(prefix.size(), 1);
684 if (!cur.inset().insertCompletion(cur, nextchar, false))
688 // try to complete as far as it is unique
689 docstring longestCompletion = longestUniqueCompletion();
690 prefix = cur.inset().completionPrefix(cur);
691 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
692 cur.inset().insertCompletion(cur, postfix, false);
693 old_cursor_ = bv->cursor();
696 // show popup without delay because the completion was not unique
697 if (lyxrc.completion_popup_after_complete
699 && popup()->model()->rowCount() > 1)
700 popup_timer_.start(0);
703 if (cur.disp_.update())
704 gui_->bufferView().processUpdateFlags(cur.disp_.update());
708 QString GuiCompleter::currentCompletion() const
710 if (!popup()->selectionModel()->hasSelection())
713 // Not sure if this is bug in Qt: currentIndex() always
714 // return the first element in the list.
715 QModelIndex idx = popup()->currentIndex();
716 return popup()->model()->data(idx, Qt::EditRole).toString();
720 void GuiCompleter::setCurrentCompletion(QString const & s)
722 QAbstractItemModel const & model = *popup()->model();
723 size_t n = model.rowCount();
727 // select the first if s is empty
728 if (s.length() == 0) {
730 popup()->setCurrentIndex(model.index(0, 0));
735 // find old selection in model
737 if (modelSorting() == QCompleter::UnsortedModel) {
738 // In unsorted models, iterate through list until the s is found
739 for (i = 0; i < n; ++i) {
741 = model.data(model.index(i, 0), Qt::EditRole).toString();
746 // In sorted models, do binary search for s.
749 while (r >= l && l < int(n)) {
750 size_t mid = (r + l) / 2;
752 = model.data(model.index(mid, 0),
753 Qt::EditRole).toString();
756 // FIXME: is this really the same order that the docstring
757 // from the CompletionList has?
758 int c = s.compare(mids, Qt::CaseSensitive);
766 // middle is not far enough
773 // loop was left without finding anything
778 LASSERT(i <= n, /**/);
781 // select the first if none was found
786 popup()->setCurrentIndex(model.index(i, 0));
791 size_t commonPrefix(QString const & s1, QString const & s2)
793 // find common prefix
795 size_t n1 = s1.length();
796 size_t n2 = s2.length();
797 for (j = 0; j < n1 && j < n2; ++j) {
798 if (s1.at(j) != s2.at(j))
805 docstring GuiCompleter::longestUniqueCompletion() const
807 QAbstractItemModel const & model = *popup()->model();
808 size_t n = model.rowCount();
811 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
813 if (modelSorting() == QCompleter::UnsortedModel) {
814 // For unsorted model we cannot do more than iteration.
815 // Iterate through the completions and cut off where s differs
816 for (size_t i = 0; i < n && s.length() > 0; ++i) {
818 = model.data(model.index(i, 0), Qt::EditRole).toString();
820 s = s.left(commonPrefix(is, s));
823 // For sorted models we can do binary search multiple times,
824 // each time to find the first string which has s not as prefix.
826 while (i < n && s.length() > 0) {
827 // find first string that does not have s as prefix
828 // via binary search in [i,n-1]
831 // get common prefix with the middle string
832 size_t mid = (r + i) / 2;
834 = model.data(model.index(mid, 0),
835 Qt::EditRole).toString();
836 size_t oldLen = s.length();
837 size_t len = commonPrefix(mids, s);
842 // middle is not far enough
845 // middle is maybe too far
848 } while (r - i > 0 && i < n);
852 return qstring_to_ucs4(s);
856 void GuiCompleter::popupActivated(const QString & completion)
858 Cursor cur = gui_->bufferView().cursor();
859 cur.updateFlags(Update::None);
861 docstring prefix = cur.inset().completionPrefix(cur);
862 docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
863 cur.inset().insertCompletion(cur, postfix, true);
867 if (cur.disp_.update())
868 gui_->bufferView().processUpdateFlags(cur.disp_.update());
872 void GuiCompleter::popupHighlighted(const QString & completion)
877 Cursor cur = gui_->bufferView().cursor();
878 cur.updateFlags(Update::None);
881 updateInline(cur, completion);
883 if (cur.disp_.update())
884 gui_->bufferView().processUpdateFlags(cur.disp_.update());
887 } // namespace frontend
890 #include "GuiCompleter_moc.cpp"