]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiRef.cpp
Remove GuiRef::typeAllowed, as it is now always allowed.
[lyx.git] / src / frontends / qt / GuiRef.cpp
1 /**
2  * \file GuiRef.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiRef.h"
15
16 #include "GuiApplication.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferList.h"
21 #include "BufferView.h"
22 #include "Cursor.h"
23 #include "FuncRequest.h"
24
25 #include "qt_helpers.h"
26
27 #include "insets/InsetRef.h"
28
29 #include "support/FileName.h"
30 #include "support/FileNameList.h"
31 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
32
33 #include <QLineEdit>
34 #include <QCheckBox>
35 #include <QTreeWidget>
36 #include <QTreeWidgetItem>
37 #include <QPushButton>
38 #include <QToolTip>
39 #include <QCloseEvent>
40 #include <QHeaderView>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46 namespace frontend {
47
48 GuiRef::GuiRef(GuiView & lv)
49         : GuiDialog(lv, "ref", qt_("Cross-reference")),
50           params_(insetCode("ref"))
51 {
52         setupUi(this);
53
54         at_ref_ = false;
55
56         // The filter bar
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()));
67 #else
68         connect(filter_, &FancyLineEdit::downPressed,
69                 refsTW, [=](){ focusAndHighlight(refsTW); });
70 #endif
71
72         filterBarL->addWidget(filter_, 0);
73         findKeysLA->setBuddy(filter_);
74
75         sortingCO->addItem(qt_("By Occurrence"), "unsorted");
76         sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
77         sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
78
79         buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
80         buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
81
82         refsTW->setColumnCount(1);
83         refsTW->header()->setVisible(false);
84
85         connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
86
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()));
121
122         enableBoxes();
123
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);
129
130         restored_buffer_ = -1;
131         active_buffer_ = -1;
132
133         setFocusProxy(filter_);
134 }
135
136
137 void GuiRef::enableView(bool enable)
138 {
139         if (!enable)
140                 // In the opposite case, updateContents() will be called anyway.
141                 updateContents();
142         GuiDialog::enableView(enable);
143 }
144
145
146 void GuiRef::enableBoxes()
147 {
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);
156 }
157
158
159 void GuiRef::changed_adaptor()
160 {
161         changed();
162         enableBoxes();
163 }
164
165
166 void GuiRef::gotoClicked()
167 {
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.
172         bool const toggled =
173                 last_reference_.isEmpty() || last_reference_.isNull();
174         if (toggled)
175                 last_reference_ = referenceED->text();
176         gotoRef();
177         if (toggled)
178                 last_reference_.clear();
179 }
180
181
182 void GuiRef::selectionChanged()
183 {
184         if (isBufferReadonly())
185                 return;
186
187         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
188         if (selections.isEmpty())
189                 return;
190         QTreeWidgetItem * sel = selections.first();
191         refHighlighted(sel);
192         return;
193 }
194
195
196 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
197 {
198         if (sel->childCount() > 0) {
199                 sel->setExpanded(true);
200                 return;
201         }
202
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 = sel->isSelected();
207
208         if (cur_item_selected)
209                 referenceED->setText(sel->text(0));
210
211         if (at_ref_)
212                 gotoRef();
213         gotoPB->setEnabled(true);
214         if (!isBufferReadonly())
215                 typeCO->setEnabled(true);
216         nameED->setHidden(!nameAllowed());
217         nameL->setHidden(!nameAllowed());
218 }
219
220
221 void GuiRef::refTextChanged(QString const & str)
222 {
223         gotoPB->setEnabled(!str.isEmpty());
224         typeCO->setEnabled(!str.isEmpty());
225         typeLA->setEnabled(!str.isEmpty());
226 }
227
228
229 void GuiRef::refSelected(QTreeWidgetItem * sel)
230 {
231         if (isBufferReadonly())
232                 return;
233
234         if (sel->childCount()) {
235                 sel->setExpanded(false);
236                 return;
237         }
238
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 = sel->isSelected();
243
244         if (cur_item_selected)
245                 referenceED->setText(sel->text(0));
246         // <enter> or double click, inserts ref and closes dialog
247         slotOK();
248 }
249
250
251 void GuiRef::sortToggled()
252 {
253         redoRefs();
254 }
255
256
257 void GuiRef::groupToggled()
258 {
259         redoRefs();
260 }
261
262
263 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
264 {
265         switch (buttonBox->standardButton(button)) {
266         case QDialogButtonBox::Ok:
267                 slotOK();
268                 break;
269         case QDialogButtonBox::Apply:
270                 slotApply();
271                 break;
272         case QDialogButtonBox::Cancel:
273                 slotClose();
274                 resetDialog();
275                 break;
276         case QDialogButtonBox::Reset:
277                 updateClicked();
278                 break;
279         default:
280                 break;
281         }
282 }
283
284
285 void GuiRef::updateClicked()
286 {
287         updateRefs();
288 }
289
290
291 void GuiRef::dialogRejected()
292 {
293         resetDialog();
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();
297 }
298
299
300 void GuiRef::resetDialog()
301 {
302         at_ref_ = false;
303         setGotoRef();
304 }
305
306
307 void GuiRef::closeEvent(QCloseEvent * e)
308 {
309         slotClose();
310         resetDialog();
311         e->accept();
312 }
313
314
315 void GuiRef::updateContents()
316 {
317         QString const orig_type =
318                 typeCO->itemData(typeCO->currentIndex()).toString();
319
320         referenceED->clear();
321         nameED->clear();
322         typeCO->clear();
323
324         // FIXME Bring InsetMathRef on par with InsetRef
325         // (see #9798)
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");
335         } else
336                 typeCO->addItem(qt_("Formatted reference"), "prettyref");
337
338         referenceED->setText(toqstr(params_["reference"]));
339         nameED->setText(toqstr(params_["name"]));
340         nameED->setHidden(!nameAllowed());
341         nameL->setHidden(!nameAllowed());
342
343         // restore type settings for new insets
344         bool const new_inset = params_["reference"].empty();
345         if (new_inset) {
346                 int index = typeCO->findData(orig_type);
347                 if (index == -1)
348                         index = 0;
349                 typeCO->setCurrentIndex(index);
350         }
351         else
352                 typeCO->setCurrentIndex(
353                         typeCO->findData(toqstr(params_.getCmdName())));
354         typeCO->setEnabled(!isBufferReadonly());
355
356         pluralCB->setChecked(params_["plural"] == "true");
357         capsCB->setChecked(params_["caps"] == "true");
358         noprefixCB->setChecked(params_["noprefix"] == "true");
359
360         // insert buffer list
361         bufferCO->clear();
362         FileNameList const buffers(theBufferList().fileNames());
363         for (FileNameList::const_iterator it = buffers.begin();
364              it != buffers.end(); ++it) {
365                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
366         }
367
368         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
369         // restore the buffer combo setting for new insets
370         if (new_inset && restored_buffer_ != -1
371             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
372                 bufferCO->setCurrentIndex(restored_buffer_);
373         else {
374                 int const num = theBufferList().bufferNum(buffer().fileName());
375                 bufferCO->setCurrentIndex(num);
376                 if (thebuffer != active_buffer_)
377                         restored_buffer_ = num;
378         }
379         active_buffer_ = thebuffer;
380
381         updateRefs();
382         enableBoxes();
383         // Activate OK/Apply buttons if the users inserts a new ref
384         // and we have a valid pre-setting.
385         bc().setValid(isValid() && new_inset);
386 }
387
388
389 void GuiRef::applyView()
390 {
391         last_reference_ = referenceED->text();
392
393         params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
394         params_["reference"] = qstring_to_ucs4(last_reference_);
395         params_["name"] = qstring_to_ucs4(nameED->text());
396         params_["plural"] = pluralCB->isChecked() ?
397               from_ascii("true") : from_ascii("false");
398         params_["caps"] = capsCB->isChecked() ?
399               from_ascii("true") : from_ascii("false");
400         params_["noprefix"] = noprefixCB->isChecked() ?
401               from_ascii("true") : from_ascii("false");
402         restored_buffer_ = bufferCO->currentIndex();
403 }
404
405
406 bool GuiRef::nameAllowed()
407 {
408         KernelDocType const doc_type = docType();
409         return doc_type != LATEX && doc_type != LITERATE;
410 }
411
412
413 void GuiRef::setGoBack()
414 {
415         gotoPB->setText(qt_("&Go Back"));
416         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
417 }
418
419
420 void GuiRef::setGotoRef()
421 {
422         gotoPB->setText(qt_("&Go to Label"));
423         gotoPB->setToolTip(qt_("Jump to the selected label"));
424 }
425
426
427 void GuiRef::gotoRef()
428 {
429         string ref = fromqstr(referenceED->text());
430
431         if (at_ref_) {
432                 // go back
433                 setGotoRef();
434                 gotoBookmark();
435         } else {
436                 // go to the ref
437                 setGoBack();
438                 gotoRef(ref);
439         }
440         at_ref_ = !at_ref_;
441 }
442
443 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
444 {
445         return s1.toLower() < s2.toLower();
446 }
447
448
449 void GuiRef::redoRefs()
450 {
451         // Prevent these widgets from emitting any signals whilst
452         // we modify their state.
453         refsTW->blockSignals(true);
454         referenceED->blockSignals(true);
455         refsTW->setUpdatesEnabled(false);
456
457         refsTW->clear();
458
459         // need this because Qt will send a highlight() here for
460         // the first item inserted
461         QString const oldSelection(referenceED->text());
462
463         QStringList refsStrings;
464         QStringList refsCategories;
465         vector<docstring>::const_iterator iter;
466         bool noprefix = false;
467         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
468                 QString const lab = toqstr(*iter);
469                 refsStrings.append(lab);
470                 if (groupCB->isChecked()) {
471                         if (lab.contains(":")) {
472                                 QString const pref = lab.split(':')[0];
473                                 if (!refsCategories.contains(pref)) {
474                                         if (!pref.isEmpty())
475                                                 refsCategories.append(pref);
476                                         else
477                                                 noprefix = true;
478                                 }
479                         }
480                         else
481                                 noprefix = true;
482                 }
483         }
484         // sort categories case-intensively
485         sort(refsCategories.begin(), refsCategories.end(),
486                   caseInsensitiveLessThan /*defined above*/);
487         if (noprefix)
488                 refsCategories.insert(0, qt_("<No prefix>"));
489
490         QString const sort_method = sortingCO->isEnabled() ?
491                                         sortingCO->itemData(sortingCO->currentIndex()).toString()
492                                         : QString();
493         if (sort_method == "nocase")
494                 sort(refsStrings.begin(), refsStrings.end(),
495                           caseInsensitiveLessThan /*defined above*/);
496         else if (sort_method == "case")
497                 sort(refsStrings.begin(), refsStrings.end());
498
499         if (groupCB->isChecked()) {
500                 QList<QTreeWidgetItem *> refsCats;
501                 for (int i = 0; i < refsCategories.size(); ++i) {
502                         QString const cat = refsCategories.at(i);
503                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
504                         item->setText(0, cat);
505                         for (int j = 0; j < refsStrings.size(); ++j) {
506                                 QString const ref = refsStrings.at(j);
507                                 if ((ref.startsWith(cat + QString(":")))
508                                     || (cat == qt_("<No prefix>")
509                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
510                                                 QTreeWidgetItem * child =
511                                                         new QTreeWidgetItem(item);
512                                                 child->setText(0, ref);
513                                                 item->addChild(child);
514                                 }
515                         }
516                         refsCats.append(item);
517                 }
518                 refsTW->addTopLevelItems(refsCats);
519         } else {
520                 QList<QTreeWidgetItem *> refsItems;
521                 for (int i = 0; i < refsStrings.size(); ++i) {
522                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
523                         item->setText(0, refsStrings.at(i));
524                         refsItems.append(item);
525                 }
526                 refsTW->addTopLevelItems(refsItems);
527         }
528
529         // restore the last selection or, for new insets, highlight
530         // the previous selection
531         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
532                 bool const newInset = oldSelection.isEmpty();
533                 QString textToFind = newInset ? last_reference_ : oldSelection;
534                 referenceED->setText(textToFind);
535                 last_reference_.clear();
536                 QTreeWidgetItemIterator it(refsTW);
537                 while (*it) {
538                         if ((*it)->text(0) == textToFind) {
539                                 refsTW->setCurrentItem(*it);
540                                 (*it)->setSelected(true);
541                                 //Make sure selected item is visible
542                                 refsTW->scrollToItem(*it);
543                                 last_reference_ = textToFind;
544                                 break;
545                         }
546                         ++it;
547                 }
548         }
549         refsTW->setUpdatesEnabled(true);
550         refsTW->update();
551
552         // redo filter
553         filterLabels();
554
555         // Re-activate the emission of signals by these widgets.
556         refsTW->blockSignals(false);
557         referenceED->blockSignals(false);
558
559         gotoPB->setEnabled(!referenceED->text().isEmpty());
560         typeCO->setEnabled(!referenceED->text().isEmpty());
561         typeLA->setEnabled(!referenceED->text().isEmpty());
562 }
563
564
565 void GuiRef::updateRefs()
566 {
567         refs_.clear();
568         int const the_buffer = bufferCO->currentIndex();
569         if (the_buffer != -1) {
570                 FileNameList const names(theBufferList().fileNames());
571                 FileName const & name = names[the_buffer];
572                 Buffer const * buf = theBufferList().getBuffer(name);
573                 buf->getLabelList(refs_);
574         }
575         sortingCO->setEnabled(!refs_.empty());
576         refsTW->setEnabled(!refs_.empty());
577         groupCB->setEnabled(!refs_.empty());
578         redoRefs();
579 }
580
581
582 bool GuiRef::isValid()
583 {
584         return !referenceED->text().isEmpty();
585 }
586
587
588 void GuiRef::gotoRef(string const & ref)
589 {
590         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
591         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
592 }
593
594
595 void GuiRef::gotoBookmark()
596 {
597         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
598 }
599
600
601 void GuiRef::filterLabels()
602 {
603         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
604                 Qt::CaseSensitive : Qt::CaseInsensitive;
605         QTreeWidgetItemIterator it(refsTW);
606         while (*it) {
607                 (*it)->setHidden(
608                         (*it)->childCount() == 0
609                         && !(*it)->text(0).contains(filter_->text(), cs)
610                 );
611                 ++it;
612         }
613 }
614
615
616 void GuiRef::resetFilter()
617 {
618         filter_->setText(QString());
619         filterLabels();
620 }
621
622
623 bool GuiRef::initialiseParams(std::string const & sdata)
624 {
625         InsetCommand::string2params(sdata, params_);
626         return true;
627 }
628
629
630 void GuiRef::dispatchParams()
631 {
632         std::string const lfun = InsetCommand::params2string(params_);
633         dispatch(FuncRequest(getLfun(), lfun));
634 }
635
636
637
638 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
639
640
641 } // namespace frontend
642 } // namespace lyx
643
644 #include "moc_GuiRef.cpp"