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