]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
cosmetics
[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<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(CiteStyle currentStyle)
217 {
218         CiteEngine const engine = citeEngine();
219         bool const natbib_engine =
220                 engine == ENGINE_NATBIB_AUTHORYEAR ||
221                 engine == ENGINE_NATBIB_NUMERICAL;
222         bool const basic_engine = engine == ENGINE_BASIC;
223
224         bool const haveSelection = 
225                 selectedLV->model()->rowCount() > 0;
226
227         bool const isNocite = currentStyle == 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<CiteStyle> const & styles = citeStyles_;
246         CitationStyle const cs = citationStyleFromString(command);
247
248         vector<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.forceUpperCase);
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<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<CiteStyle> const & styles = citeStyles_;
455         if (styles[choice] == NOCITE) {
456                 full = false;
457                 force = false;
458                 before.clear();
459                 after.clear();
460         }
461         
462         CitationStyle s;
463         s.style = styles[choice];
464         s.full = full;
465         s.forceUpperCase = force;
466         string const command = citationStyleToString(s);
467
468         params_.setCmdName(command);
469         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
470         params_["before"] = qstring_to_ucs4(before);
471         params_["after"] = qstring_to_ucs4(after);
472         dispatchParams();
473 }
474
475
476 void GuiCitation::clearSelection()
477 {
478         cited_keys_.clear();
479         selected_model_.setStringList(cited_keys_);
480 }
481
482
483 QString GuiCitation::textBefore()
484 {
485         return toqstr(params_["before"]);
486 }
487
488
489 QString GuiCitation::textAfter()
490 {
491         return toqstr(params_["after"]);
492 }
493
494
495 void GuiCitation::init()
496 {
497         // Make the list of all available bibliography keys
498         all_keys_ = to_qstring_list(availableKeys());
499         available_model_.setStringList(all_keys_);
500
501         // Ditto for the keys cited in this inset
502         QString str = toqstr(params_["key"]);
503         if (str.isEmpty())
504                 cited_keys_.clear();
505         else
506                 cited_keys_ = str.split(",");
507         selected_model_.setStringList(cited_keys_);
508 }
509
510
511 void GuiCitation::findKey(QString const & str, bool only_keys,
512         docstring field, docstring entry_type,
513         bool case_sensitive, bool reg_exp, bool reset)
514 {
515         // Used for optimisation: store last searched string.
516         static QString last_searched_string;
517         // Used to disable the above optimisation.
518         static bool last_case_sensitive;
519         static bool last_reg_exp;
520         // Reset last_searched_string in case of changed option.
521         if (last_case_sensitive != case_sensitive
522                 || last_reg_exp != reg_exp) {
523                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
524                 last_searched_string.clear();
525         }
526         // save option for next search.
527         last_case_sensitive = case_sensitive;
528         last_reg_exp = reg_exp;
529
530         Qt::CaseSensitivity qtcase = case_sensitive?
531                         Qt::CaseSensitive: Qt::CaseInsensitive;
532         QStringList keys;
533         // If new string (str) contains the last searched one...
534         if (!reset &&
535                 !last_searched_string.isEmpty() &&
536                 str.size() > 1 &&
537                 str.contains(last_searched_string, qtcase))
538                 // ... then only search within already found list.
539                 keys = available_model_.stringList();
540         else
541                 // ... else search all keys.
542                 keys = all_keys_;
543         // save searched string for next search.
544         last_searched_string = str;
545
546         QStringList result;
547         
548         // First, filter by entry_type, which will be faster than 
549         // what follows, so we may get to do that on less.
550         vector<docstring> keyVector = to_docstring_vector(keys);
551         filterByEntryType(keyVector, entry_type);
552         
553         if (str.isEmpty())
554                 result = to_qstring_list(keyVector);
555         else
556                 result = to_qstring_list(searchKeys(keyVector, only_keys, 
557                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
558         
559         available_model_.setStringList(result);
560 }
561
562
563 QStringList GuiCitation::getFieldsAsQStringList()
564 {
565         return to_qstring_list(availableFields());
566 }
567
568
569 QStringList GuiCitation::getEntriesAsQStringList()
570 {
571         return to_qstring_list(availableEntries());
572 }
573
574
575 QStringList GuiCitation::citationStyles(int sel)
576 {
577         docstring const key = qstring_to_ucs4(cited_keys_[sel]);
578         return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
579 }
580
581
582 QString GuiCitation::getKeyInfo(QString const & sel)
583 {
584         return toqstr(getInfo(qstring_to_ucs4(sel)));
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         bibkeysInfo_.fillWithBibKeys(&buffer());
599         citeStyles_ = citeStyles(engine);
600         return true;
601 }
602
603
604 void GuiCitation::clearParams()
605 {
606         params_.clear();
607         bibkeysInfo_.clear();
608 }
609
610
611 vector<docstring> GuiCitation::availableKeys() const
612 {
613         return bibkeysInfo_.getKeys();
614 }
615
616
617 vector<docstring> GuiCitation::availableFields() const
618 {
619         return bibkeysInfo_.getFields();
620 }
621
622
623 vector<docstring> GuiCitation::availableEntries() const
624 {
625         return bibkeysInfo_.getEntries();
626 }
627
628
629 void GuiCitation::filterByEntryType(
630         vector<docstring> & keyVector, docstring entry_type) 
631 {
632         if (entry_type.empty())
633                 return;
634         
635         vector<docstring>::iterator it = keyVector.begin();
636         vector<docstring>::iterator end = keyVector.end();
637         
638         vector<docstring> result;
639         for (; it != end; ++it) {
640                 docstring const key = *it;
641                 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
642                 if (cit == bibkeysInfo_.end())
643                         continue;
644                 if (cit->second.entryType() == entry_type)
645                         result.push_back(key);
646         }
647         keyVector = result;
648 }
649
650
651 CiteEngine GuiCitation::citeEngine() const
652 {
653         return buffer().params().citeEngine();
654 }
655
656
657 docstring GuiCitation::getInfo(docstring const & key) const
658 {
659         if (bibkeysInfo_.empty())
660                 return docstring();
661
662         return bibkeysInfo_.getInfo(key);
663 }
664
665
666 // Escape special chars.
667 // All characters are literals except: '.|*?+(){}[]^$\'
668 // These characters are literals when preceded by a "\", which is done here
669 // @todo: This function should be moved to support, and then the test in tests
670 //        should be moved there as well.
671 static docstring escape_special_chars(docstring const & expr)
672 {
673         // Search for all chars '.|*?+(){}[^$]\'
674         // Note that '[' and '\' must be escaped.
675         // This is a limitation of boost::regex, but all other chars in BREs
676         // are assumed literal.
677         static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
678
679         // $& is a perl-like expression that expands to all
680         // of the current match
681         // The '$' must be prefixed with the escape character '\' for
682         // boost to treat it as a literal.
683         // Thus, to prefix a matched expression with '\', we use:
684         // FIXME: UNICODE
685         return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
686 }
687
688
689 vector<docstring> GuiCitation::searchKeys(
690         vector<docstring> const & keys_to_search, bool only_keys,
691         docstring const & search_expression, docstring field,
692         bool case_sensitive, bool regex)
693 {
694         vector<docstring> foundKeys;
695
696         docstring expr = trim(search_expression);
697         if (expr.empty())
698                 return foundKeys;
699
700         if (!regex)
701                 // We must escape special chars in the search_expr so that
702                 // it is treated as a simple string by boost::regex.
703                 expr = escape_special_chars(expr);
704
705         boost::regex reg_exp;
706         try {
707                 reg_exp.assign(to_utf8(expr), case_sensitive ?
708                         boost::regex_constants::normal : boost::regex_constants::icase);
709         } catch (boost::regex_error & e) {
710                 // boost::regex throws an exception if the regular expression is not
711                 // valid.
712                 LYXERR(Debug::GUI, e.what());
713                 return vector<docstring>();
714         }
715
716         vector<docstring>::const_iterator it = keys_to_search.begin();
717         vector<docstring>::const_iterator end = keys_to_search.end();
718         for (; it != end; ++it ) {
719                 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
720                 if (info == bibkeysInfo_.end())
721                         continue;
722                 
723                 BibTeXInfo const & kvm = info->second;
724                 string data;
725                 if (only_keys)
726                         data = to_utf8(*it);
727                 else if (field.empty())
728                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
729                 else if (kvm.hasField(field))
730                         data = to_utf8(kvm.getValueForField(field));
731                 
732                 if (data.empty())
733                         continue;
734
735                 try {
736                         if (boost::regex_search(data, reg_exp))
737                                 foundKeys.push_back(*it);
738                 }
739                 catch (boost::regex_error & e) {
740                         LYXERR(Debug::GUI, e.what());
741                         return vector<docstring>();
742                 }
743         }
744         return foundKeys;
745 }
746
747
748 void GuiCitation::dispatchParams()
749 {
750         std::string const lfun = InsetCommand::params2string("citation", params_);
751         dispatch(FuncRequest(getLfun(), lfun));
752 }
753
754
755 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
756
757
758 } // namespace frontend
759 } // namespace lyx
760
761 #include "GuiCitation_moc.cpp"
762