]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Implement left-right navigation in GuiCitation
[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 "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "LyXToolBox.h"
22 #include "qt_helpers.h"
23
24 #include "Buffer.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "TextClass.h"
29 #include "FuncRequest.h"
30
31 #include "insets/InsetCommand.h"
32
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include <QCloseEvent>
39 #include <QMenu>
40 #include <QSettings>
41 #include <QShowEvent>
42 #include <QStandardItemModel>
43 #include <QVariant>
44
45 #include <vector>
46 #include <string>
47
48 #undef KeyPress
49
50 #include "support/regex.h"
51
52 #include <algorithm>
53 #include <string>
54 #include <vector>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60 namespace frontend {
61
62 // FIXME THREAD
63 // I am guessing that it would not hurt to make these private members.
64 static vector<string> citeCmds_;
65 static vector<CitationStyle> citeStyles_;
66
67
68 template<typename String>
69 static QStringList to_qstring_list(vector<String> const & v)
70 {
71         QStringList qlist;
72
73         for (size_t i = 0; i != v.size(); ++i) {
74                 if (v[i].empty())
75                         continue;
76                 qlist.append(lyx::toqstr(v[i]));
77         }
78         return qlist;
79 }
80
81
82 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 {
84         vector<lyx::docstring> v;
85         for (int i = 0; i != qlist.size(); ++i) {
86                 if (qlist[i].isEmpty())
87                         continue;
88                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
89         }
90         return v;
91 }
92
93
94 GuiCitation::GuiCitation(GuiView & lv)
95         : DialogView(lv, "citation", qt_("Citation")),
96           style_(0), params_(insetCode("citation"))
97 {
98         setupUi(this);
99
100         // The filter bar
101         filter_ = new FancyLineEdit(this);
102         filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
103         filter_->setButtonVisible(FancyLineEdit::Right, true);
104         filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
105         filter_->setAutoHideButton(FancyLineEdit::Right, true);
106         filter_->setPlaceholderText(qt_("All avail. citations"));
107
108         filterBarL->addWidget(filter_, 0);
109         findKeysLA->setBuddy(filter_);
110
111         // Add search options as button menu
112         regexp_ = new QAction(qt_("Regular e&xpression"), this);
113         regexp_->setCheckable(true);
114         casesense_ = new QAction(qt_("Case se&nsitive"), this);
115         casesense_->setCheckable(true);
116         instant_ = new QAction(qt_("Search as you &type"), this);
117         instant_->setCheckable(true);
118         instant_->setChecked(true);
119
120         QMenu * searchOpts = new QMenu(this);
121         searchOpts->addAction(regexp_);
122         searchOpts->addAction(casesense_);
123         searchOpts->addAction(instant_);
124         searchOptionsPB->setMenu(searchOpts);
125
126         connect(citationStyleCO, SIGNAL(activated(int)),
127                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
128         connect(starredCB, SIGNAL(clicked()),
129                 this, SLOT(updateStyles()));
130         connect(literalCB, SIGNAL(clicked()),
131                 this, SLOT(changed()));
132         connect(forceuppercaseCB, SIGNAL(clicked()),
133                 this, SLOT(updateStyles()));
134         connect(textBeforeED, SIGNAL(textChanged(QString)),
135                 this, SLOT(updateStyles()));
136         connect(textAfterED, SIGNAL(textChanged(QString)),
137                 this, SLOT(updateStyles()));
138         connect(textBeforeED, SIGNAL(returnPressed()),
139                 this, SLOT(on_okPB_clicked()));
140         connect(textAfterED, SIGNAL(returnPressed()),
141                 this, SLOT(on_okPB_clicked()));
142
143         selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
144                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
145         connect(selectionManager, SIGNAL(selectionChanged()),
146                 this, SLOT(setCitedKeys()));
147         connect(selectionManager, SIGNAL(updateHook()),
148                 this, SLOT(updateControls()));
149         connect(selectionManager, SIGNAL(okHook()),
150                 this, SLOT(on_okPB_clicked()));
151
152         connect(filter_, SIGNAL(rightButtonClicked()),
153                 this, SLOT(resetFilter()));
154         connect(filter_, SIGNAL(textEdited(QString)),
155                 this, SLOT(filterChanged(QString)));
156         connect(filter_, SIGNAL(returnPressed()),
157                 this, SLOT(filterPressed()));
158         connect(regexp_, SIGNAL(triggered()),
159                 this, SLOT(regexChanged()));
160         connect(casesense_, SIGNAL(triggered()),
161                 this, SLOT(caseChanged()));
162         connect(instant_, SIGNAL(triggered(bool)),
163                 this, SLOT(instantChanged(bool)));
164
165 #if (QT_VERSION < 0x050000)
166         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
167 #else
168         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
169 #endif
170
171         setFocusProxy(filter_);
172 }
173
174
175 void GuiCitation::closeEvent(QCloseEvent * e)
176 {
177         clearSelection();
178         DialogView::closeEvent(e);
179 }
180
181
182 void GuiCitation::applyView()
183 {
184         int const choice = max(0, citationStyleCO->currentIndex());
185         style_ = choice;
186         bool const full  = starredCB->isChecked();
187         bool const force = forceuppercaseCB->isChecked();
188
189         QString const before = textBeforeED->text();
190         QString const after = textAfterED->text();
191
192         applyParams(choice, full, force, before, after);
193 }
194
195
196 void GuiCitation::showEvent(QShowEvent * e)
197 {
198         filter_->clear();
199         availableLV->setFocus();
200         DialogView::showEvent(e);
201 }
202
203
204 void GuiCitation::on_okPB_clicked()
205 {
206         applyView();
207         clearSelection();
208         hide();
209 }
210
211
212 void GuiCitation::on_cancelPB_clicked()
213 {
214         clearSelection();
215         hide();
216 }
217
218
219 void GuiCitation::on_applyPB_clicked()
220 {
221         applyView();
222 }
223
224
225 void GuiCitation::on_restorePB_clicked()
226 {
227         init();
228         updateFilterHint();
229 }
230
231
232 void GuiCitation::updateControls()
233 {
234         BiblioInfo const & bi = bibInfo();
235         updateControls(bi);
236 }
237
238
239 // The main point of separating this out is that the fill*() methods
240 // called in update() do not need to be called for INTERNAL updates,
241 // such as when addPB is pressed, as the list of fields, entries, etc,
242 // will not have changed.
243 void GuiCitation::updateControls(BiblioInfo const & bi)
244 {
245         QModelIndex idx = selectionManager->getSelectedIndex(1);
246         updateInfo(bi, idx);
247         int i = citationStyleCO->currentIndex();
248         if (i == -1)
249                 i = 0;
250         updateFormatting(citeStyles_[i]);
251         selectionManager->update();
252 }
253
254
255 void GuiCitation::updateFormatting(CitationStyle currentStyle)
256 {
257         BufferParams const bp = documentBuffer().params();
258         bool const force = currentStyle.forceUpperCase;
259         bool const starred = currentStyle.hasStarredVersion;
260         bool const full = starred && bp.fullAuthorList();
261         bool const textbefore = currentStyle.textBefore;
262         bool const textafter = currentStyle.textAfter;
263
264         int const rows = selectedLV->model()->rowCount();
265
266         bool const qualified = currentStyle.hasQualifiedList
267                 && (rows > 1
268                     || !params_["pretextlist"].empty()
269                     || !params_["posttextlist"].empty());
270         selectedLV->horizontalHeader()->setVisible(qualified);
271         selectedLV->setColumnHidden(0, !qualified);
272         selectedLV->setColumnHidden(2, !qualified);
273         bool const haveSelection = rows > 0;
274         if (qualified) {
275                 textBeforeLA->setText(qt_("General text befo&re:"));
276                 textAfterLA->setText(qt_("General &text after:"));
277                 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
278                                              "For text that precedes individual items, "
279                                              "double-click on the respective entry above."));
280                 textAfterLA->setToolTip(qt_("General &text after:"));
281                 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
282                                              "For text that follows individual items, "
283                                              "double-click on the respective entry above."));
284         } else {
285                 textBeforeLA->setText(qt_("Text befo&re:"));
286                 if (textbefore && haveSelection)
287                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
288                 else
289                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
290                                                      "if the current citation style supports this."));
291                 textAfterLA->setText(qt_("&Text after:"));
292                 if (textafter && haveSelection)
293                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
294                 else
295                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
296                                                     "if the current citation style supports this."));
297         }
298
299         forceuppercaseCB->setEnabled(force && haveSelection);
300         if (force && haveSelection)
301                 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\").");
302         else
303                 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
304                                              "if the current citation style supports this.");
305         starredCB->setEnabled(full && haveSelection);
306         textBeforeED->setEnabled(textbefore && haveSelection);
307         textBeforeLA->setEnabled(textbefore && haveSelection);
308         textAfterED->setEnabled(textafter && haveSelection);
309         textAfterLA->setEnabled(textafter && haveSelection);
310         literalCB->setEnabled(textbefore || textafter);
311         citationStyleCO->setEnabled(haveSelection);
312         citationStyleLA->setEnabled(haveSelection);
313
314         // Check if we have a custom string/tooltip for the starred version
315         if (starred && !currentStyle.stardesc.empty()) {
316                 string val =
317                         bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
318                 docstring guistring;
319                 if (!val.empty()) {
320                         guistring = translateIfPossible(from_utf8(val));
321                         starredCB->setText(toqstr(guistring));
322                         starredCB->setEnabled(haveSelection);
323                 }
324                 if (!currentStyle.startooltip.empty()) {
325                         val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
326                                                               currentStyle.startooltip);
327                         if (!val.empty())
328                                 guistring = translateIfPossible(from_utf8(val));
329                 }
330                 // Tooltip might also be empty
331                 starredCB->setToolTip(toqstr(guistring));
332         } else {
333                 // This is the default meaning of the starred commands
334                 starredCB->setText(qt_("All aut&hors"));
335                 if (full && haveSelection)
336                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
337                 else
338                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
339                                                   "if the current citation style supports this."));
340         }
341 }
342
343
344 // Update the styles for the style combo, citationStyleCO, and mark the
345 // settings as changed. Called upon changing the cited keys (including
346 // merely reordering the keys) or editing the text before/after fields.
347 void GuiCitation::updateStyles()
348 {
349         BiblioInfo const & bi = bibInfo();
350         updateStyles(bi);
351         changed();
352 }
353
354
355 // Update the styles for the style combo, citationStyleCO.
356 void GuiCitation::updateStyles(BiblioInfo const & bi)
357 {
358         QStringList selected_keys = selectedKeys();
359         int curr = selectedLV->model()->rowCount() - 1;
360
361         if (curr < 0 || selected_keys.empty()) {
362                 citationStyleCO->clear();
363                 citationStyleCO->setEnabled(false);
364                 citationStyleLA->setEnabled(false);
365                 return;
366         }
367
368         static const size_t max_length = 80;
369         QStringList sty = citationStyles(bi, max_length);
370
371         if (sty.isEmpty()) {
372                 // some error
373                 citationStyleCO->setEnabled(false);
374                 citationStyleLA->setEnabled(false);
375                 citationStyleCO->clear();
376                 return;
377         }
378
379         citationStyleCO->blockSignals(true);
380
381         // save old index
382         int const curindex = citationStyleCO->currentIndex();
383         int const oldIndex = (curindex < 0) ? style_ : curindex;
384         citationStyleCO->clear();
385         citationStyleCO->insertItems(0, sty);
386         citationStyleCO->setEnabled(true);
387         citationStyleLA->setEnabled(true);
388         // restore old index
389         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
390                 citationStyleCO->setCurrentIndex(oldIndex);
391
392         citationStyleCO->blockSignals(false);
393 }
394
395
396 void GuiCitation::fillFields(BiblioInfo const & bi)
397 {
398         fieldsCO->blockSignals(true);
399         int const oldIndex = fieldsCO->currentIndex();
400         fieldsCO->clear();
401         QStringList const fields = to_qstring_list(bi.getFields());
402         fieldsCO->insertItem(0, qt_("All fields"));
403         fieldsCO->insertItem(1, qt_("Keys"));
404         fieldsCO->insertItems(2, fields);
405         if (oldIndex != -1 && oldIndex < fieldsCO->count())
406                 fieldsCO->setCurrentIndex(oldIndex);
407         fieldsCO->blockSignals(false);
408 }
409
410
411 void GuiCitation::fillEntries(BiblioInfo const & bi)
412 {
413         entriesCO->blockSignals(true);
414         int const oldIndex = entriesCO->currentIndex();
415         entriesCO->clear();
416         QStringList const entries = to_qstring_list(bi.getEntries());
417         entriesCO->insertItem(0, qt_("All entry types"));
418         entriesCO->insertItems(1, entries);
419         if (oldIndex != -1 && oldIndex < entriesCO->count())
420                 entriesCO->setCurrentIndex(oldIndex);
421         entriesCO->blockSignals(false);
422 }
423
424
425 bool GuiCitation::isSelected(QModelIndex const & idx)
426 {
427         QString const str = idx.data().toString();
428         return selectedKeys().contains(str);
429 }
430
431
432 void GuiCitation::setButtons()
433 {
434         int const srows = selectedLV->model()->rowCount();
435         applyPB->setEnabled(srows > 0);
436         okPB->setEnabled(srows > 0);
437 }
438
439
440 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
441 {
442         if (!idx.isValid() || bi.empty()) {
443                 infoML->document()->clear();
444                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
445                 return;
446         }
447
448         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
449         CiteItem ci;
450         ci.richtext = true;
451         QString const keytxt = toqstr(
452                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
453         infoML->document()->setHtml(keytxt);
454 }
455
456
457 void GuiCitation::findText(QString const & text, bool reset)
458 {
459         //"All Fields" and "Keys" are the first two
460         int index = fieldsCO->currentIndex() - 2;
461         BiblioInfo const & bi = bibInfo();
462         vector<docstring> const & fields = bi.getFields();
463         docstring field;
464
465         if (index <= -1 || index >= int(fields.size()))
466                 //either "All Fields" or "Keys" or an invalid value
467                 field = from_ascii("");
468         else
469                 field = fields[index];
470
471         //Was it "Keys"?
472         bool const onlyKeys = index == -1;
473
474         //"All Entry Types" is first.
475         index = entriesCO->currentIndex() - 1;
476         vector<docstring> const & entries = bi.getEntries();
477         docstring entry_type;
478         if (index < 0 || index >= int(entries.size()))
479                 entry_type = from_ascii("");
480         else
481                 entry_type = entries[index];
482
483         bool const case_sentitive = casesense_->isChecked();
484         bool const reg_exp = regexp_->isChecked();
485
486         findKey(bi, text, onlyKeys, field, entry_type,
487                        case_sentitive, reg_exp, reset);
488         //FIXME
489         //It'd be nice to save and restore the current selection in
490         //availableLV. Currently, we get an automatic reset, since the
491         //model is reset.
492
493         updateControls(bi);
494 }
495
496
497 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
498 {
499         findText(filter_->text(), true);
500 }
501
502
503 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
504 {
505         findText(filter_->text(), true);
506 }
507
508
509 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
510 {
511         if (index >= 0 && index < citationStyleCO->count()) {
512                 vector<CitationStyle> const & styles = citeStyles_;
513                 updateFormatting(styles[index]);
514                 changed();
515         }
516 }
517
518
519 void GuiCitation::filterChanged(const QString & text)
520 {
521         if (!text.isEmpty()) {
522                 if (instant_->isChecked())
523                         findText(filter_->text());
524                 return;
525         }
526         findText(filter_->text());
527         filter_->setFocus();
528 }
529
530
531 void GuiCitation::filterPressed()
532 {
533         findText(filter_->text(), true);
534 }
535
536
537 void GuiCitation::resetFilter()
538 {
539         filter_->setText(QString());
540         findText(filter_->text(), true);
541 }
542
543
544 void GuiCitation::caseChanged()
545 {
546         findText(filter_->text());
547 }
548
549
550 void GuiCitation::regexChanged()
551 {
552         findText(filter_->text());
553 }
554
555
556 void GuiCitation::updateFilterHint()
557 {
558         QString const hint = instant_->isChecked() ?
559                 qt_("Enter string to filter the list of available citations") :
560                 qt_("Enter string to filter the list of available citations and press <Enter>");
561         filter_->setToolTip(hint);
562 }
563
564
565 void GuiCitation::instantChanged(bool checked)
566 {
567         if (checked)
568                 findText(filter_->text(), true);
569
570         updateFilterHint();
571 }
572
573
574 void GuiCitation::changed()
575 {
576         setButtons();
577 }
578
579
580 void GuiCitation::applyParams(int const choice, bool full, bool force,
581         QString before, QString after)
582 {
583         if (cited_keys_.isEmpty())
584                 return;
585
586         vector<CitationStyle> const & styles = citeStyles_;
587
588         CitationStyle cs = styles[choice];
589
590         if (!cs.textBefore)
591                 before.clear();
592         if (!cs.textAfter)
593                 after.clear();
594
595         cs.forceUpperCase &= force;
596         cs.hasStarredVersion &= full;
597         string const command = citationStyleToString(cs);
598
599         params_.setCmdName(command);
600         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
601         params_["before"] = qstring_to_ucs4(before);
602         params_["after"] = qstring_to_ucs4(after);
603         if (cs.hasQualifiedList) {
604                 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
605                 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
606         }
607         params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
608         dispatchParams();
609 }
610
611
612 void GuiCitation::clearSelection()
613 {
614         cited_keys_.clear();
615         setSelectedKeys(cited_keys_);
616 }
617
618
619 void GuiCitation::setSelectedKeys(QStringList const sl)
620 {
621         selected_model_.clear();
622         selected_model_.setColumnCount(3);
623         QStringList headers;
624         headers << qt_("Text before")
625                 << qt_("Cite key")
626                 << qt_("Text after");
627         selected_model_.setHorizontalHeaderLabels(headers);
628         selectedLV->setColumnHidden(0, true);
629         selectedLV->setColumnHidden(2, true);
630         selectedLV->verticalHeader()->setVisible(false);
631         selectedLV->horizontalHeader()->setVisible(false);
632         QStringList::const_iterator it  = sl.begin();
633         QStringList::const_iterator end = sl.end();
634         for (int i = 0; it != end; ++it, ++i) {
635                 QStandardItem * si = new QStandardItem();
636                 si->setData(*it);
637                 si->setText(*it);
638                 si->setToolTip(*it);
639                 si->setEditable(false);
640                 selected_model_.setItem(i, 1, si);
641         }
642 }
643
644
645 QStringList GuiCitation::selectedKeys()
646 {
647         QStringList res;
648         for (int i = 0; i != selected_model_.rowCount(); ++i) {
649                 QStandardItem const * item = selected_model_.item(i, 1);
650                 if (item)
651                         res.append(item->text());
652         }
653         return res;
654 }
655
656
657 void GuiCitation::setPreTexts(vector<docstring> const m)
658 {
659         for (docstring const & s: m) {
660                 QStandardItem * si = new QStandardItem();
661                 docstring key;
662                 docstring pre = split(s, key, ' ');
663                 si->setData(toqstr(pre));
664                 si->setText(toqstr(pre));
665                 QModelIndexList qmil =
666                                 selected_model_.match(selected_model_.index(0, 1),
667                                                      Qt::DisplayRole, toqstr(key), 1,
668                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
669                 if (!qmil.empty())
670                         selected_model_.setItem(qmil.front().row(), 0, si);
671         }
672 }
673
674
675 vector<docstring> GuiCitation::getPreTexts()
676 {
677         vector<docstring> res;
678         for (int i = 0; i != selected_model_.rowCount(); ++i) {
679                 QStandardItem const * key = selected_model_.item(i, 1);
680                 QStandardItem const * pre = selected_model_.item(i, 0);
681                 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
682                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
683         }
684         return res;
685 }
686
687
688 void GuiCitation::setPostTexts(vector<docstring> const m)
689 {
690         for (docstring const & s: m) {
691                 QStandardItem * si = new QStandardItem();
692                 docstring key;
693                 docstring post = split(s, key, ' ');
694                 si->setData(toqstr(post));
695                 si->setText(toqstr(post));
696                 QModelIndexList qmil =
697                                 selected_model_.match(selected_model_.index(0, 1),
698                                                      Qt::DisplayRole, toqstr(key), 1,
699                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
700                 if (!qmil.empty())
701                         selected_model_.setItem(qmil.front().row(), 2, si);
702         }
703 }
704
705
706 vector<docstring> GuiCitation::getPostTexts()
707 {
708         vector<docstring> res;
709         for (int i = 0; i != selected_model_.rowCount(); ++i) {
710                 QStandardItem const * key = selected_model_.item(i, 1);
711                 QStandardItem const * post = selected_model_.item(i, 2);
712                 if (key && post)
713                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
714         }
715         return res;
716 }
717
718
719 void GuiCitation::init()
720 {
721         // Make the list of all available bibliography keys
722         BiblioInfo const & bi = bibInfo();
723         all_keys_ = to_qstring_list(bi.getKeys());
724
725         available_model_.setStringList(all_keys_);
726
727         // Ditto for the keys cited in this inset
728         QString str = toqstr(params_["key"]);
729         if (str.isEmpty())
730                 cited_keys_.clear();
731         else
732                 cited_keys_ = str.split(",");
733         setSelectedKeys(cited_keys_);
734
735         // Initialize the drop downs
736         fillEntries(bi);
737         fillFields(bi);
738
739         // Initialize the citation formatting
740         string const & cmd = params_.getCmdName();
741         CitationStyle const cs =
742                 citationStyleFromString(cmd, documentBuffer().params());
743
744         forceuppercaseCB->setChecked(cs.forceUpperCase);
745         starredCB->setChecked(cs.hasStarredVersion &&
746                 documentBuffer().params().fullAuthorList());
747         textBeforeED->setText(toqstr(params_["before"]));
748         textAfterED->setText(toqstr(params_["after"]));
749         literalCB->setChecked(params_["literal"] == "true");
750
751         setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
752         setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
753
754         // Update the interface
755         updateControls(bi);
756         updateStyles(bi);
757         if (selected_model_.rowCount()) {
758                 selectedLV->blockSignals(true);
759                 selectedLV->setFocus();
760                 selectedLV->selectRow(0);
761                 selectedLV->blockSignals(false);
762
763                 // Find the citation style
764                 vector<string> const & cmds = citeCmds_;
765                 vector<string>::const_iterator cit =
766                         std::find(cmds.begin(), cmds.end(), cs.name);
767                 int i = 0;
768                 if (cit != cmds.end())
769                         i = int(cit - cmds.begin());
770
771                 // Set the style combo appropriately
772                 citationStyleCO->blockSignals(true);
773                 citationStyleCO->setCurrentIndex(i);
774                 citationStyleCO->blockSignals(false);
775                 updateFormatting(citeStyles_[i]);
776         } else
777                 availableLV->setFocus();
778
779         applyPB->setEnabled(false);
780         okPB->setEnabled(false);
781 }
782
783
784 void GuiCitation::findKey(BiblioInfo const & bi,
785         QString const & str, bool only_keys,
786         docstring field, docstring entry_type,
787         bool case_sensitive, bool reg_exp, bool reset)
788 {
789         // FIXME THREAD
790         // This should be moved to a class member.
791         // Used for optimisation: store last searched string.
792         static QString last_searched_string;
793         // Used to disable the above optimisation.
794         static bool last_case_sensitive;
795         static bool last_reg_exp;
796         // Reset last_searched_string in case of changed option.
797         if (last_case_sensitive != case_sensitive
798                 || last_reg_exp != reg_exp) {
799                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
800                 last_searched_string.clear();
801         }
802         // save option for next search.
803         last_case_sensitive = case_sensitive;
804         last_reg_exp = reg_exp;
805
806         Qt::CaseSensitivity qtcase = case_sensitive ?
807                         Qt::CaseSensitive: Qt::CaseInsensitive;
808         QStringList keys;
809         // If new string (str) contains the last searched one...
810         if (!reset &&
811                 !last_searched_string.isEmpty() &&
812                 str.size() > 1 &&
813                 str.contains(last_searched_string, qtcase))
814                 // ... then only search within already found list.
815                 keys = available_model_.stringList();
816         else
817                 // ... else search all keys.
818                 keys = all_keys_;
819         // save searched string for next search.
820         last_searched_string = str;
821
822         QStringList result;
823
824         // First, filter by entry_type, which will be faster than
825         // what follows, so we may get to do that on less.
826         vector<docstring> keyVector = to_docstring_vector(keys);
827         filterByEntryType(bi, keyVector, entry_type);
828
829         if (str.isEmpty())
830                 result = to_qstring_list(keyVector);
831         else
832                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
833                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
834
835         available_model_.setStringList(result);
836 }
837
838
839 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
840 {
841         vector<docstring> const keys = to_docstring_vector(cited_keys_);
842         vector<CitationStyle> styles = citeStyles_;
843         int ind = citationStyleCO->currentIndex();
844         if (ind == -1)
845                 ind = 0;
846         CitationStyle cs = styles[ind];
847         vector<docstring> pretexts = getPreTexts();
848         vector<docstring> posttexts = getPostTexts();
849         bool const qualified = cs.hasQualifiedList
850                 && (selectedLV->model()->rowCount() > 1
851                     || !pretexts.empty()
852                     || !posttexts.empty());
853         std::map<docstring, docstring> pres;
854         for (docstring const & s: pretexts) {
855                 docstring key;
856                 docstring val = split(s, key, ' ');
857                 pres[key] = val;
858         }
859         std::map<docstring, docstring> posts;
860         for (docstring const & s: posttexts) {
861                 docstring key;
862                 docstring val = split(s, key, ' ');
863                 posts[key] = val;
864         }
865         CiteItem ci;
866         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
867         ci.textAfter = qstring_to_ucs4(textAfterED->text());
868         ci.forceUpperCase = forceuppercaseCB->isChecked();
869         ci.Starred = starredCB->isChecked();
870         ci.context = CiteItem::Dialog;
871         ci.max_size = max_size;
872         ci.isQualified = qualified;
873         ci.pretexts = pres;
874         ci.posttexts = posts;
875         vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
876         return to_qstring_list(ret);
877 }
878
879
880 void GuiCitation::setCitedKeys()
881 {
882         cited_keys_ = selectedKeys();
883         updateStyles();
884 }
885
886
887 bool GuiCitation::initialiseParams(string const & data)
888 {
889         InsetCommand::string2params(data, params_);
890         citeCmds_ = documentBuffer().params().citeCommands();
891         citeStyles_ = documentBuffer().params().citeStyles();
892         init();
893         return true;
894 }
895
896
897 void GuiCitation::clearParams()
898 {
899         params_.clear();
900 }
901
902
903 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
904         vector<docstring> & keyVector, docstring entry_type)
905 {
906         if (entry_type.empty())
907                 return;
908
909         vector<docstring>::iterator it = keyVector.begin();
910         vector<docstring>::iterator end = keyVector.end();
911
912         vector<docstring> result;
913         for (; it != end; ++it) {
914                 docstring const key = *it;
915                 BiblioInfo::const_iterator cit = bi.find(key);
916                 if (cit == bi.end())
917                         continue;
918                 if (cit->second.entryType() == entry_type)
919                         result.push_back(key);
920         }
921         keyVector = result;
922 }
923
924
925 // Escape special chars.
926 // All characters are literals except: '.|*?+(){}[]^$\'
927 // These characters are literals when preceded by a "\", which is done here
928 // @todo: This function should be moved to support, and then the test in tests
929 //        should be moved there as well.
930 static docstring escape_special_chars(docstring const & expr)
931 {
932         // Search for all chars '.|*?+(){}[^$]\'
933         // Note that '[', ']', and '\' must be escaped.
934         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
935
936         // $& is an ECMAScript format expression that expands to all
937         // of the current match
938 #ifdef LYX_USE_STD_REGEX
939         // To prefix a matched expression with a single literal backslash, we
940         // need to escape it for the C++ compiler and use:
941         // FIXME: UNICODE
942         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
943 #else
944         // A backslash in the format string starts an escape sequence in boost.
945         // Thus, to prefix a matched expression with a single literal backslash,
946         // we need to give two backslashes to the regex engine, and escape both
947         // for the C++ compiler and use:
948         // FIXME: UNICODE
949         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
950 #endif
951 }
952
953
954 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
955         vector<docstring> const & keys_to_search, bool only_keys,
956         docstring const & search_expression, docstring field,
957         bool case_sensitive, bool regex)
958 {
959         vector<docstring> foundKeys;
960
961         docstring expr = trim(search_expression);
962         if (expr.empty())
963                 return foundKeys;
964
965         if (!regex)
966                 // We must escape special chars in the search_expr so that
967                 // it is treated as a simple string by lyx::regex.
968                 expr = escape_special_chars(expr);
969
970         lyx::regex reg_exp;
971         try {
972                 reg_exp.assign(to_utf8(expr), case_sensitive ?
973                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
974         } catch (lyx::regex_error const & e) {
975                 // lyx::regex throws an exception if the regular expression is not
976                 // valid.
977                 LYXERR(Debug::GUI, e.what());
978                 return vector<docstring>();
979         }
980
981         vector<docstring>::const_iterator it = keys_to_search.begin();
982         vector<docstring>::const_iterator end = keys_to_search.end();
983         for (; it != end; ++it ) {
984                 BiblioInfo::const_iterator info = bi.find(*it);
985                 if (info == bi.end())
986                         continue;
987
988                 BibTeXInfo const & kvm = info->second;
989                 string data;
990                 if (only_keys)
991                         data = to_utf8(*it);
992                 else if (field.empty())
993                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
994                 else
995                         data = to_utf8(kvm[field]);
996
997                 if (data.empty())
998                         continue;
999
1000                 try {
1001                         if (lyx::regex_search(data, reg_exp))
1002                                 foundKeys.push_back(*it);
1003                 }
1004                 catch (lyx::regex_error const & e) {
1005                         LYXERR(Debug::GUI, e.what());
1006                         return vector<docstring>();
1007                 }
1008         }
1009         return foundKeys;
1010 }
1011
1012
1013 void GuiCitation::dispatchParams()
1014 {
1015         std::string const lfun = InsetCommand::params2string(params_);
1016         dispatch(FuncRequest(getLfun(), lfun));
1017 }
1018
1019
1020 BiblioInfo const & GuiCitation::bibInfo() const
1021 {
1022         Buffer const & buf = documentBuffer();
1023         buf.reloadBibInfoCache();
1024         return buf.masterBibInfo();
1025 }
1026
1027
1028 void GuiCitation::saveSession() const
1029 {
1030         Dialog::saveSession();
1031         QSettings settings;
1032         settings.setValue(
1033                 sessionKey() + "/regex", regexp_->isChecked());
1034         settings.setValue(
1035                 sessionKey() + "/casesensitive", casesense_->isChecked());
1036         settings.setValue(
1037                 sessionKey() + "/autofind", instant_->isChecked());
1038         settings.setValue(
1039                 sessionKey() + "/citestyle", style_);
1040 }
1041
1042
1043 void GuiCitation::restoreSession()
1044 {
1045         Dialog::restoreSession();
1046         QSettings settings;
1047         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1048         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1049         instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1050         style_ = settings.value(sessionKey() + "/citestyle").toInt();
1051         updateFilterHint();
1052 }
1053
1054
1055 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1056
1057
1058 } // namespace frontend
1059 } // namespace lyx
1060
1061 #include "moc_GuiCitation.cpp"
1062