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 "qt_helpers.h"
20 #include "BufferParams.h"
21 #include "FuncRequest.h"
23 #include "insets/InsetCommand.h"
25 #include "support/debug.h"
26 #include "support/docstring.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
30 #include <QCloseEvent>
38 #include <boost/regex.hpp>
45 using namespace lyx::support;
50 static vector<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 : GuiDialog(lv, "citation", qt_("Citation")),
81 params_(insetCode("citation"))
85 connect(citationStyleCO, SIGNAL(activated(int)),
86 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
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(findLE, SIGNAL(returnPressed()),
96 this, SLOT(on_searchPB_clicked()));
97 connect(textBeforeED, SIGNAL(returnPressed()),
98 this, SLOT(on_okPB_clicked()));
99 connect(textAfterED, SIGNAL(returnPressed()),
100 this, SLOT(on_okPB_clicked()));
102 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
104 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
105 addPB, deletePB, upPB, downPB, available(), selected());
106 connect(selectionManager, SIGNAL(selectionChanged()),
107 this, SLOT(setCitedKeys()));
108 connect(selectionManager, SIGNAL(updateHook()),
109 this, SLOT(updateDialog()));
110 connect(selectionManager, SIGNAL(okHook()),
111 this, SLOT(on_okPB_clicked()));
113 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
114 // FIXME: the sizeHint() for this is _way_ too high
115 infoML->setFixedHeight(60);
119 GuiCitation::~GuiCitation()
121 delete selectionManager;
125 void GuiCitation::cleanUp()
133 void GuiCitation::closeEvent(QCloseEvent * e)
141 void GuiCitation::applyView()
143 int const choice = max(0, citationStyleCO->currentIndex());
145 bool const full = fulllistCB->isChecked();
146 bool const force = forceuppercaseCB->isChecked();
148 QString const before = textBeforeED->text();
149 QString const after = textAfterED->text();
151 apply(choice, full, force, before, after);
155 void GuiCitation::showEvent(QShowEvent * e)
159 availableLV->setFocus();
160 GuiDialog::showEvent(e);
164 void GuiCitation::on_okPB_clicked()
172 void GuiCitation::on_cancelPB_clicked()
179 void GuiCitation::on_applyPB_clicked()
185 void GuiCitation::on_restorePB_clicked()
192 void GuiCitation::updateView()
201 // The main point of separating this out is that the fill*() methods
202 // called in update() do not need to be called for INTERNAL updates,
203 // such as when addPB is pressed, as the list of fields, entries, etc,
204 // will not have changed. At the moment, however, the division between
205 // fillStyles() and updateStyle() doesn't lend itself to dividing the
206 // two methods, though they should be divisible.
207 void GuiCitation::updateDialog()
209 if (selectionManager->selectedFocused()) {
210 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
211 updateInfo(availableLV->currentIndex());
213 updateInfo(selectedLV->currentIndex());
215 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
216 updateInfo(QModelIndex());
218 updateInfo(availableLV->currentIndex());
222 textBeforeED->setText(textBefore());
223 textAfterED->setText(textAfter());
229 void GuiCitation::updateFormatting(CiteStyle currentStyle)
231 CiteEngine const engine = citeEngine();
232 bool const natbib_engine =
233 engine == ENGINE_NATBIB_AUTHORYEAR ||
234 engine == ENGINE_NATBIB_NUMERICAL;
235 bool const basic_engine = engine == ENGINE_BASIC;
237 bool const haveSelection =
238 selectedLV->model()->rowCount() > 0;
240 bool const isNocite = currentStyle == NOCITE;
242 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
243 forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
244 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
245 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
246 textAfterED->setEnabled(haveSelection && !isNocite);
247 textAfterLA->setEnabled(haveSelection && !isNocite);
248 citationStyleCO->setEnabled(haveSelection);
249 citationStyleLA->setEnabled(haveSelection);
253 void GuiCitation::updateStyle()
255 string const & command = params_.getCmdName();
257 // Find the style of the citekeys
258 vector<CiteStyle> const & styles = citeStyles_;
259 CitationStyle const cs = citationStyleFromString(command);
261 vector<CiteStyle>::const_iterator cit =
262 std::find(styles.begin(), styles.end(), cs.style);
264 // restore the latest natbib style
265 if (style_ >= 0 && style_ < citationStyleCO->count())
266 citationStyleCO->setCurrentIndex(style_);
268 citationStyleCO->setCurrentIndex(0);
270 if (cit != styles.end()) {
271 int const i = int(cit - styles.begin());
272 citationStyleCO->setCurrentIndex(i);
273 fulllistCB->setChecked(cs.full);
274 forceuppercaseCB->setChecked(cs.forceUpperCase);
276 fulllistCB->setChecked(false);
277 forceuppercaseCB->setChecked(false);
279 updateFormatting(cs.style);
282 // This one needs to be called whenever citationStyleCO needs
283 // to be updated---and this would be on anything that changes the
284 // selection in selectedLV, or on a general update.
285 void GuiCitation::fillStyles()
287 int const oldIndex = citationStyleCO->currentIndex();
289 citationStyleCO->clear();
291 QStringList selected_keys = selected()->stringList();
292 if (selected_keys.empty()) {
293 citationStyleCO->setEnabled(false);
294 citationStyleLA->setEnabled(false);
298 int curr = selectedLV->model()->rowCount() - 1;
302 if (!selectedLV->selectionModel()->selectedIndexes().empty())
303 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
305 QStringList sty = citationStyles(curr);
307 citationStyleCO->setEnabled(!sty.isEmpty());
308 citationStyleLA->setEnabled(!sty.isEmpty());
313 citationStyleCO->insertItems(0, sty);
315 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
316 citationStyleCO->setCurrentIndex(oldIndex);
320 void GuiCitation::fillFields()
322 fieldsCO->blockSignals(true);
323 int const oldIndex = fieldsCO->currentIndex();
325 QStringList const & fields = getFieldsAsQStringList();
326 fieldsCO->insertItem(0, qt_("All Fields"));
327 fieldsCO->insertItem(1, qt_("Keys"));
328 fieldsCO->insertItems(2, fields);
329 if (oldIndex != -1 && oldIndex < fieldsCO->count())
330 fieldsCO->setCurrentIndex(oldIndex);
331 fieldsCO->blockSignals(false);
335 void GuiCitation::fillEntries()
337 entriesCO->blockSignals(true);
338 int const oldIndex = entriesCO->currentIndex();
340 QStringList const & entries = getEntriesAsQStringList();
341 entriesCO->insertItem(0, qt_("All Entry Types"));
342 entriesCO->insertItems(1, entries);
343 if (oldIndex != -1 && oldIndex < entriesCO->count())
344 entriesCO->setCurrentIndex(oldIndex);
345 entriesCO->blockSignals(false);
349 bool GuiCitation::isSelected(const QModelIndex & idx)
351 QString const str = idx.data().toString();
352 return selected()->stringList().contains(str);
356 void GuiCitation::setButtons()
358 selectionManager->update();
359 int const srows = selectedLV->model()->rowCount();
360 applyPB->setEnabled(srows > 0);
361 okPB->setEnabled(srows > 0);
365 void GuiCitation::updateInfo(QModelIndex const & idx)
368 QString const keytxt = getKeyInfo(idx.data().toString());
369 infoML->document()->setPlainText(keytxt);
371 infoML->document()->clear();
375 void GuiCitation::findText(QString const & text, bool reset)
377 //"All Fields" and "Keys" are the first two
378 int index = fieldsCO->currentIndex() - 2;
379 vector<docstring> const & fields = availableFields();
382 if (index <= -1 || index >= int(fields.size()))
383 //either "All Fields" or "Keys" or an invalid value
384 field = from_ascii("");
386 field = fields[index];
389 bool const onlyKeys = index == -1;
391 //"All Entry Types" is first.
392 index = entriesCO->currentIndex() - 1;
393 vector<docstring> const & entries = availableEntries();
394 docstring entry_type;
395 if (index < 0 || index >= int(entries.size()))
396 entry_type = from_ascii("");
398 entry_type = entries[index];
400 bool const case_sentitive = caseCB->checkState();
401 bool const reg_exp = regexCB->checkState();
402 findKey(text, onlyKeys, field, entry_type,
403 case_sentitive, reg_exp, reset);
405 //It'd be nice to save and restore the current selection in
406 //availableLV. Currently, we get an automatic reset, since the
413 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
415 findText(findLE->text(), true);
419 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
421 findText(findLE->text(), true);
425 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
427 if (index >= 0 && index < citationStyleCO->count()) {
428 vector<CiteStyle> const & styles = citeStyles_;
429 updateFormatting(styles[index]);
434 void GuiCitation::on_findLE_textChanged(const QString & text)
436 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
437 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
438 if (!text.isEmpty()) {
440 findText(findLE->text());
443 findText(findLE->text());
447 void GuiCitation::on_searchPB_clicked()
449 findText(findLE->text(), true);
453 void GuiCitation::on_caseCB_stateChanged(int)
455 findText(findLE->text());
459 void GuiCitation::on_regexCB_stateChanged(int)
461 findText(findLE->text());
465 void GuiCitation::on_asTypeCB_stateChanged(int)
467 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
468 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
470 findText(findLE->text(), true);
474 void GuiCitation::changed()
480 void GuiCitation::apply(int const choice, bool full, bool force,
481 QString before, QString after)
483 if (cited_keys_.isEmpty())
486 vector<CiteStyle> const & styles = citeStyles_;
487 if (styles[choice] == NOCITE) {
495 s.style = styles[choice];
497 s.forceUpperCase = force;
498 string const command = citationStyleToString(s);
500 params_.setCmdName(command);
501 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
502 params_["before"] = qstring_to_ucs4(before);
503 params_["after"] = qstring_to_ucs4(after);
508 void GuiCitation::clearSelection()
511 selected_model_.setStringList(cited_keys_);
515 QString GuiCitation::textBefore()
517 return toqstr(params_["before"]);
521 QString GuiCitation::textAfter()
523 return toqstr(params_["after"]);
527 void GuiCitation::init()
529 // Make the list of all available bibliography keys
530 all_keys_ = to_qstring_list(availableKeys());
531 available_model_.setStringList(all_keys_);
533 // Ditto for the keys cited in this inset
534 QString str = toqstr(params_["key"]);
538 cited_keys_ = str.split(",");
539 selected_model_.setStringList(cited_keys_);
543 void GuiCitation::findKey(QString const & str, bool only_keys,
544 docstring field, docstring entry_type,
545 bool case_sensitive, bool reg_exp, bool reset)
547 // Used for optimisation: store last searched string.
548 static QString last_searched_string;
549 // Used to disable the above optimisation.
550 static bool last_case_sensitive;
551 static bool last_reg_exp;
552 // Reset last_searched_string in case of changed option.
553 if (last_case_sensitive != case_sensitive
554 || last_reg_exp != reg_exp) {
555 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
556 last_searched_string.clear();
558 // save option for next search.
559 last_case_sensitive = case_sensitive;
560 last_reg_exp = reg_exp;
562 Qt::CaseSensitivity qtcase = case_sensitive ?
563 Qt::CaseSensitive: Qt::CaseInsensitive;
565 // If new string (str) contains the last searched one...
567 !last_searched_string.isEmpty() &&
569 str.contains(last_searched_string, qtcase))
570 // ... then only search within already found list.
571 keys = available_model_.stringList();
573 // ... else search all keys.
575 // save searched string for next search.
576 last_searched_string = str;
580 // First, filter by entry_type, which will be faster than
581 // what follows, so we may get to do that on less.
582 vector<docstring> keyVector = to_docstring_vector(keys);
583 filterByEntryType(keyVector, entry_type);
586 result = to_qstring_list(keyVector);
588 result = to_qstring_list(searchKeys(keyVector, only_keys,
589 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
591 available_model_.setStringList(result);
595 QStringList GuiCitation::getFieldsAsQStringList()
597 return to_qstring_list(availableFields());
601 QStringList GuiCitation::getEntriesAsQStringList()
603 return to_qstring_list(availableEntries());
607 QStringList GuiCitation::citationStyles(int sel)
609 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
610 return to_qstring_list(bibInfo().getCiteStrings(key, buffer()));
614 QString GuiCitation::getKeyInfo(QString const & sel)
616 return toqstr(getInfo(qstring_to_ucs4(sel)));
620 void GuiCitation::setCitedKeys()
622 cited_keys_ = selected_model_.stringList();
626 bool GuiCitation::initialiseParams(string const & data)
628 InsetCommand::string2params("citation", data, params_);
629 CiteEngine const engine = buffer().params().citeEngine();
630 citeStyles_ = citeStyles(engine);
635 void GuiCitation::clearParams()
641 vector<docstring> GuiCitation::availableKeys() const
643 return bibInfo().getKeys();
647 vector<docstring> GuiCitation::availableFields() const
649 return bibInfo().getFields();
653 vector<docstring> GuiCitation::availableEntries() const
655 return bibInfo().getEntries();
659 void GuiCitation::filterByEntryType(
660 vector<docstring> & keyVector, docstring entry_type)
662 if (entry_type.empty())
665 vector<docstring>::iterator it = keyVector.begin();
666 vector<docstring>::iterator end = keyVector.end();
668 vector<docstring> result;
669 for (; it != end; ++it) {
670 docstring const key = *it;
671 BiblioInfo::const_iterator cit = bibInfo().find(key);
672 if (cit == bibInfo().end())
674 if (cit->second.entryType() == entry_type)
675 result.push_back(key);
681 CiteEngine GuiCitation::citeEngine() const
683 return buffer().params().citeEngine();
687 docstring GuiCitation::getInfo(docstring const & key) const
689 if (bibInfo().empty())
692 return bibInfo().getInfo(key);
696 // Escape special chars.
697 // All characters are literals except: '.|*?+(){}[]^$\'
698 // These characters are literals when preceded by a "\", which is done here
699 // @todo: This function should be moved to support, and then the test in tests
700 // should be moved there as well.
701 static docstring escape_special_chars(docstring const & expr)
703 // Search for all chars '.|*?+(){}[^$]\'
704 // Note that '[' and '\' must be escaped.
705 // This is a limitation of boost::regex, but all other chars in BREs
706 // are assumed literal.
707 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
709 // $& is a perl-like expression that expands to all
710 // of the current match
711 // The '$' must be prefixed with the escape character '\' for
712 // boost to treat it as a literal.
713 // Thus, to prefix a matched expression with '\', we use:
715 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
719 vector<docstring> GuiCitation::searchKeys(
720 vector<docstring> const & keys_to_search, bool only_keys,
721 docstring const & search_expression, docstring field,
722 bool case_sensitive, bool regex)
724 vector<docstring> foundKeys;
726 docstring expr = trim(search_expression);
731 // We must escape special chars in the search_expr so that
732 // it is treated as a simple string by boost::regex.
733 expr = escape_special_chars(expr);
735 boost::regex reg_exp;
737 reg_exp.assign(to_utf8(expr), case_sensitive ?
738 boost::regex_constants::normal : boost::regex_constants::icase);
739 } catch (boost::regex_error & e) {
740 // boost::regex throws an exception if the regular expression is not
742 LYXERR(Debug::GUI, e.what());
743 return vector<docstring>();
746 vector<docstring>::const_iterator it = keys_to_search.begin();
747 vector<docstring>::const_iterator end = keys_to_search.end();
748 for (; it != end; ++it ) {
749 BiblioInfo::const_iterator info = bibInfo().find(*it);
750 if (info == bibInfo().end())
753 BibTeXInfo const & kvm = info->second;
757 else if (field.empty())
758 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
759 else if (kvm.hasField(field))
760 data = to_utf8(kvm.getValueForField(field));
766 if (boost::regex_search(data, reg_exp))
767 foundKeys.push_back(*it);
769 catch (boost::regex_error & e) {
770 LYXERR(Debug::GUI, e.what());
771 return vector<docstring>();
778 void GuiCitation::dispatchParams()
780 std::string const lfun = InsetCommand::params2string("citation", params_);
781 dispatch(FuncRequest(getLfun(), lfun));
785 BiblioInfo const & GuiCitation::bibInfo() const
787 return buffer().masterBibInfo();
791 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
794 } // namespace frontend
797 #include "GuiCitation_moc.cpp"