]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
b50b472f3466e3058131648c128f49070e7044e4
[lyx.git] / src / frontends / qt4 / GuiCompleter.cpp
1 /**
2  * \file GuiCompleter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Stefan Schimanski
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiWorkArea.h"
14
15 #include "Buffer.h"
16 #include "BufferView.h"
17 #include "Cursor.h"
18 #include "Dimension.h"
19 #include "FuncRequest.h"
20 #include "GuiView.h"
21 #include "LyXFunc.h"
22 #include "LyXRC.h"
23 #include "Paragraph.h"
24 #include "version.h"
25
26 #include "support/debug.h"
27
28 #include <QApplication>
29 #include <QAbstractListModel>
30 #include <QHeaderView>
31 #include <QPainter>
32 #include <QPixmapCache>
33 #include <QScrollBar>
34 #include <QItemDelegate>
35 #include <QTreeView>
36 #include <QTimer>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42 namespace frontend {
43
44 class RtlItemDelegate : public QItemDelegate {
45 public:
46         explicit RtlItemDelegate(QObject * parent = 0)
47                 : QItemDelegate(parent) {}
48
49 protected:
50         virtual void drawDisplay(QPainter * painter,
51                 QStyleOptionViewItem const & option,
52                 QRect const & rect, QString const & text) const
53         {
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));
58         }
59 };
60
61
62 class PixmapItemDelegate : public QItemDelegate {
63 public:
64         explicit PixmapItemDelegate(QObject *parent = 0)
65         : QItemDelegate(parent) {}
66
67 protected:
68         void paint(QPainter *painter, const QStyleOptionViewItem &option,
69                    const QModelIndex &index) const
70         {
71                 QStyleOptionViewItem opt = setOptions(index, option);
72                 QVariant value = index.data(Qt::DisplayRole);
73                 QPixmap pixmap = qvariant_cast<QPixmap>(value);
74                 
75                 // draw
76                 painter->save();
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,
82                                 pixmap);
83                 }
84                 drawFocus(painter, opt, option.rect);
85                 painter->restore();
86         }
87 };
88
89
90 class GuiCompletionModel : public QAbstractListModel {
91 public:
92         ///
93         GuiCompletionModel(QObject * parent,
94                 Inset::CompletionList const * l)
95                 : QAbstractListModel(parent), list_(l) {}
96         ///
97         ~GuiCompletionModel()
98                 { delete list_; }
99         ///
100         bool sorted() const
101         {
102                 if (list_)
103                         return list_->sorted();
104                 else
105                         return false;
106         }
107         ///
108         int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
109         {
110                 return 2;
111         }
112         ///
113         int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
114         {
115                 if (list_ == 0)
116                         return 0;
117                 else
118                         return list_->size();
119         }
120
121         ///
122         QVariant data(const QModelIndex & index, int role) const
123         {
124                 if (list_ == 0)
125                         return QVariant();
126
127                 if (index.row() < 0 || index.row() >= rowCount())
128                         return QVariant();
129
130                 if (role != Qt::DisplayRole && role != Qt::EditRole)
131                     return QVariant();
132                     
133                 if (index.column() == 0)
134                         return toqstr(list_->data(index.row()));
135                 else if (index.column() == 1) {
136                         // get icon from cache
137                         QPixmap scaled;
138                         QString const name = ":" + toqstr(list_->icon(index.row()));
139                         if (!QPixmapCache::find("completion" + name, scaled)) {
140                                 // load icon from disk
141                                 QPixmap p = QPixmap(name);
142                                 if (!p.isNull()) {
143                                         // scale it to 16x16 or smaller
144                                         scaled
145                                         = p.scaled(min(16, p.width()), min(16, p.height()), 
146                                                 Qt::KeepAspectRatio, Qt::SmoothTransformation);
147                                 }
148
149                                 QPixmapCache::insert("completion" + name, scaled);
150                         }
151                         return scaled;
152                 }
153                 return QVariant();
154         }
155
156 private:
157         ///
158         Inset::CompletionList const * list_;
159 };
160
161
162 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
163         : QCompleter(parent), gui_(gui), updateLock_(0),
164           inlineVisible_(false)
165 {
166         // Setup the completion popup
167         setModel(new GuiCompletionModel(this, 0));
168         setCompletionMode(QCompleter::PopupCompletion);
169         setWidget(gui_);
170         
171         // create the popup
172         QTreeView *listView = new QTreeView;
173         listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
174         listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
175         listView->setSelectionBehavior(QAbstractItemView::SelectRows);
176         listView->setSelectionMode(QAbstractItemView::SingleSelection);
177         listView->header()->hide();
178         listView->setIndentation(0);
179         setPopup(listView);
180         popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
181         rtlItemDelegate_ = new RtlItemDelegate(this);
182         
183         // create timeout timers
184         popup_timer_.setSingleShot(true);
185         inline_timer_.setSingleShot(true);
186         connect(this, SIGNAL(highlighted(const QString &)),
187                 this, SLOT(popupHighlighted(const QString &)));
188         connect(this, SIGNAL(activated(const QString &)),
189                 this, SLOT(popupActivated(const QString &)));
190         connect(&popup_timer_, SIGNAL(timeout()),
191                 this, SLOT(showPopup()));
192         connect(&inline_timer_, SIGNAL(timeout()),
193                 this, SLOT(showInline()));
194 }
195
196
197 GuiCompleter::~GuiCompleter()
198 {
199         popup()->hide();
200 }
201
202
203 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
204 {
205         // hijack back the tab key from the popup
206         // (which stole it from the workspace before)
207         if (e->type() == QEvent::KeyPress && popupVisible()) {
208                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
209                 switch (ke->key()) {
210                 case Qt::Key_Tab:
211                         tab();
212                         ke->accept();
213                         return true;
214                 default: break;
215                 }
216         }
217         
218         return QCompleter::eventFilter(watched, e);
219 }
220
221
222 bool GuiCompleter::popupPossible(Cursor const & cur) const
223 {
224         return QApplication::activeWindow()
225                 && gui_->hasFocus()
226                 && cur.inset().completionSupported(cur);
227 }
228
229
230 bool GuiCompleter::inlinePossible(Cursor const & cur) const
231 {
232         return cur.inset().inlineCompletionSupported(cur);
233 }
234
235
236 bool GuiCompleter::popupVisible() const
237 {
238         return popup()->isVisible();
239 }
240
241
242 bool GuiCompleter::inlineVisible() const
243 {
244         // In fact using BufferView::inlineCompletionPos.empty() should be
245         // here. But unfortunately this information is not good enough
246         // because destructive operations like backspace might invalidate
247         // inlineCompletionPos. But then the completion should stay visible
248         // (i.e. reshown on the next update). Hence be keep this information
249         // in the inlineVisible_ variable.
250         return inlineVisible_;
251 }
252
253
254 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
255 {
256         // parameters which affect the completion
257         bool moved = cur != old_cursor_;
258         if (moved)
259                 old_cursor_ = cur;
260
261         bool possiblePopupState = popupPossible(cur) && cursorInView;
262         bool possibleInlineState = inlinePossible(cur) && cursorInView;
263
264         // we moved or popup state is not ok for popup?
265         if ((moved && !keep) || !possiblePopupState) {
266                 // stop an old completion timer
267                 if (popup_timer_.isActive())
268                         popup_timer_.stop();
269
270                 // hide old popup
271                 if (popupVisible())
272                         popup()->hide();
273         }
274
275         // we moved or inline state is not ok for inline completion?
276         if ((moved && !keep) || !possibleInlineState) {
277                 // stop an old completion timer
278                 if (inline_timer_.isActive())
279                         inline_timer_.stop();
280
281                 // hide old inline completion
282                 if (inlineVisible()) {
283                         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
284                         inlineVisible_ = false;
285                 }
286         }
287
288         // we inserted something and are in a possible popup state?
289         if (!popupVisible() && possiblePopupState && start
290                 && cur.inset().automaticPopupCompletion())
291                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
292
293         // we inserted something and are in a possible inline completion state?
294         if (!inlineVisible() && possibleInlineState && start
295                 && cur.inset().automaticInlineCompletion())
296                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
297
298         // update prefix if popup is visible or if it will be visible soon
299         if (popupVisible() || inlineVisible()
300             || popup_timer_.isActive() || inline_timer_.isActive())
301                 updatePrefix(cur);
302 }
303
304
305 void GuiCompleter::updateVisibility(bool start, bool keep)
306 {
307         Cursor cur = gui_->bufferView().cursor();
308         cur.updateFlags(Update::None);
309         
310         updateVisibility(cur, start, keep);
311         
312         if (cur.disp_.update())
313                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
314 }
315
316
317 void GuiCompleter::updatePrefix(Cursor & cur)
318 {
319         // get new prefix. Do nothing if unchanged
320         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
321         if (newPrefix == completionPrefix())
322                 return;
323         
324         // value which should be kept selected
325         QString old = currentCompletion();
326         if (old.length() == 0)
327                 old = last_selection_;
328         
329         // update completer to new prefix
330         setCompletionPrefix(newPrefix);
331         
332         // update popup because its size might have changed
333         if (popupVisible())
334                 updatePopup(cur);
335
336         // restore old selection
337         setCurrentCompletion(old);
338         
339         // if popup is not empty, the new selection will
340         // be our last valid one
341         QString const & s = currentCompletion();
342         if (s.length() > 0)
343                 last_selection_ = s;
344         else
345                 last_selection_ = old;
346         
347         // update inline completion because the default
348         // completion string might have changed
349         if (inlineVisible())
350                 updateInline(cur, s);
351 }
352
353
354 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
355 {
356         if (!cur.inset().inlineCompletionSupported(cur))
357                 return;
358         
359         // compute postfix
360         docstring prefix = cur.inset().completionPrefix(cur);
361         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
362         
363         // shorten it if necessary
364         if (lyxrc.completion_inline_dots != -1
365             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
366                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
367
368         // set inline completion at cursor position
369         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
370         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
371         inlineVisible_ = true;
372 }
373
374
375 void GuiCompleter::updatePopup(Cursor & cur)
376 {
377         if (!cur.inset().completionSupported(cur))
378                 return;
379         
380         if (completionCount() == 0)
381                 return;
382         
383         // get dimensions of completion prefix
384         Dimension dim;
385         int x;
386         int y;
387         cur.inset().completionPosAndDim(cur, x, y, dim);
388         
389         // and calculate the rect of the popup
390         QRect rect;
391         if (popup()->layoutDirection() == Qt::RightToLeft)
392                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
393         else
394                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
395         
396         // show/update popup
397         complete(rect);
398         QTreeView * p = static_cast<QTreeView *>(popup());
399         p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
400 }
401
402
403 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
404 {
405         // value which should be kept selected
406         QString old = currentCompletion();
407         if (old.length() == 0)
408                 old = last_selection_;
409
410         // set whether rtl
411         bool rtl = false;
412         if (cur.inTexted()) {
413                 Paragraph const & par = cur.paragraph();
414                 Font const font =
415                 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
416                 rtl = font.isVisibleRightToLeft();
417         }
418         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
419
420         // turn the direction of the strings in the popup.
421         // Qt does not do that itself.
422         popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
423
424         // set new model
425         Inset::CompletionList const * list
426         = cur.inset().createCompletionList(cur);
427         setModel(new GuiCompletionModel(this, list));
428         if (list->sorted())
429                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
430         else
431                 setModelSorting(QCompleter::UnsortedModel);
432
433         // show popup
434         if (popupUpdate)
435                 updatePopup(cur);
436
437         // restore old selection
438         setCurrentCompletion(old);
439         
440         // if popup is not empty, the new selection will
441         // be our last valid one
442         QString const & s = currentCompletion();
443         if (s.length() > 0)
444                 last_selection_ = s;
445         else
446                 last_selection_ = old;
447         
448         // show inline completion
449         if (inlineUpdate)
450                 updateInline(cur, currentCompletion());
451 }
452
453
454 void GuiCompleter::showPopup(Cursor & cur)
455 {
456         if (!popupPossible(cur))
457                 return;
458         
459         updateModel(cur, true, inlineVisible());
460         updatePrefix(cur);
461 }
462         
463
464 void GuiCompleter::showInline(Cursor & cur)
465 {
466         if (!inlinePossible(cur))
467                 return;
468         
469         updateModel(cur, popupVisible(), true);
470         updatePrefix(cur);
471 }
472
473
474 void GuiCompleter::showPopup()
475 {
476         Cursor cur = gui_->bufferView().cursor();
477         cur.updateFlags(Update::None);
478         
479         showPopup(cur);
480
481         // redraw if needed
482         if (cur.disp_.update())
483                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
484 }
485
486
487 void GuiCompleter::showInline()
488 {
489         Cursor cur = gui_->bufferView().cursor();
490         cur.updateFlags(Update::None);
491         
492         showInline(cur);
493
494         // redraw if needed
495         if (cur.disp_.update())
496                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
497 }
498
499
500 void GuiCompleter::activate()
501 {
502         if (!popupVisible() && !inlineVisible())
503                 return;
504
505         // Complete with current selection in the popup.
506         QString s = currentCompletion();
507         popup()->hide();
508         popupActivated(s);
509 }
510
511
512 void GuiCompleter::tab()
513 {
514         BufferView * bv = &gui_->bufferView();
515         Cursor cur = bv->cursor();
516         cur.updateFlags(Update::None);
517         
518         // check that inline completion is active
519         if (!inlineVisible()) {
520                 // try to activate the inline completion
521                 if (cur.inset().inlineCompletionSupported(cur)) {
522                         showInline();
523                         
524                         // show popup without delay because the completion was not unique
525                         if (lyxrc.completion_popup_after_complete
526                             && !popupVisible()
527                             && popup()->model()->rowCount() > 1)
528                                 popup_timer_.start(0);
529
530                         return;
531                 }
532                 // or try popup
533                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
534                         showPopup();
535                         return;
536                 }
537                 
538                 return;
539         }
540         
541         // If completion is active, at least complete by one character
542         docstring prefix = cur.inset().completionPrefix(cur);
543         docstring completion = from_utf8(fromqstr(currentCompletion()));
544         if (completion.size() <= prefix.size()) {
545                 // finalize completion
546                 cur.inset().insertCompletion(cur, docstring(), true);
547                 
548                 // hide popup and inline completion
549                 popup()->hide();
550                 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
551                 inlineVisible_ = false;
552                 updateVisibility(false, false);
553                 return;
554         }
555         docstring nextchar = completion.substr(prefix.size(), 1);
556         if (!cur.inset().insertCompletion(cur, nextchar, false))
557                 return;
558         updatePrefix(cur);
559
560         // try to complete as far as it is unique
561         docstring longestCompletion = longestUniqueCompletion();
562         prefix = cur.inset().completionPrefix(cur);
563         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
564         cur.inset().insertCompletion(cur, postfix, false);
565         old_cursor_ = bv->cursor();
566         updatePrefix(cur);
567
568         // show popup without delay because the completion was not unique
569         if (lyxrc.completion_popup_after_complete
570             && !popupVisible()
571             && popup()->model()->rowCount() > 1)
572                 popup_timer_.start(0);
573
574         // redraw if needed
575         if (cur.disp_.update())
576                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
577 }
578
579
580 QString GuiCompleter::currentCompletion() const
581 {
582         if (!popup()->selectionModel()->hasSelection())
583                 return QString();
584
585         // Not sure if this is bug in Qt: currentIndex() always 
586         // return the first element in the list.
587         QModelIndex idx = popup()->currentIndex();
588         return popup()->model()->data(idx, Qt::EditRole).toString();
589 }
590
591
592 void GuiCompleter::setCurrentCompletion(QString const & s)
593 {       
594         QAbstractItemModel const & model = *popup()->model();
595         size_t n = model.rowCount();
596         if (n == 0)
597                 return;
598
599         // select the first if s is empty
600         if (s.length() == 0) {
601                 updateLock_++;
602                 popup()->setCurrentIndex(model.index(0, 0));
603                 updateLock_--;
604                 return;
605         }
606
607         // iterate through list until the s is found
608         // FIXME: there must be a better way than this iteration
609         size_t i;
610         for (i = 0; i < n; ++i) {
611                 QString const & is
612                 = model.data(model.index(i, 0), Qt::EditRole).toString();
613                 if (is == s)
614                         break;
615         }
616
617         // select the first if none was found
618         if (i == n)
619                 i = 0;
620
621         updateLock_++;
622         popup()->setCurrentIndex(model.index(i, 0));
623         updateLock_--;
624 }
625
626
627 docstring GuiCompleter::longestUniqueCompletion() const {
628         QAbstractItemModel const & model = *popup()->model();
629         QString s = currentCompletion();
630         size_t n = model.rowCount();
631
632         // iterate through the completions and cut off where s differs
633         for (size_t i = 0; i < n && s.length() > 0; ++i) {
634                 QString const & is
635                 = model.data(model.index(i, 0), Qt::EditRole).toString();
636
637                 // find common prefix
638                 size_t j;
639                 size_t isn = is.length();
640                 size_t sn = s.length();
641                 for (j = 0; j < isn && j < sn; ++j) {
642                         if (s.at(j) != is.at(j))
643                                 break;
644                 }
645                 s = s.left(j);
646         }
647
648         return from_utf8(fromqstr(s));
649 }
650
651
652 void GuiCompleter::popupActivated(const QString & completion)
653 {
654         Cursor cur = gui_->bufferView().cursor();
655         cur.updateFlags(Update::None);
656         
657         docstring prefix = cur.inset().completionPrefix(cur);
658         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
659         cur.inset().insertCompletion(cur, postfix, true);
660         updateVisibility(cur, false);
661         
662         if (cur.disp_.update())
663                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
664 }
665
666
667 void GuiCompleter::popupHighlighted(const QString & completion)
668 {
669         if (updateLock_ > 0)
670                 return;
671
672         Cursor cur = gui_->bufferView().cursor();
673         cur.updateFlags(Update::None);
674         
675         updateInline(cur, completion);
676         
677         if (cur.disp_.update())
678                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
679 }
680
681 } // namespace frontend
682 } // namespace lyx
683
684 #include "GuiCompleter_moc.cpp"