]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
On Linux show in crash message box the backtrace
[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 "GuiCompleter.h"
14
15 #include "Buffer.h"
16 #include "BufferView.h"
17 #include "CompletionList.h"
18 #include "Cursor.h"
19 #include "Dimension.h"
20 #include "GuiWorkArea.h"
21 #include "GuiView.h"
22 #include "LyX.h"
23 #include "LyXRC.h"
24 #include "Paragraph.h"
25 #include "qt_helpers.h"
26 #include "version.h"
27
28 #include "support/lassert.h"
29 #include "support/debug.h"
30
31 #include <QApplication>
32 #include <QHeaderView>
33 #include <QKeyEvent>
34 #include <QPainter>
35 #include <QPixmapCache>
36 #include <QScrollBar>
37 #include <QItemDelegate>
38 #include <QTreeView>
39 #include <QTimer>
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45 namespace frontend {
46
47 class CompleterItemDelegate : public QItemDelegate
48 {
49 public:
50         explicit CompleterItemDelegate(QObject * parent)
51                 : QItemDelegate(parent)
52         {}
53
54         ~CompleterItemDelegate()
55         {}
56
57 protected:
58         void paint(QPainter *painter, const QStyleOptionViewItem &option,
59                    const QModelIndex &index) const
60         {
61                 if (index.column() == 0) {
62                         QItemDelegate::paint(painter, option, index);
63                         return;
64                 }
65                 QStyleOptionViewItem opt = setOptions(index, option);
66                 QVariant value = index.data(Qt::DisplayRole);
67                 QPixmap pixmap = qvariant_cast<QPixmap>(value);
68                 
69                 // draw
70                 painter->save();
71                 drawBackground(painter, opt, index);
72                 if (!pixmap.isNull()) {
73                         const QSize size = pixmap.size();
74                         painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
75                                 option.rect.top() + (option.rect.height() - size.height()) / 2,
76                                 pixmap);
77                 }
78                 drawFocus(painter, opt, option.rect);
79                 painter->restore();
80         }
81 };
82
83 class GuiCompletionModel : public QAbstractListModel
84 {
85 public:
86         ///
87         GuiCompletionModel(QObject * parent, CompletionList const * l)
88                 : QAbstractListModel(parent), list_(l)
89         {}
90         ///
91         ~GuiCompletionModel() { delete list_; }
92         ///
93         void setList(CompletionList const * l) {
94                 beginResetModel();
95                 delete list_;
96                 list_ = l;
97                 endResetModel();
98         }
99         ///
100         bool sorted() const
101         {
102                 if (list_)
103                         return list_->sorted();
104                 return false;
105         }
106         ///
107         int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
108         {
109                 return 2;
110         }
111         ///
112         int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
113         {
114                 if (list_ == 0)
115                         return 0;
116                 return list_->size();
117         }
118
119         ///
120         QVariant data(const QModelIndex & index, int role) const
121         {
122                 if (list_ == 0)
123                         return QVariant();
124
125                 if (index.row() < 0 || index.row() >= rowCount())
126                         return QVariant();
127
128                 if (role != Qt::DisplayRole && role != Qt::EditRole)
129                     return QVariant();
130                     
131                 if (index.column() == 0)
132                         return toqstr(list_->data(index.row()));
133
134                 if (index.column() != 1)
135                         return QVariant();
136         
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                         QPixmapCache::insert("completion" + name, scaled);
149                 }
150                 return scaled;
151         }
152
153 private:
154         /// owned by us
155         CompletionList const * list_;
156 };
157
158
159 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
160         : QCompleter(parent), gui_(gui), old_cursor_(0), updateLock_(0),
161           inlineVisible_(false), popupVisible_(false),
162           modelActive_(false)
163 {
164         // Setup the completion popup
165         model_ = new GuiCompletionModel(this, 0);
166         setModel(model_);
167         setCompletionMode(QCompleter::PopupCompletion);
168         setCaseSensitivity(Qt::CaseSensitive);
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         
182         itemDelegate_ = new CompleterItemDelegate(this);
183         popup()->setItemDelegate(itemDelegate_);
184         
185         // create timeout timers
186         popup_timer_.setSingleShot(true);
187         inline_timer_.setSingleShot(true);
188         connect(this, SIGNAL(highlighted(const QString &)),
189                 this, SLOT(popupHighlighted(const QString &)));
190         connect(this, SIGNAL(activated(const QString &)),
191                 this, SLOT(popupActivated(const QString &)));
192         connect(&popup_timer_, SIGNAL(timeout()),
193                 this, SLOT(showPopup()));
194         connect(&inline_timer_, SIGNAL(timeout()),
195                 this, SLOT(showInline()));
196 }
197
198
199 GuiCompleter::~GuiCompleter()
200 {
201         popup()->hide();
202 }
203
204
205 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
206 {
207         // hijack back the tab key from the popup
208         // (which stole it from the workspace before)
209         if (e->type() == QEvent::KeyPress && popupVisible()) {
210                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
211                 switch (ke->key()) {
212                 case Qt::Key_Tab:
213                         tab();
214                         ke->accept();
215                         return true;
216                 default: break;
217                 }
218         }
219         
220         return QCompleter::eventFilter(watched, e);
221 }
222
223
224 bool GuiCompleter::popupPossible(Cursor const & cur) const
225 {
226         return QApplication::activeWindow()
227                 && gui_->hasFocus()
228                 && cur.inset().completionSupported(cur);
229 }
230
231
232 bool GuiCompleter::inlinePossible(Cursor const & cur) const
233 {
234         return cur.inset().inlineCompletionSupported(cur);
235 }
236
237
238 bool GuiCompleter::uniqueCompletionAvailable() const
239 {
240         if (!modelActive_)
241                 return false;
242
243         size_t n = popup()->model()->rowCount();
244         if (n > 1 || n == 0)
245                 return false;
246
247         // if there is exactly one, we have to check whether it is a 
248         // real completion, i.e. longer than the current prefix.
249         if (completionPrefix() == currentCompletion())
250                 return false;
251
252         return true;
253 }
254
255
256 bool GuiCompleter::completionAvailable() const
257 {
258         if (!modelActive_)
259                 return false;
260
261         size_t n = popup()->model()->rowCount();
262
263         // if there is exactly one, we have to check whether it is a 
264         // real completion, i.e. longer than the current prefix.
265         if (n == 1 && completionPrefix() == currentCompletion())
266             return false;
267
268         return n > 0;
269 }
270
271
272 bool GuiCompleter::popupVisible() const
273 {
274         return popupVisible_;
275 }
276
277
278 bool GuiCompleter::inlineVisible() const
279 {
280         // In fact using BufferView::inlineCompletionPos.empty() should be
281         // here. But unfortunately this information is not good enough
282         // because destructive operations like backspace might invalidate
283         // inlineCompletionPos. But then the completion should stay visible
284         // (i.e. reshown on the next update). Hence be keep this information
285         // in the inlineVisible_ variable.
286         return inlineVisible_;
287 }
288
289
290 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep)
291 {
292         // parameters which affect the completion
293         bool moved = cur != old_cursor_;
294         if (moved)
295                 old_cursor_ = cur;
296
297         bool const possiblePopupState = popupPossible(cur);
298         bool const possibleInlineState = inlinePossible(cur);
299
300         // we moved or popup state is not ok for popup?
301         if ((moved && !keep) || !possiblePopupState)
302                 hidePopup();
303
304         // we moved or inline state is not ok for inline completion?
305         if ((moved && !keep) || !possibleInlineState)
306                 hideInline(cur);
307
308         // we inserted something and are in a possible popup state?
309         if (!popupVisible() && possiblePopupState && start
310                 && cur.inset().automaticPopupCompletion())
311                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
312
313         // we inserted something and are in a possible inline completion state?
314         if (!inlineVisible() && possibleInlineState && start
315                 && cur.inset().automaticInlineCompletion())
316                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
317         else if (cur.inMathed() && !lyxrc.completion_inline_math) {
318                 // no inline completion, hence a metrics update is needed
319                 if (!(cur.result().screenUpdate() & Update::Force))
320                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
321         }
322
323         // update prefix if any completion is possible
324         bool modelActive = modelActive_ && model()->rowCount() > 0;
325         if (possiblePopupState || possibleInlineState) {
326                 if (modelActive)
327                         updatePrefix(cur);
328                 else
329                         updateAvailability();
330         }
331 }
332
333
334 void GuiCompleter::updateVisibility(bool start, bool keep)
335 {
336         Cursor cur = gui_->bufferView().cursor();
337         cur.screenUpdateFlags(Update::None);
338         
339         updateVisibility(cur, start, keep);
340         
341         if (cur.result().screenUpdate())
342                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
343 }
344
345
346 void GuiCompleter::updatePrefix(Cursor const & cur)
347 {
348         // get new prefix. Do nothing if unchanged
349         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
350         if (newPrefix == completionPrefix())
351                 return;
352         
353         // value which should be kept selected
354         QString old = currentCompletion();
355         if (old.length() == 0)
356                 old = last_selection_;
357         
358         // update completer to new prefix
359         setCompletionPrefix(newPrefix);
360
361         // update popup because its size might have changed
362         if (popupVisible())
363                 updatePopup(cur);
364
365         // restore old selection
366         setCurrentCompletion(old);
367         
368         // if popup is not empty, the new selection will
369         // be our last valid one
370         QString const & s = currentCompletion();
371         if (popupVisible() || inlineVisible()) {
372                 if (s.length() > 0)
373                         last_selection_ = s;
374                 else
375                         last_selection_ = old;
376         }
377
378         // update inline completion because the default
379         // completion string might have changed
380         if (inlineVisible())
381                 updateInline(cur, s);
382 }
383
384
385 void GuiCompleter::updateInline(Cursor const & cur, QString const & completion)
386 {
387         if (!cur.inset().inlineCompletionSupported(cur))
388                 return;
389         
390         // compute postfix
391         docstring prefix = cur.inset().completionPrefix(cur);
392         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
393         
394         // shorten it if necessary
395         if (lyxrc.completion_inline_dots != -1
396             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
397                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
398
399         // set inline completion at cursor position
400         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
401         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
402         inlineVisible_ = true;
403 }
404
405
406 void GuiCompleter::updatePopup(Cursor const & cur)
407 {
408         if (!cur.inset().completionSupported(cur))
409                 return;
410         
411         popupVisible_ = true;
412
413         if (completionCount() == 0) {
414                 QTimer::singleShot(0, popup(), SLOT(hide()));
415                 return;
416         }
417
418         QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
419 }
420
421
422 void GuiCompleter::asyncUpdatePopup()
423 {
424         Cursor cur = gui_->bufferView().cursor();
425         if (!cur.inset().completionSupported(cur)
426                   || !cur.bv().paragraphVisible(cur)) {
427                 popupVisible_ = false;
428                 return;
429         }
430
431         // get dimensions of completion prefix
432         Dimension dim;
433         int x;
434         int y;
435         cur.inset().completionPosAndDim(cur, x, y, dim);
436         
437         // and calculate the rect of the popup
438         QRect rect;
439         if (popup()->layoutDirection() == Qt::RightToLeft)
440                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
441         else
442                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
443         
444         // Resize the columns in the popup.
445         // This should really be in the constructor. But somehow the treeview
446         // has a bad memory about it and we have to tell him again and again.
447         QTreeView * listView = static_cast<QTreeView *>(popup());
448         listView->header()->setStretchLastSection(false);
449         setSectionResizeMode(listView->header(), 0, QHeaderView::Stretch);
450         setSectionResizeMode(listView->header(), 1, QHeaderView::Fixed);
451         listView->header()->resizeSection(1, 22);
452         
453         // show/update popup
454         complete(rect);
455 }
456
457
458 void GuiCompleter::updateAvailability()
459 {
460         // this should really only be of interest if no completion is
461         // visible yet, i.e. especially if automatic completion is disabled.
462         if (inlineVisible() || popupVisible())
463                 return;
464         Cursor const & cur = gui_->bufferView().cursor();
465         if (!popupPossible(cur) && !inlinePossible(cur))
466                 return;
467         
468         updateModel(cur, false, false);
469 }
470         
471
472 void GuiCompleter::updateModel(Cursor const & cur, bool popupUpdate, bool inlineUpdate)
473 {
474         // value which should be kept selected
475         QString old = currentCompletion();
476         if (old.length() == 0)
477                 old = last_selection_;
478
479         // set whether rtl
480         bool rtl = false;
481         if (cur.inTexted()) {
482                 Paragraph const & par = cur.paragraph();
483                 Font const & font =
484                         par.getFontSettings(cur.bv().buffer().params(), cur.pos());
485                 rtl = font.isVisibleRightToLeft();
486         }
487         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
488
489         // set new model
490         CompletionList const * list = cur.inset().createCompletionList(cur);
491         model_->setList(list);
492         modelActive_ = true;
493         if (list->sorted())
494                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
495         else
496                 setModelSorting(QCompleter::UnsortedModel);
497
498         // set prefix
499         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
500         if (newPrefix != completionPrefix())
501                 setCompletionPrefix(newPrefix);
502
503         // show popup
504         if (popupUpdate)
505                 updatePopup(cur);
506
507         // restore old selection
508         setCurrentCompletion(old);
509         
510         // if popup is not empty, the new selection will
511         // be our last valid one
512         if (popupVisible() || inlineVisible()) {
513                 QString const & s = currentCompletion();
514                 if (s.length() > 0)
515                         last_selection_ = s;
516                 else
517                         last_selection_ = old;
518         }
519
520         // show inline completion
521         if (inlineUpdate)
522                 updateInline(cur, currentCompletion());
523 }
524
525
526 void GuiCompleter::showPopup(Cursor const & cur)
527 {
528         if (!popupPossible(cur))
529                 return;
530         
531         updateModel(cur, true, inlineVisible());
532 }
533
534
535 void GuiCompleter::asyncHidePopup()
536 {
537         popup()->hide();
538         if (!inlineVisible())
539                 model_->setList(0);
540 }
541
542
543 void GuiCompleter::showInline(Cursor const & cur)
544 {
545         if (!inlinePossible(cur))
546                 return;
547         
548         updateModel(cur, popupVisible(), true);
549 }
550
551
552 void GuiCompleter::hideInline(Cursor const & cur)
553 {
554         gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
555         inlineVisible_ = false;
556         
557         if (inline_timer_.isActive())
558                 inline_timer_.stop();
559         
560         // Trigger asynchronous part of hideInline. We might be
561         // in a dispatcher here and the setModel call might
562         // trigger focus events which is are not healthy here.
563         QTimer::singleShot(0, this, SLOT(asyncHideInline()));
564
565         // mark that the asynchronous part will reset the model
566         if (!popupVisible())
567                 modelActive_ = false;
568 }
569
570
571 void GuiCompleter::asyncHideInline()
572 {
573         if (!popupVisible())
574                 model_->setList(0);
575 }
576
577
578 void GuiCompleter::showPopup()
579 {
580         Cursor cur = gui_->bufferView().cursor();
581         cur.screenUpdateFlags(Update::None);
582         
583         showPopup(cur);
584
585         // redraw if needed
586         if (cur.result().screenUpdate())
587                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
588 }
589
590
591 void GuiCompleter::showInline()
592 {
593         Cursor cur = gui_->bufferView().cursor();
594         cur.screenUpdateFlags(Update::None);
595         
596         showInline(cur);
597
598         // redraw if needed
599         if (cur.result().screenUpdate())
600                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
601 }
602
603
604 void GuiCompleter::hidePopup()
605 {
606         popupVisible_ = false;
607
608         if (popup_timer_.isActive())
609                 popup_timer_.stop();
610
611         // hide popup asynchronously because we might be here inside of
612         // LFUN dispatchers. Hiding a popup can trigger a focus event on the
613         // workarea which then redisplays the cursor. But the metrics are not
614         // yet up to date such that the coord cache has not all insets yet. The
615         // cursorPos methods would triggers asserts in the coord cache then.
616         QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
617         
618         // mark that the asynchronous part will reset the model
619         if (!inlineVisible())
620                 modelActive_ = false;
621 }
622
623
624 void GuiCompleter::hideInline()
625 {
626         Cursor cur = gui_->bufferView().cursor();
627         cur.screenUpdateFlags(Update::None);
628         
629         hideInline(cur);
630         
631         // redraw if needed
632         if (cur.result().screenUpdate())
633                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
634 }
635
636
637 void GuiCompleter::activate()
638 {
639         if (!popupVisible() && !inlineVisible())
640                 tab();
641         else
642                 popupActivated(currentCompletion());
643 }
644
645
646 void GuiCompleter::tab()
647 {
648         BufferView * bv = &gui_->bufferView();
649         Cursor cur = bv->cursor();
650         cur.screenUpdateFlags(Update::None);
651         
652         // check that inline completion is active
653         if (!inlineVisible() && !uniqueCompletionAvailable()) {
654                 // try to activate the inline completion
655                 if (cur.inset().inlineCompletionSupported(cur)) {
656                         showInline();
657                         
658                         // show popup without delay because the completion was not unique
659                         if (lyxrc.completion_popup_after_complete
660                             && !popupVisible()
661                             && popup()->model()->rowCount() > 1)
662                                 popup_timer_.start(0);
663
664                         return;
665                 }
666                 // or try popup
667                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
668                         showPopup();
669                         return;
670                 }
671                 
672                 return;
673         }
674         
675         // Make undo possible
676         cur.beginUndoGroup();
677         cur.recordUndo();
678
679         // If completion is active, at least complete by one character
680         docstring prefix = cur.inset().completionPrefix(cur);
681         docstring completion = qstring_to_ucs4(currentCompletion());
682         if (completion.size() <= prefix.size()) {
683                 // finalize completion
684                 cur.inset().insertCompletion(cur, docstring(), true);
685                 
686                 // hide popup and inline completion
687                 hidePopup();
688                 hideInline(cur);
689                 updateVisibility(false, false);
690                 cur.endUndoGroup();
691                 return;
692         }
693         docstring nextchar = completion.substr(prefix.size(), 1);
694         if (!cur.inset().insertCompletion(cur, nextchar, false)) {
695                 cur.endUndoGroup();
696                 return;
697         }
698         updatePrefix(cur);
699
700         // try to complete as far as it is unique
701         docstring longestCompletion = longestUniqueCompletion();
702         prefix = cur.inset().completionPrefix(cur);
703         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
704         cur.inset().insertCompletion(cur, postfix, false);
705         old_cursor_ = bv->cursor();
706         updatePrefix(cur);
707
708         // show popup without delay because the completion was not unique
709         if (lyxrc.completion_popup_after_complete
710             && !popupVisible()
711             && popup()->model()->rowCount() > 1)
712                 popup_timer_.start(0);
713
714         // redraw if needed
715         if (cur.result().screenUpdate())
716                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
717         cur.endUndoGroup();
718 }
719
720
721 QString GuiCompleter::currentCompletion() const
722 {
723         if (!popup()->selectionModel()->hasSelection())
724                 return QString();
725
726         // Not sure if this is bug in Qt: currentIndex() always 
727         // return the first element in the list.
728         QModelIndex idx = popup()->currentIndex();
729         return popup()->model()->data(idx, Qt::EditRole).toString();
730 }
731
732
733 void GuiCompleter::setCurrentCompletion(QString const & s)
734 {       
735         QAbstractItemModel const & model = *popup()->model();
736         size_t n = model.rowCount();
737         if (n == 0)
738                 return;
739
740         // select the first if s is empty
741         if (s.length() == 0) {
742                 updateLock_++;
743                 popup()->setCurrentIndex(model.index(0, 0));
744                 updateLock_--;
745                 return;
746         }
747
748         // find old selection in model
749         size_t i;
750         if (modelSorting() == QCompleter::UnsortedModel) {
751                 // In unsorted models, iterate through list until the s is found
752                 for (i = 0; i < n; ++i) {
753                         QString const & is
754                         = model.data(model.index(i, 0), Qt::EditRole).toString();
755                         if (is == s)
756                                 break;
757                 }
758         } else {
759                 // In sorted models, do binary search for s.
760                 int l = 0;
761                 int r = n - 1;
762                 while (r >= l && l < int(n)) {
763                         size_t mid = (r + l) / 2;
764                         QString const & mids
765                         = model.data(model.index(mid, 0),
766                                      Qt::EditRole).toString();
767
768                         // left or right?
769                         // FIXME: is this really the same order that the docstring
770                         // from the CompletionList has?
771                         int c = s.compare(mids, Qt::CaseSensitive);
772                         if (c == 0) {
773                                 l = mid;
774                                 break;
775                         } else if (l == r) {
776                                 l = n;
777                                 break;
778                         } else if (c > 0)
779                                 // middle is not far enough
780                                 l = mid + 1;
781                         else
782                                 // middle is too far
783                                 r = mid - 1;
784                 }
785
786                 // loop was left without finding anything
787                 if (r < l)
788                         i = n;
789                 else
790                         i = l;
791                 // we can try to recover
792                 LASSERT(i <= n, i = 0);
793         }
794
795         // select the first if none was found
796         if (i == n)
797                 i = 0;
798
799         updateLock_++;
800         popup()->setCurrentIndex(model.index(i, 0));
801         updateLock_--;
802 }
803
804
805 size_t commonPrefix(QString const & s1, QString const & s2)
806 {
807         // find common prefix
808         size_t j;
809         size_t n1 = s1.length();
810         size_t n2 = s2.length();
811         for (j = 0; j < n1 && j < n2; ++j) {
812                 if (s1.at(j) != s2.at(j))
813                         break;
814         }
815         return j;
816 }
817
818
819 docstring GuiCompleter::longestUniqueCompletion() const
820 {
821         QAbstractItemModel const & model = *popup()->model();
822         size_t n = model.rowCount();
823         if (n == 0)
824                 return docstring();
825         QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
826
827         if (modelSorting() == QCompleter::UnsortedModel) {
828                 // For unsorted model we cannot do more than iteration.
829                 // Iterate through the completions and cut off where s differs
830                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
831                         QString const & is
832                         = model.data(model.index(i, 0), Qt::EditRole).toString();
833
834                         s = s.left(commonPrefix(is, s));
835                 }
836         } else {
837                 // For sorted models we can do binary search multiple times,
838                 // each time to find the first string which has s not as prefix.
839                 size_t i = 0;
840                 while (i < n && s.length() > 0) {
841                         // find first string that does not have s as prefix
842                         // via binary search in [i,n-1]
843                         size_t r = n - 1;
844                         do {
845                                 // get common prefix with the middle string
846                                 size_t mid = (r + i) / 2;
847                                 QString const & mids
848                                 = model.data(model.index(mid, 0), 
849                                         Qt::EditRole).toString();
850                                 size_t oldLen = s.length();
851                                 size_t len = commonPrefix(mids, s);
852                                 s = s.left(len);
853
854                                 // left or right?
855                                 if (oldLen == len) {
856                                         // middle is not far enough
857                                         i = mid + 1;
858                                 } else {
859                                         // middle is maybe too far
860                                         r = mid;
861                                 }
862                         } while (r - i > 0 && i < n);
863                 }
864         }
865
866         return qstring_to_ucs4(s);
867 }
868
869
870 void GuiCompleter::popupActivated(const QString & completion)
871 {
872         Cursor cur = gui_->bufferView().cursor();
873         cur.screenUpdateFlags(Update::None);
874
875         cur.beginUndoGroup();
876         cur.recordUndo();
877
878         docstring prefix = cur.inset().completionPrefix(cur);
879         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
880         cur.inset().insertCompletion(cur, postfix, true);
881         hidePopup();
882         hideInline(cur);
883         
884         if (cur.result().screenUpdate())
885                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
886         cur.endUndoGroup();
887 }
888
889
890 void GuiCompleter::popupHighlighted(const QString & completion)
891 {
892         if (updateLock_ > 0)
893                 return;
894
895         Cursor cur = gui_->bufferView().cursor();
896         cur.screenUpdateFlags(Update::None);
897         
898         if (inlineVisible())
899                 updateInline(cur, completion);
900         
901         if (cur.result().screenUpdate())
902                 gui_->bufferView().processUpdateFlags(cur.result().screenUpdate());
903 }
904
905 } // namespace frontend
906 } // namespace lyx
907
908 #include "moc_GuiCompleter.cpp"