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