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