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::CompletionListPtr l)
76 : QAbstractListModel(parent), list(l) {}
78 int columnCount(const QModelIndex & parent = QModelIndex()) const
83 int rowCount(const QModelIndex & parent = QModelIndex()) const
92 QVariant data(const QModelIndex & index, int role) const
97 if (index.row() < 0 || index.row() >= rowCount())
100 if (role != Qt::DisplayRole && role != Qt::EditRole)
103 if (index.column() == 0)
104 return toqstr(list->data(index.row()));
105 else if (index.column() == 1) {
106 // get icon from cache
108 QString const name = ":" + toqstr(list->icon(index.row()));
109 if (!QPixmapCache::find("completion" + name, scaled)) {
110 // load icon from disk
111 QPixmap p = QPixmap(name);
113 // scale it to 16x16 or smaller
115 = p.scaled(min(16, p.width()), min(16, p.height()),
116 Qt::KeepAspectRatio, Qt::SmoothTransformation);
119 QPixmapCache::insert("completion" + name, scaled);
128 Inset::CompletionListPtr list;
132 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
133 : QCompleter(parent), gui_(gui), updateLock_(0)
135 // Setup the completion popup
136 setModel(new GuiCompletionModel(this, Inset::CompletionListPtr()));
137 setCompletionMode(QCompleter::PopupCompletion);
141 QTreeView *listView = new QTreeView;
142 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
143 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
144 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
145 listView->setSelectionMode(QAbstractItemView::SingleSelection);
146 listView->header()->hide();
147 listView->setIndentation(0);
149 popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(popup()));
151 // create timeout timers
152 popup_timer_.setSingleShot(true);
153 inline_timer_.setSingleShot(true);
154 connect(this, SIGNAL(highlighted(const QString &)),
155 this, SLOT(popupHighlighted(const QString &)));
156 connect(this, SIGNAL(activated(const QString &)),
157 this, SLOT(popupActivated(const QString &)));
158 connect(&popup_timer_, SIGNAL(timeout()),
159 this, SLOT(showPopup()));
160 connect(&inline_timer_, SIGNAL(timeout()),
161 this, SLOT(showInline()));
165 GuiCompleter::~GuiCompleter()
171 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
173 // hijack back the tab key from the popup
174 // (which stole it from the workspace before)
175 if (e->type() == QEvent::KeyPress && popupVisible()) {
176 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
186 return QCompleter::eventFilter(watched, e);
190 bool GuiCompleter::popupPossible(Cursor const & cur) const
192 return QApplication::activeWindow()
194 && cur.inset().completionSupported(cur);
198 bool GuiCompleter::inlinePossible(Cursor const & cur) const
200 return cur.inset().inlineCompletionSupported(cur);
204 bool GuiCompleter::popupVisible() const
206 return popup()->isVisible();
210 bool GuiCompleter::inlineVisible() const
212 return !gui_->bufferView().inlineCompletionPos().empty();
216 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
218 // parameters which affect the completion
219 bool moved = cur != old_cursor_;
223 bool possiblePopupState = popupPossible(cur) && cursorInView;
224 bool possibleInlineState = inlinePossible(cur) && cursorInView;
226 // we moved or popup state is not ok for popup?
227 if ((moved && !keep) || !possiblePopupState) {
228 // stop an old completion timer
229 if (popup_timer_.isActive())
237 // we moved or inline state is not ok for inline completion?
238 if ((moved && !keep) || !possibleInlineState) {
239 // stop an old completion timer
240 if (inline_timer_.isActive())
241 inline_timer_.stop();
243 // hide old inline completion
245 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
248 // we inserted something and are in a possible popup state?
249 if (!popupVisible() && possiblePopupState && start
250 && cur.inset().automaticPopupCompletion())
251 popup_timer_.start(lyxrc.completion_popup_delay * 1000.0);
253 // we inserted something and are in a possible inline completion state?
254 if (!inlineVisible() && possibleInlineState && start
255 && cur.inset().automaticInlineCompletion())
256 inline_timer_.start(lyxrc.completion_inline_delay * 1000.0);
258 // update prefix if popup is visible or if it will be visible soon
259 if (popupVisible() || inlineVisible()
260 || popup_timer_.isActive() || inline_timer_.isActive())
265 void GuiCompleter::updateVisibility(bool start, bool keep)
267 Cursor cur = gui_->bufferView().cursor();
268 cur.updateFlags(Update::None);
270 updateVisibility(cur, start, keep);
272 if (cur.disp_.update())
273 gui_->bufferView().processUpdateFlags(cur.disp_.update());
277 void GuiCompleter::updatePrefix(Cursor & cur)
279 // get new prefix. Do nothing if unchanged
280 QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
281 if (newPrefix == completionPrefix())
284 // value which should be kept selected
285 QString old = currentCompletion();
286 if (old.length() == 0)
287 old = last_selection_;
289 // update completer to new prefix
290 setCompletionPrefix(newPrefix);
292 // update popup because its size might have changed
296 // restore old selection
297 setCurrentCompletion(old);
299 // if popup is not empty, the new selection will
300 // be our last valid one
301 QString const & s = currentCompletion();
305 last_selection_ = old;
307 // update inline completion because the default
308 // completion string might have changed
310 updateInline(cur, s);
314 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
316 if (!cur.inset().inlineCompletionSupported(cur))
320 docstring prefix = cur.inset().completionPrefix(cur);
321 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
323 // shorten it if necessary
324 if (lyxrc.completion_inline_dots != -1
325 && postfix.size() > unsigned(lyxrc.completion_inline_dots))
326 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
328 // set inline completion at cursor position
329 size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
330 gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
334 void GuiCompleter::updatePopup(Cursor & cur)
336 if (!cur.inset().completionSupported(cur))
339 if (completionCount() == 0)
342 // get dimensions of completion prefix
346 cur.inset().completionPosAndDim(cur, x, y, dim);
347 QRect insetRect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
351 QTreeView * p = static_cast<QTreeView *>(popup());
352 p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
356 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
358 // value which should be kept selected
359 QString old = currentCompletion();
360 if (old.length() == 0)
361 old = last_selection_;
364 setModel(new GuiCompletionModel(this, cur.inset().completionList(cur)));
370 // restore old selection
371 setCurrentCompletion(old);
373 // if popup is not empty, the new selection will
374 // be our last valid one
375 QString const & s = currentCompletion();
379 last_selection_ = old;
381 // show inline completion
383 updateInline(cur, currentCompletion());
387 void GuiCompleter::showPopup(Cursor & cur)
389 if (!popupPossible(cur))
392 updateModel(cur, true, inlineVisible());
397 void GuiCompleter::showInline(Cursor & cur)
399 if (!inlinePossible(cur))
402 updateModel(cur, popupVisible(), true);
407 void GuiCompleter::showPopup()
409 Cursor cur = gui_->bufferView().cursor();
410 cur.updateFlags(Update::None);
415 if (cur.disp_.update())
416 gui_->bufferView().processUpdateFlags(cur.disp_.update());
420 void GuiCompleter::showInline()
422 Cursor cur = gui_->bufferView().cursor();
423 cur.updateFlags(Update::None);
428 if (cur.disp_.update())
429 gui_->bufferView().processUpdateFlags(cur.disp_.update());
433 void GuiCompleter::activate()
435 if (!popupVisible() && !inlineVisible())
438 // Complete with current selection in the popup.
439 QString s = currentCompletion();
445 void GuiCompleter::tab()
447 BufferView * bv = &gui_->bufferView();
448 Cursor cur = bv->cursor();
449 cur.updateFlags(Update::None);
451 // check that inline completion is active
452 if (!inlineVisible()) {
453 // try to activate the inline completion
454 if (cur.inset().inlineCompletionSupported(cur)) {
457 // show popup without delay because the completion was not unique
458 if (lyxrc.completion_popup_after_complete
460 && popup()->model()->rowCount() > 1)
461 popup_timer_.start(0);
466 if (!popupVisible() && cur.inset().completionSupported(cur)) {
474 // If completion is active, at least complete by one character
475 docstring prefix = cur.inset().completionPrefix(cur);
476 docstring completion = from_utf8(fromqstr(currentCompletion()));
477 if (completion.size() <= prefix.size()) {
478 // finalize completion
479 cur.inset().insertCompletion(cur, docstring(), true);
481 updateVisibility(false, false);
484 docstring nextchar = completion.substr(prefix.size(), 1);
485 if (!cur.inset().insertCompletion(cur, nextchar, false))
489 // try to complete as far as it is unique
490 docstring longestCompletion = longestUniqueCompletion();
491 prefix = cur.inset().completionPrefix(cur);
492 docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
493 cur.inset().insertCompletion(cur, postfix, false);
494 old_cursor_ = bv->cursor();
497 // show popup without delay because the completion was not unique
498 if (lyxrc.completion_popup_after_complete
500 && popup()->model()->rowCount() > 1)
501 popup_timer_.start(0);
504 if (cur.disp_.update())
505 gui_->bufferView().processUpdateFlags(cur.disp_.update());
509 QString GuiCompleter::currentCompletion() const
511 if (!popup()->selectionModel()->hasSelection())
514 // Not sure if this is bug in Qt: currentIndex() always
515 // return the first element in the list.
516 QModelIndex idx = popup()->currentIndex();
517 return popup()->model()->data(idx, Qt::EditRole).toString();
521 void GuiCompleter::setCurrentCompletion(QString const & s)
523 QAbstractItemModel const & model = *popup()->model();
524 size_t n = model.rowCount();
528 // select the first if s is empty
529 if (s.length() == 0) {
531 popup()->setCurrentIndex(model.index(0, 0));
536 // iterate through list until the s is found
537 // FIXME: there must be a better way than this iteration
539 for (i = 0; i < n; ++i) {
541 = model.data(model.index(i, 0), Qt::EditRole).toString();
546 // select the first if none was found
551 popup()->setCurrentIndex(model.index(i, 0));
556 docstring GuiCompleter::longestUniqueCompletion() const {
557 QAbstractItemModel const & model = *popup()->model();
558 QString s = currentCompletion();
559 size_t n = model.rowCount();
561 // iterate through the completions and cut off where s differs
562 for (size_t i = 0; i < n && s.length() > 0; ++i) {
564 = model.data(model.index(i, 0), Qt::EditRole).toString();
566 // find common prefix
568 size_t isn = is.length();
569 size_t sn = s.length();
570 for (j = 0; j < isn && j < sn; ++j) {
571 if (s.at(j) != is.at(j))
577 return from_utf8(fromqstr(s));
581 void GuiCompleter::popupActivated(const QString & completion)
583 Cursor cur = gui_->bufferView().cursor();
584 cur.updateFlags(Update::None);
586 docstring prefix = cur.inset().completionPrefix(cur);
587 docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
588 cur.inset().insertCompletion(cur, postfix, true);
589 updateVisibility(cur, false);
591 if (cur.disp_.update())
592 gui_->bufferView().processUpdateFlags(cur.disp_.update());
596 void GuiCompleter::popupHighlighted(const QString & completion)
601 Cursor cur = gui_->bufferView().cursor();
602 cur.updateFlags(Update::None);
604 updateInline(cur, completion);
606 if (cur.disp_.update())
607 gui_->bufferView().processUpdateFlags(cur.disp_.update());
610 } // namespace frontend
613 #include "GuiCompleter_moc.cpp"