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 params_(insetCode("citation"))
99 filter_ = new FancyLineEdit(this);
100 #if QT_VERSION >= 0x040600
101 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
102 filter_->setButtonVisible(FancyLineEdit::Right, true);
103 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
104 filter_->setAutoHideButton(FancyLineEdit::Right, true);
106 #if QT_VERSION >= 0x040700
107 filter_->setPlaceholderText(qt_("All avail. citations"));
110 filterBarL->addWidget(filter_, 0);
111 findKeysLA->setBuddy(filter_);
113 // Add search options as button menu
114 regexp_ = new QAction(qt_("Regular e&xpression"), this);
115 regexp_->setCheckable(true);
116 casesense_ = new QAction(qt_("Case se&nsitive"), this);
117 casesense_->setCheckable(true);
118 instant_ = new QAction(qt_("Search as you &type"), this);
119 instant_->setCheckable(true);
120 instant_->setChecked(true);
122 QMenu * searchOpts = new QMenu(this);
123 searchOpts->addAction(regexp_);
124 searchOpts->addAction(casesense_);
125 searchOpts->addAction(instant_);
126 searchOptionsPB->setMenu(searchOpts);
128 connect(citationStyleCO, SIGNAL(activated(int)),
129 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
130 connect(fulllistCB, SIGNAL(clicked()),
131 this, SLOT(changed()));
132 connect(forceuppercaseCB, SIGNAL(clicked()),
133 this, SLOT(changed()));
134 connect(textBeforeED, SIGNAL(textChanged(QString)),
135 this, SLOT(updateStyles()));
136 connect(textAfterED, SIGNAL(textChanged(QString)),
137 this, SLOT(updateStyles()));
138 connect(textBeforeED, SIGNAL(returnPressed()),
139 this, SLOT(on_okPB_clicked()));
140 connect(textAfterED, SIGNAL(returnPressed()),
141 this, SLOT(on_okPB_clicked()));
143 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
144 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
145 connect(selectionManager, SIGNAL(selectionChanged()),
146 this, SLOT(setCitedKeys()));
147 connect(selectionManager, SIGNAL(updateHook()),
148 this, SLOT(updateControls()));
149 connect(selectionManager, SIGNAL(okHook()),
150 this, SLOT(on_okPB_clicked()));
152 connect(filter_, SIGNAL(rightButtonClicked()),
153 this, SLOT(resetFilter()));
154 connect(filter_, SIGNAL(textEdited(QString)),
155 this, SLOT(filterChanged(QString)));
156 connect(filter_, SIGNAL(returnPressed()),
157 this, SLOT(filterPressed()));
158 connect(regexp_, SIGNAL(triggered()),
159 this, SLOT(regexChanged()));
160 connect(casesense_, SIGNAL(triggered()),
161 this, SLOT(caseChanged()));
162 connect(instant_, SIGNAL(triggered(bool)),
163 this, SLOT(instantChanged(bool)));
165 setFocusProxy(filter_);
169 GuiCitation::~GuiCitation()
171 delete selectionManager;
175 void GuiCitation::closeEvent(QCloseEvent * e)
178 DialogView::closeEvent(e);
182 void GuiCitation::applyView()
184 int const choice = max(0, citationStyleCO->currentIndex());
186 bool const full = fulllistCB->isChecked();
187 bool const force = forceuppercaseCB->isChecked();
189 QString const before = textBeforeED->text();
190 QString const after = textAfterED->text();
192 applyParams(choice, full, force, before, after);
196 void GuiCitation::showEvent(QShowEvent * e)
199 availableLV->setFocus();
200 DialogView::showEvent(e);
204 void GuiCitation::on_okPB_clicked()
212 void GuiCitation::on_cancelPB_clicked()
219 void GuiCitation::on_applyPB_clicked()
225 void GuiCitation::on_restorePB_clicked()
232 void GuiCitation::updateControls()
234 BiblioInfo const & bi = bibInfo();
239 // The main point of separating this out is that the fill*() methods
240 // called in update() do not need to be called for INTERNAL updates,
241 // such as when addPB is pressed, as the list of fields, entries, etc,
242 // will not have changed.
243 void GuiCitation::updateControls(BiblioInfo const & bi)
245 QModelIndex idx = selectionManager->getSelectedIndex();
247 int i = citationStyleCO->currentIndex();
250 updateFormatting(citeStyles_[i]);
251 selectionManager->update();
255 void GuiCitation::updateFormatting(CitationStyle currentStyle)
257 bool const force = currentStyle.forceUpperCase;
258 bool const full = currentStyle.fullAuthorList &&
259 documentBuffer().params().fullAuthorList();
260 bool const textbefore = currentStyle.textBefore;
261 bool const textafter = currentStyle.textAfter;
263 bool const haveSelection =
264 selectedLV->model()->rowCount() > 0;
266 forceuppercaseCB->setEnabled(force && haveSelection);
267 fulllistCB->setEnabled(full && haveSelection);
268 textBeforeED->setEnabled(textbefore && haveSelection);
269 textBeforeLA->setEnabled(textbefore && haveSelection);
270 textAfterED->setEnabled(textafter && haveSelection);
271 textAfterLA->setEnabled(textafter && haveSelection);
272 citationStyleCO->setEnabled(haveSelection);
273 citationStyleLA->setEnabled(haveSelection);
277 // Update the styles for the style combo, citationStyleCO, and mark the
278 // settings as changed. Called upon changing the cited keys (including
279 // merely reordering the keys) or editing the text before/after fields.
280 void GuiCitation::updateStyles()
282 BiblioInfo const & bi = bibInfo();
288 // Update the styles for the style combo, citationStyleCO.
289 void GuiCitation::updateStyles(BiblioInfo const & bi)
291 QStringList selected_keys = selected_model_.stringList();
292 int curr = selectedLV->model()->rowCount() - 1;
294 if (curr < 0 || selected_keys.empty()) {
295 citationStyleCO->clear();
296 citationStyleCO->setEnabled(false);
297 citationStyleLA->setEnabled(false);
301 static const size_t max_length = 80;
302 QStringList sty = citationStyles(bi, max_length);
306 citationStyleCO->setEnabled(false);
307 citationStyleLA->setEnabled(false);
308 citationStyleCO->clear();
312 citationStyleCO->blockSignals(true);
315 int const oldIndex = citationStyleCO->currentIndex();
316 citationStyleCO->clear();
317 citationStyleCO->insertItems(0, sty);
318 citationStyleCO->setEnabled(true);
319 citationStyleLA->setEnabled(true);
321 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
322 citationStyleCO->setCurrentIndex(oldIndex);
324 citationStyleCO->blockSignals(false);
328 void GuiCitation::fillFields(BiblioInfo const & bi)
330 fieldsCO->blockSignals(true);
331 int const oldIndex = fieldsCO->currentIndex();
333 QStringList const fields = to_qstring_list(bi.getFields());
334 fieldsCO->insertItem(0, qt_("All fields"));
335 fieldsCO->insertItem(1, qt_("Keys"));
336 fieldsCO->insertItems(2, fields);
337 if (oldIndex != -1 && oldIndex < fieldsCO->count())
338 fieldsCO->setCurrentIndex(oldIndex);
339 fieldsCO->blockSignals(false);
343 void GuiCitation::fillEntries(BiblioInfo const & bi)
345 entriesCO->blockSignals(true);
346 int const oldIndex = entriesCO->currentIndex();
348 QStringList const entries = to_qstring_list(bi.getEntries());
349 entriesCO->insertItem(0, qt_("All entry types"));
350 entriesCO->insertItems(1, entries);
351 if (oldIndex != -1 && oldIndex < entriesCO->count())
352 entriesCO->setCurrentIndex(oldIndex);
353 entriesCO->blockSignals(false);
357 bool GuiCitation::isSelected(QModelIndex const & idx)
359 QString const str = idx.data().toString();
360 return selected_model_.stringList().contains(str);
364 void GuiCitation::setButtons()
366 int const srows = selectedLV->model()->rowCount();
367 applyPB->setEnabled(srows > 0);
368 okPB->setEnabled(srows > 0);
372 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
374 if (!idx.isValid() || bi.empty()) {
375 infoML->document()->clear();
376 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
380 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
381 QString const keytxt = toqstr(
382 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
383 infoML->document()->setHtml(keytxt);
387 void GuiCitation::findText(QString const & text, bool reset)
389 //"All Fields" and "Keys" are the first two
390 int index = fieldsCO->currentIndex() - 2;
391 BiblioInfo const & bi = bibInfo();
392 vector<docstring> const & fields = bi.getFields();
395 if (index <= -1 || index >= int(fields.size()))
396 //either "All Fields" or "Keys" or an invalid value
397 field = from_ascii("");
399 field = fields[index];
402 bool const onlyKeys = index == -1;
404 //"All Entry Types" is first.
405 index = entriesCO->currentIndex() - 1;
406 vector<docstring> const & entries = bi.getEntries();
407 docstring entry_type;
408 if (index < 0 || index >= int(entries.size()))
409 entry_type = from_ascii("");
411 entry_type = entries[index];
413 bool const case_sentitive = casesense_->isChecked();
414 bool const reg_exp = regexp_->isChecked();
416 findKey(bi, text, onlyKeys, field, entry_type,
417 case_sentitive, reg_exp, reset);
419 //It'd be nice to save and restore the current selection in
420 //availableLV. Currently, we get an automatic reset, since the
427 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
429 findText(filter_->text(), true);
433 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
435 findText(filter_->text(), true);
439 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
441 if (index >= 0 && index < citationStyleCO->count()) {
442 vector<CitationStyle> const & styles = citeStyles_;
443 updateFormatting(styles[index]);
449 void GuiCitation::filterChanged(const QString & text)
451 if (!text.isEmpty()) {
452 if (instant_->isChecked())
453 findText(filter_->text());
456 findText(filter_->text());
461 void GuiCitation::filterPressed()
463 findText(filter_->text(), true);
467 void GuiCitation::resetFilter()
469 filter_->setText(QString());
470 findText(filter_->text(), true);
474 void GuiCitation::caseChanged()
476 findText(filter_->text());
480 void GuiCitation::regexChanged()
482 findText(filter_->text());
486 void GuiCitation::updateFilterHint()
488 QString const hint = instant_->isChecked() ?
489 qt_("Enter string to filter the list of available citations") :
490 qt_("Enter string to filter the list of available citations and press <Enter>");
491 filter_->setToolTip(hint);
495 void GuiCitation::instantChanged(bool checked)
498 findText(filter_->text(), true);
504 void GuiCitation::changed()
510 void GuiCitation::applyParams(int const choice, bool full, bool force,
511 QString before, QString after)
513 if (cited_keys_.isEmpty())
516 vector<CitationStyle> const & styles = citeStyles_;
518 CitationStyle cs = styles[choice];
525 cs.forceUpperCase &= force;
526 cs.fullAuthorList &= full;
527 string const command = citationStyleToString(cs);
529 params_.setCmdName(command);
530 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
531 params_["before"] = qstring_to_ucs4(before);
532 params_["after"] = qstring_to_ucs4(after);
537 void GuiCitation::clearSelection()
540 selected_model_.setStringList(cited_keys_);
544 void GuiCitation::init()
546 // Make the list of all available bibliography keys
547 BiblioInfo const & bi = bibInfo();
548 all_keys_ = to_qstring_list(bi.getKeys());
549 available_model_.setStringList(all_keys_);
551 // Ditto for the keys cited in this inset
552 QString str = toqstr(params_["key"]);
556 cited_keys_ = str.split(",");
557 selected_model_.setStringList(cited_keys_);
559 // Initialize the drop downs
563 // Initialize the citation formatting
564 string const & cmd = params_.getCmdName();
565 CitationStyle const cs = citationStyleFromString(cmd);
566 forceuppercaseCB->setChecked(cs.forceUpperCase);
567 fulllistCB->setChecked(cs.fullAuthorList &&
568 documentBuffer().params().fullAuthorList());
569 textBeforeED->setText(toqstr(params_["before"]));
570 textAfterED->setText(toqstr(params_["after"]));
572 // Update the interface
575 if (selected_model_.rowCount()) {
576 selectedLV->blockSignals(true);
577 selectedLV->setFocus();
578 QModelIndex idx = selected_model_.index(0, 0);
579 selectedLV->selectionModel()->select(idx,
580 QItemSelectionModel::ClearAndSelect);
581 selectedLV->blockSignals(false);
583 // Find the citation style
584 vector<string> const & cmds = citeCmds_;
585 vector<string>::const_iterator cit =
586 std::find(cmds.begin(), cmds.end(), cs.cmd);
588 if (cit != cmds.end())
589 i = int(cit - cmds.begin());
591 // Set the style combo appropriately
592 citationStyleCO->blockSignals(true);
593 citationStyleCO->setCurrentIndex(i);
594 citationStyleCO->blockSignals(false);
595 updateFormatting(citeStyles_[i]);
597 availableLV->setFocus();
599 applyPB->setEnabled(false);
600 okPB->setEnabled(false);
604 void GuiCitation::findKey(BiblioInfo const & bi,
605 QString const & str, bool only_keys,
606 docstring field, docstring entry_type,
607 bool case_sensitive, bool reg_exp, bool reset)
610 // Used for optimisation: store last searched string.
611 static QString last_searched_string;
612 // Used to disable the above optimisation.
613 static bool last_case_sensitive;
614 static bool last_reg_exp;
615 // Reset last_searched_string in case of changed option.
616 if (last_case_sensitive != case_sensitive
617 || last_reg_exp != reg_exp) {
618 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
619 last_searched_string.clear();
621 // save option for next search.
622 last_case_sensitive = case_sensitive;
623 last_reg_exp = reg_exp;
625 Qt::CaseSensitivity qtcase = case_sensitive ?
626 Qt::CaseSensitive: Qt::CaseInsensitive;
628 // If new string (str) contains the last searched one...
630 !last_searched_string.isEmpty() &&
632 str.contains(last_searched_string, qtcase))
633 // ... then only search within already found list.
634 keys = available_model_.stringList();
636 // ... else search all keys.
638 // save searched string for next search.
639 last_searched_string = str;
643 // First, filter by entry_type, which will be faster than
644 // what follows, so we may get to do that on less.
645 vector<docstring> keyVector = to_docstring_vector(keys);
646 filterByEntryType(bi, keyVector, entry_type);
649 result = to_qstring_list(keyVector);
651 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
652 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
654 available_model_.setStringList(result);
658 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
660 docstring const before = qstring_to_ucs4(textBeforeED->text());
661 docstring const after = qstring_to_ucs4(textAfterED->text());
662 vector<docstring> const keys = to_docstring_vector(cited_keys_);
663 vector<CitationStyle> styles = citeStyles_;
664 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
665 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
666 before, after, from_utf8("dialog"), max_size);
667 return to_qstring_list(ret);
671 void GuiCitation::setCitedKeys()
673 cited_keys_ = selected_model_.stringList();
678 bool GuiCitation::initialiseParams(string const & data)
680 InsetCommand::string2params(data, params_);
681 citeCmds_ = documentBuffer().params().citeCommands();
682 citeStyles_ = documentBuffer().params().citeStyles();
688 void GuiCitation::clearParams()
694 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
695 vector<docstring> & keyVector, docstring entry_type)
697 if (entry_type.empty())
700 vector<docstring>::iterator it = keyVector.begin();
701 vector<docstring>::iterator end = keyVector.end();
703 vector<docstring> result;
704 for (; it != end; ++it) {
705 docstring const key = *it;
706 BiblioInfo::const_iterator cit = bi.find(key);
709 if (cit->second.entryType() == entry_type)
710 result.push_back(key);
716 // Escape special chars.
717 // All characters are literals except: '.|*?+(){}[]^$\'
718 // These characters are literals when preceded by a "\", which is done here
719 // @todo: This function should be moved to support, and then the test in tests
720 // should be moved there as well.
721 static docstring escape_special_chars(docstring const & expr)
723 // Search for all chars '.|*?+(){}[^$]\'
724 // Note that '[', ']', and '\' must be escaped.
725 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
727 // $& is an ECMAScript format expression that expands to all
728 // of the current match
729 #if defined(LYX_USE_CXX11) && defined(LYX_USE_STD_REGEX)
730 // To prefix a matched expression with a single literal backslash, we
731 // need to escape it for the C++ compiler and use:
733 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
735 // A backslash in the format string starts an escape sequence in boost.
736 // Thus, to prefix a matched expression with a single literal backslash,
737 // we need to give two backslashes to the regex engine, and escape both
738 // for the C++ compiler and use:
740 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
745 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
746 vector<docstring> const & keys_to_search, bool only_keys,
747 docstring const & search_expression, docstring field,
748 bool case_sensitive, bool regex)
750 vector<docstring> foundKeys;
752 docstring expr = trim(search_expression);
757 // We must escape special chars in the search_expr so that
758 // it is treated as a simple string by lyx::regex.
759 expr = escape_special_chars(expr);
763 reg_exp.assign(to_utf8(expr), case_sensitive ?
764 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
765 } catch (lyx::regex_error const & e) {
766 // lyx::regex throws an exception if the regular expression is not
768 LYXERR(Debug::GUI, e.what());
769 return vector<docstring>();
772 vector<docstring>::const_iterator it = keys_to_search.begin();
773 vector<docstring>::const_iterator end = keys_to_search.end();
774 for (; it != end; ++it ) {
775 BiblioInfo::const_iterator info = bi.find(*it);
776 if (info == bi.end())
779 BibTeXInfo const & kvm = info->second;
783 else if (field.empty())
784 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
786 data = to_utf8(kvm[field]);
792 if (lyx::regex_search(data, reg_exp))
793 foundKeys.push_back(*it);
795 catch (lyx::regex_error const & e) {
796 LYXERR(Debug::GUI, e.what());
797 return vector<docstring>();
804 void GuiCitation::dispatchParams()
806 std::string const lfun = InsetCommand::params2string(params_);
807 dispatch(FuncRequest(getLfun(), lfun));
811 BiblioInfo const & GuiCitation::bibInfo() const
813 Buffer const & buf = documentBuffer();
814 buf.reloadBibInfoCache();
815 return buf.masterBibInfo();
819 void GuiCitation::saveSession(QSettings & settings) const
821 Dialog::saveSession(settings);
823 sessionKey() + "/regex", regexp_->isChecked());
825 sessionKey() + "/casesensitive", casesense_->isChecked());
827 sessionKey() + "/autofind", instant_->isChecked());
831 void GuiCitation::restoreSession()
833 Dialog::restoreSession();
835 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
836 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
837 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
842 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
845 } // namespace frontend
848 #include "moc_GuiCitation.cpp"