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