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