3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
16 #include "GuiApplication.h"
19 #include "BufferParams.h"
20 #include "BufferList.h"
21 #include "BufferView.h"
23 #include "FancyLineEdit.h"
24 #include "FuncRequest.h"
25 #include "PDFOptions.h"
27 #include "qt_helpers.h"
29 #include "insets/InsetRef.h"
31 #include "support/FileName.h"
32 #include "support/FileNameList.h"
33 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
37 #include <QTreeWidget>
38 #include <QTreeWidgetItem>
39 #include <QPushButton>
41 #include <QCloseEvent>
42 #include <QHeaderView>
45 using namespace lyx::support;
50 GuiRef::GuiRef(GuiView & lv)
51 : GuiDialog(lv, "ref", qt_("Cross-reference")),
52 params_(insetCode("ref"))
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); });
66 filterBarL->addWidget(filter_, 0);
67 findKeysLA->setBuddy(filter_);
69 sortingCO->addItem(qt_("By Occurrence"), "unsorted");
70 sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
71 sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
73 buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
74 buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
76 connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
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()));
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);
121 restored_buffer_ = -1;
124 setFocusProxy(filter_);
128 void GuiRef::enableView(bool enable)
131 // In the opposite case, updateContents() will be called anyway.
133 GuiDialog::enableView(enable);
137 void GuiRef::enableBoxes()
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);
154 void GuiRef::changed_adaptor()
161 void GuiRef::gotoClicked()
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.
168 last_reference_.isEmpty() || last_reference_.isNull();
170 last_reference_ = referenceED->text();
173 last_reference_.clear();
177 void GuiRef::selectionChanged()
179 if (isBufferReadonly())
182 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
183 if (selections.isEmpty())
185 QTreeWidgetItem * sel = selections.first();
190 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
192 if (sel->childCount() > 0) {
193 sel->setExpanded(true);
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();
202 if (cur_item_selected)
203 referenceED->setText(sel->data(0, Qt::UserRole).toString());
207 gotoPB->setEnabled(true);
208 if (!isBufferReadonly())
209 typeCO->setEnabled(true);
213 void GuiRef::refTextChanged(QString const & str)
215 gotoPB->setEnabled(!str.isEmpty());
216 typeCO->setEnabled(!str.isEmpty());
217 typeLA->setEnabled(!str.isEmpty());
221 void GuiRef::refSelected(QTreeWidgetItem * sel)
223 if (isBufferReadonly())
226 if (sel->childCount()) {
227 sel->setExpanded(false);
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();
236 if (cur_item_selected)
237 referenceED->setText(sel->data(0, Qt::UserRole).toString());
238 // <enter> or double click, inserts ref and closes dialog
243 void GuiRef::sortToggled()
249 void GuiRef::groupToggled()
255 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
257 switch (buttonBox->standardButton(button)) {
258 case QDialogButtonBox::Ok:
261 case QDialogButtonBox::Apply:
264 case QDialogButtonBox::Cancel:
268 case QDialogButtonBox::Reset:
277 void GuiRef::updateClicked()
283 void GuiRef::dialogRejected()
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();
292 void GuiRef::resetDialog()
299 void GuiRef::closeEvent(QCloseEvent * e)
307 void GuiRef::updateContents()
309 QString const orig_type =
310 typeCO->itemData(typeCO->currentIndex()).toString();
312 referenceED->clear();
315 // FIXME Bring InsetMathRef on par with InsetRef
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");
326 referenceED->setText(toqstr(params_["reference"]));
328 // restore type settings for new insets
329 bool const new_inset = params_["reference"].empty();
331 int index = typeCO->findData(orig_type);
334 typeCO->setCurrentIndex(index);
337 typeCO->setCurrentIndex(
338 typeCO->findData(toqstr(params_.getCmdName())));
339 typeCO->setEnabled(!isBufferReadonly());
341 pluralCB->setChecked(params_["plural"] == "true");
342 capsCB->setChecked(params_["caps"] == "true");
343 noprefixCB->setChecked(params_["noprefix"] == "true");
344 nolinkCB->setChecked(params_["nolink"] == "true");
346 // insert buffer list
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())));
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_);
360 int const num = theBufferList().bufferNum(buffer().fileName());
361 bufferCO->setCurrentIndex(num);
362 if (thebuffer != active_buffer_)
363 restored_buffer_ = num;
365 active_buffer_ = thebuffer;
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);
375 void GuiRef::applyView()
377 last_reference_ = referenceED->text();
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();
393 void GuiRef::setGoBack()
395 gotoPB->setText(qt_("&Go Back"));
396 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
400 void GuiRef::setGotoRef()
402 gotoPB->setText(qt_("&Go to Label"));
403 gotoPB->setToolTip(qt_("Jump to the selected label"));
407 void GuiRef::gotoRef()
409 string ref = fromqstr(referenceED->text());
423 inline bool caseInsensitiveLessThanVec(std::tuple<QString, QString, QString> const & s1, std::tuple<QString, QString, QString> const & s2)
425 return std::get<0>(s1).toLower() < std::get<0>(s2).toLower();
428 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
430 return s1.toLower() < s2.toLower();
434 void GuiRef::redoRefs()
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);
444 // need this because Qt will send a highlight() here for
445 // the first item inserted
446 QString const oldSelection(referenceED->text());
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 (auto const & ref : refs_) {
457 // first: plain label name, second: gui name, third: pretty name
458 QString const lab = toqstr(get<0>(ref));
459 refsNames.append({lab, toqstr(get<1>(ref)),
460 toqstr(get<2>(*iter))});
461 if (groupCB->isChecked()) {
462 if (lab.contains(":")) {
463 QString const pref = lab.split(':')[0];
464 if (!refsCategories.contains(pref)) {
466 refsCategories.append(pref);
475 // sort categories case-insensitively
476 sort(refsCategories.begin(), refsCategories.end(),
477 caseInsensitiveLessThan /*defined above*/);
479 refsCategories.insert(0, qt_("<No prefix>"));
481 QString const sort_method = sortingCO->isEnabled() ?
482 sortingCO->itemData(sortingCO->currentIndex()).toString()
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());
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);
512 refsCats.append(item);
514 refsTW->addTopLevelItems(refsCats);
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);
527 refsTW->addTopLevelItems(refsItems);
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);
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;
550 refsTW->setUpdatesEnabled(true);
556 // Re-activate the emission of signals by these widgets.
557 refsTW->blockSignals(false);
558 referenceED->blockSignals(false);
560 gotoPB->setEnabled(!referenceED->text().isEmpty());
561 typeCO->setEnabled(!referenceED->text().isEmpty());
562 typeLA->setEnabled(!referenceED->text().isEmpty());
566 void GuiRef::updateRefs()
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_);
576 sortingCO->setEnabled(!refs_.empty());
577 refsTW->setEnabled(!refs_.empty());
578 groupCB->setEnabled(!refs_.empty());
583 bool GuiRef::isValid()
585 return !referenceED->text().isEmpty();
589 void GuiRef::gotoRef(string const & ref)
591 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
592 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
596 void GuiRef::gotoBookmark()
598 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
602 void GuiRef::filterLabels()
604 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
605 Qt::CaseSensitive : Qt::CaseInsensitive;
606 QTreeWidgetItemIterator it(refsTW);
609 (*it)->childCount() == 0
610 && !(*it)->text(0).contains(filter_->text(), cs)
611 && !(*it)->text(1).contains(filter_->text(), cs)
618 void GuiRef::resetFilter()
620 filter_->setText(QString());
625 bool GuiRef::initialiseParams(std::string const & sdata)
627 InsetCommand::string2params(sdata, params_);
632 void GuiRef::dispatchParams()
634 std::string const lfun = InsetCommand::params2string(params_);
635 dispatch(FuncRequest(getLfun(), lfun));
640 } // namespace frontend
643 #include "moc_GuiRef.cpp"