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