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