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"
25 #include "support/debug.h"
27 #include <QApplication>
28 #include <QAbstractListModel>
29 #include <QHeaderView>
31 #include <QPixmapCache>
33 #include <QItemDelegate>
38 using namespace lyx::support;
44 class PixmapItemDelegate : public QItemDelegate {
46 explicit PixmapItemDelegate(QObject *parent = 0)
47 : QItemDelegate(parent) {}
50 void paint(QPainter *painter, const QStyleOptionViewItem &option,
51 const QModelIndex &index) const
53 QStyleOptionViewItemV3 opt = setOptions(index, option);
54 QVariant value = index.data(Qt::DisplayRole);
55 QPixmap pixmap = qvariant_cast<QPixmap>(value);
59 drawBackground(painter, opt, index);
60 if (!pixmap.isNull()) {
61 const QSize size = pixmap.size();
62 painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
63 option.rect.top() + (option.rect.height() - size.height()) / 2,
66 drawFocus(painter, opt, option.rect);
72 class GuiCompletionModel : public QAbstractListModel {
75 GuiCompletionModel(QObject * parent, Inset::CompletionList const * l)
76 : QAbstractListModel(parent), list_(l) {}
81 int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
86 int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
95 QVariant data(const QModelIndex & index, int role) const
100 if (index.row() < 0 || index.row() >= rowCount())
103 if (role != Qt::DisplayRole && role != Qt::EditRole)
106 if (index.column() == 0)
107 return toqstr(list_->data(index.row()));
108 else if (index.column() == 1) {
109 // get icon from cache
111 QString const name = ":" + toqstr(list_->icon(index.row()));
112 if (!QPixmapCache::find("completion" + name, scaled)) {
113 // load icon from disk
114 QPixmap p = QPixmap(name);
116 // scale it to 16x16 or smaller
118 = p.scaled(min(16, p.width()), min(16, p.height()),
119 Qt::KeepAspectRatio, Qt::SmoothTransformation);
122 QPixmapCache::insert("completion" + name, scaled);
131 Inset::CompletionList const * list_;
135 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
136 : QCompleter(parent), gui_(gui), updateLock_(0)
138 // Setup the completion popup
139 setModel(new GuiCompletionModel(this, 0));
140 setCompletionMode(QCompleter::PopupCompletion);
144 QTreeView *listView = new QTreeView;
145 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
146 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
147 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
148 listView->setSelectionMode(QAbstractItemView::SingleSelection);
149 listView->header()->hide();
150 listView->setIndentation(0);
152 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(popup()));
154 // create timeout timers
155 popup_timer_.setSingleShot(true);
156 inline_timer_.setSingleShot(true);
157 connect(this, SIGNAL(highlighted(const QString &)),
158 this, SLOT(popupHighlighted(const QString &)));
159 connect(this, SIGNAL(activated(const QString &)),
160 this, SLOT(popupActivated(const QString &)));
161 connect(&popup_timer_, SIGNAL(timeout()),
162 this, SLOT(showPopup()));
163 connect(&inline_timer_, SIGNAL(timeout()),
164 this, SLOT(showInline()));
168 GuiCompleter::~GuiCompleter()
174 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
176 // hijack back the tab key from the popup
177 // (which stole it from the workspace before)
178 if (e->type() == QEvent::KeyPress && popupVisible()) {
179 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
189 return QCompleter::eventFilter(watched, e);
193 bool GuiCompleter::popupPossible(Cursor const & cur) const
195 return QApplication::activeWindow()
197 && cur.inset().completionSupported(cur);
201 bool GuiCompleter::inlinePossible(Cursor const & cur) const
203 return cur.inset().inlineCompletionSupported(cur);
207 bool GuiCompleter::popupVisible() const
209 return popup()->isVisible();
213 bool GuiCompleter::inlineVisible() const
215 return !gui_->bufferView().inlineCompletionPos().empty();
219 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
221 // parameters which affect the completion
222 bool moved = cur != old_cursor_;
226 bool possiblePopupState = popupPossible(cur) && cursorInView;
227 bool possibleInlineState = inlinePossible(cur) && cursorInView;
229 // we moved or popup state is not ok for popup?
230 if ((moved && !keep) || !possiblePopupState) {
231 // stop an old completion timer
232 if (popup_timer_.isActive())
240 // we moved or inline state is not ok for inline completion?
241 if ((moved && !keep) || !possibleInlineState) {
242 // stop an old completion timer
243 if (inline_timer_.isActive())
244 inline_timer_.stop();
246 // hide old inline completion
248 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
251 // we inserted something and are in a possible popup state?
252 if (!popupVisible() && possiblePopupState && start
253 && cur.inset().automaticPopupCompletion())
254 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
256 // we inserted something and are in a possible inline completion state?
257 if (!inlineVisible() && possibleInlineState && start
258 && cur.inset().automaticInlineCompletion())
259 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
261 // update prefix if popup is visible or if it will be visible soon
262 if (popupVisible() || inlineVisible()
263 || popup_timer_.isActive() || inline_timer_.isActive())
268 void GuiCompleter::updateVisibility(bool start, bool keep)
270 Cursor cur = gui_->bufferView().cursor();
271 cur.updateFlags(Update::None);
273 updateVisibility(cur, start, keep);
275 if (cur.disp_.update())
276 gui_->bufferView().processUpdateFlags(cur.disp_.update());
280 void GuiCompleter::updatePrefix(Cursor & cur)
282 // get new prefix. Do nothing if unchanged
283 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
284 if (newPrefix == completionPrefix())
287 // value which should be kept selected
288 QString old = currentCompletion();
289 if (old.length() == 0)
290 old = last_selection_;
292 // update completer to new prefix
293 setCompletionPrefix(newPrefix);
295 // update popup because its size might have changed
299 // restore old selection
300 setCurrentCompletion(old);
302 // if popup is not empty, the new selection will
303 // be our last valid one
304 QString const & s = currentCompletion();
308 last_selection_ = old;
310 // update inline completion because the default
311 // completion string might have changed
313 updateInline(cur, s);
317 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
319 if (!cur.inset().inlineCompletionSupported(cur))
323 docstring prefix = cur.inset().completionPrefix(cur);
324 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
326 // shorten it if necessary
327 if (lyxrc.completion_inline_dots != -1
328 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
329 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
331 // set inline completion at cursor position
332 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
333 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
337 void GuiCompleter::updatePopup(Cursor & cur)
339 if (!cur.inset().completionSupported(cur))
342 if (completionCount() == 0)
345 // get dimensions of completion prefix
349 cur.inset().completionPosAndDim(cur, x, y, dim);
350 QRect insetRect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
354 QTreeView * p = static_cast<QTreeView *>(popup());
355 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
359 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
361 // value which should be kept selected
362 QString old = currentCompletion();
363 if (old.length() == 0)
364 old = last_selection_;
367 setModel(new GuiCompletionModel(this, cur.inset().completionList(cur)));
373 // restore old selection
374 setCurrentCompletion(old);
376 // if popup is not empty, the new selection will
377 // be our last valid one
378 QString const & s = currentCompletion();
382 last_selection_ = old;
384 // show inline completion
386 updateInline(cur, currentCompletion());
390 void GuiCompleter::showPopup(Cursor & cur)
392 if (!popupPossible(cur))
395 updateModel(cur, true, inlineVisible());
400 void GuiCompleter::showInline(Cursor & cur)
402 if (!inlinePossible(cur))
405 updateModel(cur, popupVisible(), true);
410 void GuiCompleter::showPopup()
412 Cursor cur = gui_->bufferView().cursor();
413 cur.updateFlags(Update::None);
418 if (cur.disp_.update())
419 gui_->bufferView().processUpdateFlags(cur.disp_.update());
423 void GuiCompleter::showInline()
425 Cursor cur = gui_->bufferView().cursor();
426 cur.updateFlags(Update::None);
431 if (cur.disp_.update())
432 gui_->bufferView().processUpdateFlags(cur.disp_.update());
436 void GuiCompleter::activate()
438 if (!popupVisible() && !inlineVisible())
441 // Complete with current selection in the popup.
442 QString s = currentCompletion();
448 void GuiCompleter::tab()
450 BufferView * bv = &gui_->bufferView();
451 Cursor cur = bv->cursor();
452 cur.updateFlags(Update::None);
454 // check that inline completion is active
455 if (!inlineVisible()) {
456 // try to activate the inline completion
457 if (cur.inset().inlineCompletionSupported(cur)) {
460 // show popup without delay because the completion was not unique
461 if (lyxrc.completion_popup_after_complete
463 && popup()->model()->rowCount() > 1)
464 popup_timer_.start(0);
469 if (!popupVisible() && cur.inset().completionSupported(cur)) {
477 // If completion is active, at least complete by one character
478 docstring prefix = cur.inset().completionPrefix(cur);
479 docstring completion = from_utf8(fromqstr(currentCompletion()));
480 if (completion.size() <= prefix.size()) {
481 // finalize completion
482 cur.inset().insertCompletion(cur, docstring(), true);
484 updateVisibility(false, false);
487 docstring nextchar = completion.substr(prefix.size(), 1);
488 if (!cur.inset().insertCompletion(cur, nextchar, false))
492 // try to complete as far as it is unique
493 docstring longestCompletion = longestUniqueCompletion();
494 prefix = cur.inset().completionPrefix(cur);
495 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
496 cur.inset().insertCompletion(cur, postfix, false);
497 old_cursor_ = bv->cursor();
500 // show popup without delay because the completion was not unique
501 if (lyxrc.completion_popup_after_complete
503 && popup()->model()->rowCount() > 1)
504 popup_timer_.start(0);
507 if (cur.disp_.update())
508 gui_->bufferView().processUpdateFlags(cur.disp_.update());
512 QString GuiCompleter::currentCompletion() const
514 if (!popup()->selectionModel()->hasSelection())
517 // Not sure if this is bug in Qt: currentIndex() always
518 // return the first element in the list.
519 QModelIndex idx = popup()->currentIndex();
520 return popup()->model()->data(idx, Qt::EditRole).toString();
524 void GuiCompleter::setCurrentCompletion(QString const & s)
526 QAbstractItemModel const & model = *popup()->model();
527 size_t n = model.rowCount();
531 // select the first if s is empty
532 if (s.length() == 0) {
534 popup()->setCurrentIndex(model.index(0, 0));
539 // iterate through list until the s is found
540 // FIXME: there must be a better way than this iteration
542 for (i = 0; i < n; ++i) {
544 = model.data(model.index(i, 0), Qt::EditRole).toString();
549 // select the first if none was found
554 popup()->setCurrentIndex(model.index(i, 0));
559 docstring GuiCompleter::longestUniqueCompletion() const {
560 QAbstractItemModel const & model = *popup()->model();
561 QString s = currentCompletion();
562 size_t n = model.rowCount();
564 // iterate through the completions and cut off where s differs
565 for (size_t i = 0; i < n && s.length() > 0; ++i) {
567 = model.data(model.index(i, 0), Qt::EditRole).toString();
569 // find common prefix
571 size_t isn = is.length();
572 size_t sn = s.length();
573 for (j = 0; j < isn && j < sn; ++j) {
574 if (s.at(j) != is.at(j))
580 return from_utf8(fromqstr(s));
584 void GuiCompleter::popupActivated(const QString & completion)
586 Cursor cur = gui_->bufferView().cursor();
587 cur.updateFlags(Update::None);
589 docstring prefix = cur.inset().completionPrefix(cur);
590 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
591 cur.inset().insertCompletion(cur, postfix, true);
592 updateVisibility(cur, false);
594 if (cur.disp_.update())
595 gui_->bufferView().processUpdateFlags(cur.disp_.update());
599 void GuiCompleter::popupHighlighted(const QString & completion)
604 Cursor cur = gui_->bufferView().cursor();
605 cur.updateFlags(Update::None);
607 updateInline(cur, completion);
609 if (cur.disp_.update())
610 gui_->bufferView().processUpdateFlags(cur.disp_.update());
613 } // namespace frontend
616 #include "GuiCompleter_moc.cpp"