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