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;
58 // I am guessing that it would not hurt to make these private members.
59 static vector<string> citeCmds_;
60 static vector<CitationStyle> citeStyles_;
63 template<typename String>
64 static QStringList to_qstring_list(vector<String> const & v)
68 for (size_t i = 0; i != v.size(); ++i) {
71 qlist.append(lyx::toqstr(v[i]));
77 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
79 vector<lyx::docstring> v;
80 for (int i = 0; i != qlist.size(); ++i) {
81 if (qlist[i].isEmpty())
83 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
89 GuiCitation::GuiCitation(GuiView & lv)
90 : DialogView(lv, "citation", qt_("Citation")),
91 params_(insetCode("citation"))
95 connect(citationStyleCO, SIGNAL(activated(int)),
96 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
97 connect(fulllistCB, SIGNAL(clicked()),
98 this, SLOT(changed()));
99 connect(forceuppercaseCB, SIGNAL(clicked()),
100 this, SLOT(changed()));
101 connect(textBeforeED, SIGNAL(textChanged(QString)),
102 this, SLOT(updateStyles()));
103 connect(textAfterED, SIGNAL(textChanged(QString)),
104 this, SLOT(updateStyles()));
105 connect(findLE, SIGNAL(returnPressed()),
106 this, SLOT(on_searchPB_clicked()));
107 connect(textBeforeED, SIGNAL(returnPressed()),
108 this, SLOT(on_okPB_clicked()));
109 connect(textAfterED, SIGNAL(returnPressed()),
110 this, SLOT(on_okPB_clicked()));
112 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
113 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
114 connect(selectionManager, SIGNAL(selectionChanged()),
115 this, SLOT(setCitedKeys()));
116 connect(selectionManager, SIGNAL(updateHook()),
117 this, SLOT(updateControls()));
118 connect(selectionManager, SIGNAL(okHook()),
119 this, SLOT(on_okPB_clicked()));
121 setFocusProxy(availableLV);
125 GuiCitation::~GuiCitation()
127 delete selectionManager;
131 void GuiCitation::closeEvent(QCloseEvent * e)
134 DialogView::closeEvent(e);
138 void GuiCitation::applyView()
140 int const choice = max(0, citationStyleCO->currentIndex());
142 bool const full = fulllistCB->isChecked();
143 bool const force = forceuppercaseCB->isChecked();
145 QString const before = textBeforeED->text();
146 QString const after = textAfterED->text();
148 applyParams(choice, full, force, before, after);
152 void GuiCitation::showEvent(QShowEvent * e)
155 availableLV->setFocus();
157 // Set the minimal size of the QToolbox. Without this, the size of the
158 // QToolbox is only determined by values in the ui file (e.g. computed by
159 // qtcreator) and therefore causes portability and localisation issues. Note
160 // that the page widgets must have a layout with layoutSizeContraint =
161 // SetMinimumSize or similar. KNOWN ISSUE: the calculations are incorrect
162 // the first time the dialog is shown. This problem is mitigated by the fact
163 // that LyX remembers the dialog sizes between sessions.
164 QSize minimum_size = QSize(0,0);
165 // Compute the max of the minimal sizes of the pages
167 for (int i = 0; (page = citationTB->widget(i)); ++i)
168 minimum_size = minimum_size.expandedTo(page->minimumSizeHint());
169 // Add the height of the tabs
170 if (citationTB->currentWidget())
171 minimum_size.rheight() += citationTB->height() -
172 citationTB->currentWidget()->height();
173 citationTB->setMinimumSize(minimum_size);
175 DialogView::showEvent(e);
179 void GuiCitation::on_citationTB_currentChanged(int i)
183 else if (citationStyleCO->isEnabled())
184 citationStyleCO->setFocus();
186 textAfterED->setFocus();
190 void GuiCitation::on_okPB_clicked()
198 void GuiCitation::on_cancelPB_clicked()
205 void GuiCitation::on_applyPB_clicked()
211 void GuiCitation::on_restorePB_clicked()
217 void GuiCitation::updateControls()
219 BiblioInfo const & bi = bibInfo();
224 // The main point of separating this out is that the fill*() methods
225 // called in update() do not need to be called for INTERNAL updates,
226 // such as when addPB is pressed, as the list of fields, entries, etc,
227 // will not have changed.
228 void GuiCitation::updateControls(BiblioInfo const & bi)
230 QModelIndex idx = selectionManager->getSelectedIndex();
232 selectionManager->update();
236 void GuiCitation::updateFormatting(CitationStyle currentStyle)
238 bool const force = currentStyle.forceUpperCase;
239 bool const full = currentStyle.fullAuthorList &&
240 documentBuffer().params().fullAuthorList();
241 bool const textbefore = currentStyle.textBefore;
242 bool const textafter = currentStyle.textAfter;
244 bool const haveSelection =
245 selectedLV->model()->rowCount() > 0;
247 forceuppercaseCB->setEnabled(force && haveSelection);
248 fulllistCB->setEnabled(full && haveSelection);
249 textBeforeED->setEnabled(textbefore && haveSelection);
250 textBeforeLA->setEnabled(textbefore && haveSelection);
251 textAfterED->setEnabled(textafter && haveSelection);
252 textAfterLA->setEnabled(textafter && haveSelection);
253 citationStyleCO->setEnabled(haveSelection);
254 citationStyleLA->setEnabled(haveSelection);
258 // Update the styles for the style combo, citationStyleCO, and mark the
259 // settings as changed. Called upon changing the cited keys (including
260 // merely reordering the keys) or editing the text before/after fields.
261 void GuiCitation::updateStyles()
263 BiblioInfo const & bi = bibInfo();
269 // Update the styles for the style combo, citationStyleCO.
270 void GuiCitation::updateStyles(BiblioInfo const & bi)
272 QStringList selected_keys = selected_model_.stringList();
273 int curr = selectedLV->model()->rowCount() - 1;
275 if (curr < 0 || selected_keys.empty()) {
276 citationStyleCO->clear();
277 citationStyleCO->setEnabled(false);
278 citationStyleLA->setEnabled(false);
282 static const size_t max_length = 80;
283 QStringList sty = citationStyles(bi, max_length);
287 citationStyleCO->setEnabled(false);
288 citationStyleLA->setEnabled(false);
289 citationStyleCO->clear();
293 citationStyleCO->blockSignals(true);
296 int const oldIndex = citationStyleCO->currentIndex();
297 citationStyleCO->clear();
298 citationStyleCO->insertItems(0, sty);
299 citationStyleCO->setEnabled(true);
300 citationStyleLA->setEnabled(true);
302 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
303 citationStyleCO->setCurrentIndex(oldIndex);
305 citationStyleCO->blockSignals(false);
309 void GuiCitation::fillFields(BiblioInfo const & bi)
311 fieldsCO->blockSignals(true);
312 int const oldIndex = fieldsCO->currentIndex();
314 QStringList const fields = to_qstring_list(bi.getFields());
315 fieldsCO->insertItem(0, qt_("All fields"));
316 fieldsCO->insertItem(1, qt_("Keys"));
317 fieldsCO->insertItems(2, fields);
318 if (oldIndex != -1 && oldIndex < fieldsCO->count())
319 fieldsCO->setCurrentIndex(oldIndex);
320 fieldsCO->blockSignals(false);
324 void GuiCitation::fillEntries(BiblioInfo const & bi)
326 entriesCO->blockSignals(true);
327 int const oldIndex = entriesCO->currentIndex();
329 QStringList const entries = to_qstring_list(bi.getEntries());
330 entriesCO->insertItem(0, qt_("All entry types"));
331 entriesCO->insertItems(1, entries);
332 if (oldIndex != -1 && oldIndex < entriesCO->count())
333 entriesCO->setCurrentIndex(oldIndex);
334 entriesCO->blockSignals(false);
338 bool GuiCitation::isSelected(QModelIndex const & idx)
340 QString const str = idx.data().toString();
341 return selected_model_.stringList().contains(str);
345 void GuiCitation::setButtons()
347 int const srows = selectedLV->model()->rowCount();
348 applyPB->setEnabled(srows > 0);
349 okPB->setEnabled(srows > 0);
353 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
355 if (!idx.isValid() || bi.empty()) {
356 infoML->document()->clear();
360 QString const keytxt = toqstr(
361 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
362 infoML->document()->setHtml(keytxt);
366 void GuiCitation::findText(QString const & text, bool reset)
368 //"All Fields" and "Keys" are the first two
369 int index = fieldsCO->currentIndex() - 2;
370 BiblioInfo const & bi = bibInfo();
371 vector<docstring> const & fields = bi.getFields();
374 if (index <= -1 || index >= int(fields.size()))
375 //either "All Fields" or "Keys" or an invalid value
376 field = from_ascii("");
378 field = fields[index];
381 bool const onlyKeys = index == -1;
383 //"All Entry Types" is first.
384 index = entriesCO->currentIndex() - 1;
385 vector<docstring> const & entries = bi.getEntries();
386 docstring entry_type;
387 if (index < 0 || index >= int(entries.size()))
388 entry_type = from_ascii("");
390 entry_type = entries[index];
392 bool const case_sentitive = caseCB->checkState();
393 bool const reg_exp = regexCB->checkState();
394 findKey(bi, text, onlyKeys, field, entry_type,
395 case_sentitive, reg_exp, reset);
397 //It'd be nice to save and restore the current selection in
398 //availableLV. Currently, we get an automatic reset, since the
405 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
407 findText(findLE->text(), true);
411 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
413 findText(findLE->text(), true);
417 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
419 if (index >= 0 && index < citationStyleCO->count()) {
420 vector<CitationStyle> const & styles = citeStyles_;
421 updateFormatting(styles[index]);
427 void GuiCitation::on_findLE_textChanged(const QString & text)
429 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
430 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
431 if (!text.isEmpty()) {
433 findText(findLE->text());
436 findText(findLE->text());
440 void GuiCitation::on_searchPB_clicked()
442 findText(findLE->text(), true);
446 void GuiCitation::on_caseCB_stateChanged(int)
448 findText(findLE->text());
452 void GuiCitation::on_regexCB_stateChanged(int)
454 findText(findLE->text());
458 void GuiCitation::on_asTypeCB_stateChanged(int)
460 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
461 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
463 findText(findLE->text(), true);
467 void GuiCitation::changed()
473 void GuiCitation::applyParams(int const choice, bool full, bool force,
474 QString before, QString after)
476 if (cited_keys_.isEmpty())
479 vector<CitationStyle> const & styles = citeStyles_;
481 CitationStyle cs = styles[choice];
488 cs.forceUpperCase &= force;
489 cs.fullAuthorList &= full;
490 string const command = citationStyleToString(cs);
492 params_.setCmdName(command);
493 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
494 params_["before"] = qstring_to_ucs4(before);
495 params_["after"] = qstring_to_ucs4(after);
500 void GuiCitation::clearSelection()
503 selected_model_.setStringList(cited_keys_);
507 void GuiCitation::init()
509 // Make the list of all available bibliography keys
510 BiblioInfo const & bi = bibInfo();
511 all_keys_ = to_qstring_list(bi.getKeys());
512 available_model_.setStringList(all_keys_);
514 // Ditto for the keys cited in this inset
515 QString str = toqstr(params_["key"]);
519 cited_keys_ = str.split(",");
520 selected_model_.setStringList(cited_keys_);
522 // Initialize the drop downs
526 // Initialize the citation formatting
527 string const & cmd = params_.getCmdName();
528 CitationStyle const cs = citationStyleFromString(cmd);
529 forceuppercaseCB->setChecked(cs.forceUpperCase);
530 fulllistCB->setChecked(cs.fullAuthorList &&
531 documentBuffer().params().fullAuthorList());
532 textBeforeED->setText(toqstr(params_["before"]));
533 textAfterED->setText(toqstr(params_["after"]));
535 // Update the interface
538 if (selected_model_.rowCount()) {
539 selectedLV->blockSignals(true);
540 selectedLV->setFocus();
541 QModelIndex idx = selected_model_.index(0, 0);
542 selectedLV->selectionModel()->select(idx,
543 QItemSelectionModel::ClearAndSelect);
544 selectedLV->blockSignals(false);
546 // Find the citation style
547 vector<string> const & cmds = citeCmds_;
548 vector<string>::const_iterator cit =
549 std::find(cmds.begin(), cmds.end(), cs.cmd);
551 if (cit != cmds.end())
552 i = int(cit - cmds.begin());
554 // Set the style combo appropriately
555 citationStyleCO->blockSignals(true);
556 citationStyleCO->setCurrentIndex(i);
557 citationStyleCO->blockSignals(false);
558 updateFormatting(citeStyles_[i]);
560 availableLV->setFocus();
562 applyPB->setEnabled(false);
563 okPB->setEnabled(false);
567 void GuiCitation::findKey(BiblioInfo const & bi,
568 QString const & str, bool only_keys,
569 docstring field, docstring entry_type,
570 bool case_sensitive, bool reg_exp, bool reset)
573 // Used for optimisation: store last searched string.
574 static QString last_searched_string;
575 // Used to disable the above optimisation.
576 static bool last_case_sensitive;
577 static bool last_reg_exp;
578 // Reset last_searched_string in case of changed option.
579 if (last_case_sensitive != case_sensitive
580 || last_reg_exp != reg_exp) {
581 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
582 last_searched_string.clear();
584 // save option for next search.
585 last_case_sensitive = case_sensitive;
586 last_reg_exp = reg_exp;
588 Qt::CaseSensitivity qtcase = case_sensitive ?
589 Qt::CaseSensitive: Qt::CaseInsensitive;
591 // If new string (str) contains the last searched one...
593 !last_searched_string.isEmpty() &&
595 str.contains(last_searched_string, qtcase))
596 // ... then only search within already found list.
597 keys = available_model_.stringList();
599 // ... else search all keys.
601 // save searched string for next search.
602 last_searched_string = str;
606 // First, filter by entry_type, which will be faster than
607 // what follows, so we may get to do that on less.
608 vector<docstring> keyVector = to_docstring_vector(keys);
609 filterByEntryType(bi, keyVector, entry_type);
612 result = to_qstring_list(keyVector);
614 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
615 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
617 available_model_.setStringList(result);
621 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
623 docstring const before = qstring_to_ucs4(textBeforeED->text());
624 docstring const after = qstring_to_ucs4(textAfterED->text());
625 vector<docstring> const keys = to_docstring_vector(cited_keys_);
626 vector<CitationStyle> styles = citeStyles_;
627 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
628 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
629 before, after, from_utf8("dialog"), max_size);
630 return to_qstring_list(ret);
634 void GuiCitation::setCitedKeys()
636 cited_keys_ = selected_model_.stringList();
641 bool GuiCitation::initialiseParams(string const & data)
643 InsetCommand::string2params(data, params_);
644 citeCmds_ = documentBuffer().params().citeCommands();
645 citeStyles_ = documentBuffer().params().citeStyles();
651 void GuiCitation::clearParams()
657 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
658 vector<docstring> & keyVector, docstring entry_type)
660 if (entry_type.empty())
663 vector<docstring>::iterator it = keyVector.begin();
664 vector<docstring>::iterator end = keyVector.end();
666 vector<docstring> result;
667 for (; it != end; ++it) {
668 docstring const key = *it;
669 BiblioInfo::const_iterator cit = bi.find(key);
672 if (cit->second.entryType() == entry_type)
673 result.push_back(key);
679 // Escape special chars.
680 // All characters are literals except: '.|*?+(){}[]^$\'
681 // These characters are literals when preceded by a "\", which is done here
682 // @todo: This function should be moved to support, and then the test in tests
683 // should be moved there as well.
684 static docstring escape_special_chars(docstring const & expr)
686 // Search for all chars '.|*?+(){}[^$]\'
687 // Note that '[', ']', and '\' must be escaped.
688 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
690 // $& is an ECMAScript format expression that expands to all
691 // of the current match
692 #if defined(LYX_USE_CXX11) && defined(LYX_USE_STD_REGEX)
693 // To prefix a matched expression with a single literal backslash, we
694 // need to escape it for the C++ compiler and use:
696 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
698 // A backslash in the format string starts an escape sequence in boost.
699 // Thus, to prefix a matched expression with a single literal backslash,
700 // we need to give two backslashes to the regex engine, and escape both
701 // for the C++ compiler and use:
703 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
708 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
709 vector<docstring> const & keys_to_search, bool only_keys,
710 docstring const & search_expression, docstring field,
711 bool case_sensitive, bool regex)
713 vector<docstring> foundKeys;
715 docstring expr = trim(search_expression);
720 // We must escape special chars in the search_expr so that
721 // it is treated as a simple string by lyx::regex.
722 expr = escape_special_chars(expr);
726 reg_exp.assign(to_utf8(expr), case_sensitive ?
727 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
728 } catch (lyx::regex_error const & e) {
729 // lyx::regex throws an exception if the regular expression is not
731 LYXERR(Debug::GUI, e.what());
732 return vector<docstring>();
735 vector<docstring>::const_iterator it = keys_to_search.begin();
736 vector<docstring>::const_iterator end = keys_to_search.end();
737 for (; it != end; ++it ) {
738 BiblioInfo::const_iterator info = bi.find(*it);
739 if (info == bi.end())
742 BibTeXInfo const & kvm = info->second;
746 else if (field.empty())
747 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
749 data = to_utf8(kvm[field]);
755 if (lyx::regex_search(data, reg_exp))
756 foundKeys.push_back(*it);
758 catch (lyx::regex_error const & e) {
759 LYXERR(Debug::GUI, e.what());
760 return vector<docstring>();
767 void GuiCitation::dispatchParams()
769 std::string const lfun = InsetCommand::params2string(params_);
770 dispatch(FuncRequest(getLfun(), lfun));
774 BiblioInfo const & GuiCitation::bibInfo() const
776 Buffer const & buf = documentBuffer();
777 buf.reloadBibInfoCache();
778 return buf.masterBibInfo();
782 void GuiCitation::saveSession() const
784 Dialog::saveSession();
787 sessionKey() + "/regex", regexCB->isChecked());
789 sessionKey() + "/casesensitive", caseCB->isChecked());
791 sessionKey() + "/autofind", asTypeCB->isChecked());
795 void GuiCitation::restoreSession()
797 Dialog::restoreSession();
800 settings.value(sessionKey() + "/regex").toBool());
802 settings.value(sessionKey() + "/casesensitive").toBool());
803 asTypeCB->setChecked(
804 settings.value(sessionKey() + "/autofind").toBool());
808 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
811 } // namespace frontend
814 #include "moc_GuiCitation.cpp"