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