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 return toqstr(list_->data(index.row()));
135 else if (index.column() == 1) {
136 // get icon from cache
138 QString const name = ":" + toqstr(list_->icon(index.row()));
139 if (!QPixmapCache::find("completion" + name, scaled)) {
140 // load icon from disk
141 QPixmap p = QPixmap(name);
143 // scale it to 16x16 or smaller
144 scaled = p.scaled(min(16, p.width()), min(16, p.height()),
145 Qt::KeepAspectRatio, Qt::SmoothTransformation);
148 QPixmapCache::insert("completion" + name, scaled);
157 Inset::CompletionList const * list_;
161 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
162 : QCompleter(parent), gui_(gui), updateLock_(0),
163 inlineVisible_(false)
165 // Setup the completion popup
166 setModel(new GuiCompletionModel(this, 0));
167 setCompletionMode(QCompleter::PopupCompletion);
171 QTreeView *listView = new QTreeView;
172 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
173 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
174 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
175 listView->setSelectionMode(QAbstractItemView::SingleSelection);
176 listView->header()->hide();
177 listView->setIndentation(0);
178 listView->setUniformRowHeights(true);
180 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
181 rtlItemDelegate_ = new RtlItemDelegate(this);
183 // create timeout timers
184 popup_timer_.setSingleShot(true);
185 inline_timer_.setSingleShot(true);
186 connect(this, SIGNAL(highlighted(const QString &)),
187 this, SLOT(popupHighlighted(const QString &)));
188 connect(this, SIGNAL(activated(const QString &)),
189 this, SLOT(popupActivated(const QString &)));
190 connect(&popup_timer_, SIGNAL(timeout()),
191 this, SLOT(showPopup()));
192 connect(&inline_timer_, SIGNAL(timeout()),
193 this, SLOT(showInline()));
197 GuiCompleter::~GuiCompleter()
203 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
205 // hijack back the tab key from the popup
206 // (which stole it from the workspace before)
207 if (e->type() == QEvent::KeyPress && popupVisible()) {
208 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
218 return QCompleter::eventFilter(watched, e);
222 bool GuiCompleter::popupPossible(Cursor const & cur) const
224 return QApplication::activeWindow()
226 && cur.inset().completionSupported(cur);
230 bool GuiCompleter::inlinePossible(Cursor const & cur) const
232 return cur.inset().inlineCompletionSupported(cur);
236 bool GuiCompleter::completionAvailable() const
238 size_t n = popup()->model()->rowCount();
240 // if there is exactly one, we have to check whether it is a
241 // real completion, i.e. longer than the current prefix.
242 if (n == 1 && completionPrefix() == currentCompletion())
249 bool GuiCompleter::popupVisible() const
251 return popup()->isVisible();
255 bool GuiCompleter::inlineVisible() const
257 // In fact using BufferView::inlineCompletionPos.empty() should be
258 // here. But unfortunately this information is not good enough
259 // because destructive operations like backspace might invalidate
260 // inlineCompletionPos. But then the completion should stay visible
261 // (i.e. reshown on the next update). Hence be keep this information
262 // in the inlineVisible_ variable.
263 return inlineVisible_;
267 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
269 // parameters which affect the completion
270 bool moved = cur != old_cursor_;
274 bool possiblePopupState = popupPossible(cur) && cursorInView;
275 bool possibleInlineState = inlinePossible(cur) && cursorInView;
277 // we moved or popup state is not ok for popup?
278 if ((moved && !keep) || !possiblePopupState)
281 // we moved or inline state is not ok for inline completion?
282 if ((moved && !keep) || !possibleInlineState)
285 // we inserted something and are in a possible popup state?
286 if (!popupVisible() && possiblePopupState && start
287 && cur.inset().automaticPopupCompletion())
288 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
290 // we inserted something and are in a possible inline completion state?
291 if (!inlineVisible() && possibleInlineState && start
292 && cur.inset().automaticInlineCompletion())
293 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
295 // update prefix if any completion is possible
296 bool modelActive = model()->rowCount() > 0;
297 if (possiblePopupState || possibleInlineState) {
301 updateAvailability();
306 void GuiCompleter::updateVisibility(bool start, bool keep)
308 Cursor cur = gui_->bufferView().cursor();
309 cur.updateFlags(Update::None);
311 updateVisibility(cur, start, keep);
313 if (cur.disp_.update())
314 gui_->bufferView().processUpdateFlags(cur.disp_.update());
318 void GuiCompleter::updatePrefix(Cursor & cur)
320 // get new prefix. Do nothing if unchanged
321 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
322 if (newPrefix == completionPrefix())
325 // value which should be kept selected
326 QString old = currentCompletion();
327 if (old.length() == 0)
328 old = last_selection_;
330 // update completer to new prefix
331 setCompletionPrefix(newPrefix);
333 // update popup because its size might have changed
337 // restore old selection
338 setCurrentCompletion(old);
340 // if popup is not empty, the new selection will
341 // be our last valid one
342 QString const & s = currentCompletion();
343 if (popupVisible() || inlineVisible()) {
347 last_selection_ = old;
350 // update inline completion because the default
351 // completion string might have changed
353 updateInline(cur, s);
357 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
359 if (!cur.inset().inlineCompletionSupported(cur))
363 docstring prefix = cur.inset().completionPrefix(cur);
364 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
366 // shorten it if necessary
367 if (lyxrc.completion_inline_dots != -1
368 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
369 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
371 // set inline completion at cursor position
372 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
373 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
374 inlineVisible_ = true;
378 void GuiCompleter::updatePopup(Cursor & cur)
380 if (!cur.inset().completionSupported(cur))
383 if (completionCount() == 0)
386 // get dimensions of completion prefix
390 cur.inset().completionPosAndDim(cur, x, y, dim);
392 // and calculate the rect of the popup
394 if (popup()->layoutDirection() == Qt::RightToLeft)
395 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
397 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
400 QTreeView * p = static_cast<QTreeView *>(popup());
401 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
407 void GuiCompleter::updateAvailability()
409 // this should really only be of interest if no completion is
410 // visible yet, i.e. especially if automatic completion is disabled.
411 if (inlineVisible() || popupVisible())
413 Cursor & cur = gui_->bufferView().cursor();
414 if (!popupPossible(cur) && !inlinePossible(cur))
417 updateModel(cur, false, false);
421 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
423 // value which should be kept selected
424 QString old = currentCompletion();
425 if (old.length() == 0)
426 old = last_selection_;
430 if (cur.inTexted()) {
431 Paragraph const & par = cur.paragraph();
433 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
434 rtl = font.isVisibleRightToLeft();
436 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
438 // turn the direction of the strings in the popup.
439 // Qt does not do that itself.
440 popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
443 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
444 setModel(new GuiCompletionModel(this, list));
446 setModelSorting(QCompleter::CaseSensitivelySortedModel);
448 setModelSorting(QCompleter::UnsortedModel);
451 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
452 if (newPrefix != completionPrefix())
453 setCompletionPrefix(newPrefix);
459 // restore old selection
460 setCurrentCompletion(old);
462 // if popup is not empty, the new selection will
463 // be our last valid one
464 if (popupVisible() || inlineVisible()) {
465 QString const & s = currentCompletion();
469 last_selection_ = old;
472 // show inline completion
474 updateInline(cur, currentCompletion());
478 void GuiCompleter::showPopup(Cursor & cur)
480 if (!popupPossible(cur))
483 updateModel(cur, true, inlineVisible());
487 void GuiCompleter::hidePopup(Cursor & cur)
490 if (popup_timer_.isActive())
493 if (!inlineVisible())
494 setModel(new GuiCompletionModel(this, 0));
498 void GuiCompleter::showInline(Cursor & cur)
500 if (!inlinePossible(cur))
503 updateModel(cur, popupVisible(), true);
507 void GuiCompleter::hideInline(Cursor & cur)
509 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
510 inlineVisible_ = false;
513 setModel(new GuiCompletionModel(this, 0));
517 void GuiCompleter::showPopup()
519 Cursor cur = gui_->bufferView().cursor();
520 cur.updateFlags(Update::None);
525 if (cur.disp_.update())
526 gui_->bufferView().processUpdateFlags(cur.disp_.update());
530 void GuiCompleter::showInline()
532 Cursor cur = gui_->bufferView().cursor();
533 cur.updateFlags(Update::None);
538 if (cur.disp_.update())
539 gui_->bufferView().processUpdateFlags(cur.disp_.update());
543 void GuiCompleter::hidePopup()
545 Cursor cur = gui_->bufferView().cursor();
546 cur.updateFlags(Update::None);
551 if (cur.disp_.update())
552 gui_->bufferView().processUpdateFlags(cur.disp_.update());
556 void GuiCompleter::hideInline()
558 Cursor cur = gui_->bufferView().cursor();
559 cur.updateFlags(Update::None);
564 if (cur.disp_.update())
565 gui_->bufferView().processUpdateFlags(cur.disp_.update());
569 void GuiCompleter::activate()
571 if (!popupVisible() && !inlineVisible())
574 popupActivated(currentCompletion());
578 void GuiCompleter::tab()
580 BufferView * bv = &gui_->bufferView();
581 Cursor cur = bv->cursor();
582 cur.updateFlags(Update::None);
584 // check that inline completion is active
585 if (!inlineVisible()) {
586 // try to activate the inline completion
587 if (cur.inset().inlineCompletionSupported(cur)) {
590 // show popup without delay because the completion was not unique
591 if (lyxrc.completion_popup_after_complete
593 && popup()->model()->rowCount() > 1)
594 popup_timer_.start(0);
599 if (!popupVisible() && cur.inset().completionSupported(cur)) {
607 // If completion is active, at least complete by one character
608 docstring prefix = cur.inset().completionPrefix(cur);
609 docstring completion = from_utf8(fromqstr(currentCompletion()));
610 if (completion.size() <= prefix.size()) {
611 // finalize completion
612 cur.inset().insertCompletion(cur, docstring(), true);
614 // hide popup and inline completion
617 updateVisibility(false, false);
620 docstring nextchar = completion.substr(prefix.size(), 1);
621 if (!cur.inset().insertCompletion(cur, nextchar, false))
625 // try to complete as far as it is unique
626 docstring longestCompletion = longestUniqueCompletion();
627 prefix = cur.inset().completionPrefix(cur);
628 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
629 cur.inset().insertCompletion(cur, postfix, false);
630 old_cursor_ = bv->cursor();
633 // show popup without delay because the completion was not unique
634 if (lyxrc.completion_popup_after_complete
636 && popup()->model()->rowCount() > 1)
637 popup_timer_.start(0);
640 if (cur.disp_.update())
641 gui_->bufferView().processUpdateFlags(cur.disp_.update());
645 QString GuiCompleter::currentCompletion() const
647 if (!popup()->selectionModel()->hasSelection())
650 // Not sure if this is bug in Qt: currentIndex() always
651 // return the first element in the list.
652 QModelIndex idx = popup()->currentIndex();
653 return popup()->model()->data(idx, Qt::EditRole).toString();
657 void GuiCompleter::setCurrentCompletion(QString const & s)
659 QAbstractItemModel const & model = *popup()->model();
660 size_t n = model.rowCount();
664 // select the first if s is empty
665 if (s.length() == 0) {
667 popup()->setCurrentIndex(model.index(0, 0));
672 // find old selection in model
674 if (modelSorting() == QCompleter::UnsortedModel) {
675 // In unsorted models, iterate through list until the s is found
676 for (i = 0; i < n; ++i) {
678 = model.data(model.index(i, 0), Qt::EditRole).toString();
683 // In sorted models, do binary search for s.
686 while (r >= l && l < int(n)) {
687 size_t mid = (r + l) / 2;
689 = model.data(model.index(mid, 0),
690 Qt::EditRole).toString();
693 // FIXME: is this really the same order that the docstring
694 // from the CompletionList has?
695 int c = s.compare(mids, Qt::CaseSensitive);
703 // middle is not far enough
710 // loop was left without finding anything
715 BOOST_ASSERT(0 <= i && i <= n);
718 // select the first if none was found
723 popup()->setCurrentIndex(model.index(i, 0));
728 size_t commonPrefix(QString const & s1, QString const & s2)
730 // find common prefix
732 size_t n1 = s1.length();
733 size_t n2 = s2.length();
734 for (j = 0; j < n1 && j < n2; ++j) {
735 if (s1.at(j) != s2.at(j))
742 docstring GuiCompleter::longestUniqueCompletion() const
744 QAbstractItemModel const & model = *popup()->model();
745 size_t n = model.rowCount();
748 QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
750 if (modelSorting() == QCompleter::UnsortedModel) {
751 // For unsorted model we cannot do more than iteration.
752 // Iterate through the completions and cut off where s differs
753 for (size_t i = 0; i < n && s.length() > 0; ++i) {
755 = model.data(model.index(i, 0), Qt::EditRole).toString();
757 s = s.left(commonPrefix(is, s));
760 // For sorted models we can do binary search multiple times,
761 // each time to find the first string which has s not as prefix.
763 while (i < n && s.length() > 0) {
764 // find first string that does not have s as prefix
765 // via binary search in [i,n-1]
768 // get common prefix with the middle string
769 size_t mid = (r + i) / 2;
771 = model.data(model.index(mid, 0),
772 Qt::EditRole).toString();
773 size_t oldLen = s.length();
774 size_t len = commonPrefix(mids, s);
779 // middle is not far enough
782 // middle is maybe too far
785 } while (r - i > 0 && i < n);
789 return from_utf8(fromqstr(s));
793 void GuiCompleter::popupActivated(const QString & completion)
795 Cursor cur = gui_->bufferView().cursor();
796 cur.updateFlags(Update::None);
798 docstring prefix = cur.inset().completionPrefix(cur);
799 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
800 cur.inset().insertCompletion(cur, postfix, true);
804 if (cur.disp_.update())
805 gui_->bufferView().processUpdateFlags(cur.disp_.update());
809 void GuiCompleter::popupHighlighted(const QString & completion)
814 Cursor cur = gui_->bufferView().cursor();
815 cur.updateFlags(Update::None);
818 updateInline(cur, completion);
820 if (cur.disp_.update())
821 gui_->bufferView().processUpdateFlags(cur.disp_.update());
824 } // namespace frontend
827 #include "GuiCompleter_moc.cpp"