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