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