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) {}
50 virtual void drawDisplay(QPainter * painter,
51 QStyleOptionViewItem const & option,
52 QRect const & rect, QString const & text) const
54 // FIXME: do this more elegantly
55 docstring stltext = qstring_to_ucs4(text);
56 reverse(stltext.begin(), stltext.end());
57 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
62 class PixmapItemDelegate : public QItemDelegate {
64 explicit PixmapItemDelegate(QObject *parent = 0)
65 : QItemDelegate(parent) {}
68 void paint(QPainter *painter, const QStyleOptionViewItem &option,
69 const QModelIndex &index) const
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);
90 class GuiCompletionModel : public QAbstractListModel {
93 GuiCompletionModel(QObject * parent,
94 Inset::CompletionList const * l)
95 : QAbstractListModel(parent), list_(l) {}
103 return list_->sorted();
108 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
113 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
118 return list_->size();
122 QVariant data(const QModelIndex & index, int role) const
127 if (index.row() < 0 || index.row() >= rowCount())
130 if (role != Qt::DisplayRole && role != Qt::EditRole)
133 if (index.column() == 0) {
134 docstring const word = list_->data(index.row());
136 } else if (index.column() == 1) {
137 // get icon from cache
139 QString const name = ":" + toqstr(list_->icon(index.row()));
140 if (!QPixmapCache::find("completion" + name, scaled)) {
141 // load icon from disk
142 QPixmap p = QPixmap(name);
144 // scale it to 16x16 or smaller
145 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
146 Qt::KeepAspectRatio, Qt::SmoothTransformation);
149 QPixmapCache::insert("completion" + name, scaled);
158 Inset::CompletionList const * list_;
162 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
163 : QCompleter(parent), gui_(gui), updateLock_(0),
164 inlineVisible_(false)
166 // Setup the completion popup
167 setModel(new GuiCompletionModel(this, 0));
168 setCompletionMode(QCompleter::PopupCompletion);
172 QTreeView *listView = new QTreeView;
173 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
174 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
175 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
176 listView->setSelectionMode(QAbstractItemView::SingleSelection);
177 listView->header()->hide();
178 listView->setIndentation(0);
179 listView->setUniformRowHeights(true);
181 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
182 rtlItemDelegate_ = new RtlItemDelegate(this);
184 // create timeout timers
185 popup_timer_.setSingleShot(true);
186 inline_timer_.setSingleShot(true);
187 connect(this, SIGNAL(highlighted(const QString &)),
188 this, SLOT(popupHighlighted(const QString &)));
189 connect(this, SIGNAL(activated(const QString &)),
190 this, SLOT(popupActivated(const QString &)));
191 connect(&popup_timer_, SIGNAL(timeout()),
192 this, SLOT(showPopup()));
193 connect(&inline_timer_, SIGNAL(timeout()),
194 this, SLOT(showInline()));
198 GuiCompleter::~GuiCompleter()
204 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
206 // hijack back the tab key from the popup
207 // (which stole it from the workspace before)
208 if (e->type() == QEvent::KeyPress && popupVisible()) {
209 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
219 return QCompleter::eventFilter(watched, e);
223 bool GuiCompleter::popupPossible(Cursor const & cur) const
225 return QApplication::activeWindow()
227 && cur.inset().completionSupported(cur);
231 bool GuiCompleter::inlinePossible(Cursor const & cur) const
233 return cur.inset().inlineCompletionSupported(cur);
237 bool GuiCompleter::completionAvailable() const
239 size_t n = popup()->model()->rowCount();
241 // if there is exactly one, we have to check whether it is a
242 // real completion, i.e. longer than the current prefix.
243 if (n == 1 && completionPrefix() == currentCompletion())
250 bool GuiCompleter::popupVisible() const
252 return popup()->isVisible();
256 bool GuiCompleter::inlineVisible() const
258 // In fact using BufferView::inlineCompletionPos.empty() should be
259 // here. But unfortunately this information is not good enough
260 // because destructive operations like backspace might invalidate
261 // inlineCompletionPos. But then the completion should stay visible
262 // (i.e. reshown on the next update). Hence be keep this information
263 // in the inlineVisible_ variable.
264 return inlineVisible_;
268 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
270 // parameters which affect the completion
271 bool moved = cur != old_cursor_;
275 bool possiblePopupState = popupPossible(cur) && cursorInView;
276 bool possibleInlineState = inlinePossible(cur) && cursorInView;
278 // we moved or popup state is not ok for popup?
279 if ((moved && !keep) || !possiblePopupState)
282 // we moved or inline state is not ok for inline completion?
283 if ((moved && !keep) || !possibleInlineState)
286 // we inserted something and are in a possible popup state?
287 if (!popupVisible() && possiblePopupState && start
288 && cur.inset().automaticPopupCompletion())
289 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
291 // we inserted something and are in a possible inline completion state?
292 if (!inlineVisible() && possibleInlineState && start
293 && cur.inset().automaticInlineCompletion())
294 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
296 // update prefix if any completion is possible
297 bool modelActive = model()->rowCount() > 0;
298 if (possiblePopupState || possibleInlineState) {
302 updateAvailability();
307 void GuiCompleter::updateVisibility(bool start, bool keep)
309 Cursor cur = gui_->bufferView().cursor();
310 cur.updateFlags(Update::None);
312 updateVisibility(cur, start, keep);
314 if (cur.disp_.update())
315 gui_->bufferView().processUpdateFlags(cur.disp_.update());
319 void GuiCompleter::updatePrefix(Cursor & cur)
321 // get new prefix. Do nothing if unchanged
322 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
323 if (newPrefix == completionPrefix())
326 // value which should be kept selected
327 QString old = currentCompletion();
328 if (old.length() == 0)
329 old = last_selection_;
331 // update completer to new prefix
332 setCompletionPrefix(newPrefix);
334 // update popup because its size might have changed
338 // restore old selection
339 setCurrentCompletion(old);
341 // if popup is not empty, the new selection will
342 // be our last valid one
343 QString const & s = currentCompletion();
344 if (popupVisible() || inlineVisible()) {
348 last_selection_ = old;
351 // update inline completion because the default
352 // completion string might have changed
354 updateInline(cur, s);
358 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
360 if (!cur.inset().inlineCompletionSupported(cur))
364 docstring prefix = cur.inset().completionPrefix(cur);
365 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
367 // shorten it if necessary
368 if (lyxrc.completion_inline_dots != -1
369 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
370 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
372 // set inline completion at cursor position
373 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
374 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
375 inlineVisible_ = true;
379 void GuiCompleter::updatePopup(Cursor & cur)
381 if (!cur.inset().completionSupported(cur))
384 if (completionCount() == 0)
387 // get dimensions of completion prefix
391 cur.inset().completionPosAndDim(cur, x, y, dim);
393 // and calculate the rect of the popup
395 if (popup()->layoutDirection() == Qt::RightToLeft)
396 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
398 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
401 QTreeView * p = static_cast<QTreeView *>(popup());
402 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
408 void GuiCompleter::updateAvailability()
410 // this should really only be of interest if no completion is
411 // visible yet, i.e. especially if automatic completion is disabled.
412 if (inlineVisible() || popupVisible())
414 Cursor & cur = gui_->bufferView().cursor();
415 if (!popupPossible(cur) && !inlinePossible(cur))
418 updateModel(cur, false, false);
422 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
424 // value which should be kept selected
425 QString old = currentCompletion();
426 if (old.length() == 0)
427 old = last_selection_;
431 if (cur.inTexted()) {
432 Paragraph const & par = cur.paragraph();
434 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
435 rtl = font.isVisibleRightToLeft();
437 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
439 // turn the direction of the strings in the popup.
440 // Qt does not do that itself.
441 popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
444 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
445 setModel(new GuiCompletionModel(this, list));
447 setModelSorting(QCompleter::CaseSensitivelySortedModel);
449 setModelSorting(QCompleter::UnsortedModel);
452 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
453 if (newPrefix != completionPrefix())
454 setCompletionPrefix(newPrefix);
460 // restore old selection
461 setCurrentCompletion(old);
463 // if popup is not empty, the new selection will
464 // be our last valid one
465 if (popupVisible() || inlineVisible()) {
466 QString const & s = currentCompletion();
470 last_selection_ = old;
473 // show inline completion
475 updateInline(cur, currentCompletion());
479 void GuiCompleter::showPopup(Cursor & cur)
481 if (!popupPossible(cur))
484 updateModel(cur, true, inlineVisible());
488 void GuiCompleter::hidePopup(Cursor & cur)
491 if (popup_timer_.isActive())
494 if (!inlineVisible())
495 setModel(new GuiCompletionModel(this, 0));
499 void GuiCompleter::showInline(Cursor & cur)
501 if (!inlinePossible(cur))
504 updateModel(cur, popupVisible(), true);
508 void GuiCompleter::hideInline(Cursor & cur)
510 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
511 inlineVisible_ = false;
514 setModel(new GuiCompletionModel(this, 0));
518 void GuiCompleter::showPopup()
520 Cursor cur = gui_->bufferView().cursor();
521 cur.updateFlags(Update::None);
526 if (cur.disp_.update())
527 gui_->bufferView().processUpdateFlags(cur.disp_.update());
531 void GuiCompleter::showInline()
533 Cursor cur = gui_->bufferView().cursor();
534 cur.updateFlags(Update::None);
539 if (cur.disp_.update())
540 gui_->bufferView().processUpdateFlags(cur.disp_.update());
544 void GuiCompleter::hidePopup()
546 Cursor cur = gui_->bufferView().cursor();
547 cur.updateFlags(Update::None);
552 if (cur.disp_.update())
553 gui_->bufferView().processUpdateFlags(cur.disp_.update());
557 void GuiCompleter::hideInline()
559 Cursor cur = gui_->bufferView().cursor();
560 cur.updateFlags(Update::None);
565 if (cur.disp_.update())
566 gui_->bufferView().processUpdateFlags(cur.disp_.update());
570 void GuiCompleter::activate()
572 if (!popupVisible() && !inlineVisible())
575 popupActivated(currentCompletion());
579 void GuiCompleter::tab()
581 BufferView * bv = &gui_->bufferView();
582 Cursor cur = bv->cursor();
583 cur.updateFlags(Update::None);
585 // check that inline completion is active
586 if (!inlineVisible()) {
587 // try to activate the inline completion
588 if (cur.inset().inlineCompletionSupported(cur)) {
591 // show popup without delay because the completion was not unique
592 if (lyxrc.completion_popup_after_complete
594 && popup()->model()->rowCount() > 1)
595 popup_timer_.start(0);
600 if (!popupVisible() && cur.inset().completionSupported(cur)) {
608 // If completion is active, at least complete by one character
609 docstring prefix = cur.inset().completionPrefix(cur);
610 docstring completion = from_utf8(fromqstr(currentCompletion()));
611 if (completion.size() <= prefix.size()) {
612 // finalize completion
613 cur.inset().insertCompletion(cur, docstring(), true);
615 // hide popup and inline completion
618 updateVisibility(false, false);
621 docstring nextchar = completion.substr(prefix.size(), 1);
622 if (!cur.inset().insertCompletion(cur, nextchar, false))
626 // try to complete as far as it is unique
627 docstring longestCompletion = longestUniqueCompletion();
628 prefix = cur.inset().completionPrefix(cur);
629 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
630 cur.inset().insertCompletion(cur, postfix, false);
631 old_cursor_ = bv->cursor();
634 // show popup without delay because the completion was not unique
635 if (lyxrc.completion_popup_after_complete
637 && popup()->model()->rowCount() > 1)
638 popup_timer_.start(0);
641 if (cur.disp_.update())
642 gui_->bufferView().processUpdateFlags(cur.disp_.update());
646 QString GuiCompleter::currentCompletion() const
648 if (!popup()->selectionModel()->hasSelection())
651 // Not sure if this is bug in Qt: currentIndex() always
652 // return the first element in the list.
653 QModelIndex idx = popup()->currentIndex();
654 return popup()->model()->data(idx, Qt::EditRole).toString();
658 void GuiCompleter::setCurrentCompletion(QString const & s)
660 QAbstractItemModel const & model = *popup()->model();
661 size_t n = model.rowCount();
665 // select the first if s is empty
666 if (s.length() == 0) {
668 popup()->setCurrentIndex(model.index(0, 0));
673 // find old selection in model
675 if (modelSorting() == QCompleter::UnsortedModel) {
676 // In unsorted models, iterate through list until the s is found
677 for (i = 0; i < n; ++i) {
679 = model.data(model.index(i, 0), Qt::EditRole).toString();
684 // In sorted models, do binary search for s.
687 while (r >= l && l < int(n)) {
688 size_t mid = (r + l) / 2;
690 = model.data(model.index(mid, 0),
691 Qt::EditRole).toString();
694 // FIXME: is this really the same order that the docstring
695 // from the CompletionList has?
696 int c = s.compare(mids, Qt::CaseSensitive);
704 // middle is not far enough
711 // loop was left without finding anything
716 BOOST_ASSERT(0 <= i && i <= n);
719 // select the first if none was found
724 popup()->setCurrentIndex(model.index(i, 0));
729 size_t commonPrefix(QString const & s1, QString const & s2)
731 // find common prefix
733 size_t n1 = s1.length();
734 size_t n2 = s2.length();
735 for (j = 0; j < n1 && j < n2; ++j) {
736 if (s1.at(j) != s2.at(j))
743 docstring GuiCompleter::longestUniqueCompletion() const
745 QAbstractItemModel const & model = *popup()->model();
746 QString s = currentCompletion();
747 size_t n = model.rowCount();
749 if (modelSorting() == QCompleter::UnsortedModel) {
750 // For unsorted model we cannot do more than iteration.
751 // Iterate through the completions and cut off where s differs
752 for (size_t i = 0; i < n && s.length() > 0; ++i) {
754 = model.data(model.index(i, 0), Qt::EditRole).toString();
756 s = s.left(commonPrefix(is, s));
759 // For sorted models we can do binary search multiple times,
760 // each time to find the first string which has s not as prefix.
762 while (i < n && s.length() > 0) {
763 // find first string that does not have s as prefix
764 // via binary search in [i,n-1]
767 // get common prefix with the middle string
768 size_t mid = (r + i) / 2;
770 = model.data(model.index(mid, 0),
771 Qt::EditRole).toString();
772 size_t oldLen = s.length();
773 size_t len = commonPrefix(mids, s);
778 // middle is not far enough
781 // middle is maybe too far
784 } while (r - i > 0 && i < n);
788 return from_utf8(fromqstr(s));
792 void GuiCompleter::popupActivated(const QString & completion)
794 Cursor cur = gui_->bufferView().cursor();
795 cur.updateFlags(Update::None);
797 docstring prefix = cur.inset().completionPrefix(cur);
798 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
799 cur.inset().insertCompletion(cur, postfix, true);
803 if (cur.disp_.update())
804 gui_->bufferView().processUpdateFlags(cur.disp_.update());
808 void GuiCompleter::popupHighlighted(const QString & completion)
813 Cursor cur = gui_->bufferView().cursor();
814 cur.updateFlags(Update::None);
817 updateInline(cur, completion);
819 if (cur.disp_.update())
820 gui_->bufferView().processUpdateFlags(cur.disp_.update());
823 } // namespace frontend
826 #include "GuiCompleter_moc.cpp"