]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiRef.cpp
a07b73537887d3759bcae654e5ab850be7e214a6
[lyx.git] / src / frontends / qt / GuiRef.cpp
1 /**
2  * \file GuiRef.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiRef.h"
15
16 #include "GuiApplication.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferList.h"
21 #include "BufferView.h"
22 #include "Cursor.h"
23 #include "FancyLineEdit.h"
24 #include "FuncRequest.h"
25 #include "PDFOptions.h"
26
27 #include "qt_helpers.h"
28
29 #include "insets/InsetRef.h"
30
31 #include "support/FileName.h"
32 #include "support/FileNameList.h"
33 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
34
35 #include <QLineEdit>
36 #include <QCheckBox>
37 #include <QTreeWidget>
38 #include <QTreeWidgetItem>
39 #include <QPushButton>
40 #include <QToolTip>
41 #include <QCloseEvent>
42 #include <QHeaderView>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48 namespace frontend {
49
50 GuiRef::GuiRef(GuiView & lv)
51         : GuiDialog(lv, "ref", qt_("Cross-reference")),
52           params_(insetCode("ref"))
53 {
54         setupUi(this);
55
56         at_ref_ = false;
57
58         // The filter bar
59         filter_ = new FancyLineEdit(this);
60         filter_->setClearButton(true);
61         filter_->setPlaceholderText(qt_("All available labels"));
62         filter_->setToolTip(qt_("Enter string to filter the list of available labels"));
63         connect(filter_, &FancyLineEdit::downPressed,
64                 refsTW, [this](){ focusAndHighlight(refsTW); });
65
66         filterBarL->addWidget(filter_, 0);
67         findKeysLA->setBuddy(filter_);
68
69         sortingCO->addItem(qt_("By Occurrence"), "unsorted");
70         sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
71         sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
72
73         buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
74         buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
75
76         refsTW->setColumnCount(1);
77         refsTW->header()->setVisible(false);
78
79         connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
80
81         connect(typeCO, SIGNAL(activated(int)),
82                 this, SLOT(changed_adaptor()));
83         connect(referenceED, SIGNAL(textChanged(QString)),
84                 this, SLOT(refTextChanged(QString)));
85         connect(referenceED, SIGNAL(textChanged(QString)),
86                 this, SLOT(changed_adaptor()));
87         connect(filter_, SIGNAL(textEdited(QString)),
88                 this, SLOT(filterLabels()));
89         connect(filter_, SIGNAL(rightButtonClicked()),
90                 this, SLOT(resetFilter()));
91         connect(csFindCB, SIGNAL(clicked()),
92                 this, SLOT(filterLabels()));
93         connect(refsTW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
94                 this, SLOT(refHighlighted(QTreeWidgetItem *)));
95         connect(refsTW, SIGNAL(itemSelectionChanged()),
96                 this, SLOT(selectionChanged()));
97         connect(refsTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
98                 this, SLOT(refSelected(QTreeWidgetItem *)));
99         connect(sortingCO, SIGNAL(activated(int)),
100                 this, SLOT(sortToggled()));
101         connect(groupCB, SIGNAL(clicked()),
102                 this, SLOT(groupToggled()));
103         connect(gotoPB, SIGNAL(clicked()),
104                 this, SLOT(gotoClicked()));
105         connect(bufferCO, SIGNAL(activated(int)),
106                 this, SLOT(updateClicked()));
107         connect(pluralCB, SIGNAL(clicked()),
108                 this, SLOT(changed_adaptor()));
109         connect(capsCB, SIGNAL(clicked()),
110                 this, SLOT(changed_adaptor()));
111         connect(noprefixCB, SIGNAL(clicked()),
112                 this, SLOT(changed_adaptor()));
113         connect(nolinkCB, SIGNAL(clicked()),
114                 this, SLOT(changed_adaptor()));
115
116         enableBoxes();
117
118         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
119         bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
120         bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
121         bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
122         bc().addReadOnly(typeCO);
123
124         restored_buffer_ = -1;
125         active_buffer_ = -1;
126
127         setFocusProxy(filter_);
128 }
129
130
131 void GuiRef::enableView(bool enable)
132 {
133         if (!enable)
134                 // In the opposite case, updateContents() will be called anyway.
135                 updateContents();
136         GuiDialog::enableView(enable);
137 }
138
139
140 void GuiRef::enableBoxes()
141 {
142         QString const reftype =
143             typeCO->itemData(typeCO->currentIndex()).toString();
144         bool const isFormatted = (reftype == "formatted");
145         bool const isLabelOnly = (reftype == "labelonly");
146         bool const usingRefStyle = buffer().params().use_refstyle;
147         bool const intext = bufferview()->cursor().inTexted();
148         bool const hyper_on = buffer().params().pdfoptions().use_hyperref;
149         pluralCB->setEnabled(intext && isFormatted && usingRefStyle);
150         capsCB->setEnabled(intext && isFormatted && usingRefStyle);
151         noprefixCB->setEnabled(intext && isLabelOnly);
152         // disabling of hyperlinks not supported by formatted references
153         nolinkCB->setEnabled(hyper_on && intext && !isFormatted && !isLabelOnly);
154 }
155
156
157 void GuiRef::changed_adaptor()
158 {
159         changed();
160         enableBoxes();
161 }
162
163
164 void GuiRef::gotoClicked()
165 {
166         // By setting last_reference_, we ensure that the reference
167         // to which we are going (or from which we are returning) is
168         // restored in the dialog. It's a bit of a hack, but it works,
169         // and no-one seems to have any better idea.
170         bool const toggled =
171                 last_reference_.isEmpty() || last_reference_.isNull();
172         if (toggled)
173                 last_reference_ = referenceED->text();
174         gotoRef();
175         if (toggled)
176                 last_reference_.clear();
177 }
178
179
180 void GuiRef::selectionChanged()
181 {
182         if (isBufferReadonly())
183                 return;
184
185         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
186         if (selections.isEmpty())
187                 return;
188         QTreeWidgetItem * sel = selections.first();
189         refHighlighted(sel);
190 }
191
192
193 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
194 {
195         if (sel->childCount() > 0) {
196                 sel->setExpanded(true);
197                 return;
198         }
199
200 /*      int const cur_item = refsTW->currentRow();
201         bool const cur_item_selected = cur_item >= 0 ?
202                 refsLB->isSelected(cur_item) : false;*/
203         bool const cur_item_selected = sel->isSelected();
204
205         if (cur_item_selected)
206                 referenceED->setText(sel->data(0, Qt::UserRole).toString());
207
208         if (at_ref_)
209                 gotoRef();
210         gotoPB->setEnabled(true);
211         if (!isBufferReadonly())
212                 typeCO->setEnabled(true);
213 }
214
215
216 void GuiRef::refTextChanged(QString const & str)
217 {
218         gotoPB->setEnabled(!str.isEmpty());
219         typeCO->setEnabled(!str.isEmpty());
220         typeLA->setEnabled(!str.isEmpty());
221 }
222
223
224 void GuiRef::refSelected(QTreeWidgetItem * sel)
225 {
226         if (isBufferReadonly())
227                 return;
228
229         if (sel->childCount()) {
230                 sel->setExpanded(false);
231                 return;
232         }
233
234 /*      int const cur_item = refsTW->currentRow();
235         bool const cur_item_selected = cur_item >= 0 ?
236                 refsLB->isSelected(cur_item) : false;*/
237         bool const cur_item_selected = sel->isSelected();
238
239         if (cur_item_selected)
240                 referenceED->setText(sel->data(0, Qt::UserRole).toString());
241         // <enter> or double click, inserts ref and closes dialog
242         slotOK();
243 }
244
245
246 void GuiRef::sortToggled()
247 {
248         redoRefs();
249 }
250
251
252 void GuiRef::groupToggled()
253 {
254         redoRefs();
255 }
256
257
258 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
259 {
260         switch (buttonBox->standardButton(button)) {
261         case QDialogButtonBox::Ok:
262                 slotOK();
263                 break;
264         case QDialogButtonBox::Apply:
265                 slotApply();
266                 break;
267         case QDialogButtonBox::Cancel:
268                 slotClose();
269                 resetDialog();
270                 break;
271         case QDialogButtonBox::Reset:
272                 updateClicked();
273                 break;
274         default:
275                 break;
276         }
277 }
278
279
280 void GuiRef::updateClicked()
281 {
282         updateRefs();
283 }
284
285
286 void GuiRef::dialogRejected()
287 {
288         resetDialog();
289         // We have to do this manually, instead of calling slotClose(), because
290         // the dialog has already been made invisible before rejected() triggers.
291         Dialog::disconnect();
292 }
293
294
295 void GuiRef::resetDialog()
296 {
297         at_ref_ = false;
298         setGotoRef();
299 }
300
301
302 void GuiRef::closeEvent(QCloseEvent * e)
303 {
304         slotClose();
305         resetDialog();
306         e->accept();
307 }
308
309
310 void GuiRef::updateContents()
311 {
312         QString const orig_type =
313                 typeCO->itemData(typeCO->currentIndex()).toString();
314
315         referenceED->clear();
316         typeCO->clear();
317
318         // FIXME Bring InsetMathRef on par with InsetRef
319         // (see #11104)
320         typeCO->addItem(qt_("<reference>"), "ref");
321         typeCO->addItem(qt_("(<reference>)"), "eqref");
322         typeCO->addItem(qt_("<page>"), "pageref");
323         typeCO->addItem(qt_("on page <page>"), "vpageref");
324         typeCO->addItem(qt_("<reference> on page <page>"), "vref");
325         typeCO->addItem(qt_("Textual reference"), "nameref");
326         typeCO->addItem(qt_("Formatted reference"), "formatted");
327         typeCO->addItem(qt_("Label only"), "labelonly");
328
329         referenceED->setText(toqstr(params_["reference"]));
330
331         // restore type settings for new insets
332         bool const new_inset = params_["reference"].empty();
333         if (new_inset) {
334                 int index = typeCO->findData(orig_type);
335                 if (index == -1)
336                         index = 0;
337                 typeCO->setCurrentIndex(index);
338         }
339         else
340                 typeCO->setCurrentIndex(
341                         typeCO->findData(toqstr(params_.getCmdName())));
342         typeCO->setEnabled(!isBufferReadonly());
343
344         pluralCB->setChecked(params_["plural"] == "true");
345         capsCB->setChecked(params_["caps"] == "true");
346         noprefixCB->setChecked(params_["noprefix"] == "true");
347         nolinkCB->setChecked(params_["nolink"] == "true");
348
349         // insert buffer list
350         bufferCO->clear();
351         FileNameList const buffers(theBufferList().fileNames());
352         for (FileNameList::const_iterator it = buffers.begin();
353              it != buffers.end(); ++it) {
354                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
355         }
356
357         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
358         // restore the buffer combo setting for new insets
359         if (new_inset && restored_buffer_ != -1
360             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
361                 bufferCO->setCurrentIndex(restored_buffer_);
362         else {
363                 int const num = theBufferList().bufferNum(buffer().fileName());
364                 bufferCO->setCurrentIndex(num);
365                 if (thebuffer != active_buffer_)
366                         restored_buffer_ = num;
367         }
368         active_buffer_ = thebuffer;
369
370         updateRefs();
371         enableBoxes();
372         // Activate OK/Apply buttons if the users inserts a new ref
373         // and we have a valid pre-setting.
374         bc().setValid(isValid() && new_inset);
375 }
376
377
378 void GuiRef::applyView()
379 {
380         last_reference_ = referenceED->text();
381
382         params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
383         params_["reference"] = qstring_to_ucs4(last_reference_);
384         params_["plural"] = pluralCB->isChecked() ?
385               from_ascii("true") : from_ascii("false");
386         params_["caps"] = capsCB->isChecked() ?
387               from_ascii("true") : from_ascii("false");
388         params_["noprefix"] = noprefixCB->isChecked() ?
389               from_ascii("true") : from_ascii("false");
390         params_["nolink"] = nolinkCB->isChecked() ?
391               from_ascii("true") : from_ascii("false");
392         restored_buffer_ = bufferCO->currentIndex();
393 }
394
395
396 void GuiRef::setGoBack()
397 {
398         gotoPB->setText(qt_("&Go Back"));
399         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
400 }
401
402
403 void GuiRef::setGotoRef()
404 {
405         gotoPB->setText(qt_("&Go to Label"));
406         gotoPB->setToolTip(qt_("Jump to the selected label"));
407 }
408
409
410 void GuiRef::gotoRef()
411 {
412         string ref = fromqstr(referenceED->text());
413
414         if (at_ref_) {
415                 // go back
416                 setGotoRef();
417                 gotoBookmark();
418         } else {
419                 // go to the ref
420                 setGoBack();
421                 gotoRef(ref);
422         }
423         at_ref_ = !at_ref_;
424 }
425
426 inline bool caseInsensitiveLessThanVec(QPair<QString, QString> const & s1, QPair<QString, QString> const & s2)
427 {
428         return s1.first.toLower() < s2.first.toLower();
429 }
430
431 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
432 {
433         return s1.toLower() < s2.toLower();
434 }
435
436
437 void GuiRef::redoRefs()
438 {
439         // Prevent these widgets from emitting any signals whilst
440         // we modify their state.
441         refsTW->blockSignals(true);
442         referenceED->blockSignals(true);
443         refsTW->setUpdatesEnabled(false);
444
445         refsTW->clear();
446
447         // need this because Qt will send a highlight() here for
448         // the first item inserted
449         QString const oldSelection(referenceED->text());
450
451         // Plain label and GUI string. This might get resorted below
452         QVector<QPair<QString, QString>> refsNames;
453         // List of categories (prefixes)
454         QStringList refsCategories;
455         // Do we have a prefix-less label at all?
456         bool noprefix = false;
457         vector<std::pair<docstring, docstring>>::const_iterator iter;
458         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
459                 // first: plain label name, second: gui name
460                 QString const lab = toqstr((*iter).first);
461                 refsNames.append(QPair(lab, toqstr((*iter).second)));
462                 if (groupCB->isChecked()) {
463                         if (lab.contains(":")) {
464                                 QString const pref = lab.split(':')[0];
465                                 if (!refsCategories.contains(pref)) {
466                                         if (!pref.isEmpty())
467                                                 refsCategories.append(pref);
468                                         else
469                                                 noprefix = true;
470                                 }
471                         }
472                         else
473                                 noprefix = true;
474                 }
475         }
476         // sort categories case-intensively
477         sort(refsCategories.begin(), refsCategories.end(),
478                   caseInsensitiveLessThan /*defined above*/);
479         if (noprefix)
480                 refsCategories.insert(0, qt_("<No prefix>"));
481
482         QString const sort_method = sortingCO->isEnabled() ?
483                                         sortingCO->itemData(sortingCO->currentIndex()).toString()
484                                         : QString();
485         // Sort items if so requested.
486         if (sort_method == "nocase")
487                 sort(refsNames.begin(), refsNames.end(),
488                           caseInsensitiveLessThanVec /*defined above*/);
489         else if (sort_method == "case")
490                 sort(refsNames.begin(), refsNames.end());
491
492         if (groupCB->isChecked()) {
493                 QList<QTreeWidgetItem *> refsCats;
494                 for (int i = 0; i < refsCategories.size(); ++i) {
495                         QString const & cat = refsCategories.at(i);
496                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
497                         item->setText(0, cat);
498                         for (int j = 0; j < refsNames.size(); ++j) {
499                                 QString const ref = refsNames.at(j).first;
500                                 if ((ref.startsWith(cat + QString(":")))
501                                     || (cat == qt_("<No prefix>")
502                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
503                                                 QTreeWidgetItem * child =
504                                                         new QTreeWidgetItem(item);
505                                                 QString const val = refsNames.at(j).second;
506                                                 child->setText(0, val);
507                                                 child->setData(0, Qt::UserRole, ref);
508                                                 item->addChild(child);
509                                 }
510                         }
511                         refsCats.append(item);
512                 }
513                 refsTW->addTopLevelItems(refsCats);
514         } else {
515                 QList<QTreeWidgetItem *> refsItems;
516                 for (int i = 0; i < refsNames.size(); ++i) {
517                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
518                         QString const ref = refsNames.at(i).first;
519                         QString const val = refsNames.at(i).second;
520                         item->setText(0, val);
521                         item->setData(0, Qt::UserRole, ref);
522                         refsItems.append(item);
523                 }
524                 refsTW->addTopLevelItems(refsItems);
525         }
526
527         // restore the last selection or, for new insets, highlight
528         // the previous selection
529         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
530                 bool const newInset = oldSelection.isEmpty();
531                 QString textToFind = newInset ? last_reference_ : oldSelection;
532                 referenceED->setText(textToFind);
533                 last_reference_.clear();
534                 QTreeWidgetItemIterator it(refsTW);
535                 while (*it) {
536                         if ((*it)->text(0) == textToFind) {
537                                 refsTW->setCurrentItem(*it);
538                                 (*it)->setSelected(true);
539                                 //Make sure selected item is visible
540                                 refsTW->scrollToItem(*it);
541                                 last_reference_ = textToFind;
542                                 break;
543                         }
544                         ++it;
545                 }
546         }
547         refsTW->setUpdatesEnabled(true);
548         refsTW->update();
549
550         // redo filter
551         filterLabels();
552
553         // Re-activate the emission of signals by these widgets.
554         refsTW->blockSignals(false);
555         referenceED->blockSignals(false);
556
557         gotoPB->setEnabled(!referenceED->text().isEmpty());
558         typeCO->setEnabled(!referenceED->text().isEmpty());
559         typeLA->setEnabled(!referenceED->text().isEmpty());
560 }
561
562
563 void GuiRef::updateRefs()
564 {
565         refs_.clear();
566         int const the_buffer = bufferCO->currentIndex();
567         if (the_buffer != -1) {
568                 FileNameList const names(theBufferList().fileNames());
569                 FileName const & name = names[the_buffer];
570                 Buffer const * buf = theBufferList().getBuffer(name);
571                 buf->getLabelList(refs_);
572         }
573         sortingCO->setEnabled(!refs_.empty());
574         refsTW->setEnabled(!refs_.empty());
575         groupCB->setEnabled(!refs_.empty());
576         redoRefs();
577 }
578
579
580 bool GuiRef::isValid()
581 {
582         return !referenceED->text().isEmpty();
583 }
584
585
586 void GuiRef::gotoRef(string const & ref)
587 {
588         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
589         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
590 }
591
592
593 void GuiRef::gotoBookmark()
594 {
595         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
596 }
597
598
599 void GuiRef::filterLabels()
600 {
601         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
602                 Qt::CaseSensitive : Qt::CaseInsensitive;
603         QTreeWidgetItemIterator it(refsTW);
604         while (*it) {
605                 (*it)->setHidden(
606                         (*it)->childCount() == 0
607                         && !(*it)->text(0).contains(filter_->text(), cs)
608                 );
609                 ++it;
610         }
611 }
612
613
614 void GuiRef::resetFilter()
615 {
616         filter_->setText(QString());
617         filterLabels();
618 }
619
620
621 bool GuiRef::initialiseParams(std::string const & sdata)
622 {
623         InsetCommand::string2params(sdata, params_);
624         return true;
625 }
626
627
628 void GuiRef::dispatchParams()
629 {
630         std::string const lfun = InsetCommand::params2string(params_);
631         dispatch(FuncRequest(getLfun(), lfun));
632         connectToNewInset();
633 }
634
635
636 } // namespace frontend
637 } // namespace lyx
638
639 #include "moc_GuiRef.cpp"