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) {}
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 return QItemDelegate::drawDisplay(painter, option, rect, text);
62 // FIXME: do this more elegantly
63 docstring stltext = qstring_to_ucs4(text);
64 reverse(stltext.begin(), stltext.end());
65 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
73 class PixmapItemDelegate : public QItemDelegate {
75 explicit PixmapItemDelegate(QObject *parent = 0)
76 : QItemDelegate(parent) {}
79 void paint(QPainter *painter, const QStyleOptionViewItem &option,
80 const QModelIndex &index) const
82 QStyleOptionViewItem opt = setOptions(index, option);
83 QVariant value = index.data(Qt::DisplayRole);
84 QPixmap pixmap = qvariant_cast<QPixmap>(value);
88 drawBackground(painter, opt, index);
89 if (!pixmap.isNull()) {
90 const QSize size = pixmap.size();
91 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
92 option.rect.top() + (option.rect.height() - size.height()) / 2,
95 drawFocus(painter, opt, option.rect);
101 class GuiCompletionModel : public QAbstractListModel {
104 GuiCompletionModel(QObject * parent,
105 Inset::CompletionList const * l)
106 : QAbstractListModel(parent), list_(l) {}
108 ~GuiCompletionModel()
114 return list_->sorted();
119 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
124 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
129 return list_->size();
133 QVariant data(const QModelIndex & index, int role) const
138 if (index.row() < 0 || index.row() >= rowCount())
141 if (role != Qt::DisplayRole && role != Qt::EditRole)
144 if (index.column() == 0)
145 return toqstr(list_->data(index.row()));
146 else if (index.column() == 1) {
147 // get icon from cache
149 QString const name = ":" + toqstr(list_->icon(index.row()));
150 if (!QPixmapCache::find("completion" + name, scaled)) {
151 // load icon from disk
152 QPixmap p = QPixmap(name);
154 // scale it to 16x16 or smaller
155 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
156 Qt::KeepAspectRatio, Qt::SmoothTransformation);
159 QPixmapCache::insert("completion" + name, scaled);
168 Inset::CompletionList const * list_;
172 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
173 : QCompleter(parent), gui_(gui), updateLock_(0),
174 inlineVisible_(false)
176 // Setup the completion popup
177 setModel(new GuiCompletionModel(this, 0));
178 setCompletionMode(QCompleter::PopupCompletion);
182 QTreeView *listView = new QTreeView;
183 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
184 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
185 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
186 listView->setSelectionMode(QAbstractItemView::SingleSelection);
187 listView->header()->hide();
188 listView->setIndentation(0);
189 listView->setUniformRowHeights(true);
191 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
192 rtlItemDelegate_ = new RtlItemDelegate(this);
193 popup()->setItemDelegateForColumn(0, rtlItemDelegate_);
195 // create timeout timers
196 popup_timer_.setSingleShot(true);
197 inline_timer_.setSingleShot(true);
198 connect(this, SIGNAL(highlighted(const QString &)),
199 this, SLOT(popupHighlighted(const QString &)));
200 connect(this, SIGNAL(activated(const QString &)),
201 this, SLOT(popupActivated(const QString &)));
202 connect(&popup_timer_, SIGNAL(timeout()),
203 this, SLOT(showPopup()));
204 connect(&inline_timer_, SIGNAL(timeout()),
205 this, SLOT(showInline()));
209 GuiCompleter::~GuiCompleter()
215 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
217 // hijack back the tab key from the popup
218 // (which stole it from the workspace before)
219 if (e->type() == QEvent::KeyPress && popupVisible()) {
220 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
230 return QCompleter::eventFilter(watched, e);
234 bool GuiCompleter::popupPossible(Cursor const & cur) const
236 return QApplication::activeWindow()
238 && cur.inset().completionSupported(cur);
242 bool GuiCompleter::inlinePossible(Cursor const & cur) const
244 return cur.inset().inlineCompletionSupported(cur);
248 bool GuiCompleter::completionAvailable() const
250 size_t n = popup()->model()->rowCount();
252 // if there is exactly one, we have to check whether it is a
253 // real completion, i.e. longer than the current prefix.
254 if (n == 1 && completionPrefix() == currentCompletion())
261 bool GuiCompleter::popupVisible() const
263 return popup()->isVisible();
267 bool GuiCompleter::inlineVisible() const
269 // In fact using BufferView::inlineCompletionPos.empty() should be
270 // here. But unfortunately this information is not good enough
271 // because destructive operations like backspace might invalidate
272 // inlineCompletionPos. But then the completion should stay visible
273 // (i.e. reshown on the next update). Hence be keep this information
274 // in the inlineVisible_ variable.
275 return inlineVisible_;
279 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
281 // parameters which affect the completion
282 bool moved = cur != old_cursor_;
286 bool possiblePopupState = popupPossible(cur) && cursorInView;
287 bool possibleInlineState = inlinePossible(cur) && cursorInView;
289 // we moved or popup state is not ok for popup?
290 if ((moved && !keep) || !possiblePopupState)
293 // we moved or inline state is not ok for inline completion?
294 if ((moved && !keep) || !possibleInlineState)
297 // we inserted something and are in a possible popup state?
298 if (!popupVisible() && possiblePopupState && start
299 && cur.inset().automaticPopupCompletion())
300 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
302 // we inserted something and are in a possible inline completion state?
303 if (!inlineVisible() && possibleInlineState && start
304 && cur.inset().automaticInlineCompletion())
305 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
307 // update prefix if any completion is possible
308 bool modelActive = model()->rowCount() > 0;
309 if (possiblePopupState || possibleInlineState) {
313 updateAvailability();
318 void GuiCompleter::updateVisibility(bool start, bool keep)
320 Cursor cur = gui_->bufferView().cursor();
321 cur.updateFlags(Update::None);
323 updateVisibility(cur, start, keep);
325 if (cur.disp_.update())
326 gui_->bufferView().processUpdateFlags(cur.disp_.update());
330 void GuiCompleter::updatePrefix(Cursor & cur)
332 // get new prefix. Do nothing if unchanged
333 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
334 if (newPrefix == completionPrefix())
337 // value which should be kept selected
338 QString old = currentCompletion();
339 if (old.length() == 0)
340 old = last_selection_;
342 // update completer to new prefix
343 setCompletionPrefix(newPrefix);
345 // update popup because its size might have changed
349 // restore old selection
350 setCurrentCompletion(old);
352 // if popup is not empty, the new selection will
353 // be our last valid one
354 QString const & s = currentCompletion();
355 if (popupVisible() || inlineVisible()) {
359 last_selection_ = old;
362 // update inline completion because the default
363 // completion string might have changed
365 updateInline(cur, s);
369 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
371 if (!cur.inset().inlineCompletionSupported(cur))
375 docstring prefix = cur.inset().completionPrefix(cur);
376 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
378 // shorten it if necessary
379 if (lyxrc.completion_inline_dots != -1
380 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
381 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
383 // set inline completion at cursor position
384 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
385 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
386 inlineVisible_ = true;
390 void GuiCompleter::updatePopup(Cursor & cur)
392 if (!cur.inset().completionSupported(cur))
395 if (completionCount() == 0)
398 // get dimensions of completion prefix
402 cur.inset().completionPosAndDim(cur, x, y, dim);
404 // and calculate the rect of the popup
406 if (popup()->layoutDirection() == Qt::RightToLeft)
407 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
409 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
412 QTreeView * p = static_cast<QTreeView *>(popup());
413 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
419 void GuiCompleter::updateAvailability()
421 // this should really only be of interest if no completion is
422 // visible yet, i.e. especially if automatic completion is disabled.
423 if (inlineVisible() || popupVisible())
425 Cursor & cur = gui_->bufferView().cursor();
426 if (!popupPossible(cur) && !inlinePossible(cur))
429 updateModel(cur, false, false);
433 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
435 // value which should be kept selected
436 QString old = currentCompletion();
437 if (old.length() == 0)
438 old = last_selection_;
442 if (cur.inTexted()) {
443 Paragraph const & par = cur.paragraph();
445 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
446 rtl = font.isVisibleRightToLeft();
448 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
450 // turn the direction of the strings in the popup.
451 // Qt does not do that itself.
452 rtlItemDelegate_->setEnabled(rtl);
455 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
456 setModel(new GuiCompletionModel(this, list));
458 setModelSorting(QCompleter::CaseSensitivelySortedModel);
460 setModelSorting(QCompleter::UnsortedModel);
463 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
464 if (newPrefix != completionPrefix())
465 setCompletionPrefix(newPrefix);
471 // restore old selection
472 setCurrentCompletion(old);
474 // if popup is not empty, the new selection will
475 // be our last valid one
476 if (popupVisible() || inlineVisible()) {
477 QString const & s = currentCompletion();
481 last_selection_ = old;
484 // show inline completion
486 updateInline(cur, currentCompletion());
490 void GuiCompleter::showPopup(Cursor & cur)
492 if (!popupPossible(cur))
495 updateModel(cur, true, inlineVisible());
499 void GuiCompleter::hidePopup(Cursor & cur)
501 // hide popup asynchronously because we might be here inside of
502 // LFUN dispatchers. Hiding a popup can trigger a focus event on the
503 // workarea which then redisplays the cursor. But the metrics are not
504 // yet up to date such that the coord cache has not all insets yet. The
505 // cursorPos methods would triggers asserts in the coord cache then.
506 QTimer::singleShot(0, popup(), SLOT(hide()));
508 if (popup_timer_.isActive())
511 if (!inlineVisible())
512 setModel(new GuiCompletionModel(this, 0));
516 void GuiCompleter::showInline(Cursor & cur)
518 if (!inlinePossible(cur))
521 updateModel(cur, popupVisible(), true);
525 void GuiCompleter::hideInline(Cursor & cur)
527 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
528 inlineVisible_ = false;
531 setModel(new GuiCompletionModel(this, 0));
535 void GuiCompleter::showPopup()
537 Cursor cur = gui_->bufferView().cursor();
538 cur.updateFlags(Update::None);
543 if (cur.disp_.update())
544 gui_->bufferView().processUpdateFlags(cur.disp_.update());
548 void GuiCompleter::showInline()
550 Cursor cur = gui_->bufferView().cursor();
551 cur.updateFlags(Update::None);
556 if (cur.disp_.update())
557 gui_->bufferView().processUpdateFlags(cur.disp_.update());
561 void GuiCompleter::hidePopup()
563 Cursor cur = gui_->bufferView().cursor();
564 cur.updateFlags(Update::None);
569 if (cur.disp_.update())
570 gui_->bufferView().processUpdateFlags(cur.disp_.update());
574 void GuiCompleter::hideInline()
576 Cursor cur = gui_->bufferView().cursor();
577 cur.updateFlags(Update::None);
582 if (cur.disp_.update())
583 gui_->bufferView().processUpdateFlags(cur.disp_.update());
587 void GuiCompleter::activate()
589 if (!popupVisible() && !inlineVisible())
592 popupActivated(currentCompletion());
596 void GuiCompleter::tab()
598 BufferView * bv = &gui_->bufferView();
599 Cursor cur = bv->cursor();
600 cur.updateFlags(Update::None);
602 // check that inline completion is active
603 if (!inlineVisible()) {
604 // try to activate the inline completion
605 if (cur.inset().inlineCompletionSupported(cur)) {
608 // show popup without delay because the completion was not unique
609 if (lyxrc.completion_popup_after_complete
611 && popup()->model()->rowCount() > 1)
612 popup_timer_.start(0);
617 if (!popupVisible() && cur.inset().completionSupported(cur)) {
625 // If completion is active, at least complete by one character
626 docstring prefix = cur.inset().completionPrefix(cur);
627 docstring completion = from_utf8(fromqstr(currentCompletion()));
628 if (completion.size() <= prefix.size()) {
629 // finalize completion
630 cur.inset().insertCompletion(cur, docstring(), true);
632 // hide popup and inline completion
635 updateVisibility(false, false);
638 docstring nextchar = completion.substr(prefix.size(), 1);
639 if (!cur.inset().insertCompletion(cur, nextchar, false))
643 // try to complete as far as it is unique
644 docstring longestCompletion = longestUniqueCompletion();
645 prefix = cur.inset().completionPrefix(cur);
646 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
647 cur.inset().insertCompletion(cur, postfix, false);
648 old_cursor_ = bv->cursor();
651 // show popup without delay because the completion was not unique
652 if (lyxrc.completion_popup_after_complete
654 && popup()->model()->rowCount() > 1)
655 popup_timer_.start(0);
658 if (cur.disp_.update())
659 gui_->bufferView().processUpdateFlags(cur.disp_.update());
663 QString GuiCompleter::currentCompletion() const
665 if (!popup()->selectionModel()->hasSelection())
668 // Not sure if this is bug in Qt: currentIndex() always
669 // return the first element in the list.
670 QModelIndex idx = popup()->currentIndex();
671 return popup()->model()->data(idx, Qt::EditRole).toString();
675 void GuiCompleter::setCurrentCompletion(QString const & s)
677 QAbstractItemModel const & model = *popup()->model();
678 size_t n = model.rowCount();
682 // select the first if s is empty
683 if (s.length() == 0) {
685 popup()->setCurrentIndex(model.index(0, 0));
690 // find old selection in model
692 if (modelSorting() == QCompleter::UnsortedModel) {
693 // In unsorted models, iterate through list until the s is found
694 for (i = 0; i < n; ++i) {
696 = model.data(model.index(i, 0), Qt::EditRole).toString();
701 // In sorted models, do binary search for s.
704 while (r >= l && l < int(n)) {
705 size_t mid = (r + l) / 2;
707 = model.data(model.index(mid, 0),
708 Qt::EditRole).toString();
711 // FIXME: is this really the same order that the docstring
712 // from the CompletionList has?
713 int c = s.compare(mids, Qt::CaseSensitive);
721 // middle is not far enough
728 // loop was left without finding anything
733 BOOST_ASSERT(0 <= i && i <= n);
736 // select the first if none was found
741 popup()->setCurrentIndex(model.index(i, 0));
746 size_t commonPrefix(QString const & s1, QString const & s2)
748 // find common prefix
750 size_t n1 = s1.length();
751 size_t n2 = s2.length();
752 for (j = 0; j < n1 && j < n2; ++j) {
753 if (s1.at(j) != s2.at(j))
760 docstring GuiCompleter::longestUniqueCompletion() const
762 QAbstractItemModel const & model = *popup()->model();
763 size_t n = model.rowCount();
766 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
768 if (modelSorting() == QCompleter::UnsortedModel) {
769 // For unsorted model we cannot do more than iteration.
770 // Iterate through the completions and cut off where s differs
771 for (size_t i = 0; i < n && s.length() > 0; ++i) {
773 = model.data(model.index(i, 0), Qt::EditRole).toString();
775 s = s.left(commonPrefix(is, s));
778 // For sorted models we can do binary search multiple times,
779 // each time to find the first string which has s not as prefix.
781 while (i < n && s.length() > 0) {
782 // find first string that does not have s as prefix
783 // via binary search in [i,n-1]
786 // get common prefix with the middle string
787 size_t mid = (r + i) / 2;
789 = model.data(model.index(mid, 0),
790 Qt::EditRole).toString();
791 size_t oldLen = s.length();
792 size_t len = commonPrefix(mids, s);
797 // middle is not far enough
800 // middle is maybe too far
803 } while (r - i > 0 && i < n);
807 return from_utf8(fromqstr(s));
811 void GuiCompleter::popupActivated(const QString & completion)
813 Cursor cur = gui_->bufferView().cursor();
814 cur.updateFlags(Update::None);
816 docstring prefix = cur.inset().completionPrefix(cur);
817 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
818 cur.inset().insertCompletion(cur, postfix, true);
822 if (cur.disp_.update())
823 gui_->bufferView().processUpdateFlags(cur.disp_.update());
827 void GuiCompleter::popupHighlighted(const QString & completion)
832 Cursor cur = gui_->bufferView().cursor();
833 cur.updateFlags(Update::None);
836 updateInline(cur, completion);
838 if (cur.disp_.update())
839 gui_->bufferView().processUpdateFlags(cur.disp_.update());
842 } // namespace frontend
845 #include "GuiCompleter_moc.cpp"