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