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