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"
31 #include "frontends/alert.h"
33 #include "insets/InsetBibtex.h"
35 #include "support/debug.h"
36 #include "support/ExceptionMessage.h"
37 #include "support/FileName.h"
38 #include "support/filetools.h" // changeExtension
39 #include "support/gettext.h"
40 #include "support/lstrings.h"
42 #include <QDialogButtonBox>
43 #include <QPushButton>
44 #include <QListWidget>
49 using namespace lyx::support;
55 GuiBibtex::GuiBibtex(GuiView & lv)
56 : GuiDialog(lv, "bibtex", qt_("BibTeX Bibliography")),
57 params_(insetCode("bibtex"))
61 QDialog::setModal(true);
62 setWindowModality(Qt::WindowModal);
65 filter_ = new FancyLineEdit(this);
66 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
67 filter_->setButtonVisible(FancyLineEdit::Right, true);
68 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
69 filter_->setAutoHideButton(FancyLineEdit::Right, true);
70 filter_->setPlaceholderText(qt_("All avail. databases"));
72 filterBarL->addWidget(filter_, 0);
73 findKeysLA->setBuddy(filter_);
75 connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
76 this, SLOT(slotButtonBox(QAbstractButton *)));
77 connect(stylePB, SIGNAL(clicked()),
78 this, SLOT(browseBstPressed()));
79 connect(styleCB, SIGNAL(editTextChanged(QString)),
80 this, SLOT(change_adaptor()));
81 connect(bibtocCB, SIGNAL(clicked()),
82 this, SLOT(change_adaptor()));
83 connect(btPrintCO, SIGNAL(activated(int)),
84 this, SLOT(change_adaptor()));
85 connect(rescanPB, SIGNAL(clicked()),
86 this, SLOT(rescanClicked()));
87 connect(biblatexOptsLE, SIGNAL(textChanged(QString)),
88 this, SLOT(change_adaptor()));
89 connect(bibEncodingCO, SIGNAL(activated(int)),
90 this, SLOT(change_adaptor()));
91 connect(browseBibPB, SIGNAL(clicked()),
92 this, SLOT(browseBibPressed()));
94 selected_model_.insertColumns(0, 1);
95 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
96 addBibPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
97 connect(selectionManager, SIGNAL(selectionChanged()),
98 this, SLOT(databaseChanged()));
99 connect(selectionManager, SIGNAL(updateHook()),
100 this, SLOT(selUpdated()));
101 connect(selectionManager, SIGNAL(okHook()),
102 this, SLOT(on_buttonBox_accepted()));
104 connect(filter_, SIGNAL(rightButtonClicked()),
105 this, SLOT(resetFilter()));
106 connect(filter_, SIGNAL(textEdited(QString)),
107 this, SLOT(filterChanged(QString)));
108 connect(filter_, SIGNAL(returnPressed()),
109 this, SLOT(filterPressed()));
110 #if (QT_VERSION < 0x050000)
111 connect(filter_, SIGNAL(downPressed()),
112 availableLV, SLOT(setFocus()));
114 connect(filter_, &FancyLineEdit::downPressed,
115 availableLV, [=](){ focusAndHighlight(availableLV); });
118 availableLV->setToolTip(formatToolTip(qt_("This list consists of all databases that are indexed by LaTeX and thus are found without a file path. "
119 "This is usually everything in the bib/ subdirectory of LaTeX's texmf tree. "
120 "If you want to reuse your own database, this is the place you should store it.")));
122 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
123 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
124 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
125 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
126 bc().addReadOnly(stylePB);
127 bc().addReadOnly(styleCB);
128 bc().addReadOnly(bibtocCB);
129 bc().addReadOnly(bibEncodingCO);
131 #if (QT_VERSION < 0x050000)
132 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
134 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
137 // Always put the default encoding in the first position.
138 bibEncodingCO->addItem(qt_("Document Encoding"), "default");
139 for (auto const & encvar : encodings) {
140 if (!encvar.unsafe() && !encvar.guiName().empty())
141 encodings_.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
143 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
144 while (it != encodings_.constEnd()) {
145 bibEncodingCO->addItem(it.key(), it.value());
149 setFocusProxy(filter_);
153 void GuiBibtex::init()
155 all_bibs_ = bibFiles(false);
156 available_model_.setStringList(all_bibs_);
158 QString bibs = toqstr(params_["bibfiles"]);
160 selected_bibs_.clear();
162 selected_bibs_ = bibs.split(",");
163 setSelectedBibs(selected_bibs_);
165 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
166 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
167 selectionManager->update();
171 void GuiBibtex::change_adaptor()
178 void GuiBibtex::setButtons()
180 int const srows = selectedLV->model()->rowCount();
181 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
182 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
186 void GuiBibtex::selUpdated()
188 selectionManager->update();
189 editPB->setEnabled(deletePB->isEnabled());
194 void GuiBibtex::on_buttonBox_accepted()
202 void GuiBibtex::browseBstPressed()
204 QString const file = browseBst(QString());
209 QString const filen = changeExtension(file, "");
210 bool present = false;
213 for (int i = 0; i != styleCB->count(); ++i) {
214 if (styleCB->itemText(i) == filen) {
221 styleCB->insertItem(0, filen);
223 styleCB->setCurrentIndex(pres);
228 void GuiBibtex::browseBibPressed()
230 QString const file = browseBib(QString()).trimmed();
235 QString const f = changeExtension(file, "");
237 if (!selected_bibs_.contains(f)) {
238 selected_bibs_.append(f);
239 setSelectedBibs(selected_bibs_);
245 void GuiBibtex::on_editPB_clicked()
247 QModelIndexList selIdx =
248 selectedLV->selectionModel()->selectedIndexes();
249 if (selIdx.isEmpty())
251 QModelIndex idx = selIdx.first();
252 QString sel = idx.data().toString();
253 FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
258 void GuiBibtex::rescanClicked()
265 void GuiBibtex::clearSelection()
267 selected_bibs_.clear();
268 setSelectedBibs(selected_bibs_);
272 void GuiBibtex::setSelectedBibs(QStringList const sl)
274 selected_model_.clear();
276 headers << qt_("Database")
277 << qt_("File Encoding");
278 selected_model_.setHorizontalHeaderLabels(headers);
279 bool const moreencs = usingBiblatex() && sl.count() > 1;
280 selectedLV->setColumnHidden(1, !moreencs);
281 selectedLV->verticalHeader()->setVisible(false);
282 selectedLV->horizontalHeader()->setVisible(moreencs);
284 bibEncodingLA->setText(qt_("General E&ncoding:"));
285 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
286 "encoding than the LyX document, specify it here. "
287 "If indivivual databases have different encodings, "
288 "you can set it in the list above."));
290 bibEncodingLA->setText(qt_("E&ncoding:"));
291 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
292 "encoding than the LyX document, specify it here"));
294 QStringList::const_iterator it = sl.begin();
295 QStringList::const_iterator end = sl.end();
296 for (int i = 0; it != end; ++it, ++i) {
297 QStandardItem * si = new QStandardItem();
301 si->setEditable(false);
302 selected_model_.insertRow(i, si);
303 QComboBox * cb = new QComboBox;
304 cb->addItem(qt_("General Encoding"), "general");
305 cb->addItem(qt_("Document Encoding"), "auto");
306 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
307 while (it != encodings_.constEnd()) {
308 cb->addItem(it.key(), it.value());
311 cb->setToolTip(qt_("If this bibliography database uses a different "
312 "encoding than specified below, set it here"));
313 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
315 editPB->setEnabled(deletePB->isEnabled());
319 QStringList GuiBibtex::selectedBibs()
322 for (int i = 0; i != selected_model_.rowCount(); ++i) {
323 QStandardItem const * item = selected_model_.item(i);
325 res.append(item->text());
331 void GuiBibtex::databaseChanged()
333 selected_bibs_ = selectedBibs();
334 setSelectedBibs(selected_bibs_);
338 void GuiBibtex::updateContents()
340 bool const bibtopic = usingBibtopic();
341 bool const biblatex = usingBiblatex();
344 setTitle(qt_("Biblatex Bibliography"));
346 setTitle(qt_("BibTeX Bibliography"));
348 QString const bibstyle = styleFile();
350 bool const hasbibintoc = buffer().params().documentClass().bibInToc()
353 bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
354 bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
357 btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
359 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
360 btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
361 if (usingBiblatex() && !buffer().masterParams().multibib.empty())
362 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
364 docstring btprint = params_["btprint"];
367 btprint = from_ascii("btPrintCited");
368 btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
370 docstring encoding = params_["encoding"];
371 if (encoding.empty())
373 encoding = from_ascii("default");
374 bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
376 // Only useful for biblatex
377 biblatexOptsLA->setVisible(biblatex);
378 biblatexOptsLE->setVisible(biblatex);
380 // only useful for BibTeX
381 bstGB->setVisible(!biblatex);
388 QStringList const str = bibStyles();
389 for (int i = 0; i != str.count(); ++i) {
390 QString item = changeExtension(str[i], "");
391 if (item == bibstyle)
393 styleCB->addItem(item);
396 if (item_nr == -1 && !bibstyle.isEmpty()) {
397 styleCB->addItem(bibstyle);
398 item_nr = styleCB->count() - 1;
403 styleCB->setCurrentIndex(item_nr);
405 styleCB->clearEditText();
407 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
409 setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
410 editPB->setEnabled(deletePB->isEnabled());
414 void GuiBibtex::applyView()
418 int maxCount = selected_bibs_.count();
419 for (int i = 0; i < maxCount; i++) {
422 QString item = selected_bibs_.at(i);
423 docstring bibfile = qstring_to_ucs4(item);
427 params_["bibfiles"] = dbs;
429 docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
430 bool const bibtotoc = bibtocCB->isChecked();
432 if (bibtotoc && !bibstyle.empty()) {
433 // both bibtotoc and style
434 params_["options"] = "bibtotoc," + bibstyle;
435 } else if (bibtotoc) {
436 // bibtotoc and no style
437 params_["options"] = from_ascii("bibtotoc");
439 // only style. An empty one is valid, because some
440 // documentclasses have an own \bibliographystyle{}
442 params_["options"] = bibstyle;
445 params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
447 params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
449 params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
452 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
456 QString GuiBibtex::browseBib(QString const & in_name) const
458 QString const label1 = qt_("D&ocuments");
459 QString const dir1 = toqstr(lyxrc.document_path);
460 QStringList const filter(qt_("BibTeX Databases (*.bib)"));
461 return browseRelToParent(in_name, bufferFilePath(),
462 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
466 QString GuiBibtex::browseBst(QString const & in_name) const
468 QString const label1 = qt_("D&ocuments");
469 QString const dir1 = toqstr(lyxrc.document_path);
470 QStringList const filter(qt_("BibTeX Styles (*.bst)"));
471 return browseRelToParent(in_name, bufferFilePath(),
472 qt_("Select a BibTeX style"), filter, false, label1, dir1);
476 QStringList GuiBibtex::bibStyles() const
478 QStringList sdata = texFileList("bstFiles.lst");
479 // test whether we have a valid list, otherwise run rescan
480 if (sdata.isEmpty()) {
482 sdata = texFileList("bstFiles.lst");
484 for (int i = 0; i != sdata.size(); ++i)
485 sdata[i] = onlyFileName(sdata[i]);
486 // sort on filename only (no path)
492 QStringList GuiBibtex::bibFiles(bool const extension) const
494 QStringList sdata = texFileList("bibFiles.lst");
495 // test whether we have a valid list, otherwise run rescan
496 if (sdata.isEmpty()) {
498 sdata = texFileList("bibFiles.lst");
500 for (int i = 0; i != sdata.size(); ++i)
501 sdata[i] = extension ? onlyFileName(sdata[i])
502 : changeExtension(onlyFileName(sdata[i]), "");
503 // sort on filename only (no path)
509 vector<docstring> GuiBibtex::getFileEncodings()
511 vector<docstring> res;
512 for (int i = 0; i != selected_model_.rowCount(); ++i) {
513 QStandardItem const * key = selected_model_.item(i, 0);
514 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
515 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
516 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
517 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
523 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
525 for (docstring const & s: m) {
527 QString enc = toqstr(split(s, key, ' '));
528 QModelIndexList qmil =
529 selected_model_.match(selected_model_.index(0, 0),
530 Qt::DisplayRole, toqstr(key), 1,
531 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
533 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
534 cb->setCurrentIndex(cb->findData(enc));
540 void GuiBibtex::rescanBibStyles() const
543 rescanTexStyles("bib");
545 rescanTexStyles("bst bib");
549 void GuiBibtex::findText(QString const & text)
551 QStringList const result = bibFiles(false).filter(text);
552 available_model_.setStringList(result);
556 void GuiBibtex::filterChanged(const QString & text)
558 if (!text.isEmpty()) {
559 findText(filter_->text());
562 findText(filter_->text());
567 void GuiBibtex::filterPressed()
569 findText(filter_->text());
573 void GuiBibtex::resetFilter()
575 filter_->setText(QString());
576 findText(filter_->text());
581 bool GuiBibtex::usingBibtopic() const
583 return buffer().params().useBibtopic();
587 bool GuiBibtex::bibtotoc() const
589 return prefixIs(to_utf8(params_["options"]), "bibtotoc");
593 bool GuiBibtex::usingBiblatex() const
595 return buffer().masterBuffer()->params().useBiblatex();
599 QString GuiBibtex::styleFile() const
601 // the different bibtex packages have (and need) their
602 // own "plain" stylefiles
603 QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
605 QString bst = toqstr(params_["options"]);
608 int pos = bst.indexOf(',');
611 // docstring bibtotoc = from_ascii("bibtotoc");
612 // bst = split(bst, bibtotoc, ',');
613 bst = bst.mid(pos + 1);
619 // propose default style file for new insets
620 // existing insets might have (legally) no bst files
621 // (if the class already provides a style)
622 if (bst.isEmpty() && params_["bibfiles"].empty())
629 bool GuiBibtex::initialiseParams(std::string const & sdata)
631 InsetCommand::string2params(sdata, params_);
637 void GuiBibtex::dispatchParams()
639 std::string const lfun = InsetCommand::params2string(params_);
640 dispatch(FuncRequest(getLfun(), lfun));
644 Dialog * createGuiBibtex(GuiView & lv) { return new GuiBibtex(lv); }
647 } // namespace frontend
650 #include "moc_GuiBibtex.cpp"