]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
2246888268ffdbc1204c40ee0da84e885c07cb5b
[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         listView->setUniformRowHeights(true);
180         setPopup(listView);
181         popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
182         rtlItemDelegate_ = new RtlItemDelegate(this);
183         
184         // create timeout timers
185         popup_timer_.setSingleShot(true);
186         inline_timer_.setSingleShot(true);
187         connect(this, SIGNAL(highlighted(const QString &)),
188                 this, SLOT(popupHighlighted(const QString &)));
189         connect(this, SIGNAL(activated(const QString &)),
190                 this, SLOT(popupActivated(const QString &)));
191         connect(&popup_timer_, SIGNAL(timeout()),
192                 this, SLOT(showPopup()));
193         connect(&inline_timer_, SIGNAL(timeout()),
194                 this, SLOT(showInline()));
195 }
196
197
198 GuiCompleter::~GuiCompleter()
199 {
200         popup()->hide();
201 }
202
203
204 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
205 {
206         // hijack back the tab key from the popup
207         // (which stole it from the workspace before)
208         if (e->type() == QEvent::KeyPress && popupVisible()) {
209                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
210                 switch (ke->key()) {
211                 case Qt::Key_Tab:
212                         tab();
213                         ke->accept();
214                         return true;
215                 default: break;
216                 }
217         }
218         
219         return QCompleter::eventFilter(watched, e);
220 }
221
222
223 bool GuiCompleter::popupPossible(Cursor const & cur) const
224 {
225         return QApplication::activeWindow()
226                 && gui_->hasFocus()
227                 && cur.inset().completionSupported(cur);
228 }
229
230
231 bool GuiCompleter::inlinePossible(Cursor const & cur) const
232 {
233         return cur.inset().inlineCompletionSupported(cur);
234 }
235
236
237 bool GuiCompleter::popupVisible() const
238 {
239         return popup()->isVisible();
240 }
241
242
243 bool GuiCompleter::inlineVisible() const
244 {
245         // In fact using BufferView::inlineCompletionPos.empty() should be
246         // here. But unfortunately this information is not good enough
247         // because destructive operations like backspace might invalidate
248         // inlineCompletionPos. But then the completion should stay visible
249         // (i.e. reshown on the next update). Hence be keep this information
250         // in the inlineVisible_ variable.
251         return inlineVisible_;
252 }
253
254
255 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
256 {
257         // parameters which affect the completion
258         bool moved = cur != old_cursor_;
259         if (moved)
260                 old_cursor_ = cur;
261
262         bool possiblePopupState = popupPossible(cur) && cursorInView;
263         bool possibleInlineState = inlinePossible(cur) && cursorInView;
264
265         // we moved or popup state is not ok for popup?
266         if ((moved && !keep) || !possiblePopupState) {
267                 // stop an old completion timer
268                 if (popup_timer_.isActive())
269                         popup_timer_.stop();
270
271                 // hide old popup
272                 if (popupVisible())
273                         popup()->hide();
274         }
275
276         // we moved or inline state is not ok for inline completion?
277         if ((moved && !keep) || !possibleInlineState) {
278                 // stop an old completion timer
279                 if (inline_timer_.isActive())
280                         inline_timer_.stop();
281
282                 // hide old inline completion
283                 if (inlineVisible()) {
284                         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
285                         inlineVisible_ = false;
286                 }
287         }
288
289         // we inserted something and are in a possible popup state?
290         if (!popupVisible() && possiblePopupState && start
291                 && cur.inset().automaticPopupCompletion())
292                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
293
294         // we inserted something and are in a possible inline completion state?
295         if (!inlineVisible() && possibleInlineState && start
296                 && cur.inset().automaticInlineCompletion())
297                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
298
299         // update prefix if popup is visible or if it will be visible soon
300         if (popupVisible() || inlineVisible()
301             || popup_timer_.isActive() || inline_timer_.isActive())
302                 updatePrefix(cur);
303 }
304
305
306 void GuiCompleter::updateVisibility(bool start, bool keep)
307 {
308         Cursor cur = gui_->bufferView().cursor();
309         cur.updateFlags(Update::None);
310         
311         updateVisibility(cur, start, keep);
312         
313         if (cur.disp_.update())
314                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
315 }
316
317
318 void GuiCompleter::updatePrefix(Cursor & cur)
319 {
320         // get new prefix. Do nothing if unchanged
321         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
322         if (newPrefix == completionPrefix())
323                 return;
324         
325         // value which should be kept selected
326         QString old = currentCompletion();
327         if (old.length() == 0)
328                 old = last_selection_;
329         
330         // update completer to new prefix
331         setCompletionPrefix(newPrefix);
332         
333         // update popup because its size might have changed
334         if (popupVisible())
335                 updatePopup(cur);
336
337         // restore old selection
338         setCurrentCompletion(old);
339         
340         // if popup is not empty, the new selection will
341         // be our last valid one
342         QString const & s = currentCompletion();
343         if (s.length() > 0)
344                 last_selection_ = s;
345         else
346                 last_selection_ = old;
347         
348         // update inline completion because the default
349         // completion string might have changed
350         if (inlineVisible())
351                 updateInline(cur, s);
352 }
353
354
355 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
356 {
357         if (!cur.inset().inlineCompletionSupported(cur))
358                 return;
359         
360         // compute postfix
361         docstring prefix = cur.inset().completionPrefix(cur);
362         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
363         
364         // shorten it if necessary
365         if (lyxrc.completion_inline_dots != -1
366             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
367                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
368
369         // set inline completion at cursor position
370         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
371         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
372         inlineVisible_ = true;
373 }
374
375
376 void GuiCompleter::updatePopup(Cursor & cur)
377 {
378         if (!cur.inset().completionSupported(cur))
379                 return;
380         
381         if (completionCount() == 0)
382                 return;
383         
384         // get dimensions of completion prefix
385         Dimension dim;
386         int x;
387         int y;
388         cur.inset().completionPosAndDim(cur, x, y, dim);
389         
390         // and calculate the rect of the popup
391         QRect rect;
392         if (popup()->layoutDirection() == Qt::RightToLeft)
393                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
394         else
395                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
396         
397         // show/update popup
398         complete(rect);
399         QTreeView * p = static_cast<QTreeView *>(popup());
400         p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
401 }
402
403
404 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
405 {
406         // value which should be kept selected
407         QString old = currentCompletion();
408         if (old.length() == 0)
409                 old = last_selection_;
410
411         // set whether rtl
412         bool rtl = false;
413         if (cur.inTexted()) {
414                 Paragraph const & par = cur.paragraph();
415                 Font const font =
416                 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
417                 rtl = font.isVisibleRightToLeft();
418         }
419         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
420
421         // turn the direction of the strings in the popup.
422         // Qt does not do that itself.
423         popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
424
425         // set new model
426         Inset::CompletionList const * list
427         = cur.inset().createCompletionList(cur);
428         setModel(new GuiCompletionModel(this, list));
429         if (list->sorted())
430                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
431         else
432                 setModelSorting(QCompleter::UnsortedModel);
433
434         // show popup
435         if (popupUpdate)
436                 updatePopup(cur);
437
438         // restore old selection
439         setCurrentCompletion(old);
440         
441         // if popup is not empty, the new selection will
442         // be our last valid one
443         QString const & s = currentCompletion();
444         if (s.length() > 0)
445                 last_selection_ = s;
446         else
447                 last_selection_ = old;
448         
449         // show inline completion
450         if (inlineUpdate)
451                 updateInline(cur, currentCompletion());
452 }
453
454
455 void GuiCompleter::showPopup(Cursor & cur)
456 {
457         if (!popupPossible(cur))
458                 return;
459         
460         updateModel(cur, true, inlineVisible());
461         updatePrefix(cur);
462 }
463         
464
465 void GuiCompleter::showInline(Cursor & cur)
466 {
467         if (!inlinePossible(cur))
468                 return;
469         
470         updateModel(cur, popupVisible(), true);
471         updatePrefix(cur);
472 }
473
474
475 void GuiCompleter::showPopup()
476 {
477         Cursor cur = gui_->bufferView().cursor();
478         cur.updateFlags(Update::None);
479         
480         showPopup(cur);
481
482         // redraw if needed
483         if (cur.disp_.update())
484                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
485 }
486
487
488 void GuiCompleter::showInline()
489 {
490         Cursor cur = gui_->bufferView().cursor();
491         cur.updateFlags(Update::None);
492         
493         showInline(cur);
494
495         // redraw if needed
496         if (cur.disp_.update())
497                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
498 }
499
500
501 void GuiCompleter::activate()
502 {
503         if (!popupVisible() && !inlineVisible())
504                 return;
505
506         // Complete with current selection in the popup.
507         QString s = currentCompletion();
508         popup()->hide();
509         popupActivated(s);
510 }
511
512
513 void GuiCompleter::tab()
514 {
515         BufferView * bv = &gui_->bufferView();
516         Cursor cur = bv->cursor();
517         cur.updateFlags(Update::None);
518         
519         // check that inline completion is active
520         if (!inlineVisible()) {
521                 // try to activate the inline completion
522                 if (cur.inset().inlineCompletionSupported(cur)) {
523                         showInline();
524                         
525                         // show popup without delay because the completion was not unique
526                         if (lyxrc.completion_popup_after_complete
527                             && !popupVisible()
528                             && popup()->model()->rowCount() > 1)
529                                 popup_timer_.start(0);
530
531                         return;
532                 }
533                 // or try popup
534                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
535                         showPopup();
536                         return;
537                 }
538                 
539                 return;
540         }
541         
542         // If completion is active, at least complete by one character
543         docstring prefix = cur.inset().completionPrefix(cur);
544         docstring completion = from_utf8(fromqstr(currentCompletion()));
545         if (completion.size() <= prefix.size()) {
546                 // finalize completion
547                 cur.inset().insertCompletion(cur, docstring(), true);
548                 
549                 // hide popup and inline completion
550                 popup()->hide();
551                 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
552                 inlineVisible_ = false;
553                 updateVisibility(false, false);
554                 return;
555         }
556         docstring nextchar = completion.substr(prefix.size(), 1);
557         if (!cur.inset().insertCompletion(cur, nextchar, false))
558                 return;
559         updatePrefix(cur);
560
561         // try to complete as far as it is unique
562         docstring longestCompletion = longestUniqueCompletion();
563         prefix = cur.inset().completionPrefix(cur);
564         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
565         cur.inset().insertCompletion(cur, postfix, false);
566         old_cursor_ = bv->cursor();
567         updatePrefix(cur);
568
569         // show popup without delay because the completion was not unique
570         if (lyxrc.completion_popup_after_complete
571             && !popupVisible()
572             && popup()->model()->rowCount() > 1)
573                 popup_timer_.start(0);
574
575         // redraw if needed
576         if (cur.disp_.update())
577                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
578 }
579
580
581 QString GuiCompleter::currentCompletion() const
582 {
583         if (!popup()->selectionModel()->hasSelection())
584                 return QString();
585
586         // Not sure if this is bug in Qt: currentIndex() always 
587         // return the first element in the list.
588         QModelIndex idx = popup()->currentIndex();
589         return popup()->model()->data(idx, Qt::EditRole).toString();
590 }
591
592
593 void GuiCompleter::setCurrentCompletion(QString const & s)
594 {       
595         QAbstractItemModel const & model = *popup()->model();
596         size_t n = model.rowCount();
597         if (n == 0)
598                 return;
599
600         // select the first if s is empty
601         if (s.length() == 0) {
602                 updateLock_++;
603                 popup()->setCurrentIndex(model.index(0, 0));
604                 updateLock_--;
605                 return;
606         }
607
608         // find old selection in model
609         size_t i;
610         if (modelSorting() == QCompleter::UnsortedModel) {
611                 // In unsorted models, iterate through list until the s is found
612                 for (i = 0; i < n; ++i) {
613                         QString const & is
614                         = model.data(model.index(i, 0), Qt::EditRole).toString();
615                         if (is == s)
616                                 break;
617                 }
618         } else {
619                 // In sorted models, do binary search for s.
620                 i = 0;
621                 size_t r = n - 1;
622                 do {
623                         size_t mid = (r + i) / 2;
624                         QString const & mids
625                         = model.data(model.index(mid, 0),
626                                      Qt::EditRole).toString();
627
628                         // left or right?
629                         // FIXME: is this really the same order that the docstring
630                         // from the CompletionList has?
631                         int c = s.compare(mids, Qt::CaseSensitive);
632                         if (c == 0) {
633                                 i = mid;
634                                 break;
635                         } else if (c > 0)
636                                 // middle is not far enough
637                                 i = mid + 1;
638                         else
639                                 // middle is too far
640                                 r = mid - 1;
641
642                 } while (r - i > 0 && i < n);
643         }
644
645         // select the first if none was found
646         if (i == n)
647                 i = 0;
648
649         updateLock_++;
650         popup()->setCurrentIndex(model.index(i, 0));
651         updateLock_--;
652 }
653
654
655 size_t commonPrefix(QString const & s1, QString const & s2)
656 {
657         // find common prefix
658         size_t j;
659         size_t n1 = s1.length();
660         size_t n2 = s2.length();
661         for (j = 0; j < n1 && j < n2; ++j) {
662                 if (s1.at(j) != s2.at(j))
663                         break;
664         }
665         return j;
666 }
667
668
669 docstring GuiCompleter::longestUniqueCompletion() const
670 {
671         QAbstractItemModel const & model = *popup()->model();
672         QString s = currentCompletion();
673         size_t n = model.rowCount();
674
675         if (modelSorting() == QCompleter::UnsortedModel) {
676                 // For unsorted model we cannot do more than iteration.
677                 // Iterate through the completions and cut off where s differs
678                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
679                         QString const & is
680                         = model.data(model.index(i, 0), Qt::EditRole).toString();
681
682                         s = s.left(commonPrefix(is, s));
683                 }
684         } else {
685                 // For sorted models we can do binary search multiple times,
686                 // each time to find the first string which has s not as prefix.
687                 size_t i = 0;
688                 while (i < n && s.length() > 0) {
689                         // find first string that does not have s as prefix
690                         // via binary search in [i,n-1]
691                         size_t r = n - 1;
692                         do {
693                                 // get common prefix with the middle string
694                                 size_t mid = (r + i) / 2;
695                                 QString const & mids
696                                 = model.data(model.index(mid, 0), 
697                                         Qt::EditRole).toString();
698                                 size_t oldLen = s.length();
699                                 size_t len = commonPrefix(mids, s);
700                                 s = s.left(len);
701
702                                 // left or right?
703                                 if (oldLen == len) {
704                                         // middle is not far enough
705                                         i = mid + 1;
706                                 } else {
707                                         // middle is maybe too far
708                                         r = mid;
709                                 }
710                         } while (r - i > 0 && i < n);
711                 }
712         }
713
714         return from_utf8(fromqstr(s));
715 }
716
717
718 void GuiCompleter::popupActivated(const QString & completion)
719 {
720         Cursor cur = gui_->bufferView().cursor();
721         cur.updateFlags(Update::None);
722         
723         docstring prefix = cur.inset().completionPrefix(cur);
724         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
725         cur.inset().insertCompletion(cur, postfix, true);
726         updateVisibility(cur, false);
727         
728         if (cur.disp_.update())
729                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
730 }
731
732
733 void GuiCompleter::popupHighlighted(const QString & completion)
734 {
735         if (updateLock_ > 0)
736                 return;
737
738         Cursor cur = gui_->bufferView().cursor();
739         cur.updateFlags(Update::None);
740         
741         updateInline(cur, completion);
742         
743         if (cur.disp_.update())
744                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
745 }
746
747 } // namespace frontend
748 } // namespace lyx
749
750 #include "GuiCompleter_moc.cpp"