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 connect(filter_, &FancyLineEdit::downPressed,
112 availableLV, [this](){ focusAndHighlight(availableLV); });
114 availableLV->setToolTip(formatToolTip(qt_("This list consists of all databases that are indexed by LaTeX and thus are found without a file path. "
115 "This is usually everything in the bib/ subdirectory of LaTeX's texmf tree. "
116 "If you want to reuse your own database, this is the place you should store it.")));
118 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
119 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
120 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
121 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
122 bc().addReadOnly(stylePB);
123 bc().addReadOnly(styleCB);
124 bc().addReadOnly(bibtocCB);
125 bc().addReadOnly(bibEncodingCO);
127 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
129 // Always put the default encoding in the first position.
130 bibEncodingCO->addItem(qt_("Document Encoding"), "default");
131 for (auto const & encvar : encodings) {
132 if (!encvar.unsafe() && !encvar.guiName().empty())
133 encodings_.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
135 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
136 while (it != encodings_.constEnd()) {
137 bibEncodingCO->addItem(it.key(), it.value());
141 setFocusProxy(filter_);
145 void GuiBibtex::init()
147 all_bibs_ = bibFiles(false);
148 available_model_.setStringList(all_bibs_);
150 QString bibs = toqstr(params_["bibfiles"]);
152 selected_bibs_.clear();
154 selected_bibs_ = bibs.split(",");
155 setSelectedBibs(selected_bibs_);
157 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
158 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
159 selectionManager->update();
163 void GuiBibtex::change_adaptor()
170 void GuiBibtex::setButtons()
172 int const srows = selectedLV->model()->rowCount();
173 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
174 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
175 inheritPB->setEnabled(hasInherits());
179 void GuiBibtex::selUpdated()
181 selectionManager->update();
182 editPB->setEnabled(deletePB->isEnabled());
187 void GuiBibtex::on_buttonBox_accepted()
195 void GuiBibtex::browseBstPressed()
197 QString const file = browseBst(QString());
202 QString const filen = changeExtension(file, "");
203 bool present = false;
206 for (int i = 0; i != styleCB->count(); ++i) {
207 if (styleCB->itemText(i) == filen) {
214 styleCB->insertItem(0, filen);
216 styleCB->setCurrentIndex(pres);
221 void GuiBibtex::browseBibPressed()
223 QString const file = browseBib(QString()).trimmed();
228 QString const f = changeExtension(file, "");
230 if (!selected_bibs_.contains(f)) {
231 selected_bibs_.append(f);
232 setSelectedBibs(selected_bibs_);
238 bool GuiBibtex::hasInherits()
240 if (!buffer().parent())
243 docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
247 for (auto const & f : mbibs) {
248 if (!selected_bibs_.contains(toqstr(f)))
255 void GuiBibtex::inheritPressed()
257 docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
259 vector<docstring> nfe;
260 for (auto const & f : mbibs) {
261 if (!selected_bibs_.contains(toqstr(f))) {
262 selected_bibs_.append(toqstr(f));
263 setSelectedBibs(selected_bibs_);
265 if (usingBiblatex()) {
266 string const bfe = buffer().masterParams().bibFileEncoding(to_utf8(f));
268 nfe.push_back(f + " " + from_utf8(bfe));
275 setFileEncodings(nfe);
281 void GuiBibtex::on_editPB_clicked()
283 QModelIndexList selIdx =
284 selectedLV->selectionModel()->selectedIndexes();
285 if (selIdx.isEmpty())
287 QModelIndex idx = selIdx.first();
288 QString sel = idx.data().toString();
289 FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
294 void GuiBibtex::rescanClicked()
301 void GuiBibtex::clearSelection()
303 selected_bibs_.clear();
304 setSelectedBibs(selected_bibs_);
308 void GuiBibtex::setSelectedBibs(QStringList const & sl)
310 selected_model_.clear();
312 headers << qt_("Database")
313 << qt_("File Encoding");
314 selected_model_.setHorizontalHeaderLabels(headers);
315 bool const moreencs = usingBiblatex() && sl.count() > 1;
316 selectedLV->setColumnHidden(1, !moreencs);
317 selectedLV->verticalHeader()->setVisible(false);
318 selectedLV->horizontalHeader()->setVisible(moreencs);
320 bibEncodingLA->setText(qt_("General E&ncoding:"));
321 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
322 "encoding than the LyX document, specify it here. "
323 "If indivivual databases have different encodings, "
324 "you can set it in the list above."));
326 bibEncodingLA->setText(qt_("E&ncoding:"));
327 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
328 "encoding than the LyX document, specify it here"));
330 QStringList::const_iterator it = sl.begin();
331 QStringList::const_iterator end = sl.end();
332 for (int i = 0; it != end; ++it, ++i) {
333 QStandardItem * si = new QStandardItem();
337 si->setEditable(false);
338 selected_model_.insertRow(i, si);
339 QComboBox * cb = new QComboBox;
340 cb->addItem(qt_("General Encoding"), "general");
341 cb->addItem(qt_("Document Encoding"), "auto");
342 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
343 while (it != encodings_.constEnd()) {
344 cb->addItem(it.key(), it.value());
347 cb->setToolTip(qt_("If this bibliography database uses a different "
348 "encoding than specified below, set it here"));
349 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
351 editPB->setEnabled(deletePB->isEnabled());
355 QStringList GuiBibtex::selectedBibs()
358 for (int i = 0; i != selected_model_.rowCount(); ++i) {
359 QStandardItem const * item = selected_model_.item(i);
361 res.append(item->text());
367 void GuiBibtex::databaseChanged()
369 selected_bibs_ = selectedBibs();
370 setSelectedBibs(selected_bibs_);
374 void GuiBibtex::updateContents()
376 bool const bibtopic = usingBibtopic();
377 bool const biblatex = usingBiblatex();
380 setTitle(qt_("Biblatex Bibliography"));
382 setTitle(qt_("BibTeX Bibliography"));
384 QString const bibstyle = styleFile();
386 bool const hasbibintoc = buffer().params().documentClass().bibInToc()
389 bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
390 bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
392 inheritPB->setEnabled(hasInherits());
395 btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
397 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
398 btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
399 if (usingBiblatex() && !buffer().masterParams().multibib.empty())
400 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
402 docstring btprint = params_["btprint"];
405 btprint = from_ascii("btPrintCited");
406 btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
408 docstring encoding = params_["encoding"];
409 if (encoding.empty())
411 encoding = from_ascii("default");
412 bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
414 // Only useful for biblatex
415 biblatexOptsLA->setVisible(biblatex);
416 biblatexOptsLE->setVisible(biblatex);
418 // only useful for BibTeX
419 bstGB->setVisible(!biblatex);
426 QStringList const str = bibStyles();
427 for (int i = 0; i != str.count(); ++i) {
428 QString item = changeExtension(str[i], "");
429 if (item == bibstyle)
431 styleCB->addItem(item);
434 if (item_nr == -1 && !bibstyle.isEmpty()) {
435 styleCB->addItem(bibstyle);
436 item_nr = styleCB->count() - 1;
441 styleCB->setCurrentIndex(item_nr);
443 styleCB->clearEditText();
445 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
447 setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
448 editPB->setEnabled(deletePB->isEnabled());
452 void GuiBibtex::applyView()
456 int maxCount = selected_bibs_.count();
457 for (int i = 0; i < maxCount; i++) {
460 QString item = selected_bibs_.at(i);
461 docstring bibfile = qstring_to_ucs4(item);
465 params_["bibfiles"] = dbs;
467 docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
468 bool const bibtotoc = bibtocCB->isChecked();
470 if (bibtotoc && !bibstyle.empty()) {
471 // both bibtotoc and style
472 params_["options"] = "bibtotoc," + bibstyle;
473 } else if (bibtotoc) {
474 // bibtotoc and no style
475 params_["options"] = from_ascii("bibtotoc");
477 // only style. An empty one is valid, because some
478 // documentclasses have an own \bibliographystyle{}
480 params_["options"] = bibstyle;
483 params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
485 params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
487 params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
490 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
494 QString GuiBibtex::browseBib(QString const & in_name) const
496 QString const label1 = qt_("D&ocuments");
497 QString const dir1 = toqstr(lyxrc.document_path);
498 QStringList const filter(qt_("BibTeX Databases (*.bib)"));
499 return browseRelToParent(in_name, bufferFilePath(),
500 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
504 QString GuiBibtex::browseBst(QString const & in_name) const
506 QString const label1 = qt_("D&ocuments");
507 QString const dir1 = toqstr(lyxrc.document_path);
508 QStringList const filter(qt_("BibTeX Styles (*.bst)"));
509 return browseRelToParent(in_name, bufferFilePath(),
510 qt_("Select a BibTeX style"), filter, false, label1, dir1);
514 QStringList GuiBibtex::bibStyles() const
516 QStringList sdata = texFileList("bstFiles.lst");
517 // test whether we have a valid list, otherwise run rescan
518 if (sdata.isEmpty()) {
520 sdata = texFileList("bstFiles.lst");
522 for (int i = 0; i != sdata.size(); ++i)
523 sdata[i] = onlyFileName(sdata[i]);
524 // sort on filename only (no path)
530 QStringList GuiBibtex::bibFiles(bool const extension) const
532 QStringList sdata = texFileList("bibFiles.lst");
533 // test whether we have a valid list, otherwise run rescan
534 if (sdata.isEmpty()) {
536 sdata = texFileList("bibFiles.lst");
538 for (int i = 0; i != sdata.size(); ++i)
539 sdata[i] = extension ? onlyFileName(sdata[i])
540 : changeExtension(onlyFileName(sdata[i]), "");
541 // sort on filename only (no path)
547 vector<docstring> GuiBibtex::getFileEncodings()
549 vector<docstring> res;
550 for (int i = 0; i != selected_model_.rowCount(); ++i) {
551 QStandardItem const * key = selected_model_.item(i, 0);
552 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
553 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
554 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
555 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
561 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
563 for (docstring const & s: m) {
565 QString enc = toqstr(split(s, key, ' '));
566 QModelIndexList qmil =
567 selected_model_.match(selected_model_.index(0, 0),
568 Qt::DisplayRole, toqstr(key), 1,
569 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
571 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
572 cb->setCurrentIndex(cb->findData(enc));
578 void GuiBibtex::rescanBibStyles() const
581 rescanTexStyles("bib");
583 rescanTexStyles("bst bib");
587 void GuiBibtex::findText(QString const & text)
589 QStringList const result = bibFiles(false).filter(text);
590 available_model_.setStringList(result);
594 void GuiBibtex::filterChanged(const QString & text)
596 if (!text.isEmpty()) {
597 findText(filter_->text());
600 findText(filter_->text());
605 void GuiBibtex::filterPressed()
607 findText(filter_->text());
611 void GuiBibtex::resetFilter()
613 filter_->setText(QString());
614 findText(filter_->text());
619 bool GuiBibtex::usingBibtopic() const
621 return buffer().params().useBibtopic();
625 bool GuiBibtex::bibtotoc() const
627 return prefixIs(to_utf8(params_["options"]), "bibtotoc");
631 bool GuiBibtex::usingBiblatex() const
633 return buffer().masterBuffer()->params().useBiblatex();
637 QString GuiBibtex::styleFile() const
639 // the different bibtex packages have (and need) their
640 // own "plain" stylefiles
641 QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
643 QString bst = toqstr(params_["options"]);
646 int pos = bst.indexOf(',');
649 // docstring bibtotoc = from_ascii("bibtotoc");
650 // bst = split(bst, bibtotoc, ',');
651 bst = bst.mid(pos + 1);
657 // propose default style file for new insets
658 // existing insets might have (legally) no bst files
659 // (if the class already provides a style)
660 if (bst.isEmpty() && params_["bibfiles"].empty())
667 bool GuiBibtex::initialiseParams(std::string const & sdata)
669 InsetCommand::string2params(sdata, params_);
675 void GuiBibtex::dispatchParams()
677 std::string const lfun = InsetCommand::params2string(params_);
678 dispatch(FuncRequest(getLfun(), lfun));
683 } // namespace frontend
686 #include "moc_GuiBibtex.cpp"