3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Angus Leeming
9 * \author Jürgen Spitzmüller
11 * Full author contact details are available in file CREDITS.
16 #include "GuiBibtex.h"
19 #include "BufferParams.h"
20 #include "CiteEnginesList.h"
22 #include "FuncRequest.h"
23 #include "GuiApplication.h"
25 #include "qt_helpers.h"
26 #include "TextClass.h"
27 #include "Validator.h"
29 #include "ButtonPolicy.h"
30 #include "FancyLineEdit.h"
32 #include "frontends/alert.h"
34 #include "insets/InsetBibtex.h"
36 #include "support/debug.h"
37 #include "support/docstring_list.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/FileName.h"
40 #include "support/filetools.h" // changeExtension
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
44 #include <QDialogButtonBox>
45 #include <QPushButton>
46 #include <QListWidget>
51 using namespace lyx::support;
57 GuiBibtex::GuiBibtex(GuiView & lv)
58 : GuiDialog(lv, "bibtex", qt_("BibTeX Bibliography")),
59 params_(insetCode("bibtex"))
63 QDialog::setModal(true);
64 setWindowModality(Qt::WindowModal);
67 filter_ = new FancyLineEdit(this);
68 filter_->setClearButton(true);
69 filter_->setPlaceholderText(qt_("All avail. databases"));
71 filterBarL->addWidget(filter_, 0);
72 findKeysLA->setBuddy(filter_);
74 connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
75 this, SLOT(slotButtonBox(QAbstractButton *)));
76 connect(stylePB, SIGNAL(clicked()),
77 this, SLOT(browseBstPressed()));
78 connect(styleCB, SIGNAL(editTextChanged(QString)),
79 this, SLOT(change_adaptor()));
80 connect(bibtocCB, SIGNAL(clicked()),
81 this, SLOT(change_adaptor()));
82 connect(btPrintCO, SIGNAL(activated(int)),
83 this, SLOT(change_adaptor()));
84 connect(rescanPB, SIGNAL(clicked()),
85 this, SLOT(rescanClicked()));
86 connect(biblatexOptsLE, SIGNAL(textChanged(QString)),
87 this, SLOT(change_adaptor()));
88 connect(bibEncodingCO, SIGNAL(activated(int)),
89 this, SLOT(change_adaptor()));
90 connect(browseBibPB, SIGNAL(clicked()),
91 this, SLOT(browseBibPressed()));
92 connect(inheritPB, SIGNAL(clicked()),
93 this, SLOT(inheritPressed()));
95 selected_model_.insertColumns(0, 1);
96 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
97 addBibPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
98 connect(selectionManager, SIGNAL(selectionChanged()),
99 this, SLOT(databaseChanged()));
100 connect(selectionManager, SIGNAL(updateHook()),
101 this, SLOT(selUpdated()));
102 connect(selectionManager, SIGNAL(okHook()),
103 this, SLOT(on_buttonBox_accepted()));
105 connect(filter_, SIGNAL(rightButtonClicked()),
106 this, SLOT(resetFilter()));
107 connect(filter_, SIGNAL(textEdited(QString)),
108 this, SLOT(filterChanged(QString)));
109 connect(filter_, SIGNAL(returnPressed()),
110 this, SLOT(filterPressed()));
111 #if (QT_VERSION < 0x050000)
112 connect(filter_, SIGNAL(downPressed()),
113 availableLV, SLOT(setFocus()));
115 connect(filter_, &FancyLineEdit::downPressed,
116 availableLV, [this](){ focusAndHighlight(availableLV); });
119 availableLV->setToolTip(formatToolTip(qt_("This list consists of all databases that are indexed by LaTeX and thus are found without a file path. "
120 "This is usually everything in the bib/ subdirectory of LaTeX's texmf tree. "
121 "If you want to reuse your own database, this is the place you should store it.")));
123 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
124 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
125 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
126 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
127 bc().addReadOnly(stylePB);
128 bc().addReadOnly(styleCB);
129 bc().addReadOnly(bibtocCB);
130 bc().addReadOnly(bibEncodingCO);
132 #if (QT_VERSION < 0x050000)
133 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
135 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
138 // Always put the default encoding in the first position.
139 bibEncodingCO->addItem(qt_("Document Encoding"), "default");
140 for (auto const & encvar : encodings) {
141 if (!encvar.unsafe() && !encvar.guiName().empty())
142 encodings_.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
144 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
145 while (it != encodings_.constEnd()) {
146 bibEncodingCO->addItem(it.key(), it.value());
150 setFocusProxy(filter_);
154 void GuiBibtex::init()
156 all_bibs_ = bibFiles(false);
157 available_model_.setStringList(all_bibs_);
159 QString bibs = toqstr(params_["bibfiles"]);
161 selected_bibs_.clear();
163 selected_bibs_ = bibs.split(",");
164 setSelectedBibs(selected_bibs_);
166 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
167 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
168 selectionManager->update();
172 void GuiBibtex::change_adaptor()
179 void GuiBibtex::setButtons()
181 int const srows = selectedLV->model()->rowCount();
182 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
183 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
184 inheritPB->setEnabled(hasInherits());
188 void GuiBibtex::selUpdated()
190 selectionManager->update();
191 editPB->setEnabled(deletePB->isEnabled());
196 void GuiBibtex::on_buttonBox_accepted()
204 void GuiBibtex::browseBstPressed()
206 QString const file = browseBst(QString());
211 QString const filen = changeExtension(file, "");
212 bool present = false;
215 for (int i = 0; i != styleCB->count(); ++i) {
216 if (styleCB->itemText(i) == filen) {
223 styleCB->insertItem(0, filen);
225 styleCB->setCurrentIndex(pres);
230 void GuiBibtex::browseBibPressed()
232 QString const file = browseBib(QString()).trimmed();
237 QString const f = changeExtension(file, "");
239 if (!selected_bibs_.contains(f)) {
240 selected_bibs_.append(f);
241 setSelectedBibs(selected_bibs_);
247 bool GuiBibtex::hasInherits()
249 if (!buffer().parent())
252 docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
256 for (auto const & f : mbibs) {
257 if (!selected_bibs_.contains(toqstr(f)))
264 void GuiBibtex::inheritPressed()
266 docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
268 vector<docstring> nfe;
269 for (auto const & f : mbibs) {
270 if (!selected_bibs_.contains(toqstr(f))) {
271 selected_bibs_.append(toqstr(f));
272 setSelectedBibs(selected_bibs_);
274 if (usingBiblatex()) {
275 string const bfe = buffer().masterParams().bibFileEncoding(to_utf8(f));
277 nfe.push_back(f + " " + from_utf8(bfe));
284 setFileEncodings(nfe);
290 void GuiBibtex::on_editPB_clicked()
292 QModelIndexList selIdx =
293 selectedLV->selectionModel()->selectedIndexes();
294 if (selIdx.isEmpty())
296 QModelIndex idx = selIdx.first();
297 QString sel = idx.data().toString();
298 FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
303 void GuiBibtex::rescanClicked()
310 void GuiBibtex::clearSelection()
312 selected_bibs_.clear();
313 setSelectedBibs(selected_bibs_);
317 void GuiBibtex::setSelectedBibs(QStringList const & sl)
319 selected_model_.clear();
321 headers << qt_("Database")
322 << qt_("File Encoding");
323 selected_model_.setHorizontalHeaderLabels(headers);
324 bool const moreencs = usingBiblatex() && sl.count() > 1;
325 selectedLV->setColumnHidden(1, !moreencs);
326 selectedLV->verticalHeader()->setVisible(false);
327 selectedLV->horizontalHeader()->setVisible(moreencs);
329 bibEncodingLA->setText(qt_("General E&ncoding:"));
330 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
331 "encoding than the LyX document, specify it here. "
332 "If indivivual databases have different encodings, "
333 "you can set it in the list above."));
335 bibEncodingLA->setText(qt_("E&ncoding:"));
336 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
337 "encoding than the LyX document, specify it here"));
339 QStringList::const_iterator it = sl.begin();
340 QStringList::const_iterator end = sl.end();
341 for (int i = 0; it != end; ++it, ++i) {
342 QStandardItem * si = new QStandardItem();
346 si->setEditable(false);
347 selected_model_.insertRow(i, si);
348 QComboBox * cb = new QComboBox;
349 cb->addItem(qt_("General Encoding"), "general");
350 cb->addItem(qt_("Document Encoding"), "auto");
351 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
352 while (it != encodings_.constEnd()) {
353 cb->addItem(it.key(), it.value());
356 cb->setToolTip(qt_("If this bibliography database uses a different "
357 "encoding than specified below, set it here"));
358 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
360 editPB->setEnabled(deletePB->isEnabled());
364 QStringList GuiBibtex::selectedBibs()
367 for (int i = 0; i != selected_model_.rowCount(); ++i) {
368 QStandardItem const * item = selected_model_.item(i);
370 res.append(item->text());
376 void GuiBibtex::databaseChanged()
378 selected_bibs_ = selectedBibs();
379 setSelectedBibs(selected_bibs_);
383 void GuiBibtex::updateContents()
385 bool const bibtopic = usingBibtopic();
386 bool const biblatex = usingBiblatex();
389 setTitle(qt_("Biblatex Bibliography"));
391 setTitle(qt_("BibTeX Bibliography"));
393 QString const bibstyle = styleFile();
395 bool const hasbibintoc = buffer().params().documentClass().bibInToc()
398 bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
399 bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
401 inheritPB->setEnabled(hasInherits());
404 btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
406 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
407 btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
408 if (usingBiblatex() && !buffer().masterParams().multibib.empty())
409 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
411 docstring btprint = params_["btprint"];
414 btprint = from_ascii("btPrintCited");
415 btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
417 docstring encoding = params_["encoding"];
418 if (encoding.empty())
420 encoding = from_ascii("default");
421 bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
423 // Only useful for biblatex
424 biblatexOptsLA->setVisible(biblatex);
425 biblatexOptsLE->setVisible(biblatex);
427 // only useful for BibTeX
428 bstGB->setVisible(!biblatex);
435 QStringList const str = bibStyles();
436 for (int i = 0; i != str.count(); ++i) {
437 QString item = changeExtension(str[i], "");
438 if (item == bibstyle)
440 styleCB->addItem(item);
443 if (item_nr == -1 && !bibstyle.isEmpty()) {
444 styleCB->addItem(bibstyle);
445 item_nr = styleCB->count() - 1;
450 styleCB->setCurrentIndex(item_nr);
452 styleCB->clearEditText();
454 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
456 setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
457 editPB->setEnabled(deletePB->isEnabled());
461 void GuiBibtex::applyView()
465 int maxCount = selected_bibs_.count();
466 for (int i = 0; i < maxCount; i++) {
469 QString item = selected_bibs_.at(i);
470 docstring bibfile = qstring_to_ucs4(item);
474 params_["bibfiles"] = dbs;
476 docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
477 bool const bibtotoc = bibtocCB->isChecked();
479 if (bibtotoc && !bibstyle.empty()) {
480 // both bibtotoc and style
481 params_["options"] = "bibtotoc," + bibstyle;
482 } else if (bibtotoc) {
483 // bibtotoc and no style
484 params_["options"] = from_ascii("bibtotoc");
486 // only style. An empty one is valid, because some
487 // documentclasses have an own \bibliographystyle{}
489 params_["options"] = bibstyle;
492 params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
494 params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
496 params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
499 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
503 QString GuiBibtex::browseBib(QString const & in_name) const
505 QString const label1 = qt_("D&ocuments");
506 QString const dir1 = toqstr(lyxrc.document_path);
507 QStringList const filter(qt_("BibTeX Databases (*.bib)"));
508 return browseRelToParent(in_name, bufferFilePath(),
509 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
513 QString GuiBibtex::browseBst(QString const & in_name) const
515 QString const label1 = qt_("D&ocuments");
516 QString const dir1 = toqstr(lyxrc.document_path);
517 QStringList const filter(qt_("BibTeX Styles (*.bst)"));
518 return browseRelToParent(in_name, bufferFilePath(),
519 qt_("Select a BibTeX style"), filter, false, label1, dir1);
523 QStringList GuiBibtex::bibStyles() const
525 QStringList sdata = texFileList("bstFiles.lst");
526 // test whether we have a valid list, otherwise run rescan
527 if (sdata.isEmpty()) {
529 sdata = texFileList("bstFiles.lst");
531 for (int i = 0; i != sdata.size(); ++i)
532 sdata[i] = onlyFileName(sdata[i]);
533 // sort on filename only (no path)
539 QStringList GuiBibtex::bibFiles(bool const extension) const
541 QStringList sdata = texFileList("bibFiles.lst");
542 // test whether we have a valid list, otherwise run rescan
543 if (sdata.isEmpty()) {
545 sdata = texFileList("bibFiles.lst");
547 for (int i = 0; i != sdata.size(); ++i)
548 sdata[i] = extension ? onlyFileName(sdata[i])
549 : changeExtension(onlyFileName(sdata[i]), "");
550 // sort on filename only (no path)
556 vector<docstring> GuiBibtex::getFileEncodings()
558 vector<docstring> res;
559 for (int i = 0; i != selected_model_.rowCount(); ++i) {
560 QStandardItem const * key = selected_model_.item(i, 0);
561 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
562 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
563 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
564 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
570 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
572 for (docstring const & s: m) {
574 QString enc = toqstr(split(s, key, ' '));
575 QModelIndexList qmil =
576 selected_model_.match(selected_model_.index(0, 0),
577 Qt::DisplayRole, toqstr(key), 1,
578 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
580 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
581 cb->setCurrentIndex(cb->findData(enc));
587 void GuiBibtex::rescanBibStyles() const
590 rescanTexStyles("bib");
592 rescanTexStyles("bst bib");
596 void GuiBibtex::findText(QString const & text)
598 QStringList const result = bibFiles(false).filter(text);
599 available_model_.setStringList(result);
603 void GuiBibtex::filterChanged(const QString & text)
605 if (!text.isEmpty()) {
606 findText(filter_->text());
609 findText(filter_->text());
614 void GuiBibtex::filterPressed()
616 findText(filter_->text());
620 void GuiBibtex::resetFilter()
622 filter_->setText(QString());
623 findText(filter_->text());
628 bool GuiBibtex::usingBibtopic() const
630 return buffer().params().useBibtopic();
634 bool GuiBibtex::bibtotoc() const
636 return prefixIs(to_utf8(params_["options"]), "bibtotoc");
640 bool GuiBibtex::usingBiblatex() const
642 return buffer().masterBuffer()->params().useBiblatex();
646 QString GuiBibtex::styleFile() const
648 // the different bibtex packages have (and need) their
649 // own "plain" stylefiles
650 QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
652 QString bst = toqstr(params_["options"]);
655 int pos = bst.indexOf(',');
658 // docstring bibtotoc = from_ascii("bibtotoc");
659 // bst = split(bst, bibtotoc, ',');
660 bst = bst.mid(pos + 1);
666 // propose default style file for new insets
667 // existing insets might have (legally) no bst files
668 // (if the class already provides a style)
669 if (bst.isEmpty() && params_["bibfiles"].empty())
676 bool GuiBibtex::initialiseParams(std::string const & sdata)
678 InsetCommand::string2params(sdata, params_);
684 void GuiBibtex::dispatchParams()
686 std::string const lfun = InsetCommand::params2string(params_);
687 dispatch(FuncRequest(getLfun(), lfun));
692 } // namespace frontend
695 #include "moc_GuiBibtex.cpp"