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::popupVisible() const
238 return popup()->isVisible();
242 bool GuiCompleter::inlineVisible() const
244 // In fact using BufferView::inlineCompletionPos.empty() should be
245 // here. But unfortunately this information is not good enough
246 // because destructive operations like backspace might invalidate
247 // inlineCompletionPos. But then the completion should stay visible
248 // (i.e. reshown on the next update). Hence be keep this information
249 // in the inlineVisible_ variable.
250 return inlineVisible_;
254 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
256 // parameters which affect the completion
257 bool moved = cur != old_cursor_;
261 bool possiblePopupState = popupPossible(cur) && cursorInView;
262 bool possibleInlineState = inlinePossible(cur) && cursorInView;
264 // we moved or popup state is not ok for popup?
265 if ((moved && !keep) || !possiblePopupState)
268 // we moved or inline state is not ok for inline completion?
269 if ((moved && !keep) || !possibleInlineState)
272 // we inserted something and are in a possible popup state?
273 if (!popupVisible() && possiblePopupState && start
274 && cur.inset().automaticPopupCompletion())
275 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
277 // we inserted something and are in a possible inline completion state?
278 if (!inlineVisible() && possibleInlineState && start
279 && cur.inset().automaticInlineCompletion())
280 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
282 // update prefix if popup is visible or if it will be visible soon
283 if (popupVisible() || inlineVisible()
284 || popup_timer_.isActive() || inline_timer_.isActive())
289 void GuiCompleter::updateVisibility(bool start, bool keep)
291 Cursor cur = gui_->bufferView().cursor();
292 cur.updateFlags(Update::None);
294 updateVisibility(cur, start, keep);
296 if (cur.disp_.update())
297 gui_->bufferView().processUpdateFlags(cur.disp_.update());
301 void GuiCompleter::updatePrefix(Cursor & cur)
303 // get new prefix. Do nothing if unchanged
304 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
305 if (newPrefix == completionPrefix())
308 // value which should be kept selected
309 QString old = currentCompletion();
310 if (old.length() == 0)
311 old = last_selection_;
313 // update completer to new prefix
314 setCompletionPrefix(newPrefix);
316 // update popup because its size might have changed
320 // restore old selection
321 setCurrentCompletion(old);
323 // if popup is not empty, the new selection will
324 // be our last valid one
325 QString const & s = currentCompletion();
329 last_selection_ = old;
331 // update inline completion because the default
332 // completion string might have changed
334 updateInline(cur, s);
338 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
340 if (!cur.inset().inlineCompletionSupported(cur))
344 docstring prefix = cur.inset().completionPrefix(cur);
345 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
347 // shorten it if necessary
348 if (lyxrc.completion_inline_dots != -1
349 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
350 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
352 // set inline completion at cursor position
353 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
354 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
355 inlineVisible_ = true;
359 void GuiCompleter::updatePopup(Cursor & cur)
361 if (!cur.inset().completionSupported(cur))
364 if (completionCount() == 0)
367 // get dimensions of completion prefix
371 cur.inset().completionPosAndDim(cur, x, y, dim);
373 // and calculate the rect of the popup
375 if (popup()->layoutDirection() == Qt::RightToLeft)
376 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
378 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
381 QTreeView * p = static_cast<QTreeView *>(popup());
382 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
388 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
390 // value which should be kept selected
391 QString old = currentCompletion();
392 if (old.length() == 0)
393 old = last_selection_;
397 if (cur.inTexted()) {
398 Paragraph const & par = cur.paragraph();
400 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
401 rtl = font.isVisibleRightToLeft();
403 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
405 // turn the direction of the strings in the popup.
406 // Qt does not do that itself.
407 popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
410 Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
411 setModel(new GuiCompletionModel(this, list));
413 setModelSorting(QCompleter::CaseSensitivelySortedModel);
415 setModelSorting(QCompleter::UnsortedModel);
418 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
419 if (newPrefix != completionPrefix())
420 setCompletionPrefix(newPrefix);
426 // restore old selection
427 setCurrentCompletion(old);
429 // if popup is not empty, the new selection will
430 // be our last valid one
431 QString const & s = currentCompletion();
435 last_selection_ = old;
437 // show inline completion
439 updateInline(cur, currentCompletion());
443 void GuiCompleter::showPopup(Cursor & cur)
445 if (!popupPossible(cur))
448 updateModel(cur, true, inlineVisible());
452 void GuiCompleter::hidePopup(Cursor & cur)
455 if (popup_timer_.isActive())
460 void GuiCompleter::showInline(Cursor & cur)
462 if (!inlinePossible(cur))
465 updateModel(cur, popupVisible(), true);
469 void GuiCompleter::hideInline(Cursor & cur)
471 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
472 inlineVisible_ = false;
476 void GuiCompleter::showPopup()
478 Cursor cur = gui_->bufferView().cursor();
479 cur.updateFlags(Update::None);
484 if (cur.disp_.update())
485 gui_->bufferView().processUpdateFlags(cur.disp_.update());
489 void GuiCompleter::showInline()
491 Cursor cur = gui_->bufferView().cursor();
492 cur.updateFlags(Update::None);
497 if (cur.disp_.update())
498 gui_->bufferView().processUpdateFlags(cur.disp_.update());
502 void GuiCompleter::hidePopup()
504 Cursor cur = gui_->bufferView().cursor();
505 cur.updateFlags(Update::None);
510 if (cur.disp_.update())
511 gui_->bufferView().processUpdateFlags(cur.disp_.update());
515 void GuiCompleter::hideInline()
517 Cursor cur = gui_->bufferView().cursor();
518 cur.updateFlags(Update::None);
523 if (cur.disp_.update())
524 gui_->bufferView().processUpdateFlags(cur.disp_.update());
528 void GuiCompleter::activate()
530 if (!popupVisible() && !inlineVisible())
533 popupActivated(currentCompletion());
537 void GuiCompleter::tab()
539 BufferView * bv = &gui_->bufferView();
540 Cursor cur = bv->cursor();
541 cur.updateFlags(Update::None);
543 // check that inline completion is active
544 if (!inlineVisible()) {
545 // try to activate the inline completion
546 if (cur.inset().inlineCompletionSupported(cur)) {
549 // show popup without delay because the completion was not unique
550 if (lyxrc.completion_popup_after_complete
552 && popup()->model()->rowCount() > 1)
553 popup_timer_.start(0);
558 if (!popupVisible() && cur.inset().completionSupported(cur)) {
566 // If completion is active, at least complete by one character
567 docstring prefix = cur.inset().completionPrefix(cur);
568 docstring completion = from_utf8(fromqstr(currentCompletion()));
569 if (completion.size() <= prefix.size()) {
570 // finalize completion
571 cur.inset().insertCompletion(cur, docstring(), true);
573 // hide popup and inline completion
576 updateVisibility(false, false);
579 docstring nextchar = completion.substr(prefix.size(), 1);
580 if (!cur.inset().insertCompletion(cur, nextchar, false))
584 // try to complete as far as it is unique
585 docstring longestCompletion = longestUniqueCompletion();
586 prefix = cur.inset().completionPrefix(cur);
587 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
588 cur.inset().insertCompletion(cur, postfix, false);
589 old_cursor_ = bv->cursor();
592 // show popup without delay because the completion was not unique
593 if (lyxrc.completion_popup_after_complete
595 && popup()->model()->rowCount() > 1)
596 popup_timer_.start(0);
599 if (cur.disp_.update())
600 gui_->bufferView().processUpdateFlags(cur.disp_.update());
604 QString GuiCompleter::currentCompletion() const
606 if (!popup()->selectionModel()->hasSelection())
609 // Not sure if this is bug in Qt: currentIndex() always
610 // return the first element in the list.
611 QModelIndex idx = popup()->currentIndex();
612 return popup()->model()->data(idx, Qt::EditRole).toString();
616 void GuiCompleter::setCurrentCompletion(QString const & s)
618 QAbstractItemModel const & model = *popup()->model();
619 size_t n = model.rowCount();
623 // select the first if s is empty
624 if (s.length() == 0) {
626 popup()->setCurrentIndex(model.index(0, 0));
631 // find old selection in model
633 if (modelSorting() == QCompleter::UnsortedModel) {
634 // In unsorted models, iterate through list until the s is found
635 for (i = 0; i < n; ++i) {
637 = model.data(model.index(i, 0), Qt::EditRole).toString();
642 // In sorted models, do binary search for s.
645 while (r >= l && l < int(n)) {
646 size_t mid = (r + l) / 2;
648 = model.data(model.index(mid, 0),
649 Qt::EditRole).toString();
652 // FIXME: is this really the same order that the docstring
653 // from the CompletionList has?
654 int c = s.compare(mids, Qt::CaseSensitive);
662 // middle is not far enough
669 // loop was left without finding anything
674 BOOST_ASSERT(0 <= i && i <= n);
677 // select the first if none was found
682 popup()->setCurrentIndex(model.index(i, 0));
687 size_t commonPrefix(QString const & s1, QString const & s2)
689 // find common prefix
691 size_t n1 = s1.length();
692 size_t n2 = s2.length();
693 for (j = 0; j < n1 && j < n2; ++j) {
694 if (s1.at(j) != s2.at(j))
701 docstring GuiCompleter::longestUniqueCompletion() const
703 QAbstractItemModel const & model = *popup()->model();
704 QString s = currentCompletion();
705 size_t n = model.rowCount();
707 if (modelSorting() == QCompleter::UnsortedModel) {
708 // For unsorted model we cannot do more than iteration.
709 // Iterate through the completions and cut off where s differs
710 for (size_t i = 0; i < n && s.length() > 0; ++i) {
712 = model.data(model.index(i, 0), Qt::EditRole).toString();
714 s = s.left(commonPrefix(is, s));
717 // For sorted models we can do binary search multiple times,
718 // each time to find the first string which has s not as prefix.
720 while (i < n && s.length() > 0) {
721 // find first string that does not have s as prefix
722 // via binary search in [i,n-1]
725 // get common prefix with the middle string
726 size_t mid = (r + i) / 2;
728 = model.data(model.index(mid, 0),
729 Qt::EditRole).toString();
730 size_t oldLen = s.length();
731 size_t len = commonPrefix(mids, s);
736 // middle is not far enough
739 // middle is maybe too far
742 } while (r - i > 0 && i < n);
746 return from_utf8(fromqstr(s));
750 void GuiCompleter::popupActivated(const QString & completion)
752 Cursor cur = gui_->bufferView().cursor();
753 cur.updateFlags(Update::None);
755 docstring prefix = cur.inset().completionPrefix(cur);
756 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
757 cur.inset().insertCompletion(cur, postfix, true);
761 if (cur.disp_.update())
762 gui_->bufferView().processUpdateFlags(cur.disp_.update());
766 void GuiCompleter::popupHighlighted(const QString & completion)
771 Cursor cur = gui_->bufferView().cursor();
772 cur.updateFlags(Update::None);
775 updateInline(cur, completion);
777 if (cur.disp_.update())
778 gui_->bufferView().processUpdateFlags(cur.disp_.update());
781 } // namespace frontend
784 #include "GuiCompleter_moc.cpp"