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 "GuiWorkArea.h"
16 #include "BufferView.h"
17 #include "CompletionList.h"
19 #include "Dimension.h"
20 #include "FuncRequest.h"
24 #include "Paragraph.h"
27 #include "support/debug.h"
29 #include <QApplication>
30 #include <QHeaderView>
32 #include <QPixmapCache>
34 #include <QItemDelegate>
39 using namespace lyx::support;
44 class RtlItemDelegate : public QItemDelegate {
46 explicit RtlItemDelegate(QObject * parent = 0)
47 : QItemDelegate(parent), enabled_(false) {}
49 void setEnabled(bool enabled = true)
55 virtual void drawDisplay(QPainter * painter,
56 QStyleOptionViewItem const & option,
57 QRect const & rect, QString const & text) const
60 QItemDelegate::drawDisplay(painter, option, rect, text);
64 // FIXME: do this more elegantly
65 docstring stltext = qstring_to_ucs4(text);
66 reverse(stltext.begin(), stltext.end());
67 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
75 class PixmapItemDelegate : public QItemDelegate {
77 explicit PixmapItemDelegate(QObject *parent = 0)
78 : QItemDelegate(parent) {}
81 void paint(QPainter *painter, const QStyleOptionViewItem &option,
82 const QModelIndex &index) const
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);
103 class GuiCompletionModel : public QAbstractListModel {
106 GuiCompletionModel(QObject * parent, CompletionList const * l)
107 : QAbstractListModel(parent), list_(l) {}
109 ~GuiCompletionModel()
115 return list_->sorted();
120 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
125 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
130 return list_->size();
134 QVariant data(const QModelIndex & index, int role) const
139 if (index.row() < 0 || index.row() >= rowCount())
142 if (role != Qt::DisplayRole && role != Qt::EditRole)
145 if (index.column() == 0)
146 return toqstr(list_->data(index.row()));
147 else if (index.column() == 1) {
148 // get icon from cache
150 QString const name = ":" + toqstr(list_->icon(index.row()));
151 if (!QPixmapCache::find("completion" + name, scaled)) {
152 // load icon from disk
153 QPixmap p = QPixmap(name);
155 // scale it to 16x16 or smaller
156 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
157 Qt::KeepAspectRatio, Qt::SmoothTransformation);
160 QPixmapCache::insert("completion" + name, scaled);
169 CompletionList const * list_;
173 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
174 : QCompleter(parent), gui_(gui), updateLock_(0),
175 inlineVisible_(false), popupVisible_(false),
178 // Setup the completion popup
179 setModel(new GuiCompletionModel(this, 0));
180 setCompletionMode(QCompleter::PopupCompletion);
184 QTreeView *listView = new QTreeView;
185 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
186 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
187 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
188 listView->setSelectionMode(QAbstractItemView::SingleSelection);
189 listView->header()->hide();
190 listView->setIndentation(0);
191 listView->setUniformRowHeights(true);
194 rtlItemDelegate_ = new RtlItemDelegate(this);
195 popup()->setItemDelegateForColumn(0, rtlItemDelegate_);
196 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
198 // create timeout timers
199 popup_timer_.setSingleShot(true);
200 inline_timer_.setSingleShot(true);
201 connect(this, SIGNAL(highlighted(const QString &)),
202 this, SLOT(popupHighlighted(const QString &)));
203 connect(this, SIGNAL(activated(const QString &)),
204 this, SLOT(popupActivated(const QString &)));
205 connect(&popup_timer_, SIGNAL(timeout()),
206 this, SLOT(showPopup()));
207 connect(&inline_timer_, SIGNAL(timeout()),
208 this, SLOT(showInline()));
212 GuiCompleter::~GuiCompleter()
218 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
220 // hijack back the tab key from the popup
221 // (which stole it from the workspace before)
222 if (e->type() == QEvent::KeyPress && popupVisible()) {
223 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
233 return QCompleter::eventFilter(watched, e);
237 bool GuiCompleter::popupPossible(Cursor const & cur) const
239 return QApplication::activeWindow()
241 && cur.inset().completionSupported(cur);
245 bool GuiCompleter::inlinePossible(Cursor const & cur) const
247 return cur.inset().inlineCompletionSupported(cur);
251 bool GuiCompleter::completionAvailable() const
256 size_t n = popup()->model()->rowCount();
258 // if there is exactly one, we have to check whether it is a
259 // real completion, i.e. longer than the current prefix.
260 if (n == 1 && completionPrefix() == currentCompletion())
267 bool GuiCompleter::popupVisible() const
269 return popupVisible_;
273 bool GuiCompleter::inlineVisible() const
275 // In fact using BufferView::inlineCompletionPos.empty() should be
276 // here. But unfortunately this information is not good enough
277 // because destructive operations like backspace might invalidate
278 // inlineCompletionPos. But then the completion should stay visible
279 // (i.e. reshown on the next update). Hence be keep this information
280 // in the inlineVisible_ variable.
281 return inlineVisible_;
285 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
287 // parameters which affect the completion
288 bool moved = cur != old_cursor_;
292 bool possiblePopupState = popupPossible(cur) && cursorInView;
293 bool possibleInlineState = inlinePossible(cur) && cursorInView;
295 // we moved or popup state is not ok for popup?
296 if ((moved && !keep) || !possiblePopupState)
299 // we moved or inline state is not ok for inline completion?
300 if ((moved && !keep) || !possibleInlineState)
303 // we inserted something and are in a possible popup state?
304 if (!popupVisible() && possiblePopupState && start
305 && cur.inset().automaticPopupCompletion())
306 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
308 // we inserted something and are in a possible inline completion state?
309 if (!inlineVisible() && possibleInlineState && start
310 && cur.inset().automaticInlineCompletion())
311 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
313 // update prefix if any completion is possible
314 bool modelActive = modelActive_ && model()->rowCount() > 0;
315 if (possiblePopupState || possibleInlineState) {
319 updateAvailability();
324 void GuiCompleter::updateVisibility(bool start, bool keep)
326 Cursor cur = gui_->bufferView().cursor();
327 cur.updateFlags(Update::None);
329 updateVisibility(cur, start, keep);
331 if (cur.disp_.update())
332 gui_->bufferView().processUpdateFlags(cur.disp_.update());
336 void GuiCompleter::updatePrefix(Cursor & cur)
338 // get new prefix. Do nothing if unchanged
339 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
340 if (newPrefix == completionPrefix())
343 // value which should be kept selected
344 QString old = currentCompletion();
345 if (old.length() == 0)
346 old = last_selection_;
348 // update completer to new prefix
349 setCompletionPrefix(newPrefix);
351 // update popup because its size might have changed
355 // restore old selection
356 setCurrentCompletion(old);
358 // if popup is not empty, the new selection will
359 // be our last valid one
360 QString const & s = currentCompletion();
361 if (popupVisible() || inlineVisible()) {
365 last_selection_ = old;
368 // update inline completion because the default
369 // completion string might have changed
371 updateInline(cur, s);
375 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
377 if (!cur.inset().inlineCompletionSupported(cur))
381 docstring prefix = cur.inset().completionPrefix(cur);
382 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
384 // shorten it if necessary
385 if (lyxrc.completion_inline_dots != -1
386 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
387 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
389 // set inline completion at cursor position
390 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
391 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
392 inlineVisible_ = true;
396 void GuiCompleter::updatePopup(Cursor & cur)
398 if (!cur.inset().completionSupported(cur))
401 popupVisible_ = true;
403 if (completionCount() == 0) {
404 QTimer::singleShot(0, popup(), SLOT(hide()));
408 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
412 void GuiCompleter::asyncUpdatePopup()
414 Cursor cur = gui_->bufferView().cursor();
415 if (!cur.inset().completionSupported(cur)) {
416 popupVisible_ = false;
420 // get dimensions of completion prefix
424 cur.inset().completionPosAndDim(cur, x, y, dim);
426 // and calculate the rect of the popup
428 if (popup()->layoutDirection() == Qt::RightToLeft)
429 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
431 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
433 // Resize the columns in the popup.
434 // This should really be in the constructor. But somehow the treeview
435 // has a bad memory about it and we have to tell him again and again.
436 QTreeView * listView = static_cast<QTreeView *>(popup());
437 listView->header()->setStretchLastSection(false);
438 listView->header()->setResizeMode(0, QHeaderView::Stretch);
439 listView->header()->setResizeMode(1, QHeaderView::Fixed);
440 listView->header()->resizeSection(1, 22);
447 void GuiCompleter::updateAvailability()
449 // this should really only be of interest if no completion is
450 // visible yet, i.e. especially if automatic completion is disabled.
451 if (inlineVisible() || popupVisible())
453 Cursor & cur = gui_->bufferView().cursor();
454 if (!popupPossible(cur) && !inlinePossible(cur))
457 updateModel(cur, false, false);
461 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
463 // value which should be kept selected
464 QString old = currentCompletion();
465 if (old.length() == 0)
466 old = last_selection_;
470 if (cur.inTexted()) {
471 Paragraph const & par = cur.paragraph();
473 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
474 rtl = font.isVisibleRightToLeft();
476 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
478 // turn the direction of the strings in the popup.
479 // Qt does not do that itself.
480 rtlItemDelegate_->setEnabled(rtl);
483 CompletionList const * list = cur.inset().createCompletionList(cur);
484 setModel(new GuiCompletionModel(this, list));
487 setModelSorting(QCompleter::CaseSensitivelySortedModel);
489 setModelSorting(QCompleter::UnsortedModel);
492 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
493 if (newPrefix != completionPrefix())
494 setCompletionPrefix(newPrefix);
500 // restore old selection
501 setCurrentCompletion(old);
503 // if popup is not empty, the new selection will
504 // be our last valid one
505 if (popupVisible() || inlineVisible()) {
506 QString const & s = currentCompletion();
510 last_selection_ = old;
513 // show inline completion
515 updateInline(cur, currentCompletion());
519 void GuiCompleter::showPopup(Cursor & cur)
521 if (!popupPossible(cur))
524 updateModel(cur, true, inlineVisible());
528 void GuiCompleter::hidePopup(Cursor & cur)
530 popupVisible_ = false;
532 if (popup_timer_.isActive())
535 // hide popup asynchronously because we might be here inside of
536 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
537 // workarea which then redisplays the cursor. But the metrics are not
538 // yet up to date such that the coord cache has not all insets yet. The
539 // cursorPos methods would triggers asserts in the coord cache then.
540 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
542 // mark that the asynchronous part will reset the model
543 if (!inlineVisible())
544 modelActive_ = false;
548 void GuiCompleter::asyncHidePopup()
551 if (!inlineVisible())
552 setModel(new GuiCompletionModel(this, 0));
556 void GuiCompleter::showInline(Cursor & cur)
558 if (!inlinePossible(cur))
561 updateModel(cur, popupVisible(), true);
565 void GuiCompleter::hideInline(Cursor & cur)
567 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
568 inlineVisible_ = false;
570 if (inline_timer_.isActive())
571 inline_timer_.stop();
573 // Trigger asynchronous part of hideInline. We might be
574 // in a dispatcher here and the setModel call might
575 // trigger focus events which is are not healthy here.
576 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
578 // mark that the asynchronous part will reset the model
580 modelActive_ = false;
584 void GuiCompleter::asyncHideInline()
587 setModel(new GuiCompletionModel(this, 0));
591 void GuiCompleter::showPopup()
593 Cursor cur = gui_->bufferView().cursor();
594 cur.updateFlags(Update::None);
599 if (cur.disp_.update())
600 gui_->bufferView().processUpdateFlags(cur.disp_.update());
604 void GuiCompleter::showInline()
606 Cursor cur = gui_->bufferView().cursor();
607 cur.updateFlags(Update::None);
612 if (cur.disp_.update())
613 gui_->bufferView().processUpdateFlags(cur.disp_.update());
617 void GuiCompleter::hidePopup()
619 Cursor cur = gui_->bufferView().cursor();
620 cur.updateFlags(Update::None);
625 if (cur.disp_.update())
626 gui_->bufferView().processUpdateFlags(cur.disp_.update());
630 void GuiCompleter::hideInline()
632 Cursor cur = gui_->bufferView().cursor();
633 cur.updateFlags(Update::None);
638 if (cur.disp_.update())
639 gui_->bufferView().processUpdateFlags(cur.disp_.update());
643 void GuiCompleter::activate()
645 if (!popupVisible() && !inlineVisible())
648 popupActivated(currentCompletion());
652 void GuiCompleter::tab()
654 BufferView * bv = &gui_->bufferView();
655 Cursor cur = bv->cursor();
656 cur.updateFlags(Update::None);
658 // check that inline completion is active
659 if (!inlineVisible()) {
660 // try to activate the inline completion
661 if (cur.inset().inlineCompletionSupported(cur)) {
664 // show popup without delay because the completion was not unique
665 if (lyxrc.completion_popup_after_complete
667 && popup()->model()->rowCount() > 1)
668 popup_timer_.start(0);
673 if (!popupVisible() && cur.inset().completionSupported(cur)) {
681 // If completion is active, at least complete by one character
682 docstring prefix = cur.inset().completionPrefix(cur);
683 docstring completion = from_utf8(fromqstr(currentCompletion()));
684 if (completion.size() <= prefix.size()) {
685 // finalize completion
686 cur.inset().insertCompletion(cur, docstring(), true);
688 // hide popup and inline completion
691 updateVisibility(false, false);
694 docstring nextchar = completion.substr(prefix.size(), 1);
695 if (!cur.inset().insertCompletion(cur, nextchar, false))
699 // try to complete as far as it is unique
700 docstring longestCompletion = longestUniqueCompletion();
701 prefix = cur.inset().completionPrefix(cur);
702 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
703 cur.inset().insertCompletion(cur, postfix, false);
704 old_cursor_ = bv->cursor();
707 // show popup without delay because the completion was not unique
708 if (lyxrc.completion_popup_after_complete
710 && popup()->model()->rowCount() > 1)
711 popup_timer_.start(0);
714 if (cur.disp_.update())
715 gui_->bufferView().processUpdateFlags(cur.disp_.update());
719 QString GuiCompleter::currentCompletion() const
721 if (!popup()->selectionModel()->hasSelection())
724 // Not sure if this is bug in Qt: currentIndex() always
725 // return the first element in the list.
726 QModelIndex idx = popup()->currentIndex();
727 return popup()->model()->data(idx, Qt::EditRole).toString();
731 void GuiCompleter::setCurrentCompletion(QString const & s)
733 QAbstractItemModel const & model = *popup()->model();
734 size_t n = model.rowCount();
738 // select the first if s is empty
739 if (s.length() == 0) {
741 popup()->setCurrentIndex(model.index(0, 0));
746 // find old selection in model
748 if (modelSorting() == QCompleter::UnsortedModel) {
749 // In unsorted models, iterate through list until the s is found
750 for (i = 0; i < n; ++i) {
752 = model.data(model.index(i, 0), Qt::EditRole).toString();
757 // In sorted models, do binary search for s.
760 while (r >= l && l < int(n)) {
761 size_t mid = (r + l) / 2;
763 = model.data(model.index(mid, 0),
764 Qt::EditRole).toString();
767 // FIXME: is this really the same order that the docstring
768 // from the CompletionList has?
769 int c = s.compare(mids, Qt::CaseSensitive);
777 // middle is not far enough
784 // loop was left without finding anything
789 BOOST_ASSERT(0 <= i && i <= n);
792 // select the first if none was found
797 popup()->setCurrentIndex(model.index(i, 0));
802 size_t commonPrefix(QString const & s1, QString const & s2)
804 // find common prefix
806 size_t n1 = s1.length();
807 size_t n2 = s2.length();
808 for (j = 0; j < n1 && j < n2; ++j) {
809 if (s1.at(j) != s2.at(j))
816 docstring GuiCompleter::longestUniqueCompletion() const
818 QAbstractItemModel const & model = *popup()->model();
819 size_t n = model.rowCount();
822 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
824 if (modelSorting() == QCompleter::UnsortedModel) {
825 // For unsorted model we cannot do more than iteration.
826 // Iterate through the completions and cut off where s differs
827 for (size_t i = 0; i < n && s.length() > 0; ++i) {
829 = model.data(model.index(i, 0), Qt::EditRole).toString();
831 s = s.left(commonPrefix(is, s));
834 // For sorted models we can do binary search multiple times,
835 // each time to find the first string which has s not as prefix.
837 while (i < n && s.length() > 0) {
838 // find first string that does not have s as prefix
839 // via binary search in [i,n-1]
842 // get common prefix with the middle string
843 size_t mid = (r + i) / 2;
845 = model.data(model.index(mid, 0),
846 Qt::EditRole).toString();
847 size_t oldLen = s.length();
848 size_t len = commonPrefix(mids, s);
853 // middle is not far enough
856 // middle is maybe too far
859 } while (r - i > 0 && i < n);
863 return from_utf8(fromqstr(s));
867 void GuiCompleter::popupActivated(const QString & completion)
869 Cursor cur = gui_->bufferView().cursor();
870 cur.updateFlags(Update::None);
872 docstring prefix = cur.inset().completionPrefix(cur);
873 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
874 cur.inset().insertCompletion(cur, postfix, true);
878 if (cur.disp_.update())
879 gui_->bufferView().processUpdateFlags(cur.disp_.update());
883 void GuiCompleter::popupHighlighted(const QString & completion)
888 Cursor cur = gui_->bufferView().cursor();
889 cur.updateFlags(Update::None);
892 updateInline(cur, completion);
894 if (cur.disp_.update())
895 gui_->bufferView().processUpdateFlags(cur.disp_.update());
898 } // namespace frontend
901 #include "GuiCompleter_moc.cpp"