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_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
68 filter_->setButtonVisible(FancyLineEdit::Right, true);
69 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
70 filter_->setAutoHideButton(FancyLineEdit::Right, true);
71 filter_->setPlaceholderText(qt_("All avail. databases"));
73 filterBarL->addWidget(filter_, 0);
74 findKeysLA->setBuddy(filter_);
76 connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
77 this, SLOT(slotButtonBox(QAbstractButton *)));
78 connect(stylePB, SIGNAL(clicked()),
79 this, SLOT(browseBstPressed()));
80 connect(styleCB, SIGNAL(editTextChanged(QString)),
81 this, SLOT(change_adaptor()));
82 connect(bibtocCB, SIGNAL(clicked()),
83 this, SLOT(change_adaptor()));
84 connect(btPrintCO, SIGNAL(activated(int)),
85 this, SLOT(change_adaptor()));
86 connect(rescanPB, SIGNAL(clicked()),
87 this, SLOT(rescanClicked()));
88 connect(biblatexOptsLE, SIGNAL(textChanged(QString)),
89 this, SLOT(change_adaptor()));
90 connect(bibEncodingCO, SIGNAL(activated(int)),
91 this, SLOT(change_adaptor()));
92 connect(browseBibPB, SIGNAL(clicked()),
93 this, SLOT(browseBibPressed()));
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, [=](){ 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);
187 void GuiBibtex::selUpdated()
189 selectionManager->update();
190 editPB->setEnabled(deletePB->isEnabled());
195 void GuiBibtex::on_buttonBox_accepted()
203 void GuiBibtex::browseBstPressed()
205 QString const file = browseBst(QString());
210 QString const filen = changeExtension(file, "");
211 bool present = false;
214 for (int i = 0; i != styleCB->count(); ++i) {
215 if (styleCB->itemText(i) == filen) {
222 styleCB->insertItem(0, filen);
224 styleCB->setCurrentIndex(pres);
229 void GuiBibtex::browseBibPressed()
231 QString const file = browseBib(QString()).trimmed();
236 QString const f = changeExtension(file, "");
238 if (!selected_bibs_.contains(f)) {
239 selected_bibs_.append(f);
240 setSelectedBibs(selected_bibs_);
246 void GuiBibtex::on_editPB_clicked()
248 QModelIndexList selIdx =
249 selectedLV->selectionModel()->selectedIndexes();
250 if (selIdx.isEmpty())
252 QModelIndex idx = selIdx.first();
253 QString sel = idx.data().toString();
254 FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
259 void GuiBibtex::rescanClicked()
266 void GuiBibtex::clearSelection()
268 selected_bibs_.clear();
269 setSelectedBibs(selected_bibs_);
273 void GuiBibtex::setSelectedBibs(QStringList const & sl)
275 selected_model_.clear();
277 headers << qt_("Database")
278 << qt_("File Encoding");
279 selected_model_.setHorizontalHeaderLabels(headers);
280 bool const moreencs = usingBiblatex() && sl.count() > 1;
281 selectedLV->setColumnHidden(1, !moreencs);
282 selectedLV->verticalHeader()->setVisible(false);
283 selectedLV->horizontalHeader()->setVisible(moreencs);
285 bibEncodingLA->setText(qt_("General E&ncoding:"));
286 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
287 "encoding than the LyX document, specify it here. "
288 "If indivivual databases have different encodings, "
289 "you can set it in the list above."));
291 bibEncodingLA->setText(qt_("E&ncoding:"));
292 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
293 "encoding than the LyX document, specify it here"));
295 QStringList::const_iterator it = sl.begin();
296 QStringList::const_iterator end = sl.end();
297 for (int i = 0; it != end; ++it, ++i) {
298 QStandardItem * si = new QStandardItem();
302 si->setEditable(false);
303 selected_model_.insertRow(i, si);
304 QComboBox * cb = new QComboBox;
305 cb->addItem(qt_("General Encoding"), "general");
306 cb->addItem(qt_("Document Encoding"), "auto");
307 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
308 while (it != encodings_.constEnd()) {
309 cb->addItem(it.key(), it.value());
312 cb->setToolTip(qt_("If this bibliography database uses a different "
313 "encoding than specified below, set it here"));
314 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
316 editPB->setEnabled(deletePB->isEnabled());
320 QStringList GuiBibtex::selectedBibs()
323 for (int i = 0; i != selected_model_.rowCount(); ++i) {
324 QStandardItem const * item = selected_model_.item(i);
326 res.append(item->text());
332 void GuiBibtex::databaseChanged()
334 selected_bibs_ = selectedBibs();
335 setSelectedBibs(selected_bibs_);
339 void GuiBibtex::updateContents()
341 bool const bibtopic = usingBibtopic();
342 bool const biblatex = usingBiblatex();
345 setTitle(qt_("Biblatex Bibliography"));
347 setTitle(qt_("BibTeX Bibliography"));
349 QString const bibstyle = styleFile();
351 bool const hasbibintoc = buffer().params().documentClass().bibInToc()
354 bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
355 bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
358 btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
360 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
361 btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
362 if (usingBiblatex() && !buffer().masterParams().multibib.empty())
363 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
365 docstring btprint = params_["btprint"];
368 btprint = from_ascii("btPrintCited");
369 btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
371 docstring encoding = params_["encoding"];
372 if (encoding.empty())
374 encoding = from_ascii("default");
375 bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
377 // Only useful for biblatex
378 biblatexOptsLA->setVisible(biblatex);
379 biblatexOptsLE->setVisible(biblatex);
381 // only useful for BibTeX
382 bstGB->setVisible(!biblatex);
389 QStringList const str = bibStyles();
390 for (int i = 0; i != str.count(); ++i) {
391 QString item = changeExtension(str[i], "");
392 if (item == bibstyle)
394 styleCB->addItem(item);
397 if (item_nr == -1 && !bibstyle.isEmpty()) {
398 styleCB->addItem(bibstyle);
399 item_nr = styleCB->count() - 1;
404 styleCB->setCurrentIndex(item_nr);
406 styleCB->clearEditText();
408 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
410 setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
411 editPB->setEnabled(deletePB->isEnabled());
415 void GuiBibtex::applyView()
419 int maxCount = selected_bibs_.count();
420 for (int i = 0; i < maxCount; i++) {
423 QString item = selected_bibs_.at(i);
424 docstring bibfile = qstring_to_ucs4(item);
428 params_["bibfiles"] = dbs;
430 docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
431 bool const bibtotoc = bibtocCB->isChecked();
433 if (bibtotoc && !bibstyle.empty()) {
434 // both bibtotoc and style
435 params_["options"] = "bibtotoc," + bibstyle;
436 } else if (bibtotoc) {
437 // bibtotoc and no style
438 params_["options"] = from_ascii("bibtotoc");
440 // only style. An empty one is valid, because some
441 // documentclasses have an own \bibliographystyle{}
443 params_["options"] = bibstyle;
446 params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
448 params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
450 params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
453 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
457 QString GuiBibtex::browseBib(QString const & in_name) const
459 QString const label1 = qt_("D&ocuments");
460 QString const dir1 = toqstr(lyxrc.document_path);
461 QStringList const filter(qt_("BibTeX Databases (*.bib)"));
462 return browseRelToParent(in_name, bufferFilePath(),
463 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
467 QString GuiBibtex::browseBst(QString const & in_name) const
469 QString const label1 = qt_("D&ocuments");
470 QString const dir1 = toqstr(lyxrc.document_path);
471 QStringList const filter(qt_("BibTeX Styles (*.bst)"));
472 return browseRelToParent(in_name, bufferFilePath(),
473 qt_("Select a BibTeX style"), filter, false, label1, dir1);
477 QStringList GuiBibtex::bibStyles() const
479 QStringList sdata = texFileList("bstFiles.lst");
480 // test whether we have a valid list, otherwise run rescan
481 if (sdata.isEmpty()) {
483 sdata = texFileList("bstFiles.lst");
485 for (int i = 0; i != sdata.size(); ++i)
486 sdata[i] = onlyFileName(sdata[i]);
487 // sort on filename only (no path)
493 QStringList GuiBibtex::bibFiles(bool const extension) const
495 QStringList sdata = texFileList("bibFiles.lst");
496 // test whether we have a valid list, otherwise run rescan
497 if (sdata.isEmpty()) {
499 sdata = texFileList("bibFiles.lst");
501 for (int i = 0; i != sdata.size(); ++i)
502 sdata[i] = extension ? onlyFileName(sdata[i])
503 : changeExtension(onlyFileName(sdata[i]), "");
504 // sort on filename only (no path)
510 vector<docstring> GuiBibtex::getFileEncodings()
512 vector<docstring> res;
513 for (int i = 0; i != selected_model_.rowCount(); ++i) {
514 QStandardItem const * key = selected_model_.item(i, 0);
515 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
516 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
517 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
518 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
524 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
526 for (docstring const & s: m) {
528 QString enc = toqstr(split(s, key, ' '));
529 QModelIndexList qmil =
530 selected_model_.match(selected_model_.index(0, 0),
531 Qt::DisplayRole, toqstr(key), 1,
532 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
534 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
535 cb->setCurrentIndex(cb->findData(enc));
541 void GuiBibtex::rescanBibStyles() const
544 rescanTexStyles("bib");
546 rescanTexStyles("bst bib");
550 void GuiBibtex::findText(QString const & text)
552 QStringList const result = bibFiles(false).filter(text);
553 available_model_.setStringList(result);
557 void GuiBibtex::filterChanged(const QString & text)
559 if (!text.isEmpty()) {
560 findText(filter_->text());
563 findText(filter_->text());
568 void GuiBibtex::filterPressed()
570 findText(filter_->text());
574 void GuiBibtex::resetFilter()
576 filter_->setText(QString());
577 findText(filter_->text());
582 bool GuiBibtex::usingBibtopic() const
584 return buffer().params().useBibtopic();
588 bool GuiBibtex::bibtotoc() const
590 return prefixIs(to_utf8(params_["options"]), "bibtotoc");
594 bool GuiBibtex::usingBiblatex() const
596 return buffer().masterBuffer()->params().useBiblatex();
600 QString GuiBibtex::styleFile() const
602 // the different bibtex packages have (and need) their
603 // own "plain" stylefiles
604 QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
606 QString bst = toqstr(params_["options"]);
609 int pos = bst.indexOf(',');
612 // docstring bibtotoc = from_ascii("bibtotoc");
613 // bst = split(bst, bibtotoc, ',');
614 bst = bst.mid(pos + 1);
620 // propose default style file for new insets
621 // existing insets might have (legally) no bst files
622 // (if the class already provides a style)
623 if (bst.isEmpty() && params_["bibfiles"].empty())
630 bool GuiBibtex::initialiseParams(std::string const & sdata)
632 InsetCommand::string2params(sdata, params_);
638 void GuiBibtex::dispatchParams()
640 std::string const lfun = InsetCommand::params2string(params_);
641 dispatch(FuncRequest(getLfun(), lfun));
645 Dialog * createGuiBibtex(GuiView & lv) { return new GuiBibtex(lv); }
648 } // namespace frontend
651 #include "moc_GuiBibtex.cpp"