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"
26 #include "qt_helpers.h"
28 #include "insets/InsetRef.h"
30 #include "support/FileName.h"
31 #include "support/FileNameList.h"
32 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
36 #include <QTreeWidget>
37 #include <QTreeWidgetItem>
38 #include <QPushButton>
40 #include <QCloseEvent>
41 #include <QHeaderView>
44 using namespace lyx::support;
49 GuiRef::GuiRef(GuiView & lv)
50 : GuiDialog(lv, "ref", qt_("Cross-reference")),
51 params_(insetCode("ref"))
58 filter_ = new FancyLineEdit(this);
59 filter_->setClearButton(true);
60 filter_->setPlaceholderText(qt_("All available labels"));
61 filter_->setToolTip(qt_("Enter string to filter the list of available labels"));
62 connect(filter_, &FancyLineEdit::downPressed,
63 refsTW, [this](){ focusAndHighlight(refsTW); });
65 filterBarL->addWidget(filter_, 0);
66 findKeysLA->setBuddy(filter_);
68 sortingCO->addItem(qt_("By Occurrence"), "unsorted");
69 sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
70 sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
72 buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
73 buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
75 refsTW->setColumnCount(1);
76 refsTW->header()->setVisible(false);
78 connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
80 connect(typeCO, SIGNAL(activated(int)),
81 this, SLOT(changed_adaptor()));
82 connect(referenceED, SIGNAL(textChanged(QString)),
83 this, SLOT(refTextChanged(QString)));
84 connect(referenceED, SIGNAL(textChanged(QString)),
85 this, SLOT(changed_adaptor()));
86 connect(filter_, SIGNAL(textEdited(QString)),
87 this, SLOT(filterLabels()));
88 connect(filter_, SIGNAL(rightButtonClicked()),
89 this, SLOT(resetFilter()));
90 connect(csFindCB, SIGNAL(clicked()),
91 this, SLOT(filterLabels()));
92 connect(refsTW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
93 this, SLOT(refHighlighted(QTreeWidgetItem *)));
94 connect(refsTW, SIGNAL(itemSelectionChanged()),
95 this, SLOT(selectionChanged()));
96 connect(refsTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
97 this, SLOT(refSelected(QTreeWidgetItem *)));
98 connect(sortingCO, SIGNAL(activated(int)),
99 this, SLOT(sortToggled()));
100 connect(groupCB, SIGNAL(clicked()),
101 this, SLOT(groupToggled()));
102 connect(gotoPB, SIGNAL(clicked()),
103 this, SLOT(gotoClicked()));
104 connect(bufferCO, SIGNAL(activated(int)),
105 this, SLOT(updateClicked()));
106 connect(pluralCB, SIGNAL(clicked()),
107 this, SLOT(changed_adaptor()));
108 connect(capsCB, SIGNAL(clicked()),
109 this, SLOT(changed_adaptor()));
110 connect(noprefixCB, 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 pluralCB->setEnabled(intext && isFormatted && usingRefStyle);
146 capsCB->setEnabled(intext && isFormatted && usingRefStyle);
147 noprefixCB->setEnabled(intext && isLabelOnly);
151 void GuiRef::changed_adaptor()
158 void GuiRef::gotoClicked()
160 // By setting last_reference_, we ensure that the reference
161 // to which we are going (or from which we are returning) is
162 // restored in the dialog. It's a bit of a hack, but it works,
163 // and no-one seems to have any better idea.
165 last_reference_.isEmpty() || last_reference_.isNull();
167 last_reference_ = referenceED->text();
170 last_reference_.clear();
174 void GuiRef::selectionChanged()
176 if (isBufferReadonly())
179 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
180 if (selections.isEmpty())
182 QTreeWidgetItem * sel = selections.first();
187 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
189 if (sel->childCount() > 0) {
190 sel->setExpanded(true);
194 /* int const cur_item = refsTW->currentRow();
195 bool const cur_item_selected = cur_item >= 0 ?
196 refsLB->isSelected(cur_item) : false;*/
197 bool const cur_item_selected = sel->isSelected();
199 if (cur_item_selected)
200 referenceED->setText(sel->data(0, Qt::UserRole).toString());
204 gotoPB->setEnabled(true);
205 if (!isBufferReadonly())
206 typeCO->setEnabled(true);
210 void GuiRef::refTextChanged(QString const & str)
212 gotoPB->setEnabled(!str.isEmpty());
213 typeCO->setEnabled(!str.isEmpty());
214 typeLA->setEnabled(!str.isEmpty());
218 void GuiRef::refSelected(QTreeWidgetItem * sel)
220 if (isBufferReadonly())
223 if (sel->childCount()) {
224 sel->setExpanded(false);
228 /* int const cur_item = refsTW->currentRow();
229 bool const cur_item_selected = cur_item >= 0 ?
230 refsLB->isSelected(cur_item) : false;*/
231 bool const cur_item_selected = sel->isSelected();
233 if (cur_item_selected)
234 referenceED->setText(sel->data(0, Qt::UserRole).toString());
235 // <enter> or double click, inserts ref and closes dialog
240 void GuiRef::sortToggled()
246 void GuiRef::groupToggled()
252 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
254 switch (buttonBox->standardButton(button)) {
255 case QDialogButtonBox::Ok:
258 case QDialogButtonBox::Apply:
261 case QDialogButtonBox::Cancel:
265 case QDialogButtonBox::Reset:
274 void GuiRef::updateClicked()
280 void GuiRef::dialogRejected()
283 // We have to do this manually, instead of calling slotClose(), because
284 // the dialog has already been made invisible before rejected() triggers.
285 Dialog::disconnect();
289 void GuiRef::resetDialog()
296 void GuiRef::closeEvent(QCloseEvent * e)
304 void GuiRef::updateContents()
306 QString const orig_type =
307 typeCO->itemData(typeCO->currentIndex()).toString();
309 referenceED->clear();
312 // FIXME Bring InsetMathRef on par with InsetRef
314 typeCO->addItem(qt_("<reference>"), "ref");
315 typeCO->addItem(qt_("(<reference>)"), "eqref");
316 typeCO->addItem(qt_("<page>"), "pageref");
317 typeCO->addItem(qt_("on page <page>"), "vpageref");
318 typeCO->addItem(qt_("<reference> on page <page>"), "vref");
319 typeCO->addItem(qt_("Textual reference"), "nameref");
320 typeCO->addItem(qt_("Formatted reference"), "formatted");
321 typeCO->addItem(qt_("Label only"), "labelonly");
323 referenceED->setText(toqstr(params_["reference"]));
325 // restore type settings for new insets
326 bool const new_inset = params_["reference"].empty();
328 int index = typeCO->findData(orig_type);
331 typeCO->setCurrentIndex(index);
334 typeCO->setCurrentIndex(
335 typeCO->findData(toqstr(params_.getCmdName())));
336 typeCO->setEnabled(!isBufferReadonly());
338 pluralCB->setChecked(params_["plural"] == "true");
339 capsCB->setChecked(params_["caps"] == "true");
340 noprefixCB->setChecked(params_["noprefix"] == "true");
342 // insert buffer list
344 FileNameList const buffers(theBufferList().fileNames());
345 for (FileNameList::const_iterator it = buffers.begin();
346 it != buffers.end(); ++it) {
347 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
350 int const thebuffer = theBufferList().bufferNum(buffer().fileName());
351 // restore the buffer combo setting for new insets
352 if (new_inset && restored_buffer_ != -1
353 && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
354 bufferCO->setCurrentIndex(restored_buffer_);
356 int const num = theBufferList().bufferNum(buffer().fileName());
357 bufferCO->setCurrentIndex(num);
358 if (thebuffer != active_buffer_)
359 restored_buffer_ = num;
361 active_buffer_ = thebuffer;
365 // Activate OK/Apply buttons if the users inserts a new ref
366 // and we have a valid pre-setting.
367 bc().setValid(isValid() && new_inset);
371 void GuiRef::applyView()
373 last_reference_ = referenceED->text();
375 params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
376 params_["reference"] = qstring_to_ucs4(last_reference_);
377 params_["plural"] = pluralCB->isChecked() ?
378 from_ascii("true") : from_ascii("false");
379 params_["caps"] = capsCB->isChecked() ?
380 from_ascii("true") : from_ascii("false");
381 params_["noprefix"] = noprefixCB->isChecked() ?
382 from_ascii("true") : from_ascii("false");
383 restored_buffer_ = bufferCO->currentIndex();
387 void GuiRef::setGoBack()
389 gotoPB->setText(qt_("&Go Back"));
390 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
394 void GuiRef::setGotoRef()
396 gotoPB->setText(qt_("&Go to Label"));
397 gotoPB->setToolTip(qt_("Jump to the selected label"));
401 void GuiRef::gotoRef()
403 string ref = fromqstr(referenceED->text());
417 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
419 return s1.toLower() < s2.toLower();
423 void GuiRef::redoRefs()
425 // Prevent these widgets from emitting any signals whilst
426 // we modify their state.
427 refsTW->blockSignals(true);
428 referenceED->blockSignals(true);
429 refsTW->setUpdatesEnabled(false);
433 // need this because Qt will send a highlight() here for
434 // the first item inserted
435 QString const oldSelection(referenceED->text());
437 QStringList refsNames;
438 QStringList refsAsStrings;
439 QStringList refsCategories;
440 vector<std::pair<docstring, docstring>>::const_iterator iter;
441 bool noprefix = false;
442 for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
443 // the plain label name
444 QString const lab = toqstr((*iter).first);
445 refsNames.append(lab);
446 // the label as gui string
447 refsAsStrings.append(toqstr((*iter).second));
448 if (groupCB->isChecked()) {
449 if (lab.contains(":")) {
450 QString const pref = lab.split(':')[0];
451 if (!refsCategories.contains(pref)) {
453 refsCategories.append(pref);
462 // sort categories case-intensively
463 sort(refsCategories.begin(), refsCategories.end(),
464 caseInsensitiveLessThan /*defined above*/);
466 refsCategories.insert(0, qt_("<No prefix>"));
468 QString const sort_method = sortingCO->isEnabled() ?
469 sortingCO->itemData(sortingCO->currentIndex()).toString()
471 if (sort_method == "nocase")
472 sort(refsNames.begin(), refsNames.end(),
473 caseInsensitiveLessThan /*defined above*/);
474 else if (sort_method == "case")
475 sort(refsNames.begin(), refsNames.end());
477 if (groupCB->isChecked()) {
478 QList<QTreeWidgetItem *> refsCats;
479 for (int i = 0; i < refsCategories.size(); ++i) {
480 QString const & cat = refsCategories.at(i);
481 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
482 item->setText(0, cat);
483 for (int j = 0; j < refsNames.size(); ++j) {
484 QString const & ref = refsNames.at(j);
485 if ((ref.startsWith(cat + QString(":")))
486 || (cat == qt_("<No prefix>")
487 && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
488 QTreeWidgetItem * child =
489 new QTreeWidgetItem(item);
490 item->setText(0, refsAsStrings.at(j));
491 item->setData(0, Qt::UserRole, ref);
492 item->addChild(child);
495 refsCats.append(item);
497 refsTW->addTopLevelItems(refsCats);
499 QList<QTreeWidgetItem *> refsItems;
500 for (int i = 0; i < refsNames.size(); ++i) {
501 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
502 QString const & ref = refsNames.at(i);
503 item->setText(0, refsAsStrings.at(i));
504 item->setData(0, Qt::UserRole, ref);
505 refsItems.append(item);
507 refsTW->addTopLevelItems(refsItems);
510 // restore the last selection or, for new insets, highlight
511 // the previous selection
512 if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
513 bool const newInset = oldSelection.isEmpty();
514 QString textToFind = newInset ? last_reference_ : oldSelection;
515 referenceED->setText(textToFind);
516 last_reference_.clear();
517 QTreeWidgetItemIterator it(refsTW);
519 if ((*it)->text(0) == textToFind) {
520 refsTW->setCurrentItem(*it);
521 (*it)->setSelected(true);
522 //Make sure selected item is visible
523 refsTW->scrollToItem(*it);
524 last_reference_ = textToFind;
530 refsTW->setUpdatesEnabled(true);
536 // Re-activate the emission of signals by these widgets.
537 refsTW->blockSignals(false);
538 referenceED->blockSignals(false);
540 gotoPB->setEnabled(!referenceED->text().isEmpty());
541 typeCO->setEnabled(!referenceED->text().isEmpty());
542 typeLA->setEnabled(!referenceED->text().isEmpty());
546 void GuiRef::updateRefs()
549 int const the_buffer = bufferCO->currentIndex();
550 if (the_buffer != -1) {
551 FileNameList const names(theBufferList().fileNames());
552 FileName const & name = names[the_buffer];
553 Buffer const * buf = theBufferList().getBuffer(name);
554 buf->getLabelList(refs_);
556 sortingCO->setEnabled(!refs_.empty());
557 refsTW->setEnabled(!refs_.empty());
558 groupCB->setEnabled(!refs_.empty());
563 bool GuiRef::isValid()
565 return !referenceED->text().isEmpty();
569 void GuiRef::gotoRef(string const & ref)
571 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
572 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
576 void GuiRef::gotoBookmark()
578 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
582 void GuiRef::filterLabels()
584 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
585 Qt::CaseSensitive : Qt::CaseInsensitive;
586 QTreeWidgetItemIterator it(refsTW);
589 (*it)->childCount() == 0
590 && !(*it)->text(0).contains(filter_->text(), cs)
597 void GuiRef::resetFilter()
599 filter_->setText(QString());
604 bool GuiRef::initialiseParams(std::string const & sdata)
606 InsetCommand::string2params(sdata, params_);
611 void GuiRef::dispatchParams()
613 std::string const lfun = InsetCommand::params2string(params_);
614 dispatch(FuncRequest(getLfun(), lfun));
619 } // namespace frontend
622 #include "moc_GuiRef.cpp"