]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiBibtex.cpp
Completion: handle undo in insets' insertCompletion methods
[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/docstring_list.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/FileName.h"
40 #include "support/filetools.h" // changeExtension
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43
44 #include <QDialogButtonBox>
45 #include <QPushButton>
46 #include <QListWidget>
47 #include <QCheckBox>
48 #include <QLineEdit>
49
50 using namespace std;
51 using namespace lyx::support;
52
53 namespace lyx {
54 namespace frontend {
55
56
57 GuiBibtex::GuiBibtex(GuiView & lv)
58         : GuiDialog(lv, "bibtex", qt_("BibTeX Bibliography")),
59           params_(insetCode("bibtex"))
60 {
61         setupUi(this);
62
63         QDialog::setModal(true);
64         setWindowModality(Qt::WindowModal);
65
66         // The filter bar
67         filter_ = new FancyLineEdit(this);
68         filter_->setClearButton(true);
69         filter_->setPlaceholderText(qt_("All avail. databases"));
70
71         filterBarL->addWidget(filter_, 0);
72         findKeysLA->setBuddy(filter_);
73
74         connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
75                 this, SLOT(slotButtonBox(QAbstractButton *)));
76         connect(stylePB, SIGNAL(clicked()),
77                 this, SLOT(browseBstPressed()));
78         connect(styleCB, SIGNAL(editTextChanged(QString)),
79                 this, SLOT(change_adaptor()));
80         connect(bibtocCB, SIGNAL(clicked()),
81                 this, SLOT(change_adaptor()));
82         connect(btPrintCO, SIGNAL(activated(int)),
83                 this, SLOT(change_adaptor()));
84         connect(rescanPB, SIGNAL(clicked()),
85                 this, SLOT(rescanClicked()));
86         connect(biblatexOptsLE, SIGNAL(textChanged(QString)),
87                 this, SLOT(change_adaptor()));
88         connect(bibEncodingCO, SIGNAL(activated(int)),
89                 this, SLOT(change_adaptor()));
90         connect(browseBibPB, SIGNAL(clicked()),
91                 this, SLOT(browseBibPressed()));
92         connect(inheritPB, SIGNAL(clicked()),
93                 this, SLOT(inheritPressed()));
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, [this](){ 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         inheritPB->setEnabled(hasInherits());
185 }
186
187
188 void GuiBibtex::selUpdated()
189 {
190         selectionManager->update();
191         editPB->setEnabled(deletePB->isEnabled());
192         changed();
193 }
194
195
196 void GuiBibtex::on_buttonBox_accepted()
197 {
198         applyView();
199         clearSelection();
200         hide();
201 }
202
203
204 void GuiBibtex::browseBstPressed()
205 {
206         QString const file = browseBst(QString());
207
208         if (file.isEmpty())
209                 return;
210
211         QString const filen = changeExtension(file, "");
212         bool present = false;
213         int pres = 0;
214
215         for (int i = 0; i != styleCB->count(); ++i) {
216                 if (styleCB->itemText(i) == filen) {
217                         present = true;
218                         pres = i;
219                 }
220         }
221
222         if (!present)
223                 styleCB->insertItem(0, filen);
224
225         styleCB->setCurrentIndex(pres);
226         changed();
227 }
228
229
230 void GuiBibtex::browseBibPressed()
231 {
232         QString const file = browseBib(QString()).trimmed();
233
234         if (file.isEmpty())
235                 return;
236
237         QString const f = changeExtension(file, "");
238
239         if (!selected_bibs_.contains(f)) {
240                 selected_bibs_.append(f);
241                 setSelectedBibs(selected_bibs_);
242                 changed();
243         }
244 }
245
246
247 bool GuiBibtex::hasInherits()
248 {
249         if (!buffer().parent())
250                 return false;
251
252         docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
253         if (mbibs.empty())
254                 return false;
255
256         for (auto const & f : mbibs) {
257                 if (!selected_bibs_.contains(toqstr(f)))
258                         return true;
259         }
260         return false;
261 }
262
263
264 void GuiBibtex::inheritPressed()
265 {
266         docstring_list const mbibs = buffer().masterBuffer()->getBibfiles();
267         bool chng = false;
268         vector<docstring> nfe;
269         for (auto const & f : mbibs) {
270                 if (!selected_bibs_.contains(toqstr(f))) {
271                         selected_bibs_.append(toqstr(f));
272                         setSelectedBibs(selected_bibs_);
273                         string enc;
274                         if (usingBiblatex()) {
275                                 string const bfe = buffer().masterParams().bibFileEncoding(to_utf8(f));
276                                 if (!bfe.empty())
277                                         nfe.push_back(f + " " + from_utf8(bfe));
278                         }
279                         chng = true;
280                 }
281         }
282         if (chng) {
283                 if (!nfe.empty())
284                         setFileEncodings(nfe);
285                 change_adaptor();
286         }
287 }
288
289
290 void GuiBibtex::on_editPB_clicked()
291 {
292         QModelIndexList selIdx =
293                 selectedLV->selectionModel()->selectedIndexes();
294         if (selIdx.isEmpty())
295                 return;
296         QModelIndex idx = selIdx.first();
297         QString sel = idx.data().toString();
298         FuncRequest fr(LFUN_INSET_EDIT, fromqstr(sel));
299         dispatch(fr);
300 }
301
302
303 void GuiBibtex::rescanClicked()
304 {
305         rescanBibStyles();
306         updateContents();
307 }
308
309
310 void GuiBibtex::clearSelection()
311 {
312         selected_bibs_.clear();
313         setSelectedBibs(selected_bibs_);
314 }
315
316
317 void GuiBibtex::setSelectedBibs(QStringList const & sl)
318 {
319         selected_model_.clear();
320         QStringList headers;
321         headers << qt_("Database")
322                 << qt_("File Encoding");
323         selected_model_.setHorizontalHeaderLabels(headers);
324         bool const moreencs = usingBiblatex() && sl.count() > 1;
325         selectedLV->setColumnHidden(1, !moreencs);
326         selectedLV->verticalHeader()->setVisible(false);
327         selectedLV->horizontalHeader()->setVisible(moreencs);
328         if (moreencs) {
329                 bibEncodingLA->setText(qt_("General E&ncoding:"));
330                 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
331                                               "encoding than the LyX document, specify it here. "
332                                               "If indivivual databases have different encodings, "
333                                               "you can set it in the list above."));
334         } else {
335                 bibEncodingLA->setText(qt_("E&ncoding:"));
336                 bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
337                                               "encoding than the LyX document, specify it here"));
338         }
339         QStringList::const_iterator it  = sl.begin();
340         QStringList::const_iterator end = sl.end();
341         for (int i = 0; it != end; ++it, ++i) {
342                 QStandardItem * si = new QStandardItem();
343                 si->setData(*it);
344                 si->setText(*it);
345                 si->setToolTip(*it);
346                 si->setEditable(false);
347                 selected_model_.insertRow(i, si);
348                 QComboBox * cb = new QComboBox;
349                 cb->addItem(qt_("General Encoding"), "general");
350                 cb->addItem(qt_("Document Encoding"), "auto");
351                 QMap<QString, QString>::const_iterator it = encodings_.constBegin();
352                 while (it != encodings_.constEnd()) {
353                         cb->addItem(it.key(), it.value());
354                         ++it;
355                 }
356                 cb->setToolTip(qt_("If this bibliography database uses a different "
357                                    "encoding than specified below, set it here"));
358                 selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
359         }
360         editPB->setEnabled(deletePB->isEnabled());
361 }
362
363
364 QStringList GuiBibtex::selectedBibs()
365 {
366         QStringList res;
367         for (int i = 0; i != selected_model_.rowCount(); ++i) {
368                 QStandardItem const * item = selected_model_.item(i);
369                 if (item)
370                         res.append(item->text());
371         }
372         return res;
373 }
374
375
376 void GuiBibtex::databaseChanged()
377 {
378         selected_bibs_ = selectedBibs();
379         setSelectedBibs(selected_bibs_);
380 }
381
382
383 void GuiBibtex::updateContents()
384 {
385         bool const bibtopic = usingBibtopic();
386         bool const biblatex = usingBiblatex();
387
388         if (biblatex)
389                 setTitle(qt_("Biblatex Bibliography"));
390         else
391                 setTitle(qt_("BibTeX Bibliography"));
392
393         QString const bibstyle = styleFile();
394
395         bool const hasbibintoc = buffer().params().documentClass().bibInToc()
396                         && !biblatex;
397
398         bibtocCB->setChecked((bibtotoc() && !bibtopic) || hasbibintoc);
399         bibtocCB->setEnabled(!bibtopic && !hasbibintoc);
400
401         inheritPB->setEnabled(hasInherits());
402
403         btPrintCO->clear();
404         btPrintCO->addItem(qt_("all cited references"), toqstr("btPrintCited"));
405         if (bibtopic)
406                 btPrintCO->addItem(qt_("all uncited references"), toqstr("btPrintNotCited"));
407         btPrintCO->addItem(qt_("all references"), toqstr("btPrintAll"));
408         if (usingBiblatex() && !buffer().masterParams().multibib.empty())
409                 btPrintCO->addItem(qt_("all reference units"), toqstr("bibbysection"));
410
411         docstring btprint = params_["btprint"];
412         if (btprint.empty())
413                 // default
414                 btprint = from_ascii("btPrintCited");
415         btPrintCO->setCurrentIndex(btPrintCO->findData(toqstr(btprint)));
416
417         docstring encoding = params_["encoding"];
418         if (encoding.empty())
419                 // default
420                 encoding = from_ascii("default");
421         bibEncodingCO->setCurrentIndex(bibEncodingCO->findData(toqstr(encoding)));
422
423         // Only useful for biblatex
424         biblatexOptsLA->setVisible(biblatex);
425         biblatexOptsLE->setVisible(biblatex);
426
427         // only useful for BibTeX
428         bstGB->setVisible(!biblatex);
429
430         if (!biblatex) {
431                 styleCB->clear();
432
433                 int item_nr = -1;
434
435                 QStringList const str = bibStyles();
436                 for (int i = 0; i != str.count(); ++i) {
437                         QString item = changeExtension(str[i], "");
438                         if (item == bibstyle)
439                                 item_nr = i;
440                         styleCB->addItem(item);
441                 }
442
443                 if (item_nr == -1 && !bibstyle.isEmpty()) {
444                         styleCB->addItem(bibstyle);
445                         item_nr = styleCB->count() - 1;
446                 }
447
448
449                 if (item_nr != -1)
450                         styleCB->setCurrentIndex(item_nr);
451                 else
452                         styleCB->clearEditText();
453         } else
454                 biblatexOptsLE->setText(toqstr(params_["biblatexopts"]));
455
456         setFileEncodings(getVectorFromString(params_["file_encodings"], from_ascii("\t")));
457         editPB->setEnabled(deletePB->isEnabled());
458 }
459
460
461 void GuiBibtex::applyView()
462 {
463         docstring dbs;
464
465         int maxCount = selected_bibs_.count();
466         for (int i = 0; i < maxCount; i++) {
467                 if (i != 0)
468                         dbs += ',';
469                 QString item = selected_bibs_.at(i);
470                 docstring bibfile = qstring_to_ucs4(item);
471                 dbs += bibfile;
472         }
473
474         params_["bibfiles"] = dbs;
475
476         docstring const bibstyle = qstring_to_ucs4(styleCB->currentText());
477         bool const bibtotoc = bibtocCB->isChecked();
478
479         if (bibtotoc && !bibstyle.empty()) {
480                 // both bibtotoc and style
481                 params_["options"] = "bibtotoc," + bibstyle;
482         } else if (bibtotoc) {
483                 // bibtotoc and no style
484                 params_["options"] = from_ascii("bibtotoc");
485         } else {
486                 // only style. An empty one is valid, because some
487                 // documentclasses have an own \bibliographystyle{}
488                 // command!
489                 params_["options"] = bibstyle;
490         }
491
492         params_["biblatexopts"] = qstring_to_ucs4(biblatexOptsLE->text());
493
494         params_["btprint"] = qstring_to_ucs4(btPrintCO->itemData(btPrintCO->currentIndex()).toString());
495
496         params_["encoding"] = qstring_to_ucs4(bibEncodingCO->itemData(bibEncodingCO->currentIndex()).toString());
497
498         if (usingBiblatex())
499                 params_["file_encodings"] = getStringFromVector(getFileEncodings(), from_ascii("\t"));
500 }
501
502
503 QString GuiBibtex::browseBib(QString const & in_name) const
504 {
505         QString const label1 = qt_("D&ocuments");
506         QString const dir1 = toqstr(lyxrc.document_path);
507         QStringList const filter(qt_("BibTeX Databases (*.bib)"));
508         return browseRelToParent(in_name, bufferFilePath(),
509                 qt_("Select a BibTeX database to add"), filter, false, label1, dir1);
510 }
511
512
513 QString GuiBibtex::browseBst(QString const & in_name) const
514 {
515         QString const label1 = qt_("D&ocuments");
516         QString const dir1 = toqstr(lyxrc.document_path);
517         QStringList const filter(qt_("BibTeX Styles (*.bst)"));
518         return browseRelToParent(in_name, bufferFilePath(),
519                 qt_("Select a BibTeX style"), filter, false, label1, dir1);
520 }
521
522
523 QStringList GuiBibtex::bibStyles() const
524 {
525         QStringList sdata = texFileList("bstFiles.lst");
526         // test whether we have a valid list, otherwise run rescan
527         if (sdata.isEmpty()) {
528                 rescanBibStyles();
529                 sdata = texFileList("bstFiles.lst");
530         }
531         for (int i = 0; i != sdata.size(); ++i)
532                 sdata[i] = onlyFileName(sdata[i]);
533         // sort on filename only (no path)
534         sdata.sort();
535         return sdata;
536 }
537
538
539 QStringList GuiBibtex::bibFiles(bool const extension) const
540 {
541         QStringList sdata = texFileList("bibFiles.lst");
542         // test whether we have a valid list, otherwise run rescan
543         if (sdata.isEmpty()) {
544                 rescanBibStyles();
545                 sdata = texFileList("bibFiles.lst");
546         }
547         for (int i = 0; i != sdata.size(); ++i)
548                 sdata[i] = extension ? onlyFileName(sdata[i])
549                                      : changeExtension(onlyFileName(sdata[i]), "");
550         // sort on filename only (no path)
551         sdata.sort();
552         return sdata;
553 }
554
555
556 vector<docstring> GuiBibtex::getFileEncodings()
557 {
558         vector<docstring> res;
559         for (int i = 0; i != selected_model_.rowCount(); ++i) {
560                 QStandardItem const * key = selected_model_.item(i, 0);
561                 QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(i, 1)));
562                 QString fenc = cb ? cb->itemData(cb->currentIndex()).toString() : QString();
563                 if (key && !key->text().isEmpty() && !fenc.isEmpty() && fenc != "general")
564                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(fenc));
565         }
566         return res;
567 }
568
569
570 void GuiBibtex::setFileEncodings(vector<docstring> const & m)
571 {
572         for (docstring const & s: m) {
573                 docstring key;
574                 QString enc = toqstr(split(s, key, ' '));
575                 QModelIndexList qmil =
576                                 selected_model_.match(selected_model_.index(0, 0),
577                                                      Qt::DisplayRole, toqstr(key), 1,
578                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
579                 if (!qmil.empty()) {
580                         QComboBox * cb = qobject_cast<QComboBox*>(selectedLV->indexWidget(selected_model_.index(qmil.front().row(), 1)));
581                         cb->setCurrentIndex(cb->findData(enc));
582                 }
583         }
584 }
585
586
587 void GuiBibtex::rescanBibStyles() const
588 {
589         if (usingBiblatex())
590                 rescanTexStyles("bib");
591         else
592                 rescanTexStyles("bst bib");
593 }
594
595
596 void GuiBibtex::findText(QString const & text)
597 {
598         QStringList const result = bibFiles(false).filter(text);
599         available_model_.setStringList(result);
600 }
601
602
603 void GuiBibtex::filterChanged(const QString & text)
604 {
605         if (!text.isEmpty()) {
606                 findText(filter_->text());
607                 return;
608         }
609         findText(filter_->text());
610         filter_->setFocus();
611 }
612
613
614 void GuiBibtex::filterPressed()
615 {
616         findText(filter_->text());
617 }
618
619
620 void GuiBibtex::resetFilter()
621 {
622         filter_->setText(QString());
623         findText(filter_->text());
624 }
625
626
627
628 bool GuiBibtex::usingBibtopic() const
629 {
630         return buffer().params().useBibtopic();
631 }
632
633
634 bool GuiBibtex::bibtotoc() const
635 {
636         return prefixIs(to_utf8(params_["options"]), "bibtotoc");
637 }
638
639
640 bool GuiBibtex::usingBiblatex() const
641 {
642         return buffer().masterBuffer()->params().useBiblatex();
643 }
644
645
646 QString GuiBibtex::styleFile() const
647 {
648         // the different bibtex packages have (and need) their
649         // own "plain" stylefiles
650         QString defaultstyle = toqstr(buffer().params().defaultBiblioStyle());
651
652         QString bst = toqstr(params_["options"]);
653         if (bibtotoc()){
654                 // bibstyle exists?
655                 int pos = bst.indexOf(',');
656                 if (pos != -1) {
657                         // FIXME: check
658                         // docstring bibtotoc = from_ascii("bibtotoc");
659                         // bst = split(bst, bibtotoc, ',');
660                         bst = bst.mid(pos + 1);
661                 } else {
662                         bst.clear();
663                 }
664         }
665
666         // propose default style file for new insets
667         // existing insets might have (legally) no bst files
668         // (if the class already provides a style)
669         if (bst.isEmpty() && params_["bibfiles"].empty())
670                 bst = defaultstyle;
671
672         return bst;
673 }
674
675
676 bool GuiBibtex::initialiseParams(std::string const & sdata)
677 {
678         InsetCommand::string2params(sdata, params_);
679         init();
680         return true;
681 }
682
683
684 void GuiBibtex::dispatchParams()
685 {
686         std::string const lfun = InsetCommand::params2string(params_);
687         dispatch(FuncRequest(getLfun(), lfun));
688         connectToNewInset();
689 }
690
691
692 } // namespace frontend
693 } // namespace lyx
694
695 #include "moc_GuiBibtex.cpp"