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>
36 #include <boost/regex.hpp>
49 static vector<biblio::CiteStyle> citeStyles_;
52 template<typename String>
53 static QStringList to_qstring_list(vector<String> const & v)
57 for (size_t i = 0; i != v.size(); ++i) {
60 qlist.append(lyx::toqstr(v[i]));
66 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
68 vector<lyx::docstring> v;
69 for (int i = 0; i != qlist.size(); ++i) {
70 if (qlist[i].isEmpty())
72 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
78 GuiCitation::GuiCitation(GuiView & lv)
79 : GuiCommand(lv, "citation")
82 setViewTitle(_("Citation"));
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!");
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 InsetCommandMailer::string2params(lfun_name_, data, params_);
591 biblio::CiteEngine const engine = buffer().params().getEngine();
593 bool use_styles = engine != biblio::ENGINE_BASIC;
595 bibkeysInfo_.fillWithBibKeys(&buffer());
597 if (citeStyles_.empty())
598 citeStyles_ = biblio::getCiteStyles(engine);
600 if ((use_styles && citeStyles_.size() == 1) ||
601 (!use_styles && citeStyles_.size() != 1))
602 citeStyles_ = biblio::getCiteStyles(engine);
609 void GuiCitation::clearParams()
612 bibkeysInfo_.clear();
616 vector<docstring> const GuiCitation::availableKeys() const
618 return bibkeysInfo_.getKeys();
622 vector<docstring> const GuiCitation::availableFields() const
624 return bibkeysInfo_.getFields();
628 vector<docstring> const GuiCitation::availableEntries() const
630 return bibkeysInfo_.getEntries();
634 void GuiCitation::filterByEntryType(
635 vector<docstring> & keyVector, docstring entryType)
637 if (entryType.empty())
640 vector<docstring>::iterator it = keyVector.begin();
641 vector<docstring>::iterator end = keyVector.end();
643 vector<docstring> result;
644 for (; it != end; ++it) {
645 docstring const key = *it;
646 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
647 if (cit == bibkeysInfo_.end())
649 if (cit->second.entryType == entryType)
650 result.push_back(key);
656 biblio::CiteEngine GuiCitation::getEngine() const
658 return buffer().params().getEngine();
662 docstring GuiCitation::getInfo(docstring const & key) const
664 if (bibkeysInfo_.empty())
667 return bibkeysInfo_.getInfo(key);
671 // Escape special chars.
672 // All characters are literals except: '.|*?+(){}[]^$\'
673 // These characters are literals when preceded by a "\", which is done here
674 // @todo: This function should be moved to support, and then the test in tests
675 // should be moved there as well.
676 static docstring escape_special_chars(docstring const & expr)
678 // Search for all chars '.|*?+(){}[^$]\'
679 // Note that '[' and '\' must be escaped.
680 // This is a limitation of boost::regex, but all other chars in BREs
681 // are assumed literal.
682 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
684 // $& is a perl-like expression that expands to all
685 // of the current match
686 // The '$' must be prefixed with the escape character '\' for
687 // boost to treat it as a literal.
688 // Thus, to prefix a matched expression with '\', we use:
690 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
694 vector<docstring> GuiCitation::searchKeys(
695 vector<docstring> const & keys_to_search, bool only_keys,
696 docstring const & search_expression, docstring field,
697 bool case_sensitive, bool regex)
699 vector<docstring> foundKeys;
701 docstring expr = support::trim(search_expression);
706 // We must escape special chars in the search_expr so that
707 // it is treated as a simple string by boost::regex.
708 expr = escape_special_chars(expr);
710 boost::regex reg_exp(to_utf8(expr), case_sensitive ?
711 boost::regex_constants::normal : boost::regex_constants::icase);
713 vector<docstring>::const_iterator it = keys_to_search.begin();
714 vector<docstring>::const_iterator end = keys_to_search.end();
715 for (; it != end; ++it ) {
716 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
717 if (info == bibkeysInfo_.end())
720 BibTeXInfo const & kvm = info->second;
724 else if (field.empty())
725 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData);
726 else if (kvm.hasField(field))
727 data = to_utf8(kvm.getValueForField(field));
733 if (boost::regex_search(data, reg_exp))
734 foundKeys.push_back(*it);
736 catch (boost::regex_error &) {
737 return vector<docstring>();
744 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
747 } // namespace frontend
750 #include "GuiCitation_moc.cpp"