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_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
60 filter_->setButtonVisible(FancyLineEdit::Right, true);
61 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
62 filter_->setAutoHideButton(FancyLineEdit::Right, true);
63 filter_->setPlaceholderText(qt_("All available labels"));
64 filter_->setToolTip(qt_("Enter string to filter the list of available labels"));
65 #if (QT_VERSION < 0x050000)
66 connect(filter_, SIGNAL(downPressed()),
67 refsTW, SLOT(setFocus()));
69 connect(filter_, &FancyLineEdit::downPressed,
70 refsTW, [=, this](){ focusAndHighlight(refsTW); });
73 filterBarL->addWidget(filter_, 0);
74 findKeysLA->setBuddy(filter_);
76 sortingCO->addItem(qt_("By Occurrence"), "unsorted");
77 sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
78 sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
80 buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
81 buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
83 refsTW->setColumnCount(1);
84 refsTW->header()->setVisible(false);
86 connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
88 connect(typeCO, SIGNAL(activated(int)),
89 this, SLOT(changed_adaptor()));
90 connect(referenceED, SIGNAL(textChanged(QString)),
91 this, SLOT(refTextChanged(QString)));
92 connect(referenceED, SIGNAL(textChanged(QString)),
93 this, SLOT(changed_adaptor()));
94 connect(filter_, SIGNAL(textEdited(QString)),
95 this, SLOT(filterLabels()));
96 connect(filter_, SIGNAL(rightButtonClicked()),
97 this, SLOT(resetFilter()));
98 connect(csFindCB, SIGNAL(clicked()),
99 this, SLOT(filterLabels()));
100 connect(refsTW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
101 this, SLOT(refHighlighted(QTreeWidgetItem *)));
102 connect(refsTW, SIGNAL(itemSelectionChanged()),
103 this, SLOT(selectionChanged()));
104 connect(refsTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
105 this, SLOT(refSelected(QTreeWidgetItem *)));
106 connect(sortingCO, SIGNAL(activated(int)),
107 this, SLOT(sortToggled()));
108 connect(groupCB, SIGNAL(clicked()),
109 this, SLOT(groupToggled()));
110 connect(gotoPB, SIGNAL(clicked()),
111 this, SLOT(gotoClicked()));
112 connect(bufferCO, SIGNAL(activated(int)),
113 this, SLOT(updateClicked()));
114 connect(pluralCB, SIGNAL(clicked()),
115 this, SLOT(changed_adaptor()));
116 connect(capsCB, SIGNAL(clicked()),
117 this, SLOT(changed_adaptor()));
118 connect(noprefixCB, SIGNAL(clicked()),
119 this, SLOT(changed_adaptor()));
123 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
124 bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
125 bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
126 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
127 bc().addReadOnly(typeCO);
129 restored_buffer_ = -1;
132 setFocusProxy(filter_);
136 void GuiRef::enableView(bool enable)
139 // In the opposite case, updateContents() will be called anyway.
141 GuiDialog::enableView(enable);
145 void GuiRef::enableBoxes()
147 QString const reftype =
148 typeCO->itemData(typeCO->currentIndex()).toString();
149 bool const isFormatted = (reftype == "formatted");
150 bool const isLabelOnly = (reftype == "labelonly");
151 bool const usingRefStyle = buffer().params().use_refstyle;
152 pluralCB->setEnabled(isFormatted && usingRefStyle);
153 capsCB->setEnabled(isFormatted && usingRefStyle);
154 noprefixCB->setEnabled(isLabelOnly);
158 void GuiRef::changed_adaptor()
165 void GuiRef::gotoClicked()
167 // By setting last_reference_, we ensure that the reference
168 // to which we are going (or from which we are returning) is
169 // restored in the dialog. It's a bit of a hack, but it works,
170 // and no-one seems to have any better idea.
172 last_reference_.isEmpty() || last_reference_.isNull();
174 last_reference_ = referenceED->text();
177 last_reference_.clear();
181 void GuiRef::selectionChanged()
183 if (isBufferReadonly())
186 QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
187 if (selections.isEmpty())
189 QTreeWidgetItem * sel = selections.first();
194 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
196 if (sel->childCount() > 0) {
197 sel->setExpanded(true);
201 /* int const cur_item = refsTW->currentRow();
202 bool const cur_item_selected = cur_item >= 0 ?
203 refsLB->isSelected(cur_item) : false;*/
204 bool const cur_item_selected = sel->isSelected();
206 if (cur_item_selected)
207 referenceED->setText(sel->text(0));
211 gotoPB->setEnabled(true);
212 if (!isBufferReadonly())
213 typeCO->setEnabled(true);
217 void GuiRef::refTextChanged(QString const & str)
219 gotoPB->setEnabled(!str.isEmpty());
220 typeCO->setEnabled(!str.isEmpty());
221 typeLA->setEnabled(!str.isEmpty());
225 void GuiRef::refSelected(QTreeWidgetItem * sel)
227 if (isBufferReadonly())
230 if (sel->childCount()) {
231 sel->setExpanded(false);
235 /* int const cur_item = refsTW->currentRow();
236 bool const cur_item_selected = cur_item >= 0 ?
237 refsLB->isSelected(cur_item) : false;*/
238 bool const cur_item_selected = sel->isSelected();
240 if (cur_item_selected)
241 referenceED->setText(sel->text(0));
242 // <enter> or double click, inserts ref and closes dialog
247 void GuiRef::sortToggled()
253 void GuiRef::groupToggled()
259 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
261 switch (buttonBox->standardButton(button)) {
262 case QDialogButtonBox::Ok:
265 case QDialogButtonBox::Apply:
268 case QDialogButtonBox::Cancel:
272 case QDialogButtonBox::Reset:
281 void GuiRef::updateClicked()
287 void GuiRef::dialogRejected()
290 // We have to do this manually, instead of calling slotClose(), because
291 // the dialog has already been made invisible before rejected() triggers.
292 Dialog::disconnect();
296 void GuiRef::resetDialog()
303 void GuiRef::closeEvent(QCloseEvent * e)
311 void GuiRef::updateContents()
313 QString const orig_type =
314 typeCO->itemData(typeCO->currentIndex()).toString();
316 referenceED->clear();
319 // FIXME Bring InsetMathRef on par with InsetRef
321 typeCO->addItem(qt_("<reference>"), "ref");
322 typeCO->addItem(qt_("(<reference>)"), "eqref");
323 typeCO->addItem(qt_("<page>"), "pageref");
324 typeCO->addItem(qt_("on page <page>"), "vpageref");
325 typeCO->addItem(qt_("<reference> on page <page>"), "vref");
326 typeCO->addItem(qt_("Textual reference"), "nameref");
327 if (bufferview()->cursor().inTexted()) {
328 typeCO->addItem(qt_("Formatted reference"), "formatted");
329 typeCO->addItem(qt_("Label only"), "labelonly");
331 typeCO->addItem(qt_("Formatted reference"), "prettyref");
333 referenceED->setText(toqstr(params_["reference"]));
335 // restore type settings for new insets
336 bool const new_inset = params_["reference"].empty();
338 int index = typeCO->findData(orig_type);
341 typeCO->setCurrentIndex(index);
344 typeCO->setCurrentIndex(
345 typeCO->findData(toqstr(params_.getCmdName())));
346 typeCO->setEnabled(!isBufferReadonly());
348 pluralCB->setChecked(params_["plural"] == "true");
349 capsCB->setChecked(params_["caps"] == "true");
350 noprefixCB->setChecked(params_["noprefix"] == "true");
352 // insert buffer list
354 FileNameList const buffers(theBufferList().fileNames());
355 for (FileNameList::const_iterator it = buffers.begin();
356 it != buffers.end(); ++it) {
357 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
360 int const thebuffer = theBufferList().bufferNum(buffer().fileName());
361 // restore the buffer combo setting for new insets
362 if (new_inset && restored_buffer_ != -1
363 && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
364 bufferCO->setCurrentIndex(restored_buffer_);
366 int const num = theBufferList().bufferNum(buffer().fileName());
367 bufferCO->setCurrentIndex(num);
368 if (thebuffer != active_buffer_)
369 restored_buffer_ = num;
371 active_buffer_ = thebuffer;
375 // Activate OK/Apply buttons if the users inserts a new ref
376 // and we have a valid pre-setting.
377 bc().setValid(isValid() && new_inset);
381 void GuiRef::applyView()
383 last_reference_ = referenceED->text();
385 params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
386 params_["reference"] = qstring_to_ucs4(last_reference_);
387 params_["plural"] = pluralCB->isChecked() ?
388 from_ascii("true") : from_ascii("false");
389 params_["caps"] = capsCB->isChecked() ?
390 from_ascii("true") : from_ascii("false");
391 params_["noprefix"] = noprefixCB->isChecked() ?
392 from_ascii("true") : from_ascii("false");
393 restored_buffer_ = bufferCO->currentIndex();
397 void GuiRef::setGoBack()
399 gotoPB->setText(qt_("&Go Back"));
400 gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
404 void GuiRef::setGotoRef()
406 gotoPB->setText(qt_("&Go to Label"));
407 gotoPB->setToolTip(qt_("Jump to the selected label"));
411 void GuiRef::gotoRef()
413 string ref = fromqstr(referenceED->text());
427 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
429 return s1.toLower() < s2.toLower();
433 void GuiRef::redoRefs()
435 // Prevent these widgets from emitting any signals whilst
436 // we modify their state.
437 refsTW->blockSignals(true);
438 referenceED->blockSignals(true);
439 refsTW->setUpdatesEnabled(false);
443 // need this because Qt will send a highlight() here for
444 // the first item inserted
445 QString const oldSelection(referenceED->text());
447 QStringList refsStrings;
448 QStringList refsCategories;
449 vector<docstring>::const_iterator iter;
450 bool noprefix = false;
451 for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
452 QString const lab = toqstr(*iter);
453 refsStrings.append(lab);
454 if (groupCB->isChecked()) {
455 if (lab.contains(":")) {
456 QString const pref = lab.split(':')[0];
457 if (!refsCategories.contains(pref)) {
459 refsCategories.append(pref);
468 // sort categories case-intensively
469 sort(refsCategories.begin(), refsCategories.end(),
470 caseInsensitiveLessThan /*defined above*/);
472 refsCategories.insert(0, qt_("<No prefix>"));
474 QString const sort_method = sortingCO->isEnabled() ?
475 sortingCO->itemData(sortingCO->currentIndex()).toString()
477 if (sort_method == "nocase")
478 sort(refsStrings.begin(), refsStrings.end(),
479 caseInsensitiveLessThan /*defined above*/);
480 else if (sort_method == "case")
481 sort(refsStrings.begin(), refsStrings.end());
483 if (groupCB->isChecked()) {
484 QList<QTreeWidgetItem *> refsCats;
485 for (int i = 0; i < refsCategories.size(); ++i) {
486 QString const & cat = refsCategories.at(i);
487 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
488 item->setText(0, cat);
489 for (int j = 0; j < refsStrings.size(); ++j) {
490 QString const & ref = refsStrings.at(j);
491 if ((ref.startsWith(cat + QString(":")))
492 || (cat == qt_("<No prefix>")
493 && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
494 QTreeWidgetItem * child =
495 new QTreeWidgetItem(item);
496 child->setText(0, ref);
497 item->addChild(child);
500 refsCats.append(item);
502 refsTW->addTopLevelItems(refsCats);
504 QList<QTreeWidgetItem *> refsItems;
505 for (int i = 0; i < refsStrings.size(); ++i) {
506 QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
507 item->setText(0, refsStrings.at(i));
508 refsItems.append(item);
510 refsTW->addTopLevelItems(refsItems);
513 // restore the last selection or, for new insets, highlight
514 // the previous selection
515 if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
516 bool const newInset = oldSelection.isEmpty();
517 QString textToFind = newInset ? last_reference_ : oldSelection;
518 referenceED->setText(textToFind);
519 last_reference_.clear();
520 QTreeWidgetItemIterator it(refsTW);
522 if ((*it)->text(0) == textToFind) {
523 refsTW->setCurrentItem(*it);
524 (*it)->setSelected(true);
525 //Make sure selected item is visible
526 refsTW->scrollToItem(*it);
527 last_reference_ = textToFind;
533 refsTW->setUpdatesEnabled(true);
539 // Re-activate the emission of signals by these widgets.
540 refsTW->blockSignals(false);
541 referenceED->blockSignals(false);
543 gotoPB->setEnabled(!referenceED->text().isEmpty());
544 typeCO->setEnabled(!referenceED->text().isEmpty());
545 typeLA->setEnabled(!referenceED->text().isEmpty());
549 void GuiRef::updateRefs()
552 int const the_buffer = bufferCO->currentIndex();
553 if (the_buffer != -1) {
554 FileNameList const names(theBufferList().fileNames());
555 FileName const & name = names[the_buffer];
556 Buffer const * buf = theBufferList().getBuffer(name);
557 buf->getLabelList(refs_);
559 sortingCO->setEnabled(!refs_.empty());
560 refsTW->setEnabled(!refs_.empty());
561 groupCB->setEnabled(!refs_.empty());
566 bool GuiRef::isValid()
568 return !referenceED->text().isEmpty();
572 void GuiRef::gotoRef(string const & ref)
574 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
575 dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
579 void GuiRef::gotoBookmark()
581 dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
585 void GuiRef::filterLabels()
587 Qt::CaseSensitivity cs = csFindCB->isChecked() ?
588 Qt::CaseSensitive : Qt::CaseInsensitive;
589 QTreeWidgetItemIterator it(refsTW);
592 (*it)->childCount() == 0
593 && !(*it)->text(0).contains(filter_->text(), cs)
600 void GuiRef::resetFilter()
602 filter_->setText(QString());
607 bool GuiRef::initialiseParams(std::string const & sdata)
609 InsetCommand::string2params(sdata, params_);
614 void GuiRef::dispatchParams()
616 std::string const lfun = InsetCommand::params2string(params_);
617 dispatch(FuncRequest(getLfun(), lfun));
621 } // namespace frontend
624 #include "moc_GuiRef.cpp"