]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiBibtex.cpp
Improve some debug messages
[lyx.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_->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"));
72
73         filterBarL->addWidget(filter_, 0);
74         findKeysLA->setBuddy(filter_);
75
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()));
94
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()));
104
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()));
114 #else
115         connect(filter_, &FancyLineEdit::downPressed,
116                 availableLV, [=](){ focusAndHighlight(availableLV); });
117 #endif
118
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.")));
122
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);
131
132 #if (QT_VERSION < 0x050000)
133         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
134 #else
135         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
136 #endif
137
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()));
143         }
144         QMap<QString, QString>::const_iterator it = encodings_.constBegin();
145         while (it != encodings_.constEnd()) {
146                 bibEncodingCO->addItem(it.key(), it.value());
147                 ++it;
148         }
149
150         setFocusProxy(filter_);
151 }
152
153
154 void GuiBibtex::init()
155 {
156         all_bibs_ = bibFiles(false);
157         available_model_.setStringList(all_bibs_);
158
159         QString bibs = toqstr(params_["bibfiles"]);
160         if (bibs.isEmpty())
161                 selected_bibs_.clear();
162         else
163                 selected_bibs_ = bibs.split(",");
164         setSelectedBibs(selected_bibs_);
165
166         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
167         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
168         selectionManager->update();
169 }
170
171
172 void GuiBibtex::change_adaptor()
173 {
174         setButtons();
175         changed();
176 }
177
178
179 void GuiBibtex::setButtons()
180 {
181         int const srows = selectedLV->model()->rowCount();
182         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
183         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
184 }
185
186
187 void GuiBibtex::selUpdated()
188 {
189         selectionManager->update();
190         editPB->setEnabled(deletePB->isEnabled());
191         changed();
192 }
193
194
195 void GuiBibtex::on_buttonBox_accepted()
196 {
197         applyView();
198         clearSelection();
199         hide();
200 }
201
202
203 void GuiBibtex::browseBstPressed()
204 {
205         QString const file = browseBst(QString());
206
207         if (file.isEmpty())
208                 return;
209
210         QString const filen = changeExtension(file, "");
211         bool present = false;
212         int pres = 0;
213
214         for (int i = 0; i != styleCB->count(); ++i) {
215                 if (styleCB->itemText(i) == filen) {
216                         present = true;
217                         pres = i;
218                 }
219         }
220
221         if (!present)
222                 styleCB->insertItem(0, filen);
223
224         styleCB->setCurrentIndex(pres);
225         changed();
226 }
227
228
229 void GuiBibtex::browseBibPressed()
230 {
231         QString const file = browseBib(QString()).trimmed();
232
233         if (file.isEmpty())
234                 return;
235
236         QString const f = changeExtension(file, "");
237
238         if (!selected_bibs_.contains(f)) {
239                 selected_bibs_.append(f);
240                 setSelectedBibs(selected_bibs_);
241                 changed();
242         }
243 }
244
245
246 void GuiBibtex::on_editPB_clicked()
247 {
248         QModelIndexList selIdx =
249                 selectedLV->selectionModel()->selectedIndexes();
250         if (selIdx.isEmpty())
251                 return;
252         QModelIndex idx = selIdx.first();
253         QString sel = idx.data().toString();
254         FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
255         dispatch(fr);
256 }
257
258
259 void GuiBibtex::rescanClicked()
260 {
261         rescanBibStyles();
262         updateContents();
263 }
264
265
266 void GuiBibtex::clearSelection()
267 {
268         selected_bibs_.clear();
269         setSelectedBibs(selected_bibs_);
270 }
271
272
273 void GuiBibtex::setSelectedBibs(QStringList const & sl)
274 {
275         selected_model_.clear();
276         QStringList headers;
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);
284         if (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."));
290         } else {
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"));
294         }
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();
299                 si->setData(*it);
300                 si->setText(*it);
301                 si->setToolTip(*it);
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());
310                         ++it;
311                 }
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);
315         }
316         editPB->setEnabled(deletePB->isEnabled());
317 }
318
319
320 QStringList GuiBibtex::selectedBibs()
321 {
322         QStringList res;
323         for (int i = 0; i != selected_model_.rowCount(); ++i) {
324                 QStandardItem const * item = selected_model_.item(i);
325                 if (item)
326                         res.append(item->text());
327         }
328         return res;
329 }
330
331
332 void GuiBibtex::databaseChanged()
333 {
334         selected_bibs_ = selectedBibs();
335         setSelectedBibs(selected_bibs_);
336 }
337
338
339 void GuiBibtex::updateContents()
340 {
341         bool const bibtopic = usingBibtopic();
342         bool const biblatex = usingBiblatex();
343
344         if (biblatex)
345                 setTitle(qt_("Biblatex Bibliography"));
346         else
347                 setTitle(qt_("BibTeX Bibliography"));
348
349         QString const bibstyle = styleFile();
350
351         bool const hasbibintoc = buffer().params().documentClass().bibInToc()
352                         && !biblatex;
353
354         bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
355         bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
356
357         btPrintCO->clear();
358         btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
359         if (bibtopic)
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"));
364
365         docstring btprint = params_["btprint"];
366         if (btprint.empty())
367                 // default
368                 btprint = from_ascii("btPrintCited");
369         btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
370
371         docstring encoding = params_["encoding"];
372         if (encoding.empty())
373                 // default
374                 encoding = from_ascii("default");
375         bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
376
377         // Only useful for biblatex
378         biblatexOptsLA->setVisible(biblatex);
379         biblatexOptsLE->setVisible(biblatex);
380
381         // only useful for BibTeX
382         bstGB->setVisible(!biblatex);
383
384         if (!biblatex) {
385                 styleCB->clear();
386
387                 int item_nr = -1;
388
389                 QStringList const str = bibStyles();
390                 for (int i = 0; i != str.count(); ++i) {
391                         QString item = changeExtension(str[i], "");
392                         if (item == bibstyle)
393                                 item_nr = i;
394                         styleCB->addItem(item);
395                 }
396
397                 if (item_nr == -1 && !bibstyle.isEmpty()) {
398                         styleCB->addItem(bibstyle);
399                         item_nr = styleCB->count() - 1;
400                 }
401
402
403                 if (item_nr != -1)
404                         styleCB->setCurrentIndex(item_nr);
405                 else
406                         styleCB->clearEditText();
407         } else
408                 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
409
410         setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
411         editPB->setEnabled(deletePB->isEnabled());
412 }
413
414
415 void GuiBibtex::applyView()
416 {
417         docstring dbs;
418
419         int maxCount = selected_bibs_.count();
420         for (int i = 0; i < maxCount; i++) {
421                 if (i != 0)
422                         dbs += ',';
423                 QString item = selected_bibs_.at(i);
424                 docstring bibfile = qstring_to_ucs4(item);
425                 dbs += bibfile;
426         }
427
428         params_["bibfiles"] = dbs;
429
430         docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
431         bool const bibtotoc = bibtocCB->isChecked();
432
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");
439         } else {
440                 // only style. An empty one is valid, because some
441                 // documentclasses have an own \bibliographystyle{}
442                 // command!
443                 params_["options"] = bibstyle;
444         }
445
446         params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
447
448         params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
449
450         params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
451
452         if (usingBiblatex())
453                 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
454 }
455
456
457 QString GuiBibtex::browseBib(QString const & in_name) const
458 {
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);
464 }
465
466
467 QString GuiBibtex::browseBst(QString const & in_name) const
468 {
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);
474 }
475
476
477 QStringList GuiBibtex::bibStyles() const
478 {
479         QStringList sdata = texFileList("bstFiles.lst");
480         // test whether we have a valid list, otherwise run rescan
481         if (sdata.isEmpty()) {
482                 rescanBibStyles();
483                 sdata = texFileList("bstFiles.lst");
484         }
485         for (int i = 0; i != sdata.size(); ++i)
486                 sdata[i] = onlyFileName(sdata[i]);
487         // sort on filename only (no path)
488         sdata.sort();
489         return sdata;
490 }
491
492
493 QStringList GuiBibtex::bibFiles(bool const extension) const
494 {
495         QStringList sdata = texFileList("bibFiles.lst");
496         // test whether we have a valid list, otherwise run rescan
497         if (sdata.isEmpty()) {
498                 rescanBibStyles();
499                 sdata = texFileList("bibFiles.lst");
500         }
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)
505         sdata.sort();
506         return sdata;
507 }
508
509
510 vector<docstring> GuiBibtex::getFileEncodings()
511 {
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));
519         }
520         return res;
521 }
522
523
524 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
525 {
526         for (docstring const & s: m) {
527                 docstring key;
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));
533                 if (!qmil.empty()) {
534                         QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
535                         cb->setCurrentIndex(cb->findData(enc));
536                 }
537         }
538 }
539
540
541 void GuiBibtex::rescanBibStyles() const
542 {
543         if (usingBiblatex())
544                 rescanTexStyles("bib");
545         else
546                 rescanTexStyles("bst bib");
547 }
548
549
550 void GuiBibtex::findText(QString const & text)
551 {
552         QStringList const result = bibFiles(false).filter(text);
553         available_model_.setStringList(result);
554 }
555
556
557 void GuiBibtex::filterChanged(const QString & text)
558 {
559         if (!text.isEmpty()) {
560                 findText(filter_->text());
561                 return;
562         }
563         findText(filter_->text());
564         filter_->setFocus();
565 }
566
567
568 void GuiBibtex::filterPressed()
569 {
570         findText(filter_->text());
571 }
572
573
574 void GuiBibtex::resetFilter()
575 {
576         filter_->setText(QString());
577         findText(filter_->text());
578 }
579
580
581
582 bool GuiBibtex::usingBibtopic() const
583 {
584         return buffer().params().useBibtopic();
585 }
586
587
588 bool GuiBibtex::bibtotoc() const
589 {
590         return prefixIs(to_utf8(params_["options"]), "bibtotoc");
591 }
592
593
594 bool GuiBibtex::usingBiblatex() const
595 {
596         return buffer().masterBuffer()->params().useBiblatex();
597 }
598
599
600 QString GuiBibtex::styleFile() const
601 {
602         // the different bibtex packages have (and need) their
603         // own "plain" stylefiles
604         QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
605
606         QString bst = toqstr(params_["options"]);
607         if (bibtotoc()){
608                 // bibstyle exists?
609                 int pos = bst.indexOf(',');
610                 if (pos != -1) {
611                         // FIXME: check
612                         // docstring bibtotoc = from_ascii("bibtotoc");
613                         // bst = split(bst, bibtotoc, ',');
614                         bst = bst.mid(pos + 1);
615                 } else {
616                         bst.clear();
617                 }
618         }
619
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())
624                 bst = defaultstyle;
625
626         return bst;
627 }
628
629
630 bool GuiBibtex::initialiseParams(std::string const & sdata)
631 {
632         InsetCommand::string2params(sdata, params_);
633         init();
634         return true;
635 }
636
637
638 void GuiBibtex::dispatchParams()
639 {
640         std::string const lfun = InsetCommand::params2string(params_);
641         dispatch(FuncRequest(getLfun(), lfun));
642 }
643
644
645 Dialog * createGuiBibtex(GuiView & lv) { return new GuiBibtex(lv); }
646
647
648 } // namespace frontend
649 } // namespace lyx
650
651 #include "moc_GuiBibtex.cpp"