]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiCitation.cpp
f485a6842df080ad172d94bb7b094d094d865655
[features.git] / src / frontends / qt4 / GuiCitation.cpp
1
2 /**
3  * \file GuiCitation.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Angus Leeming
8  * \author Kalle Dalheimer
9  * \author Abdelrazak Younes
10  * \author Richard Heck
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiCitation.h"
18
19 #include "GuiSelectionManager.h"
20 #include "qt_helpers.h"
21
22 #include "Buffer.h"
23 #include "BiblioInfo.h"
24 #include "BufferParams.h"
25 #include "FuncRequest.h"
26
27 #include "insets/InsetCommand.h"
28
29 #include "support/debug.h"
30 #include "support/docstring.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33
34 #include <QCloseEvent>
35 #include <QSettings>
36 #include <QShowEvent>
37 #include <QVariant>
38
39 #include <vector>
40 #include <string>
41
42 #undef KeyPress
43
44 #include <boost/regex.hpp>
45
46 #include <algorithm>
47 #include <string>
48 #include <vector>
49
50 using namespace std;
51 using namespace lyx::support;
52
53 namespace lyx {
54 namespace frontend {
55
56 static vector<CiteStyle> citeStyles_;
57
58
59 template<typename String>
60 static QStringList to_qstring_list(vector<String> const & v)
61 {
62         QStringList qlist;
63
64         for (size_t i = 0; i != v.size(); ++i) {
65                 if (v[i].empty())
66                         continue;
67                 qlist.append(lyx::toqstr(v[i]));
68         }
69         return qlist;
70 }
71
72
73 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
74 {
75         vector<lyx::docstring> v;
76         for (int i = 0; i != qlist.size(); ++i) {
77                 if (qlist[i].isEmpty())
78                         continue;
79                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
80         }
81         return v;
82 }
83
84
85 GuiCitation::GuiCitation(GuiView & lv)
86         : DialogView(lv, "citation", qt_("Citation")),
87           params_(insetCode("citation"))
88 {
89         setupUi(this);
90
91         connect(citationStyleCO, SIGNAL(activated(int)),
92                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
93         connect(fulllistCB, SIGNAL(clicked()),
94                 this, SLOT(changed()));
95         connect(forceuppercaseCB, SIGNAL(clicked()),
96                 this, SLOT(changed()));
97         connect(textBeforeED, SIGNAL(textChanged(QString)),
98                 this, SLOT(changed()));
99         connect(textAfterED, SIGNAL(textChanged(QString)),
100                 this, SLOT(changed()));
101         connect(findLE, SIGNAL(returnPressed()), 
102                 this, SLOT(on_searchPB_clicked()));
103         connect(textBeforeED, SIGNAL(returnPressed()),
104                 this, SLOT(on_okPB_clicked()));
105         connect(textAfterED, SIGNAL(returnPressed()),
106                 this, SLOT(on_okPB_clicked()));
107
108         selectionManager = new GuiSelectionManager(availableLV, selectedLV, 
109                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
110         connect(selectionManager, SIGNAL(selectionChanged()),
111                 this, SLOT(setCitedKeys()));
112         connect(selectionManager, SIGNAL(updateHook()),
113                 this, SLOT(updateControls()));
114         connect(selectionManager, SIGNAL(okHook()),
115                 this, SLOT(on_okPB_clicked()));
116
117         // FIXME: the sizeHint() for this is _way_ too high
118         infoML->setFixedHeight(60);
119 }
120
121
122 GuiCitation::~GuiCitation()
123 {
124         delete selectionManager;
125 }
126
127
128 void GuiCitation::closeEvent(QCloseEvent * e)
129 {
130         clearSelection();
131         DialogView::closeEvent(e);
132 }
133
134
135 void GuiCitation::applyView()
136 {
137         int const choice = max(0, citationStyleCO->currentIndex());
138         style_ = choice;
139         bool const full  = fulllistCB->isChecked();
140         bool const force = forceuppercaseCB->isChecked();
141
142         QString const before = textBeforeED->text();
143         QString const after = textAfterED->text();
144
145         apply(choice, full, force, before, after);
146 }
147
148
149 void GuiCitation::showEvent(QShowEvent * e)
150 {
151         findLE->clear();
152         availableLV->setFocus();
153         DialogView::showEvent(e);
154 }
155
156
157 void GuiCitation::on_okPB_clicked()
158 {
159         applyView();
160         clearSelection();
161         hide();
162 }
163
164
165 void GuiCitation::on_cancelPB_clicked()
166 {
167         clearSelection();
168         hide();
169 }
170
171
172 void GuiCitation::on_applyPB_clicked()
173 {
174         applyView();
175 }
176
177
178 void GuiCitation::on_restorePB_clicked()
179 {
180         init();
181 }
182
183
184 void GuiCitation::updateControls()
185 {
186         BiblioInfo const & bi = bibInfo();
187         updateControls(bi);
188 }
189
190
191 // The main point of separating this out is that the fill*() methods
192 // called in update() do not need to be called for INTERNAL updates,
193 // such as when addPB is pressed, as the list of fields, entries, etc,
194 // will not have changed. At the moment, however, the division between
195 // fillStyles() and updateStyle() doesn't lend itself to dividing the
196 // two methods, though they should be divisible.
197 void GuiCitation::updateControls(BiblioInfo const & bi)
198 {
199         QModelIndex idx = selectionManager->getSelectedIndex();
200         updateInfo(bi, idx);
201         setButtons();
202
203         textBeforeED->setText(toqstr(params_["before"]));
204         textAfterED->setText(toqstr(params_["after"]));
205         fillStyles(bi);
206         updateStyle();
207 }
208
209
210 void GuiCitation::updateFormatting(CiteStyle currentStyle)
211 {
212         CiteEngine const engine = citeEngine();
213         bool const natbib_engine =
214                 engine == ENGINE_NATBIB_AUTHORYEAR ||
215                 engine == ENGINE_NATBIB_NUMERICAL;
216         bool const basic_engine = engine == ENGINE_BASIC;
217
218         bool const haveSelection = 
219                 selectedLV->model()->rowCount() > 0;
220
221         bool const isNocite = currentStyle == NOCITE;
222
223         bool const isCiteyear =
224                 currentStyle == CITEYEAR ||
225                 currentStyle == CITEYEARPAR;
226
227         fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite
228                 && !isCiteyear);
229         forceuppercaseCB->setEnabled(natbib_engine && haveSelection
230                 && !isNocite && !isCiteyear);
231         textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
232         textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
233         textAfterED->setEnabled(haveSelection && !isNocite);
234         textAfterLA->setEnabled(haveSelection && !isNocite);
235         citationStyleCO->setEnabled(haveSelection);
236         citationStyleLA->setEnabled(haveSelection);
237 }
238
239
240 void GuiCitation::updateStyle()
241 {
242         string const & command = params_.getCmdName();
243
244         // Find the style of the citekeys
245         vector<CiteStyle> const & styles = citeStyles_;
246         CitationStyle const cs = citationStyleFromString(command);
247
248         vector<CiteStyle>::const_iterator cit =
249                 std::find(styles.begin(), styles.end(), cs.style);
250
251         if (cit != styles.end()) {
252                 int const i = int(cit - styles.begin());
253                 citationStyleCO->setCurrentIndex(i);
254                 fulllistCB->setChecked(cs.full);
255                 forceuppercaseCB->setChecked(cs.forceUpperCase);
256         } else {
257                 fulllistCB->setChecked(false);
258                 forceuppercaseCB->setChecked(false);
259         }
260         updateFormatting(cs.style);
261 }
262
263
264 // This one needs to be called whenever citationStyleCO needs
265 // to be updated---and this would be on anything that changes the
266 // selection in selectedLV, or on a general update.
267 void GuiCitation::fillStyles(BiblioInfo const & bi)
268 {
269         QStringList selected_keys = selected_model_.stringList();
270         int curr = selectedLV->model()->rowCount() - 1;
271
272         if (curr < 0 || selected_keys.empty()) {
273                 citationStyleCO->clear();
274                 citationStyleCO->setEnabled(false);
275                 citationStyleLA->setEnabled(false);
276                 return;
277         }
278
279         int const oldIndex = citationStyleCO->currentIndex();
280
281         if (!selectedLV->selectionModel()->selectedIndexes().empty())
282                 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
283
284         QStringList sty = citationStyles(bi, curr);
285         citationStyleCO->clear();
286
287         if (sty.isEmpty()) { 
288                 // some error
289                 citationStyleCO->setEnabled(false);
290                 citationStyleLA->setEnabled(false);
291                 return;
292         }
293         
294         citationStyleCO->insertItems(0, sty);
295         citationStyleCO->setEnabled(true);
296         citationStyleLA->setEnabled(true);
297
298         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
299                 citationStyleCO->setCurrentIndex(oldIndex);
300 }
301
302
303 void GuiCitation::fillFields(BiblioInfo const & bi)
304 {
305         fieldsCO->blockSignals(true);
306         int const oldIndex = fieldsCO->currentIndex();
307         fieldsCO->clear();
308         QStringList const fields = to_qstring_list(bi.getFields());
309         fieldsCO->insertItem(0, qt_("All fields"));
310         fieldsCO->insertItem(1, qt_("Keys"));
311         fieldsCO->insertItems(2, fields);
312         if (oldIndex != -1 && oldIndex < fieldsCO->count())
313                 fieldsCO->setCurrentIndex(oldIndex);
314         fieldsCO->blockSignals(false);
315 }
316
317
318 void GuiCitation::fillEntries(BiblioInfo const & bi)
319 {
320         entriesCO->blockSignals(true);
321         int const oldIndex = entriesCO->currentIndex();
322         entriesCO->clear();
323         QStringList const entries = to_qstring_list(bi.getEntries());
324         entriesCO->insertItem(0, qt_("All entry types"));
325         entriesCO->insertItems(1, entries);
326         if (oldIndex != -1 && oldIndex < entriesCO->count())
327                 entriesCO->setCurrentIndex(oldIndex);
328         entriesCO->blockSignals(false);
329 }
330
331
332 bool GuiCitation::isSelected(QModelIndex const & idx)
333 {
334         QString const str = idx.data().toString();
335         return selected_model_.stringList().contains(str);
336 }
337
338
339 void GuiCitation::setButtons()
340 {
341         selectionManager->update();
342         int const srows = selectedLV->model()->rowCount();
343         applyPB->setEnabled(srows > 0);
344         okPB->setEnabled(srows > 0);
345 }
346
347
348 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
349 {
350         if (!idx.isValid() || bi.empty()) {
351                 infoML->document()->clear();
352                 return;
353         }
354
355         QString const keytxt = toqstr(
356                 bi.getInfo(qstring_to_ucs4(idx.data().toString())));
357         infoML->document()->setPlainText(keytxt);
358 }
359
360
361 void GuiCitation::findText(QString const & text, bool reset)
362 {
363         //"All Fields" and "Keys" are the first two
364         int index = fieldsCO->currentIndex() - 2; 
365         BiblioInfo const & bi = bibInfo();
366         vector<docstring> const & fields = bi.getFields();
367         docstring field;
368         
369         if (index <= -1 || index >= int(fields.size()))
370                 //either "All Fields" or "Keys" or an invalid value
371                 field = from_ascii("");
372         else
373                 field = fields[index];
374         
375         //Was it "Keys"?
376         bool const onlyKeys = index == -1;
377         
378         //"All Entry Types" is first.
379         index = entriesCO->currentIndex() - 1; 
380         vector<docstring> const & entries = bi.getEntries();
381         docstring entry_type;
382         if (index < 0 || index >= int(entries.size()))
383                 entry_type = from_ascii("");
384         else 
385                 entry_type = entries[index];
386         
387         bool const case_sentitive = caseCB->checkState();
388         bool const reg_exp = regexCB->checkState();
389         findKey(bi, text, onlyKeys, field, entry_type, 
390                        case_sentitive, reg_exp, reset);
391         //FIXME
392         //It'd be nice to save and restore the current selection in 
393         //availableLV. Currently, we get an automatic reset, since the
394         //model is reset.
395         
396         updateControls(bi);
397 }
398
399
400 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
401 {
402         findText(findLE->text(), true);
403 }
404
405
406 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
407 {
408         findText(findLE->text(), true);
409 }
410
411
412 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
413 {
414         if (index >= 0 && index < citationStyleCO->count()) {
415                 vector<CiteStyle> const & styles = citeStyles_;
416                 updateFormatting(styles[index]);
417         }
418 }
419
420
421 void GuiCitation::on_findLE_textChanged(const QString & text)
422 {
423         bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
424         searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
425         if (!text.isEmpty()) {
426                 if (searchAsWeGo)
427                         findText(findLE->text());
428                 return;
429         }
430         findText(findLE->text());
431         findLE->setFocus();
432 }
433
434 void GuiCitation::on_searchPB_clicked()
435 {
436         findText(findLE->text(), true);
437 }
438
439
440 void GuiCitation::on_caseCB_stateChanged(int)
441 {
442         findText(findLE->text());
443 }
444
445
446 void GuiCitation::on_regexCB_stateChanged(int)
447 {
448         findText(findLE->text());
449 }
450
451
452 void GuiCitation::on_asTypeCB_stateChanged(int)
453 {
454         bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
455         searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
456         if (searchAsWeGo)
457                 findText(findLE->text(), true);
458 }
459
460
461 void GuiCitation::changed()
462 {
463         setButtons();
464 }
465
466
467 void GuiCitation::apply(int const choice, bool full, bool force,
468         QString before, QString after)
469 {
470         if (cited_keys_.isEmpty())
471                 return;
472
473         vector<CiteStyle> const & styles = citeStyles_;
474         if (styles[choice] == NOCITE) {
475                 full = false;
476                 force = false;
477                 before.clear();
478                 after.clear();
479         }
480         
481         CitationStyle s;
482         s.style = styles[choice];
483         s.full = full;
484         s.forceUpperCase = force;
485         string const command = citationStyleToString(s);
486
487         params_.setCmdName(command);
488         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
489         params_["before"] = qstring_to_ucs4(before);
490         params_["after"] = qstring_to_ucs4(after);
491         dispatchParams();
492 }
493
494
495 void GuiCitation::clearSelection()
496 {
497         cited_keys_.clear();
498         selected_model_.setStringList(cited_keys_);
499 }
500
501
502 void GuiCitation::init()
503 {
504         // Make the list of all available bibliography keys
505         BiblioInfo const & bi = bibInfo();
506         all_keys_ = to_qstring_list(bi.getKeys());
507         available_model_.setStringList(all_keys_);
508
509         // Ditto for the keys cited in this inset
510         QString str = toqstr(params_["key"]);
511         if (str.isEmpty())
512                 cited_keys_.clear();
513         else
514                 cited_keys_ = str.split(",");
515         selected_model_.setStringList(cited_keys_);
516         if (selected_model_.rowCount()) {
517                 selectedLV->blockSignals(true);
518                 selectedLV->setFocus();
519                 QModelIndex idx = selected_model_.index(0, 0);
520                 selectedLV->selectionModel()->select(idx, 
521                                 QItemSelectionModel::ClearAndSelect);
522                 selectedLV->blockSignals(false);
523         } else
524                 availableLV->setFocus();
525         fillFields(bi);
526         fillEntries(bi);
527         updateControls(bi);
528         // restore the last used natbib style
529         if (style_ >= 0 && style_ < citationStyleCO->count())
530                 citationStyleCO->setCurrentIndex(style_);
531         else
532                 citationStyleCO->setCurrentIndex(0);
533 }
534
535
536 void GuiCitation::findKey(BiblioInfo const & bi,
537         QString const & str, bool only_keys,
538         docstring field, docstring entry_type,
539         bool case_sensitive, bool reg_exp, bool reset)
540 {
541         // Used for optimisation: store last searched string.
542         static QString last_searched_string;
543         // Used to disable the above optimisation.
544         static bool last_case_sensitive;
545         static bool last_reg_exp;
546         // Reset last_searched_string in case of changed option.
547         if (last_case_sensitive != case_sensitive
548                 || last_reg_exp != reg_exp) {
549                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
550                 last_searched_string.clear();
551         }
552         // save option for next search.
553         last_case_sensitive = case_sensitive;
554         last_reg_exp = reg_exp;
555
556         Qt::CaseSensitivity qtcase = case_sensitive ?
557                         Qt::CaseSensitive: Qt::CaseInsensitive;
558         QStringList keys;
559         // If new string (str) contains the last searched one...
560         if (!reset &&
561                 !last_searched_string.isEmpty() &&
562                 str.size() > 1 &&
563                 str.contains(last_searched_string, qtcase))
564                 // ... then only search within already found list.
565                 keys = available_model_.stringList();
566         else
567                 // ... else search all keys.
568                 keys = all_keys_;
569         // save searched string for next search.
570         last_searched_string = str;
571
572         QStringList result;
573         
574         // First, filter by entry_type, which will be faster than 
575         // what follows, so we may get to do that on less.
576         vector<docstring> keyVector = to_docstring_vector(keys);
577         filterByEntryType(bi, keyVector, entry_type);
578         
579         if (str.isEmpty())
580                 result = to_qstring_list(keyVector);
581         else
582                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys, 
583                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
584         
585         available_model_.setStringList(result);
586 }
587
588
589 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, int sel)
590 {
591         docstring const key = qstring_to_ucs4(cited_keys_[sel]);
592         return to_qstring_list(bi.getCiteStrings(key, buffer()));
593 }
594
595
596 void GuiCitation::setCitedKeys() 
597 {
598         cited_keys_ = selected_model_.stringList();
599 }
600
601
602 bool GuiCitation::initialiseParams(string const & data)
603 {
604         InsetCommand::string2params("citation", data, params_);
605         CiteEngine const engine = buffer().params().citeEngine();
606         citeStyles_ = citeStyles(engine);
607         init();
608         return true;
609 }
610
611
612 void GuiCitation::clearParams()
613 {
614         params_.clear();
615 }
616
617
618 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
619         vector<docstring> & keyVector, docstring entry_type) 
620 {
621         if (entry_type.empty())
622                 return;
623         
624         vector<docstring>::iterator it = keyVector.begin();
625         vector<docstring>::iterator end = keyVector.end();
626
627         vector<docstring> result;
628         for (; it != end; ++it) {
629                 docstring const key = *it;
630                 BiblioInfo::const_iterator cit = bi.find(key);
631                 if (cit == bi.end())
632                         continue;
633                 if (cit->second.entryType() == entry_type)
634                         result.push_back(key);
635         }
636         keyVector = result;
637 }
638
639
640 CiteEngine GuiCitation::citeEngine() const
641 {
642         return buffer().params().citeEngine();
643 }
644
645
646 // Escape special chars.
647 // All characters are literals except: '.|*?+(){}[]^$\'
648 // These characters are literals when preceded by a "\", which is done here
649 // @todo: This function should be moved to support, and then the test in tests
650 //        should be moved there as well.
651 static docstring escape_special_chars(docstring const & expr)
652 {
653         // Search for all chars '.|*?+(){}[^$]\'
654         // Note that '[' and '\' must be escaped.
655         // This is a limitation of boost::regex, but all other chars in BREs
656         // are assumed literal.
657         static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
658
659         // $& is a perl-like expression that expands to all
660         // of the current match
661         // The '$' must be prefixed with the escape character '\' for
662         // boost to treat it as a literal.
663         // Thus, to prefix a matched expression with '\', we use:
664         // FIXME: UNICODE
665         return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
666 }
667
668
669 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,        
670         vector<docstring> const & keys_to_search, bool only_keys,
671         docstring const & search_expression, docstring field,
672         bool case_sensitive, bool regex)
673 {
674         vector<docstring> foundKeys;
675
676         docstring expr = trim(search_expression);
677         if (expr.empty())
678                 return foundKeys;
679
680         if (!regex)
681                 // We must escape special chars in the search_expr so that
682                 // it is treated as a simple string by boost::regex.
683                 expr = escape_special_chars(expr);
684
685         boost::regex reg_exp;
686         try {
687                 reg_exp.assign(to_utf8(expr), case_sensitive ?
688                         boost::regex_constants::normal : boost::regex_constants::icase);
689         } catch (boost::regex_error & e) {
690                 // boost::regex throws an exception if the regular expression is not
691                 // valid.
692                 LYXERR(Debug::GUI, e.what());
693                 return vector<docstring>();
694         }
695
696         vector<docstring>::const_iterator it = keys_to_search.begin();
697         vector<docstring>::const_iterator end = keys_to_search.end();
698         for (; it != end; ++it ) {
699                 BiblioInfo::const_iterator info = bi.find(*it);
700                 if (info == bi.end())
701                         continue;
702                 
703                 BibTeXInfo const & kvm = info->second;
704                 string data;
705                 if (only_keys)
706                         data = to_utf8(*it);
707                 else if (field.empty())
708                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
709                 else 
710                         data = to_utf8(kvm[field]);
711                 
712                 if (data.empty())
713                         continue;
714
715                 try {
716                         if (boost::regex_search(data, reg_exp))
717                                 foundKeys.push_back(*it);
718                 }
719                 catch (boost::regex_error & e) {
720                         LYXERR(Debug::GUI, e.what());
721                         return vector<docstring>();
722                 }
723         }
724         return foundKeys;
725 }
726
727
728 void GuiCitation::dispatchParams()
729 {
730         std::string const lfun = InsetCommand::params2string("citation", params_);
731         dispatch(FuncRequest(getLfun(), lfun));
732 }
733
734
735 BiblioInfo const & GuiCitation::bibInfo() const
736 {
737         buffer().checkBibInfoCache();
738         return buffer().masterBibInfo();
739 }
740
741
742 void GuiCitation::saveSession() const
743 {
744         Dialog::saveSession();
745         QSettings settings;
746         settings.setValue(
747                 sessionKey() + "/regex", regexCB->isChecked());
748         settings.setValue(
749                 sessionKey() + "/casesensitive", caseCB->isChecked());
750         settings.setValue(
751                 sessionKey() + "/autofind", asTypeCB->isChecked());
752 }
753
754
755 void GuiCitation::restoreSession()
756 {
757         Dialog::restoreSession();
758         QSettings settings;
759         regexCB->setChecked(
760                 settings.value(sessionKey() + "/regex").toBool());
761         caseCB->setChecked(
762                 settings.value(sessionKey() + "/casesensitive").toBool());
763         asTypeCB->setChecked(
764                 settings.value(sessionKey() + "/autofind").toBool());
765 }
766
767
768 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
769
770
771 } // namespace frontend
772 } // namespace lyx
773
774 #include "moc_GuiCitation.cpp"
775