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 style_(0), 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 // This should be moved to a class member.
575 // Used for optimisation: store last searched string.
576 static QString last_searched_string;
577 // Used to disable the above optimisation.
578 static bool last_case_sensitive;
579 static bool last_reg_exp;
580 // Reset last_searched_string in case of changed option.
581 if (last_case_sensitive != case_sensitive
582 || last_reg_exp != reg_exp) {
583 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
584 last_searched_string.clear();
586 // save option for next search.
587 last_case_sensitive = case_sensitive;
588 last_reg_exp = reg_exp;
590 Qt::CaseSensitivity qtcase = case_sensitive ?
591 Qt::CaseSensitive: Qt::CaseInsensitive;
593 // If new string (str) contains the last searched one...
595 !last_searched_string.isEmpty() &&
597 str.contains(last_searched_string, qtcase))
598 // ... then only search within already found list.
599 keys = available_model_.stringList();
601 // ... else search all keys.
603 // save searched string for next search.
604 last_searched_string = str;
608 // First, filter by entry_type, which will be faster than
609 // what follows, so we may get to do that on less.
610 vector<docstring> keyVector = to_docstring_vector(keys);
611 filterByEntryType(bi, keyVector, entry_type);
614 result = to_qstring_list(keyVector);
616 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
617 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
619 available_model_.setStringList(result);
623 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
625 docstring const before = qstring_to_ucs4(textBeforeED->text());
626 docstring const after = qstring_to_ucs4(textAfterED->text());
627 vector<docstring> const keys = to_docstring_vector(cited_keys_);
628 vector<CitationStyle> styles = citeStyles_;
629 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
630 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
631 before, after, from_utf8("dialog"), max_size);
632 return to_qstring_list(ret);
636 void GuiCitation::setCitedKeys()
638 cited_keys_ = selected_model_.stringList();
643 bool GuiCitation::initialiseParams(string const & data)
645 InsetCommand::string2params(data, params_);
646 citeCmds_ = documentBuffer().params().citeCommands();
647 citeStyles_ = documentBuffer().params().citeStyles();
653 void GuiCitation::clearParams()
659 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
660 vector<docstring> & keyVector, docstring entry_type)
662 if (entry_type.empty())
665 vector<docstring>::iterator it = keyVector.begin();
666 vector<docstring>::iterator end = keyVector.end();
668 vector<docstring> result;
669 for (; it != end; ++it) {
670 docstring const key = *it;
671 BiblioInfo::const_iterator cit = bi.find(key);
674 if (cit->second.entryType() == entry_type)
675 result.push_back(key);
681 // Escape special chars.
682 // All characters are literals except: '.|*?+(){}[]^$\'
683 // These characters are literals when preceded by a "\", which is done here
684 // @todo: This function should be moved to support, and then the test in tests
685 // should be moved there as well.
686 static docstring escape_special_chars(docstring const & expr)
688 // Search for all chars '.|*?+(){}[^$]\'
689 // Note that '[', ']', and '\' must be escaped.
690 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
692 // $& is an ECMAScript format expression that expands to all
693 // of the current match
694 #ifdef LYX_USE_STD_REGEX
695 // To prefix a matched expression with a single literal backslash, we
696 // need to escape it for the C++ compiler and use:
698 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
700 // A backslash in the format string starts an escape sequence in boost.
701 // Thus, to prefix a matched expression with a single literal backslash,
702 // we need to give two backslashes to the regex engine, and escape both
703 // for the C++ compiler and use:
705 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
710 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
711 vector<docstring> const & keys_to_search, bool only_keys,
712 docstring const & search_expression, docstring field,
713 bool case_sensitive, bool regex)
715 vector<docstring> foundKeys;
717 docstring expr = trim(search_expression);
722 // We must escape special chars in the search_expr so that
723 // it is treated as a simple string by lyx::regex.
724 expr = escape_special_chars(expr);
728 reg_exp.assign(to_utf8(expr), case_sensitive ?
729 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
730 } catch (lyx::regex_error const & e) {
731 // lyx::regex throws an exception if the regular expression is not
733 LYXERR(Debug::GUI, e.what());
734 return vector<docstring>();
737 vector<docstring>::const_iterator it = keys_to_search.begin();
738 vector<docstring>::const_iterator end = keys_to_search.end();
739 for (; it != end; ++it ) {
740 BiblioInfo::const_iterator info = bi.find(*it);
741 if (info == bi.end())
744 BibTeXInfo const & kvm = info->second;
748 else if (field.empty())
749 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
751 data = to_utf8(kvm[field]);
757 if (lyx::regex_search(data, reg_exp))
758 foundKeys.push_back(*it);
760 catch (lyx::regex_error const & e) {
761 LYXERR(Debug::GUI, e.what());
762 return vector<docstring>();
769 void GuiCitation::dispatchParams()
771 std::string const lfun = InsetCommand::params2string(params_);
772 dispatch(FuncRequest(getLfun(), lfun));
776 BiblioInfo const & GuiCitation::bibInfo() const
778 Buffer const & buf = documentBuffer();
779 buf.reloadBibInfoCache();
780 return buf.masterBibInfo();
784 void GuiCitation::saveSession() const
786 Dialog::saveSession();
789 sessionKey() + "/regex", regexCB->isChecked());
791 sessionKey() + "/casesensitive", caseCB->isChecked());
793 sessionKey() + "/autofind", asTypeCB->isChecked());
797 void GuiCitation::restoreSession()
799 Dialog::restoreSession();
802 settings.value(sessionKey() + "/regex").toBool());
804 settings.value(sessionKey() + "/casesensitive").toBool());
805 asTypeCB->setChecked(
806 settings.value(sessionKey() + "/autofind").toBool());
810 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
813 } // namespace frontend
816 #include "moc_GuiCitation.cpp"