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