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"
20 #include "frontend_helpers.h"
21 #include "qt_helpers.h"
23 #include "BufferParams.h"
25 #include "support/lstrings.h"
26 #include "support/docstring.h"
31 #include <QCloseEvent>
35 #include <boost/regex.hpp>
48 static vector<biblio::CiteStyle> citeStyles_;
51 template<typename String>
52 static QStringList to_qstring_list(vector<String> const & v)
56 for (size_t i = 0; i != v.size(); ++i) {
59 qlist.append(lyx::toqstr(v[i]));
65 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
67 vector<lyx::docstring> v;
68 for (int i = 0; i != qlist.size(); ++i) {
69 if (qlist[i].isEmpty())
71 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
77 GuiCitation::GuiCitation(LyXView & lv)
78 : GuiDialog(lv, "citation"), ControlCommand(*this, "citation")
81 setViewTitle(_("Citation"));
82 setController(this, false);
84 connect(citationStyleCO, SIGNAL(activated(int)),
85 this, SLOT(changed()));
86 connect(fulllistCB, SIGNAL(clicked()),
87 this, SLOT(changed()));
88 connect(forceuppercaseCB, SIGNAL(clicked()),
89 this, SLOT(changed()));
90 connect(textBeforeED, SIGNAL(textChanged(QString)),
91 this, SLOT(changed()));
92 connect(textAfterED, SIGNAL(textChanged(QString)),
93 this, SLOT(changed()));
94 connect(clearPB, SIGNAL(clicked()),
95 findLE, SLOT(clear()));
96 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
98 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
99 addPB, deletePB, upPB, downPB, available(), selected());
100 connect(selectionManager, SIGNAL(selectionChanged()),
101 this, SLOT(setCitedKeys()));
102 connect(selectionManager, SIGNAL(updateHook()),
103 this, SLOT(updateDialog()));
104 connect(selectionManager, SIGNAL(okHook()),
105 this, SLOT(on_okPB_clicked()));
107 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
111 void GuiCitation::cleanUp()
119 void GuiCitation::closeEvent(QCloseEvent * e)
123 GuiDialog::closeEvent(e);
127 void GuiCitation::applyView()
129 int const choice = std::max(0, citationStyleCO->currentIndex());
131 bool const full = fulllistCB->isChecked();
132 bool const force = forceuppercaseCB->isChecked();
134 QString const before = textBeforeED->text();
135 QString const after = textAfterED->text();
137 apply(choice, full, force, before, after);
141 void GuiCitation::hideView()
148 void GuiCitation::showView()
152 availableLV->setFocus();
159 bool GuiCitation::isVisibleView() const
161 return QDialog::isVisible();
165 void GuiCitation::on_okPB_clicked()
173 void GuiCitation::on_cancelPB_clicked()
180 void GuiCitation::on_applyPB_clicked()
186 void GuiCitation::on_restorePB_clicked()
193 void GuiCitation::updateView()
202 // The main point of separating this out is that the fill*() methods
203 // called in update() do not need to be called for INTERNAL updates,
204 // such as when addPB is pressed, as the list of fields, entries, etc,
205 // will not have changed. At the moment, however, the division between
206 // fillStyles() and updateStyles() doesn't lend itself to dividing the
207 // two methods, though they should be divisible.
208 void GuiCitation::updateDialog()
210 if (selectionManager->selectedFocused()) {
211 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
212 updateInfo(availableLV->currentIndex());
214 updateInfo(selectedLV->currentIndex());
216 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
217 updateInfo(QModelIndex());
219 updateInfo(availableLV->currentIndex());
223 textBeforeED->setText(textBefore());
224 textAfterED->setText(textAfter());
230 void GuiCitation::updateStyle()
232 biblio::CiteEngine const engine = getEngine();
233 bool const natbib_engine =
234 engine == biblio::ENGINE_NATBIB_AUTHORYEAR ||
235 engine == biblio::ENGINE_NATBIB_NUMERICAL;
236 bool const basic_engine = engine == biblio::ENGINE_BASIC;
238 bool const haveSelection =
239 selectedLV->model()->rowCount() > 0;
240 fulllistCB->setEnabled(natbib_engine && haveSelection);
241 forceuppercaseCB->setEnabled(natbib_engine && haveSelection);
242 textBeforeED->setEnabled(!basic_engine && haveSelection);
243 textBeforeLA->setEnabled(!basic_engine && haveSelection);
244 textAfterED->setEnabled(haveSelection);
245 textAfterLA->setEnabled(haveSelection);
246 citationStyleCO->setEnabled(!basic_engine && haveSelection);
247 citationStyleLA->setEnabled(!basic_engine && haveSelection);
249 string const & command = params().getCmdName();
251 // Find the style of the citekeys
252 vector<biblio::CiteStyle> const & styles = citeStyles_;
253 biblio::CitationStyle const cs(command);
255 vector<biblio::CiteStyle>::const_iterator cit =
256 std::find(styles.begin(), styles.end(), cs.style);
258 // restore the latest natbib style
259 if (style_ >= 0 && style_ < citationStyleCO->count())
260 citationStyleCO->setCurrentIndex(style_);
262 citationStyleCO->setCurrentIndex(0);
264 if (cit != styles.end()) {
265 int const i = int(cit - styles.begin());
266 citationStyleCO->setCurrentIndex(i);
267 fulllistCB->setChecked(cs.full);
268 forceuppercaseCB->setChecked(cs.forceUCase);
270 fulllistCB->setChecked(false);
271 forceuppercaseCB->setChecked(false);
276 //This one needs to be called whenever citationStyleCO needs
277 //to be updated---and this would be on anything that changes the
278 //selection in selectedLV, or on a general update.
279 void GuiCitation::fillStyles()
281 int const oldIndex = citationStyleCO->currentIndex();
283 citationStyleCO->clear();
285 QStringList selected_keys = selected()->stringList();
286 if (selected_keys.empty()) {
287 citationStyleCO->setEnabled(false);
288 citationStyleLA->setEnabled(false);
292 int curr = selectedLV->model()->rowCount() - 1;
296 if (!selectedLV->selectionModel()->selectedIndexes().empty())
297 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
299 QStringList sty = citationStyles(curr);
301 bool const basic_engine = (getEngine() == biblio::ENGINE_BASIC);
303 citationStyleCO->setEnabled(!sty.isEmpty() && !basic_engine);
304 citationStyleLA->setEnabled(!sty.isEmpty() && !basic_engine);
306 if (sty.isEmpty() || basic_engine)
309 citationStyleCO->insertItems(0, sty);
311 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
312 citationStyleCO->setCurrentIndex(oldIndex);
316 void GuiCitation::fillFields()
318 fieldsCO->blockSignals(true);
319 int const oldIndex = fieldsCO->currentIndex();
321 QStringList const & fields = getFieldsAsQStringList();
322 fieldsCO->insertItem(0, qt_("All Fields"));
323 fieldsCO->insertItem(1, qt_("Keys"));
324 fieldsCO->insertItems(2, fields);
325 if (oldIndex != -1 && oldIndex < fieldsCO->count())
326 fieldsCO->setCurrentIndex(oldIndex);
327 fieldsCO->blockSignals(false);
331 void GuiCitation::fillEntries()
333 entriesCO->blockSignals(true);
334 int const oldIndex = entriesCO->currentIndex();
336 QStringList const & entries = getEntriesAsQStringList();
337 entriesCO->insertItem(0, qt_("All Entry Types"));
338 entriesCO->insertItems(1, entries);
339 if (oldIndex != -1 && oldIndex < entriesCO->count())
340 entriesCO->setCurrentIndex(oldIndex);
341 entriesCO->blockSignals(false);
345 bool GuiCitation::isSelected(const QModelIndex & idx)
347 QString const str = idx.data().toString();
348 return selected()->stringList().contains(str);
352 void GuiCitation::setButtons()
354 selectionManager->update();
355 int const srows = selectedLV->model()->rowCount();
356 applyPB->setEnabled(srows > 0);
357 okPB->setEnabled(srows > 0);
361 void GuiCitation::updateInfo(QModelIndex const & idx)
364 QString const keytxt = getKeyInfo(idx.data().toString());
365 infoML->document()->setPlainText(keytxt);
367 infoML->document()->clear();
371 void GuiCitation::findText(QString const & text, bool reset)
373 //"All Fields" and "Keys" are the first two
374 int index = fieldsCO->currentIndex() - 2;
375 vector<docstring> const & fields = availableFields();
378 if (index <= -1 || index >= int(fields.size()))
379 //either "All Fields" or "Keys" or an invalid value
380 field = from_ascii("");
382 field = fields[index];
385 bool const onlyKeys = index == -1;
387 //"All Entry Types" is first.
388 index = entriesCO->currentIndex() - 1;
389 vector<docstring> const & entries = availableEntries();
391 if (index < 0 || index >= int(entries.size()))
392 entryType = from_ascii("");
394 entryType = entries[index];
396 bool const case_sentitive = caseCB->checkState();
397 bool const reg_exp = regexCB->checkState();
398 findKey(text, onlyKeys, field, entryType,
399 case_sentitive, reg_exp, reset);
401 //It'd be nice to save and restore the current selection in
402 //availableLV. Currently, we get an automatic reset, since the
409 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
411 findText(findLE->text(), true);
415 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
417 findText(findLE->text(), true);
421 void GuiCitation::on_findLE_textChanged(const QString & text)
423 clearPB->setDisabled(text.isEmpty());
430 void GuiCitation::on_caseCB_stateChanged(int)
432 findText(findLE->text());
436 void GuiCitation::on_regexCB_stateChanged(int)
438 findText(findLE->text());
442 void GuiCitation::changed()
449 void GuiCitation::apply(int const choice, bool const full, bool const force,
450 QString before, QString after)
452 if (cited_keys_.isEmpty())
455 vector<biblio::CiteStyle> const & styles = citeStyles_;
457 string const command =
458 biblio::CitationStyle(styles[choice], full, force)
461 params().setCmdName(command);
462 params()["key"] = qstring_to_ucs4(cited_keys_.join(","));
463 params()["before"] = qstring_to_ucs4(before);
464 params()["after"] = qstring_to_ucs4(after);
469 void GuiCitation::clearSelection()
472 selected_model_.setStringList(cited_keys_);
476 QString GuiCitation::textBefore()
478 return toqstr(params()["before"]);
482 QString GuiCitation::textAfter()
484 return toqstr(params()["after"]);
488 void GuiCitation::init()
490 // Make the list of all available bibliography keys
491 all_keys_ = to_qstring_list(availableKeys());
492 available_model_.setStringList(all_keys_);
494 // Ditto for the keys cited in this inset
495 QString str = toqstr(params()["key"]);
499 cited_keys_ = str.split(",");
500 selected_model_.setStringList(cited_keys_);
504 void GuiCitation::findKey(QString const & str, bool only_keys,
505 docstring field, docstring entryType,
506 bool case_sensitive, bool reg_exp, bool reset)
508 // Used for optimisation: store last searched string.
509 static QString last_searched_string;
510 // Used to disable the above optimisation.
511 static bool last_case_sensitive;
512 static bool last_reg_exp;
513 // Reset last_searched_string in case of changed option.
514 if (last_case_sensitive != case_sensitive
515 || last_reg_exp != reg_exp) {
516 LYXERR(Debug::GUI) << "GuiCitation::findKey: optimisation disabled!" << std::endl;
517 last_searched_string.clear();
519 // save option for next search.
520 last_case_sensitive = case_sensitive;
521 last_reg_exp = reg_exp;
523 Qt::CaseSensitivity qtcase = case_sensitive?
524 Qt::CaseSensitive: Qt::CaseInsensitive;
526 // If new string (str) contains the last searched one...
528 !last_searched_string.isEmpty() &&
530 str.contains(last_searched_string, qtcase))
531 // ... then only search within already found list.
532 keys = available_model_.stringList();
534 // ... else search all keys.
536 // save searched string for next search.
537 last_searched_string = str;
541 // First, filter by entryType, which will be faster than
542 // what follows, so we may get to do that on less.
543 vector<docstring> keyVector = to_docstring_vector(keys);
544 filterByEntryType(keyVector, entryType);
547 result = to_qstring_list(keyVector);
549 result = to_qstring_list(searchKeys(keyVector, only_keys,
550 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
552 available_model_.setStringList(result);
556 QStringList GuiCitation::getFieldsAsQStringList()
558 return to_qstring_list(availableFields());
562 QStringList GuiCitation::getEntriesAsQStringList()
564 return to_qstring_list(availableEntries());
568 QStringList GuiCitation::citationStyles(int sel)
570 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
571 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
575 QString GuiCitation::getKeyInfo(QString const & sel)
577 return toqstr(getInfo(qstring_to_ucs4(sel)));
581 void GuiCitation::setCitedKeys()
583 cited_keys_ = selected_model_.stringList();
587 bool GuiCitation::initialiseParams(string const & data)
589 if (!ControlCommand::initialiseParams(data))
592 biblio::CiteEngine const engine = buffer().params().getEngine();
594 bool use_styles = engine != biblio::ENGINE_BASIC;
596 bibkeysInfo_.fillWithBibKeys(&buffer());
598 if (citeStyles_.empty())
599 citeStyles_ = biblio::getCiteStyles(engine);
601 if ((use_styles && citeStyles_.size() == 1) ||
602 (!use_styles && citeStyles_.size() != 1))
603 citeStyles_ = biblio::getCiteStyles(engine);
611 void GuiCitation::clearParams()
613 ControlCommand::clearParams();
614 bibkeysInfo_.clear();
618 vector<docstring> const GuiCitation::availableKeys() const
620 return bibkeysInfo_.getKeys();
624 vector<docstring> const GuiCitation::availableFields() const
626 return bibkeysInfo_.getFields();
630 vector<docstring> const GuiCitation::availableEntries() const
632 return bibkeysInfo_.getEntries();
636 void GuiCitation::filterByEntryType(
637 vector<docstring> & keyVector, docstring entryType)
639 if (entryType.empty())
642 vector<docstring>::iterator it = keyVector.begin();
643 vector<docstring>::iterator end = keyVector.end();
645 vector<docstring> result;
646 for (; it != end; ++it) {
647 docstring const key = *it;
648 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
649 if (cit == bibkeysInfo_.end())
651 if (cit->second.entryType == entryType)
652 result.push_back(key);
658 biblio::CiteEngine GuiCitation::getEngine() const
660 return buffer().params().getEngine();
664 docstring GuiCitation::getInfo(docstring const & key) const
666 if (bibkeysInfo_.empty())
669 return bibkeysInfo_.getInfo(key);
673 // Escape special chars.
674 // All characters are literals except: '.|*?+(){}[]^$\'
675 // These characters are literals when preceded by a "\", which is done here
676 // @todo: This function should be moved to support, and then the test in tests
677 // should be moved there as well.
678 static docstring escape_special_chars(docstring const & expr)
680 // Search for all chars '.|*?+(){}[^$]\'
681 // Note that '[' and '\' must be escaped.
682 // This is a limitation of boost::regex, but all other chars in BREs
683 // are assumed literal.
684 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
686 // $& is a perl-like expression that expands to all
687 // of the current match
688 // The '$' must be prefixed with the escape character '\' for
689 // boost to treat it as a literal.
690 // Thus, to prefix a matched expression with '\', we use:
692 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
696 vector<docstring> GuiCitation::searchKeys(
697 vector<docstring> const & keys_to_search, bool only_keys,
698 docstring const & search_expression, docstring field,
699 bool case_sensitive, bool regex)
701 vector<docstring> foundKeys;
703 docstring expr = support::trim(search_expression);
708 // We must escape special chars in the search_expr so that
709 // it is treated as a simple string by boost::regex.
710 expr = escape_special_chars(expr);
712 boost::regex reg_exp(to_utf8(expr), case_sensitive ?
713 boost::regex_constants::normal : boost::regex_constants::icase);
715 vector<docstring>::const_iterator it = keys_to_search.begin();
716 vector<docstring>::const_iterator end = keys_to_search.end();
717 for (; it != end; ++it ) {
718 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
719 if (info == bibkeysInfo_.end())
722 BibTeXInfo const & kvm = info->second;
726 else if (field.empty())
727 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData);
728 else if (kvm.hasField(field))
729 data = to_utf8(kvm.getValueForField(field));
735 if (boost::regex_search(data, reg_exp))
736 foundKeys.push_back(*it);
738 catch (boost::regex_error &) {
739 return vector<docstring>();
746 Dialog * createGuiCitation(LyXView & lv) { return new GuiCitation(lv); }
749 } // namespace frontend
752 #include "GuiCitation_moc.cpp"