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