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 QStyleOptionViewItem 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 Inset::CompletionList const * list
368 = cur.inset().createCompletionList(cur);
369 setModel(new GuiCompletionModel(this, list));
375 // restore old selection
376 setCurrentCompletion(old);
378 // if popup is not empty, the new selection will
379 // be our last valid one
380 QString const & s = currentCompletion();
384 last_selection_ = old;
386 // show inline completion
388 updateInline(cur, currentCompletion());
392 void GuiCompleter::showPopup(Cursor & cur)
394 if (!popupPossible(cur))
397 updateModel(cur, true, inlineVisible());
402 void GuiCompleter::showInline(Cursor & cur)
404 if (!inlinePossible(cur))
407 updateModel(cur, popupVisible(), true);
412 void GuiCompleter::showPopup()
414 Cursor cur = gui_->bufferView().cursor();
415 cur.updateFlags(Update::None);
420 if (cur.disp_.update())
421 gui_->bufferView().processUpdateFlags(cur.disp_.update());
425 void GuiCompleter::showInline()
427 Cursor cur = gui_->bufferView().cursor();
428 cur.updateFlags(Update::None);
433 if (cur.disp_.update())
434 gui_->bufferView().processUpdateFlags(cur.disp_.update());
438 void GuiCompleter::activate()
440 if (!popupVisible() && !inlineVisible())
443 // Complete with current selection in the popup.
444 QString s = currentCompletion();
450 void GuiCompleter::tab()
452 BufferView * bv = &gui_->bufferView();
453 Cursor cur = bv->cursor();
454 cur.updateFlags(Update::None);
456 // check that inline completion is active
457 if (!inlineVisible()) {
458 // try to activate the inline completion
459 if (cur.inset().inlineCompletionSupported(cur)) {
462 // show popup without delay because the completion was not unique
463 if (lyxrc.completion_popup_after_complete
465 && popup()->model()->rowCount() > 1)
466 popup_timer_.start(0);
471 if (!popupVisible() && cur.inset().completionSupported(cur)) {
479 // If completion is active, at least complete by one character
480 docstring prefix = cur.inset().completionPrefix(cur);
481 docstring completion = from_utf8(fromqstr(currentCompletion()));
482 if (completion.size() <= prefix.size()) {
483 // finalize completion
484 cur.inset().insertCompletion(cur, docstring(), true);
486 updateVisibility(false, false);
489 docstring nextchar = completion.substr(prefix.size(), 1);
490 if (!cur.inset().insertCompletion(cur, nextchar, false))
494 // try to complete as far as it is unique
495 docstring longestCompletion = longestUniqueCompletion();
496 prefix = cur.inset().completionPrefix(cur);
497 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
498 cur.inset().insertCompletion(cur, postfix, false);
499 old_cursor_ = bv->cursor();
502 // show popup without delay because the completion was not unique
503 if (lyxrc.completion_popup_after_complete
505 && popup()->model()->rowCount() > 1)
506 popup_timer_.start(0);
509 if (cur.disp_.update())
510 gui_->bufferView().processUpdateFlags(cur.disp_.update());
514 QString GuiCompleter::currentCompletion() const
516 if (!popup()->selectionModel()->hasSelection())
519 // Not sure if this is bug in Qt: currentIndex() always
520 // return the first element in the list.
521 QModelIndex idx = popup()->currentIndex();
522 return popup()->model()->data(idx, Qt::EditRole).toString();
526 void GuiCompleter::setCurrentCompletion(QString const & s)
528 QAbstractItemModel const & model = *popup()->model();
529 size_t n = model.rowCount();
533 // select the first if s is empty
534 if (s.length() == 0) {
536 popup()->setCurrentIndex(model.index(0, 0));
541 // iterate through list until the s is found
542 // FIXME: there must be a better way than this iteration
544 for (i = 0; i < n; ++i) {
546 = model.data(model.index(i, 0), Qt::EditRole).toString();
551 // select the first if none was found
556 popup()->setCurrentIndex(model.index(i, 0));
561 docstring GuiCompleter::longestUniqueCompletion() const {
562 QAbstractItemModel const & model = *popup()->model();
563 QString s = currentCompletion();
564 size_t n = model.rowCount();
566 // iterate through the completions and cut off where s differs
567 for (size_t i = 0; i < n && s.length() > 0; ++i) {
569 = model.data(model.index(i, 0), Qt::EditRole).toString();
571 // find common prefix
573 size_t isn = is.length();
574 size_t sn = s.length();
575 for (j = 0; j < isn && j < sn; ++j) {
576 if (s.at(j) != is.at(j))
582 return from_utf8(fromqstr(s));
586 void GuiCompleter::popupActivated(const QString & completion)
588 Cursor cur = gui_->bufferView().cursor();
589 cur.updateFlags(Update::None);
591 docstring prefix = cur.inset().completionPrefix(cur);
592 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
593 cur.inset().insertCompletion(cur, postfix, true);
594 updateVisibility(cur, false);
596 if (cur.disp_.update())
597 gui_->bufferView().processUpdateFlags(cur.disp_.update());
601 void GuiCompleter::popupHighlighted(const QString & completion)
606 Cursor cur = gui_->bufferView().cursor();
607 cur.updateFlags(Update::None);
609 updateInline(cur, completion);
611 if (cur.disp_.update())
612 gui_->bufferView().processUpdateFlags(cur.disp_.update());
615 } // namespace frontend
618 #include "GuiCompleter_moc.cpp"