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