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)
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
253 size_t n = popup()->model()->rowCount();
255 // if there is exactly one, we have to check whether it is a
256 // real completion, i.e. longer than the current prefix.
257 if (n == 1 && completionPrefix() == currentCompletion())
264 bool GuiCompleter::popupVisible() const
266 return popupVisible_;
270 bool GuiCompleter::inlineVisible() const
272 // In fact using BufferView::inlineCompletionPos.empty() should be
273 // here. But unfortunately this information is not good enough
274 // because destructive operations like backspace might invalidate
275 // inlineCompletionPos. But then the completion should stay visible
276 // (i.e. reshown on the next update). Hence be keep this information
277 // in the inlineVisible_ variable.
278 return inlineVisible_;
282 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
284 // parameters which affect the completion
285 bool moved = cur != old_cursor_;
289 bool possiblePopupState = popupPossible(cur) && cursorInView;
290 bool possibleInlineState = inlinePossible(cur) && cursorInView;
292 // we moved or popup state is not ok for popup?
293 if ((moved && !keep) || !possiblePopupState)
296 // we moved or inline state is not ok for inline completion?
297 if ((moved && !keep) || !possibleInlineState)
300 // we inserted something and are in a possible popup state?
301 if (!popupVisible() && possiblePopupState && start
302 && cur.inset().automaticPopupCompletion())
303 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
305 // we inserted something and are in a possible inline completion state?
306 if (!inlineVisible() && possibleInlineState && start
307 && cur.inset().automaticInlineCompletion())
308 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
310 // update prefix if any completion is possible
311 bool modelActive = model()->rowCount() > 0;
312 if (possiblePopupState || possibleInlineState) {
316 updateAvailability();
321 void GuiCompleter::updateVisibility(bool start, bool keep)
323 Cursor cur = gui_->bufferView().cursor();
324 cur.updateFlags(Update::None);
326 updateVisibility(cur, start, keep);
328 if (cur.disp_.update())
329 gui_->bufferView().processUpdateFlags(cur.disp_.update());
333 void GuiCompleter::updatePrefix(Cursor & cur)
335 // get new prefix. Do nothing if unchanged
336 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
337 if (newPrefix == completionPrefix())
340 // value which should be kept selected
341 QString old = currentCompletion();
342 if (old.length() == 0)
343 old = last_selection_;
345 // update completer to new prefix
346 setCompletionPrefix(newPrefix);
348 // update popup because its size might have changed
352 // restore old selection
353 setCurrentCompletion(old);
355 // if popup is not empty, the new selection will
356 // be our last valid one
357 QString const & s = currentCompletion();
358 if (popupVisible() || inlineVisible()) {
362 last_selection_ = old;
365 // update inline completion because the default
366 // completion string might have changed
368 updateInline(cur, s);
372 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
374 if (!cur.inset().inlineCompletionSupported(cur))
378 docstring prefix = cur.inset().completionPrefix(cur);
379 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
381 // shorten it if necessary
382 if (lyxrc.completion_inline_dots != -1
383 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
384 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
386 // set inline completion at cursor position
387 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
388 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
389 inlineVisible_ = true;
393 void GuiCompleter::updatePopup(Cursor & cur)
395 if (!cur.inset().completionSupported(cur))
398 popupVisible_ = true;
400 if (completionCount() == 0) {
401 QTimer::singleShot(0, popup(), SLOT(hide()));
405 // show asynchronously to avoid lookups before the metrics
406 // have been computed. This can happen because we might be in
407 // the middle of a dispatch.
408 QTimer::singleShot(0, this, SLOT(asyncCompletePopup()));
412 void GuiCompleter::asyncCompletePopup()
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 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
484 setModel(new GuiCompletionModel(this, list));
486 setModelSorting(QCompleter::CaseSensitivelySortedModel);
488 setModelSorting(QCompleter::UnsortedModel);
491 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
492 if (newPrefix != completionPrefix())
493 setCompletionPrefix(newPrefix);
499 // restore old selection
500 setCurrentCompletion(old);
502 // if popup is not empty, the new selection will
503 // be our last valid one
504 if (popupVisible() || inlineVisible()) {
505 QString const & s = currentCompletion();
509 last_selection_ = old;
512 // show inline completion
514 updateInline(cur, currentCompletion());
518 void GuiCompleter::showPopup(Cursor & cur)
520 if (!popupPossible(cur))
523 updateModel(cur, true, inlineVisible());
527 void GuiCompleter::hidePopup(Cursor & cur)
529 popupVisible_ = false;
531 // hide popup asynchronously because we might be here inside of
532 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
533 // workarea which then redisplays the cursor. But the metrics are not
534 // yet up to date such that the coord cache has not all insets yet. The
535 // cursorPos methods would triggers asserts in the coord cache then.
536 QTimer::singleShot(0, popup(), SLOT(hide()));
538 if (popup_timer_.isActive())
541 if (!inlineVisible())
542 setModel(new GuiCompletionModel(this, 0));
546 void GuiCompleter::showInline(Cursor & cur)
548 if (!inlinePossible(cur))
551 updateModel(cur, popupVisible(), true);
555 void GuiCompleter::hideInline(Cursor & cur)
557 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
558 inlineVisible_ = false;
560 if (inline_timer_.isActive())
561 inline_timer_.stop();
564 setModel(new GuiCompletionModel(this, 0));
568 void GuiCompleter::showPopup()
570 Cursor cur = gui_->bufferView().cursor();
571 cur.updateFlags(Update::None);
576 if (cur.disp_.update())
577 gui_->bufferView().processUpdateFlags(cur.disp_.update());
581 void GuiCompleter::showInline()
583 Cursor cur = gui_->bufferView().cursor();
584 cur.updateFlags(Update::None);
589 if (cur.disp_.update())
590 gui_->bufferView().processUpdateFlags(cur.disp_.update());
594 void GuiCompleter::hidePopup()
596 Cursor cur = gui_->bufferView().cursor();
597 cur.updateFlags(Update::None);
602 if (cur.disp_.update())
603 gui_->bufferView().processUpdateFlags(cur.disp_.update());
607 void GuiCompleter::hideInline()
609 Cursor cur = gui_->bufferView().cursor();
610 cur.updateFlags(Update::None);
615 if (cur.disp_.update())
616 gui_->bufferView().processUpdateFlags(cur.disp_.update());
620 void GuiCompleter::activate()
622 if (!popupVisible() && !inlineVisible())
625 popupActivated(currentCompletion());
629 void GuiCompleter::tab()
631 BufferView * bv = &gui_->bufferView();
632 Cursor cur = bv->cursor();
633 cur.updateFlags(Update::None);
635 // check that inline completion is active
636 if (!inlineVisible()) {
637 // try to activate the inline completion
638 if (cur.inset().inlineCompletionSupported(cur)) {
641 // show popup without delay because the completion was not unique
642 if (lyxrc.completion_popup_after_complete
644 && popup()->model()->rowCount() > 1)
645 popup_timer_.start(0);
650 if (!popupVisible() && cur.inset().completionSupported(cur)) {
658 // If completion is active, at least complete by one character
659 docstring prefix = cur.inset().completionPrefix(cur);
660 docstring completion = from_utf8(fromqstr(currentCompletion()));
661 if (completion.size() <= prefix.size()) {
662 // finalize completion
663 cur.inset().insertCompletion(cur, docstring(), true);
665 // hide popup and inline completion
668 updateVisibility(false, false);
671 docstring nextchar = completion.substr(prefix.size(), 1);
672 if (!cur.inset().insertCompletion(cur, nextchar, false))
676 // try to complete as far as it is unique
677 docstring longestCompletion = longestUniqueCompletion();
678 prefix = cur.inset().completionPrefix(cur);
679 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
680 cur.inset().insertCompletion(cur, postfix, false);
681 old_cursor_ = bv->cursor();
684 // show popup without delay because the completion was not unique
685 if (lyxrc.completion_popup_after_complete
687 && popup()->model()->rowCount() > 1)
688 popup_timer_.start(0);
691 if (cur.disp_.update())
692 gui_->bufferView().processUpdateFlags(cur.disp_.update());
696 QString GuiCompleter::currentCompletion() const
698 if (!popup()->selectionModel()->hasSelection())
701 // Not sure if this is bug in Qt: currentIndex() always
702 // return the first element in the list.
703 QModelIndex idx = popup()->currentIndex();
704 return popup()->model()->data(idx, Qt::EditRole).toString();
708 void GuiCompleter::setCurrentCompletion(QString const & s)
710 QAbstractItemModel const & model = *popup()->model();
711 size_t n = model.rowCount();
715 // select the first if s is empty
716 if (s.length() == 0) {
718 popup()->setCurrentIndex(model.index(0, 0));
723 // find old selection in model
725 if (modelSorting() == QCompleter::UnsortedModel) {
726 // In unsorted models, iterate through list until the s is found
727 for (i = 0; i < n; ++i) {
729 = model.data(model.index(i, 0), Qt::EditRole).toString();
734 // In sorted models, do binary search for s.
737 while (r >= l && l < int(n)) {
738 size_t mid = (r + l) / 2;
740 = model.data(model.index(mid, 0),
741 Qt::EditRole).toString();
744 // FIXME: is this really the same order that the docstring
745 // from the CompletionList has?
746 int c = s.compare(mids, Qt::CaseSensitive);
754 // middle is not far enough
761 // loop was left without finding anything
766 BOOST_ASSERT(0 <= i && i <= n);
769 // select the first if none was found
774 popup()->setCurrentIndex(model.index(i, 0));
779 size_t commonPrefix(QString const & s1, QString const & s2)
781 // find common prefix
783 size_t n1 = s1.length();
784 size_t n2 = s2.length();
785 for (j = 0; j < n1 && j < n2; ++j) {
786 if (s1.at(j) != s2.at(j))
793 docstring GuiCompleter::longestUniqueCompletion() const
795 QAbstractItemModel const & model = *popup()->model();
796 size_t n = model.rowCount();
799 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
801 if (modelSorting() == QCompleter::UnsortedModel) {
802 // For unsorted model we cannot do more than iteration.
803 // Iterate through the completions and cut off where s differs
804 for (size_t i = 0; i < n && s.length() > 0; ++i) {
806 = model.data(model.index(i, 0), Qt::EditRole).toString();
808 s = s.left(commonPrefix(is, s));
811 // For sorted models we can do binary search multiple times,
812 // each time to find the first string which has s not as prefix.
814 while (i < n && s.length() > 0) {
815 // find first string that does not have s as prefix
816 // via binary search in [i,n-1]
819 // get common prefix with the middle string
820 size_t mid = (r + i) / 2;
822 = model.data(model.index(mid, 0),
823 Qt::EditRole).toString();
824 size_t oldLen = s.length();
825 size_t len = commonPrefix(mids, s);
830 // middle is not far enough
833 // middle is maybe too far
836 } while (r - i > 0 && i < n);
840 return from_utf8(fromqstr(s));
844 void GuiCompleter::popupActivated(const QString & completion)
846 Cursor cur = gui_->bufferView().cursor();
847 cur.updateFlags(Update::None);
849 docstring prefix = cur.inset().completionPrefix(cur);
850 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
851 cur.inset().insertCompletion(cur, postfix, true);
855 if (cur.disp_.update())
856 gui_->bufferView().processUpdateFlags(cur.disp_.update());
860 void GuiCompleter::popupHighlighted(const QString & completion)
865 Cursor cur = gui_->bufferView().cursor();
866 cur.updateFlags(Update::None);
869 updateInline(cur, completion);
871 if (cur.disp_.update())
872 gui_->bufferView().processUpdateFlags(cur.disp_.update());
875 } // namespace frontend
878 #include "GuiCompleter_moc.cpp"