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