]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
Remove unused UI file.
[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         setWidget(gui_);
169         
170         // create the popup
171         QTreeView *listView = new QTreeView;
172         listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
173         listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
174         listView->setSelectionBehavior(QAbstractItemView::SelectRows);
175         listView->setSelectionMode(QAbstractItemView::SingleSelection);
176         listView->header()->hide();
177         listView->setIndentation(0);
178         listView->setUniformRowHeights(true);
179         setPopup(listView);
180         
181         itemDelegate_ = new CompleterItemDelegate(this);
182         popup()->setItemDelegate(itemDelegate_);
183         
184         // create timeout timers
185         popup_timer_.setSingleShot(true);
186         inline_timer_.setSingleShot(true);
187         connect(this, SIGNAL(highlighted(const QString &)),
188                 this, SLOT(popupHighlighted(const QString &)));
189         connect(this, SIGNAL(activated(const QString &)),
190                 this, SLOT(popupActivated(const QString &)));
191         connect(&popup_timer_, SIGNAL(timeout()),
192                 this, SLOT(showPopup()));
193         connect(&inline_timer_, SIGNAL(timeout()),
194                 this, SLOT(showInline()));
195 }
196
197
198 GuiCompleter::~GuiCompleter()
199 {
200         popup()->hide();
201 }
202
203
204 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
205 {
206         // hijack back the tab key from the popup
207         // (which stole it from the workspace before)
208         if (e->type() == QEvent::KeyPress && popupVisible()) {
209                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
210                 switch (ke->key()) {
211                 case Qt::Key_Tab:
212                         tab();
213                         ke->accept();
214                         return true;
215                 default: break;
216                 }
217         }
218         
219         return QCompleter::eventFilter(watched, e);
220 }
221
222
223 bool GuiCompleter::popupPossible(Cursor const & cur) const
224 {
225         return QApplication::activeWindow()
226                 && gui_->hasFocus()
227                 && cur.inset().completionSupported(cur);
228 }
229
230
231 bool GuiCompleter::inlinePossible(Cursor const & cur) const
232 {
233         return cur.inset().inlineCompletionSupported(cur);
234 }
235
236
237 bool GuiCompleter::uniqueCompletionAvailable() const
238 {
239         if (!modelActive_)
240                 return false;
241
242         size_t n = popup()->model()->rowCount();
243         if (n > 1 || n == 0)
244                 return false;
245
246         // if there is exactly one, we have to check whether it is a 
247         // real completion, i.e. longer than the current prefix.
248         if (completionPrefix() == currentCompletion())
249                 return false;
250
251         return true;
252 }
253
254
255 bool GuiCompleter::completionAvailable() const
256 {
257         if (!modelActive_)
258                 return false;
259
260         size_t n = popup()->model()->rowCount();
261
262         // if there is exactly one, we have to check whether it is a 
263         // real completion, i.e. longer than the current prefix.
264         if (n == 1 && completionPrefix() == currentCompletion())
265             return false;
266
267         return n > 0;
268 }
269
270
271 bool GuiCompleter::popupVisible() const
272 {
273         return popupVisible_;
274 }
275
276
277 bool GuiCompleter::inlineVisible() const
278 {
279         // In fact using BufferView::inlineCompletionPos.empty() should be
280         // here. But unfortunately this information is not good enough
281         // because destructive operations like backspace might invalidate
282         // inlineCompletionPos. But then the completion should stay visible
283         // (i.e. reshown on the next update). Hence be keep this information
284         // in the inlineVisible_ variable.
285         return inlineVisible_;
286 }
287
288
289 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
290 {
291         // parameters which affect the completion
292         bool moved = cur != old_cursor_;
293         if (moved)
294                 old_cursor_ = cur;
295
296         bool possiblePopupState = popupPossible(cur) && cursorInView;
297         bool possibleInlineState = inlinePossible(cur) && cursorInView;
298
299         // we moved or popup state is not ok for popup?
300         if ((moved && !keep) || !possiblePopupState)
301                 hidePopup(cur);
302
303         // we moved or inline state is not ok for inline completion?
304         if ((moved && !keep) || !possibleInlineState)
305                 hideInline(cur);
306
307         // we inserted something and are in a possible popup state?
308         if (!popupVisible() && possiblePopupState && start
309                 && cur.inset().automaticPopupCompletion())
310                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
311
312         // we inserted something and are in a possible inline completion state?
313         if (!inlineVisible() && possibleInlineState && start
314                 && cur.inset().automaticInlineCompletion())
315                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
316         else {
317                 // no inline completion, hence a metrics update is needed
318                 if (!(cur.disp_.update() & Update::Force))
319                         cur.updateFlags(cur.disp_.update() | Update::SinglePar);
320         }
321
322         // update prefix if any completion is possible
323         bool modelActive = modelActive_ && model()->rowCount() > 0;
324         if (possiblePopupState || possibleInlineState) {
325                 if (modelActive)
326                         updatePrefix(cur);
327                 else
328                         updateAvailability();
329         }
330 }
331
332
333 void GuiCompleter::updateVisibility(bool start, bool keep)
334 {
335         Cursor cur = gui_->bufferView().cursor();
336         cur.updateFlags(Update::None);
337         
338         updateVisibility(cur, start, keep);
339         
340         if (cur.disp_.update())
341                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
342 }
343
344
345 void GuiCompleter::updatePrefix(Cursor & cur)
346 {
347         // get new prefix. Do nothing if unchanged
348         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
349         if (newPrefix == completionPrefix())
350                 return;
351         
352         // value which should be kept selected
353         QString old = currentCompletion();
354         if (old.length() == 0)
355                 old = last_selection_;
356         
357         // update completer to new prefix
358         setCompletionPrefix(newPrefix);
359
360         // update popup because its size might have changed
361         if (popupVisible())
362                 updatePopup(cur);
363
364         // restore old selection
365         setCurrentCompletion(old);
366         
367         // if popup is not empty, the new selection will
368         // be our last valid one
369         QString const & s = currentCompletion();
370         if (popupVisible() || inlineVisible()) {
371                 if (s.length() > 0)
372                         last_selection_ = s;
373                 else
374                         last_selection_ = old;
375         }
376
377         // update inline completion because the default
378         // completion string might have changed
379         if (inlineVisible())
380                 updateInline(cur, s);
381 }
382
383
384 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
385 {
386         if (!cur.inset().inlineCompletionSupported(cur))
387                 return;
388         
389         // compute postfix
390         docstring prefix = cur.inset().completionPrefix(cur);
391         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
392         
393         // shorten it if necessary
394         if (lyxrc.completion_inline_dots != -1
395             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
396                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
397
398         // set inline completion at cursor position
399         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
400         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
401         inlineVisible_ = true;
402 }
403
404
405 void GuiCompleter::updatePopup(Cursor & cur)
406 {
407         if (!cur.inset().completionSupported(cur))
408                 return;
409         
410         popupVisible_ = true;
411
412         if (completionCount() == 0) {
413                 QTimer::singleShot(0, popup(), SLOT(hide()));
414                 return;
415         }
416
417         QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
418 }
419
420
421 void GuiCompleter::asyncUpdatePopup()
422 {
423         Cursor cur = gui_->bufferView().cursor();
424         if (!cur.inset().completionSupported(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.updateFlags(Update::None);
600         
601         showPopup(cur);
602
603         // redraw if needed
604         if (cur.disp_.update())
605                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
606 }
607
608
609 void GuiCompleter::showInline()
610 {
611         Cursor cur = gui_->bufferView().cursor();
612         cur.updateFlags(Update::None);
613         
614         showInline(cur);
615
616         // redraw if needed
617         if (cur.disp_.update())
618                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
619 }
620
621
622 void GuiCompleter::hidePopup()
623 {
624         Cursor cur = gui_->bufferView().cursor();
625         cur.updateFlags(Update::None);
626         
627         hidePopup(cur);
628         
629         // redraw if needed
630         if (cur.disp_.update())
631                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
632 }
633
634
635 void GuiCompleter::hideInline()
636 {
637         Cursor cur = gui_->bufferView().cursor();
638         cur.updateFlags(Update::None);
639         
640         hideInline(cur);
641         
642         // redraw if needed
643         if (cur.disp_.update())
644                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
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.updateFlags(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.recordUndo();
688
689         // If completion is active, at least complete by one character
690         docstring prefix = cur.inset().completionPrefix(cur);
691         docstring completion = qstring_to_ucs4(currentCompletion());
692         if (completion.size() <= prefix.size()) {
693                 // finalize completion
694                 cur.inset().insertCompletion(cur, docstring(), true);
695                 
696                 // hide popup and inline completion
697                 hidePopup(cur);
698                 hideInline(cur);
699                 updateVisibility(false, false);
700                 return;
701         }
702         docstring nextchar = completion.substr(prefix.size(), 1);
703         if (!cur.inset().insertCompletion(cur, nextchar, false))
704                 return;
705         updatePrefix(cur);
706
707         // try to complete as far as it is unique
708         docstring longestCompletion = longestUniqueCompletion();
709         prefix = cur.inset().completionPrefix(cur);
710         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
711         cur.inset().insertCompletion(cur, postfix, false);
712         old_cursor_ = bv->cursor();
713         updatePrefix(cur);
714
715         // show popup without delay because the completion was not unique
716         if (lyxrc.completion_popup_after_complete
717             && !popupVisible()
718             && popup()->model()->rowCount() > 1)
719                 popup_timer_.start(0);
720
721         // redraw if needed
722         if (cur.disp_.update())
723                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
724 }
725
726
727 QString GuiCompleter::currentCompletion() const
728 {
729         if (!popup()->selectionModel()->hasSelection())
730                 return QString();
731
732         // Not sure if this is bug in Qt: currentIndex() always 
733         // return the first element in the list.
734         QModelIndex idx = popup()->currentIndex();
735         return popup()->model()->data(idx, Qt::EditRole).toString();
736 }
737
738
739 void GuiCompleter::setCurrentCompletion(QString const & s)
740 {       
741         QAbstractItemModel const & model = *popup()->model();
742         size_t n = model.rowCount();
743         if (n == 0)
744                 return;
745
746         // select the first if s is empty
747         if (s.length() == 0) {
748                 updateLock_++;
749                 popup()->setCurrentIndex(model.index(0, 0));
750                 updateLock_--;
751                 return;
752         }
753
754         // find old selection in model
755         size_t i;
756         if (modelSorting() == QCompleter::UnsortedModel) {
757                 // In unsorted models, iterate through list until the s is found
758                 for (i = 0; i < n; ++i) {
759                         QString const & is
760                         = model.data(model.index(i, 0), Qt::EditRole).toString();
761                         if (is == s)
762                                 break;
763                 }
764         } else {
765                 // In sorted models, do binary search for s.
766                 int l = 0;
767                 int r = n - 1;
768                 while (r >= l && l < int(n)) {
769                         size_t mid = (r + l) / 2;
770                         QString const & mids
771                         = model.data(model.index(mid, 0),
772                                      Qt::EditRole).toString();
773
774                         // left or right?
775                         // FIXME: is this really the same order that the docstring
776                         // from the CompletionList has?
777                         int c = s.compare(mids, Qt::CaseSensitive);
778                         if (c == 0) {
779                                 l = mid;
780                                 break;
781                         } else if (l == r) {
782                                 l = n;
783                                 break;
784                         } else if (c > 0)
785                                 // middle is not far enough
786                                 l = mid + 1;
787                         else
788                                 // middle is too far
789                                 r = mid - 1;
790                 }
791
792                 // loop was left without finding anything
793                 if (r < l)
794                         i = n;
795                 else
796                         i = l;
797                 LASSERT(i <= n, /**/);
798         }
799
800         // select the first if none was found
801         if (i == n)
802                 i = 0;
803
804         updateLock_++;
805         popup()->setCurrentIndex(model.index(i, 0));
806         updateLock_--;
807 }
808
809
810 size_t commonPrefix(QString const & s1, QString const & s2)
811 {
812         // find common prefix
813         size_t j;
814         size_t n1 = s1.length();
815         size_t n2 = s2.length();
816         for (j = 0; j < n1 && j < n2; ++j) {
817                 if (s1.at(j) != s2.at(j))
818                         break;
819         }
820         return j;
821 }
822
823
824 docstring GuiCompleter::longestUniqueCompletion() const
825 {
826         QAbstractItemModel const & model = *popup()->model();
827         size_t n = model.rowCount();
828         if (n == 0)
829                 return docstring();
830         QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
831
832         if (modelSorting() == QCompleter::UnsortedModel) {
833                 // For unsorted model we cannot do more than iteration.
834                 // Iterate through the completions and cut off where s differs
835                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
836                         QString const & is
837                         = model.data(model.index(i, 0), Qt::EditRole).toString();
838
839                         s = s.left(commonPrefix(is, s));
840                 }
841         } else {
842                 // For sorted models we can do binary search multiple times,
843                 // each time to find the first string which has s not as prefix.
844                 size_t i = 0;
845                 while (i < n && s.length() > 0) {
846                         // find first string that does not have s as prefix
847                         // via binary search in [i,n-1]
848                         size_t r = n - 1;
849                         do {
850                                 // get common prefix with the middle string
851                                 size_t mid = (r + i) / 2;
852                                 QString const & mids
853                                 = model.data(model.index(mid, 0), 
854                                         Qt::EditRole).toString();
855                                 size_t oldLen = s.length();
856                                 size_t len = commonPrefix(mids, s);
857                                 s = s.left(len);
858
859                                 // left or right?
860                                 if (oldLen == len) {
861                                         // middle is not far enough
862                                         i = mid + 1;
863                                 } else {
864                                         // middle is maybe too far
865                                         r = mid;
866                                 }
867                         } while (r - i > 0 && i < n);
868                 }
869         }
870
871         return qstring_to_ucs4(s);
872 }
873
874
875 void GuiCompleter::popupActivated(const QString & completion)
876 {
877         Cursor cur = gui_->bufferView().cursor();
878         cur.updateFlags(Update::None);
879         
880         cur.recordUndo();
881
882         docstring prefix = cur.inset().completionPrefix(cur);
883         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
884         cur.inset().insertCompletion(cur, postfix, true);
885         hidePopup(cur);
886         hideInline(cur);
887         
888         if (cur.disp_.update())
889                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
890 }
891
892
893 void GuiCompleter::popupHighlighted(const QString & completion)
894 {
895         if (updateLock_ > 0)
896                 return;
897
898         Cursor cur = gui_->bufferView().cursor();
899         cur.updateFlags(Update::None);
900         
901         if (inlineVisible())
902                 updateInline(cur, completion);
903         
904         if (cur.disp_.update())
905                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
906 }
907
908 } // namespace frontend
909 } // namespace lyx
910
911 #include "moc_GuiCompleter.cpp"