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 bool const isFormatted =
149 (InsetRef::getName(typeCO->currentIndex()) == "formatted");
150 LYXERR0(InsetRef::getName(typeCO->currentIndex()));
151 bool const isLabelOnly =
152 (InsetRef::getName(typeCO->currentIndex()) == "labelonly");
153 bool const usingRefStyle = buffer().params().use_refstyle;
154 LYXERR0(usingRefStyle);
155 pluralCB->setEnabled(isFormatted && usingRefStyle);
156 capsCB->setEnabled(isFormatted && usingRefStyle);
157 noprefixCB->setEnabled(isLabelOnly);
161 void GuiRef::changed_adaptor()
168 void GuiRef::gotoClicked()
170 // By setting last_reference_, we ensure that the reference
171 // to which we are going (or from which we are returning) is
172 // restored in the dialog. It's a bit of a hack, but it works,
173 // and no-one seems to have any better idea.
175 last_reference_.isEmpty() || last_reference_.isNull();
177 last_reference_ = referenceED->text();
180 last_reference_.clear();
184 void GuiRef::selectionChanged()
186 if (isBufferReadonly())
189 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
190 if (selections.isEmpty())
192 QTreeWidgetItem * sel = selections.first();
198 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
200 if (sel->childCount() > 0) {
201 sel->setExpanded(true);
205 /* int const cur_item = refsTW->currentRow();
206 bool const cur_item_selected = cur_item >= 0 ?
207 refsLB->isSelected(cur_item) : false;*/
208 bool const cur_item_selected = refsTW->isItemSelected(sel);
210 if (cur_item_selected)
211 referenceED->setText(sel->text(0));
215 gotoPB->setEnabled(true);
216 if (typeAllowed() && !isBufferReadonly())
217 typeCO->setEnabled(true);
218 nameED->setHidden(!nameAllowed());
219 nameL->setHidden(!nameAllowed());
223 void GuiRef::refTextChanged(QString const & str)
225 gotoPB->setEnabled(!str.isEmpty());
226 typeCO->setEnabled(!str.isEmpty());
227 typeLA->setEnabled(!str.isEmpty());
231 void GuiRef::refSelected(QTreeWidgetItem * sel)
233 if (isBufferReadonly())
236 if (sel->childCount()) {
237 sel->setExpanded(false);
241 /* int const cur_item = refsTW->currentRow();
242 bool const cur_item_selected = cur_item >= 0 ?
243 refsLB->isSelected(cur_item) : false;*/
244 bool const cur_item_selected = refsTW->isItemSelected(sel);
246 if (cur_item_selected)
247 referenceED->setText(sel->text(0));
248 // <enter> or double click, inserts ref and closes dialog
253 void GuiRef::sortToggled()
259 void GuiRef::groupToggled()
265 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
267 switch (buttonBox->standardButton(button)) {
268 case QDialogButtonBox::Ok:
271 case QDialogButtonBox::Apply:
274 case QDialogButtonBox::Cancel:
278 case QDialogButtonBox::Reset:
287 void GuiRef::updateClicked()
293 void GuiRef::dialogRejected()
296 // We have to do this manually, instead of calling slotClose(), because
297 // the dialog has already been made invisible before rejected() triggers.
298 Dialog::disconnect();
302 void GuiRef::resetDialog()
309 void GuiRef::closeEvent(QCloseEvent * e)
317 void GuiRef::updateContents()
319 QString const orig_type =
320 typeCO->itemData(typeCO->currentIndex()).toString();
322 referenceED->clear();
326 // FIXME Bring InsetMathRef on par with InsetRef
328 typeCO->addItem(qt_("<reference>"), "ref");
329 typeCO->addItem(qt_("(<reference>)"), "eqref");
330 typeCO->addItem(qt_("<page>"), "pageref");
331 typeCO->addItem(qt_("on page <page>"), "vpageref");
332 typeCO->addItem(qt_("<reference> on page <page>"), "vref");
333 typeCO->addItem(qt_("Textual reference"), "nameref");
334 if (bufferview()->cursor().inTexted()) {
335 typeCO->addItem(qt_("Formatted reference"), "formatted");
336 typeCO->addItem(qt_("Label only"), "labelonly");
338 typeCO->addItem(qt_("Formatted reference"), "prettyref");
340 referenceED->setText(toqstr(params_["reference"]));
341 nameED->setText(toqstr(params_["name"]));
342 nameED->setHidden(!nameAllowed());
343 nameL->setHidden(!nameAllowed());
345 // restore type settings for new insets
346 bool const new_inset = params_["reference"].empty();
348 int index = typeCO->findData(orig_type);
351 typeCO->setCurrentIndex(index);
354 typeCO->setCurrentIndex(
355 typeCO->findData(toqstr(params_.getCmdName())));
356 typeCO->setEnabled(typeAllowed() && !isBufferReadonly());
358 typeCO->setCurrentIndex(0);
360 pluralCB->setChecked(params_["plural"] == "true");
361 capsCB->setChecked(params_["caps"] == "true");
362 noprefixCB->setChecked(params_["noprefix"] == "true");
364 // insert buffer list
366 FileNameList const buffers(theBufferList().fileNames());
367 for (FileNameList::const_iterator it = buffers.begin();
368 it != buffers.end(); ++it) {
369 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
372 int const thebuffer = theBufferList().bufferNum(buffer().fileName());
373 // restore the buffer combo setting for new insets
374 if (new_inset && restored_buffer_ != -1
375 && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
376 bufferCO->setCurrentIndex(restored_buffer_);
378 int const num = theBufferList().bufferNum(buffer().fileName());
379 bufferCO->setCurrentIndex(num);
380 if (thebuffer != active_buffer_)
381 restored_buffer_ = num;
383 active_buffer_ = thebuffer;
387 // Activate OK/Apply buttons if the users inserts a new ref
388 // and we have a valid pre-setting.
389 bc().setValid(isValid() && new_inset);
393 void GuiRef::applyView()
395 last_reference_ = referenceED->text();
397 params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
398 params_["reference"] = qstring_to_ucs4(last_reference_);
399 params_["name"] = qstring_to_ucs4(nameED->text());
400 params_["plural"] = pluralCB->isChecked() ?
401 from_ascii("true") : from_ascii("false");
402 params_["caps"] = capsCB->isChecked() ?
403 from_ascii("true") : from_ascii("false");
404 params_["noprefix"] = noprefixCB->isChecked() ?
405 from_ascii("true") : from_ascii("false");
406 restored_buffer_ = bufferCO->currentIndex();
410 bool GuiRef::nameAllowed()
412 KernelDocType const doc_type = docType();
413 return doc_type != LATEX && doc_type != LITERATE;
417 bool GuiRef::typeAllowed()
419 return docType() != DOCBOOK;
423 void GuiRef::setGoBack()
425 gotoPB->setText(qt_("&Go Back"));
426 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
430 void GuiRef::setGotoRef()
432 gotoPB->setText(qt_("&Go to Label"));
433 gotoPB->setToolTip(qt_("Jump to the selected label"));
437 void GuiRef::gotoRef()
439 string ref = fromqstr(referenceED->text());
453 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
455 return s1.toLower() < s2.toLower();
459 void GuiRef::redoRefs()
461 // Prevent these widgets from emitting any signals whilst
462 // we modify their state.
463 refsTW->blockSignals(true);
464 referenceED->blockSignals(true);
465 refsTW->setUpdatesEnabled(false);
469 // need this because Qt will send a highlight() here for
470 // the first item inserted
471 QString const oldSelection(referenceED->text());
473 QStringList refsStrings;
474 QStringList refsCategories;
475 vector<docstring>::const_iterator iter;
476 bool noprefix = false;
477 for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
478 QString const lab = toqstr(*iter);
479 refsStrings.append(lab);
480 if (groupCB->isChecked()) {
481 if (lab.contains(":")) {
482 QString const pref = lab.split(':')[0];
483 if (!refsCategories.contains(pref)) {
485 refsCategories.append(pref);
494 // sort categories case-intensively
495 qSort(refsCategories.begin(), refsCategories.end(),
496 caseInsensitiveLessThan /*defined above*/);
498 refsCategories.insert(0, qt_("<No prefix>"));
500 QString const sort = sortingCO->isEnabled() ?
501 sortingCO->itemData(sortingCO->currentIndex()).toString()
503 if (sort == "nocase")
504 qSort(refsStrings.begin(), refsStrings.end(),
505 caseInsensitiveLessThan /*defined above*/);
506 else if (sort == "case")
507 qSort(refsStrings.begin(), refsStrings.end());
509 if (groupCB->isChecked()) {
510 QList<QTreeWidgetItem *> refsCats;
511 for (int i = 0; i < refsCategories.size(); ++i) {
512 QString const cat = refsCategories.at(i);
513 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
514 item->setText(0, cat);
515 for (int j = 0; j < refsStrings.size(); ++j) {
516 QString const ref = refsStrings.at(j);
517 if ((ref.startsWith(cat + QString(":")))
518 || (cat == qt_("<No prefix>")
519 && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
520 QTreeWidgetItem * child =
521 new QTreeWidgetItem(item);
522 child->setText(0, ref);
523 item->addChild(child);
526 refsCats.append(item);
528 refsTW->addTopLevelItems(refsCats);
530 QList<QTreeWidgetItem *> refsItems;
531 for (int i = 0; i < refsStrings.size(); ++i) {
532 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
533 item->setText(0, refsStrings.at(i));
534 refsItems.append(item);
536 refsTW->addTopLevelItems(refsItems);
539 // restore the last selection or, for new insets, highlight
540 // the previous selection
541 if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
542 bool const newInset = oldSelection.isEmpty();
543 QString textToFind = newInset ? last_reference_ : oldSelection;
544 referenceED->setText(textToFind);
545 last_reference_.clear();
546 QTreeWidgetItemIterator it(refsTW);
548 if ((*it)->text(0) == textToFind) {
549 refsTW->setCurrentItem(*it);
550 refsTW->setItemSelected(*it, true);
551 //Make sure selected item is visible
552 refsTW->scrollToItem(*it);
553 last_reference_ = textToFind;
559 refsTW->setUpdatesEnabled(true);
565 // Re-activate the emission of signals by these widgets.
566 refsTW->blockSignals(false);
567 referenceED->blockSignals(false);
569 gotoPB->setEnabled(!referenceED->text().isEmpty());
570 typeCO->setEnabled(!referenceED->text().isEmpty());
571 typeLA->setEnabled(!referenceED->text().isEmpty());
575 void GuiRef::updateRefs()
578 int const the_buffer = bufferCO->currentIndex();
579 if (the_buffer != -1) {
580 FileNameList const names(theBufferList().fileNames());
581 FileName const & name = names[the_buffer];
582 Buffer const * buf = theBufferList().getBuffer(name);
583 buf->getLabelList(refs_);
585 sortingCO->setEnabled(!refs_.empty());
586 refsTW->setEnabled(!refs_.empty());
587 groupCB->setEnabled(!refs_.empty());
592 bool GuiRef::isValid()
594 return !referenceED->text().isEmpty();
598 void GuiRef::gotoRef(string const & ref)
600 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
601 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
605 void GuiRef::gotoBookmark()
607 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
611 void GuiRef::filterLabels()
613 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
614 Qt::CaseSensitive : Qt::CaseInsensitive;
615 QTreeWidgetItemIterator it(refsTW);
618 (*it)->childCount() == 0
619 && !(*it)->text(0).contains(filter_->text(), cs)
626 void GuiRef::resetFilter()
628 filter_->setText(QString());
633 bool GuiRef::initialiseParams(std::string const & sdata)
635 InsetCommand::string2params(sdata, params_);
640 void GuiRef::dispatchParams()
642 std::string const lfun = InsetCommand::params2string(params_);
643 dispatch(FuncRequest(getLfun(), lfun));
648 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
651 } // namespace frontend
654 #include "moc_GuiRef.cpp"