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 #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);
121 QMenu * searchOpts = new QMenu(this);
122 searchOpts->addAction(regexp_);
123 searchOpts->addAction(casesense_);
124 searchOpts->addAction(instant_);
125 searchOptionsPB->setMenu(searchOpts);
127 connect(citationStyleCO, SIGNAL(activated(int)),
128 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
129 connect(fulllistCB, SIGNAL(clicked()),
130 this, SLOT(changed()));
131 connect(forceuppercaseCB, SIGNAL(clicked()),
132 this, SLOT(changed()));
133 connect(textBeforeED, SIGNAL(textChanged(QString)),
134 this, SLOT(updateStyles()));
135 connect(textAfterED, SIGNAL(textChanged(QString)),
136 this, SLOT(updateStyles()));
137 connect(textBeforeED, SIGNAL(returnPressed()),
138 this, SLOT(on_okPB_clicked()));
139 connect(textAfterED, SIGNAL(returnPressed()),
140 this, SLOT(on_okPB_clicked()));
142 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
143 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
144 connect(selectionManager, SIGNAL(selectionChanged()),
145 this, SLOT(setCitedKeys()));
146 connect(selectionManager, SIGNAL(updateHook()),
147 this, SLOT(updateControls()));
148 connect(selectionManager, SIGNAL(okHook()),
149 this, SLOT(on_okPB_clicked()));
151 connect(filter_, SIGNAL(rightButtonClicked()),
152 this, SLOT(resetFilter()));
153 connect(filter_, SIGNAL(textEdited(QString)),
154 this, SLOT(filterChanged(QString)));
155 connect(filter_, SIGNAL(returnPressed()),
156 this, SLOT(filterPressed()));
157 connect(regexp_, SIGNAL(triggered()),
158 this, SLOT(regexChanged()));
159 connect(casesense_, SIGNAL(triggered()),
160 this, SLOT(caseChanged()));
161 connect(instant_, SIGNAL(triggered(bool)),
162 this, SLOT(instantChanged(bool)));
164 setFocusProxy(filter_);
168 GuiCitation::~GuiCitation()
170 delete selectionManager;
174 void GuiCitation::closeEvent(QCloseEvent * e)
177 DialogView::closeEvent(e);
181 void GuiCitation::applyView()
183 int const choice = max(0, citationStyleCO->currentIndex());
185 bool const full = fulllistCB->isChecked();
186 bool const force = forceuppercaseCB->isChecked();
188 QString const before = textBeforeED->text();
189 QString const after = textAfterED->text();
191 applyParams(choice, full, force, before, after);
195 void GuiCitation::showEvent(QShowEvent * e)
198 availableLV->setFocus();
199 DialogView::showEvent(e);
203 void GuiCitation::on_okPB_clicked()
211 void GuiCitation::on_cancelPB_clicked()
218 void GuiCitation::on_applyPB_clicked()
224 void GuiCitation::on_restorePB_clicked()
231 void GuiCitation::updateControls()
233 BiblioInfo const & bi = bibInfo();
238 // The main point of separating this out is that the fill*() methods
239 // called in update() do not need to be called for INTERNAL updates,
240 // such as when addPB is pressed, as the list of fields, entries, etc,
241 // will not have changed.
242 void GuiCitation::updateControls(BiblioInfo const & bi)
244 QModelIndex idx = selectionManager->getSelectedIndex();
246 selectionManager->update();
250 void GuiCitation::updateFormatting(CitationStyle currentStyle)
252 bool const force = currentStyle.forceUpperCase;
253 bool const full = currentStyle.fullAuthorList &&
254 documentBuffer().params().fullAuthorList();
255 bool const textbefore = currentStyle.textBefore;
256 bool const textafter = currentStyle.textAfter;
258 bool const haveSelection =
259 selectedLV->model()->rowCount() > 0;
261 forceuppercaseCB->setEnabled(force && haveSelection);
262 fulllistCB->setEnabled(full && haveSelection);
263 textBeforeED->setEnabled(textbefore && haveSelection);
264 textBeforeLA->setEnabled(textbefore && haveSelection);
265 textAfterED->setEnabled(textafter && haveSelection);
266 textAfterLA->setEnabled(textafter && haveSelection);
267 citationStyleCO->setEnabled(haveSelection);
268 citationStyleLA->setEnabled(haveSelection);
272 // Update the styles for the style combo, citationStyleCO, and mark the
273 // settings as changed. Called upon changing the cited keys (including
274 // merely reordering the keys) or editing the text before/after fields.
275 void GuiCitation::updateStyles()
277 BiblioInfo const & bi = bibInfo();
283 // Update the styles for the style combo, citationStyleCO.
284 void GuiCitation::updateStyles(BiblioInfo const & bi)
286 QStringList selected_keys = selected_model_.stringList();
287 int curr = selectedLV->model()->rowCount() - 1;
289 if (curr < 0 || selected_keys.empty()) {
290 citationStyleCO->clear();
291 citationStyleCO->setEnabled(false);
292 citationStyleLA->setEnabled(false);
296 static const size_t max_length = 80;
297 QStringList sty = citationStyles(bi, max_length);
301 citationStyleCO->setEnabled(false);
302 citationStyleLA->setEnabled(false);
303 citationStyleCO->clear();
307 citationStyleCO->blockSignals(true);
310 int const oldIndex = citationStyleCO->currentIndex();
311 citationStyleCO->clear();
312 citationStyleCO->insertItems(0, sty);
313 citationStyleCO->setEnabled(true);
314 citationStyleLA->setEnabled(true);
316 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
317 citationStyleCO->setCurrentIndex(oldIndex);
319 citationStyleCO->blockSignals(false);
323 void GuiCitation::fillFields(BiblioInfo const & bi)
325 fieldsCO->blockSignals(true);
326 int const oldIndex = fieldsCO->currentIndex();
328 QStringList const fields = to_qstring_list(bi.getFields());
329 fieldsCO->insertItem(0, qt_("All fields"));
330 fieldsCO->insertItem(1, qt_("Keys"));
331 fieldsCO->insertItems(2, fields);
332 if (oldIndex != -1 && oldIndex < fieldsCO->count())
333 fieldsCO->setCurrentIndex(oldIndex);
334 fieldsCO->blockSignals(false);
338 void GuiCitation::fillEntries(BiblioInfo const & bi)
340 entriesCO->blockSignals(true);
341 int const oldIndex = entriesCO->currentIndex();
343 QStringList const entries = to_qstring_list(bi.getEntries());
344 entriesCO->insertItem(0, qt_("All entry types"));
345 entriesCO->insertItems(1, entries);
346 if (oldIndex != -1 && oldIndex < entriesCO->count())
347 entriesCO->setCurrentIndex(oldIndex);
348 entriesCO->blockSignals(false);
352 bool GuiCitation::isSelected(QModelIndex const & idx)
354 QString const str = idx.data().toString();
355 return selected_model_.stringList().contains(str);
359 void GuiCitation::setButtons()
361 int const srows = selectedLV->model()->rowCount();
362 applyPB->setEnabled(srows > 0);
363 okPB->setEnabled(srows > 0);
367 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
369 if (!idx.isValid() || bi.empty()) {
370 infoML->document()->clear();
371 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
375 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
376 QString const keytxt = toqstr(
377 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
378 infoML->document()->setHtml(keytxt);
382 void GuiCitation::findText(QString const & text, bool reset)
384 //"All Fields" and "Keys" are the first two
385 int index = fieldsCO->currentIndex() - 2;
386 BiblioInfo const & bi = bibInfo();
387 vector<docstring> const & fields = bi.getFields();
390 if (index <= -1 || index >= int(fields.size()))
391 //either "All Fields" or "Keys" or an invalid value
392 field = from_ascii("");
394 field = fields[index];
397 bool const onlyKeys = index == -1;
399 //"All Entry Types" is first.
400 index = entriesCO->currentIndex() - 1;
401 vector<docstring> const & entries = bi.getEntries();
402 docstring entry_type;
403 if (index < 0 || index >= int(entries.size()))
404 entry_type = from_ascii("");
406 entry_type = entries[index];
408 bool const case_sentitive = casesense_->isChecked();
409 bool const reg_exp = regexp_->isChecked();
411 findKey(bi, text, onlyKeys, field, entry_type,
412 case_sentitive, reg_exp, reset);
414 //It'd be nice to save and restore the current selection in
415 //availableLV. Currently, we get an automatic reset, since the
422 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
424 findText(filter_->text(), true);
428 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
430 findText(filter_->text(), true);
434 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
436 if (index >= 0 && index < citationStyleCO->count()) {
437 vector<CitationStyle> const & styles = citeStyles_;
438 updateFormatting(styles[index]);
444 void GuiCitation::filterChanged(const QString & text)
446 if (!text.isEmpty()) {
447 if (instant_->isChecked())
448 findText(filter_->text());
451 findText(filter_->text());
456 void GuiCitation::filterPressed()
458 findText(filter_->text(), true);
462 void GuiCitation::resetFilter()
464 filter_->setText(QString());
465 findText(filter_->text(), true);
469 void GuiCitation::caseChanged()
471 findText(filter_->text());
475 void GuiCitation::regexChanged()
477 findText(filter_->text());
481 void GuiCitation::updateFilterHint()
483 QString const hint = instant_->isChecked() ?
484 qt_("Enter string to filter the list of available citations") :
485 qt_("Enter string to filter the list of available citations and press <Enter>");
486 filter_->setToolTip(hint);
490 void GuiCitation::instantChanged(bool checked)
493 findText(filter_->text(), true);
499 void GuiCitation::changed()
505 void GuiCitation::applyParams(int const choice, bool full, bool force,
506 QString before, QString after)
508 if (cited_keys_.isEmpty())
511 vector<CitationStyle> const & styles = citeStyles_;
513 CitationStyle cs = styles[choice];
520 cs.forceUpperCase &= force;
521 cs.fullAuthorList &= full;
522 string const command = citationStyleToString(cs);
524 params_.setCmdName(command);
525 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
526 params_["before"] = qstring_to_ucs4(before);
527 params_["after"] = qstring_to_ucs4(after);
532 void GuiCitation::clearSelection()
535 selected_model_.setStringList(cited_keys_);
539 void GuiCitation::init()
541 // Make the list of all available bibliography keys
542 BiblioInfo const & bi = bibInfo();
543 all_keys_ = to_qstring_list(bi.getKeys());
544 available_model_.setStringList(all_keys_);
546 // Ditto for the keys cited in this inset
547 QString str = toqstr(params_["key"]);
551 cited_keys_ = str.split(",");
552 selected_model_.setStringList(cited_keys_);
554 // Initialize the drop downs
558 // Initialize the citation formatting
559 string const & cmd = params_.getCmdName();
560 CitationStyle const cs = citationStyleFromString(cmd);
561 forceuppercaseCB->setChecked(cs.forceUpperCase);
562 fulllistCB->setChecked(cs.fullAuthorList &&
563 documentBuffer().params().fullAuthorList());
564 textBeforeED->setText(toqstr(params_["before"]));
565 textAfterED->setText(toqstr(params_["after"]));
567 // Update the interface
570 if (selected_model_.rowCount()) {
571 selectedLV->blockSignals(true);
572 selectedLV->setFocus();
573 QModelIndex idx = selected_model_.index(0, 0);
574 selectedLV->selectionModel()->select(idx,
575 QItemSelectionModel::ClearAndSelect);
576 selectedLV->blockSignals(false);
578 // Find the citation style
579 vector<string> const & cmds = citeCmds_;
580 vector<string>::const_iterator cit =
581 std::find(cmds.begin(), cmds.end(), cs.cmd);
583 if (cit != cmds.end())
584 i = int(cit - cmds.begin());
586 // Set the style combo appropriately
587 citationStyleCO->blockSignals(true);
588 citationStyleCO->setCurrentIndex(i);
589 citationStyleCO->blockSignals(false);
590 updateFormatting(citeStyles_[i]);
592 availableLV->setFocus();
594 applyPB->setEnabled(false);
595 okPB->setEnabled(false);
599 void GuiCitation::findKey(BiblioInfo const & bi,
600 QString const & str, bool only_keys,
601 docstring field, docstring entry_type,
602 bool case_sensitive, bool reg_exp, bool reset)
605 // This should be moved to a class member.
606 // Used for optimisation: store last searched string.
607 static QString last_searched_string;
608 // Used to disable the above optimisation.
609 static bool last_case_sensitive;
610 static bool last_reg_exp;
611 // Reset last_searched_string in case of changed option.
612 if (last_case_sensitive != case_sensitive
613 || last_reg_exp != reg_exp) {
614 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
615 last_searched_string.clear();
617 // save option for next search.
618 last_case_sensitive = case_sensitive;
619 last_reg_exp = reg_exp;
621 Qt::CaseSensitivity qtcase = case_sensitive ?
622 Qt::CaseSensitive: Qt::CaseInsensitive;
624 // If new string (str) contains the last searched one...
626 !last_searched_string.isEmpty() &&
628 str.contains(last_searched_string, qtcase))
629 // ... then only search within already found list.
630 keys = available_model_.stringList();
632 // ... else search all keys.
634 // save searched string for next search.
635 last_searched_string = str;
639 // First, filter by entry_type, which will be faster than
640 // what follows, so we may get to do that on less.
641 vector<docstring> keyVector = to_docstring_vector(keys);
642 filterByEntryType(bi, keyVector, entry_type);
645 result = to_qstring_list(keyVector);
647 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
648 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
650 available_model_.setStringList(result);
654 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
656 docstring const before = qstring_to_ucs4(textBeforeED->text());
657 docstring const after = qstring_to_ucs4(textAfterED->text());
658 vector<docstring> const keys = to_docstring_vector(cited_keys_);
659 vector<CitationStyle> styles = citeStyles_;
660 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
661 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
662 before, after, from_utf8("dialog"), max_size);
663 return to_qstring_list(ret);
667 void GuiCitation::setCitedKeys()
669 cited_keys_ = selected_model_.stringList();
674 bool GuiCitation::initialiseParams(string const & data)
676 InsetCommand::string2params(data, params_);
677 citeCmds_ = documentBuffer().params().citeCommands();
678 citeStyles_ = documentBuffer().params().citeStyles();
684 void GuiCitation::clearParams()
690 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
691 vector<docstring> & keyVector, docstring entry_type)
693 if (entry_type.empty())
696 vector<docstring>::iterator it = keyVector.begin();
697 vector<docstring>::iterator end = keyVector.end();
699 vector<docstring> result;
700 for (; it != end; ++it) {
701 docstring const key = *it;
702 BiblioInfo::const_iterator cit = bi.find(key);
705 if (cit->second.entryType() == entry_type)
706 result.push_back(key);
712 // Escape special chars.
713 // All characters are literals except: '.|*?+(){}[]^$\'
714 // These characters are literals when preceded by a "\", which is done here
715 // @todo: This function should be moved to support, and then the test in tests
716 // should be moved there as well.
717 static docstring escape_special_chars(docstring const & expr)
719 // Search for all chars '.|*?+(){}[^$]\'
720 // Note that '[', ']', and '\' must be escaped.
721 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
723 // $& is an ECMAScript format expression that expands to all
724 // of the current match
725 #ifdef LYX_USE_STD_REGEX
726 // To prefix a matched expression with a single literal backslash, we
727 // need to escape it for the C++ compiler and use:
729 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
731 // A backslash in the format string starts an escape sequence in boost.
732 // Thus, to prefix a matched expression with a single literal backslash,
733 // we need to give two backslashes to the regex engine, and escape both
734 // for the C++ compiler and use:
736 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
741 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
742 vector<docstring> const & keys_to_search, bool only_keys,
743 docstring const & search_expression, docstring field,
744 bool case_sensitive, bool regex)
746 vector<docstring> foundKeys;
748 docstring expr = trim(search_expression);
753 // We must escape special chars in the search_expr so that
754 // it is treated as a simple string by lyx::regex.
755 expr = escape_special_chars(expr);
759 reg_exp.assign(to_utf8(expr), case_sensitive ?
760 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
761 } catch (lyx::regex_error const & e) {
762 // lyx::regex throws an exception if the regular expression is not
764 LYXERR(Debug::GUI, e.what());
765 return vector<docstring>();
768 vector<docstring>::const_iterator it = keys_to_search.begin();
769 vector<docstring>::const_iterator end = keys_to_search.end();
770 for (; it != end; ++it ) {
771 BiblioInfo::const_iterator info = bi.find(*it);
772 if (info == bi.end())
775 BibTeXInfo const & kvm = info->second;
779 else if (field.empty())
780 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
782 data = to_utf8(kvm[field]);
788 if (lyx::regex_search(data, reg_exp))
789 foundKeys.push_back(*it);
791 catch (lyx::regex_error const & e) {
792 LYXERR(Debug::GUI, e.what());
793 return vector<docstring>();
800 void GuiCitation::dispatchParams()
802 std::string const lfun = InsetCommand::params2string(params_);
803 dispatch(FuncRequest(getLfun(), lfun));
807 BiblioInfo const & GuiCitation::bibInfo() const
809 Buffer const & buf = documentBuffer();
810 buf.reloadBibInfoCache();
811 return buf.masterBibInfo();
815 void GuiCitation::saveSession() const
817 Dialog::saveSession();
820 sessionKey() + "/regex", regexp_->isChecked());
822 sessionKey() + "/casesensitive", casesense_->isChecked());
824 sessionKey() + "/autofind", instant_->isChecked());
828 void GuiCitation::restoreSession()
830 Dialog::restoreSession();
832 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
833 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
834 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
839 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
842 } // namespace frontend
845 #include "moc_GuiCitation.cpp"