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 "LyXToolBox.h"
21 #include "qt_helpers.h"
24 #include "BufferView.h"
25 #include "BiblioInfo.h"
26 #include "BufferParams.h"
27 #include "FuncRequest.h"
29 #include "insets/InsetCommand.h"
31 #include "support/debug.h"
32 #include "support/docstring.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
36 #include <QCloseEvent>
46 #include "support/regex.h"
53 using namespace lyx::support;
59 // I am guessing that it would not hurt to make these private members.
60 static vector<string> citeCmds_;
61 static vector<CitationStyle> citeStyles_;
64 template<typename String>
65 static QStringList to_qstring_list(vector<String> const & v)
69 for (size_t i = 0; i != v.size(); ++i) {
72 qlist.append(lyx::toqstr(v[i]));
78 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
80 vector<lyx::docstring> v;
81 for (int i = 0; i != qlist.size(); ++i) {
82 if (qlist[i].isEmpty())
84 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
90 GuiCitation::GuiCitation(GuiView & lv)
91 : DialogView(lv, "citation", qt_("Citation")),
92 params_(insetCode("citation"))
96 connect(citationStyleCO, SIGNAL(activated(int)),
97 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
98 connect(fulllistCB, SIGNAL(clicked()),
99 this, SLOT(changed()));
100 connect(forceuppercaseCB, SIGNAL(clicked()),
101 this, SLOT(changed()));
102 connect(textBeforeED, SIGNAL(textChanged(QString)),
103 this, SLOT(updateStyles()));
104 connect(textAfterED, SIGNAL(textChanged(QString)),
105 this, SLOT(updateStyles()));
106 connect(findLE, SIGNAL(returnPressed()),
107 this, SLOT(on_searchPB_clicked()));
108 connect(textBeforeED, SIGNAL(returnPressed()),
109 this, SLOT(on_okPB_clicked()));
110 connect(textAfterED, SIGNAL(returnPressed()),
111 this, SLOT(on_okPB_clicked()));
113 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
114 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
115 connect(selectionManager, SIGNAL(selectionChanged()),
116 this, SLOT(setCitedKeys()));
117 connect(selectionManager, SIGNAL(updateHook()),
118 this, SLOT(updateControls()));
119 connect(selectionManager, SIGNAL(okHook()),
120 this, SLOT(on_okPB_clicked()));
122 setFocusProxy(availableLV);
126 GuiCitation::~GuiCitation()
128 delete selectionManager;
132 void GuiCitation::closeEvent(QCloseEvent * e)
135 DialogView::closeEvent(e);
139 void GuiCitation::applyView()
141 int const choice = max(0, citationStyleCO->currentIndex());
143 bool const full = fulllistCB->isChecked();
144 bool const force = forceuppercaseCB->isChecked();
146 QString const before = textBeforeED->text();
147 QString const after = textAfterED->text();
149 applyParams(choice, full, force, before, after);
153 void GuiCitation::showEvent(QShowEvent * e)
156 availableLV->setFocus();
158 // Set the minimal size of the QToolbox. Without this, the size of the
159 // QToolbox is only determined by values in the ui file (e.g. computed by
160 // qtcreator) and therefore causes portability and localisation issues. Note
161 // that the page widgets must have a layout with layoutSizeContraint =
162 // SetMinimumSize or similar. KNOWN ISSUE: the calculations are incorrect
163 // the first time the dialog is shown. This problem is mitigated by the fact
164 // that LyX remembers the dialog sizes between sessions.
165 QSize minimum_size = QSize(0,0);
166 // Compute the max of the minimal sizes of the pages
168 for (int i = 0; (page = citationTB->widget(i)); ++i)
169 minimum_size = minimum_size.expandedTo(page->minimumSizeHint());
170 // Add the height of the tabs
171 if (citationTB->currentWidget())
172 minimum_size.rheight() += citationTB->height() -
173 citationTB->currentWidget()->height();
174 citationTB->setMinimumSize(minimum_size);
176 DialogView::showEvent(e);
180 void GuiCitation::on_citationTB_currentChanged(int i)
184 else if (citationStyleCO->isEnabled())
185 citationStyleCO->setFocus();
187 textAfterED->setFocus();
191 void GuiCitation::on_okPB_clicked()
199 void GuiCitation::on_cancelPB_clicked()
206 void GuiCitation::on_applyPB_clicked()
212 void GuiCitation::on_restorePB_clicked()
218 void GuiCitation::updateControls()
220 BiblioInfo const & bi = bibInfo();
225 // The main point of separating this out is that the fill*() methods
226 // called in update() do not need to be called for INTERNAL updates,
227 // such as when addPB is pressed, as the list of fields, entries, etc,
228 // will not have changed.
229 void GuiCitation::updateControls(BiblioInfo const & bi)
231 QModelIndex idx = selectionManager->getSelectedIndex();
233 selectionManager->update();
237 void GuiCitation::updateFormatting(CitationStyle currentStyle)
239 bool const force = currentStyle.forceUpperCase;
240 bool const full = currentStyle.fullAuthorList &&
241 documentBuffer().params().fullAuthorList();
242 bool const textbefore = currentStyle.textBefore;
243 bool const textafter = currentStyle.textAfter;
245 bool const haveSelection =
246 selectedLV->model()->rowCount() > 0;
248 forceuppercaseCB->setEnabled(force && haveSelection);
249 fulllistCB->setEnabled(full && haveSelection);
250 textBeforeED->setEnabled(textbefore && haveSelection);
251 textBeforeLA->setEnabled(textbefore && haveSelection);
252 textAfterED->setEnabled(textafter && haveSelection);
253 textAfterLA->setEnabled(textafter && haveSelection);
254 citationStyleCO->setEnabled(haveSelection);
255 citationStyleLA->setEnabled(haveSelection);
259 // Update the styles for the style combo, citationStyleCO, and mark the
260 // settings as changed. Called upon changing the cited keys (including
261 // merely reordering the keys) or editing the text before/after fields.
262 void GuiCitation::updateStyles()
264 BiblioInfo const & bi = bibInfo();
270 // Update the styles for the style combo, citationStyleCO.
271 void GuiCitation::updateStyles(BiblioInfo const & bi)
273 QStringList selected_keys = selected_model_.stringList();
274 int curr = selectedLV->model()->rowCount() - 1;
276 if (curr < 0 || selected_keys.empty()) {
277 citationStyleCO->clear();
278 citationStyleCO->setEnabled(false);
279 citationStyleLA->setEnabled(false);
283 static const size_t max_length = 80;
284 QStringList sty = citationStyles(bi, max_length);
288 citationStyleCO->setEnabled(false);
289 citationStyleLA->setEnabled(false);
290 citationStyleCO->clear();
294 citationStyleCO->blockSignals(true);
297 int const oldIndex = citationStyleCO->currentIndex();
298 citationStyleCO->clear();
299 citationStyleCO->insertItems(0, sty);
300 citationStyleCO->setEnabled(true);
301 citationStyleLA->setEnabled(true);
303 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
304 citationStyleCO->setCurrentIndex(oldIndex);
306 citationStyleCO->blockSignals(false);
310 void GuiCitation::fillFields(BiblioInfo const & bi)
312 fieldsCO->blockSignals(true);
313 int const oldIndex = fieldsCO->currentIndex();
315 QStringList const fields = to_qstring_list(bi.getFields());
316 fieldsCO->insertItem(0, qt_("All fields"));
317 fieldsCO->insertItem(1, qt_("Keys"));
318 fieldsCO->insertItems(2, fields);
319 if (oldIndex != -1 && oldIndex < fieldsCO->count())
320 fieldsCO->setCurrentIndex(oldIndex);
321 fieldsCO->blockSignals(false);
325 void GuiCitation::fillEntries(BiblioInfo const & bi)
327 entriesCO->blockSignals(true);
328 int const oldIndex = entriesCO->currentIndex();
330 QStringList const entries = to_qstring_list(bi.getEntries());
331 entriesCO->insertItem(0, qt_("All entry types"));
332 entriesCO->insertItems(1, entries);
333 if (oldIndex != -1 && oldIndex < entriesCO->count())
334 entriesCO->setCurrentIndex(oldIndex);
335 entriesCO->blockSignals(false);
339 bool GuiCitation::isSelected(QModelIndex const & idx)
341 QString const str = idx.data().toString();
342 return selected_model_.stringList().contains(str);
346 void GuiCitation::setButtons()
348 int const srows = selectedLV->model()->rowCount();
349 applyPB->setEnabled(srows > 0);
350 okPB->setEnabled(srows > 0);
354 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
356 if (!idx.isValid() || bi.empty()) {
357 infoML->document()->clear();
361 QString const keytxt = toqstr(
362 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
363 infoML->document()->setHtml(keytxt);
367 void GuiCitation::findText(QString const & text, bool reset)
369 //"All Fields" and "Keys" are the first two
370 int index = fieldsCO->currentIndex() - 2;
371 BiblioInfo const & bi = bibInfo();
372 vector<docstring> const & fields = bi.getFields();
375 if (index <= -1 || index >= int(fields.size()))
376 //either "All Fields" or "Keys" or an invalid value
377 field = from_ascii("");
379 field = fields[index];
382 bool const onlyKeys = index == -1;
384 //"All Entry Types" is first.
385 index = entriesCO->currentIndex() - 1;
386 vector<docstring> const & entries = bi.getEntries();
387 docstring entry_type;
388 if (index < 0 || index >= int(entries.size()))
389 entry_type = from_ascii("");
391 entry_type = entries[index];
393 bool const case_sentitive = caseCB->checkState();
394 bool const reg_exp = regexCB->checkState();
395 findKey(bi, text, onlyKeys, field, entry_type,
396 case_sentitive, reg_exp, reset);
398 //It'd be nice to save and restore the current selection in
399 //availableLV. Currently, we get an automatic reset, since the
406 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
408 findText(findLE->text(), true);
412 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
414 findText(findLE->text(), true);
418 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
420 if (index >= 0 && index < citationStyleCO->count()) {
421 vector<CitationStyle> const & styles = citeStyles_;
422 updateFormatting(styles[index]);
428 void GuiCitation::on_findLE_textChanged(const QString & text)
430 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
431 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
432 if (!text.isEmpty()) {
434 findText(findLE->text());
437 findText(findLE->text());
441 void GuiCitation::on_searchPB_clicked()
443 findText(findLE->text(), true);
447 void GuiCitation::on_caseCB_stateChanged(int)
449 findText(findLE->text());
453 void GuiCitation::on_regexCB_stateChanged(int)
455 findText(findLE->text());
459 void GuiCitation::on_asTypeCB_stateChanged(int)
461 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
462 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
464 findText(findLE->text(), true);
468 void GuiCitation::changed()
474 void GuiCitation::applyParams(int const choice, bool full, bool force,
475 QString before, QString after)
477 if (cited_keys_.isEmpty())
480 vector<CitationStyle> const & styles = citeStyles_;
482 CitationStyle cs = styles[choice];
489 cs.forceUpperCase &= force;
490 cs.fullAuthorList &= full;
491 string const command = citationStyleToString(cs);
493 params_.setCmdName(command);
494 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
495 params_["before"] = qstring_to_ucs4(before);
496 params_["after"] = qstring_to_ucs4(after);
501 void GuiCitation::clearSelection()
504 selected_model_.setStringList(cited_keys_);
508 void GuiCitation::init()
510 // Make the list of all available bibliography keys
511 BiblioInfo const & bi = bibInfo();
512 all_keys_ = to_qstring_list(bi.getKeys());
513 available_model_.setStringList(all_keys_);
515 // Ditto for the keys cited in this inset
516 QString str = toqstr(params_["key"]);
520 cited_keys_ = str.split(",");
521 selected_model_.setStringList(cited_keys_);
523 // Initialize the drop downs
527 // Initialize the citation formatting
528 string const & cmd = params_.getCmdName();
529 CitationStyle const cs = citationStyleFromString(cmd);
530 forceuppercaseCB->setChecked(cs.forceUpperCase);
531 fulllistCB->setChecked(cs.fullAuthorList &&
532 documentBuffer().params().fullAuthorList());
533 textBeforeED->setText(toqstr(params_["before"]));
534 textAfterED->setText(toqstr(params_["after"]));
536 // Update the interface
539 if (selected_model_.rowCount()) {
540 selectedLV->blockSignals(true);
541 selectedLV->setFocus();
542 QModelIndex idx = selected_model_.index(0, 0);
543 selectedLV->selectionModel()->select(idx,
544 QItemSelectionModel::ClearAndSelect);
545 selectedLV->blockSignals(false);
547 // Find the citation style
548 vector<string> const & cmds = citeCmds_;
549 vector<string>::const_iterator cit =
550 std::find(cmds.begin(), cmds.end(), cs.cmd);
552 if (cit != cmds.end())
553 i = int(cit - cmds.begin());
555 // Set the style combo appropriately
556 citationStyleCO->blockSignals(true);
557 citationStyleCO->setCurrentIndex(i);
558 citationStyleCO->blockSignals(false);
559 updateFormatting(citeStyles_[i]);
561 availableLV->setFocus();
563 applyPB->setEnabled(false);
564 okPB->setEnabled(false);
568 void GuiCitation::findKey(BiblioInfo const & bi,
569 QString const & str, bool only_keys,
570 docstring field, docstring entry_type,
571 bool case_sensitive, bool reg_exp, bool reset)
574 // Used for optimisation: store last searched string.
575 static QString last_searched_string;
576 // Used to disable the above optimisation.
577 static bool last_case_sensitive;
578 static bool last_reg_exp;
579 // Reset last_searched_string in case of changed option.
580 if (last_case_sensitive != case_sensitive
581 || last_reg_exp != reg_exp) {
582 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
583 last_searched_string.clear();
585 // save option for next search.
586 last_case_sensitive = case_sensitive;
587 last_reg_exp = reg_exp;
589 Qt::CaseSensitivity qtcase = case_sensitive ?
590 Qt::CaseSensitive: Qt::CaseInsensitive;
592 // If new string (str) contains the last searched one...
594 !last_searched_string.isEmpty() &&
596 str.contains(last_searched_string, qtcase))
597 // ... then only search within already found list.
598 keys = available_model_.stringList();
600 // ... else search all keys.
602 // save searched string for next search.
603 last_searched_string = str;
607 // First, filter by entry_type, which will be faster than
608 // what follows, so we may get to do that on less.
609 vector<docstring> keyVector = to_docstring_vector(keys);
610 filterByEntryType(bi, keyVector, entry_type);
613 result = to_qstring_list(keyVector);
615 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
616 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
618 available_model_.setStringList(result);
622 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
624 docstring const before = qstring_to_ucs4(textBeforeED->text());
625 docstring const after = qstring_to_ucs4(textAfterED->text());
626 vector<docstring> const keys = to_docstring_vector(cited_keys_);
627 vector<CitationStyle> styles = citeStyles_;
628 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
629 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
630 before, after, from_utf8("dialog"), max_size);
631 return to_qstring_list(ret);
635 void GuiCitation::setCitedKeys()
637 cited_keys_ = selected_model_.stringList();
642 bool GuiCitation::initialiseParams(string const & data)
644 InsetCommand::string2params(data, params_);
645 citeCmds_ = documentBuffer().params().citeCommands();
646 citeStyles_ = documentBuffer().params().citeStyles();
652 void GuiCitation::clearParams()
658 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
659 vector<docstring> & keyVector, docstring entry_type)
661 if (entry_type.empty())
664 vector<docstring>::iterator it = keyVector.begin();
665 vector<docstring>::iterator end = keyVector.end();
667 vector<docstring> result;
668 for (; it != end; ++it) {
669 docstring const key = *it;
670 BiblioInfo::const_iterator cit = bi.find(key);
673 if (cit->second.entryType() == entry_type)
674 result.push_back(key);
680 // Escape special chars.
681 // All characters are literals except: '.|*?+(){}[]^$\'
682 // These characters are literals when preceded by a "\", which is done here
683 // @todo: This function should be moved to support, and then the test in tests
684 // should be moved there as well.
685 static docstring escape_special_chars(docstring const & expr)
687 // Search for all chars '.|*?+(){}[^$]\'
688 // Note that '[', ']', and '\' must be escaped.
689 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
691 // $& is an ECMAScript format expression that expands to all
692 // of the current match
693 #if defined(LYX_USE_CXX11) && defined(LYX_USE_STD_REGEX)
694 // To prefix a matched expression with a single literal backslash, we
695 // need to escape it for the C++ compiler and use:
697 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
699 // A backslash in the format string starts an escape sequence in boost.
700 // Thus, to prefix a matched expression with a single literal backslash,
701 // we need to give two backslashes to the regex engine, and escape both
702 // for the C++ compiler and use:
704 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
709 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
710 vector<docstring> const & keys_to_search, bool only_keys,
711 docstring const & search_expression, docstring field,
712 bool case_sensitive, bool regex)
714 vector<docstring> foundKeys;
716 docstring expr = trim(search_expression);
721 // We must escape special chars in the search_expr so that
722 // it is treated as a simple string by lyx::regex.
723 expr = escape_special_chars(expr);
727 reg_exp.assign(to_utf8(expr), case_sensitive ?
728 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
729 } catch (lyx::regex_error const & e) {
730 // lyx::regex throws an exception if the regular expression is not
732 LYXERR(Debug::GUI, e.what());
733 return vector<docstring>();
736 vector<docstring>::const_iterator it = keys_to_search.begin();
737 vector<docstring>::const_iterator end = keys_to_search.end();
738 for (; it != end; ++it ) {
739 BiblioInfo::const_iterator info = bi.find(*it);
740 if (info == bi.end())
743 BibTeXInfo const & kvm = info->second;
747 else if (field.empty())
748 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
750 data = to_utf8(kvm[field]);
756 if (lyx::regex_search(data, reg_exp))
757 foundKeys.push_back(*it);
759 catch (lyx::regex_error const & e) {
760 LYXERR(Debug::GUI, e.what());
761 return vector<docstring>();
768 void GuiCitation::dispatchParams()
770 std::string const lfun = InsetCommand::params2string(params_);
771 dispatch(FuncRequest(getLfun(), lfun));
775 BiblioInfo const & GuiCitation::bibInfo() const
777 Buffer const & buf = documentBuffer();
778 buf.reloadBibInfoCache();
779 return buf.masterBibInfo();
783 void GuiCitation::saveSession() const
785 Dialog::saveSession();
788 sessionKey() + "/regex", regexCB->isChecked());
790 sessionKey() + "/casesensitive", caseCB->isChecked());
792 sessionKey() + "/autofind", asTypeCB->isChecked());
796 void GuiCitation::restoreSession()
798 Dialog::restoreSession();
801 settings.value(sessionKey() + "/regex").toBool());
803 settings.value(sessionKey() + "/casesensitive").toBool());
804 asTypeCB->setChecked(
805 settings.value(sessionKey() + "/autofind").toBool());
809 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
812 } // namespace frontend
815 #include "moc_GuiCitation.cpp"