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) {}
100 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
105 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
110 return list_->size();
114 QVariant data(const QModelIndex & index, int role) const
119 if (index.row() < 0 || index.row() >= rowCount())
122 if (role != Qt::DisplayRole && role != Qt::EditRole)
125 if (index.column() == 0)
126 return toqstr(list_->data(index.row()));
127 else if (index.column() == 1) {
128 // get icon from cache
130 QString const name = ":" + toqstr(list_->icon(index.row()));
131 if (!QPixmapCache::find("completion" + name, scaled)) {
132 // load icon from disk
133 QPixmap p = QPixmap(name);
135 // scale it to 16x16 or smaller
137 = p.scaled(min(16, p.width()), min(16, p.height()),
138 Qt::KeepAspectRatio, Qt::SmoothTransformation);
141 QPixmapCache::insert("completion" + name, scaled);
150 Inset::CompletionList const * list_;
154 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
155 : QCompleter(parent), gui_(gui), updateLock_(0),
156 inlineVisible_(false)
158 // Setup the completion popup
159 setModel(new GuiCompletionModel(this, 0));
160 setCompletionMode(QCompleter::PopupCompletion);
164 QTreeView *listView = new QTreeView;
165 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
166 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
167 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
168 listView->setSelectionMode(QAbstractItemView::SingleSelection);
169 listView->header()->hide();
170 listView->setIndentation(0);
172 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
174 // create timeout timers
175 popup_timer_.setSingleShot(true);
176 inline_timer_.setSingleShot(true);
177 connect(this, SIGNAL(highlighted(const QString &)),
178 this, SLOT(popupHighlighted(const QString &)));
179 connect(this, SIGNAL(activated(const QString &)),
180 this, SLOT(popupActivated(const QString &)));
181 connect(&popup_timer_, SIGNAL(timeout()),
182 this, SLOT(showPopup()));
183 connect(&inline_timer_, SIGNAL(timeout()),
184 this, SLOT(showInline()));
188 GuiCompleter::~GuiCompleter()
194 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
196 // hijack back the tab key from the popup
197 // (which stole it from the workspace before)
198 if (e->type() == QEvent::KeyPress && popupVisible()) {
199 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
209 return QCompleter::eventFilter(watched, e);
213 bool GuiCompleter::popupPossible(Cursor const & cur) const
215 return QApplication::activeWindow()
217 && cur.inset().completionSupported(cur);
221 bool GuiCompleter::inlinePossible(Cursor const & cur) const
223 return cur.inset().inlineCompletionSupported(cur);
227 bool GuiCompleter::popupVisible() const
229 return popup()->isVisible();
233 bool GuiCompleter::inlineVisible() const
235 // In fact using BufferView::inlineCompletionPos.empty() should be
236 // here. But unfortunately this information is not good enough
237 // because destructive operations like backspace might invalidate
238 // inlineCompletionPos. But then the completion should stay visible
239 // (i.e. reshown on the next update). Hence be keep this information
240 // in the inlineVisible_ variable.
241 return inlineVisible_;
245 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
247 // parameters which affect the completion
248 bool moved = cur != old_cursor_;
252 bool possiblePopupState = popupPossible(cur) && cursorInView;
253 bool possibleInlineState = inlinePossible(cur) && cursorInView;
255 // we moved or popup state is not ok for popup?
256 if ((moved && !keep) || !possiblePopupState) {
257 // stop an old completion timer
258 if (popup_timer_.isActive())
266 // we moved or inline state is not ok for inline completion?
267 if ((moved && !keep) || !possibleInlineState) {
268 // stop an old completion timer
269 if (inline_timer_.isActive())
270 inline_timer_.stop();
272 // hide old inline completion
273 if (inlineVisible()) {
274 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
275 inlineVisible_ = false;
279 // we inserted something and are in a possible popup state?
280 if (!popupVisible() && possiblePopupState && start
281 && cur.inset().automaticPopupCompletion())
282 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
284 // we inserted something and are in a possible inline completion state?
285 if (!inlineVisible() && possibleInlineState && start
286 && cur.inset().automaticInlineCompletion())
287 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
289 // update prefix if popup is visible or if it will be visible soon
290 if (popupVisible() || inlineVisible()
291 || popup_timer_.isActive() || inline_timer_.isActive())
296 void GuiCompleter::updateVisibility(bool start, bool keep)
298 Cursor cur = gui_->bufferView().cursor();
299 cur.updateFlags(Update::None);
301 updateVisibility(cur, start, keep);
303 if (cur.disp_.update())
304 gui_->bufferView().processUpdateFlags(cur.disp_.update());
308 void GuiCompleter::updatePrefix(Cursor & cur)
310 // get new prefix. Do nothing if unchanged
311 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
312 if (newPrefix == completionPrefix())
315 // value which should be kept selected
316 QString old = currentCompletion();
317 if (old.length() == 0)
318 old = last_selection_;
320 // update completer to new prefix
321 setCompletionPrefix(newPrefix);
323 // update popup because its size might have changed
327 // restore old selection
328 setCurrentCompletion(old);
330 // if popup is not empty, the new selection will
331 // be our last valid one
332 QString const & s = currentCompletion();
336 last_selection_ = old;
338 // update inline completion because the default
339 // completion string might have changed
341 updateInline(cur, s);
345 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
347 if (!cur.inset().inlineCompletionSupported(cur))
351 docstring prefix = cur.inset().completionPrefix(cur);
352 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
354 // shorten it if necessary
355 if (lyxrc.completion_inline_dots != -1
356 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
357 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
359 // set inline completion at cursor position
360 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
361 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
362 inlineVisible_ = true;
366 void GuiCompleter::updatePopup(Cursor & cur)
368 if (!cur.inset().completionSupported(cur))
371 if (completionCount() == 0)
374 // get dimensions of completion prefix
378 cur.inset().completionPosAndDim(cur, x, y, dim);
380 // and calculate the rect of the popup
382 if (popup()->layoutDirection() == Qt::RightToLeft)
383 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
385 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
389 QTreeView * p = static_cast<QTreeView *>(popup());
390 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
394 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
396 // value which should be kept selected
397 QString old = currentCompletion();
398 if (old.length() == 0)
399 old = last_selection_;
403 if (cur.inTexted()) {
404 Paragraph const & par = cur.paragraph();
406 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
407 rtl = font.isVisibleRightToLeft();
409 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
411 // turn the direction of the strings in the popup.
412 // Qt does not do that itself.
413 popup()->setItemDelegateForColumn(0, rtl ? new RtlItemDelegate : 0);
416 Inset::CompletionList const * list
417 = cur.inset().createCompletionList(cur);
418 setModel(new GuiCompletionModel(this, list));
424 // restore old selection
425 setCurrentCompletion(old);
427 // if popup is not empty, the new selection will
428 // be our last valid one
429 QString const & s = currentCompletion();
433 last_selection_ = old;
435 // show inline completion
437 updateInline(cur, currentCompletion());
441 void GuiCompleter::showPopup(Cursor & cur)
443 if (!popupPossible(cur))
446 updateModel(cur, true, inlineVisible());
451 void GuiCompleter::showInline(Cursor & cur)
453 if (!inlinePossible(cur))
456 updateModel(cur, popupVisible(), true);
461 void GuiCompleter::showPopup()
463 Cursor cur = gui_->bufferView().cursor();
464 cur.updateFlags(Update::None);
469 if (cur.disp_.update())
470 gui_->bufferView().processUpdateFlags(cur.disp_.update());
474 void GuiCompleter::showInline()
476 Cursor cur = gui_->bufferView().cursor();
477 cur.updateFlags(Update::None);
482 if (cur.disp_.update())
483 gui_->bufferView().processUpdateFlags(cur.disp_.update());
487 void GuiCompleter::activate()
489 if (!popupVisible() && !inlineVisible())
492 // Complete with current selection in the popup.
493 QString s = currentCompletion();
499 void GuiCompleter::tab()
501 BufferView * bv = &gui_->bufferView();
502 Cursor cur = bv->cursor();
503 cur.updateFlags(Update::None);
505 // check that inline completion is active
506 if (!inlineVisible()) {
507 // try to activate the inline completion
508 if (cur.inset().inlineCompletionSupported(cur)) {
511 // show popup without delay because the completion was not unique
512 if (lyxrc.completion_popup_after_complete
514 && popup()->model()->rowCount() > 1)
515 popup_timer_.start(0);
520 if (!popupVisible() && cur.inset().completionSupported(cur)) {
528 // If completion is active, at least complete by one character
529 docstring prefix = cur.inset().completionPrefix(cur);
530 docstring completion = from_utf8(fromqstr(currentCompletion()));
531 if (completion.size() <= prefix.size()) {
532 // finalize completion
533 cur.inset().insertCompletion(cur, docstring(), true);
535 // hide popup and inline completion
537 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
538 inlineVisible_ = false;
539 updateVisibility(false, false);
542 docstring nextchar = completion.substr(prefix.size(), 1);
543 if (!cur.inset().insertCompletion(cur, nextchar, false))
547 // try to complete as far as it is unique
548 docstring longestCompletion = longestUniqueCompletion();
549 prefix = cur.inset().completionPrefix(cur);
550 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
551 cur.inset().insertCompletion(cur, postfix, false);
552 old_cursor_ = bv->cursor();
555 // show popup without delay because the completion was not unique
556 if (lyxrc.completion_popup_after_complete
558 && popup()->model()->rowCount() > 1)
559 popup_timer_.start(0);
562 if (cur.disp_.update())
563 gui_->bufferView().processUpdateFlags(cur.disp_.update());
567 QString GuiCompleter::currentCompletion() const
569 if (!popup()->selectionModel()->hasSelection())
572 // Not sure if this is bug in Qt: currentIndex() always
573 // return the first element in the list.
574 QModelIndex idx = popup()->currentIndex();
575 return popup()->model()->data(idx, Qt::EditRole).toString();
579 void GuiCompleter::setCurrentCompletion(QString const & s)
581 QAbstractItemModel const & model = *popup()->model();
582 size_t n = model.rowCount();
586 // select the first if s is empty
587 if (s.length() == 0) {
589 popup()->setCurrentIndex(model.index(0, 0));
594 // iterate through list until the s is found
595 // FIXME: there must be a better way than this iteration
597 for (i = 0; i < n; ++i) {
599 = model.data(model.index(i, 0), Qt::EditRole).toString();
604 // select the first if none was found
609 popup()->setCurrentIndex(model.index(i, 0));
614 docstring GuiCompleter::longestUniqueCompletion() const {
615 QAbstractItemModel const & model = *popup()->model();
616 QString s = currentCompletion();
617 size_t n = model.rowCount();
619 // iterate through the completions and cut off where s differs
620 for (size_t i = 0; i < n && s.length() > 0; ++i) {
622 = model.data(model.index(i, 0), Qt::EditRole).toString();
624 // find common prefix
626 size_t isn = is.length();
627 size_t sn = s.length();
628 for (j = 0; j < isn && j < sn; ++j) {
629 if (s.at(j) != is.at(j))
635 return from_utf8(fromqstr(s));
639 void GuiCompleter::popupActivated(const QString & completion)
641 Cursor cur = gui_->bufferView().cursor();
642 cur.updateFlags(Update::None);
644 docstring prefix = cur.inset().completionPrefix(cur);
645 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
646 cur.inset().insertCompletion(cur, postfix, true);
647 updateVisibility(cur, false);
649 if (cur.disp_.update())
650 gui_->bufferView().processUpdateFlags(cur.disp_.update());
654 void GuiCompleter::popupHighlighted(const QString & completion)
659 Cursor cur = gui_->bufferView().cursor();
660 cur.updateFlags(Update::None);
662 updateInline(cur, completion);
664 if (cur.disp_.update())
665 gui_->bufferView().processUpdateFlags(cur.disp_.update());
668 } // namespace frontend
671 #include "GuiCompleter_moc.cpp"