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/ExceptionMessage.h"
38 #include "support/FileName.h"
39 #include "support/filetools.h" // changeExtension
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
43 #include <QDialogButtonBox>
44 #include <QPushButton>
45 #include <QListWidget>
50 using namespace lyx::support;
56 GuiBibtex::GuiBibtex(GuiView & lv)
57 : GuiDialog(lv, "bibtex", qt_("BibTeX Bibliography")),
58 params_(insetCode("bibtex"))
62 QDialog::setModal(true);
63 setWindowModality(Qt::WindowModal);
66 filter_ = new FancyLineEdit(this);
67 filter_->setClearButton(true);
68 filter_->setPlaceholderText(qt_("All avail. databases"));
70 filterBarL->addWidget(filter_, 0);
71 findKeysLA->setBuddy(filter_);
73 connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
74 this, SLOT(slotButtonBox(QAbstractButton *)));
75 connect(stylePB, SIGNAL(clicked()),
76 this, SLOT(browseBstPressed()));
77 connect(styleCB, SIGNAL(editTextChanged(QString)),
78 this, SLOT(change_adaptor()));
79 connect(bibtocCB, SIGNAL(clicked()),
80 this, SLOT(change_adaptor()));
81 connect(btPrintCO, SIGNAL(activated(int)),
82 this, SLOT(change_adaptor()));
83 connect(rescanPB, SIGNAL(clicked()),
84 this, SLOT(rescanClicked()));
85 connect(biblatexOptsLE, SIGNAL(textChanged(QString)),
86 this, SLOT(change_adaptor()));
87 connect(bibEncodingCO, SIGNAL(activated(int)),
88 this, SLOT(change_adaptor()));
89 connect(browseBibPB, SIGNAL(clicked()),
90 this, SLOT(browseBibPressed()));
92 selected_model_.insertColumns(0, 1);
93 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
94 addBibPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
95 connect(selectionManager, SIGNAL(selectionChanged()),
96 this, SLOT(databaseChanged()));
97 connect(selectionManager, SIGNAL(updateHook()),
98 this, SLOT(selUpdated()));
99 connect(selectionManager, SIGNAL(okHook()),
100 this, SLOT(on_buttonBox_accepted()));
102 connect(filter_, SIGNAL(rightButtonClicked()),
103 this, SLOT(resetFilter()));
104 connect(filter_, SIGNAL(textEdited(QString)),
105 this, SLOT(filterChanged(QString)));
106 connect(filter_, SIGNAL(returnPressed()),
107 this, SLOT(filterPressed()));
108 #if (QT_VERSION < 0x050000)
109 connect(filter_, SIGNAL(downPressed()),
110 availableLV, SLOT(setFocus()));
112 connect(filter_, &FancyLineEdit::downPressed,
113 availableLV, [this](){ focusAndHighlight(availableLV); });
116 availableLV->setToolTip(formatToolTip(qt_("This list consists of all databases that are indexed by LaTeX and thus are found without a file path. "
117 "This is usually everything in the bib/ subdirectory of LaTeX's texmf tree. "
118 "If you want to reuse your own database, this is the place you should store it.")));
120 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
121 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
122 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
123 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
124 bc().addReadOnly(stylePB);
125 bc().addReadOnly(styleCB);
126 bc().addReadOnly(bibtocCB);
127 bc().addReadOnly(bibEncodingCO);
129 #if (QT_VERSION < 0x050000)
130 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
132 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
135 // Always put the default encoding in the first position.
136 bibEncodingCO->addItem(qt_("Document Encoding"), "default");
137 for (auto const & encvar : encodings) {
138 if (!encvar.unsafe() && !encvar.guiName().empty())
139 encodings_.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
141 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
142 while (it != encodings_.constEnd()) {
143 bibEncodingCO->addItem(it.key(), it.value());
147 setFocusProxy(filter_);
151 void GuiBibtex::init()
153 all_bibs_ = bibFiles(false);
154 available_model_.setStringList(all_bibs_);
156 QString bibs = toqstr(params_["bibfiles"]);
158 selected_bibs_.clear();
160 selected_bibs_ = bibs.split(",");
161 setSelectedBibs(selected_bibs_);
163 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
164 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
165 selectionManager->update();
169 void GuiBibtex::change_adaptor()
176 void GuiBibtex::setButtons()
178 int const srows = selectedLV->model()->rowCount();
179 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
180 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
184 void GuiBibtex::selUpdated()
186 selectionManager->update();
187 editPB->setEnabled(deletePB->isEnabled());
192 void GuiBibtex::on_buttonBox_accepted()
200 void GuiBibtex::browseBstPressed()
202 QString const file = browseBst(QString());
207 QString const filen = changeExtension(file, "");
208 bool present = false;
211 for (int i = 0; i != styleCB->count(); ++i) {
212 if (styleCB->itemText(i) == filen) {
219 styleCB->insertItem(0, filen);
221 styleCB->setCurrentIndex(pres);
226 void GuiBibtex::browseBibPressed()
228 QString const file = browseBib(QString()).trimmed();
233 QString const f = changeExtension(file, "");
235 if (!selected_bibs_.contains(f)) {
236 selected_bibs_.append(f);
237 setSelectedBibs(selected_bibs_);
243 void GuiBibtex::on_editPB_clicked()
245 QModelIndexList selIdx =
246 selectedLV->selectionModel()->selectedIndexes();
247 if (selIdx.isEmpty())
249 QModelIndex idx = selIdx.first();
250 QString sel = idx.data().toString();
251 FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
256 void GuiBibtex::rescanClicked()
263 void GuiBibtex::clearSelection()
265 selected_bibs_.clear();
266 setSelectedBibs(selected_bibs_);
270 void GuiBibtex::setSelectedBibs(QStringList const & sl)
272 selected_model_.clear();
274 headers << qt_("Database")
275 << qt_("File Encoding");
276 selected_model_.setHorizontalHeaderLabels(headers);
277 bool const moreencs = usingBiblatex() && sl.count() > 1;
278 selectedLV->setColumnHidden(1, !moreencs);
279 selectedLV->verticalHeader()->setVisible(false);
280 selectedLV->horizontalHeader()->setVisible(moreencs);
282 bibEncodingLA->setText(qt_("General E&ncoding:"));
283 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
284 "encoding than the LyX document, specify it here. "
285 "If indivivual databases have different encodings, "
286 "you can set it in the list above."));
288 bibEncodingLA->setText(qt_("E&ncoding:"));
289 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
290 "encoding than the LyX document, specify it here"));
292 QStringList::const_iterator it = sl.begin();
293 QStringList::const_iterator end = sl.end();
294 for (int i = 0; it != end; ++it, ++i) {
295 QStandardItem * si = new QStandardItem();
299 si->setEditable(false);
300 selected_model_.insertRow(i, si);
301 QComboBox * cb = new QComboBox;
302 cb->addItem(qt_("General Encoding"), "general");
303 cb->addItem(qt_("Document Encoding"), "auto");
304 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
305 while (it != encodings_.constEnd()) {
306 cb->addItem(it.key(), it.value());
309 cb->setToolTip(qt_("If this bibliography database uses a different "
310 "encoding than specified below, set it here"));
311 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
313 editPB->setEnabled(deletePB->isEnabled());
317 QStringList GuiBibtex::selectedBibs()
320 for (int i = 0; i != selected_model_.rowCount(); ++i) {
321 QStandardItem const * item = selected_model_.item(i);
323 res.append(item->text());
329 void GuiBibtex::databaseChanged()
331 selected_bibs_ = selectedBibs();
332 setSelectedBibs(selected_bibs_);
336 void GuiBibtex::updateContents()
338 bool const bibtopic = usingBibtopic();
339 bool const biblatex = usingBiblatex();
342 setTitle(qt_("Biblatex Bibliography"));
344 setTitle(qt_("BibTeX Bibliography"));
346 QString const bibstyle = styleFile();
348 bool const hasbibintoc = buffer().params().documentClass().bibInToc()
351 bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
352 bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
355 btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
357 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
358 btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
359 if (usingBiblatex() && !buffer().masterParams().multibib.empty())
360 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
362 docstring btprint = params_["btprint"];
365 btprint = from_ascii("btPrintCited");
366 btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
368 docstring encoding = params_["encoding"];
369 if (encoding.empty())
371 encoding = from_ascii("default");
372 bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
374 // Only useful for biblatex
375 biblatexOptsLA->setVisible(biblatex);
376 biblatexOptsLE->setVisible(biblatex);
378 // only useful for BibTeX
379 bstGB->setVisible(!biblatex);
386 QStringList const str = bibStyles();
387 for (int i = 0; i != str.count(); ++i) {
388 QString item = changeExtension(str[i], "");
389 if (item == bibstyle)
391 styleCB->addItem(item);
394 if (item_nr == -1 && !bibstyle.isEmpty()) {
395 styleCB->addItem(bibstyle);
396 item_nr = styleCB->count() - 1;
401 styleCB->setCurrentIndex(item_nr);
403 styleCB->clearEditText();
405 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
407 setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
408 editPB->setEnabled(deletePB->isEnabled());
412 void GuiBibtex::applyView()
416 int maxCount = selected_bibs_.count();
417 for (int i = 0; i < maxCount; i++) {
420 QString item = selected_bibs_.at(i);
421 docstring bibfile = qstring_to_ucs4(item);
425 params_["bibfiles"] = dbs;
427 docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
428 bool const bibtotoc = bibtocCB->isChecked();
430 if (bibtotoc && !bibstyle.empty()) {
431 // both bibtotoc and style
432 params_["options"] = "bibtotoc," + bibstyle;
433 } else if (bibtotoc) {
434 // bibtotoc and no style
435 params_["options"] = from_ascii("bibtotoc");
437 // only style. An empty one is valid, because some
438 // documentclasses have an own \bibliographystyle{}
440 params_["options"] = bibstyle;
443 params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
445 params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
447 params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
450 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
454 QString GuiBibtex::browseBib(QString const & in_name) const
456 QString const label1 = qt_("D&ocuments");
457 QString const dir1 = toqstr(lyxrc.document_path);
458 QStringList const filter(qt_("BibTeX Databases (*.bib)"));
459 return browseRelToParent(in_name, bufferFilePath(),
460 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
464 QString GuiBibtex::browseBst(QString const & in_name) const
466 QString const label1 = qt_("D&ocuments");
467 QString const dir1 = toqstr(lyxrc.document_path);
468 QStringList const filter(qt_("BibTeX Styles (*.bst)"));
469 return browseRelToParent(in_name, bufferFilePath(),
470 qt_("Select a BibTeX style"), filter, false, label1, dir1);
474 QStringList GuiBibtex::bibStyles() const
476 QStringList sdata = texFileList("bstFiles.lst");
477 // test whether we have a valid list, otherwise run rescan
478 if (sdata.isEmpty()) {
480 sdata = texFileList("bstFiles.lst");
482 for (int i = 0; i != sdata.size(); ++i)
483 sdata[i] = onlyFileName(sdata[i]);
484 // sort on filename only (no path)
490 QStringList GuiBibtex::bibFiles(bool const extension) const
492 QStringList sdata = texFileList("bibFiles.lst");
493 // test whether we have a valid list, otherwise run rescan
494 if (sdata.isEmpty()) {
496 sdata = texFileList("bibFiles.lst");
498 for (int i = 0; i != sdata.size(); ++i)
499 sdata[i] = extension ? onlyFileName(sdata[i])
500 : changeExtension(onlyFileName(sdata[i]), "");
501 // sort on filename only (no path)
507 vector<docstring> GuiBibtex::getFileEncodings()
509 vector<docstring> res;
510 for (int i = 0; i != selected_model_.rowCount(); ++i) {
511 QStandardItem const * key = selected_model_.item(i, 0);
512 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
513 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
514 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
515 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
521 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
523 for (docstring const & s: m) {
525 QString enc = toqstr(split(s, key, ' '));
526 QModelIndexList qmil =
527 selected_model_.match(selected_model_.index(0, 0),
528 Qt::DisplayRole, toqstr(key), 1,
529 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
531 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
532 cb->setCurrentIndex(cb->findData(enc));
538 void GuiBibtex::rescanBibStyles() const
541 rescanTexStyles("bib");
543 rescanTexStyles("bst bib");
547 void GuiBibtex::findText(QString const & text)
549 QStringList const result = bibFiles(false).filter(text);
550 available_model_.setStringList(result);
554 void GuiBibtex::filterChanged(const QString & text)
556 if (!text.isEmpty()) {
557 findText(filter_->text());
560 findText(filter_->text());
565 void GuiBibtex::filterPressed()
567 findText(filter_->text());
571 void GuiBibtex::resetFilter()
573 filter_->setText(QString());
574 findText(filter_->text());
579 bool GuiBibtex::usingBibtopic() const
581 return buffer().params().useBibtopic();
585 bool GuiBibtex::bibtotoc() const
587 return prefixIs(to_utf8(params_["options"]), "bibtotoc");
591 bool GuiBibtex::usingBiblatex() const
593 return buffer().masterBuffer()->params().useBiblatex();
597 QString GuiBibtex::styleFile() const
599 // the different bibtex packages have (and need) their
600 // own "plain" stylefiles
601 QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
603 QString bst = toqstr(params_["options"]);
606 int pos = bst.indexOf(',');
609 // docstring bibtotoc = from_ascii("bibtotoc");
610 // bst = split(bst, bibtotoc, ',');
611 bst = bst.mid(pos + 1);
617 // propose default style file for new insets
618 // existing insets might have (legally) no bst files
619 // (if the class already provides a style)
620 if (bst.isEmpty() && params_["bibfiles"].empty())
627 bool GuiBibtex::initialiseParams(std::string const & sdata)
629 InsetCommand::string2params(sdata, params_);
635 void GuiBibtex::dispatchParams()
637 std::string const lfun = InsetCommand::params2string(params_);
638 dispatch(FuncRequest(getLfun(), lfun));
643 } // namespace frontend
646 #include "moc_GuiBibtex.cpp"