]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiBibtex.cpp
Guard against possible referencing null.
[features.git] / src / frontends / qt / GuiBibtex.cpp
1 /**
2  * \file GuiBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Herbert Voß
8  * \author Angus Leeming
9  * \author Jürgen Spitzmüller
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiBibtex.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "CiteEnginesList.h"
21 #include "Encoding.h"
22 #include "FuncRequest.h"
23 #include "GuiApplication.h"
24 #include "LyXRC.h"
25 #include "qt_helpers.h"
26 #include "TextClass.h"
27 #include "Validator.h"
28
29 #include "ButtonPolicy.h"
30 #include "FancyLineEdit.h"
31
32 #include "frontends/alert.h"
33
34 #include "insets/InsetBibtex.h"
35
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"
42
43 #include <QDialogButtonBox>
44 #include <QPushButton>
45 #include <QListWidget>
46 #include <QCheckBox>
47 #include <QLineEdit>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53 namespace frontend {
54
55
56 GuiBibtex::GuiBibtex(GuiView & lv)
57         : GuiDialog(lv, "bibtex", qt_("BibTeX Bibliography")),
58           params_(insetCode("bibtex"))
59 {
60         setupUi(this);
61
62         QDialog::setModal(true);
63         setWindowModality(Qt::WindowModal);
64
65         // The filter bar
66         filter_ = new FancyLineEdit(this);
67         filter_->setClearButton(true);
68         filter_->setPlaceholderText(qt_("All avail. databases"));
69
70         filterBarL->addWidget(filter_, 0);
71         findKeysLA->setBuddy(filter_);
72
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()));
91
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()));
101
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()));
111 #else
112         connect(filter_, &FancyLineEdit::downPressed,
113                 availableLV, [this](){ focusAndHighlight(availableLV); });
114 #endif
115
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.")));
119
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);
128
129 #if (QT_VERSION < 0x050000)
130         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
131 #else
132         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
133 #endif
134
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()));
140         }
141         QMap<QString, QString>::const_iterator it = encodings_.constBegin();
142         while (it != encodings_.constEnd()) {
143                 bibEncodingCO->addItem(it.key(), it.value());
144                 ++it;
145         }
146
147         setFocusProxy(filter_);
148 }
149
150
151 void GuiBibtex::init()
152 {
153         all_bibs_ = bibFiles(false);
154         available_model_.setStringList(all_bibs_);
155
156         QString bibs = toqstr(params_["bibfiles"]);
157         if (bibs.isEmpty())
158                 selected_bibs_.clear();
159         else
160                 selected_bibs_ = bibs.split(",");
161         setSelectedBibs(selected_bibs_);
162
163         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
164         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
165         selectionManager->update();
166 }
167
168
169 void GuiBibtex::change_adaptor()
170 {
171         setButtons();
172         changed();
173 }
174
175
176 void GuiBibtex::setButtons()
177 {
178         int const srows = selectedLV->model()->rowCount();
179         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
180         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
181 }
182
183
184 void GuiBibtex::selUpdated()
185 {
186         selectionManager->update();
187         editPB->setEnabled(deletePB->isEnabled());
188         changed();
189 }
190
191
192 void GuiBibtex::on_buttonBox_accepted()
193 {
194         applyView();
195         clearSelection();
196         hide();
197 }
198
199
200 void GuiBibtex::browseBstPressed()
201 {
202         QString const file = browseBst(QString());
203
204         if (file.isEmpty())
205                 return;
206
207         QString const filen = changeExtension(file, "");
208         bool present = false;
209         int pres = 0;
210
211         for (int i = 0; i != styleCB->count(); ++i) {
212                 if (styleCB->itemText(i) == filen) {
213                         present = true;
214                         pres = i;
215                 }
216         }
217
218         if (!present)
219                 styleCB->insertItem(0, filen);
220
221         styleCB->setCurrentIndex(pres);
222         changed();
223 }
224
225
226 void GuiBibtex::browseBibPressed()
227 {
228         QString const file = browseBib(QString()).trimmed();
229
230         if (file.isEmpty())
231                 return;
232
233         QString const f = changeExtension(file, "");
234
235         if (!selected_bibs_.contains(f)) {
236                 selected_bibs_.append(f);
237                 setSelectedBibs(selected_bibs_);
238                 changed();
239         }
240 }
241
242
243 void GuiBibtex::on_editPB_clicked()
244 {
245         QModelIndexList selIdx =
246                 selectedLV->selectionModel()->selectedIndexes();
247         if (selIdx.isEmpty())
248                 return;
249         QModelIndex idx = selIdx.first();
250         QString sel = idx.data().toString();
251         FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
252         dispatch(fr);
253 }
254
255
256 void GuiBibtex::rescanClicked()
257 {
258         rescanBibStyles();
259         updateContents();
260 }
261
262
263 void GuiBibtex::clearSelection()
264 {
265         selected_bibs_.clear();
266         setSelectedBibs(selected_bibs_);
267 }
268
269
270 void GuiBibtex::setSelectedBibs(QStringList const & sl)
271 {
272         selected_model_.clear();
273         QStringList headers;
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);
281         if (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."));
287         } else {
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"));
291         }
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();
296                 si->setData(*it);
297                 si->setText(*it);
298                 si->setToolTip(*it);
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());
307                         ++it;
308                 }
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);
312         }
313         editPB->setEnabled(deletePB->isEnabled());
314 }
315
316
317 QStringList GuiBibtex::selectedBibs()
318 {
319         QStringList res;
320         for (int i = 0; i != selected_model_.rowCount(); ++i) {
321                 QStandardItem const * item = selected_model_.item(i);
322                 if (item)
323                         res.append(item->text());
324         }
325         return res;
326 }
327
328
329 void GuiBibtex::databaseChanged()
330 {
331         selected_bibs_ = selectedBibs();
332         setSelectedBibs(selected_bibs_);
333 }
334
335
336 void GuiBibtex::updateContents()
337 {
338         bool const bibtopic = usingBibtopic();
339         bool const biblatex = usingBiblatex();
340
341         if (biblatex)
342                 setTitle(qt_("Biblatex Bibliography"));
343         else
344                 setTitle(qt_("BibTeX Bibliography"));
345
346         QString const bibstyle = styleFile();
347
348         bool const hasbibintoc = buffer().params().documentClass().bibInToc()
349                         && !biblatex;
350
351         bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
352         bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
353
354         btPrintCO->clear();
355         btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
356         if (bibtopic)
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"));
361
362         docstring btprint = params_["btprint"];
363         if (btprint.empty())
364                 // default
365                 btprint = from_ascii("btPrintCited");
366         btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
367
368         docstring encoding = params_["encoding"];
369         if (encoding.empty())
370                 // default
371                 encoding = from_ascii("default");
372         bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
373
374         // Only useful for biblatex
375         biblatexOptsLA->setVisible(biblatex);
376         biblatexOptsLE->setVisible(biblatex);
377
378         // only useful for BibTeX
379         bstGB->setVisible(!biblatex);
380
381         if (!biblatex) {
382                 styleCB->clear();
383
384                 int item_nr = -1;
385
386                 QStringList const str = bibStyles();
387                 for (int i = 0; i != str.count(); ++i) {
388                         QString item = changeExtension(str[i], "");
389                         if (item == bibstyle)
390                                 item_nr = i;
391                         styleCB->addItem(item);
392                 }
393
394                 if (item_nr == -1 && !bibstyle.isEmpty()) {
395                         styleCB->addItem(bibstyle);
396                         item_nr = styleCB->count() - 1;
397                 }
398
399
400                 if (item_nr != -1)
401                         styleCB->setCurrentIndex(item_nr);
402                 else
403                         styleCB->clearEditText();
404         } else
405                 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
406
407         setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
408         editPB->setEnabled(deletePB->isEnabled());
409 }
410
411
412 void GuiBibtex::applyView()
413 {
414         docstring dbs;
415
416         int maxCount = selected_bibs_.count();
417         for (int i = 0; i < maxCount; i++) {
418                 if (i != 0)
419                         dbs += ',';
420                 QString item = selected_bibs_.at(i);
421                 docstring bibfile = qstring_to_ucs4(item);
422                 dbs += bibfile;
423         }
424
425         params_["bibfiles"] = dbs;
426
427         docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
428         bool const bibtotoc = bibtocCB->isChecked();
429
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");
436         } else {
437                 // only style. An empty one is valid, because some
438                 // documentclasses have an own \bibliographystyle{}
439                 // command!
440                 params_["options"] = bibstyle;
441         }
442
443         params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
444
445         params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
446
447         params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
448
449         if (usingBiblatex())
450                 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
451 }
452
453
454 QString GuiBibtex::browseBib(QString const & in_name) const
455 {
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);
461 }
462
463
464 QString GuiBibtex::browseBst(QString const & in_name) const
465 {
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);
471 }
472
473
474 QStringList GuiBibtex::bibStyles() const
475 {
476         QStringList sdata = texFileList("bstFiles.lst");
477         // test whether we have a valid list, otherwise run rescan
478         if (sdata.isEmpty()) {
479                 rescanBibStyles();
480                 sdata = texFileList("bstFiles.lst");
481         }
482         for (int i = 0; i != sdata.size(); ++i)
483                 sdata[i] = onlyFileName(sdata[i]);
484         // sort on filename only (no path)
485         sdata.sort();
486         return sdata;
487 }
488
489
490 QStringList GuiBibtex::bibFiles(bool const extension) const
491 {
492         QStringList sdata = texFileList("bibFiles.lst");
493         // test whether we have a valid list, otherwise run rescan
494         if (sdata.isEmpty()) {
495                 rescanBibStyles();
496                 sdata = texFileList("bibFiles.lst");
497         }
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)
502         sdata.sort();
503         return sdata;
504 }
505
506
507 vector<docstring> GuiBibtex::getFileEncodings()
508 {
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));
516         }
517         return res;
518 }
519
520
521 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
522 {
523         for (docstring const & s: m) {
524                 docstring key;
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));
530                 if (!qmil.empty()) {
531                         QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
532                         cb->setCurrentIndex(cb->findData(enc));
533                 }
534         }
535 }
536
537
538 void GuiBibtex::rescanBibStyles() const
539 {
540         if (usingBiblatex())
541                 rescanTexStyles("bib");
542         else
543                 rescanTexStyles("bst bib");
544 }
545
546
547 void GuiBibtex::findText(QString const & text)
548 {
549         QStringList const result = bibFiles(false).filter(text);
550         available_model_.setStringList(result);
551 }
552
553
554 void GuiBibtex::filterChanged(const QString & text)
555 {
556         if (!text.isEmpty()) {
557                 findText(filter_->text());
558                 return;
559         }
560         findText(filter_->text());
561         filter_->setFocus();
562 }
563
564
565 void GuiBibtex::filterPressed()
566 {
567         findText(filter_->text());
568 }
569
570
571 void GuiBibtex::resetFilter()
572 {
573         filter_->setText(QString());
574         findText(filter_->text());
575 }
576
577
578
579 bool GuiBibtex::usingBibtopic() const
580 {
581         return buffer().params().useBibtopic();
582 }
583
584
585 bool GuiBibtex::bibtotoc() const
586 {
587         return prefixIs(to_utf8(params_["options"]), "bibtotoc");
588 }
589
590
591 bool GuiBibtex::usingBiblatex() const
592 {
593         return buffer().masterBuffer()->params().useBiblatex();
594 }
595
596
597 QString GuiBibtex::styleFile() const
598 {
599         // the different bibtex packages have (and need) their
600         // own "plain" stylefiles
601         QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
602
603         QString bst = toqstr(params_["options"]);
604         if (bibtotoc()){
605                 // bibstyle exists?
606                 int pos = bst.indexOf(',');
607                 if (pos != -1) {
608                         // FIXME: check
609                         // docstring bibtotoc = from_ascii("bibtotoc");
610                         // bst = split(bst, bibtotoc, ',');
611                         bst = bst.mid(pos + 1);
612                 } else {
613                         bst.clear();
614                 }
615         }
616
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())
621                 bst = defaultstyle;
622
623         return bst;
624 }
625
626
627 bool GuiBibtex::initialiseParams(std::string const & sdata)
628 {
629         InsetCommand::string2params(sdata, params_);
630         init();
631         return true;
632 }
633
634
635 void GuiBibtex::dispatchParams()
636 {
637         std::string const lfun = InsetCommand::params2string(params_);
638         dispatch(FuncRequest(getLfun(), lfun));
639         connectToNewInset();
640 }
641
642
643 } // namespace frontend
644 } // namespace lyx
645
646 #include "moc_GuiBibtex.cpp"