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