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