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
145 = 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::popupVisible() const
239 return popup()->isVisible();
243 bool GuiCompleter::inlineVisible() const
245 // In fact using BufferView::inlineCompletionPos.empty() should be
246 // here. But unfortunately this information is not good enough
247 // because destructive operations like backspace might invalidate
248 // inlineCompletionPos. But then the completion should stay visible
249 // (i.e. reshown on the next update). Hence be keep this information
250 // in the inlineVisible_ variable.
251 return inlineVisible_;
255 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
257 // parameters which affect the completion
258 bool moved = cur != old_cursor_;
262 bool possiblePopupState = popupPossible(cur) && cursorInView;
263 bool possibleInlineState = inlinePossible(cur) && cursorInView;
265 // we moved or popup state is not ok for popup?
266 if ((moved && !keep) || !possiblePopupState) {
267 // stop an old completion timer
268 if (popup_timer_.isActive())
276 // we moved or inline state is not ok for inline completion?
277 if ((moved && !keep) || !possibleInlineState) {
278 // stop an old completion timer
279 if (inline_timer_.isActive())
280 inline_timer_.stop();
282 // hide old inline completion
283 if (inlineVisible()) {
284 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
285 inlineVisible_ = false;
289 // we inserted something and are in a possible popup state?
290 if (!popupVisible() && possiblePopupState && start
291 && cur.inset().automaticPopupCompletion())
292 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
294 // we inserted something and are in a possible inline completion state?
295 if (!inlineVisible() && possibleInlineState && start
296 && cur.inset().automaticInlineCompletion())
297 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
299 // update prefix if popup is visible or if it will be visible soon
300 if (popupVisible() || inlineVisible()
301 || popup_timer_.isActive() || inline_timer_.isActive())
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();
346 last_selection_ = old;
348 // update inline completion because the default
349 // completion string might have changed
351 updateInline(cur, s);
355 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
357 if (!cur.inset().inlineCompletionSupported(cur))
361 docstring prefix = cur.inset().completionPrefix(cur);
362 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
364 // shorten it if necessary
365 if (lyxrc.completion_inline_dots != -1
366 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
367 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
369 // set inline completion at cursor position
370 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
371 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
372 inlineVisible_ = true;
376 void GuiCompleter::updatePopup(Cursor & cur)
378 if (!cur.inset().completionSupported(cur))
381 if (completionCount() == 0)
384 // get dimensions of completion prefix
388 cur.inset().completionPosAndDim(cur, x, y, dim);
390 // and calculate the rect of the popup
392 if (popup()->layoutDirection() == Qt::RightToLeft)
393 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
395 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
399 QTreeView * p = static_cast<QTreeView *>(popup());
400 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
404 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
406 // value which should be kept selected
407 QString old = currentCompletion();
408 if (old.length() == 0)
409 old = last_selection_;
413 if (cur.inTexted()) {
414 Paragraph const & par = cur.paragraph();
416 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
417 rtl = font.isVisibleRightToLeft();
419 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
421 // turn the direction of the strings in the popup.
422 // Qt does not do that itself.
423 popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
426 Inset::CompletionList const * list
427 = cur.inset().createCompletionList(cur);
428 setModel(new GuiCompletionModel(this, list));
430 setModelSorting(QCompleter::CaseSensitivelySortedModel);
432 setModelSorting(QCompleter::UnsortedModel);
435 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
436 if (newPrefix != completionPrefix())
437 setCompletionPrefix(newPrefix);
443 // restore old selection
444 setCurrentCompletion(old);
446 // if popup is not empty, the new selection will
447 // be our last valid one
448 QString const & s = currentCompletion();
452 last_selection_ = old;
454 // show inline completion
456 updateInline(cur, currentCompletion());
460 void GuiCompleter::showPopup(Cursor & cur)
462 if (!popupPossible(cur))
465 updateModel(cur, true, inlineVisible());
469 void GuiCompleter::showInline(Cursor & cur)
471 if (!inlinePossible(cur))
474 updateModel(cur, popupVisible(), true);
478 void GuiCompleter::showPopup()
480 Cursor cur = gui_->bufferView().cursor();
481 cur.updateFlags(Update::None);
486 if (cur.disp_.update())
487 gui_->bufferView().processUpdateFlags(cur.disp_.update());
491 void GuiCompleter::showInline()
493 Cursor cur = gui_->bufferView().cursor();
494 cur.updateFlags(Update::None);
499 if (cur.disp_.update())
500 gui_->bufferView().processUpdateFlags(cur.disp_.update());
504 void GuiCompleter::activate()
506 if (!popupVisible() && !inlineVisible())
509 // Complete with current selection in the popup.
510 QString s = currentCompletion();
516 void GuiCompleter::tab()
518 BufferView * bv = &gui_->bufferView();
519 Cursor cur = bv->cursor();
520 cur.updateFlags(Update::None);
522 // check that inline completion is active
523 if (!inlineVisible()) {
524 // try to activate the inline completion
525 if (cur.inset().inlineCompletionSupported(cur)) {
528 // show popup without delay because the completion was not unique
529 if (lyxrc.completion_popup_after_complete
531 && popup()->model()->rowCount() > 1)
532 popup_timer_.start(0);
537 if (!popupVisible() && cur.inset().completionSupported(cur)) {
545 // If completion is active, at least complete by one character
546 docstring prefix = cur.inset().completionPrefix(cur);
547 docstring completion = from_utf8(fromqstr(currentCompletion()));
548 if (completion.size() <= prefix.size()) {
549 // finalize completion
550 cur.inset().insertCompletion(cur, docstring(), true);
552 // hide popup and inline completion
554 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
555 inlineVisible_ = false;
556 updateVisibility(false, false);
559 docstring nextchar = completion.substr(prefix.size(), 1);
560 if (!cur.inset().insertCompletion(cur, nextchar, false))
564 // try to complete as far as it is unique
565 docstring longestCompletion = longestUniqueCompletion();
566 prefix = cur.inset().completionPrefix(cur);
567 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
568 cur.inset().insertCompletion(cur, postfix, false);
569 old_cursor_ = bv->cursor();
572 // show popup without delay because the completion was not unique
573 if (lyxrc.completion_popup_after_complete
575 && popup()->model()->rowCount() > 1)
576 popup_timer_.start(0);
579 if (cur.disp_.update())
580 gui_->bufferView().processUpdateFlags(cur.disp_.update());
584 QString GuiCompleter::currentCompletion() const
586 if (!popup()->selectionModel()->hasSelection())
589 // Not sure if this is bug in Qt: currentIndex() always
590 // return the first element in the list.
591 QModelIndex idx = popup()->currentIndex();
592 return popup()->model()->data(idx, Qt::EditRole).toString();
596 void GuiCompleter::setCurrentCompletion(QString const & s)
598 QAbstractItemModel const & model = *popup()->model();
599 size_t n = model.rowCount();
603 // select the first if s is empty
604 if (s.length() == 0) {
606 popup()->setCurrentIndex(model.index(0, 0));
611 // find old selection in model
613 if (modelSorting() == QCompleter::UnsortedModel) {
614 // In unsorted models, iterate through list until the s is found
615 for (i = 0; i < n; ++i) {
617 = model.data(model.index(i, 0), Qt::EditRole).toString();
622 // In sorted models, do binary search for s.
627 size_t mid = (r + i) / 2;
629 = model.data(model.index(mid, 0),
630 Qt::EditRole).toString();
633 // FIXME: is this really the same order that the docstring
634 // from the CompletionList has?
635 c = s.compare(mids, Qt::CaseSensitive);
640 // middle is not far enough
646 } while (r - i > 0 && i < n);
648 // loop was left with failed comparison?
649 // i.e. word was not found.
654 // select the first if none was found
659 popup()->setCurrentIndex(model.index(i, 0));
664 size_t commonPrefix(QString const & s1, QString const & s2)
666 // find common prefix
668 size_t n1 = s1.length();
669 size_t n2 = s2.length();
670 for (j = 0; j < n1 && j < n2; ++j) {
671 if (s1.at(j) != s2.at(j))
678 docstring GuiCompleter::longestUniqueCompletion() const
680 QAbstractItemModel const & model = *popup()->model();
681 QString s = currentCompletion();
682 size_t n = model.rowCount();
684 if (modelSorting() == QCompleter::UnsortedModel) {
685 // For unsorted model we cannot do more than iteration.
686 // Iterate through the completions and cut off where s differs
687 for (size_t i = 0; i < n && s.length() > 0; ++i) {
689 = model.data(model.index(i, 0), Qt::EditRole).toString();
691 s = s.left(commonPrefix(is, s));
694 // For sorted models we can do binary search multiple times,
695 // each time to find the first string which has s not as prefix.
697 while (i < n && s.length() > 0) {
698 // find first string that does not have s as prefix
699 // via binary search in [i,n-1]
702 // get common prefix with the middle string
703 size_t mid = (r + i) / 2;
705 = model.data(model.index(mid, 0),
706 Qt::EditRole).toString();
707 size_t oldLen = s.length();
708 size_t len = commonPrefix(mids, s);
713 // middle is not far enough
716 // middle is maybe too far
719 } while (r - i > 0 && i < n);
723 return from_utf8(fromqstr(s));
727 void GuiCompleter::popupActivated(const QString & completion)
729 Cursor cur = gui_->bufferView().cursor();
730 cur.updateFlags(Update::None);
732 docstring prefix = cur.inset().completionPrefix(cur);
733 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
734 cur.inset().insertCompletion(cur, postfix, true);
735 updateVisibility(cur, false);
737 if (cur.disp_.update())
738 gui_->bufferView().processUpdateFlags(cur.disp_.update());
742 void GuiCompleter::popupHighlighted(const QString & completion)
747 Cursor cur = gui_->bufferView().cursor();
748 cur.updateFlags(Update::None);
750 updateInline(cur, completion);
752 if (cur.disp_.update())
753 gui_->bufferView().processUpdateFlags(cur.disp_.update());
756 } // namespace frontend
759 #include "GuiCompleter_moc.cpp"