]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
0576d2866b13c9174f8114395023f72ee852737e
[lyx.git] / src / frontends / qt4 / GuiCompleter.cpp
1 /**
2  * \file GuiCompleter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Stefan Schimanski
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiWorkArea.h"
14
15 #include "Buffer.h"
16 #include "BufferView.h"
17 #include "Cursor.h"
18 #include "Dimension.h"
19 #include "FuncRequest.h"
20 #include "GuiView.h"
21 #include "LyXFunc.h"
22 #include "LyXRC.h"
23 #include "Paragraph.h"
24 #include "version.h"
25
26 #include "support/debug.h"
27
28 #include <QApplication>
29 #include <QAbstractListModel>
30 #include <QHeaderView>
31 #include <QPainter>
32 #include <QPixmapCache>
33 #include <QScrollBar>
34 #include <QItemDelegate>
35 #include <QTreeView>
36 #include <QTimer>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42 namespace frontend {
43
44 class RtlItemDelegate : public QItemDelegate {
45 public:
46         explicit RtlItemDelegate(QObject * parent = 0)
47                 : QItemDelegate(parent) {}
48
49 protected:
50         virtual void drawDisplay(QPainter * painter,
51                 QStyleOptionViewItem const & option,
52                 QRect const & rect, QString const & text) const
53         {
54                 // FIXME: do this more elegantly
55                 docstring stltext = qstring_to_ucs4(text);
56                 reverse(stltext.begin(), stltext.end());
57                 QItemDelegate::drawDisplay(painter, option, rect, toqstr(stltext));
58         }
59 };
60
61
62 class PixmapItemDelegate : public QItemDelegate {
63 public:
64         explicit PixmapItemDelegate(QObject *parent = 0)
65         : QItemDelegate(parent) {}
66
67 protected:
68         void paint(QPainter *painter, const QStyleOptionViewItem &option,
69                    const QModelIndex &index) const
70         {
71                 QStyleOptionViewItem opt = setOptions(index, option);
72                 QVariant value = index.data(Qt::DisplayRole);
73                 QPixmap pixmap = qvariant_cast<QPixmap>(value);
74                 
75                 // draw
76                 painter->save();
77                 drawBackground(painter, opt, index);
78                 if (!pixmap.isNull()) {
79                         const QSize size = pixmap.size();
80                         painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
81                                 option.rect.top() + (option.rect.height() - size.height()) / 2,
82                                 pixmap);
83                 }
84                 drawFocus(painter, opt, option.rect);
85                 painter->restore();
86         }
87 };
88
89
90 class GuiCompletionModel : public QAbstractListModel {
91 public:
92         ///
93         GuiCompletionModel(QObject * parent,
94                 Inset::CompletionList const * l)
95                 : QAbstractListModel(parent), list_(l) {}
96         ///
97         ~GuiCompletionModel()
98                 { delete list_; }
99         ///
100         int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
101         {
102                 return 2;
103         }
104         ///
105         int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
106         {
107                 if (list_ == 0)
108                         return 0;
109                 else
110                         return list_->size();
111         }
112
113         ///
114         QVariant data(const QModelIndex & index, int role) const
115         {
116                 if (list_ == 0)
117                         return QVariant();
118
119                 if (index.row() < 0 || index.row() >= rowCount())
120                         return QVariant();
121
122                 if (role != Qt::DisplayRole && role != Qt::EditRole)
123                     return QVariant();
124                     
125                 if (index.column() == 0)
126                         return toqstr(list_->data(index.row()));
127                 else if (index.column() == 1) {
128                         // get icon from cache
129                         QPixmap scaled;
130                         QString const name = ":" + toqstr(list_->icon(index.row()));
131                         if (!QPixmapCache::find("completion" + name, scaled)) {
132                                 // load icon from disk
133                                 QPixmap p = QPixmap(name);
134                                 if (!p.isNull()) {
135                                         // scale it to 16x16 or smaller
136                                         scaled
137                                         = p.scaled(min(16, p.width()), min(16, p.height()), 
138                                                 Qt::KeepAspectRatio, Qt::SmoothTransformation);
139                                 }
140
141                                 QPixmapCache::insert("completion" + name, scaled);
142                         }
143                         return scaled;
144                 }
145                 return QVariant();
146         }
147
148 private:
149         ///
150         Inset::CompletionList const * list_;
151 };
152
153
154 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
155         : QCompleter(parent), gui_(gui), updateLock_(0),
156           inlineVisible_(false)
157 {
158         // Setup the completion popup
159         setModel(new GuiCompletionModel(this, 0));
160         setCompletionMode(QCompleter::PopupCompletion);
161         setWidget(gui_);
162         
163         // create the popup
164         QTreeView *listView = new QTreeView;
165         listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
166         listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
167         listView->setSelectionBehavior(QAbstractItemView::SelectRows);
168         listView->setSelectionMode(QAbstractItemView::SingleSelection);
169         listView->header()->hide();
170         listView->setIndentation(0);
171         setPopup(listView);
172         popup()->setItemDelegateForColumn(1, new PixmapItemDelegate(this));
173
174         // create timeout timers
175         popup_timer_.setSingleShot(true);
176         inline_timer_.setSingleShot(true);
177         connect(this, SIGNAL(highlighted(const QString &)),
178                 this, SLOT(popupHighlighted(const QString &)));
179         connect(this, SIGNAL(activated(const QString &)),
180                 this, SLOT(popupActivated(const QString &)));
181         connect(&popup_timer_, SIGNAL(timeout()),
182                 this, SLOT(showPopup()));
183         connect(&inline_timer_, SIGNAL(timeout()),
184                 this, SLOT(showInline()));
185 }
186
187
188 GuiCompleter::~GuiCompleter()
189 {
190         popup()->hide();
191 }
192
193
194 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
195 {
196         // hijack back the tab key from the popup
197         // (which stole it from the workspace before)
198         if (e->type() == QEvent::KeyPress && popupVisible()) {
199                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
200                 switch (ke->key()) {
201                 case Qt::Key_Tab:
202                         tab();
203                         ke->accept();
204                         return true;
205                 default: break;
206                 }
207         }
208         
209         return QCompleter::eventFilter(watched, e);
210 }
211
212
213 bool GuiCompleter::popupPossible(Cursor const & cur) const
214 {
215         return QApplication::activeWindow()
216                 && gui_->hasFocus()
217                 && cur.inset().completionSupported(cur);
218 }
219
220
221 bool GuiCompleter::inlinePossible(Cursor const & cur) const
222 {
223         return cur.inset().inlineCompletionSupported(cur);
224 }
225
226
227 bool GuiCompleter::popupVisible() const
228 {
229         return popup()->isVisible();
230 }
231
232
233 bool GuiCompleter::inlineVisible() const
234 {
235         // In fact using BufferView::inlineCompletionPos.empty() should be
236         // here. But unfortunately this information is not good enough
237         // because destructive operations like backspace might invalidate
238         // inlineCompletionPos. But then the completion should stay visible
239         // (i.e. reshown on the next update). Hence be keep this information
240         // in the inlineVisible_ variable.
241         return inlineVisible_;
242 }
243
244
245 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
246 {
247         // parameters which affect the completion
248         bool moved = cur != old_cursor_;
249         if (moved)
250                 old_cursor_ = cur;
251
252         bool possiblePopupState = popupPossible(cur) && cursorInView;
253         bool possibleInlineState = inlinePossible(cur) && cursorInView;
254
255         // we moved or popup state is not ok for popup?
256         if ((moved && !keep) || !possiblePopupState) {
257                 // stop an old completion timer
258                 if (popup_timer_.isActive())
259                         popup_timer_.stop();
260
261                 // hide old popup
262                 if (popupVisible())
263                         popup()->hide();
264         }
265
266         // we moved or inline state is not ok for inline completion?
267         if ((moved && !keep) || !possibleInlineState) {
268                 // stop an old completion timer
269                 if (inline_timer_.isActive())
270                         inline_timer_.stop();
271
272                 // hide old inline completion
273                 if (inlineVisible()) {
274                         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
275                         inlineVisible_ = false;
276                 }
277         }
278
279         // we inserted something and are in a possible popup state?
280         if (!popupVisible() && possiblePopupState && start
281                 && cur.inset().automaticPopupCompletion())
282                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
283
284         // we inserted something and are in a possible inline completion state?
285         if (!inlineVisible() && possibleInlineState && start
286                 && cur.inset().automaticInlineCompletion())
287                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
288
289         // update prefix if popup is visible or if it will be visible soon
290         if (popupVisible() || inlineVisible()
291             || popup_timer_.isActive() || inline_timer_.isActive())
292                 updatePrefix(cur);
293 }
294
295
296 void GuiCompleter::updateVisibility(bool start, bool keep)
297 {
298         Cursor cur = gui_->bufferView().cursor();
299         cur.updateFlags(Update::None);
300         
301         updateVisibility(cur, start, keep);
302         
303         if (cur.disp_.update())
304                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
305 }
306
307
308 void GuiCompleter::updatePrefix(Cursor & cur)
309 {
310         // get new prefix. Do nothing if unchanged
311         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
312         if (newPrefix == completionPrefix())
313                 return;
314         
315         // value which should be kept selected
316         QString old = currentCompletion();
317         if (old.length() == 0)
318                 old = last_selection_;
319         
320         // update completer to new prefix
321         setCompletionPrefix(newPrefix);
322         
323         // update popup because its size might have changed
324         if (popupVisible())
325                 updatePopup(cur);
326
327         // restore old selection
328         setCurrentCompletion(old);
329         
330         // if popup is not empty, the new selection will
331         // be our last valid one
332         QString const & s = currentCompletion();
333         if (s.length() > 0)
334                 last_selection_ = s;
335         else
336                 last_selection_ = old;
337         
338         // update inline completion because the default
339         // completion string might have changed
340         if (inlineVisible())
341                 updateInline(cur, s);
342 }
343
344
345 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
346 {
347         if (!cur.inset().inlineCompletionSupported(cur))
348                 return;
349         
350         // compute postfix
351         docstring prefix = cur.inset().completionPrefix(cur);
352         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
353         
354         // shorten it if necessary
355         if (lyxrc.completion_inline_dots != -1
356             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
357                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
358
359         // set inline completion at cursor position
360         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
361         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
362         inlineVisible_ = true;
363 }
364
365
366 void GuiCompleter::updatePopup(Cursor & cur)
367 {
368         if (!cur.inset().completionSupported(cur))
369                 return;
370         
371         if (completionCount() == 0)
372                 return;
373         
374         // get dimensions of completion prefix
375         Dimension dim;
376         int x;
377         int y;
378         cur.inset().completionPosAndDim(cur, x, y, dim);
379         
380         // and calculate the rect of the popup
381         QRect rect;
382         if (popup()->layoutDirection() == Qt::RightToLeft)
383                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
384         else
385                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
386         
387         // show/update popup
388         complete(rect);
389         QTreeView * p = static_cast<QTreeView *>(popup());
390         p->setColumnWidth(0, popup()->width() - 22 - p->verticalScrollBar()->width());
391 }
392
393
394 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
395 {
396         // value which should be kept selected
397         QString old = currentCompletion();
398         if (old.length() == 0)
399                 old = last_selection_;
400
401         // set whether rtl
402         bool rtl = false;
403         if (cur.inTexted()) {
404                 Paragraph const & par = cur.paragraph();
405                 Font const font =
406                 par.getFontSettings(cur.bv().buffer().params(), cur.pos());
407                 rtl = font.isVisibleRightToLeft();
408         }
409         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
410
411         // turn the direction of the strings in the popup.
412         // Qt does not do that itself.
413         popup()->setItemDelegateForColumn(0, rtl ? new RtlItemDelegate : 0);
414
415         // set new model
416         Inset::CompletionList const * list
417         = cur.inset().createCompletionList(cur);
418         setModel(new GuiCompletionModel(this, list));
419
420         // show popup
421         if (popupUpdate)
422                 updatePopup(cur);
423
424         // restore old selection
425         setCurrentCompletion(old);
426         
427         // if popup is not empty, the new selection will
428         // be our last valid one
429         QString const & s = currentCompletion();
430         if (s.length() > 0)
431                 last_selection_ = s;
432         else
433                 last_selection_ = old;
434         
435         // show inline completion
436         if (inlineUpdate)
437                 updateInline(cur, currentCompletion());
438 }
439
440
441 void GuiCompleter::showPopup(Cursor & cur)
442 {
443         if (!popupPossible(cur))
444                 return;
445         
446         updateModel(cur, true, inlineVisible());
447         updatePrefix(cur);
448 }
449         
450
451 void GuiCompleter::showInline(Cursor & cur)
452 {
453         if (!inlinePossible(cur))
454                 return;
455         
456         updateModel(cur, popupVisible(), true);
457         updatePrefix(cur);
458 }
459
460
461 void GuiCompleter::showPopup()
462 {
463         Cursor cur = gui_->bufferView().cursor();
464         cur.updateFlags(Update::None);
465         
466         showPopup(cur);
467
468         // redraw if needed
469         if (cur.disp_.update())
470                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
471 }
472
473
474 void GuiCompleter::showInline()
475 {
476         Cursor cur = gui_->bufferView().cursor();
477         cur.updateFlags(Update::None);
478         
479         showInline(cur);
480
481         // redraw if needed
482         if (cur.disp_.update())
483                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
484 }
485
486
487 void GuiCompleter::activate()
488 {
489         if (!popupVisible() && !inlineVisible())
490                 return;
491
492         // Complete with current selection in the popup.
493         QString s = currentCompletion();
494         popup()->hide();
495         popupActivated(s);
496 }
497
498
499 void GuiCompleter::tab()
500 {
501         BufferView * bv = &gui_->bufferView();
502         Cursor cur = bv->cursor();
503         cur.updateFlags(Update::None);
504         
505         // check that inline completion is active
506         if (!inlineVisible()) {
507                 // try to activate the inline completion
508                 if (cur.inset().inlineCompletionSupported(cur)) {
509                         showInline();
510                         
511                         // show popup without delay because the completion was not unique
512                         if (lyxrc.completion_popup_after_complete
513                             && !popupVisible()
514                             && popup()->model()->rowCount() > 1)
515                                 popup_timer_.start(0);
516
517                         return;
518                 }
519                 // or try popup
520                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
521                         showPopup();
522                         return;
523                 }
524                 
525                 return;
526         }
527         
528         // If completion is active, at least complete by one character
529         docstring prefix = cur.inset().completionPrefix(cur);
530         docstring completion = from_utf8(fromqstr(currentCompletion()));
531         if (completion.size() <= prefix.size()) {
532                 // finalize completion
533                 cur.inset().insertCompletion(cur, docstring(), true);
534                 
535                 // hide popup and inline completion
536                 popup()->hide();
537                 gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
538                 inlineVisible_ = false;
539                 updateVisibility(false, false);
540                 return;
541         }
542         docstring nextchar = completion.substr(prefix.size(), 1);
543         if (!cur.inset().insertCompletion(cur, nextchar, false))
544                 return;
545         updatePrefix(cur);
546
547         // try to complete as far as it is unique
548         docstring longestCompletion = longestUniqueCompletion();
549         prefix = cur.inset().completionPrefix(cur);
550         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
551         cur.inset().insertCompletion(cur, postfix, false);
552         old_cursor_ = bv->cursor();
553         updatePrefix(cur);
554
555         // show popup without delay because the completion was not unique
556         if (lyxrc.completion_popup_after_complete
557             && !popupVisible()
558             && popup()->model()->rowCount() > 1)
559                 popup_timer_.start(0);
560
561         // redraw if needed
562         if (cur.disp_.update())
563                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
564 }
565
566
567 QString GuiCompleter::currentCompletion() const
568 {
569         if (!popup()->selectionModel()->hasSelection())
570                 return QString();
571
572         // Not sure if this is bug in Qt: currentIndex() always 
573         // return the first element in the list.
574         QModelIndex idx = popup()->currentIndex();
575         return popup()->model()->data(idx, Qt::EditRole).toString();
576 }
577
578
579 void GuiCompleter::setCurrentCompletion(QString const & s)
580 {       
581         QAbstractItemModel const & model = *popup()->model();
582         size_t n = model.rowCount();
583         if (n == 0)
584                 return;
585
586         // select the first if s is empty
587         if (s.length() == 0) {
588                 updateLock_++;
589                 popup()->setCurrentIndex(model.index(0, 0));
590                 updateLock_--;
591                 return;
592         }
593
594         // iterate through list until the s is found
595         // FIXME: there must be a better way than this iteration
596         size_t i;
597         for (i = 0; i < n; ++i) {
598                 QString const & is
599                 = model.data(model.index(i, 0), Qt::EditRole).toString();
600                 if (is == s)
601                         break;
602         }
603
604         // select the first if none was found
605         if (i == n)
606                 i = 0;
607
608         updateLock_++;
609         popup()->setCurrentIndex(model.index(i, 0));
610         updateLock_--;
611 }
612
613
614 docstring GuiCompleter::longestUniqueCompletion() const {
615         QAbstractItemModel const & model = *popup()->model();
616         QString s = currentCompletion();
617         size_t n = model.rowCount();
618
619         // iterate through the completions and cut off where s differs
620         for (size_t i = 0; i < n && s.length() > 0; ++i) {
621                 QString const & is
622                 = model.data(model.index(i, 0), Qt::EditRole).toString();
623
624                 // find common prefix
625                 size_t j;
626                 size_t isn = is.length();
627                 size_t sn = s.length();
628                 for (j = 0; j < isn && j < sn; ++j) {
629                         if (s.at(j) != is.at(j))
630                                 break;
631                 }
632                 s = s.left(j);
633         }
634
635         return from_utf8(fromqstr(s));
636 }
637
638
639 void GuiCompleter::popupActivated(const QString & completion)
640 {
641         Cursor cur = gui_->bufferView().cursor();
642         cur.updateFlags(Update::None);
643         
644         docstring prefix = cur.inset().completionPrefix(cur);
645         docstring postfix = from_utf8(fromqstr(completion.mid(prefix.length())));
646         cur.inset().insertCompletion(cur, postfix, true);
647         updateVisibility(cur, false);
648         
649         if (cur.disp_.update())
650                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
651 }
652
653
654 void GuiCompleter::popupHighlighted(const QString & completion)
655 {
656         if (updateLock_ > 0)
657                 return;
658
659         Cursor cur = gui_->bufferView().cursor();
660         cur.updateFlags(Update::None);
661         
662         updateInline(cur, completion);
663         
664         if (cur.disp_.update())
665                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
666 }
667
668 } // namespace frontend
669 } // namespace lyx
670
671 #include "GuiCompleter_moc.cpp"