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;
45 class PixmapItemDelegate : public QItemDelegate {
47 explicit PixmapItemDelegate(QObject *parent = 0)
48 : QItemDelegate(parent) {}
51 void paint(QPainter *painter, const QStyleOptionViewItem &option,
52 const QModelIndex &index) const
54 QStyleOptionViewItem opt = setOptions(index, option);
55 QVariant value = index.data(Qt::DisplayRole);
56 QPixmap pixmap = qvariant_cast<QPixmap>(value);
60 drawBackground(painter, opt, index);
61 if (!pixmap.isNull()) {
62 const QSize size = pixmap.size();
63 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
64 option.rect.top() + (option.rect.height() - size.height()) / 2,
67 drawFocus(painter, opt, option.rect);
73 class GuiCompletionModel : public QAbstractListModel {
76 GuiCompletionModel(QObject * parent,
77 Inset::CompletionList const * l, bool rtl)
78 : QAbstractListModel(parent), list_(l), rtl_(rtl) {}
83 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
88 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
97 QVariant data(const QModelIndex & index, int role) const
102 if (index.row() < 0 || index.row() >= rowCount())
105 if (role != Qt::DisplayRole && role != Qt::EditRole)
108 if (index.column() == 0) {
109 docstring s = list_->data(index.row());
111 reverse(s.begin(), s.end());
113 } else if (index.column() == 1) {
114 // get icon from cache
116 QString const name = ":" + toqstr(list_->icon(index.row()));
117 if (!QPixmapCache::find("completion" + name, scaled)) {
118 // load icon from disk
119 QPixmap p = QPixmap(name);
121 // scale it to 16x16 or smaller
123 = p.scaled(min(16, p.width()), min(16, p.height()),
124 Qt::KeepAspectRatio, Qt::SmoothTransformation);
127 QPixmapCache::insert("completion" + name, scaled);
142 Inset::CompletionList const * list_;
148 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
149 : QCompleter(parent), gui_(gui), updateLock_(0)
151 // Setup the completion popup
152 setModel(new GuiCompletionModel(this, 0, false));
153 setCompletionMode(QCompleter::PopupCompletion);
157 QTreeView *listView = new QTreeView;
158 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
159 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
160 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
161 listView->setSelectionMode(QAbstractItemView::SingleSelection);
162 listView->header()->hide();
163 listView->setIndentation(0);
165 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(popup()));
167 // create timeout timers
168 popup_timer_.setSingleShot(true);
169 inline_timer_.setSingleShot(true);
170 connect(this, SIGNAL(highlighted(const QString &)),
171 this, SLOT(popupHighlighted(const QString &)));
172 connect(this, SIGNAL(activated(const QString &)),
173 this, SLOT(popupActivated(const QString &)));
174 connect(&popup_timer_, SIGNAL(timeout()),
175 this, SLOT(showPopup()));
176 connect(&inline_timer_, SIGNAL(timeout()),
177 this, SLOT(showInline()));
181 GuiCompleter::~GuiCompleter()
187 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
189 // hijack back the tab key from the popup
190 // (which stole it from the workspace before)
191 if (e->type() == QEvent::KeyPress && popupVisible()) {
192 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
202 return QCompleter::eventFilter(watched, e);
206 bool GuiCompleter::popupPossible(Cursor const & cur) const
208 return QApplication::activeWindow()
210 && cur.inset().completionSupported(cur);
214 bool GuiCompleter::inlinePossible(Cursor const & cur) const
216 return cur.inset().inlineCompletionSupported(cur);
220 bool GuiCompleter::popupVisible() const
222 return popup()->isVisible();
226 bool GuiCompleter::inlineVisible() const
228 return !gui_->bufferView().inlineCompletionPos().empty();
232 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
234 // parameters which affect the completion
235 bool moved = cur != old_cursor_;
239 bool possiblePopupState = popupPossible(cur) && cursorInView;
240 bool possibleInlineState = inlinePossible(cur) && cursorInView;
242 // we moved or popup state is not ok for popup?
243 if ((moved && !keep) || !possiblePopupState) {
244 // stop an old completion timer
245 if (popup_timer_.isActive())
253 // we moved or inline state is not ok for inline completion?
254 if ((moved && !keep) || !possibleInlineState) {
255 // stop an old completion timer
256 if (inline_timer_.isActive())
257 inline_timer_.stop();
259 // hide old inline completion
261 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
264 // we inserted something and are in a possible popup state?
265 if (!popupVisible() && possiblePopupState && start
266 && cur.inset().automaticPopupCompletion())
267 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
269 // we inserted something and are in a possible inline completion state?
270 if (!inlineVisible() && possibleInlineState && start
271 && cur.inset().automaticInlineCompletion())
272 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
274 // update prefix if popup is visible or if it will be visible soon
275 if (popupVisible() || inlineVisible()
276 || popup_timer_.isActive() || inline_timer_.isActive())
281 void GuiCompleter::updateVisibility(bool start, bool keep)
283 Cursor cur = gui_->bufferView().cursor();
284 cur.updateFlags(Update::None);
286 updateVisibility(cur, start, keep);
288 if (cur.disp_.update())
289 gui_->bufferView().processUpdateFlags(cur.disp_.update());
293 void GuiCompleter::updatePrefix(Cursor & cur)
295 // get new prefix. Do nothing if unchanged
296 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
297 if (newPrefix == completionPrefix())
300 // value which should be kept selected
301 QString old = currentCompletion();
302 if (old.length() == 0)
303 old = last_selection_;
305 // update completer to new prefix
306 setCompletionPrefix(newPrefix);
308 // update popup because its size might have changed
312 // restore old selection
313 setCurrentCompletion(old);
315 // if popup is not empty, the new selection will
316 // be our last valid one
317 QString const & s = currentCompletion();
321 last_selection_ = old;
323 // update inline completion because the default
324 // completion string might have changed
326 updateInline(cur, s);
330 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
332 if (!cur.inset().inlineCompletionSupported(cur))
336 docstring prefix = cur.inset().completionPrefix(cur);
337 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
339 // shorten it if necessary
340 if (lyxrc.completion_inline_dots != -1
341 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
342 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
344 // set inline completion at cursor position
345 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
346 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
350 void GuiCompleter::updatePopup(Cursor & cur)
352 if (!cur.inset().completionSupported(cur))
355 if (completionCount() == 0)
358 // get dimensions of completion prefix
362 cur.inset().completionPosAndDim(cur, x, y, dim);
364 // and calculate the rect of the popup
366 if (static_cast<GuiCompletionModel const *>(model())->rtl())
367 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
369 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
373 QTreeView * p = static_cast<QTreeView *>(popup());
374 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
378 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
380 // value which should be kept selected
381 QString old = currentCompletion();
382 if (old.length() == 0)
383 old = last_selection_;
387 if (cur.inTexted()) {
388 Paragraph const & par = cur.paragraph();
390 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
391 rtl = font.isVisibleRightToLeft();
393 popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
396 Inset::CompletionList const * list
397 = cur.inset().createCompletionList(cur);
398 setModel(new GuiCompletionModel(this, list, rtl));
404 // restore old selection
405 setCurrentCompletion(old);
407 // if popup is not empty, the new selection will
408 // be our last valid one
409 QString const & s = currentCompletion();
413 last_selection_ = old;
415 // show inline completion
417 updateInline(cur, currentCompletion());
421 void GuiCompleter::showPopup(Cursor & cur)
423 if (!popupPossible(cur))
426 updateModel(cur, true, inlineVisible());
431 void GuiCompleter::showInline(Cursor & cur)
433 if (!inlinePossible(cur))
436 updateModel(cur, popupVisible(), true);
441 void GuiCompleter::showPopup()
443 Cursor cur = gui_->bufferView().cursor();
444 cur.updateFlags(Update::None);
449 if (cur.disp_.update())
450 gui_->bufferView().processUpdateFlags(cur.disp_.update());
454 void GuiCompleter::showInline()
456 Cursor cur = gui_->bufferView().cursor();
457 cur.updateFlags(Update::None);
462 if (cur.disp_.update())
463 gui_->bufferView().processUpdateFlags(cur.disp_.update());
467 void GuiCompleter::activate()
469 if (!popupVisible() && !inlineVisible())
472 // Complete with current selection in the popup.
473 QString s = currentCompletion();
479 void GuiCompleter::tab()
481 BufferView * bv = &gui_->bufferView();
482 Cursor cur = bv->cursor();
483 cur.updateFlags(Update::None);
485 // check that inline completion is active
486 if (!inlineVisible()) {
487 // try to activate the inline completion
488 if (cur.inset().inlineCompletionSupported(cur)) {
491 // show popup without delay because the completion was not unique
492 if (lyxrc.completion_popup_after_complete
494 && popup()->model()->rowCount() > 1)
495 popup_timer_.start(0);
500 if (!popupVisible() && cur.inset().completionSupported(cur)) {
508 // If completion is active, at least complete by one character
509 docstring prefix = cur.inset().completionPrefix(cur);
510 docstring completion = from_utf8(fromqstr(currentCompletion()));
511 if (completion.size() <= prefix.size()) {
512 // finalize completion
513 cur.inset().insertCompletion(cur, docstring(), true);
515 updateVisibility(false, false);
518 docstring nextchar = completion.substr(prefix.size(), 1);
519 if (!cur.inset().insertCompletion(cur, nextchar, false))
523 // try to complete as far as it is unique
524 docstring longestCompletion = longestUniqueCompletion();
525 prefix = cur.inset().completionPrefix(cur);
526 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
527 cur.inset().insertCompletion(cur, postfix, false);
528 old_cursor_ = bv->cursor();
531 // show popup without delay because the completion was not unique
532 if (lyxrc.completion_popup_after_complete
534 && popup()->model()->rowCount() > 1)
535 popup_timer_.start(0);
538 if (cur.disp_.update())
539 gui_->bufferView().processUpdateFlags(cur.disp_.update());
543 QString GuiCompleter::currentCompletion() const
545 if (!popup()->selectionModel()->hasSelection())
548 // Not sure if this is bug in Qt: currentIndex() always
549 // return the first element in the list.
550 QModelIndex idx = popup()->currentIndex();
551 return popup()->model()->data(idx, Qt::EditRole).toString();
555 void GuiCompleter::setCurrentCompletion(QString const & s)
557 QAbstractItemModel const & model = *popup()->model();
558 size_t n = model.rowCount();
562 // select the first if s is empty
563 if (s.length() == 0) {
565 popup()->setCurrentIndex(model.index(0, 0));
570 // iterate through list until the s is found
571 // FIXME: there must be a better way than this iteration
573 for (i = 0; i < n; ++i) {
575 = model.data(model.index(i, 0), Qt::EditRole).toString();
580 // select the first if none was found
585 popup()->setCurrentIndex(model.index(i, 0));
590 docstring GuiCompleter::longestUniqueCompletion() const {
591 QAbstractItemModel const & model = *popup()->model();
592 QString s = currentCompletion();
593 size_t n = model.rowCount();
595 // iterate through the completions and cut off where s differs
596 for (size_t i = 0; i < n && s.length() > 0; ++i) {
598 = model.data(model.index(i, 0), Qt::EditRole).toString();
600 // find common prefix
602 size_t isn = is.length();
603 size_t sn = s.length();
604 for (j = 0; j < isn && j < sn; ++j) {
605 if (s.at(j) != is.at(j))
611 return from_utf8(fromqstr(s));
615 void GuiCompleter::popupActivated(const QString & completion)
617 Cursor cur = gui_->bufferView().cursor();
618 cur.updateFlags(Update::None);
620 docstring prefix = cur.inset().completionPrefix(cur);
621 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
622 cur.inset().insertCompletion(cur, postfix, true);
623 updateVisibility(cur, false);
625 if (cur.disp_.update())
626 gui_->bufferView().processUpdateFlags(cur.disp_.update());
630 void GuiCompleter::popupHighlighted(const QString & completion)
635 Cursor cur = gui_->bufferView().cursor();
636 cur.updateFlags(Update::None);
638 updateInline(cur, completion);
640 if (cur.disp_.update())
641 gui_->bufferView().processUpdateFlags(cur.disp_.update());
644 } // namespace frontend
647 #include "GuiCompleter_moc.cpp"