]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
44e887e40907c785eeea8459c44d63200d17f793
[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->currentData().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 = citationStyleCO->currentData().toString();
396         QString const olddata = (curdata.isEmpty()) ? style_ : curdata;
397         citationStyleCO->clear();
398         BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
399         BiblioInfo::CiteStringMap::const_iterator end = sty.end();
400         for (int ii = 1; cit != end; ++cit, ++ii)
401                 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
402         citationStyleCO->setEnabled(true);
403         citationStyleLA->setEnabled(true);
404         // restore old style selection
405         int const i = citationStyleCO->findData(olddata);
406         if (i != -1)
407                 citationStyleCO->setCurrentIndex(i);
408
409         citationStyleCO->blockSignals(false);
410 }
411
412
413 void GuiCitation::fillFields(BiblioInfo const & bi)
414 {
415         fieldsCO->blockSignals(true);
416         int const oldIndex = fieldsCO->currentIndex();
417         fieldsCO->clear();
418         QStringList const fields = to_qstring_list(bi.getFields());
419         fieldsCO->insertItem(0, qt_("All fields"));
420         fieldsCO->insertItem(1, qt_("Keys"));
421         fieldsCO->insertItems(2, fields);
422         if (oldIndex != -1 && oldIndex < fieldsCO->count())
423                 fieldsCO->setCurrentIndex(oldIndex);
424         fieldsCO->blockSignals(false);
425 }
426
427
428 void GuiCitation::fillEntries(BiblioInfo const & bi)
429 {
430         entriesCO->blockSignals(true);
431         int const oldIndex = entriesCO->currentIndex();
432         entriesCO->clear();
433         QStringList const entries = to_qstring_list(bi.getEntries());
434         entriesCO->insertItem(0, qt_("All entry types"));
435         entriesCO->insertItems(1, entries);
436         if (oldIndex != -1 && oldIndex < entriesCO->count())
437                 entriesCO->setCurrentIndex(oldIndex);
438         entriesCO->blockSignals(false);
439 }
440
441
442 bool GuiCitation::isSelected(QModelIndex const & idx)
443 {
444         QString const str = idx.data().toString();
445         return selectedKeys().contains(str);
446 }
447
448
449 void GuiCitation::setButtons()
450 {
451         int const srows = selectedLV->model()->rowCount();
452         applyPB->setEnabled(srows > 0);
453         okPB->setEnabled(srows > 0);
454 }
455
456
457 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
458 {
459         if (!idx.isValid() || bi.empty()) {
460                 infoML->document()->clear();
461                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
462                 return;
463         }
464
465         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
466         CiteItem ci;
467         ci.richtext = true;
468         QString const keytxt = toqstr(
469                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
470         infoML->document()->setHtml(keytxt);
471 }
472
473
474 void GuiCitation::findText(QString const & text, bool reset)
475 {
476         //"All Fields" and "Keys" are the first two
477         int index = fieldsCO->currentIndex() - 2;
478         BiblioInfo const & bi = bibInfo();
479         vector<docstring> const & fields = bi.getFields();
480         docstring field;
481
482         if (index <= -1 || index >= int(fields.size()))
483                 //either "All Fields" or "Keys" or an invalid value
484                 field = from_ascii("");
485         else
486                 field = fields[index];
487
488         //Was it "Keys"?
489         bool const onlyKeys = index == -1;
490
491         //"All Entry Types" is first.
492         index = entriesCO->currentIndex() - 1;
493         vector<docstring> const & entries = bi.getEntries();
494         docstring entry_type;
495         if (index < 0 || index >= int(entries.size()))
496                 entry_type = from_ascii("");
497         else
498                 entry_type = entries[index];
499
500         bool const case_sentitive = casesense_->isChecked();
501         bool const reg_exp = regexp_->isChecked();
502
503         findKey(bi, text, onlyKeys, field, entry_type,
504                        case_sentitive, reg_exp, reset);
505         //FIXME
506         //It'd be nice to save and restore the current selection in
507         //availableLV. Currently, we get an automatic reset, since the
508         //model is reset.
509
510         updateControls(bi);
511 }
512
513
514 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
515 {
516         findText(filter_->text(), true);
517 }
518
519
520 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
521 {
522         findText(filter_->text(), true);
523 }
524
525
526 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
527 {
528         if (index >= 0 && index < citationStyleCO->count()) {
529                 vector<CitationStyle> const & styles = citeStyles_;
530                 updateFormatting(styles[index]);
531                 changed();
532         }
533 }
534
535
536 void GuiCitation::filterChanged(const QString & text)
537 {
538         if (!text.isEmpty()) {
539                 if (instant_->isChecked())
540                         findText(filter_->text());
541                 return;
542         }
543         findText(filter_->text());
544         filter_->setFocus();
545 }
546
547
548 void GuiCitation::filterPressed()
549 {
550         findText(filter_->text(), true);
551 }
552
553
554 void GuiCitation::resetFilter()
555 {
556         filter_->setText(QString());
557         findText(filter_->text(), true);
558 }
559
560
561 void GuiCitation::caseChanged()
562 {
563         findText(filter_->text());
564 }
565
566
567 void GuiCitation::regexChanged()
568 {
569         findText(filter_->text());
570 }
571
572
573 void GuiCitation::updateFilterHint()
574 {
575         QString const hint = instant_->isChecked() ?
576                 qt_("Enter string to filter the list of available citations") :
577                 qt_("Enter string to filter the list of available citations and press <Enter>");
578         filter_->setToolTip(hint);
579 }
580
581
582 void GuiCitation::instantChanged(bool checked)
583 {
584         if (checked)
585                 findText(filter_->text(), true);
586
587         updateFilterHint();
588 }
589
590
591 void GuiCitation::changed()
592 {
593         setButtons();
594 }
595
596
597 void GuiCitation::applyParams(int const choice, bool full, bool force,
598         QString before, QString after)
599 {
600         if (cited_keys_.isEmpty())
601                 return;
602
603         vector<CitationStyle> const & styles = citeStyles_;
604
605         CitationStyle cs = styles[choice];
606
607         if (!cs.textBefore)
608                 before.clear();
609         if (!cs.textAfter)
610                 after.clear();
611
612         cs.forceUpperCase &= force;
613         cs.hasStarredVersion &= full;
614         string const command = citationStyleToString(cs);
615
616         params_.setCmdName(command);
617         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
618         params_["before"] = qstring_to_ucs4(before);
619         params_["after"] = qstring_to_ucs4(after);
620         if (cs.hasQualifiedList) {
621                 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
622                 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
623         }
624         params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
625         dispatchParams();
626 }
627
628
629 void GuiCitation::clearSelection()
630 {
631         cited_keys_.clear();
632         setSelectedKeys(cited_keys_);
633 }
634
635
636 void GuiCitation::setSelectedKeys(QStringList const sl)
637 {
638         selected_model_.clear();
639         selected_model_.setColumnCount(3);
640         QStringList headers;
641         headers << qt_("Text before")
642                 << qt_("Cite key")
643                 << qt_("Text after");
644         selected_model_.setHorizontalHeaderLabels(headers);
645         selectedLV->setColumnHidden(0, true);
646         selectedLV->setColumnHidden(2, true);
647         selectedLV->verticalHeader()->setVisible(false);
648         selectedLV->horizontalHeader()->setVisible(false);
649         QStringList::const_iterator it  = sl.begin();
650         QStringList::const_iterator end = sl.end();
651         for (int i = 0; it != end; ++it, ++i) {
652                 QStandardItem * si = new QStandardItem();
653                 si->setData(*it);
654                 si->setText(*it);
655                 si->setToolTip(*it);
656                 si->setEditable(false);
657                 selected_model_.setItem(i, 1, si);
658         }
659 }
660
661
662 QStringList GuiCitation::selectedKeys()
663 {
664         QStringList res;
665         for (int i = 0; i != selected_model_.rowCount(); ++i) {
666                 QStandardItem const * item = selected_model_.item(i, 1);
667                 if (item)
668                         res.append(item->text());
669         }
670         return res;
671 }
672
673
674 void GuiCitation::setPreTexts(vector<docstring> const m)
675 {
676         for (docstring const & s: m) {
677                 QStandardItem * si = new QStandardItem();
678                 docstring key;
679                 docstring pre = split(s, key, ' ');
680                 si->setData(toqstr(pre));
681                 si->setText(toqstr(pre));
682                 QModelIndexList qmil =
683                                 selected_model_.match(selected_model_.index(0, 1),
684                                                      Qt::DisplayRole, toqstr(key), 1,
685                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
686                 if (!qmil.empty())
687                         selected_model_.setItem(qmil.front().row(), 0, si);
688         }
689 }
690
691
692 vector<docstring> GuiCitation::getPreTexts()
693 {
694         vector<docstring> res;
695         for (int i = 0; i != selected_model_.rowCount(); ++i) {
696                 QStandardItem const * key = selected_model_.item(i, 1);
697                 QStandardItem const * pre = selected_model_.item(i, 0);
698                 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
699                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
700         }
701         return res;
702 }
703
704
705 void GuiCitation::setPostTexts(vector<docstring> const m)
706 {
707         for (docstring const & s: m) {
708                 QStandardItem * si = new QStandardItem();
709                 docstring key;
710                 docstring post = split(s, key, ' ');
711                 si->setData(toqstr(post));
712                 si->setText(toqstr(post));
713                 QModelIndexList qmil =
714                                 selected_model_.match(selected_model_.index(0, 1),
715                                                      Qt::DisplayRole, toqstr(key), 1,
716                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
717                 if (!qmil.empty())
718                         selected_model_.setItem(qmil.front().row(), 2, si);
719         }
720 }
721
722
723 vector<docstring> GuiCitation::getPostTexts()
724 {
725         vector<docstring> res;
726         for (int i = 0; i != selected_model_.rowCount(); ++i) {
727                 QStandardItem const * key = selected_model_.item(i, 1);
728                 QStandardItem const * post = selected_model_.item(i, 2);
729                 if (key && post)
730                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
731         }
732         return res;
733 }
734
735
736 void GuiCitation::init()
737 {
738         // Make the list of all available bibliography keys
739         BiblioInfo const & bi = bibInfo();
740         all_keys_ = to_qstring_list(bi.getKeys());
741
742         available_model_.setStringList(all_keys_);
743
744         // Ditto for the keys cited in this inset
745         QString str = toqstr(params_["key"]);
746         if (str.isEmpty())
747                 cited_keys_.clear();
748         else
749                 cited_keys_ = str.split(",");
750         setSelectedKeys(cited_keys_);
751
752         // Initialize the drop downs
753         fillEntries(bi);
754         fillFields(bi);
755
756         // Initialize the citation formatting
757         string const & cmd = params_.getCmdName();
758         CitationStyle const cs =
759                 citationStyleFromString(cmd, documentBuffer().params());
760
761         forceuppercaseCB->setChecked(cs.forceUpperCase);
762         starredCB->setChecked(cs.hasStarredVersion &&
763                 documentBuffer().params().fullAuthorList());
764         textBeforeED->setText(toqstr(params_["before"]));
765         textAfterED->setText(toqstr(params_["after"]));
766
767         // if this is a new citation, we set the literal checkbox
768         // to its last set value.
769         if (cited_keys_.isEmpty())
770                 literalCB->setChecked(literal_);
771         else
772                 literalCB->setChecked(params_["literal"] == "true");
773
774         setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
775         setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
776
777         // Update the interface
778         updateControls(bi);
779         updateStyles(bi);
780         if (selected_model_.rowCount()) {
781                 selectedLV->blockSignals(true);
782                 selectedLV->setFocus();
783                 selectedLV->selectRow(0);
784                 selectedLV->blockSignals(false);
785
786                 // Find the citation style
787                 vector<string> const & cmds = citeCmds_;
788                 vector<string>::const_iterator cit =
789                         std::find(cmds.begin(), cmds.end(), cs.name);
790                 int i = 0;
791                 if (cit != cmds.end())
792                         i = int(cit - cmds.begin());
793
794                 // Set the style combo appropriately
795                 citationStyleCO->blockSignals(true);
796                 citationStyleCO->setCurrentIndex(i);
797                 citationStyleCO->blockSignals(false);
798                 updateFormatting(citeStyles_[i]);
799         } else
800                 availableLV->setFocus();
801
802         applyPB->setEnabled(false);
803         okPB->setEnabled(false);
804 }
805
806
807 void GuiCitation::findKey(BiblioInfo const & bi,
808         QString const & str, bool only_keys,
809         docstring field, docstring entry_type,
810         bool case_sensitive, bool reg_exp, bool reset)
811 {
812         // FIXME THREAD
813         // This should be moved to a class member.
814         // Used for optimisation: store last searched string.
815         static QString last_searched_string;
816         // Used to disable the above optimisation.
817         static bool last_case_sensitive;
818         static bool last_reg_exp;
819         // Reset last_searched_string in case of changed option.
820         if (last_case_sensitive != case_sensitive
821                 || last_reg_exp != reg_exp) {
822                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
823                 last_searched_string.clear();
824         }
825         // save option for next search.
826         last_case_sensitive = case_sensitive;
827         last_reg_exp = reg_exp;
828
829         Qt::CaseSensitivity qtcase = case_sensitive ?
830                         Qt::CaseSensitive: Qt::CaseInsensitive;
831         QStringList keys;
832         // If new string (str) contains the last searched one...
833         if (!reset &&
834                 !last_searched_string.isEmpty() &&
835                 str.size() > 1 &&
836                 str.contains(last_searched_string, qtcase))
837                 // ... then only search within already found list.
838                 keys = available_model_.stringList();
839         else
840                 // ... else search all keys.
841                 keys = all_keys_;
842         // save searched string for next search.
843         last_searched_string = str;
844
845         QStringList result;
846
847         // First, filter by entry_type, which will be faster than
848         // what follows, so we may get to do that on less.
849         vector<docstring> keyVector = to_docstring_vector(keys);
850         filterByEntryType(bi, keyVector, entry_type);
851
852         if (str.isEmpty())
853                 result = to_qstring_list(keyVector);
854         else
855                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
856                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
857
858         available_model_.setStringList(result);
859 }
860
861
862 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
863 {
864         vector<docstring> const keys = to_docstring_vector(cited_keys_);
865         vector<CitationStyle> styles = citeStyles_;
866         int ind = citationStyleCO->currentIndex();
867         if (ind == -1)
868                 ind = 0;
869         CitationStyle cs = styles[ind];
870         vector<docstring> pretexts = getPreTexts();
871         vector<docstring> posttexts = getPostTexts();
872         bool const qualified = cs.hasQualifiedList
873                 && (selectedLV->model()->rowCount() > 1
874                     || !pretexts.empty()
875                     || !posttexts.empty());
876         std::map<docstring, docstring> pres;
877         for (docstring const & s: pretexts) {
878                 docstring key;
879                 docstring val = split(s, key, ' ');
880                 pres[key] = val;
881         }
882         std::map<docstring, docstring> posts;
883         for (docstring const & s: posttexts) {
884                 docstring key;
885                 docstring val = split(s, key, ' ');
886                 posts[key] = val;
887         }
888         CiteItem ci;
889         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
890         ci.textAfter = qstring_to_ucs4(textAfterED->text());
891         ci.forceUpperCase = forceuppercaseCB->isChecked();
892         ci.Starred = starredCB->isChecked();
893         ci.context = CiteItem::Dialog;
894         ci.max_size = max_size;
895         ci.isQualified = qualified;
896         ci.pretexts = pres;
897         ci.posttexts = posts;
898         BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
899         return ret;
900 }
901
902
903 void GuiCitation::setCitedKeys()
904 {
905         cited_keys_ = selectedKeys();
906         updateStyles();
907 }
908
909
910 bool GuiCitation::initialiseParams(string const & data)
911 {
912         InsetCommand::string2params(data, params_);
913         citeCmds_ = documentBuffer().params().citeCommands();
914         citeStyles_ = documentBuffer().params().citeStyles();
915         init();
916         return true;
917 }
918
919
920 void GuiCitation::clearParams()
921 {
922         params_.clear();
923 }
924
925
926 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
927         vector<docstring> & keyVector, docstring entry_type)
928 {
929         if (entry_type.empty())
930                 return;
931
932         vector<docstring>::iterator it = keyVector.begin();
933         vector<docstring>::iterator end = keyVector.end();
934
935         vector<docstring> result;
936         for (; it != end; ++it) {
937                 docstring const key = *it;
938                 BiblioInfo::const_iterator cit = bi.find(key);
939                 if (cit == bi.end())
940                         continue;
941                 if (cit->second.entryType() == entry_type)
942                         result.push_back(key);
943         }
944         keyVector = result;
945 }
946
947
948 // Escape special chars.
949 // All characters are literals except: '.|*?+(){}[]^$\'
950 // These characters are literals when preceded by a "\", which is done here
951 // @todo: This function should be moved to support, and then the test in tests
952 //        should be moved there as well.
953 static docstring escape_special_chars(docstring const & expr)
954 {
955         // Search for all chars '.|*?+(){}[^$]\'
956         // Note that '[', ']', and '\' must be escaped.
957         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
958
959         // $& is an ECMAScript format expression that expands to all
960         // of the current match
961 #ifdef LYX_USE_STD_REGEX
962         // To prefix a matched expression with a single literal backslash, we
963         // need to escape it for the C++ compiler and use:
964         // FIXME: UNICODE
965         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
966 #else
967         // A backslash in the format string starts an escape sequence in boost.
968         // Thus, to prefix a matched expression with a single literal backslash,
969         // we need to give two backslashes to the regex engine, and escape both
970         // for the C++ compiler and use:
971         // FIXME: UNICODE
972         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
973 #endif
974 }
975
976
977 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
978         vector<docstring> const & keys_to_search, bool only_keys,
979         docstring const & search_expression, docstring field,
980         bool case_sensitive, bool regex)
981 {
982         vector<docstring> foundKeys;
983
984         docstring expr = trim(search_expression);
985         if (expr.empty())
986                 return foundKeys;
987
988         if (!regex)
989                 // We must escape special chars in the search_expr so that
990                 // it is treated as a simple string by lyx::regex.
991                 expr = escape_special_chars(expr);
992
993         lyx::regex reg_exp;
994         try {
995                 reg_exp.assign(to_utf8(expr), case_sensitive ?
996                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
997         } catch (lyx::regex_error const & e) {
998                 // lyx::regex throws an exception if the regular expression is not
999                 // valid.
1000                 LYXERR(Debug::GUI, e.what());
1001                 return vector<docstring>();
1002         }
1003
1004         vector<docstring>::const_iterator it = keys_to_search.begin();
1005         vector<docstring>::const_iterator end = keys_to_search.end();
1006         for (; it != end; ++it ) {
1007                 BiblioInfo::const_iterator info = bi.find(*it);
1008                 if (info == bi.end())
1009                         continue;
1010
1011                 BibTeXInfo const & kvm = info->second;
1012                 string data;
1013                 if (only_keys)
1014                         data = to_utf8(*it);
1015                 else if (field.empty())
1016                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1017                 else
1018                         data = to_utf8(kvm[field]);
1019
1020                 if (data.empty())
1021                         continue;
1022
1023                 try {
1024                         if (lyx::regex_search(data, reg_exp))
1025                                 foundKeys.push_back(*it);
1026                 }
1027                 catch (lyx::regex_error const & e) {
1028                         LYXERR(Debug::GUI, e.what());
1029                         return vector<docstring>();
1030                 }
1031         }
1032         return foundKeys;
1033 }
1034
1035
1036 void GuiCitation::dispatchParams()
1037 {
1038         std::string const lfun = InsetCommand::params2string(params_);
1039         dispatch(FuncRequest(getLfun(), lfun));
1040 }
1041
1042
1043 BiblioInfo const & GuiCitation::bibInfo() const
1044 {
1045         Buffer const & buf = documentBuffer();
1046         buf.reloadBibInfoCache();
1047         return buf.masterBibInfo();
1048 }
1049
1050
1051 void GuiCitation::saveSession() const
1052 {
1053         Dialog::saveSession();
1054         QSettings settings;
1055         settings.setValue(
1056                 sessionKey() + "/regex", regexp_->isChecked());
1057         settings.setValue(
1058                 sessionKey() + "/casesensitive", casesense_->isChecked());
1059         settings.setValue(
1060                 sessionKey() + "/autofind", instant_->isChecked());
1061         settings.setValue(
1062                 sessionKey() + "/citestyle", style_);
1063         settings.setValue(
1064                 sessionKey() + "/literal", literal_);
1065 }
1066
1067
1068 void GuiCitation::restoreSession()
1069 {
1070         Dialog::restoreSession();
1071         QSettings settings;
1072         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1073         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1074         instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1075         style_ = settings.value(sessionKey() + "/citestyle").toString();
1076         literal_ = settings.value(sessionKey() + "/literal", false).toBool();
1077         updateFilterHint();
1078 }
1079
1080
1081 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1082
1083
1084 } // namespace frontend
1085 } // namespace lyx
1086
1087 #include "moc_GuiCitation.cpp"
1088