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