2 * \file GuiCitation.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
7 * \author Kalle Dalheimer
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
16 #include "GuiCitation.h"
18 #include "support/debug.h"
19 #include "support/gettext.h"
20 #include "qt_helpers.h"
22 #include "BufferParams.h"
24 #include "support/lstrings.h"
25 #include "support/docstring.h"
27 #include "insets/InsetCommand.h"
32 #include <QCloseEvent>
37 #include <boost/regex.hpp>
50 static vector<biblio::CiteStyle> citeStyles_;
53 template<typename String>
54 static QStringList to_qstring_list(vector<String> const & v)
58 for (size_t i = 0; i != v.size(); ++i) {
61 qlist.append(lyx::toqstr(v[i]));
67 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
69 vector<lyx::docstring> v;
70 for (int i = 0; i != qlist.size(); ++i) {
71 if (qlist[i].isEmpty())
73 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
79 GuiCitation::GuiCitation(GuiView & lv)
80 : GuiCommand(lv, "citation")
83 setViewTitle(_("Citation"));
85 connect(citationStyleCO, SIGNAL(activated(int)),
86 this, SLOT(changed()));
87 connect(fulllistCB, SIGNAL(clicked()),
88 this, SLOT(changed()));
89 connect(forceuppercaseCB, SIGNAL(clicked()),
90 this, SLOT(changed()));
91 connect(textBeforeED, SIGNAL(textChanged(QString)),
92 this, SLOT(changed()));
93 connect(textAfterED, SIGNAL(textChanged(QString)),
94 this, SLOT(changed()));
95 connect(clearPB, SIGNAL(clicked()),
96 findLE, SLOT(clear()));
97 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
99 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
100 addPB, deletePB, upPB, downPB, available(), selected());
101 connect(selectionManager, SIGNAL(selectionChanged()),
102 this, SLOT(setCitedKeys()));
103 connect(selectionManager, SIGNAL(updateHook()),
104 this, SLOT(updateDialog()));
105 connect(selectionManager, SIGNAL(okHook()),
106 this, SLOT(on_okPB_clicked()));
108 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
112 void GuiCitation::cleanUp()
120 void GuiCitation::closeEvent(QCloseEvent * e)
124 GuiDialog::closeEvent(e);
128 void GuiCitation::applyView()
130 int const choice = std::max(0, citationStyleCO->currentIndex());
132 bool const full = fulllistCB->isChecked();
133 bool const force = forceuppercaseCB->isChecked();
135 QString const before = textBeforeED->text();
136 QString const after = textAfterED->text();
138 apply(choice, full, force, before, after);
142 void GuiCitation::showEvent(QShowEvent * e)
146 availableLV->setFocus();
147 GuiDialog::showEvent(e);
151 void GuiCitation::on_okPB_clicked()
159 void GuiCitation::on_cancelPB_clicked()
166 void GuiCitation::on_applyPB_clicked()
172 void GuiCitation::on_restorePB_clicked()
179 void GuiCitation::updateView()
188 // The main point of separating this out is that the fill*() methods
189 // called in update() do not need to be called for INTERNAL updates,
190 // such as when addPB is pressed, as the list of fields, entries, etc,
191 // will not have changed. At the moment, however, the division between
192 // fillStyles() and updateStyles() doesn't lend itself to dividing the
193 // two methods, though they should be divisible.
194 void GuiCitation::updateDialog()
196 if (selectionManager->selectedFocused()) {
197 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
198 updateInfo(availableLV->currentIndex());
200 updateInfo(selectedLV->currentIndex());
202 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
203 updateInfo(QModelIndex());
205 updateInfo(availableLV->currentIndex());
209 textBeforeED->setText(textBefore());
210 textAfterED->setText(textAfter());
216 void GuiCitation::updateStyle()
218 biblio::CiteEngine const engine = getEngine();
219 bool const natbib_engine =
220 engine == biblio::ENGINE_NATBIB_AUTHORYEAR ||
221 engine == biblio::ENGINE_NATBIB_NUMERICAL;
222 bool const basic_engine = engine == biblio::ENGINE_BASIC;
224 bool const haveSelection =
225 selectedLV->model()->rowCount() > 0;
226 fulllistCB->setEnabled(natbib_engine && haveSelection);
227 forceuppercaseCB->setEnabled(natbib_engine && haveSelection);
228 textBeforeED->setEnabled(!basic_engine && haveSelection);
229 textBeforeLA->setEnabled(!basic_engine && haveSelection);
230 textAfterED->setEnabled(haveSelection);
231 textAfterLA->setEnabled(haveSelection);
232 citationStyleCO->setEnabled(!basic_engine && haveSelection);
233 citationStyleLA->setEnabled(!basic_engine && haveSelection);
235 string const & command = params_.getCmdName();
237 // Find the style of the citekeys
238 vector<biblio::CiteStyle> const & styles = citeStyles_;
239 biblio::CitationStyle const cs(command);
241 vector<biblio::CiteStyle>::const_iterator cit =
242 std::find(styles.begin(), styles.end(), cs.style);
244 // restore the latest natbib style
245 if (style_ >= 0 && style_ < citationStyleCO->count())
246 citationStyleCO->setCurrentIndex(style_);
248 citationStyleCO->setCurrentIndex(0);
250 if (cit != styles.end()) {
251 int const i = int(cit - styles.begin());
252 citationStyleCO->setCurrentIndex(i);
253 fulllistCB->setChecked(cs.full);
254 forceuppercaseCB->setChecked(cs.forceUCase);
256 fulllistCB->setChecked(false);
257 forceuppercaseCB->setChecked(false);
262 //This one needs to be called whenever citationStyleCO needs
263 //to be updated---and this would be on anything that changes the
264 //selection in selectedLV, or on a general update.
265 void GuiCitation::fillStyles()
267 int const oldIndex = citationStyleCO->currentIndex();
269 citationStyleCO->clear();
271 QStringList selected_keys = selected()->stringList();
272 if (selected_keys.empty()) {
273 citationStyleCO->setEnabled(false);
274 citationStyleLA->setEnabled(false);
278 int curr = selectedLV->model()->rowCount() - 1;
282 if (!selectedLV->selectionModel()->selectedIndexes().empty())
283 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
285 QStringList sty = citationStyles(curr);
287 bool const basic_engine = (getEngine() == biblio::ENGINE_BASIC);
289 citationStyleCO->setEnabled(!sty.isEmpty() && !basic_engine);
290 citationStyleLA->setEnabled(!sty.isEmpty() && !basic_engine);
292 if (sty.isEmpty() || basic_engine)
295 citationStyleCO->insertItems(0, sty);
297 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
298 citationStyleCO->setCurrentIndex(oldIndex);
302 void GuiCitation::fillFields()
304 fieldsCO->blockSignals(true);
305 int const oldIndex = fieldsCO->currentIndex();
307 QStringList const & fields = getFieldsAsQStringList();
308 fieldsCO->insertItem(0, qt_("All Fields"));
309 fieldsCO->insertItem(1, qt_("Keys"));
310 fieldsCO->insertItems(2, fields);
311 if (oldIndex != -1 && oldIndex < fieldsCO->count())
312 fieldsCO->setCurrentIndex(oldIndex);
313 fieldsCO->blockSignals(false);
317 void GuiCitation::fillEntries()
319 entriesCO->blockSignals(true);
320 int const oldIndex = entriesCO->currentIndex();
322 QStringList const & entries = getEntriesAsQStringList();
323 entriesCO->insertItem(0, qt_("All Entry Types"));
324 entriesCO->insertItems(1, entries);
325 if (oldIndex != -1 && oldIndex < entriesCO->count())
326 entriesCO->setCurrentIndex(oldIndex);
327 entriesCO->blockSignals(false);
331 bool GuiCitation::isSelected(const QModelIndex & idx)
333 QString const str = idx.data().toString();
334 return selected()->stringList().contains(str);
338 void GuiCitation::setButtons()
340 selectionManager->update();
341 int const srows = selectedLV->model()->rowCount();
342 applyPB->setEnabled(srows > 0);
343 okPB->setEnabled(srows > 0);
347 void GuiCitation::updateInfo(QModelIndex const & idx)
350 QString const keytxt = getKeyInfo(idx.data().toString());
351 infoML->document()->setPlainText(keytxt);
353 infoML->document()->clear();
357 void GuiCitation::findText(QString const & text, bool reset)
359 //"All Fields" and "Keys" are the first two
360 int index = fieldsCO->currentIndex() - 2;
361 vector<docstring> const & fields = availableFields();
364 if (index <= -1 || index >= int(fields.size()))
365 //either "All Fields" or "Keys" or an invalid value
366 field = from_ascii("");
368 field = fields[index];
371 bool const onlyKeys = index == -1;
373 //"All Entry Types" is first.
374 index = entriesCO->currentIndex() - 1;
375 vector<docstring> const & entries = availableEntries();
377 if (index < 0 || index >= int(entries.size()))
378 entryType = from_ascii("");
380 entryType = entries[index];
382 bool const case_sentitive = caseCB->checkState();
383 bool const reg_exp = regexCB->checkState();
384 findKey(text, onlyKeys, field, entryType,
385 case_sentitive, reg_exp, reset);
387 //It'd be nice to save and restore the current selection in
388 //availableLV. Currently, we get an automatic reset, since the
395 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
397 findText(findLE->text(), true);
401 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
403 findText(findLE->text(), true);
407 void GuiCitation::on_findLE_textChanged(const QString & text)
409 clearPB->setDisabled(text.isEmpty());
416 void GuiCitation::on_caseCB_stateChanged(int)
418 findText(findLE->text());
422 void GuiCitation::on_regexCB_stateChanged(int)
424 findText(findLE->text());
428 void GuiCitation::changed()
435 void GuiCitation::apply(int const choice, bool const full, bool const force,
436 QString before, QString after)
438 if (cited_keys_.isEmpty())
441 vector<biblio::CiteStyle> const & styles = citeStyles_;
443 string const command =
444 biblio::CitationStyle(styles[choice], full, force)
447 params_.setCmdName(command);
448 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
449 params_["before"] = qstring_to_ucs4(before);
450 params_["after"] = qstring_to_ucs4(after);
455 void GuiCitation::clearSelection()
458 selected_model_.setStringList(cited_keys_);
462 QString GuiCitation::textBefore()
464 return toqstr(params_["before"]);
468 QString GuiCitation::textAfter()
470 return toqstr(params_["after"]);
474 void GuiCitation::init()
476 // Make the list of all available bibliography keys
477 all_keys_ = to_qstring_list(availableKeys());
478 available_model_.setStringList(all_keys_);
480 // Ditto for the keys cited in this inset
481 QString str = toqstr(params_["key"]);
485 cited_keys_ = str.split(",");
486 selected_model_.setStringList(cited_keys_);
490 void GuiCitation::findKey(QString const & str, bool only_keys,
491 docstring field, docstring entryType,
492 bool case_sensitive, bool reg_exp, bool reset)
494 // Used for optimisation: store last searched string.
495 static QString last_searched_string;
496 // Used to disable the above optimisation.
497 static bool last_case_sensitive;
498 static bool last_reg_exp;
499 // Reset last_searched_string in case of changed option.
500 if (last_case_sensitive != case_sensitive
501 || last_reg_exp != reg_exp) {
502 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
503 last_searched_string.clear();
505 // save option for next search.
506 last_case_sensitive = case_sensitive;
507 last_reg_exp = reg_exp;
509 Qt::CaseSensitivity qtcase = case_sensitive?
510 Qt::CaseSensitive: Qt::CaseInsensitive;
512 // If new string (str) contains the last searched one...
514 !last_searched_string.isEmpty() &&
516 str.contains(last_searched_string, qtcase))
517 // ... then only search within already found list.
518 keys = available_model_.stringList();
520 // ... else search all keys.
522 // save searched string for next search.
523 last_searched_string = str;
527 // First, filter by entryType, which will be faster than
528 // what follows, so we may get to do that on less.
529 vector<docstring> keyVector = to_docstring_vector(keys);
530 filterByEntryType(keyVector, entryType);
533 result = to_qstring_list(keyVector);
535 result = to_qstring_list(searchKeys(keyVector, only_keys,
536 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
538 available_model_.setStringList(result);
542 QStringList GuiCitation::getFieldsAsQStringList()
544 return to_qstring_list(availableFields());
548 QStringList GuiCitation::getEntriesAsQStringList()
550 return to_qstring_list(availableEntries());
554 QStringList GuiCitation::citationStyles(int sel)
556 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
557 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
561 QString GuiCitation::getKeyInfo(QString const & sel)
563 return toqstr(getInfo(qstring_to_ucs4(sel)));
567 void GuiCitation::setCitedKeys()
569 cited_keys_ = selected_model_.stringList();
573 bool GuiCitation::initialiseParams(string const & data)
575 InsetCommandMailer::string2params(lfun_name_, data, params_);
577 biblio::CiteEngine const engine = buffer().params().getEngine();
579 bool use_styles = engine != biblio::ENGINE_BASIC;
581 bibkeysInfo_.fillWithBibKeys(&buffer());
583 if (citeStyles_.empty())
584 citeStyles_ = biblio::getCiteStyles(engine);
586 if ((use_styles && citeStyles_.size() == 1) ||
587 (!use_styles && citeStyles_.size() != 1))
588 citeStyles_ = biblio::getCiteStyles(engine);
595 void GuiCitation::clearParams()
598 bibkeysInfo_.clear();
602 vector<docstring> const GuiCitation::availableKeys() const
604 return bibkeysInfo_.getKeys();
608 vector<docstring> const GuiCitation::availableFields() const
610 return bibkeysInfo_.getFields();
614 vector<docstring> const GuiCitation::availableEntries() const
616 return bibkeysInfo_.getEntries();
620 void GuiCitation::filterByEntryType(
621 vector<docstring> & keyVector, docstring entryType)
623 if (entryType.empty())
626 vector<docstring>::iterator it = keyVector.begin();
627 vector<docstring>::iterator end = keyVector.end();
629 vector<docstring> result;
630 for (; it != end; ++it) {
631 docstring const key = *it;
632 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
633 if (cit == bibkeysInfo_.end())
635 if (cit->second.entryType == entryType)
636 result.push_back(key);
642 biblio::CiteEngine GuiCitation::getEngine() const
644 return buffer().params().getEngine();
648 docstring GuiCitation::getInfo(docstring const & key) const
650 if (bibkeysInfo_.empty())
653 return bibkeysInfo_.getInfo(key);
657 // Escape special chars.
658 // All characters are literals except: '.|*?+(){}[]^$\'
659 // These characters are literals when preceded by a "\", which is done here
660 // @todo: This function should be moved to support, and then the test in tests
661 // should be moved there as well.
662 static docstring escape_special_chars(docstring const & expr)
664 // Search for all chars '.|*?+(){}[^$]\'
665 // Note that '[' and '\' must be escaped.
666 // This is a limitation of boost::regex, but all other chars in BREs
667 // are assumed literal.
668 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
670 // $& is a perl-like expression that expands to all
671 // of the current match
672 // The '$' must be prefixed with the escape character '\' for
673 // boost to treat it as a literal.
674 // Thus, to prefix a matched expression with '\', we use:
676 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
680 vector<docstring> GuiCitation::searchKeys(
681 vector<docstring> const & keys_to_search, bool only_keys,
682 docstring const & search_expression, docstring field,
683 bool case_sensitive, bool regex)
685 vector<docstring> foundKeys;
687 docstring expr = support::trim(search_expression);
692 // We must escape special chars in the search_expr so that
693 // it is treated as a simple string by boost::regex.
694 expr = escape_special_chars(expr);
696 boost::regex reg_exp(to_utf8(expr), case_sensitive ?
697 boost::regex_constants::normal : boost::regex_constants::icase);
699 vector<docstring>::const_iterator it = keys_to_search.begin();
700 vector<docstring>::const_iterator end = keys_to_search.end();
701 for (; it != end; ++it ) {
702 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
703 if (info == bibkeysInfo_.end())
706 BibTeXInfo const & kvm = info->second;
710 else if (field.empty())
711 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData);
712 else if (kvm.hasField(field))
713 data = to_utf8(kvm.getValueForField(field));
719 if (boost::regex_search(data, reg_exp))
720 foundKeys.push_back(*it);
722 catch (boost::regex_error &) {
723 return vector<docstring>();
730 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
733 } // namespace frontend
736 #include "GuiCitation_moc.cpp"