]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Implement down key press in FancyLineEdit
[lyx.git] / src / frontends / qt4 / GuiCitation.cpp
1
2 /**
3  * \file GuiCitation.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Angus Leeming
8  * \author Kalle Dalheimer
9  * \author Abdelrazak Younes
10  * \author Richard Heck
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiCitation.h"
18
19 #include "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "LyXToolBox.h"
22 #include "qt_helpers.h"
23
24 #include "Buffer.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "TextClass.h"
29 #include "FuncRequest.h"
30
31 #include "insets/InsetCommand.h"
32
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include <QCloseEvent>
39 #include <QMenu>
40 #include <QSettings>
41 #include <QShowEvent>
42 #include <QStandardItemModel>
43 #include <QVariant>
44
45 #include <vector>
46 #include <string>
47
48 #undef KeyPress
49
50 #include "support/regex.h"
51
52 #include <algorithm>
53 #include <string>
54 #include <vector>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60 namespace frontend {
61
62 // FIXME THREAD
63 // I am guessing that it would not hurt to make these private members.
64 static vector<string> citeCmds_;
65 static vector<CitationStyle> citeStyles_;
66
67
68 template<typename String>
69 static QStringList to_qstring_list(vector<String> const & v)
70 {
71         QStringList qlist;
72
73         for (size_t i = 0; i != v.size(); ++i) {
74                 if (v[i].empty())
75                         continue;
76                 qlist.append(lyx::toqstr(v[i]));
77         }
78         return qlist;
79 }
80
81
82 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 {
84         vector<lyx::docstring> v;
85         for (int i = 0; i != qlist.size(); ++i) {
86                 if (qlist[i].isEmpty())
87                         continue;
88                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
89         }
90         return v;
91 }
92
93
94 GuiCitation::GuiCitation(GuiView & lv)
95         : DialogView(lv, "citation", qt_("Citation")),
96           style_(0), params_(insetCode("citation"))
97 {
98         setupUi(this);
99
100         // The filter bar
101         filter_ = new FancyLineEdit(this);
102         filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
103         filter_->setButtonVisible(FancyLineEdit::Right, true);
104         filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
105         filter_->setAutoHideButton(FancyLineEdit::Right, true);
106         filter_->setPlaceholderText(qt_("All avail. citations"));
107
108         filterBarL->addWidget(filter_, 0);
109         findKeysLA->setBuddy(filter_);
110
111         // Add search options as button menu
112         regexp_ = new QAction(qt_("Regular e&xpression"), this);
113         regexp_->setCheckable(true);
114         casesense_ = new QAction(qt_("Case se&nsitive"), this);
115         casesense_->setCheckable(true);
116         instant_ = new QAction(qt_("Search as you &type"), this);
117         instant_->setCheckable(true);
118         instant_->setChecked(true);
119
120         QMenu * searchOpts = new QMenu(this);
121         searchOpts->addAction(regexp_);
122         searchOpts->addAction(casesense_);
123         searchOpts->addAction(instant_);
124         searchOptionsPB->setMenu(searchOpts);
125
126         connect(citationStyleCO, SIGNAL(activated(int)),
127                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
128         connect(starredCB, SIGNAL(clicked()),
129                 this, SLOT(updateStyles()));
130         connect(literalCB, SIGNAL(clicked()),
131                 this, SLOT(changed()));
132         connect(forceuppercaseCB, SIGNAL(clicked()),
133                 this, SLOT(updateStyles()));
134         connect(textBeforeED, SIGNAL(textChanged(QString)),
135                 this, SLOT(updateStyles()));
136         connect(textAfterED, SIGNAL(textChanged(QString)),
137                 this, SLOT(updateStyles()));
138         connect(textBeforeED, SIGNAL(returnPressed()),
139                 this, SLOT(on_okPB_clicked()));
140         connect(textAfterED, SIGNAL(returnPressed()),
141                 this, SLOT(on_okPB_clicked()));
142
143         selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
144                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
145         connect(selectionManager, SIGNAL(selectionChanged()),
146                 this, SLOT(setCitedKeys()));
147         connect(selectionManager, SIGNAL(updateHook()),
148                 this, SLOT(updateControls()));
149         connect(selectionManager, SIGNAL(okHook()),
150                 this, SLOT(on_okPB_clicked()));
151
152         connect(filter_, SIGNAL(rightButtonClicked()),
153                 this, SLOT(resetFilter()));
154         connect(filter_, SIGNAL(textEdited(QString)),
155                 this, SLOT(filterChanged(QString)));
156         connect(filter_, SIGNAL(returnPressed()),
157                 this, SLOT(filterPressed()));
158 #if (QT_VERSION < 0x050000)
159         connect(filter_, SIGNAL(downPressed()),
160                 availableLV, SLOT(setFocus()));
161 #else
162         connect(filter_, &FancyLineEdit::downPressed,
163                 availableLV, [=](){ focusAndHighlight(availableLV); });
164 #endif
165         connect(regexp_, SIGNAL(triggered()),
166                 this, SLOT(regexChanged()));
167         connect(casesense_, SIGNAL(triggered()),
168                 this, SLOT(caseChanged()));
169         connect(instant_, SIGNAL(triggered(bool)),
170                 this, SLOT(instantChanged(bool)));
171
172 #if (QT_VERSION < 0x050000)
173         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
174 #else
175         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
176 #endif
177
178         setFocusProxy(filter_);
179 }
180
181
182 void GuiCitation::closeEvent(QCloseEvent * e)
183 {
184         clearSelection();
185         DialogView::closeEvent(e);
186 }
187
188
189 void GuiCitation::applyView()
190 {
191         int const choice = max(0, citationStyleCO->currentIndex());
192         style_ = choice;
193         bool const full  = starredCB->isChecked();
194         bool const force = forceuppercaseCB->isChecked();
195
196         QString const before = textBeforeED->text();
197         QString const after = textAfterED->text();
198
199         applyParams(choice, full, force, before, after);
200 }
201
202
203 void GuiCitation::showEvent(QShowEvent * e)
204 {
205         filter_->clear();
206         availableLV->setFocus();
207         DialogView::showEvent(e);
208 }
209
210
211 void GuiCitation::on_okPB_clicked()
212 {
213         applyView();
214         clearSelection();
215         hide();
216 }
217
218
219 void GuiCitation::on_cancelPB_clicked()
220 {
221         clearSelection();
222         hide();
223 }
224
225
226 void GuiCitation::on_applyPB_clicked()
227 {
228         applyView();
229 }
230
231
232 void GuiCitation::on_restorePB_clicked()
233 {
234         init();
235         updateFilterHint();
236 }
237
238
239 void GuiCitation::updateControls()
240 {
241         BiblioInfo const & bi = bibInfo();
242         updateControls(bi);
243 }
244
245
246 // The main point of separating this out is that the fill*() methods
247 // called in update() do not need to be called for INTERNAL updates,
248 // such as when addPB is pressed, as the list of fields, entries, etc,
249 // will not have changed.
250 void GuiCitation::updateControls(BiblioInfo const & bi)
251 {
252         QModelIndex idx = selectionManager->getSelectedIndex(1);
253         updateInfo(bi, idx);
254         int i = citationStyleCO->currentIndex();
255         if (i == -1)
256                 i = 0;
257         updateFormatting(citeStyles_[i]);
258         selectionManager->update();
259 }
260
261
262 void GuiCitation::updateFormatting(CitationStyle currentStyle)
263 {
264         BufferParams const bp = documentBuffer().params();
265         bool const force = currentStyle.forceUpperCase;
266         bool const starred = currentStyle.hasStarredVersion;
267         bool const full = starred && bp.fullAuthorList();
268         bool const textbefore = currentStyle.textBefore;
269         bool const textafter = currentStyle.textAfter;
270
271         int const rows = selectedLV->model()->rowCount();
272
273         bool const qualified = currentStyle.hasQualifiedList
274                 && (rows > 1
275                     || !params_["pretextlist"].empty()
276                     || !params_["posttextlist"].empty());
277         selectedLV->horizontalHeader()->setVisible(qualified);
278         selectedLV->setColumnHidden(0, !qualified);
279         selectedLV->setColumnHidden(2, !qualified);
280         bool const haveSelection = rows > 0;
281         if (qualified) {
282                 textBeforeLA->setText(qt_("General text befo&re:"));
283                 textAfterLA->setText(qt_("General &text after:"));
284                 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
285                                              "For text that precedes individual items, "
286                                              "double-click on the respective entry above."));
287                 textAfterLA->setToolTip(qt_("General &text after:"));
288                 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
289                                              "For text that follows individual items, "
290                                              "double-click on the respective entry above."));
291         } else {
292                 textBeforeLA->setText(qt_("Text befo&re:"));
293                 if (textbefore && haveSelection)
294                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
295                 else
296                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
297                                                      "if the current citation style supports this."));
298                 textAfterLA->setText(qt_("&Text after:"));
299                 if (textafter && haveSelection)
300                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
301                 else
302                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
303                                                     "if the current citation style supports this."));
304         }
305
306         forceuppercaseCB->setEnabled(force && haveSelection);
307         if (force && haveSelection)
308                 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\").");
309         else
310                 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
311                                              "if the current citation style supports this.");
312         starredCB->setEnabled(full && haveSelection);
313         textBeforeED->setEnabled(textbefore && haveSelection);
314         textBeforeLA->setEnabled(textbefore && haveSelection);
315         textAfterED->setEnabled(textafter && haveSelection);
316         textAfterLA->setEnabled(textafter && haveSelection);
317         literalCB->setEnabled(textbefore || textafter);
318         citationStyleCO->setEnabled(haveSelection);
319         citationStyleLA->setEnabled(haveSelection);
320
321         // Check if we have a custom string/tooltip for the starred version
322         if (starred && !currentStyle.stardesc.empty()) {
323                 string val =
324                         bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
325                 docstring guistring;
326                 if (!val.empty()) {
327                         guistring = translateIfPossible(from_utf8(val));
328                         starredCB->setText(toqstr(guistring));
329                         starredCB->setEnabled(haveSelection);
330                 }
331                 if (!currentStyle.startooltip.empty()) {
332                         val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
333                                                               currentStyle.startooltip);
334                         if (!val.empty())
335                                 guistring = translateIfPossible(from_utf8(val));
336                 }
337                 // Tooltip might also be empty
338                 starredCB->setToolTip(toqstr(guistring));
339         } else {
340                 // This is the default meaning of the starred commands
341                 starredCB->setText(qt_("All aut&hors"));
342                 if (full && haveSelection)
343                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
344                 else
345                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
346                                                   "if the current citation style supports this."));
347         }
348 }
349
350
351 // Update the styles for the style combo, citationStyleCO, and mark the
352 // settings as changed. Called upon changing the cited keys (including
353 // merely reordering the keys) or editing the text before/after fields.
354 void GuiCitation::updateStyles()
355 {
356         BiblioInfo const & bi = bibInfo();
357         updateStyles(bi);
358         changed();
359 }
360
361
362 // Update the styles for the style combo, citationStyleCO.
363 void GuiCitation::updateStyles(BiblioInfo const & bi)
364 {
365         QStringList selected_keys = selectedKeys();
366         int curr = selectedLV->model()->rowCount() - 1;
367
368         if (curr < 0 || selected_keys.empty()) {
369                 citationStyleCO->clear();
370                 citationStyleCO->setEnabled(false);
371                 citationStyleLA->setEnabled(false);
372                 return;
373         }
374
375         static const size_t max_length = 80;
376         QStringList sty = citationStyles(bi, max_length);
377
378         if (sty.isEmpty()) {
379                 // some error
380                 citationStyleCO->setEnabled(false);
381                 citationStyleLA->setEnabled(false);
382                 citationStyleCO->clear();
383                 return;
384         }
385
386         citationStyleCO->blockSignals(true);
387
388         // save old index
389         int const curindex = citationStyleCO->currentIndex();
390         int const oldIndex = (curindex < 0) ? style_ : curindex;
391         citationStyleCO->clear();
392         citationStyleCO->insertItems(0, sty);
393         citationStyleCO->setEnabled(true);
394         citationStyleLA->setEnabled(true);
395         // restore old index
396         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
397                 citationStyleCO->setCurrentIndex(oldIndex);
398
399         citationStyleCO->blockSignals(false);
400 }
401
402
403 void GuiCitation::fillFields(BiblioInfo const & bi)
404 {
405         fieldsCO->blockSignals(true);
406         int const oldIndex = fieldsCO->currentIndex();
407         fieldsCO->clear();
408         QStringList const fields = to_qstring_list(bi.getFields());
409         fieldsCO->insertItem(0, qt_("All fields"));
410         fieldsCO->insertItem(1, qt_("Keys"));
411         fieldsCO->insertItems(2, fields);
412         if (oldIndex != -1 && oldIndex < fieldsCO->count())
413                 fieldsCO->setCurrentIndex(oldIndex);
414         fieldsCO->blockSignals(false);
415 }
416
417
418 void GuiCitation::fillEntries(BiblioInfo const & bi)
419 {
420         entriesCO->blockSignals(true);
421         int const oldIndex = entriesCO->currentIndex();
422         entriesCO->clear();
423         QStringList const entries = to_qstring_list(bi.getEntries());
424         entriesCO->insertItem(0, qt_("All entry types"));
425         entriesCO->insertItems(1, entries);
426         if (oldIndex != -1 && oldIndex < entriesCO->count())
427                 entriesCO->setCurrentIndex(oldIndex);
428         entriesCO->blockSignals(false);
429 }
430
431
432 bool GuiCitation::isSelected(QModelIndex const & idx)
433 {
434         QString const str = idx.data().toString();
435         return selectedKeys().contains(str);
436 }
437
438
439 void GuiCitation::setButtons()
440 {
441         int const srows = selectedLV->model()->rowCount();
442         applyPB->setEnabled(srows > 0);
443         okPB->setEnabled(srows > 0);
444 }
445
446
447 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
448 {
449         if (!idx.isValid() || bi.empty()) {
450                 infoML->document()->clear();
451                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
452                 return;
453         }
454
455         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
456         CiteItem ci;
457         ci.richtext = true;
458         QString const keytxt = toqstr(
459                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
460         infoML->document()->setHtml(keytxt);
461 }
462
463
464 void GuiCitation::findText(QString const & text, bool reset)
465 {
466         //"All Fields" and "Keys" are the first two
467         int index = fieldsCO->currentIndex() - 2;
468         BiblioInfo const & bi = bibInfo();
469         vector<docstring> const & fields = bi.getFields();
470         docstring field;
471
472         if (index <= -1 || index >= int(fields.size()))
473                 //either "All Fields" or "Keys" or an invalid value
474                 field = from_ascii("");
475         else
476                 field = fields[index];
477
478         //Was it "Keys"?
479         bool const onlyKeys = index == -1;
480
481         //"All Entry Types" is first.
482         index = entriesCO->currentIndex() - 1;
483         vector<docstring> const & entries = bi.getEntries();
484         docstring entry_type;
485         if (index < 0 || index >= int(entries.size()))
486                 entry_type = from_ascii("");
487         else
488                 entry_type = entries[index];
489
490         bool const case_sentitive = casesense_->isChecked();
491         bool const reg_exp = regexp_->isChecked();
492
493         findKey(bi, text, onlyKeys, field, entry_type,
494                        case_sentitive, reg_exp, reset);
495         //FIXME
496         //It'd be nice to save and restore the current selection in
497         //availableLV. Currently, we get an automatic reset, since the
498         //model is reset.
499
500         updateControls(bi);
501 }
502
503
504 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
505 {
506         findText(filter_->text(), true);
507 }
508
509
510 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
511 {
512         findText(filter_->text(), true);
513 }
514
515
516 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
517 {
518         if (index >= 0 && index < citationStyleCO->count()) {
519                 vector<CitationStyle> const & styles = citeStyles_;
520                 updateFormatting(styles[index]);
521                 changed();
522         }
523 }
524
525
526 void GuiCitation::filterChanged(const QString & text)
527 {
528         if (!text.isEmpty()) {
529                 if (instant_->isChecked())
530                         findText(filter_->text());
531                 return;
532         }
533         findText(filter_->text());
534         filter_->setFocus();
535 }
536
537
538 void GuiCitation::filterPressed()
539 {
540         findText(filter_->text(), true);
541 }
542
543
544 void GuiCitation::resetFilter()
545 {
546         filter_->setText(QString());
547         findText(filter_->text(), true);
548 }
549
550
551 void GuiCitation::caseChanged()
552 {
553         findText(filter_->text());
554 }
555
556
557 void GuiCitation::regexChanged()
558 {
559         findText(filter_->text());
560 }
561
562
563 void GuiCitation::updateFilterHint()
564 {
565         QString const hint = instant_->isChecked() ?
566                 qt_("Enter string to filter the list of available citations") :
567                 qt_("Enter string to filter the list of available citations and press <Enter>");
568         filter_->setToolTip(hint);
569 }
570
571
572 void GuiCitation::instantChanged(bool checked)
573 {
574         if (checked)
575                 findText(filter_->text(), true);
576
577         updateFilterHint();
578 }
579
580
581 void GuiCitation::changed()
582 {
583         setButtons();
584 }
585
586
587 void GuiCitation::applyParams(int const choice, bool full, bool force,
588         QString before, QString after)
589 {
590         if (cited_keys_.isEmpty())
591                 return;
592
593         vector<CitationStyle> const & styles = citeStyles_;
594
595         CitationStyle cs = styles[choice];
596
597         if (!cs.textBefore)
598                 before.clear();
599         if (!cs.textAfter)
600                 after.clear();
601
602         cs.forceUpperCase &= force;
603         cs.hasStarredVersion &= full;
604         string const command = citationStyleToString(cs);
605
606         params_.setCmdName(command);
607         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
608         params_["before"] = qstring_to_ucs4(before);
609         params_["after"] = qstring_to_ucs4(after);
610         if (cs.hasQualifiedList) {
611                 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
612                 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
613         }
614         params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
615         dispatchParams();
616 }
617
618
619 void GuiCitation::clearSelection()
620 {
621         cited_keys_.clear();
622         setSelectedKeys(cited_keys_);
623 }
624
625
626 void GuiCitation::setSelectedKeys(QStringList const sl)
627 {
628         selected_model_.clear();
629         selected_model_.setColumnCount(3);
630         QStringList headers;
631         headers << qt_("Text before")
632                 << qt_("Cite key")
633                 << qt_("Text after");
634         selected_model_.setHorizontalHeaderLabels(headers);
635         selectedLV->setColumnHidden(0, true);
636         selectedLV->setColumnHidden(2, true);
637         selectedLV->verticalHeader()->setVisible(false);
638         selectedLV->horizontalHeader()->setVisible(false);
639         QStringList::const_iterator it  = sl.begin();
640         QStringList::const_iterator end = sl.end();
641         for (int i = 0; it != end; ++it, ++i) {
642                 QStandardItem * si = new QStandardItem();
643                 si->setData(*it);
644                 si->setText(*it);
645                 si->setToolTip(*it);
646                 si->setEditable(false);
647                 selected_model_.setItem(i, 1, si);
648         }
649 }
650
651
652 QStringList GuiCitation::selectedKeys()
653 {
654         QStringList res;
655         for (int i = 0; i != selected_model_.rowCount(); ++i) {
656                 QStandardItem const * item = selected_model_.item(i, 1);
657                 if (item)
658                         res.append(item->text());
659         }
660         return res;
661 }
662
663
664 void GuiCitation::setPreTexts(vector<docstring> const m)
665 {
666         for (docstring const & s: m) {
667                 QStandardItem * si = new QStandardItem();
668                 docstring key;
669                 docstring pre = split(s, key, ' ');
670                 si->setData(toqstr(pre));
671                 si->setText(toqstr(pre));
672                 QModelIndexList qmil =
673                                 selected_model_.match(selected_model_.index(0, 1),
674                                                      Qt::DisplayRole, toqstr(key), 1,
675                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
676                 if (!qmil.empty())
677                         selected_model_.setItem(qmil.front().row(), 0, si);
678         }
679 }
680
681
682 vector<docstring> GuiCitation::getPreTexts()
683 {
684         vector<docstring> res;
685         for (int i = 0; i != selected_model_.rowCount(); ++i) {
686                 QStandardItem const * key = selected_model_.item(i, 1);
687                 QStandardItem const * pre = selected_model_.item(i, 0);
688                 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
689                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
690         }
691         return res;
692 }
693
694
695 void GuiCitation::setPostTexts(vector<docstring> const m)
696 {
697         for (docstring const & s: m) {
698                 QStandardItem * si = new QStandardItem();
699                 docstring key;
700                 docstring post = split(s, key, ' ');
701                 si->setData(toqstr(post));
702                 si->setText(toqstr(post));
703                 QModelIndexList qmil =
704                                 selected_model_.match(selected_model_.index(0, 1),
705                                                      Qt::DisplayRole, toqstr(key), 1,
706                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
707                 if (!qmil.empty())
708                         selected_model_.setItem(qmil.front().row(), 2, si);
709         }
710 }
711
712
713 vector<docstring> GuiCitation::getPostTexts()
714 {
715         vector<docstring> res;
716         for (int i = 0; i != selected_model_.rowCount(); ++i) {
717                 QStandardItem const * key = selected_model_.item(i, 1);
718                 QStandardItem const * post = selected_model_.item(i, 2);
719                 if (key && post)
720                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
721         }
722         return res;
723 }
724
725
726 void GuiCitation::init()
727 {
728         // Make the list of all available bibliography keys
729         BiblioInfo const & bi = bibInfo();
730         all_keys_ = to_qstring_list(bi.getKeys());
731
732         available_model_.setStringList(all_keys_);
733
734         // Ditto for the keys cited in this inset
735         QString str = toqstr(params_["key"]);
736         if (str.isEmpty())
737                 cited_keys_.clear();
738         else
739                 cited_keys_ = str.split(",");
740         setSelectedKeys(cited_keys_);
741
742         // Initialize the drop downs
743         fillEntries(bi);
744         fillFields(bi);
745
746         // Initialize the citation formatting
747         string const & cmd = params_.getCmdName();
748         CitationStyle const cs =
749                 citationStyleFromString(cmd, documentBuffer().params());
750
751         forceuppercaseCB->setChecked(cs.forceUpperCase);
752         starredCB->setChecked(cs.hasStarredVersion &&
753                 documentBuffer().params().fullAuthorList());
754         textBeforeED->setText(toqstr(params_["before"]));
755         textAfterED->setText(toqstr(params_["after"]));
756         literalCB->setChecked(params_["literal"] == "true");
757
758         setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
759         setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
760
761         // Update the interface
762         updateControls(bi);
763         updateStyles(bi);
764         if (selected_model_.rowCount()) {
765                 selectedLV->blockSignals(true);
766                 selectedLV->setFocus();
767                 selectedLV->selectRow(0);
768                 selectedLV->blockSignals(false);
769
770                 // Find the citation style
771                 vector<string> const & cmds = citeCmds_;
772                 vector<string>::const_iterator cit =
773                         std::find(cmds.begin(), cmds.end(), cs.name);
774                 int i = 0;
775                 if (cit != cmds.end())
776                         i = int(cit - cmds.begin());
777
778                 // Set the style combo appropriately
779                 citationStyleCO->blockSignals(true);
780                 citationStyleCO->setCurrentIndex(i);
781                 citationStyleCO->blockSignals(false);
782                 updateFormatting(citeStyles_[i]);
783         } else
784                 availableLV->setFocus();
785
786         applyPB->setEnabled(false);
787         okPB->setEnabled(false);
788 }
789
790
791 void GuiCitation::findKey(BiblioInfo const & bi,
792         QString const & str, bool only_keys,
793         docstring field, docstring entry_type,
794         bool case_sensitive, bool reg_exp, bool reset)
795 {
796         // FIXME THREAD
797         // This should be moved to a class member.
798         // Used for optimisation: store last searched string.
799         static QString last_searched_string;
800         // Used to disable the above optimisation.
801         static bool last_case_sensitive;
802         static bool last_reg_exp;
803         // Reset last_searched_string in case of changed option.
804         if (last_case_sensitive != case_sensitive
805                 || last_reg_exp != reg_exp) {
806                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
807                 last_searched_string.clear();
808         }
809         // save option for next search.
810         last_case_sensitive = case_sensitive;
811         last_reg_exp = reg_exp;
812
813         Qt::CaseSensitivity qtcase = case_sensitive ?
814                         Qt::CaseSensitive: Qt::CaseInsensitive;
815         QStringList keys;
816         // If new string (str) contains the last searched one...
817         if (!reset &&
818                 !last_searched_string.isEmpty() &&
819                 str.size() > 1 &&
820                 str.contains(last_searched_string, qtcase))
821                 // ... then only search within already found list.
822                 keys = available_model_.stringList();
823         else
824                 // ... else search all keys.
825                 keys = all_keys_;
826         // save searched string for next search.
827         last_searched_string = str;
828
829         QStringList result;
830
831         // First, filter by entry_type, which will be faster than
832         // what follows, so we may get to do that on less.
833         vector<docstring> keyVector = to_docstring_vector(keys);
834         filterByEntryType(bi, keyVector, entry_type);
835
836         if (str.isEmpty())
837                 result = to_qstring_list(keyVector);
838         else
839                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
840                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
841
842         available_model_.setStringList(result);
843 }
844
845
846 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
847 {
848         vector<docstring> const keys = to_docstring_vector(cited_keys_);
849         vector<CitationStyle> styles = citeStyles_;
850         int ind = citationStyleCO->currentIndex();
851         if (ind == -1)
852                 ind = 0;
853         CitationStyle cs = styles[ind];
854         vector<docstring> pretexts = getPreTexts();
855         vector<docstring> posttexts = getPostTexts();
856         bool const qualified = cs.hasQualifiedList
857                 && (selectedLV->model()->rowCount() > 1
858                     || !pretexts.empty()
859                     || !posttexts.empty());
860         std::map<docstring, docstring> pres;
861         for (docstring const & s: pretexts) {
862                 docstring key;
863                 docstring val = split(s, key, ' ');
864                 pres[key] = val;
865         }
866         std::map<docstring, docstring> posts;
867         for (docstring const & s: posttexts) {
868                 docstring key;
869                 docstring val = split(s, key, ' ');
870                 posts[key] = val;
871         }
872         CiteItem ci;
873         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
874         ci.textAfter = qstring_to_ucs4(textAfterED->text());
875         ci.forceUpperCase = forceuppercaseCB->isChecked();
876         ci.Starred = starredCB->isChecked();
877         ci.context = CiteItem::Dialog;
878         ci.max_size = max_size;
879         ci.isQualified = qualified;
880         ci.pretexts = pres;
881         ci.posttexts = posts;
882         vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
883         return to_qstring_list(ret);
884 }
885
886
887 void GuiCitation::setCitedKeys()
888 {
889         cited_keys_ = selectedKeys();
890         updateStyles();
891 }
892
893
894 bool GuiCitation::initialiseParams(string const & data)
895 {
896         InsetCommand::string2params(data, params_);
897         citeCmds_ = documentBuffer().params().citeCommands();
898         citeStyles_ = documentBuffer().params().citeStyles();
899         init();
900         return true;
901 }
902
903
904 void GuiCitation::clearParams()
905 {
906         params_.clear();
907 }
908
909
910 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
911         vector<docstring> & keyVector, docstring entry_type)
912 {
913         if (entry_type.empty())
914                 return;
915
916         vector<docstring>::iterator it = keyVector.begin();
917         vector<docstring>::iterator end = keyVector.end();
918
919         vector<docstring> result;
920         for (; it != end; ++it) {
921                 docstring const key = *it;
922                 BiblioInfo::const_iterator cit = bi.find(key);
923                 if (cit == bi.end())
924                         continue;
925                 if (cit->second.entryType() == entry_type)
926                         result.push_back(key);
927         }
928         keyVector = result;
929 }
930
931
932 // Escape special chars.
933 // All characters are literals except: '.|*?+(){}[]^$\'
934 // These characters are literals when preceded by a "\", which is done here
935 // @todo: This function should be moved to support, and then the test in tests
936 //        should be moved there as well.
937 static docstring escape_special_chars(docstring const & expr)
938 {
939         // Search for all chars '.|*?+(){}[^$]\'
940         // Note that '[', ']', and '\' must be escaped.
941         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
942
943         // $& is an ECMAScript format expression that expands to all
944         // of the current match
945 #ifdef LYX_USE_STD_REGEX
946         // To prefix a matched expression with a single literal backslash, we
947         // need to escape it for the C++ compiler and use:
948         // FIXME: UNICODE
949         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
950 #else
951         // A backslash in the format string starts an escape sequence in boost.
952         // Thus, to prefix a matched expression with a single literal backslash,
953         // we need to give two backslashes to the regex engine, and escape both
954         // for the C++ compiler and use:
955         // FIXME: UNICODE
956         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
957 #endif
958 }
959
960
961 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
962         vector<docstring> const & keys_to_search, bool only_keys,
963         docstring const & search_expression, docstring field,
964         bool case_sensitive, bool regex)
965 {
966         vector<docstring> foundKeys;
967
968         docstring expr = trim(search_expression);
969         if (expr.empty())
970                 return foundKeys;
971
972         if (!regex)
973                 // We must escape special chars in the search_expr so that
974                 // it is treated as a simple string by lyx::regex.
975                 expr = escape_special_chars(expr);
976
977         lyx::regex reg_exp;
978         try {
979                 reg_exp.assign(to_utf8(expr), case_sensitive ?
980                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
981         } catch (lyx::regex_error const & e) {
982                 // lyx::regex throws an exception if the regular expression is not
983                 // valid.
984                 LYXERR(Debug::GUI, e.what());
985                 return vector<docstring>();
986         }
987
988         vector<docstring>::const_iterator it = keys_to_search.begin();
989         vector<docstring>::const_iterator end = keys_to_search.end();
990         for (; it != end; ++it ) {
991                 BiblioInfo::const_iterator info = bi.find(*it);
992                 if (info == bi.end())
993                         continue;
994
995                 BibTeXInfo const & kvm = info->second;
996                 string data;
997                 if (only_keys)
998                         data = to_utf8(*it);
999                 else if (field.empty())
1000                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1001                 else
1002                         data = to_utf8(kvm[field]);
1003
1004                 if (data.empty())
1005                         continue;
1006
1007                 try {
1008                         if (lyx::regex_search(data, reg_exp))
1009                                 foundKeys.push_back(*it);
1010                 }
1011                 catch (lyx::regex_error const & e) {
1012                         LYXERR(Debug::GUI, e.what());
1013                         return vector<docstring>();
1014                 }
1015         }
1016         return foundKeys;
1017 }
1018
1019
1020 void GuiCitation::dispatchParams()
1021 {
1022         std::string const lfun = InsetCommand::params2string(params_);
1023         dispatch(FuncRequest(getLfun(), lfun));
1024 }
1025
1026
1027 BiblioInfo const & GuiCitation::bibInfo() const
1028 {
1029         Buffer const & buf = documentBuffer();
1030         buf.reloadBibInfoCache();
1031         return buf.masterBibInfo();
1032 }
1033
1034
1035 void GuiCitation::saveSession() const
1036 {
1037         Dialog::saveSession();
1038         QSettings settings;
1039         settings.setValue(
1040                 sessionKey() + "/regex", regexp_->isChecked());
1041         settings.setValue(
1042                 sessionKey() + "/casesensitive", casesense_->isChecked());
1043         settings.setValue(
1044                 sessionKey() + "/autofind", instant_->isChecked());
1045         settings.setValue(
1046                 sessionKey() + "/citestyle", style_);
1047 }
1048
1049
1050 void GuiCitation::restoreSession()
1051 {
1052         Dialog::restoreSession();
1053         QSettings settings;
1054         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1055         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1056         instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1057         style_ = settings.value(sessionKey() + "/citestyle").toInt();
1058         updateFilterHint();
1059 }
1060
1061
1062 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1063
1064
1065 } // namespace frontend
1066 } // namespace lyx
1067
1068 #include "moc_GuiCitation.cpp"
1069