3 * \file GuiCitation.cpp
4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Angus Leeming
8 * \author Kalle Dalheimer
9 * \author Abdelrazak Younes
10 * \author Richard Heck
12 * Full author contact details are available in file CREDITS.
17 #include "GuiCitation.h"
19 #include "GuiSelectionManager.h"
20 #include "qt_helpers.h"
23 #include "BufferView.h"
24 #include "BiblioInfo.h"
25 #include "BufferParams.h"
26 #include "FuncRequest.h"
28 #include "insets/InsetCommand.h"
30 #include "support/debug.h"
31 #include "support/docstring.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
35 #include <QCloseEvent>
45 #include "support/regex.h"
52 using namespace lyx::support;
57 static vector<string> citeCmds_;
58 static vector<CitationStyle> citeStyles_;
61 template<typename String>
62 static QStringList to_qstring_list(vector<String> const & v)
66 for (size_t i = 0; i != v.size(); ++i) {
69 qlist.append(lyx::toqstr(v[i]));
75 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
77 vector<lyx::docstring> v;
78 for (int i = 0; i != qlist.size(); ++i) {
79 if (qlist[i].isEmpty())
81 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
87 GuiCitation::GuiCitation(GuiView & lv)
88 : DialogView(lv, "citation", qt_("Citation")),
89 params_(insetCode("citation"))
93 connect(citationStyleCO, SIGNAL(activated(int)),
94 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
95 connect(fulllistCB, SIGNAL(clicked()),
96 this, SLOT(changed()));
97 connect(forceuppercaseCB, SIGNAL(clicked()),
98 this, SLOT(changed()));
99 connect(textBeforeED, SIGNAL(textChanged(QString)),
100 this, SLOT(updateStyles()));
101 connect(textAfterED, SIGNAL(textChanged(QString)),
102 this, SLOT(updateStyles()));
103 connect(findLE, SIGNAL(returnPressed()),
104 this, SLOT(on_searchPB_clicked()));
105 connect(textBeforeED, SIGNAL(returnPressed()),
106 this, SLOT(on_okPB_clicked()));
107 connect(textAfterED, SIGNAL(returnPressed()),
108 this, SLOT(on_okPB_clicked()));
110 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
111 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
112 connect(selectionManager, SIGNAL(selectionChanged()),
113 this, SLOT(setCitedKeys()));
114 connect(selectionManager, SIGNAL(updateHook()),
115 this, SLOT(updateControls()));
116 connect(selectionManager, SIGNAL(okHook()),
117 this, SLOT(on_okPB_clicked()));
119 setFocusProxy(availableLV);
123 GuiCitation::~GuiCitation()
125 delete selectionManager;
129 void GuiCitation::closeEvent(QCloseEvent * e)
132 DialogView::closeEvent(e);
136 void GuiCitation::applyView()
138 int const choice = max(0, citationStyleCO->currentIndex());
140 bool const full = fulllistCB->isChecked();
141 bool const force = forceuppercaseCB->isChecked();
143 QString const before = textBeforeED->text();
144 QString const after = textAfterED->text();
146 apply(choice, full, force, before, after);
150 void GuiCitation::showEvent(QShowEvent * e)
153 availableLV->setFocus();
154 DialogView::showEvent(e);
158 void GuiCitation::on_okPB_clicked()
166 void GuiCitation::on_cancelPB_clicked()
173 void GuiCitation::on_applyPB_clicked()
179 void GuiCitation::on_restorePB_clicked()
185 void GuiCitation::updateControls()
187 BiblioInfo const & bi = bibInfo();
192 // The main point of separating this out is that the fill*() methods
193 // called in update() do not need to be called for INTERNAL updates,
194 // such as when addPB is pressed, as the list of fields, entries, etc,
195 // will not have changed.
196 void GuiCitation::updateControls(BiblioInfo const & bi)
198 QModelIndex idx = selectionManager->getSelectedIndex();
200 selectionManager->update();
204 void GuiCitation::updateFormatting(CitationStyle currentStyle)
206 bool const force = currentStyle.forceUpperCase;
207 bool const full = currentStyle.fullAuthorList &&
208 documentBuffer().params().fullAuthorList();
209 bool const textbefore = currentStyle.textBefore;
210 bool const textafter = currentStyle.textAfter;
212 bool const haveSelection =
213 selectedLV->model()->rowCount() > 0;
215 forceuppercaseCB->setEnabled(force && haveSelection);
216 fulllistCB->setEnabled(full && haveSelection);
217 textBeforeED->setEnabled(textbefore && haveSelection);
218 textBeforeLA->setEnabled(textbefore && haveSelection);
219 textAfterED->setEnabled(textafter && haveSelection);
220 textAfterLA->setEnabled(textafter && haveSelection);
221 citationStyleCO->setEnabled(haveSelection);
222 citationStyleLA->setEnabled(haveSelection);
226 // Update the styles for the style combo, citationStyleCO, and mark the
227 // settings as changed. Called upon changing the cited keys (including
228 // merely reordering the keys) or editing the text before/after fields.
229 void GuiCitation::updateStyles()
231 BiblioInfo const & bi = bibInfo();
237 // Update the styles for the style combo, citationStyleCO.
238 void GuiCitation::updateStyles(BiblioInfo const & bi)
240 QStringList selected_keys = selected_model_.stringList();
241 int curr = selectedLV->model()->rowCount() - 1;
243 if (curr < 0 || selected_keys.empty()) {
244 citationStyleCO->clear();
245 citationStyleCO->setEnabled(false);
246 citationStyleLA->setEnabled(false);
250 if (!selectedLV->selectionModel()->selectedIndexes().empty())
251 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
253 QStringList sty = citationStyles(bi);
257 citationStyleCO->setEnabled(false);
258 citationStyleLA->setEnabled(false);
259 citationStyleCO->clear();
263 citationStyleCO->blockSignals(true);
266 int const oldIndex = citationStyleCO->currentIndex();
267 citationStyleCO->clear();
268 citationStyleCO->insertItems(0, sty);
269 citationStyleCO->setEnabled(true);
270 citationStyleLA->setEnabled(true);
272 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
273 citationStyleCO->setCurrentIndex(oldIndex);
275 citationStyleCO->blockSignals(false);
279 void GuiCitation::fillFields(BiblioInfo const & bi)
281 fieldsCO->blockSignals(true);
282 int const oldIndex = fieldsCO->currentIndex();
284 QStringList const fields = to_qstring_list(bi.getFields());
285 fieldsCO->insertItem(0, qt_("All fields"));
286 fieldsCO->insertItem(1, qt_("Keys"));
287 fieldsCO->insertItems(2, fields);
288 if (oldIndex != -1 && oldIndex < fieldsCO->count())
289 fieldsCO->setCurrentIndex(oldIndex);
290 fieldsCO->blockSignals(false);
294 void GuiCitation::fillEntries(BiblioInfo const & bi)
296 entriesCO->blockSignals(true);
297 int const oldIndex = entriesCO->currentIndex();
299 QStringList const entries = to_qstring_list(bi.getEntries());
300 entriesCO->insertItem(0, qt_("All entry types"));
301 entriesCO->insertItems(1, entries);
302 if (oldIndex != -1 && oldIndex < entriesCO->count())
303 entriesCO->setCurrentIndex(oldIndex);
304 entriesCO->blockSignals(false);
308 bool GuiCitation::isSelected(QModelIndex const & idx)
310 QString const str = idx.data().toString();
311 return selected_model_.stringList().contains(str);
315 void GuiCitation::setButtons()
317 int const srows = selectedLV->model()->rowCount();
318 applyPB->setEnabled(srows > 0);
319 okPB->setEnabled(srows > 0);
323 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
325 if (!idx.isValid() || bi.empty()) {
326 infoML->document()->clear();
330 QString const keytxt = toqstr(
331 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
332 infoML->document()->setHtml(keytxt);
336 void GuiCitation::findText(QString const & text, bool reset)
338 //"All Fields" and "Keys" are the first two
339 int index = fieldsCO->currentIndex() - 2;
340 BiblioInfo const & bi = bibInfo();
341 vector<docstring> const & fields = bi.getFields();
344 if (index <= -1 || index >= int(fields.size()))
345 //either "All Fields" or "Keys" or an invalid value
346 field = from_ascii("");
348 field = fields[index];
351 bool const onlyKeys = index == -1;
353 //"All Entry Types" is first.
354 index = entriesCO->currentIndex() - 1;
355 vector<docstring> const & entries = bi.getEntries();
356 docstring entry_type;
357 if (index < 0 || index >= int(entries.size()))
358 entry_type = from_ascii("");
360 entry_type = entries[index];
362 bool const case_sentitive = caseCB->checkState();
363 bool const reg_exp = regexCB->checkState();
364 findKey(bi, text, onlyKeys, field, entry_type,
365 case_sentitive, reg_exp, reset);
367 //It'd be nice to save and restore the current selection in
368 //availableLV. Currently, we get an automatic reset, since the
375 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
377 findText(findLE->text(), true);
381 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
383 findText(findLE->text(), true);
387 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
389 if (index >= 0 && index < citationStyleCO->count()) {
390 vector<CitationStyle> const & styles = citeStyles_;
391 updateFormatting(styles[index]);
397 void GuiCitation::on_findLE_textChanged(const QString & text)
399 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
400 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
401 if (!text.isEmpty()) {
403 findText(findLE->text());
406 findText(findLE->text());
410 void GuiCitation::on_searchPB_clicked()
412 findText(findLE->text(), true);
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::on_asTypeCB_stateChanged(int)
430 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
431 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
433 findText(findLE->text(), true);
437 void GuiCitation::changed()
443 void GuiCitation::apply(int const choice, bool full, bool force,
444 QString before, QString after)
446 if (cited_keys_.isEmpty())
449 vector<CitationStyle> const & styles = citeStyles_;
451 CitationStyle cs = styles[choice];
458 cs.forceUpperCase &= force;
459 cs.fullAuthorList &= full;
460 string const command = citationStyleToString(cs);
462 params_.setCmdName(command);
463 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
464 params_["before"] = qstring_to_ucs4(before);
465 params_["after"] = qstring_to_ucs4(after);
470 void GuiCitation::clearSelection()
473 selected_model_.setStringList(cited_keys_);
477 void GuiCitation::init()
479 // Make the list of all available bibliography keys
480 BiblioInfo const & bi = bibInfo();
481 all_keys_ = to_qstring_list(bi.getKeys());
482 available_model_.setStringList(all_keys_);
484 // Ditto for the keys cited in this inset
485 QString str = toqstr(params_["key"]);
489 cited_keys_ = str.split(",");
490 selected_model_.setStringList(cited_keys_);
492 // Initialize the drop downs
496 // Initialize the citation formatting
497 string const & cmd = params_.getCmdName();
498 CitationStyle const cs = citationStyleFromString(cmd);
499 forceuppercaseCB->setChecked(cs.forceUpperCase);
500 fulllistCB->setChecked(cs.fullAuthorList &&
501 documentBuffer().params().fullAuthorList());
502 textBeforeED->setText(toqstr(params_["before"]));
503 textAfterED->setText(toqstr(params_["after"]));
505 // Update the interface
508 if (selected_model_.rowCount()) {
509 selectedLV->blockSignals(true);
510 selectedLV->setFocus();
511 QModelIndex idx = selected_model_.index(0, 0);
512 selectedLV->selectionModel()->select(idx,
513 QItemSelectionModel::ClearAndSelect);
514 selectedLV->blockSignals(false);
516 // Find the citation style
517 vector<string> const & cmds = citeCmds_;
518 vector<string>::const_iterator cit =
519 std::find(cmds.begin(), cmds.end(), cs.cmd);
521 if (cit != cmds.end())
522 i = int(cit - cmds.begin());
524 // Set the style combo appropriately
525 citationStyleCO->blockSignals(true);
526 citationStyleCO->setCurrentIndex(i);
527 citationStyleCO->blockSignals(false);
528 updateFormatting(citeStyles_[i]);
530 availableLV->setFocus();
532 applyPB->setEnabled(false);
533 okPB->setEnabled(false);
537 void GuiCitation::findKey(BiblioInfo const & bi,
538 QString const & str, bool only_keys,
539 docstring field, docstring entry_type,
540 bool case_sensitive, bool reg_exp, bool reset)
542 // Used for optimisation: store last searched string.
543 static QString last_searched_string;
544 // Used to disable the above optimisation.
545 static bool last_case_sensitive;
546 static bool last_reg_exp;
547 // Reset last_searched_string in case of changed option.
548 if (last_case_sensitive != case_sensitive
549 || last_reg_exp != reg_exp) {
550 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
551 last_searched_string.clear();
553 // save option for next search.
554 last_case_sensitive = case_sensitive;
555 last_reg_exp = reg_exp;
557 Qt::CaseSensitivity qtcase = case_sensitive ?
558 Qt::CaseSensitive: Qt::CaseInsensitive;
560 // If new string (str) contains the last searched one...
562 !last_searched_string.isEmpty() &&
564 str.contains(last_searched_string, qtcase))
565 // ... then only search within already found list.
566 keys = available_model_.stringList();
568 // ... else search all keys.
570 // save searched string for next search.
571 last_searched_string = str;
575 // First, filter by entry_type, which will be faster than
576 // what follows, so we may get to do that on less.
577 vector<docstring> keyVector = to_docstring_vector(keys);
578 filterByEntryType(bi, keyVector, entry_type);
581 result = to_qstring_list(keyVector);
583 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
584 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
586 available_model_.setStringList(result);
590 QStringList GuiCitation::citationStyles(BiblioInfo const & bi)
592 docstring const before = qstring_to_ucs4(textBeforeED->text());
593 docstring const after = qstring_to_ucs4(textAfterED->text());
594 vector<docstring> const keys = to_docstring_vector(cited_keys_);
595 vector<CitationStyle> styles = citeStyles_;
596 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
597 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
598 false, before, after, from_utf8("dialog"));
599 return to_qstring_list(ret);
603 void GuiCitation::setCitedKeys()
605 cited_keys_ = selected_model_.stringList();
610 bool GuiCitation::initialiseParams(string const & data)
612 InsetCommand::string2params(data, params_);
613 citeCmds_ = documentBuffer().params().citeCommands();
614 citeStyles_ = documentBuffer().params().citeStyles();
620 void GuiCitation::clearParams()
626 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
627 vector<docstring> & keyVector, docstring entry_type)
629 if (entry_type.empty())
632 vector<docstring>::iterator it = keyVector.begin();
633 vector<docstring>::iterator end = keyVector.end();
635 vector<docstring> result;
636 for (; it != end; ++it) {
637 docstring const key = *it;
638 BiblioInfo::const_iterator cit = bi.find(key);
641 if (cit->second.entryType() == entry_type)
642 result.push_back(key);
648 // Escape special chars.
649 // All characters are literals except: '.|*?+(){}[]^$\'
650 // These characters are literals when preceded by a "\", which is done here
651 // @todo: This function should be moved to support, and then the test in tests
652 // should be moved there as well.
653 static docstring escape_special_chars(docstring const & expr)
655 // Search for all chars '.|*?+(){}[^$]\'
656 // Note that '[' and '\' must be escaped.
657 // This is a limitation of lyx::regex, but all other chars in BREs
658 // are assumed literal.
659 static const lyx::regex reg("[].|*?+(){}^$\\[\\\\]");
661 // $& is a perl-like expression that expands to all
662 // of the current match
663 // The '$' must be prefixed with the escape character '\' for
664 // boost to treat it as a literal.
665 // Thus, to prefix a matched expression with '\', we use:
667 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
671 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
672 vector<docstring> const & keys_to_search, bool only_keys,
673 docstring const & search_expression, docstring field,
674 bool case_sensitive, bool regex)
676 vector<docstring> foundKeys;
678 docstring expr = trim(search_expression);
683 // We must escape special chars in the search_expr so that
684 // it is treated as a simple string by lyx::regex.
685 expr = escape_special_chars(expr);
689 reg_exp.assign(to_utf8(expr), case_sensitive ?
690 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
691 } catch (lyx::regex_error & e) {
692 // lyx::regex throws an exception if the regular expression is not
694 LYXERR(Debug::GUI, e.what());
695 return vector<docstring>();
698 vector<docstring>::const_iterator it = keys_to_search.begin();
699 vector<docstring>::const_iterator end = keys_to_search.end();
700 for (; it != end; ++it ) {
701 BiblioInfo::const_iterator info = bi.find(*it);
702 if (info == bi.end())
705 BibTeXInfo const & kvm = info->second;
709 else if (field.empty())
710 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
712 data = to_utf8(kvm[field]);
718 if (lyx::regex_search(data, reg_exp))
719 foundKeys.push_back(*it);
721 catch (lyx::regex_error & e) {
722 LYXERR(Debug::GUI, e.what());
723 return vector<docstring>();
730 void GuiCitation::dispatchParams()
732 std::string const lfun = InsetCommand::params2string(params_);
733 dispatch(FuncRequest(getLfun(), lfun));
737 BiblioInfo const & GuiCitation::bibInfo() const
739 Buffer const & buf = documentBuffer();
740 buf.reloadBibInfoCache();
741 return buf.masterBibInfo();
745 void GuiCitation::saveSession() const
747 Dialog::saveSession();
750 sessionKey() + "/regex", regexCB->isChecked());
752 sessionKey() + "/casesensitive", caseCB->isChecked());
754 sessionKey() + "/autofind", asTypeCB->isChecked());
758 void GuiCitation::restoreSession()
760 Dialog::restoreSession();
763 settings.value(sessionKey() + "/regex").toBool());
765 settings.value(sessionKey() + "/casesensitive").toBool());
766 asTypeCB->setChecked(
767 settings.value(sessionKey() + "/autofind").toBool());
771 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
774 } // namespace frontend
777 #include "moc_GuiCitation.cpp"