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"
18 #include "Dimension.h"
19 #include "FuncRequest.h"
23 #include "Paragraph.h"
26 #include "support/debug.h"
28 #include <QApplication>
29 #include <QAbstractListModel>
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,
107 Inset::CompletionList const * l)
108 : QAbstractListModel(parent), list_(l) {}
110 ~GuiCompletionModel()
116 return list_->sorted();
121 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
126 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
131 return list_->size();
135 QVariant data(const QModelIndex & index, int role) const
140 if (index.row() < 0 || index.row() >= rowCount())
143 if (role != Qt::DisplayRole && role != Qt::EditRole)
146 if (index.column() == 0)
147 return toqstr(list_->data(index.row()));
148 else if (index.column() == 1) {
149 // get icon from cache
151 QString const name = ":" + toqstr(list_->icon(index.row()));
152 if (!QPixmapCache::find("completion" + name, scaled)) {
153 // load icon from disk
154 QPixmap p = QPixmap(name);
156 // scale it to 16x16 or smaller
157 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
158 Qt::KeepAspectRatio, Qt::SmoothTransformation);
161 QPixmapCache::insert("completion" + name, scaled);
170 Inset::CompletionList const * list_;
174 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
175 : QCompleter(parent), gui_(gui), updateLock_(0),
176 inlineVisible_(false), popupVisible_(false),
179 // Setup the completion popup
180 setModel(new GuiCompletionModel(this, 0));
181 setCompletionMode(QCompleter::PopupCompletion);
185 QTreeView *listView = new QTreeView;
186 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
187 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
188 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
189 listView->setSelectionMode(QAbstractItemView::SingleSelection);
190 listView->header()->hide();
191 listView->setIndentation(0);
192 listView->setUniformRowHeights(true);
195 rtlItemDelegate_ = new RtlItemDelegate(this);
196 popup()->setItemDelegateForColumn(0, rtlItemDelegate_);
197 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
199 // create timeout timers
200 popup_timer_.setSingleShot(true);
201 inline_timer_.setSingleShot(true);
202 connect(this, SIGNAL(highlighted(const QString &)),
203 this, SLOT(popupHighlighted(const QString &)));
204 connect(this, SIGNAL(activated(const QString &)),
205 this, SLOT(popupActivated(const QString &)));
206 connect(&popup_timer_, SIGNAL(timeout()),
207 this, SLOT(showPopup()));
208 connect(&inline_timer_, SIGNAL(timeout()),
209 this, SLOT(showInline()));
213 GuiCompleter::~GuiCompleter()
219 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
221 // hijack back the tab key from the popup
222 // (which stole it from the workspace before)
223 if (e->type() == QEvent::KeyPress && popupVisible()) {
224 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
234 return QCompleter::eventFilter(watched, e);
238 bool GuiCompleter::popupPossible(Cursor const & cur) const
240 return QApplication::activeWindow()
242 && cur.inset().completionSupported(cur);
246 bool GuiCompleter::inlinePossible(Cursor const & cur) const
248 return cur.inset().inlineCompletionSupported(cur);
252 bool GuiCompleter::completionAvailable() const
257 size_t n = popup()->model()->rowCount();
259 // if there is exactly one, we have to check whether it is a
260 // real completion, i.e. longer than the current prefix.
261 if (n == 1 && completionPrefix() == currentCompletion())
268 bool GuiCompleter::popupVisible() const
270 return popupVisible_;
274 bool GuiCompleter::inlineVisible() const
276 // In fact using BufferView::inlineCompletionPos.empty() should be
277 // here. But unfortunately this information is not good enough
278 // because destructive operations like backspace might invalidate
279 // inlineCompletionPos. But then the completion should stay visible
280 // (i.e. reshown on the next update). Hence be keep this information
281 // in the inlineVisible_ variable.
282 return inlineVisible_;
286 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
288 // parameters which affect the completion
289 bool moved = cur != old_cursor_;
293 bool possiblePopupState = popupPossible(cur) && cursorInView;
294 bool possibleInlineState = inlinePossible(cur) && cursorInView;
296 // we moved or popup state is not ok for popup?
297 if ((moved && !keep) || !possiblePopupState)
300 // we moved or inline state is not ok for inline completion?
301 if ((moved && !keep) || !possibleInlineState)
304 // we inserted something and are in a possible popup state?
305 if (!popupVisible() && possiblePopupState && start
306 && cur.inset().automaticPopupCompletion())
307 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
309 // we inserted something and are in a possible inline completion state?
310 if (!inlineVisible() && possibleInlineState && start
311 && cur.inset().automaticInlineCompletion())
312 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
314 // update prefix if any completion is possible
315 bool modelActive = modelActive_ && model()->rowCount() > 0;
316 if (possiblePopupState || possibleInlineState) {
320 updateAvailability();
325 void GuiCompleter::updateVisibility(bool start, bool keep)
327 Cursor cur = gui_->bufferView().cursor();
328 cur.updateFlags(Update::None);
330 updateVisibility(cur, start, keep);
332 if (cur.disp_.update())
333 gui_->bufferView().processUpdateFlags(cur.disp_.update());
337 void GuiCompleter::updatePrefix(Cursor & cur)
339 // get new prefix. Do nothing if unchanged
340 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
341 if (newPrefix == completionPrefix())
344 // value which should be kept selected
345 QString old = currentCompletion();
346 if (old.length() == 0)
347 old = last_selection_;
349 // update completer to new prefix
350 setCompletionPrefix(newPrefix);
352 // update popup because its size might have changed
356 // restore old selection
357 setCurrentCompletion(old);
359 // if popup is not empty, the new selection will
360 // be our last valid one
361 QString const & s = currentCompletion();
362 if (popupVisible() || inlineVisible()) {
366 last_selection_ = old;
369 // update inline completion because the default
370 // completion string might have changed
372 updateInline(cur, s);
376 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
378 if (!cur.inset().inlineCompletionSupported(cur))
382 docstring prefix = cur.inset().completionPrefix(cur);
383 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
385 // shorten it if necessary
386 if (lyxrc.completion_inline_dots != -1
387 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
388 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
390 // set inline completion at cursor position
391 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
392 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
393 inlineVisible_ = true;
397 void GuiCompleter::updatePopup(Cursor & cur)
399 if (!cur.inset().completionSupported(cur))
402 popupVisible_ = true;
404 if (completionCount() == 0) {
405 QTimer::singleShot(0, popup(), SLOT(hide()));
409 QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
413 void GuiCompleter::asyncUpdatePopup()
415 Cursor cur = gui_->bufferView().cursor();
416 if (!cur.inset().completionSupported(cur)) {
417 popupVisible_ = false;
421 // get dimensions of completion prefix
425 cur.inset().completionPosAndDim(cur, x, y, dim);
427 // and calculate the rect of the popup
429 if (popup()->layoutDirection() == Qt::RightToLeft)
430 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
432 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
434 // Resize the columns in the popup.
435 // This should really be in the constructor. But somehow the treeview
436 // has a bad memory about it and we have to tell him again and again.
437 QTreeView * listView = static_cast<QTreeView *>(popup());
438 listView->header()->setStretchLastSection(false);
439 listView->header()->setResizeMode(0, QHeaderView::Stretch);
440 listView->header()->setResizeMode(1, QHeaderView::Fixed);
441 listView->header()->resizeSection(1, 22);
448 void GuiCompleter::updateAvailability()
450 // this should really only be of interest if no completion is
451 // visible yet, i.e. especially if automatic completion is disabled.
452 if (inlineVisible() || popupVisible())
454 Cursor & cur = gui_->bufferView().cursor();
455 if (!popupPossible(cur) && !inlinePossible(cur))
458 updateModel(cur, false, false);
462 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
464 // value which should be kept selected
465 QString old = currentCompletion();
466 if (old.length() == 0)
467 old = last_selection_;
471 if (cur.inTexted()) {
472 Paragraph const & par = cur.paragraph();
474 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
475 rtl = font.isVisibleRightToLeft();
477 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
479 // turn the direction of the strings in the popup.
480 // Qt does not do that itself.
481 rtlItemDelegate_->setEnabled(rtl);
484 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
485 setModel(new GuiCompletionModel(this, list));
488 setModelSorting(QCompleter::CaseSensitivelySortedModel);
490 setModelSorting(QCompleter::UnsortedModel);
493 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
494 if (newPrefix != completionPrefix())
495 setCompletionPrefix(newPrefix);
501 // restore old selection
502 setCurrentCompletion(old);
504 // if popup is not empty, the new selection will
505 // be our last valid one
506 if (popupVisible() || inlineVisible()) {
507 QString const & s = currentCompletion();
511 last_selection_ = old;
514 // show inline completion
516 updateInline(cur, currentCompletion());
520 void GuiCompleter::showPopup(Cursor & cur)
522 if (!popupPossible(cur))
525 updateModel(cur, true, inlineVisible());
529 void GuiCompleter::hidePopup(Cursor & cur)
531 popupVisible_ = false;
533 if (popup_timer_.isActive())
536 // hide popup asynchronously because we might be here inside of
537 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
538 // workarea which then redisplays the cursor. But the metrics are not
539 // yet up to date such that the coord cache has not all insets yet. The
540 // cursorPos methods would triggers asserts in the coord cache then.
541 QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
543 // mark that the asynchronous part will reset the model
544 if (!inlineVisible())
545 modelActive_ = false;
549 void GuiCompleter::asyncHidePopup()
552 if (!inlineVisible())
553 setModel(new GuiCompletionModel(this, 0));
557 void GuiCompleter::showInline(Cursor & cur)
559 if (!inlinePossible(cur))
562 updateModel(cur, popupVisible(), true);
566 void GuiCompleter::hideInline(Cursor & cur)
568 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
569 inlineVisible_ = false;
571 if (inline_timer_.isActive())
572 inline_timer_.stop();
574 // Trigger asynchronous part of hideInline. We might be
575 // in a dispatcher here and the setModel call might
576 // trigger focus events which is are not healthy here.
577 QTimer::singleShot(0, this, SLOT(asyncHideModel()));
579 // mark that the asynchronous part will reset the model
581 modelActive_ = false;
585 void GuiCompleter::asyncHideInline()
588 setModel(new GuiCompletionModel(this, 0));
592 void GuiCompleter::showPopup()
594 Cursor cur = gui_->bufferView().cursor();
595 cur.updateFlags(Update::None);
600 if (cur.disp_.update())
601 gui_->bufferView().processUpdateFlags(cur.disp_.update());
605 void GuiCompleter::showInline()
607 Cursor cur = gui_->bufferView().cursor();
608 cur.updateFlags(Update::None);
613 if (cur.disp_.update())
614 gui_->bufferView().processUpdateFlags(cur.disp_.update());
618 void GuiCompleter::hidePopup()
620 Cursor cur = gui_->bufferView().cursor();
621 cur.updateFlags(Update::None);
626 if (cur.disp_.update())
627 gui_->bufferView().processUpdateFlags(cur.disp_.update());
631 void GuiCompleter::hideInline()
633 Cursor cur = gui_->bufferView().cursor();
634 cur.updateFlags(Update::None);
639 if (cur.disp_.update())
640 gui_->bufferView().processUpdateFlags(cur.disp_.update());
644 void GuiCompleter::activate()
646 if (!popupVisible() && !inlineVisible())
649 popupActivated(currentCompletion());
653 void GuiCompleter::tab()
655 BufferView * bv = &gui_->bufferView();
656 Cursor cur = bv->cursor();
657 cur.updateFlags(Update::None);
659 // check that inline completion is active
660 if (!inlineVisible()) {
661 // try to activate the inline completion
662 if (cur.inset().inlineCompletionSupported(cur)) {
665 // show popup without delay because the completion was not unique
666 if (lyxrc.completion_popup_after_complete
668 && popup()->model()->rowCount() > 1)
669 popup_timer_.start(0);
674 if (!popupVisible() && cur.inset().completionSupported(cur)) {
682 // If completion is active, at least complete by one character
683 docstring prefix = cur.inset().completionPrefix(cur);
684 docstring completion = from_utf8(fromqstr(currentCompletion()));
685 if (completion.size() <= prefix.size()) {
686 // finalize completion
687 cur.inset().insertCompletion(cur, docstring(), true);
689 // hide popup and inline completion
692 updateVisibility(false, false);
695 docstring nextchar = completion.substr(prefix.size(), 1);
696 if (!cur.inset().insertCompletion(cur, nextchar, false))
700 // try to complete as far as it is unique
701 docstring longestCompletion = longestUniqueCompletion();
702 prefix = cur.inset().completionPrefix(cur);
703 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
704 cur.inset().insertCompletion(cur, postfix, false);
705 old_cursor_ = bv->cursor();
708 // show popup without delay because the completion was not unique
709 if (lyxrc.completion_popup_after_complete
711 && popup()->model()->rowCount() > 1)
712 popup_timer_.start(0);
715 if (cur.disp_.update())
716 gui_->bufferView().processUpdateFlags(cur.disp_.update());
720 QString GuiCompleter::currentCompletion() const
722 if (!popup()->selectionModel()->hasSelection())
725 // Not sure if this is bug in Qt: currentIndex() always
726 // return the first element in the list.
727 QModelIndex idx = popup()->currentIndex();
728 return popup()->model()->data(idx, Qt::EditRole).toString();
732 void GuiCompleter::setCurrentCompletion(QString const & s)
734 QAbstractItemModel const & model = *popup()->model();
735 size_t n = model.rowCount();
739 // select the first if s is empty
740 if (s.length() == 0) {
742 popup()->setCurrentIndex(model.index(0, 0));
747 // find old selection in model
749 if (modelSorting() == QCompleter::UnsortedModel) {
750 // In unsorted models, iterate through list until the s is found
751 for (i = 0; i < n; ++i) {
753 = model.data(model.index(i, 0), Qt::EditRole).toString();
758 // In sorted models, do binary search for s.
761 while (r >= l && l < int(n)) {
762 size_t mid = (r + l) / 2;
764 = model.data(model.index(mid, 0),
765 Qt::EditRole).toString();
768 // FIXME: is this really the same order that the docstring
769 // from the CompletionList has?
770 int c = s.compare(mids, Qt::CaseSensitive);
778 // middle is not far enough
785 // loop was left without finding anything
790 BOOST_ASSERT(0 <= i && i <= n);
793 // select the first if none was found
798 popup()->setCurrentIndex(model.index(i, 0));
803 size_t commonPrefix(QString const & s1, QString const & s2)
805 // find common prefix
807 size_t n1 = s1.length();
808 size_t n2 = s2.length();
809 for (j = 0; j < n1 && j < n2; ++j) {
810 if (s1.at(j) != s2.at(j))
817 docstring GuiCompleter::longestUniqueCompletion() const
819 QAbstractItemModel const & model = *popup()->model();
820 size_t n = model.rowCount();
823 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
825 if (modelSorting() == QCompleter::UnsortedModel) {
826 // For unsorted model we cannot do more than iteration.
827 // Iterate through the completions and cut off where s differs
828 for (size_t i = 0; i < n && s.length() > 0; ++i) {
830 = model.data(model.index(i, 0), Qt::EditRole).toString();
832 s = s.left(commonPrefix(is, s));
835 // For sorted models we can do binary search multiple times,
836 // each time to find the first string which has s not as prefix.
838 while (i < n && s.length() > 0) {
839 // find first string that does not have s as prefix
840 // via binary search in [i,n-1]
843 // get common prefix with the middle string
844 size_t mid = (r + i) / 2;
846 = model.data(model.index(mid, 0),
847 Qt::EditRole).toString();
848 size_t oldLen = s.length();
849 size_t len = commonPrefix(mids, s);
854 // middle is not far enough
857 // middle is maybe too far
860 } while (r - i > 0 && i < n);
864 return from_utf8(fromqstr(s));
868 void GuiCompleter::popupActivated(const QString & completion)
870 Cursor cur = gui_->bufferView().cursor();
871 cur.updateFlags(Update::None);
873 docstring prefix = cur.inset().completionPrefix(cur);
874 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
875 cur.inset().insertCompletion(cur, postfix, true);
879 if (cur.disp_.update())
880 gui_->bufferView().processUpdateFlags(cur.disp_.update());
884 void GuiCompleter::popupHighlighted(const QString & completion)
889 Cursor cur = gui_->bufferView().cursor();
890 cur.updateFlags(Update::None);
893 updateInline(cur, completion);
895 if (cur.disp_.update())
896 gui_->bufferView().processUpdateFlags(cur.disp_.update());
899 } // namespace frontend
902 #include "GuiCompleter_moc.cpp"