]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
* fix spelling in comments to please John.
[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 "FuncRequest.h"
21 #include "GuiWorkArea.h"
22 #include "GuiView.h"
23 #include "LyXFunc.h"
24 #include "LyXRC.h"
25 #include "Paragraph.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 <QPainter>
34 #include <QPixmapCache>
35 #include <QScrollBar>
36 #include <QItemDelegate>
37 #include <QTreeView>
38 #include <QTimer>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44 namespace frontend {
45
46 class CompleterItemDelegate : public QItemDelegate
47 {
48 public:
49         explicit CompleterItemDelegate(QObject * parent)
50                 : QItemDelegate(parent)
51         {}
52
53         ~CompleterItemDelegate()
54         {}
55
56 protected:
57         void paint(QPainter *painter, const QStyleOptionViewItem &option,
58                    const QModelIndex &index) const
59         {
60                 if (index.column() == 0) {
61                         QItemDelegate::paint(painter, option, index);
62                         return;
63                 }
64                 QStyleOptionViewItem opt = setOptions(index, option);
65                 QVariant value = index.data(Qt::DisplayRole);
66                 QPixmap pixmap = qvariant_cast<QPixmap>(value);
67                 
68                 // draw
69                 painter->save();
70                 drawBackground(painter, opt, index);
71                 if (!pixmap.isNull()) {
72                         const QSize size = pixmap.size();
73                         painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
74                                 option.rect.top() + (option.rect.height() - size.height()) / 2,
75                                 pixmap);
76                 }
77                 drawFocus(painter, opt, option.rect);
78                 painter->restore();
79         }
80 };
81
82 class GuiCompletionModel : public QAbstractListModel
83 {
84 public:
85         ///
86         GuiCompletionModel(QObject * parent, CompletionList const * l)
87                 : QAbstractListModel(parent), list_(l)
88         {}
89         ///
90         ~GuiCompletionModel() { delete list_; }
91         ///
92         void setList(CompletionList const * l) {
93                 delete list_;
94                 list_ = l;
95                 reset();
96         }
97         ///
98         bool sorted() const
99         {
100                 if (list_)
101                         return list_->sorted();
102                 return false;
103         }
104         ///
105         int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
106         {
107                 return 2;
108         }
109         ///
110         int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
111         {
112                 if (list_ == 0)
113                         return 0;
114                 else
115                         return list_->size();
116         }
117
118         ///
119         QVariant data(const QModelIndex & index, int role) const
120         {
121                 if (list_ == 0)
122                         return QVariant();
123
124                 if (index.row() < 0 || index.row() >= rowCount())
125                         return QVariant();
126
127                 if (role != Qt::DisplayRole && role != Qt::EditRole)
128                     return QVariant();
129                     
130                 if (index.column() == 0)
131                         return toqstr(list_->data(index.row()));
132
133                 if (index.column() == 1) {
134                         // get icon from cache
135                         QPixmap scaled;
136                         QString const name = ":" + toqstr(list_->icon(index.row()));
137                         if (!QPixmapCache::find("completion" + name, scaled)) {
138                                 // load icon from disk
139                                 QPixmap p = QPixmap(name);
140                                 if (!p.isNull()) {
141                                         // scale it to 16x16 or smaller
142                                         scaled = p.scaled(min(16, p.width()), min(16, p.height()), 
143                                                 Qt::KeepAspectRatio, Qt::SmoothTransformation);
144                                 }
145
146                                 QPixmapCache::insert("completion" + name, scaled);
147                         }
148                         return scaled;
149                 }
150                 return QVariant();
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::CaseInsensitive);
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, bool cursorInView)
291 {
292         // parameters which affect the completion
293         bool moved = cur != old_cursor_;
294         if (moved)
295                 old_cursor_ = cur;
296
297         bool possiblePopupState = popupPossible(cur) && cursorInView;
298         bool possibleInlineState = inlinePossible(cur) && cursorInView;
299
300         // we moved or popup state is not ok for popup?
301         if ((moved && !keep) || !possiblePopupState)
302                 hidePopup(cur);
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 {
318                 // no inline completion, hence a metrics update is needed
319                 if (!(cur.disp_.update() & Update::Force))
320                         cur.updateFlags(cur.disp_.update() | 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.updateFlags(Update::None);
338         
339         updateVisibility(cur, start, keep);
340         
341         if (cur.disp_.update())
342                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
343 }
344
345
346 void GuiCompleter::updatePrefix(Cursor & 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 & 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 & 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                 popupVisible_ = false;
427                 return;
428         }
429
430         // get dimensions of completion prefix
431         Dimension dim;
432         int x;
433         int y;
434         cur.inset().completionPosAndDim(cur, x, y, dim);
435         
436         // and calculate the rect of the popup
437         QRect rect;
438         if (popup()->layoutDirection() == Qt::RightToLeft)
439                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
440         else
441                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
442         
443         // Resize the columns in the popup.
444         // This should really be in the constructor. But somehow the treeview
445         // has a bad memory about it and we have to tell him again and again.
446         QTreeView * listView = static_cast<QTreeView *>(popup());
447         listView->header()->setStretchLastSection(false);
448         listView->header()->setResizeMode(0, QHeaderView::Stretch);
449         listView->header()->setResizeMode(1, QHeaderView::Fixed);
450         listView->header()->resizeSection(1, 22);
451         
452         // show/update popup
453         complete(rect);
454 }
455
456
457 void GuiCompleter::updateAvailability()
458 {
459         // this should really only be of interest if no completion is
460         // visible yet, i.e. especially if automatic completion is disabled.
461         if (inlineVisible() || popupVisible())
462                 return;
463         Cursor & cur = gui_->bufferView().cursor();
464         if (!popupPossible(cur) && !inlinePossible(cur))
465                 return;
466         
467         updateModel(cur, false, false);
468 }
469         
470
471 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
472 {
473         // value which should be kept selected
474         QString old = currentCompletion();
475         if (old.length() == 0)
476                 old = last_selection_;
477
478         // set whether rtl
479         bool rtl = false;
480         if (cur.inTexted()) {
481                 Paragraph const & par = cur.paragraph();
482                 Font const & font =
483                         par.getFontSettings(cur.bv().buffer().params(), cur.pos());
484                 rtl = font.isVisibleRightToLeft();
485         }
486         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
487
488         // set new model
489         CompletionList const * list = cur.inset().createCompletionList(cur);
490         model_->setList(list);
491         modelActive_ = true;
492         if (list->sorted())
493                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
494         else
495                 setModelSorting(QCompleter::UnsortedModel);
496
497         // set prefix
498         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
499         if (newPrefix != completionPrefix())
500                 setCompletionPrefix(newPrefix);
501
502         // show popup
503         if (popupUpdate)
504                 updatePopup(cur);
505
506         // restore old selection
507         setCurrentCompletion(old);
508         
509         // if popup is not empty, the new selection will
510         // be our last valid one
511         if (popupVisible() || inlineVisible()) {
512                 QString const & s = currentCompletion();
513                 if (s.length() > 0)
514                         last_selection_ = s;
515                 else
516                         last_selection_ = old;
517         }
518
519         // show inline completion
520         if (inlineUpdate)
521                 updateInline(cur, currentCompletion());
522 }
523
524
525 void GuiCompleter::showPopup(Cursor & cur)
526 {
527         if (!popupPossible(cur))
528                 return;
529         
530         updateModel(cur, true, inlineVisible());
531 }
532
533
534 void GuiCompleter::hidePopup(Cursor &)
535 {
536         popupVisible_ = false;
537
538         if (popup_timer_.isActive())
539                 popup_timer_.stop();
540
541         // hide popup asynchronously because we might be here inside of
542         // LFUN dispatchers. Hiding a popup can trigger a focus event on the 
543         // workarea which then redisplays the cursor. But the metrics are not
544         // yet up to date such that the coord cache has not all insets yet. The
545         // cursorPos methods would triggers asserts in the coord cache then.
546         QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
547         
548         // mark that the asynchronous part will reset the model
549         if (!inlineVisible())
550                 modelActive_ = false;
551 }
552
553
554 void GuiCompleter::asyncHidePopup()
555 {
556         popup()->hide();
557         if (!inlineVisible())
558                 model_->setList(0);
559 }
560
561
562 void GuiCompleter::showInline(Cursor & cur)
563 {
564         if (!inlinePossible(cur))
565                 return;
566         
567         updateModel(cur, popupVisible(), true);
568 }
569
570
571 void GuiCompleter::hideInline(Cursor & cur)
572 {
573         gui_->bufferView().setInlineCompletion(cur, DocIterator(cur.buffer()), docstring());
574         inlineVisible_ = false;
575         
576         if (inline_timer_.isActive())
577                 inline_timer_.stop();
578         
579         // Trigger asynchronous part of hideInline. We might be
580         // in a dispatcher here and the setModel call might
581         // trigger focus events which is are not healthy here.
582         QTimer::singleShot(0, this, SLOT(asyncHideInline()));
583
584         // mark that the asynchronous part will reset the model
585         if (!popupVisible())
586                 modelActive_ = false;
587 }
588
589
590 void GuiCompleter::asyncHideInline()
591 {
592         if (!popupVisible())
593                 model_->setList(0);
594 }
595
596
597 void GuiCompleter::showPopup()
598 {
599         Cursor cur = gui_->bufferView().cursor();
600         cur.updateFlags(Update::None);
601         
602         showPopup(cur);
603
604         // redraw if needed
605         if (cur.disp_.update())
606                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
607 }
608
609
610 void GuiCompleter::showInline()
611 {
612         Cursor cur = gui_->bufferView().cursor();
613         cur.updateFlags(Update::None);
614         
615         showInline(cur);
616
617         // redraw if needed
618         if (cur.disp_.update())
619                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
620 }
621
622
623 void GuiCompleter::hidePopup()
624 {
625         Cursor cur = gui_->bufferView().cursor();
626         cur.updateFlags(Update::None);
627         
628         hidePopup(cur);
629         
630         // redraw if needed
631         if (cur.disp_.update())
632                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
633 }
634
635
636 void GuiCompleter::hideInline()
637 {
638         Cursor cur = gui_->bufferView().cursor();
639         cur.updateFlags(Update::None);
640         
641         hideInline(cur);
642         
643         // redraw if needed
644         if (cur.disp_.update())
645                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
646 }
647
648
649 void GuiCompleter::activate()
650 {
651         if (!popupVisible() && !inlineVisible())
652                 tab();
653         else
654                 popupActivated(currentCompletion());
655 }
656
657
658 void GuiCompleter::tab()
659 {
660         BufferView * bv = &gui_->bufferView();
661         Cursor cur = bv->cursor();
662         cur.updateFlags(Update::None);
663         
664         // check that inline completion is active
665         if (!inlineVisible() && !uniqueCompletionAvailable()) {
666                 // try to activate the inline completion
667                 if (cur.inset().inlineCompletionSupported(cur)) {
668                         showInline();
669                         
670                         // show popup without delay because the completion was not unique
671                         if (lyxrc.completion_popup_after_complete
672                             && !popupVisible()
673                             && popup()->model()->rowCount() > 1)
674                                 popup_timer_.start(0);
675
676                         return;
677                 }
678                 // or try popup
679                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
680                         showPopup();
681                         return;
682                 }
683                 
684                 return;
685         }
686         
687         // Make undo possible
688         cur.recordUndo();
689
690         // If completion is active, at least complete by one character
691         docstring prefix = cur.inset().completionPrefix(cur);
692         docstring completion = qstring_to_ucs4(currentCompletion());
693         if (completion.size() <= prefix.size()) {
694                 // finalize completion
695                 cur.inset().insertCompletion(cur, docstring(), true);
696                 
697                 // hide popup and inline completion
698                 hidePopup(cur);
699                 hideInline(cur);
700                 updateVisibility(false, false);
701                 return;
702         }
703         docstring nextchar = completion.substr(prefix.size(), 1);
704         if (!cur.inset().insertCompletion(cur, nextchar, false))
705                 return;
706         updatePrefix(cur);
707
708         // try to complete as far as it is unique
709         docstring longestCompletion = longestUniqueCompletion();
710         prefix = cur.inset().completionPrefix(cur);
711         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
712         cur.inset().insertCompletion(cur, postfix, false);
713         old_cursor_ = bv->cursor();
714         updatePrefix(cur);
715
716         // show popup without delay because the completion was not unique
717         if (lyxrc.completion_popup_after_complete
718             && !popupVisible()
719             && popup()->model()->rowCount() > 1)
720                 popup_timer_.start(0);
721
722         // redraw if needed
723         if (cur.disp_.update())
724                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
725 }
726
727
728 QString GuiCompleter::currentCompletion() const
729 {
730         if (!popup()->selectionModel()->hasSelection())
731                 return QString();
732
733         // Not sure if this is bug in Qt: currentIndex() always 
734         // return the first element in the list.
735         QModelIndex idx = popup()->currentIndex();
736         return popup()->model()->data(idx, Qt::EditRole).toString();
737 }
738
739
740 void GuiCompleter::setCurrentCompletion(QString const & s)
741 {       
742         QAbstractItemModel const & model = *popup()->model();
743         size_t n = model.rowCount();
744         if (n == 0)
745                 return;
746
747         // select the first if s is empty
748         if (s.length() == 0) {
749                 updateLock_++;
750                 popup()->setCurrentIndex(model.index(0, 0));
751                 updateLock_--;
752                 return;
753         }
754
755         // find old selection in model
756         size_t i;
757         if (modelSorting() == QCompleter::UnsortedModel) {
758                 // In unsorted models, iterate through list until the s is found
759                 for (i = 0; i < n; ++i) {
760                         QString const & is
761                         = model.data(model.index(i, 0), Qt::EditRole).toString();
762                         if (is == s)
763                                 break;
764                 }
765         } else {
766                 // In sorted models, do binary search for s.
767                 int l = 0;
768                 int r = n - 1;
769                 while (r >= l && l < int(n)) {
770                         size_t mid = (r + l) / 2;
771                         QString const & mids
772                         = model.data(model.index(mid, 0),
773                                      Qt::EditRole).toString();
774
775                         // left or right?
776                         // FIXME: is this really the same order that the docstring
777                         // from the CompletionList has?
778                         int c = s.compare(mids, Qt::CaseSensitive);
779                         if (c == 0) {
780                                 l = mid;
781                                 break;
782                         } else if (l == r) {
783                                 l = n;
784                                 break;
785                         } else if (c > 0)
786                                 // middle is not far enough
787                                 l = mid + 1;
788                         else
789                                 // middle is too far
790                                 r = mid - 1;
791                 }
792
793                 // loop was left without finding anything
794                 if (r < l)
795                         i = n;
796                 else
797                         i = l;
798                 LASSERT(i <= n, /**/);
799         }
800
801         // select the first if none was found
802         if (i == n)
803                 i = 0;
804
805         updateLock_++;
806         popup()->setCurrentIndex(model.index(i, 0));
807         updateLock_--;
808 }
809
810
811 size_t commonPrefix(QString const & s1, QString const & s2)
812 {
813         // find common prefix
814         size_t j;
815         size_t n1 = s1.length();
816         size_t n2 = s2.length();
817         for (j = 0; j < n1 && j < n2; ++j) {
818                 if (s1.at(j) != s2.at(j))
819                         break;
820         }
821         return j;
822 }
823
824
825 docstring GuiCompleter::longestUniqueCompletion() const
826 {
827         QAbstractItemModel const & model = *popup()->model();
828         size_t n = model.rowCount();
829         if (n == 0)
830                 return docstring();
831         QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
832
833         if (modelSorting() == QCompleter::UnsortedModel) {
834                 // For unsorted model we cannot do more than iteration.
835                 // Iterate through the completions and cut off where s differs
836                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
837                         QString const & is
838                         = model.data(model.index(i, 0), Qt::EditRole).toString();
839
840                         s = s.left(commonPrefix(is, s));
841                 }
842         } else {
843                 // For sorted models we can do binary search multiple times,
844                 // each time to find the first string which has s not as prefix.
845                 size_t i = 0;
846                 while (i < n && s.length() > 0) {
847                         // find first string that does not have s as prefix
848                         // via binary search in [i,n-1]
849                         size_t r = n - 1;
850                         do {
851                                 // get common prefix with the middle string
852                                 size_t mid = (r + i) / 2;
853                                 QString const & mids
854                                 = model.data(model.index(mid, 0), 
855                                         Qt::EditRole).toString();
856                                 size_t oldLen = s.length();
857                                 size_t len = commonPrefix(mids, s);
858                                 s = s.left(len);
859
860                                 // left or right?
861                                 if (oldLen == len) {
862                                         // middle is not far enough
863                                         i = mid + 1;
864                                 } else {
865                                         // middle is maybe too far
866                                         r = mid;
867                                 }
868                         } while (r - i > 0 && i < n);
869                 }
870         }
871
872         return qstring_to_ucs4(s);
873 }
874
875
876 void GuiCompleter::popupActivated(const QString & completion)
877 {
878         Cursor cur = gui_->bufferView().cursor();
879         cur.updateFlags(Update::None);
880         
881         cur.recordUndo();
882
883         docstring prefix = cur.inset().completionPrefix(cur);
884         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
885         cur.inset().insertCompletion(cur, postfix, true);
886         hidePopup(cur);
887         hideInline(cur);
888         
889         if (cur.disp_.update())
890                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
891 }
892
893
894 void GuiCompleter::popupHighlighted(const QString & completion)
895 {
896         if (updateLock_ > 0)
897                 return;
898
899         Cursor cur = gui_->bufferView().cursor();
900         cur.updateFlags(Update::None);
901         
902         if (inlineVisible())
903                 updateInline(cur, completion);
904         
905         if (cur.disp_.update())
906                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
907 }
908
909 } // namespace frontend
910 } // namespace lyx
911
912 #include "moc_GuiCompleter.cpp"