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 refsTW->setColumnCount(1);
77 refsTW->header()->setVisible(false);
79 connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
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()));
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);
124 restored_buffer_ = -1;
127 setFocusProxy(filter_);
131 void GuiRef::enableView(bool enable)
134 // In the opposite case, updateContents() will be called anyway.
136 GuiDialog::enableView(enable);
140 void GuiRef::enableBoxes()
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);
157 void GuiRef::changed_adaptor()
164 void GuiRef::gotoClicked()
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.
171 last_reference_.isEmpty() || last_reference_.isNull();
173 last_reference_ = referenceED->text();
176 last_reference_.clear();
180 void GuiRef::selectionChanged()
182 if (isBufferReadonly())
185 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
186 if (selections.isEmpty())
188 QTreeWidgetItem * sel = selections.first();
193 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
195 if (sel->childCount() > 0) {
196 sel->setExpanded(true);
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();
205 if (cur_item_selected)
206 referenceED->setText(sel->data(0, Qt::UserRole).toString());
210 gotoPB->setEnabled(true);
211 if (!isBufferReadonly())
212 typeCO->setEnabled(true);
216 void GuiRef::refTextChanged(QString const & str)
218 gotoPB->setEnabled(!str.isEmpty());
219 typeCO->setEnabled(!str.isEmpty());
220 typeLA->setEnabled(!str.isEmpty());
224 void GuiRef::refSelected(QTreeWidgetItem * sel)
226 if (isBufferReadonly())
229 if (sel->childCount()) {
230 sel->setExpanded(false);
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();
239 if (cur_item_selected)
240 referenceED->setText(sel->data(0, Qt::UserRole).toString());
241 // <enter> or double click, inserts ref and closes dialog
246 void GuiRef::sortToggled()
252 void GuiRef::groupToggled()
258 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
260 switch (buttonBox->standardButton(button)) {
261 case QDialogButtonBox::Ok:
264 case QDialogButtonBox::Apply:
267 case QDialogButtonBox::Cancel:
271 case QDialogButtonBox::Reset:
280 void GuiRef::updateClicked()
286 void GuiRef::dialogRejected()
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();
295 void GuiRef::resetDialog()
302 void GuiRef::closeEvent(QCloseEvent * e)
310 void GuiRef::updateContents()
312 QString const orig_type =
313 typeCO->itemData(typeCO->currentIndex()).toString();
315 referenceED->clear();
318 // FIXME Bring InsetMathRef on par with InsetRef
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");
329 referenceED->setText(toqstr(params_["reference"]));
331 // restore type settings for new insets
332 bool const new_inset = params_["reference"].empty();
334 int index = typeCO->findData(orig_type);
337 typeCO->setCurrentIndex(index);
340 typeCO->setCurrentIndex(
341 typeCO->findData(toqstr(params_.getCmdName())));
342 typeCO->setEnabled(!isBufferReadonly());
344 pluralCB->setChecked(params_["plural"] == "true");
345 capsCB->setChecked(params_["caps"] == "true");
346 noprefixCB->setChecked(params_["noprefix"] == "true");
347 nolinkCB->setChecked(params_["nolink"] == "true");
349 // insert buffer list
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())));
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_);
363 int const num = theBufferList().bufferNum(buffer().fileName());
364 bufferCO->setCurrentIndex(num);
365 if (thebuffer != active_buffer_)
366 restored_buffer_ = num;
368 active_buffer_ = thebuffer;
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);
378 void GuiRef::applyView()
380 last_reference_ = referenceED->text();
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();
396 void GuiRef::setGoBack()
398 gotoPB->setText(qt_("&Go Back"));
399 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
403 void GuiRef::setGotoRef()
405 gotoPB->setText(qt_("&Go to Label"));
406 gotoPB->setToolTip(qt_("Jump to the selected label"));
410 void GuiRef::gotoRef()
412 string ref = fromqstr(referenceED->text());
426 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
428 return s1.toLower() < s2.toLower();
432 void GuiRef::redoRefs()
434 // Prevent these widgets from emitting any signals whilst
435 // we modify their state.
436 refsTW->blockSignals(true);
437 referenceED->blockSignals(true);
438 refsTW->setUpdatesEnabled(false);
442 // need this because Qt will send a highlight() here for
443 // the first item inserted
444 QString const oldSelection(referenceED->text());
446 QStringList refsNames;
447 QMap<QString, QString> refsAsStrings;
448 QStringList refsCategories;
449 vector<std::pair<docstring, docstring>>::const_iterator iter;
450 bool noprefix = false;
451 for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
452 // the plain label name
453 QString const lab = toqstr((*iter).first);
454 refsNames.append(lab);
455 // the label as gui string
456 refsAsStrings.insert(lab, toqstr((*iter).second));
457 if (groupCB->isChecked()) {
458 if (lab.contains(":")) {
459 QString const pref = lab.split(':')[0];
460 if (!refsCategories.contains(pref)) {
462 refsCategories.append(pref);
471 // sort categories case-intensively
472 sort(refsCategories.begin(), refsCategories.end(),
473 caseInsensitiveLessThan /*defined above*/);
475 refsCategories.insert(0, qt_("<No prefix>"));
477 QString const sort_method = sortingCO->isEnabled() ?
478 sortingCO->itemData(sortingCO->currentIndex()).toString()
480 if (sort_method == "nocase")
481 sort(refsNames.begin(), refsNames.end(),
482 caseInsensitiveLessThan /*defined above*/);
483 else if (sort_method == "case")
484 sort(refsNames.begin(), refsNames.end());
486 if (groupCB->isChecked()) {
487 QList<QTreeWidgetItem *> refsCats;
488 for (int i = 0; i < refsCategories.size(); ++i) {
489 QString const & cat = refsCategories.at(i);
490 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
491 item->setText(0, cat);
492 for (int j = 0; j < refsNames.size(); ++j) {
493 QString const & ref = refsNames.at(j);
494 if ((ref.startsWith(cat + QString(":")))
495 || (cat == qt_("<No prefix>")
496 && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
497 QTreeWidgetItem * child =
498 new QTreeWidgetItem(item);
499 QString const val = refsAsStrings.value(ref, ref);
500 child->setText(0, val);
501 child->setData(0, Qt::UserRole, ref);
502 item->addChild(child);
505 refsCats.append(item);
507 refsTW->addTopLevelItems(refsCats);
509 QList<QTreeWidgetItem *> refsItems;
510 for (int i = 0; i < refsNames.size(); ++i) {
511 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
512 QString const & ref = refsNames.at(i);
513 QString const val = refsAsStrings.value(ref, ref);
514 item->setText(0, val);
515 item->setData(0, Qt::UserRole, ref);
516 refsItems.append(item);
518 refsTW->addTopLevelItems(refsItems);
521 // restore the last selection or, for new insets, highlight
522 // the previous selection
523 if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
524 bool const newInset = oldSelection.isEmpty();
525 QString textToFind = newInset ? last_reference_ : oldSelection;
526 referenceED->setText(textToFind);
527 last_reference_.clear();
528 QTreeWidgetItemIterator it(refsTW);
530 if ((*it)->text(0) == textToFind) {
531 refsTW->setCurrentItem(*it);
532 (*it)->setSelected(true);
533 //Make sure selected item is visible
534 refsTW->scrollToItem(*it);
535 last_reference_ = textToFind;
541 refsTW->setUpdatesEnabled(true);
547 // Re-activate the emission of signals by these widgets.
548 refsTW->blockSignals(false);
549 referenceED->blockSignals(false);
551 gotoPB->setEnabled(!referenceED->text().isEmpty());
552 typeCO->setEnabled(!referenceED->text().isEmpty());
553 typeLA->setEnabled(!referenceED->text().isEmpty());
557 void GuiRef::updateRefs()
560 int const the_buffer = bufferCO->currentIndex();
561 if (the_buffer != -1) {
562 FileNameList const names(theBufferList().fileNames());
563 FileName const & name = names[the_buffer];
564 Buffer const * buf = theBufferList().getBuffer(name);
565 buf->getLabelList(refs_);
567 sortingCO->setEnabled(!refs_.empty());
568 refsTW->setEnabled(!refs_.empty());
569 groupCB->setEnabled(!refs_.empty());
574 bool GuiRef::isValid()
576 return !referenceED->text().isEmpty();
580 void GuiRef::gotoRef(string const & ref)
582 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
583 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
587 void GuiRef::gotoBookmark()
589 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
593 void GuiRef::filterLabels()
595 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
596 Qt::CaseSensitive : Qt::CaseInsensitive;
597 QTreeWidgetItemIterator it(refsTW);
600 (*it)->childCount() == 0
601 && !(*it)->text(0).contains(filter_->text(), cs)
608 void GuiRef::resetFilter()
610 filter_->setText(QString());
615 bool GuiRef::initialiseParams(std::string const & sdata)
617 InsetCommand::string2params(sdata, params_);
622 void GuiRef::dispatchParams()
624 std::string const lfun = InsetCommand::params2string(params_);
625 dispatch(FuncRequest(getLfun(), lfun));
630 } // namespace frontend
633 #include "moc_GuiRef.cpp"