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 "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "LyXToolBox.h"
22 #include "qt_helpers.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "FuncRequest.h"
30 #include "insets/InsetCommand.h"
32 #include "support/debug.h"
33 #include "support/docstring.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #include <QCloseEvent>
48 #include "support/regex.h"
55 using namespace lyx::support;
61 // I am guessing that it would not hurt to make these private members.
62 static vector<string> citeCmds_;
63 static vector<CitationStyle> citeStyles_;
66 template<typename String>
67 static QStringList to_qstring_list(vector<String> const & v)
71 for (size_t i = 0; i != v.size(); ++i) {
74 qlist.append(lyx::toqstr(v[i]));
80 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
82 vector<lyx::docstring> v;
83 for (int i = 0; i != qlist.size(); ++i) {
84 if (qlist[i].isEmpty())
86 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
92 GuiCitation::GuiCitation(GuiView & lv)
93 : DialogView(lv, "citation", qt_("Citation")),
94 style_(0), params_(insetCode("citation"))
99 filter_ = new FancyLineEdit(this);
100 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
101 filter_->setButtonVisible(FancyLineEdit::Right, true);
102 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
103 filter_->setAutoHideButton(FancyLineEdit::Right, true);
104 filter_->setPlaceholderText(qt_("All avail. citations"));
106 filterBarL->addWidget(filter_, 0);
107 findKeysLA->setBuddy(filter_);
109 // Add search options as button menu
110 regexp_ = new QAction(qt_("Regular e&xpression"), this);
111 regexp_->setCheckable(true);
112 casesense_ = new QAction(qt_("Case se&nsitive"), this);
113 casesense_->setCheckable(true);
114 instant_ = new QAction(qt_("Search as you &type"), this);
115 instant_->setCheckable(true);
116 instant_->setChecked(true);
118 QMenu * searchOpts = new QMenu(this);
119 searchOpts->addAction(regexp_);
120 searchOpts->addAction(casesense_);
121 searchOpts->addAction(instant_);
122 searchOptionsPB->setMenu(searchOpts);
124 connect(citationStyleCO, SIGNAL(activated(int)),
125 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
126 connect(fulllistCB, SIGNAL(clicked()),
127 this, SLOT(changed()));
128 connect(forceuppercaseCB, SIGNAL(clicked()),
129 this, SLOT(changed()));
130 connect(textBeforeED, SIGNAL(textChanged(QString)),
131 this, SLOT(updateStyles()));
132 connect(textAfterED, SIGNAL(textChanged(QString)),
133 this, SLOT(updateStyles()));
134 connect(textBeforeED, SIGNAL(returnPressed()),
135 this, SLOT(on_okPB_clicked()));
136 connect(textAfterED, SIGNAL(returnPressed()),
137 this, SLOT(on_okPB_clicked()));
139 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
140 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
141 connect(selectionManager, SIGNAL(selectionChanged()),
142 this, SLOT(setCitedKeys()));
143 connect(selectionManager, SIGNAL(updateHook()),
144 this, SLOT(updateControls()));
145 connect(selectionManager, SIGNAL(okHook()),
146 this, SLOT(on_okPB_clicked()));
148 connect(filter_, SIGNAL(rightButtonClicked()),
149 this, SLOT(resetFilter()));
150 connect(filter_, SIGNAL(textEdited(QString)),
151 this, SLOT(filterChanged(QString)));
152 connect(filter_, SIGNAL(returnPressed()),
153 this, SLOT(filterPressed()));
154 connect(regexp_, SIGNAL(triggered()),
155 this, SLOT(regexChanged()));
156 connect(casesense_, SIGNAL(triggered()),
157 this, SLOT(caseChanged()));
158 connect(instant_, SIGNAL(triggered(bool)),
159 this, SLOT(instantChanged(bool)));
161 setFocusProxy(filter_);
165 GuiCitation::~GuiCitation()
167 delete selectionManager;
171 void GuiCitation::closeEvent(QCloseEvent * e)
174 DialogView::closeEvent(e);
178 void GuiCitation::applyView()
180 int const choice = max(0, citationStyleCO->currentIndex());
182 bool const full = fulllistCB->isChecked();
183 bool const force = forceuppercaseCB->isChecked();
185 QString const before = textBeforeED->text();
186 QString const after = textAfterED->text();
188 applyParams(choice, full, force, before, after);
192 void GuiCitation::showEvent(QShowEvent * e)
195 availableLV->setFocus();
196 DialogView::showEvent(e);
200 void GuiCitation::on_okPB_clicked()
208 void GuiCitation::on_cancelPB_clicked()
215 void GuiCitation::on_applyPB_clicked()
221 void GuiCitation::on_restorePB_clicked()
228 void GuiCitation::updateControls()
230 BiblioInfo const & bi = bibInfo();
235 // The main point of separating this out is that the fill*() methods
236 // called in update() do not need to be called for INTERNAL updates,
237 // such as when addPB is pressed, as the list of fields, entries, etc,
238 // will not have changed.
239 void GuiCitation::updateControls(BiblioInfo const & bi)
241 QModelIndex idx = selectionManager->getSelectedIndex();
243 selectionManager->update();
247 void GuiCitation::updateFormatting(CitationStyle currentStyle)
249 bool const force = currentStyle.forceUpperCase;
250 bool const full = currentStyle.fullAuthorList &&
251 documentBuffer().params().fullAuthorList();
252 bool const textbefore = currentStyle.textBefore;
253 bool const textafter = currentStyle.textAfter;
255 bool const haveSelection =
256 selectedLV->model()->rowCount() > 0;
258 forceuppercaseCB->setEnabled(force && haveSelection);
259 fulllistCB->setEnabled(full && haveSelection);
260 textBeforeED->setEnabled(textbefore && haveSelection);
261 textBeforeLA->setEnabled(textbefore && haveSelection);
262 textAfterED->setEnabled(textafter && haveSelection);
263 textAfterLA->setEnabled(textafter && haveSelection);
264 citationStyleCO->setEnabled(haveSelection);
265 citationStyleLA->setEnabled(haveSelection);
269 // Update the styles for the style combo, citationStyleCO, and mark the
270 // settings as changed. Called upon changing the cited keys (including
271 // merely reordering the keys) or editing the text before/after fields.
272 void GuiCitation::updateStyles()
274 BiblioInfo const & bi = bibInfo();
280 // Update the styles for the style combo, citationStyleCO.
281 void GuiCitation::updateStyles(BiblioInfo const & bi)
283 QStringList selected_keys = selected_model_.stringList();
284 int curr = selectedLV->model()->rowCount() - 1;
286 if (curr < 0 || selected_keys.empty()) {
287 citationStyleCO->clear();
288 citationStyleCO->setEnabled(false);
289 citationStyleLA->setEnabled(false);
293 static const size_t max_length = 80;
294 QStringList sty = citationStyles(bi, max_length);
298 citationStyleCO->setEnabled(false);
299 citationStyleLA->setEnabled(false);
300 citationStyleCO->clear();
304 citationStyleCO->blockSignals(true);
307 int const curindex = citationStyleCO->currentIndex();
308 int const oldIndex = (curindex < 0) ? style_ : curindex;
309 citationStyleCO->clear();
310 citationStyleCO->insertItems(0, sty);
311 citationStyleCO->setEnabled(true);
312 citationStyleLA->setEnabled(true);
314 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
315 citationStyleCO->setCurrentIndex(oldIndex);
317 citationStyleCO->blockSignals(false);
321 void GuiCitation::fillFields(BiblioInfo const & bi)
323 fieldsCO->blockSignals(true);
324 int const oldIndex = fieldsCO->currentIndex();
326 QStringList const fields = to_qstring_list(bi.getFields());
327 fieldsCO->insertItem(0, qt_("All fields"));
328 fieldsCO->insertItem(1, qt_("Keys"));
329 fieldsCO->insertItems(2, fields);
330 if (oldIndex != -1 && oldIndex < fieldsCO->count())
331 fieldsCO->setCurrentIndex(oldIndex);
332 fieldsCO->blockSignals(false);
336 void GuiCitation::fillEntries(BiblioInfo const & bi)
338 entriesCO->blockSignals(true);
339 int const oldIndex = entriesCO->currentIndex();
341 QStringList const entries = to_qstring_list(bi.getEntries());
342 entriesCO->insertItem(0, qt_("All entry types"));
343 entriesCO->insertItems(1, entries);
344 if (oldIndex != -1 && oldIndex < entriesCO->count())
345 entriesCO->setCurrentIndex(oldIndex);
346 entriesCO->blockSignals(false);
350 bool GuiCitation::isSelected(QModelIndex const & idx)
352 QString const str = idx.data().toString();
353 return selected_model_.stringList().contains(str);
357 void GuiCitation::setButtons()
359 int const srows = selectedLV->model()->rowCount();
360 applyPB->setEnabled(srows > 0);
361 okPB->setEnabled(srows > 0);
365 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
367 if (!idx.isValid() || bi.empty()) {
368 infoML->document()->clear();
369 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
373 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
374 QString const keytxt = toqstr(
375 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
376 infoML->document()->setHtml(keytxt);
380 void GuiCitation::findText(QString const & text, bool reset)
382 //"All Fields" and "Keys" are the first two
383 int index = fieldsCO->currentIndex() - 2;
384 BiblioInfo const & bi = bibInfo();
385 vector<docstring> const & fields = bi.getFields();
388 if (index <= -1 || index >= int(fields.size()))
389 //either "All Fields" or "Keys" or an invalid value
390 field = from_ascii("");
392 field = fields[index];
395 bool const onlyKeys = index == -1;
397 //"All Entry Types" is first.
398 index = entriesCO->currentIndex() - 1;
399 vector<docstring> const & entries = bi.getEntries();
400 docstring entry_type;
401 if (index < 0 || index >= int(entries.size()))
402 entry_type = from_ascii("");
404 entry_type = entries[index];
406 bool const case_sentitive = casesense_->isChecked();
407 bool const reg_exp = regexp_->isChecked();
409 findKey(bi, text, onlyKeys, field, entry_type,
410 case_sentitive, reg_exp, reset);
412 //It'd be nice to save and restore the current selection in
413 //availableLV. Currently, we get an automatic reset, since the
420 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
422 findText(filter_->text(), true);
426 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
428 findText(filter_->text(), true);
432 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
434 if (index >= 0 && index < citationStyleCO->count()) {
435 vector<CitationStyle> const & styles = citeStyles_;
436 updateFormatting(styles[index]);
442 void GuiCitation::filterChanged(const QString & text)
444 if (!text.isEmpty()) {
445 if (instant_->isChecked())
446 findText(filter_->text());
449 findText(filter_->text());
454 void GuiCitation::filterPressed()
456 findText(filter_->text(), true);
460 void GuiCitation::resetFilter()
462 filter_->setText(QString());
463 findText(filter_->text(), true);
467 void GuiCitation::caseChanged()
469 findText(filter_->text());
473 void GuiCitation::regexChanged()
475 findText(filter_->text());
479 void GuiCitation::updateFilterHint()
481 QString const hint = instant_->isChecked() ?
482 qt_("Enter string to filter the list of available citations") :
483 qt_("Enter string to filter the list of available citations and press <Enter>");
484 filter_->setToolTip(hint);
488 void GuiCitation::instantChanged(bool checked)
491 findText(filter_->text(), true);
497 void GuiCitation::changed()
503 void GuiCitation::applyParams(int const choice, bool full, bool force,
504 QString before, QString after)
506 if (cited_keys_.isEmpty())
509 vector<CitationStyle> const & styles = citeStyles_;
511 CitationStyle cs = styles[choice];
518 cs.forceUpperCase &= force;
519 cs.fullAuthorList &= full;
520 string const command = citationStyleToString(cs);
522 params_.setCmdName(command);
523 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
524 params_["before"] = qstring_to_ucs4(before);
525 params_["after"] = qstring_to_ucs4(after);
530 void GuiCitation::clearSelection()
533 selected_model_.setStringList(cited_keys_);
537 void GuiCitation::init()
539 // Make the list of all available bibliography keys
540 BiblioInfo const & bi = bibInfo();
541 all_keys_ = to_qstring_list(bi.getKeys());
542 available_model_.setStringList(all_keys_);
544 // Ditto for the keys cited in this inset
545 QString str = toqstr(params_["key"]);
549 cited_keys_ = str.split(",");
550 selected_model_.setStringList(cited_keys_);
552 // Initialize the drop downs
556 // Initialize the citation formatting
557 string const & cmd = params_.getCmdName();
558 CitationStyle const cs =
559 citationStyleFromString(cmd, documentBuffer().params());
560 forceuppercaseCB->setChecked(cs.forceUpperCase);
561 fulllistCB->setChecked(cs.fullAuthorList &&
562 documentBuffer().params().fullAuthorList());
563 textBeforeED->setText(toqstr(params_["before"]));
564 textAfterED->setText(toqstr(params_["after"]));
566 // Update the interface
569 if (selected_model_.rowCount()) {
570 selectedLV->blockSignals(true);
571 selectedLV->setFocus();
572 QModelIndex idx = selected_model_.index(0, 0);
573 selectedLV->selectionModel()->select(idx,
574 QItemSelectionModel::ClearAndSelect);
575 selectedLV->blockSignals(false);
577 // Find the citation style
578 vector<string> const & cmds = citeCmds_;
579 vector<string>::const_iterator cit =
580 std::find(cmds.begin(), cmds.end(), cs.name);
582 if (cit != cmds.end())
583 i = int(cit - cmds.begin());
585 // Set the style combo appropriately
586 citationStyleCO->blockSignals(true);
587 citationStyleCO->setCurrentIndex(i);
588 citationStyleCO->blockSignals(false);
589 updateFormatting(citeStyles_[i]);
591 availableLV->setFocus();
593 applyPB->setEnabled(false);
594 okPB->setEnabled(false);
598 void GuiCitation::findKey(BiblioInfo const & bi,
599 QString const & str, bool only_keys,
600 docstring field, docstring entry_type,
601 bool case_sensitive, bool reg_exp, bool reset)
604 // This should be moved to a class member.
605 // Used for optimisation: store last searched string.
606 static QString last_searched_string;
607 // Used to disable the above optimisation.
608 static bool last_case_sensitive;
609 static bool last_reg_exp;
610 // Reset last_searched_string in case of changed option.
611 if (last_case_sensitive != case_sensitive
612 || last_reg_exp != reg_exp) {
613 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
614 last_searched_string.clear();
616 // save option for next search.
617 last_case_sensitive = case_sensitive;
618 last_reg_exp = reg_exp;
620 Qt::CaseSensitivity qtcase = case_sensitive ?
621 Qt::CaseSensitive: Qt::CaseInsensitive;
623 // If new string (str) contains the last searched one...
625 !last_searched_string.isEmpty() &&
627 str.contains(last_searched_string, qtcase))
628 // ... then only search within already found list.
629 keys = available_model_.stringList();
631 // ... else search all keys.
633 // save searched string for next search.
634 last_searched_string = str;
638 // First, filter by entry_type, which will be faster than
639 // what follows, so we may get to do that on less.
640 vector<docstring> keyVector = to_docstring_vector(keys);
641 filterByEntryType(bi, keyVector, entry_type);
644 result = to_qstring_list(keyVector);
646 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
647 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
649 available_model_.setStringList(result);
653 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
655 docstring const before = qstring_to_ucs4(textBeforeED->text());
656 docstring const after = qstring_to_ucs4(textAfterED->text());
657 vector<docstring> const keys = to_docstring_vector(cited_keys_);
658 vector<CitationStyle> styles = citeStyles_;
659 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
660 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
661 before, after, from_utf8("dialog"), max_size);
662 return to_qstring_list(ret);
666 void GuiCitation::setCitedKeys()
668 cited_keys_ = selected_model_.stringList();
673 bool GuiCitation::initialiseParams(string const & data)
675 InsetCommand::string2params(data, params_);
676 citeCmds_ = documentBuffer().params().citeCommands();
677 citeStyles_ = documentBuffer().params().citeStyles();
683 void GuiCitation::clearParams()
689 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
690 vector<docstring> & keyVector, docstring entry_type)
692 if (entry_type.empty())
695 vector<docstring>::iterator it = keyVector.begin();
696 vector<docstring>::iterator end = keyVector.end();
698 vector<docstring> result;
699 for (; it != end; ++it) {
700 docstring const key = *it;
701 BiblioInfo::const_iterator cit = bi.find(key);
704 if (cit->second.entryType() == entry_type)
705 result.push_back(key);
711 // Escape special chars.
712 // All characters are literals except: '.|*?+(){}[]^$\'
713 // These characters are literals when preceded by a "\", which is done here
714 // @todo: This function should be moved to support, and then the test in tests
715 // should be moved there as well.
716 static docstring escape_special_chars(docstring const & expr)
718 // Search for all chars '.|*?+(){}[^$]\'
719 // Note that '[', ']', and '\' must be escaped.
720 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
722 // $& is an ECMAScript format expression that expands to all
723 // of the current match
724 #ifdef LYX_USE_STD_REGEX
725 // To prefix a matched expression with a single literal backslash, we
726 // need to escape it for the C++ compiler and use:
728 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
730 // A backslash in the format string starts an escape sequence in boost.
731 // Thus, to prefix a matched expression with a single literal backslash,
732 // we need to give two backslashes to the regex engine, and escape both
733 // for the C++ compiler and use:
735 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
740 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
741 vector<docstring> const & keys_to_search, bool only_keys,
742 docstring const & search_expression, docstring field,
743 bool case_sensitive, bool regex)
745 vector<docstring> foundKeys;
747 docstring expr = trim(search_expression);
752 // We must escape special chars in the search_expr so that
753 // it is treated as a simple string by lyx::regex.
754 expr = escape_special_chars(expr);
758 reg_exp.assign(to_utf8(expr), case_sensitive ?
759 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
760 } catch (lyx::regex_error const & e) {
761 // lyx::regex throws an exception if the regular expression is not
763 LYXERR(Debug::GUI, e.what());
764 return vector<docstring>();
767 vector<docstring>::const_iterator it = keys_to_search.begin();
768 vector<docstring>::const_iterator end = keys_to_search.end();
769 for (; it != end; ++it ) {
770 BiblioInfo::const_iterator info = bi.find(*it);
771 if (info == bi.end())
774 BibTeXInfo const & kvm = info->second;
778 else if (field.empty())
779 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
781 data = to_utf8(kvm[field]);
787 if (lyx::regex_search(data, reg_exp))
788 foundKeys.push_back(*it);
790 catch (lyx::regex_error const & e) {
791 LYXERR(Debug::GUI, e.what());
792 return vector<docstring>();
799 void GuiCitation::dispatchParams()
801 std::string const lfun = InsetCommand::params2string(params_);
802 dispatch(FuncRequest(getLfun(), lfun));
806 BiblioInfo const & GuiCitation::bibInfo() const
808 Buffer const & buf = documentBuffer();
809 buf.reloadBibInfoCache();
810 return buf.masterBibInfo();
814 void GuiCitation::saveSession() const
816 Dialog::saveSession();
819 sessionKey() + "/regex", regexp_->isChecked());
821 sessionKey() + "/casesensitive", casesense_->isChecked());
823 sessionKey() + "/autofind", instant_->isChecked());
825 sessionKey() + "/citestyle", style_);
829 void GuiCitation::restoreSession()
831 Dialog::restoreSession();
833 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
834 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
835 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
836 style_ = settings.value(sessionKey() + "/citestyle").toInt();
841 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
844 } // namespace frontend
847 #include "moc_GuiCitation.cpp"