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