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