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