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/assert.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 RtlItemDelegate : public QItemDelegate
48 explicit RtlItemDelegate(QObject * parent)
49 : QItemDelegate(parent), enabled_(false)
52 void setEnabled(bool enabled = true)
58 void drawDisplay(QPainter * painter,
59 QStyleOptionViewItem const & option,
60 QRect const & rect, QString const & text) const
63 QItemDelegate::drawDisplay(painter, option, rect, text);
67 // FIXME: do this more elegantly
68 docstring stltext = qstring_to_ucs4(text);
69 reverse(stltext.begin(), stltext.end());
70 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
78 class PixmapItemDelegate : public QItemDelegate
81 explicit PixmapItemDelegate(QObject * parent)
82 : QItemDelegate(parent)
86 void paint(QPainter *painter, const QStyleOptionViewItem &option,
87 const QModelIndex &index) const
89 QStyleOptionViewItem opt = setOptions(index, option);
90 QVariant value = index.data(Qt::DisplayRole);
91 QPixmap pixmap = qvariant_cast<QPixmap>(value);
95 drawBackground(painter, opt, index);
96 if (!pixmap.isNull()) {
97 const QSize size = pixmap.size();
98 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
99 option.rect.top() + (option.rect.height() - size.height()) / 2,
102 drawFocus(painter, opt, option.rect);
108 class GuiCompletionModel : public QAbstractListModel
112 GuiCompletionModel(QObject * parent, CompletionList const * l)
113 : QAbstractListModel(parent), list_(l)
116 ~GuiCompletionModel() { delete list_; }
121 return list_->sorted();
125 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
130 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
135 return list_->size();
139 QVariant data(const QModelIndex & index, int role) const
144 if (index.row() < 0 || index.row() >= rowCount())
147 if (role != Qt::DisplayRole && role != Qt::EditRole)
150 if (index.column() == 0)
151 return toqstr(list_->data(index.row()));
153 if (index.column() == 1) {
154 // get icon from cache
156 QString const name = ":" + toqstr(list_->icon(index.row()));
157 if (!QPixmapCache::find("completion" + name, scaled)) {
158 // load icon from disk
159 QPixmap p = QPixmap(name);
161 // scale it to 16x16 or smaller
162 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
163 Qt::KeepAspectRatio, Qt::SmoothTransformation);
166 QPixmapCache::insert("completion" + name, scaled);
175 CompletionList const * list_;
179 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
180 : QCompleter(parent), gui_(gui), updateLock_(0),
181 inlineVisible_(false), popupVisible_(false),
184 // Setup the completion popup
185 setModel(new GuiCompletionModel(this, 0));
186 setCompletionMode(QCompleter::PopupCompletion);
190 QTreeView *listView = new QTreeView;
191 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
192 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
193 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
194 listView->setSelectionMode(QAbstractItemView::SingleSelection);
195 listView->header()->hide();
196 listView->setIndentation(0);
197 listView->setUniformRowHeights(true);
200 rtlItemDelegate_ = new RtlItemDelegate(this);
201 popup()->setItemDelegateForColumn(0, rtlItemDelegate_);
202 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
204 // create timeout timers
205 popup_timer_.setSingleShot(true);
206 inline_timer_.setSingleShot(true);
207 connect(this, SIGNAL(highlighted(const QString &)),
208 this, SLOT(popupHighlighted(const QString &)));
209 connect(this, SIGNAL(activated(const QString &)),
210 this, SLOT(popupActivated(const QString &)));
211 connect(&popup_timer_, SIGNAL(timeout()),
212 this, SLOT(showPopup()));
213 connect(&inline_timer_, SIGNAL(timeout()),
214 this, SLOT(showInline()));
218 GuiCompleter::~GuiCompleter()
224 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
226 // hijack back the tab key from the popup
227 // (which stole it from the workspace before)
228 if (e->type() == QEvent::KeyPress && popupVisible()) {
229 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
239 return QCompleter::eventFilter(watched, e);
243 bool GuiCompleter::popupPossible(Cursor const & cur) const
245 return QApplication::activeWindow()
247 && cur.inset().completionSupported(cur);
251 bool GuiCompleter::inlinePossible(Cursor const & cur) const
253 return cur.inset().inlineCompletionSupported(cur);
257 bool GuiCompleter::completionAvailable() const
262 size_t n = popup()->model()->rowCount();
264 // if there is exactly one, we have to check whether it is a
265 // real completion, i.e. longer than the current prefix.
266 if (n == 1 && completionPrefix() == currentCompletion())
273 bool GuiCompleter::popupVisible() const
275 return popupVisible_;
279 bool GuiCompleter::inlineVisible() const
281 // In fact using BufferView::inlineCompletionPos.empty() should be
282 // here. But unfortunately this information is not good enough
283 // because destructive operations like backspace might invalidate
284 // inlineCompletionPos. But then the completion should stay visible
285 // (i.e. reshown on the next update). Hence be keep this information
286 // in the inlineVisible_ variable.
287 return inlineVisible_;
291 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
293 // parameters which affect the completion
294 bool moved = cur != old_cursor_;
298 bool possiblePopupState = popupPossible(cur) && cursorInView;
299 bool possibleInlineState = inlinePossible(cur) && cursorInView;
301 // we moved or popup state is not ok for popup?
302 if ((moved && !keep) || !possiblePopupState)
305 // we moved or inline state is not ok for inline completion?
306 if ((moved && !keep) || !possibleInlineState)
309 // we inserted something and are in a possible popup state?
310 if (!popupVisible() && possiblePopupState && start
311 && cur.inset().automaticPopupCompletion())
312 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
314 // we inserted something and are in a possible inline completion state?
315 if (!inlineVisible() && possibleInlineState && start
316 && cur.inset().automaticInlineCompletion())
317 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
319 // update prefix if any completion is possible
320 bool modelActive = modelActive_ && model()->rowCount() > 0;
321 if (possiblePopupState || possibleInlineState) {
325 updateAvailability();
330 void GuiCompleter::updateVisibility(bool start, bool keep)
332 Cursor cur = gui_->bufferView().cursor();
333 cur.updateFlags(Update::None);
335 updateVisibility(cur, start, keep);
337 if (cur.disp_.update())
338 gui_->bufferView().processUpdateFlags(cur.disp_.update());
342 void GuiCompleter::updatePrefix(Cursor & cur)
344 // get new prefix. Do nothing if unchanged
345 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
346 if (newPrefix == completionPrefix())
349 // value which should be kept selected
350 QString old = currentCompletion();
351 if (old.length() == 0)
352 old = last_selection_;
354 // update completer to new prefix
355 setCompletionPrefix(newPrefix);
357 // update popup because its size might have changed
361 // restore old selection
362 setCurrentCompletion(old);
364 // if popup is not empty, the new selection will
365 // be our last valid one
366 QString const & s = currentCompletion();
367 if (popupVisible() || inlineVisible()) {
371 last_selection_ = old;
374 // update inline completion because the default
375 // completion string might have changed
377 updateInline(cur, s);
381 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
383 if (!cur.inset().inlineCompletionSupported(cur))
387 docstring prefix = cur.inset().completionPrefix(cur);
388 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
390 // shorten it if necessary
391 if (lyxrc.completion_inline_dots != -1
392 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
393 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
395 // set inline completion at cursor position
396 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
397 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
398 inlineVisible_ = true;
402 void GuiCompleter::updatePopup(Cursor & cur)
404 if (!cur.inset().completionSupported(cur))
407 popupVisible_ = true;
409 if (completionCount() == 0) {
410 QTimer::singleShot(0, popup(), SLOT(hide()));
414 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
418 void GuiCompleter::asyncUpdatePopup()
420 Cursor cur = gui_->bufferView().cursor();
421 if (!cur.inset().completionSupported(cur)) {
422 popupVisible_ = false;
426 // get dimensions of completion prefix
430 cur.inset().completionPosAndDim(cur, x, y, dim);
432 // and calculate the rect of the popup
434 if (popup()->layoutDirection() == Qt::RightToLeft)
435 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
437 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
439 // Resize the columns in the popup.
440 // This should really be in the constructor. But somehow the treeview
441 // has a bad memory about it and we have to tell him again and again.
442 QTreeView * listView = static_cast<QTreeView *>(popup());
443 listView->header()->setStretchLastSection(false);
444 listView->header()->setResizeMode(0, QHeaderView::Stretch);
445 listView->header()->setResizeMode(1, QHeaderView::Fixed);
446 listView->header()->resizeSection(1, 22);
453 void GuiCompleter::updateAvailability()
455 // this should really only be of interest if no completion is
456 // visible yet, i.e. especially if automatic completion is disabled.
457 if (inlineVisible() || popupVisible())
459 Cursor & cur = gui_->bufferView().cursor();
460 if (!popupPossible(cur) && !inlinePossible(cur))
463 updateModel(cur, false, false);
467 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
469 // value which should be kept selected
470 QString old = currentCompletion();
471 if (old.length() == 0)
472 old = last_selection_;
476 if (cur.inTexted()) {
477 Paragraph const & par = cur.paragraph();
479 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
480 rtl = font.isVisibleRightToLeft();
482 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
484 // turn the direction of the strings in the popup.
485 // Qt does not do that itself.
486 rtlItemDelegate_->setEnabled(rtl);
489 CompletionList const * list = cur.inset().createCompletionList(cur);
490 setModel(new GuiCompletionModel(this, list));
493 setModelSorting(QCompleter::CaseSensitivelySortedModel);
495 setModelSorting(QCompleter::UnsortedModel);
498 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
499 if (newPrefix != completionPrefix())
500 setCompletionPrefix(newPrefix);
506 // restore old selection
507 setCurrentCompletion(old);
509 // if popup is not empty, the new selection will
510 // be our last valid one
511 if (popupVisible() || inlineVisible()) {
512 QString const & s = currentCompletion();
516 last_selection_ = old;
519 // show inline completion
521 updateInline(cur, currentCompletion());
525 void GuiCompleter::showPopup(Cursor & cur)
527 if (!popupPossible(cur))
530 updateModel(cur, true, inlineVisible());
534 void GuiCompleter::hidePopup(Cursor &)
536 popupVisible_ = false;
538 if (popup_timer_.isActive())
541 // hide popup asynchronously because we might be here inside of
542 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
543 // workarea which then redisplays the cursor. But the metrics are not
544 // yet up to date such that the coord cache has not all insets yet. The
545 // cursorPos methods would triggers asserts in the coord cache then.
546 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
548 // mark that the asynchronous part will reset the model
549 if (!inlineVisible())
550 modelActive_ = false;
554 void GuiCompleter::asyncHidePopup()
557 if (!inlineVisible())
558 setModel(new GuiCompletionModel(this, 0));
562 void GuiCompleter::showInline(Cursor & cur)
564 if (!inlinePossible(cur))
567 updateModel(cur, popupVisible(), true);
571 void GuiCompleter::hideInline(Cursor & cur)
573 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
574 inlineVisible_ = false;
576 if (inline_timer_.isActive())
577 inline_timer_.stop();
579 // Trigger asynchronous part of hideInline. We might be
580 // in a dispatcher here and the setModel call might
581 // trigger focus events which is are not healthy here.
582 QTimer::singleShot(0, this, SLOT(asyncHideInline()));
584 // mark that the asynchronous part will reset the model
586 modelActive_ = false;
590 void GuiCompleter::asyncHideInline()
593 setModel(new GuiCompletionModel(this, 0));
597 void GuiCompleter::showPopup()
599 Cursor cur = gui_->bufferView().cursor();
600 cur.updateFlags(Update::None);
605 if (cur.disp_.update())
606 gui_->bufferView().processUpdateFlags(cur.disp_.update());
610 void GuiCompleter::showInline()
612 Cursor cur = gui_->bufferView().cursor();
613 cur.updateFlags(Update::None);
618 if (cur.disp_.update())
619 gui_->bufferView().processUpdateFlags(cur.disp_.update());
623 void GuiCompleter::hidePopup()
625 Cursor cur = gui_->bufferView().cursor();
626 cur.updateFlags(Update::None);
631 if (cur.disp_.update())
632 gui_->bufferView().processUpdateFlags(cur.disp_.update());
636 void GuiCompleter::hideInline()
638 Cursor cur = gui_->bufferView().cursor();
639 cur.updateFlags(Update::None);
644 if (cur.disp_.update())
645 gui_->bufferView().processUpdateFlags(cur.disp_.update());
649 void GuiCompleter::activate()
651 if (!popupVisible() && !inlineVisible())
654 popupActivated(currentCompletion());
658 void GuiCompleter::tab()
660 BufferView * bv = &gui_->bufferView();
661 Cursor cur = bv->cursor();
662 cur.updateFlags(Update::None);
664 // check that inline completion is active
665 if (!inlineVisible()) {
666 // try to activate the inline completion
667 if (cur.inset().inlineCompletionSupported(cur)) {
670 // show popup without delay because the completion was not unique
671 if (lyxrc.completion_popup_after_complete
673 && popup()->model()->rowCount() > 1)
674 popup_timer_.start(0);
679 if (!popupVisible() && cur.inset().completionSupported(cur)) {
687 // If completion is active, at least complete by one character
688 docstring prefix = cur.inset().completionPrefix(cur);
689 docstring completion = from_utf8(fromqstr(currentCompletion()));
690 if (completion.size() <= prefix.size()) {
691 // finalize completion
692 cur.inset().insertCompletion(cur, docstring(), true);
694 // hide popup and inline completion
697 updateVisibility(false, false);
700 docstring nextchar = completion.substr(prefix.size(), 1);
701 if (!cur.inset().insertCompletion(cur, nextchar, false))
705 // try to complete as far as it is unique
706 docstring longestCompletion = longestUniqueCompletion();
707 prefix = cur.inset().completionPrefix(cur);
708 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
709 cur.inset().insertCompletion(cur, postfix, false);
710 old_cursor_ = bv->cursor();
713 // show popup without delay because the completion was not unique
714 if (lyxrc.completion_popup_after_complete
716 && popup()->model()->rowCount() > 1)
717 popup_timer_.start(0);
720 if (cur.disp_.update())
721 gui_->bufferView().processUpdateFlags(cur.disp_.update());
725 QString GuiCompleter::currentCompletion() const
727 if (!popup()->selectionModel()->hasSelection())
730 // Not sure if this is bug in Qt: currentIndex() always
731 // return the first element in the list.
732 QModelIndex idx = popup()->currentIndex();
733 return popup()->model()->data(idx, Qt::EditRole).toString();
737 void GuiCompleter::setCurrentCompletion(QString const & s)
739 QAbstractItemModel const & model = *popup()->model();
740 size_t n = model.rowCount();
744 // select the first if s is empty
745 if (s.length() == 0) {
747 popup()->setCurrentIndex(model.index(0, 0));
752 // find old selection in model
754 if (modelSorting() == QCompleter::UnsortedModel) {
755 // In unsorted models, iterate through list until the s is found
756 for (i = 0; i < n; ++i) {
758 = model.data(model.index(i, 0), Qt::EditRole).toString();
763 // In sorted models, do binary search for s.
766 while (r >= l && l < int(n)) {
767 size_t mid = (r + l) / 2;
769 = model.data(model.index(mid, 0),
770 Qt::EditRole).toString();
773 // FIXME: is this really the same order that the docstring
774 // from the CompletionList has?
775 int c = s.compare(mids, Qt::CaseSensitive);
783 // middle is not far enough
790 // loop was left without finding anything
795 LASSERT(i <= n, /**/);
798 // select the first if none was found
803 popup()->setCurrentIndex(model.index(i, 0));
808 size_t commonPrefix(QString const & s1, QString const & s2)
810 // find common prefix
812 size_t n1 = s1.length();
813 size_t n2 = s2.length();
814 for (j = 0; j < n1 && j < n2; ++j) {
815 if (s1.at(j) != s2.at(j))
822 docstring GuiCompleter::longestUniqueCompletion() const
824 QAbstractItemModel const & model = *popup()->model();
825 size_t n = model.rowCount();
828 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
830 if (modelSorting() == QCompleter::UnsortedModel) {
831 // For unsorted model we cannot do more than iteration.
832 // Iterate through the completions and cut off where s differs
833 for (size_t i = 0; i < n && s.length() > 0; ++i) {
835 = model.data(model.index(i, 0), Qt::EditRole).toString();
837 s = s.left(commonPrefix(is, s));
840 // For sorted models we can do binary search multiple times,
841 // each time to find the first string which has s not as prefix.
843 while (i < n && s.length() > 0) {
844 // find first string that does not have s as prefix
845 // via binary search in [i,n-1]
848 // get common prefix with the middle string
849 size_t mid = (r + i) / 2;
851 = model.data(model.index(mid, 0),
852 Qt::EditRole).toString();
853 size_t oldLen = s.length();
854 size_t len = commonPrefix(mids, s);
859 // middle is not far enough
862 // middle is maybe too far
865 } while (r - i > 0 && i < n);
869 return from_utf8(fromqstr(s));
873 void GuiCompleter::popupActivated(const QString & completion)
875 Cursor cur = gui_->bufferView().cursor();
876 cur.updateFlags(Update::None);
878 docstring prefix = cur.inset().completionPrefix(cur);
879 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
880 cur.inset().insertCompletion(cur, postfix, true);
884 if (cur.disp_.update())
885 gui_->bufferView().processUpdateFlags(cur.disp_.update());
889 void GuiCompleter::popupHighlighted(const QString & completion)
894 Cursor cur = gui_->bufferView().cursor();
895 cur.updateFlags(Update::None);
898 updateInline(cur, completion);
900 if (cur.disp_.update())
901 gui_->bufferView().processUpdateFlags(cur.disp_.update());
904 } // namespace frontend
907 #include "GuiCompleter_moc.cpp"