]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
0163779498078ff8e8435404eb43a8f67532c90a
[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<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         : 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(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         e->accept();
125 }
126
127
128 void GuiCitation::applyView()
129 {
130         int  const choice = 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 updateStyle() 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::updateFormatting(biblio::CiteStyle currentStyle)
217 {
218         biblio::CiteEngine const engine = citeEngine();
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
227         bool const isNocite = currentStyle == biblio::NOCITE;
228
229         fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
230         forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
231         textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
232         textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
233         textAfterED->setEnabled(haveSelection && !isNocite);
234         textAfterLA->setEnabled(haveSelection && !isNocite);
235         citationStyleCO->setEnabled(haveSelection);
236         citationStyleLA->setEnabled(haveSelection);
237 }
238
239
240 void GuiCitation::updateStyle()
241 {
242         string const & command = params_.getCmdName();
243
244         // Find the style of the citekeys
245         vector<biblio::CiteStyle> const & styles = citeStyles_;
246         biblio::CitationStyle const cs(command);
247
248         vector<biblio::CiteStyle>::const_iterator cit =
249                 std::find(styles.begin(), styles.end(), cs.style);
250
251         // restore the latest natbib style
252         if (style_ >= 0 && style_ < citationStyleCO->count())
253                 citationStyleCO->setCurrentIndex(style_);
254         else
255                 citationStyleCO->setCurrentIndex(0);
256
257         if (cit != styles.end()) {
258                 int const i = int(cit - styles.begin());
259                 citationStyleCO->setCurrentIndex(i);
260                 fulllistCB->setChecked(cs.full);
261                 forceuppercaseCB->setChecked(cs.forceUCase);
262         } else {
263                 fulllistCB->setChecked(false);
264                 forceuppercaseCB->setChecked(false);
265         }
266         updateFormatting(cs.style);
267 }
268
269 //This one needs to be called whenever citationStyleCO needs
270 //to be updated---and this would be on anything that changes the
271 //selection in selectedLV, or on a general update.
272 void GuiCitation::fillStyles()
273 {
274         int const oldIndex = citationStyleCO->currentIndex();
275
276         citationStyleCO->clear();
277
278         QStringList selected_keys = selected()->stringList();
279         if (selected_keys.empty()) {
280                 citationStyleCO->setEnabled(false);
281                 citationStyleLA->setEnabled(false);
282                 return;
283         }
284
285         int curr = selectedLV->model()->rowCount() - 1;
286         if (curr < 0)
287                 return;
288
289         if (!selectedLV->selectionModel()->selectedIndexes().empty())
290                 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
291
292         QStringList sty = citationStyles(curr);
293
294         citationStyleCO->setEnabled(!sty.isEmpty());
295         citationStyleLA->setEnabled(!sty.isEmpty());
296
297         if (sty.isEmpty())
298                 return;
299
300         citationStyleCO->insertItems(0, sty);
301
302         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
303                 citationStyleCO->setCurrentIndex(oldIndex);
304 }
305
306
307 void GuiCitation::fillFields()
308 {
309         fieldsCO->blockSignals(true);
310         int const oldIndex = fieldsCO->currentIndex();
311         fieldsCO->clear();
312         QStringList const & fields = getFieldsAsQStringList();
313         fieldsCO->insertItem(0, qt_("All Fields"));
314         fieldsCO->insertItem(1, qt_("Keys"));
315         fieldsCO->insertItems(2, fields);
316         if (oldIndex != -1 && oldIndex < fieldsCO->count())
317                 fieldsCO->setCurrentIndex(oldIndex);
318         fieldsCO->blockSignals(false);
319 }
320
321
322 void GuiCitation::fillEntries()
323 {
324         entriesCO->blockSignals(true);
325         int const oldIndex = entriesCO->currentIndex();
326         entriesCO->clear();
327         QStringList const & entries = getEntriesAsQStringList();
328         entriesCO->insertItem(0, qt_("All Entry Types"));
329         entriesCO->insertItems(1, entries);
330         if (oldIndex != -1 && oldIndex < entriesCO->count())
331                 entriesCO->setCurrentIndex(oldIndex);
332         entriesCO->blockSignals(false);
333 }
334
335
336 bool GuiCitation::isSelected(const QModelIndex & idx)
337 {
338         QString const str = idx.data().toString();
339         return selected()->stringList().contains(str);
340 }
341
342
343 void GuiCitation::setButtons()
344 {
345         selectionManager->update();
346         int const srows = selectedLV->model()->rowCount();
347         applyPB->setEnabled(srows > 0);
348         okPB->setEnabled(srows > 0);
349 }
350
351
352 void GuiCitation::updateInfo(QModelIndex const & idx)
353 {
354         if (idx.isValid()) {
355                 QString const keytxt = getKeyInfo(idx.data().toString());
356                 infoML->document()->setPlainText(keytxt);
357         } else
358                 infoML->document()->clear();
359 }
360
361
362 void GuiCitation::findText(QString const & text, bool reset)
363 {
364         //"All Fields" and "Keys" are the first two
365         int index = fieldsCO->currentIndex() - 2; 
366         vector<docstring> const & fields = availableFields();
367         docstring field;
368         
369         if (index <= -1 || index >= int(fields.size()))
370                 //either "All Fields" or "Keys" or an invalid value
371                 field = from_ascii("");
372         else
373                 field = fields[index];
374         
375         //Was it "Keys"?
376         bool const onlyKeys = index == -1;
377         
378         //"All Entry Types" is first.
379         index = entriesCO->currentIndex() - 1; 
380         vector<docstring> const & entries = availableEntries();
381         docstring entry_type;
382         if (index < 0 || index >= int(entries.size()))
383                 entry_type = from_ascii("");
384         else 
385                 entry_type = entries[index];
386         
387         bool const case_sentitive = caseCB->checkState();
388         bool const reg_exp = regexCB->checkState();
389         findKey(text, onlyKeys, field, entry_type, 
390                        case_sentitive, reg_exp, reset);
391         //FIXME
392         //It'd be nice to save and restore the current selection in 
393         //availableLV. Currently, we get an automatic reset, since the
394         //model is reset.
395         
396         updateDialog();
397 }
398
399
400 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
401 {
402         findText(findLE->text(), true);
403 }
404
405
406 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
407 {
408         findText(findLE->text(), true);
409 }
410
411
412 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
413 {
414         if (index >= 0 && index < citationStyleCO->count()) {
415                 vector<biblio::CiteStyle> const & styles = citeStyles_;
416                 updateFormatting(styles[index]);
417         }
418 }
419
420
421 void GuiCitation::on_findLE_textChanged(const QString & text)
422 {
423         clearPB->setDisabled(text.isEmpty());
424         if (text.isEmpty())
425                 findLE->setFocus();
426         findText(text);
427 }
428
429
430 void GuiCitation::on_caseCB_stateChanged(int)
431 {
432         findText(findLE->text());
433 }
434
435
436 void GuiCitation::on_regexCB_stateChanged(int)
437 {
438         findText(findLE->text());
439 }
440
441
442 void GuiCitation::changed()
443 {
444         setButtons();
445 }
446
447
448 void GuiCitation::apply(int const choice, bool full, bool force,
449         QString before, QString after)
450 {
451         if (cited_keys_.isEmpty())
452                 return;
453
454         vector<biblio::CiteStyle> const & styles = citeStyles_;
455         if (styles[choice] == biblio::NOCITE) {
456                 full = false;
457                 force = false;
458                 before.clear();
459                 after.clear();
460         }
461         
462         string const command =
463                 biblio::CitationStyle(styles[choice], full, force)
464                 .asLatexStr();
465
466         params_.setCmdName(command);
467         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
468         params_["before"] = qstring_to_ucs4(before);
469         params_["after"] = qstring_to_ucs4(after);
470         dispatchParams();
471 }
472
473
474 void GuiCitation::clearSelection()
475 {
476         cited_keys_.clear();
477         selected_model_.setStringList(cited_keys_);
478 }
479
480
481 QString GuiCitation::textBefore()
482 {
483         return toqstr(params_["before"]);
484 }
485
486
487 QString GuiCitation::textAfter()
488 {
489         return toqstr(params_["after"]);
490 }
491
492
493 void GuiCitation::init()
494 {
495         // Make the list of all available bibliography keys
496         all_keys_ = to_qstring_list(availableKeys());
497         available_model_.setStringList(all_keys_);
498
499         // Ditto for the keys cited in this inset
500         QString str = toqstr(params_["key"]);
501         if (str.isEmpty())
502                 cited_keys_.clear();
503         else
504                 cited_keys_ = str.split(",");
505         selected_model_.setStringList(cited_keys_);
506 }
507
508
509 void GuiCitation::findKey(QString const & str, bool only_keys,
510         docstring field, docstring entry_type,
511         bool case_sensitive, bool reg_exp, bool reset)
512 {
513         // Used for optimisation: store last searched string.
514         static QString last_searched_string;
515         // Used to disable the above optimisation.
516         static bool last_case_sensitive;
517         static bool last_reg_exp;
518         // Reset last_searched_string in case of changed option.
519         if (last_case_sensitive != case_sensitive
520                 || last_reg_exp != reg_exp) {
521                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
522                 last_searched_string.clear();
523         }
524         // save option for next search.
525         last_case_sensitive = case_sensitive;
526         last_reg_exp = reg_exp;
527
528         Qt::CaseSensitivity qtcase = case_sensitive?
529                         Qt::CaseSensitive: Qt::CaseInsensitive;
530         QStringList keys;
531         // If new string (str) contains the last searched one...
532         if (!reset &&
533                 !last_searched_string.isEmpty() &&
534                 str.size() > 1 &&
535                 str.contains(last_searched_string, qtcase))
536                 // ... then only search within already found list.
537                 keys = available_model_.stringList();
538         else
539                 // ... else search all keys.
540                 keys = all_keys_;
541         // save searched string for next search.
542         last_searched_string = str;
543
544         QStringList result;
545         
546         // First, filter by entry_type, which will be faster than 
547         // what follows, so we may get to do that on less.
548         vector<docstring> keyVector = to_docstring_vector(keys);
549         filterByEntryType(keyVector, entry_type);
550         
551         if (str.isEmpty())
552                 result = to_qstring_list(keyVector);
553         else
554                 result = to_qstring_list(searchKeys(keyVector, only_keys, 
555                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
556         
557         available_model_.setStringList(result);
558 }
559
560
561 QStringList GuiCitation::getFieldsAsQStringList()
562 {
563         return to_qstring_list(availableFields());
564 }
565
566
567 QStringList GuiCitation::getEntriesAsQStringList()
568 {
569         return to_qstring_list(availableEntries());
570 }
571
572
573 QStringList GuiCitation::citationStyles(int sel)
574 {
575         docstring const key = qstring_to_ucs4(cited_keys_[sel]);
576         return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
577 }
578
579
580 QString GuiCitation::getKeyInfo(QString const & sel)
581 {
582         return toqstr(getInfo(qstring_to_ucs4(sel)));
583 }
584
585
586 void GuiCitation::setCitedKeys() 
587 {
588         cited_keys_ = selected_model_.stringList();
589 }
590
591
592 bool GuiCitation::initialiseParams(string const & data)
593 {
594         InsetCommand::string2params("citation", data, params_);
595         biblio::CiteEngine const engine = buffer().params().citeEngine();
596         bibkeysInfo_.fillWithBibKeys(&buffer());
597         citeStyles_ = biblio::getCiteStyles(engine);
598         return true;
599 }
600
601
602 void GuiCitation::clearParams()
603 {
604         params_.clear();
605         bibkeysInfo_.clear();
606 }
607
608
609 vector<docstring> GuiCitation::availableKeys() const
610 {
611         return bibkeysInfo_.getKeys();
612 }
613
614
615 vector<docstring> GuiCitation::availableFields() const
616 {
617         return bibkeysInfo_.getFields();
618 }
619
620
621 vector<docstring> GuiCitation::availableEntries() const
622 {
623         return bibkeysInfo_.getEntries();
624 }
625
626
627 void GuiCitation::filterByEntryType(
628         vector<docstring> & keyVector, docstring entry_type) 
629 {
630         if (entry_type.empty())
631                 return;
632         
633         vector<docstring>::iterator it = keyVector.begin();
634         vector<docstring>::iterator end = keyVector.end();
635         
636         vector<docstring> result;
637         for (; it != end; ++it) {
638                 docstring const key = *it;
639                 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
640                 if (cit == bibkeysInfo_.end())
641                         continue;
642                 if (cit->second.entryType() == entry_type)
643                         result.push_back(key);
644         }
645         keyVector = result;
646 }
647
648
649 biblio::CiteEngine GuiCitation::citeEngine() const
650 {
651         return buffer().params().citeEngine();
652 }
653
654
655 docstring GuiCitation::getInfo(docstring const & key) const
656 {
657         if (bibkeysInfo_.empty())
658                 return docstring();
659
660         return bibkeysInfo_.getInfo(key);
661 }
662
663
664 // Escape special chars.
665 // All characters are literals except: '.|*?+(){}[]^$\'
666 // These characters are literals when preceded by a "\", which is done here
667 // @todo: This function should be moved to support, and then the test in tests
668 //        should be moved there as well.
669 static docstring escape_special_chars(docstring const & expr)
670 {
671         // Search for all chars '.|*?+(){}[^$]\'
672         // Note that '[' and '\' must be escaped.
673         // This is a limitation of boost::regex, but all other chars in BREs
674         // are assumed literal.
675         static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
676
677         // $& is a perl-like expression that expands to all
678         // of the current match
679         // The '$' must be prefixed with the escape character '\' for
680         // boost to treat it as a literal.
681         // Thus, to prefix a matched expression with '\', we use:
682         // FIXME: UNICODE
683         return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
684 }
685
686
687 vector<docstring> GuiCitation::searchKeys(
688         vector<docstring> const & keys_to_search, bool only_keys,
689         docstring const & search_expression, docstring field,
690         bool case_sensitive, bool regex)
691 {
692         vector<docstring> foundKeys;
693
694         docstring expr = trim(search_expression);
695         if (expr.empty())
696                 return foundKeys;
697
698         if (!regex)
699                 // We must escape special chars in the search_expr so that
700                 // it is treated as a simple string by boost::regex.
701                 expr = escape_special_chars(expr);
702
703         boost::regex reg_exp;
704         try {
705                 reg_exp.assign(to_utf8(expr), case_sensitive ?
706                         boost::regex_constants::normal : boost::regex_constants::icase);
707         } catch (boost::regex_error & e) {
708                 // boost::regex throws an exception if the regular expression is not
709                 // valid.
710                 LYXERR(Debug::GUI, e.what());
711                 return vector<docstring>();
712         }
713
714         vector<docstring>::const_iterator it = keys_to_search.begin();
715         vector<docstring>::const_iterator end = keys_to_search.end();
716         for (; it != end; ++it ) {
717                 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
718                 if (info == bibkeysInfo_.end())
719                         continue;
720                 
721                 BibTeXInfo const & kvm = info->second;
722                 string data;
723                 if (only_keys)
724                         data = to_utf8(*it);
725                 else if (field.empty())
726                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
727                 else if (kvm.hasField(field))
728                         data = to_utf8(kvm.getValueForField(field));
729                 
730                 if (data.empty())
731                         continue;
732
733                 try {
734                         if (boost::regex_search(data, reg_exp))
735                                 foundKeys.push_back(*it);
736                 }
737                 catch (boost::regex_error & e) {
738                         LYXERR(Debug::GUI, e.what());
739                         return vector<docstring>();
740                 }
741         }
742         return foundKeys;
743 }
744
745
746 void GuiCitation::dispatchParams()
747 {
748         std::string const lfun = InsetCommand::params2string("citation", params_);
749         dispatch(FuncRequest(getLfun(), lfun));
750 }
751
752
753 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
754
755
756 } // namespace frontend
757 } // namespace lyx
758
759 #include "GuiCitation_moc.cpp"
760