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