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 "FuncRequest.h"
25 #include "qt_helpers.h"
27 #include "insets/InsetRef.h"
29 #include "support/FileName.h"
30 #include "support/FileNameList.h"
31 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
35 #include <QTreeWidget>
36 #include <QTreeWidgetItem>
37 #include <QPushButton>
39 #include <QCloseEvent>
40 #include <QHeaderView>
43 using namespace lyx::support;
48 GuiRef::GuiRef(GuiView & lv)
49 : GuiDialog(lv, "ref", qt_("Cross-reference")),
50 params_(insetCode("ref"))
57 filter_ = new FancyLineEdit(this);
58 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
59 filter_->setButtonVisible(FancyLineEdit::Right, true);
60 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
61 filter_->setAutoHideButton(FancyLineEdit::Right, true);
62 filter_->setPlaceholderText(qt_("All available labels"));
63 filter_->setToolTip(qt_("Enter string to filter the list of available labels"));
64 #if (QT_VERSION < 0x050000)
65 connect(filter_, SIGNAL(downPressed()),
66 refsTW, SLOT(setFocus()));
68 connect(filter_, &FancyLineEdit::downPressed,
69 refsTW, [=](){ focusAndHighlight(refsTW); });
72 filterBarL->addWidget(filter_, 0);
73 findKeysLA->setBuddy(filter_);
75 sortingCO->addItem(qt_("By Occurrence"), "unsorted");
76 sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
77 sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
79 buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
80 buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
82 refsTW->setColumnCount(1);
83 refsTW->header()->setVisible(false);
85 connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
87 connect(typeCO, SIGNAL(activated(int)),
88 this, SLOT(changed_adaptor()));
89 connect(referenceED, SIGNAL(textChanged(QString)),
90 this, SLOT(refTextChanged(QString)));
91 connect(referenceED, SIGNAL(textChanged(QString)),
92 this, SLOT(changed_adaptor()));
93 connect(filter_, SIGNAL(textEdited(QString)),
94 this, SLOT(filterLabels()));
95 connect(filter_, SIGNAL(rightButtonClicked()),
96 this, SLOT(resetFilter()));
97 connect(csFindCB, SIGNAL(clicked()),
98 this, SLOT(filterLabels()));
99 connect(nameED, SIGNAL(textChanged(QString)),
100 this, SLOT(changed_adaptor()));
101 connect(refsTW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
102 this, SLOT(refHighlighted(QTreeWidgetItem *)));
103 connect(refsTW, SIGNAL(itemSelectionChanged()),
104 this, SLOT(selectionChanged()));
105 connect(refsTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
106 this, SLOT(refSelected(QTreeWidgetItem *)));
107 connect(sortingCO, SIGNAL(activated(int)),
108 this, SLOT(sortToggled()));
109 connect(groupCB, SIGNAL(clicked()),
110 this, SLOT(groupToggled()));
111 connect(gotoPB, SIGNAL(clicked()),
112 this, SLOT(gotoClicked()));
113 connect(bufferCO, SIGNAL(activated(int)),
114 this, SLOT(updateClicked()));
115 connect(pluralCB, SIGNAL(clicked()),
116 this, SLOT(changed_adaptor()));
117 connect(capsCB, SIGNAL(clicked()),
118 this, SLOT(changed_adaptor()));
119 connect(noprefixCB, SIGNAL(clicked()),
120 this, SLOT(changed_adaptor()));
124 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
125 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
126 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
127 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
128 bc().addReadOnly(typeCO);
130 restored_buffer_ = -1;
133 setFocusProxy(filter_);
137 void GuiRef::enableView(bool enable)
140 // In the opposite case, updateContents() will be called anyway.
142 GuiDialog::enableView(enable);
146 void GuiRef::enableBoxes()
148 QString const reftype =
149 typeCO->itemData(typeCO->currentIndex()).toString();
150 bool const isFormatted = (reftype == "formatted");
151 bool const isLabelOnly = (reftype == "labelonly");
152 bool const usingRefStyle = buffer().params().use_refstyle;
153 pluralCB->setEnabled(isFormatted && usingRefStyle);
154 capsCB->setEnabled(isFormatted && usingRefStyle);
155 noprefixCB->setEnabled(isLabelOnly);
159 void GuiRef::changed_adaptor()
166 void GuiRef::gotoClicked()
168 // By setting last_reference_, we ensure that the reference
169 // to which we are going (or from which we are returning) is
170 // restored in the dialog. It's a bit of a hack, but it works,
171 // and no-one seems to have any better idea.
173 last_reference_.isEmpty() || last_reference_.isNull();
175 last_reference_ = referenceED->text();
178 last_reference_.clear();
182 void GuiRef::selectionChanged()
184 if (isBufferReadonly())
187 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
188 if (selections.isEmpty())
190 QTreeWidgetItem * sel = selections.first();
196 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
198 if (sel->childCount() > 0) {
199 sel->setExpanded(true);
203 /* int const cur_item = refsTW->currentRow();
204 bool const cur_item_selected = cur_item >= 0 ?
205 refsLB->isSelected(cur_item) : false;*/
206 bool const cur_item_selected = refsTW->isItemSelected(sel);
208 if (cur_item_selected)
209 referenceED->setText(sel->text(0));
213 gotoPB->setEnabled(true);
214 if (typeAllowed() && !isBufferReadonly())
215 typeCO->setEnabled(true);
216 nameED->setHidden(!nameAllowed());
217 nameL->setHidden(!nameAllowed());
221 void GuiRef::refTextChanged(QString const & str)
223 gotoPB->setEnabled(!str.isEmpty());
224 typeCO->setEnabled(!str.isEmpty());
225 typeLA->setEnabled(!str.isEmpty());
229 void GuiRef::refSelected(QTreeWidgetItem * sel)
231 if (isBufferReadonly())
234 if (sel->childCount()) {
235 sel->setExpanded(false);
239 /* int const cur_item = refsTW->currentRow();
240 bool const cur_item_selected = cur_item >= 0 ?
241 refsLB->isSelected(cur_item) : false;*/
242 bool const cur_item_selected = refsTW->isItemSelected(sel);
244 if (cur_item_selected)
245 referenceED->setText(sel->text(0));
246 // <enter> or double click, inserts ref and closes dialog
251 void GuiRef::sortToggled()
257 void GuiRef::groupToggled()
263 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
265 switch (buttonBox->standardButton(button)) {
266 case QDialogButtonBox::Ok:
269 case QDialogButtonBox::Apply:
272 case QDialogButtonBox::Cancel:
276 case QDialogButtonBox::Reset:
285 void GuiRef::updateClicked()
291 void GuiRef::dialogRejected()
294 // We have to do this manually, instead of calling slotClose(), because
295 // the dialog has already been made invisible before rejected() triggers.
296 Dialog::disconnect();
300 void GuiRef::resetDialog()
307 void GuiRef::closeEvent(QCloseEvent * e)
315 void GuiRef::updateContents()
317 QString const orig_type =
318 typeCO->itemData(typeCO->currentIndex()).toString();
320 referenceED->clear();
324 // FIXME Bring InsetMathRef on par with InsetRef
326 typeCO->addItem(qt_("<reference>"), "ref");
327 typeCO->addItem(qt_("(<reference>)"), "eqref");
328 typeCO->addItem(qt_("<page>"), "pageref");
329 typeCO->addItem(qt_("on page <page>"), "vpageref");
330 typeCO->addItem(qt_("<reference> on page <page>"), "vref");
331 typeCO->addItem(qt_("Textual reference"), "nameref");
332 if (bufferview()->cursor().inTexted()) {
333 typeCO->addItem(qt_("Formatted reference"), "formatted");
334 typeCO->addItem(qt_("Label only"), "labelonly");
336 typeCO->addItem(qt_("Formatted reference"), "prettyref");
338 referenceED->setText(toqstr(params_["reference"]));
339 nameED->setText(toqstr(params_["name"]));
340 nameED->setHidden(!nameAllowed());
341 nameL->setHidden(!nameAllowed());
343 // restore type settings for new insets
344 bool const new_inset = params_["reference"].empty();
346 int index = typeCO->findData(orig_type);
349 typeCO->setCurrentIndex(index);
352 typeCO->setCurrentIndex(
353 typeCO->findData(toqstr(params_.getCmdName())));
354 typeCO->setEnabled(typeAllowed() && !isBufferReadonly());
356 typeCO->setCurrentIndex(0);
358 pluralCB->setChecked(params_["plural"] == "true");
359 capsCB->setChecked(params_["caps"] == "true");
360 noprefixCB->setChecked(params_["noprefix"] == "true");
362 // insert buffer list
364 FileNameList const buffers(theBufferList().fileNames());
365 for (FileNameList::const_iterator it = buffers.begin();
366 it != buffers.end(); ++it) {
367 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
370 int const thebuffer = theBufferList().bufferNum(buffer().fileName());
371 // restore the buffer combo setting for new insets
372 if (new_inset && restored_buffer_ != -1
373 && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
374 bufferCO->setCurrentIndex(restored_buffer_);
376 int const num = theBufferList().bufferNum(buffer().fileName());
377 bufferCO->setCurrentIndex(num);
378 if (thebuffer != active_buffer_)
379 restored_buffer_ = num;
381 active_buffer_ = thebuffer;
385 // Activate OK/Apply buttons if the users inserts a new ref
386 // and we have a valid pre-setting.
387 bc().setValid(isValid() && new_inset);
391 void GuiRef::applyView()
393 last_reference_ = referenceED->text();
395 params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
396 params_["reference"] = qstring_to_ucs4(last_reference_);
397 params_["name"] = qstring_to_ucs4(nameED->text());
398 params_["plural"] = pluralCB->isChecked() ?
399 from_ascii("true") : from_ascii("false");
400 params_["caps"] = capsCB->isChecked() ?
401 from_ascii("true") : from_ascii("false");
402 params_["noprefix"] = noprefixCB->isChecked() ?
403 from_ascii("true") : from_ascii("false");
404 restored_buffer_ = bufferCO->currentIndex();
408 bool GuiRef::nameAllowed()
410 KernelDocType const doc_type = docType();
411 return doc_type != LATEX && doc_type != LITERATE;
415 bool GuiRef::typeAllowed()
417 return docType() != DOCBOOK;
421 void GuiRef::setGoBack()
423 gotoPB->setText(qt_("&Go Back"));
424 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
428 void GuiRef::setGotoRef()
430 gotoPB->setText(qt_("&Go to Label"));
431 gotoPB->setToolTip(qt_("Jump to the selected label"));
435 void GuiRef::gotoRef()
437 string ref = fromqstr(referenceED->text());
451 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
453 return s1.toLower() < s2.toLower();
457 void GuiRef::redoRefs()
459 // Prevent these widgets from emitting any signals whilst
460 // we modify their state.
461 refsTW->blockSignals(true);
462 referenceED->blockSignals(true);
463 refsTW->setUpdatesEnabled(false);
467 // need this because Qt will send a highlight() here for
468 // the first item inserted
469 QString const oldSelection(referenceED->text());
471 QStringList refsStrings;
472 QStringList refsCategories;
473 vector<docstring>::const_iterator iter;
474 bool noprefix = false;
475 for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
476 QString const lab = toqstr(*iter);
477 refsStrings.append(lab);
478 if (groupCB->isChecked()) {
479 if (lab.contains(":")) {
480 QString const pref = lab.split(':')[0];
481 if (!refsCategories.contains(pref)) {
483 refsCategories.append(pref);
492 // sort categories case-intensively
493 qSort(refsCategories.begin(), refsCategories.end(),
494 caseInsensitiveLessThan /*defined above*/);
496 refsCategories.insert(0, qt_("<No prefix>"));
498 QString const sort = sortingCO->isEnabled() ?
499 sortingCO->itemData(sortingCO->currentIndex()).toString()
501 if (sort == "nocase")
502 qSort(refsStrings.begin(), refsStrings.end(),
503 caseInsensitiveLessThan /*defined above*/);
504 else if (sort == "case")
505 qSort(refsStrings.begin(), refsStrings.end());
507 if (groupCB->isChecked()) {
508 QList<QTreeWidgetItem *> refsCats;
509 for (int i = 0; i < refsCategories.size(); ++i) {
510 QString const cat = refsCategories.at(i);
511 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
512 item->setText(0, cat);
513 for (int j = 0; j < refsStrings.size(); ++j) {
514 QString const ref = refsStrings.at(j);
515 if ((ref.startsWith(cat + QString(":")))
516 || (cat == qt_("<No prefix>")
517 && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
518 QTreeWidgetItem * child =
519 new QTreeWidgetItem(item);
520 child->setText(0, ref);
521 item->addChild(child);
524 refsCats.append(item);
526 refsTW->addTopLevelItems(refsCats);
528 QList<QTreeWidgetItem *> refsItems;
529 for (int i = 0; i < refsStrings.size(); ++i) {
530 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
531 item->setText(0, refsStrings.at(i));
532 refsItems.append(item);
534 refsTW->addTopLevelItems(refsItems);
537 // restore the last selection or, for new insets, highlight
538 // the previous selection
539 if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
540 bool const newInset = oldSelection.isEmpty();
541 QString textToFind = newInset ? last_reference_ : oldSelection;
542 referenceED->setText(textToFind);
543 last_reference_.clear();
544 QTreeWidgetItemIterator it(refsTW);
546 if ((*it)->text(0) == textToFind) {
547 refsTW->setCurrentItem(*it);
548 (*it)->setSelected(true);
549 //Make sure selected item is visible
550 refsTW->scrollToItem(*it);
551 last_reference_ = textToFind;
557 refsTW->setUpdatesEnabled(true);
563 // Re-activate the emission of signals by these widgets.
564 refsTW->blockSignals(false);
565 referenceED->blockSignals(false);
567 gotoPB->setEnabled(!referenceED->text().isEmpty());
568 typeCO->setEnabled(!referenceED->text().isEmpty());
569 typeLA->setEnabled(!referenceED->text().isEmpty());
573 void GuiRef::updateRefs()
576 int const the_buffer = bufferCO->currentIndex();
577 if (the_buffer != -1) {
578 FileNameList const names(theBufferList().fileNames());
579 FileName const & name = names[the_buffer];
580 Buffer const * buf = theBufferList().getBuffer(name);
581 buf->getLabelList(refs_);
583 sortingCO->setEnabled(!refs_.empty());
584 refsTW->setEnabled(!refs_.empty());
585 groupCB->setEnabled(!refs_.empty());
590 bool GuiRef::isValid()
592 return !referenceED->text().isEmpty();
596 void GuiRef::gotoRef(string const & ref)
598 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
599 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
603 void GuiRef::gotoBookmark()
605 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
609 void GuiRef::filterLabels()
611 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
612 Qt::CaseSensitive : Qt::CaseInsensitive;
613 QTreeWidgetItemIterator it(refsTW);
616 (*it)->childCount() == 0
617 && !(*it)->text(0).contains(filter_->text(), cs)
624 void GuiRef::resetFilter()
626 filter_->setText(QString());
631 bool GuiRef::initialiseParams(std::string const & sdata)
633 InsetCommand::string2params(sdata, params_);
638 void GuiRef::dispatchParams()
640 std::string const lfun = InsetCommand::params2string(params_);
641 dispatch(FuncRequest(getLfun(), lfun));
646 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
649 } // namespace frontend
652 #include "moc_GuiRef.cpp"