]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
df061cb9401b1dbfb7a9d43231c1b828610c09f0
[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 = p.scaled(min(16, p.width()), min(16, p.height()), 
145                                                 Qt::KeepAspectRatio, Qt::SmoothTransformation);
146                                 }
147
148                                 QPixmapCache::insert("completion" + name, scaled);
149                         }
150                         return scaled;
151                 }
152                 return QVariant();
153         }
154
155 private:
156         ///
157         Inset::CompletionList const * list_;
158 };
159
160
161 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
162         : QCompleter(parent), gui_(gui), updateLock_(0),
163           inlineVisible_(false)
164 {
165         // Setup the completion popup
166         setModel(new GuiCompletionModel(this, 0));
167         setCompletionMode(QCompleter::PopupCompletion);
168         setWidget(gui_);
169         
170         // create the popup
171         QTreeView *listView = new QTreeView;
172         listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
173         listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
174         listView->setSelectionBehavior(QAbstractItemView::SelectRows);
175         listView->setSelectionMode(QAbstractItemView::SingleSelection);
176         listView->header()->hide();
177         listView->setIndentation(0);
178         listView->setUniformRowHeights(true);
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                 hidePopup(cur);
267
268         // we moved or inline state is not ok for inline completion?
269         if ((moved && !keep) || !possibleInlineState)
270                 hideInline(cur);
271
272         // we inserted something and are in a possible popup state?
273         if (!popupVisible() && possiblePopupState && start
274                 && cur.inset().automaticPopupCompletion())
275                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
276
277         // we inserted something and are in a possible inline completion state?
278         if (!inlineVisible() && possibleInlineState && start
279                 && cur.inset().automaticInlineCompletion())
280                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
281
282         // update prefix if popup is visible or if it will be visible soon
283         if (popupVisible() || inlineVisible()
284             || popup_timer_.isActive() || inline_timer_.isActive())
285                 updatePrefix(cur);
286 }
287
288
289 void GuiCompleter::updateVisibility(bool start, bool keep)
290 {
291         Cursor cur = gui_->bufferView().cursor();
292         cur.updateFlags(Update::None);
293         
294         updateVisibility(cur, start, keep);
295         
296         if (cur.disp_.update())
297                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
298 }
299
300
301 void GuiCompleter::updatePrefix(Cursor & cur)
302 {
303         // get new prefix. Do nothing if unchanged
304         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
305         if (newPrefix == completionPrefix())
306                 return;
307         
308         // value which should be kept selected
309         QString old = currentCompletion();
310         if (old.length() == 0)
311                 old = last_selection_;
312         
313         // update completer to new prefix
314         setCompletionPrefix(newPrefix);
315
316         // update popup because its size might have changed
317         if (popupVisible())
318                 updatePopup(cur);
319
320         // restore old selection
321         setCurrentCompletion(old);
322         
323         // if popup is not empty, the new selection will
324         // be our last valid one
325         QString const & s = currentCompletion();
326         if (s.length() > 0)
327                 last_selection_ = s;
328         else
329                 last_selection_ = old;
330         
331         // update inline completion because the default
332         // completion string might have changed
333         if (inlineVisible())
334                 updateInline(cur, s);
335 }
336
337
338 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
339 {
340         if (!cur.inset().inlineCompletionSupported(cur))
341                 return;
342         
343         // compute postfix
344         docstring prefix = cur.inset().completionPrefix(cur);
345         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
346         
347         // shorten it if necessary
348         if (lyxrc.completion_inline_dots != -1
349             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
350                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
351
352         // set inline completion at cursor position
353         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
354         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
355         inlineVisible_ = true;
356 }
357
358
359 void GuiCompleter::updatePopup(Cursor & cur)
360 {
361         if (!cur.inset().completionSupported(cur))
362                 return;
363         
364         if (completionCount() == 0)
365                 return;
366         
367         // get dimensions of completion prefix
368         Dimension dim;
369         int x;
370         int y;
371         cur.inset().completionPosAndDim(cur, x, y, dim);
372         
373         // and calculate the rect of the popup
374         QRect rect;
375         if (popup()->layoutDirection() == Qt::RightToLeft)
376                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
377         else
378                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
379         
380         // show/update popup
381         complete(rect);
382         QTreeView * p = static_cast<QTreeView *>(popup());
383         p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
384 }
385
386
387 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
388 {
389         // value which should be kept selected
390         QString old = currentCompletion();
391         if (old.length() == 0)
392                 old = last_selection_;
393
394         // set whether rtl
395         bool rtl = false;
396         if (cur.inTexted()) {
397                 Paragraph const & par = cur.paragraph();
398                 Font const font =
399                 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
400                 rtl = font.isVisibleRightToLeft();
401         }
402         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
403
404         // turn the direction of the strings in the popup.
405         // Qt does not do that itself.
406         popup()->setItemDelegateForColumn(0, rtl ? rtlItemDelegate_ : 0);
407
408         // set new model
409         Inset::CompletionList const * list = cur.inset().createCompletionList(cur);
410         setModel(new GuiCompletionModel(this, list));
411         if (list->sorted())
412                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
413         else
414                 setModelSorting(QCompleter::UnsortedModel);
415
416         // set prefix
417         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
418         if (newPrefix != completionPrefix())
419                 setCompletionPrefix(newPrefix);
420
421         // show popup
422         if (popupUpdate)
423                 updatePopup(cur);
424
425         // restore old selection
426         setCurrentCompletion(old);
427         
428         // if popup is not empty, the new selection will
429         // be our last valid one
430         QString const & s = currentCompletion();
431         if (s.length() > 0)
432                 last_selection_ = s;
433         else
434                 last_selection_ = old;
435
436         // show inline completion
437         if (inlineUpdate)
438                 updateInline(cur, currentCompletion());
439 }
440
441
442 void GuiCompleter::showPopup(Cursor & cur)
443 {
444         if (!popupPossible(cur))
445                 return;
446         
447         updateModel(cur, true, inlineVisible());
448 }
449
450
451 void GuiCompleter::hidePopup(Cursor & cur)
452 {
453         popup()->hide();
454         if (popup_timer_.isActive())
455                 popup_timer_.stop();
456 }
457
458
459 void GuiCompleter::showInline(Cursor & cur)
460 {
461         if (!inlinePossible(cur))
462                 return;
463         
464         updateModel(cur, popupVisible(), true);
465 }
466
467
468 void GuiCompleter::hideInline(Cursor & cur)
469 {
470         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
471         inlineVisible_ = false;
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::hidePopup()
502 {
503         Cursor cur = gui_->bufferView().cursor();
504         cur.updateFlags(Update::None);
505         
506         hidePopup(cur);
507         
508         // redraw if needed
509         if (cur.disp_.update())
510                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
511 }
512
513
514 void GuiCompleter::hideInline()
515 {
516         Cursor cur = gui_->bufferView().cursor();
517         cur.updateFlags(Update::None);
518         
519         hideInline(cur);
520         
521         // redraw if needed
522         if (cur.disp_.update())
523                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
524 }
525
526
527 void GuiCompleter::activate()
528 {
529         if (!popupVisible() && !inlineVisible())
530                 return;
531
532         popupActivated(currentCompletion());
533 }
534
535
536 void GuiCompleter::tab()
537 {
538         BufferView * bv = &gui_->bufferView();
539         Cursor cur = bv->cursor();
540         cur.updateFlags(Update::None);
541         
542         // check that inline completion is active
543         if (!inlineVisible()) {
544                 // try to activate the inline completion
545                 if (cur.inset().inlineCompletionSupported(cur)) {
546                         showInline();
547                         
548                         // show popup without delay because the completion was not unique
549                         if (lyxrc.completion_popup_after_complete
550                             && !popupVisible()
551                             && popup()->model()->rowCount() > 1)
552                                 popup_timer_.start(0);
553
554                         return;
555                 }
556                 // or try popup
557                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
558                         showPopup();
559                         return;
560                 }
561                 
562                 return;
563         }
564         
565         // If completion is active, at least complete by one character
566         docstring prefix = cur.inset().completionPrefix(cur);
567         docstring completion = from_utf8(fromqstr(currentCompletion()));
568         if (completion.size() <= prefix.size()) {
569                 // finalize completion
570                 cur.inset().insertCompletion(cur, docstring(), true);
571                 
572                 // hide popup and inline completion
573                 hidePopup(cur);
574                 hideInline(cur);
575                 updateVisibility(false, false);
576                 return;
577         }
578         docstring nextchar = completion.substr(prefix.size(), 1);
579         if (!cur.inset().insertCompletion(cur, nextchar, false))
580                 return;
581         updatePrefix(cur);
582
583         // try to complete as far as it is unique
584         docstring longestCompletion = longestUniqueCompletion();
585         prefix = cur.inset().completionPrefix(cur);
586         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
587         cur.inset().insertCompletion(cur, postfix, false);
588         old_cursor_ = bv->cursor();
589         updatePrefix(cur);
590
591         // show popup without delay because the completion was not unique
592         if (lyxrc.completion_popup_after_complete
593             && !popupVisible()
594             && popup()->model()->rowCount() > 1)
595                 popup_timer_.start(0);
596
597         // redraw if needed
598         if (cur.disp_.update())
599                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
600 }
601
602
603 QString GuiCompleter::currentCompletion() const
604 {
605         if (!popup()->selectionModel()->hasSelection())
606                 return QString();
607
608         // Not sure if this is bug in Qt: currentIndex() always 
609         // return the first element in the list.
610         QModelIndex idx = popup()->currentIndex();
611         return popup()->model()->data(idx, Qt::EditRole).toString();
612 }
613
614
615 void GuiCompleter::setCurrentCompletion(QString const & s)
616 {       
617         QAbstractItemModel const & model = *popup()->model();
618         size_t n = model.rowCount();
619         if (n == 0)
620                 return;
621
622         // select the first if s is empty
623         if (s.length() == 0) {
624                 updateLock_++;
625                 popup()->setCurrentIndex(model.index(0, 0));
626                 updateLock_--;
627                 return;
628         }
629
630         // find old selection in model
631         size_t i;
632         if (modelSorting() == QCompleter::UnsortedModel) {
633                 // In unsorted models, iterate through list until the s is found
634                 for (i = 0; i < n; ++i) {
635                         QString const & is
636                         = model.data(model.index(i, 0), Qt::EditRole).toString();
637                         if (is == s)
638                                 break;
639                 }
640         } else {
641                 // In sorted models, do binary search for s.
642                 int l = 0;
643                 int r = n - 1;
644                 while (r >= l && l < int(n)) {
645                         size_t mid = (r + l) / 2;
646                         QString const & mids
647                         = model.data(model.index(mid, 0),
648                                      Qt::EditRole).toString();
649
650                         // left or right?
651                         // FIXME: is this really the same order that the docstring
652                         // from the CompletionList has?
653                         int c = s.compare(mids, Qt::CaseSensitive);
654                         if (c == 0) {
655                                 l = mid;
656                                 break;
657                         } else if (l == r) {
658                                 l = n;
659                                 break;
660                         } else if (c > 0)
661                                 // middle is not far enough
662                                 l = mid + 1;
663                         else
664                                 // middle is too far
665                                 r = mid - 1;
666                 }
667
668                 // loop was left without finding anything
669                 if (r < l)
670                         i = n;
671                 else
672                         i = l;
673                 BOOST_ASSERT(0 <= i && i <= n);
674         }
675
676         // select the first if none was found
677         if (i == n)
678                 i = 0;
679
680         updateLock_++;
681         popup()->setCurrentIndex(model.index(i, 0));
682         updateLock_--;
683 }
684
685
686 size_t commonPrefix(QString const & s1, QString const & s2)
687 {
688         // find common prefix
689         size_t j;
690         size_t n1 = s1.length();
691         size_t n2 = s2.length();
692         for (j = 0; j < n1 && j < n2; ++j) {
693                 if (s1.at(j) != s2.at(j))
694                         break;
695         }
696         return j;
697 }
698
699
700 docstring GuiCompleter::longestUniqueCompletion() const
701 {
702         QAbstractItemModel const & model = *popup()->model();
703         QString s = currentCompletion();
704         size_t n = model.rowCount();
705
706         if (modelSorting() == QCompleter::UnsortedModel) {
707                 // For unsorted model we cannot do more than iteration.
708                 // Iterate through the completions and cut off where s differs
709                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
710                         QString const & is
711                         = model.data(model.index(i, 0), Qt::EditRole).toString();
712
713                         s = s.left(commonPrefix(is, s));
714                 }
715         } else {
716                 // For sorted models we can do binary search multiple times,
717                 // each time to find the first string which has s not as prefix.
718                 size_t i = 0;
719                 while (i < n && s.length() > 0) {
720                         // find first string that does not have s as prefix
721                         // via binary search in [i,n-1]
722                         size_t r = n - 1;
723                         do {
724                                 // get common prefix with the middle string
725                                 size_t mid = (r + i) / 2;
726                                 QString const & mids
727                                 = model.data(model.index(mid, 0), 
728                                         Qt::EditRole).toString();
729                                 size_t oldLen = s.length();
730                                 size_t len = commonPrefix(mids, s);
731                                 s = s.left(len);
732
733                                 // left or right?
734                                 if (oldLen == len) {
735                                         // middle is not far enough
736                                         i = mid + 1;
737                                 } else {
738                                         // middle is maybe too far
739                                         r = mid;
740                                 }
741                         } while (r - i > 0 && i < n);
742                 }
743         }
744
745         return from_utf8(fromqstr(s));
746 }
747
748
749 void GuiCompleter::popupActivated(const QString & completion)
750 {
751         Cursor cur = gui_->bufferView().cursor();
752         cur.updateFlags(Update::None);
753         
754         docstring prefix = cur.inset().completionPrefix(cur);
755         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
756         cur.inset().insertCompletion(cur, postfix, true);
757         hidePopup(cur);
758         hideInline(cur);
759         
760         if (cur.disp_.update())
761                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
762 }
763
764
765 void GuiCompleter::popupHighlighted(const QString & completion)
766 {
767         if (updateLock_ > 0)
768                 return;
769
770         Cursor cur = gui_->bufferView().cursor();
771         cur.updateFlags(Update::None);
772         
773         if (inlineVisible())
774                 updateInline(cur, completion);
775         
776         if (cur.disp_.update())
777                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
778 }
779
780 } // namespace frontend
781 } // namespace lyx
782
783 #include "GuiCompleter_moc.cpp"