]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiBibtex.cpp
Rework BibTeX dialog
[lyx.git] / src / frontends / qt4 / 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 "Validator.h"
27
28 #include "ui_BibtexAddUi.h"
29
30 #include "ButtonPolicy.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         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()));
103
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()));
113 #else
114         connect(filter_, &FancyLineEdit::downPressed,
115                 availableLV, [=](){ focusAndHighlight(availableLV); });
116 #endif
117
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.")));
121
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);
130
131         // Always put the default encoding in the first position.
132         bibEncodingCO->addItem(qt_("Document Encoding"), "default");
133         QMap<QString, QString> encodinglist;
134         for (auto const & encvar : encodings) {
135                 if (!encvar.unsafe() && !encvar.guiName().empty())
136                         encodinglist.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
137         }
138         QMap<QString, QString>::const_iterator it = encodinglist.constBegin();
139         while (it != encodinglist.constEnd()) {
140                 bibEncodingCO->addItem(it.key(), it.value());
141                 ++it;
142         }
143
144         setFocusProxy(filter_);
145 }
146
147
148 void GuiBibtex::init()
149 {
150         all_bibs_ = bibFiles(false);
151         available_model_.setStringList(all_bibs_);
152
153         QString bibs = toqstr(params_["bibfiles"]);
154         if (bibs.isEmpty())
155                 selected_bibs_.clear();
156         else
157                 selected_bibs_ = bibs.split(",");
158         setSelectedBibs(selected_bibs_);
159
160         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
161         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
162         selectionManager->update();
163 }
164
165
166 void GuiBibtex::change_adaptor()
167 {
168         setButtons();
169         changed();
170 }
171
172
173 void GuiBibtex::setButtons()
174 {
175         int const srows = selectedLV->model()->rowCount();
176         buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
177         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
178 }
179
180
181 void GuiBibtex::selUpdated()
182 {
183         selectionManager->update();
184         changed();
185 }
186
187
188 void GuiBibtex::on_buttonBox_accepted()
189 {
190         applyView();
191         clearSelection();
192         hide();
193 }
194
195
196 void GuiBibtex::browseBstPressed()
197 {
198         QString const file = browseBst(QString());
199
200         if (file.isEmpty())
201                 return;
202
203         QString const filen = changeExtension(file, "");
204         bool present = false;
205         unsigned int pres = 0;
206
207         for (int i = 0; i != styleCB->count(); ++i) {
208                 if (styleCB->itemText(i) == filen) {
209                         present = true;
210                         pres = i;
211                 }
212         }
213
214         if (!present)
215                 styleCB->insertItem(0, filen);
216
217         styleCB->setCurrentIndex(pres);
218         changed();
219 }
220
221
222 void GuiBibtex::browseBibPressed()
223 {
224         QString const file = browseBib(QString()).trimmed();
225
226         if (file.isEmpty())
227                 return;
228
229         QString const f = changeExtension(file, "");
230
231         if (!selected_bibs_.contains(f)) {
232                 selected_bibs_.append(f);
233                 setSelectedBibs(selected_bibs_);
234                 changed();
235         }
236 }
237
238
239 void GuiBibtex::rescanClicked()
240 {
241         rescanBibStyles();
242         updateContents();
243 }
244
245
246 void GuiBibtex::clearSelection()
247 {
248         selected_bibs_.clear();
249         setSelectedBibs(selected_bibs_);
250 }
251
252
253 void GuiBibtex::setSelectedBibs(QStringList const sl)
254 {
255         selected_model_.clear();
256         QStringList::const_iterator it  = sl.begin();
257         QStringList::const_iterator end = sl.end();
258         for (int i = 0; it != end; ++it, ++i) {
259                 QStandardItem * si = new QStandardItem();
260                 si->setData(*it);
261                 si->setText(*it);
262                 si->setToolTip(*it);
263                 si->setEditable(false);
264                 selected_model_.insertRow(i, si);
265         }
266 }
267
268
269 QStringList GuiBibtex::selectedBibs()
270 {
271         QStringList res;
272         for (int i = 0; i != selected_model_.rowCount(); ++i) {
273                 QStandardItem const * item = selected_model_.item(i);
274                 if (item)
275                         res.append(item->text());
276         }
277         return res;
278 }
279
280
281 void GuiBibtex::databaseChanged()
282 {
283         QString const item = selectionManager->getSelectedIndex().data().toString();
284         if (!selected_bibs_.contains(item)) {
285                 selected_bibs_.append(item);
286         } else
287                 selected_bibs_ = selectedBibs();
288         setSelectedBibs(selected_bibs_);
289 }
290
291
292 void GuiBibtex::updateContents()
293 {
294         bool bibtopic = usingBibtopic();
295         bool biblatex = usingBiblatex();
296
297         if (biblatex)
298                 setTitle(qt_("Biblatex Bibliography"));
299         else
300                 setTitle(qt_("BibTeX Bibliography"));
301
302         QString const bibstyle = styleFile();
303
304         bibtocCB->setChecked(bibtotoc() && !bibtopic);
305         bibtocCB->setEnabled(!bibtopic);
306
307         btPrintCO->clear();
308         btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
309         if (bibtopic)
310                 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
311         btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
312         if (usingBiblatex() && !buffer().masterParams().multibib.empty())
313                 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
314
315         docstring btprint = params_["btprint"];
316         if (btprint.empty())
317                 // default
318                 btprint = from_ascii("btPrintCited");
319         btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
320
321         docstring encoding = params_["encoding"];
322         if (encoding.empty())
323                 // default
324                 encoding = from_ascii("default");
325         bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
326
327         // Only useful for biblatex
328         biblatexOptsLA->setVisible(biblatex);
329         biblatexOptsLE->setVisible(biblatex);
330
331         // only useful for BibTeX
332         bstGB->setVisible(!biblatex);
333
334         if (!biblatex) {
335                 styleCB->clear();
336
337                 int item_nr = -1;
338
339                 QStringList const str = bibStyles();
340                 for (int i = 0; i != str.count(); ++i) {
341                         QString item = changeExtension(str[i], "");
342                         if (item == bibstyle)
343                                 item_nr = i;
344                         styleCB->addItem(item);
345                 }
346
347                 if (item_nr == -1 && !bibstyle.isEmpty()) {
348                         styleCB->addItem(bibstyle);
349                         item_nr = styleCB->count() - 1;
350                 }
351
352
353                 if (item_nr != -1)
354                         styleCB->setCurrentIndex(item_nr);
355                 else
356                         styleCB->clearEditText();
357         } else
358                 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
359 }
360
361
362 void GuiBibtex::applyView()
363 {
364         docstring dbs;
365
366         unsigned int maxCount = selected_bibs_.count();
367         for (unsigned int i = 0; i < maxCount; i++) {
368                 if (i != 0)
369                         dbs += ',';
370                 QString item = selected_bibs_.at(i);
371                 docstring bibfile = qstring_to_ucs4(item);
372                 dbs += bibfile;
373         }
374
375         params_["bibfiles"] = dbs;
376
377         docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
378         bool const bibtotoc = bibtocCB->isChecked();
379
380         if (bibtotoc && !bibstyle.empty()) {
381                 // both bibtotoc and style
382                 params_["options"] = "bibtotoc," + bibstyle;
383         } else if (bibtotoc) {
384                 // bibtotoc and no style
385                 params_["options"] = from_ascii("bibtotoc");
386         } else {
387                 // only style. An empty one is valid, because some
388                 // documentclasses have an own \bibliographystyle{}
389                 // command!
390                 params_["options"] = bibstyle;
391         }
392
393         params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
394
395         params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
396
397         params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
398 }
399
400
401 QString GuiBibtex::browseBib(QString const & in_name) const
402 {
403         QString const label1 = qt_("D&ocuments");
404         QString const dir1 = toqstr(lyxrc.document_path);
405         QStringList const filter(qt_("BibTeX Databases (*.bib)"));
406         return browseRelToParent(in_name, bufferFilePath(),
407                 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
408 }
409
410
411 QString GuiBibtex::browseBst(QString const & in_name) const
412 {
413         QString const label1 = qt_("D&ocuments");
414         QString const dir1 = toqstr(lyxrc.document_path);
415         QStringList const filter(qt_("BibTeX Styles (*.bst)"));
416         return browseRelToParent(in_name, bufferFilePath(),
417                 qt_("Select a BibTeX style"), filter, false, label1, dir1);
418 }
419
420
421 QStringList GuiBibtex::bibStyles() const
422 {
423         QStringList sdata = texFileList("bstFiles.lst");
424         // test whether we have a valid list, otherwise run rescan
425         if (sdata.isEmpty()) {
426                 rescanBibStyles();
427                 sdata = texFileList("bstFiles.lst");
428         }
429         for (int i = 0; i != sdata.size(); ++i)
430                 sdata[i] = onlyFileName(sdata[i]);
431         // sort on filename only (no path)
432         sdata.sort();
433         return sdata;
434 }
435
436
437 QStringList GuiBibtex::bibFiles(bool const extension) const
438 {
439         QStringList sdata = texFileList("bibFiles.lst");
440         // test whether we have a valid list, otherwise run rescan
441         if (sdata.isEmpty()) {
442                 rescanBibStyles();
443                 sdata = texFileList("bibFiles.lst");
444         }
445         for (int i = 0; i != sdata.size(); ++i)
446                 sdata[i] = extension ? onlyFileName(sdata[i])
447                                      : changeExtension(onlyFileName(sdata[i]), "");
448         // sort on filename only (no path)
449         sdata.sort();
450         return sdata;
451 }
452
453
454 void GuiBibtex::rescanBibStyles() const
455 {
456         if (usingBiblatex())
457                 rescanTexStyles("bib");
458         else
459                 rescanTexStyles("bst bib");
460 }
461
462
463 void GuiBibtex::findText(QString const & text)
464 {
465         QStringList const result = bibFiles(false).filter(text);
466         available_model_.setStringList(result);
467 }
468
469
470 void GuiBibtex::filterChanged(const QString & text)
471 {
472         if (!text.isEmpty()) {
473                 findText(filter_->text());
474                 return;
475         }
476         findText(filter_->text());
477         filter_->setFocus();
478 }
479
480
481 void GuiBibtex::filterPressed()
482 {
483         findText(filter_->text());
484 }
485
486
487 void GuiBibtex::resetFilter()
488 {
489         filter_->setText(QString());
490         findText(filter_->text());
491 }
492
493
494
495 bool GuiBibtex::usingBibtopic() const
496 {
497         return buffer().params().useBibtopic();
498 }
499
500
501 bool GuiBibtex::bibtotoc() const
502 {
503         return prefixIs(to_utf8(params_["options"]), "bibtotoc");
504 }
505
506
507 bool GuiBibtex::usingBiblatex() const
508 {
509         return buffer().masterBuffer()->params().useBiblatex();
510 }
511
512
513 QString GuiBibtex::styleFile() const
514 {
515         // the different bibtex packages have (and need) their
516         // own "plain" stylefiles
517         QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
518
519         QString bst = toqstr(params_["options"]);
520         if (bibtotoc()){
521                 // bibstyle exists?
522                 int pos = bst.indexOf(',');
523                 if (pos != -1) {
524                         // FIXME: check
525                         // docstring bibtotoc = from_ascii("bibtotoc");
526                         // bst = split(bst, bibtotoc, ',');
527                         bst = bst.mid(pos + 1);
528                 } else {
529                         bst.clear();
530                 }
531         }
532
533         // propose default style file for new insets
534         // existing insets might have (legally) no bst files
535         // (if the class already provides a style)
536         if (bst.isEmpty() && params_["bibfiles"].empty())
537                 bst = defaultstyle;
538
539         return bst;
540 }
541
542
543 bool GuiBibtex::initialiseParams(std::string const & sdata)
544 {
545         InsetCommand::string2params(sdata, params_);
546         init();
547         return true;
548 }
549
550
551 void GuiBibtex::dispatchParams()
552 {
553         std::string const lfun = InsetCommand::params2string(params_);
554         dispatch(FuncRequest(getLfun(), lfun));
555 }
556
557
558 Dialog * createGuiBibtex(GuiView & lv) { return new GuiBibtex(lv); }
559
560
561 } // namespace frontend
562 } // namespace lyx
563
564 #include "moc_GuiBibtex.cpp"