]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiRef.cpp
Fix problem caused by re-ordering of menu at 5f6332bf4.
[lyx.git] / src / frontends / qt4 / 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         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);
158 }
159
160
161 void GuiRef::changed_adaptor()
162 {
163         changed();
164         enableBoxes();
165 }
166
167
168 void GuiRef::gotoClicked()
169 {
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.
174         bool const toggled =
175                 last_reference_.isEmpty() || last_reference_.isNull();
176         if (toggled)
177                 last_reference_ = referenceED->text();
178         gotoRef();
179         if (toggled)
180                 last_reference_.clear();
181 }
182
183
184 void GuiRef::selectionChanged()
185 {
186         if (isBufferReadonly())
187                 return;
188
189         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
190         if (selections.isEmpty())
191                 return;
192         QTreeWidgetItem * sel = selections.first();
193         refHighlighted(sel);
194         return;
195 }
196
197
198 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
199 {
200         if (sel->childCount() > 0) {
201                 sel->setExpanded(true);
202                 return;
203         }
204
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);
209
210         if (cur_item_selected)
211                 referenceED->setText(sel->text(0));
212
213         if (at_ref_)
214                 gotoRef();
215         gotoPB->setEnabled(true);
216         if (typeAllowed() && !isBufferReadonly())
217                 typeCO->setEnabled(true);
218         nameED->setHidden(!nameAllowed());
219         nameL->setHidden(!nameAllowed());
220 }
221
222
223 void GuiRef::refTextChanged(QString const & str)
224 {
225         gotoPB->setEnabled(!str.isEmpty());
226         typeCO->setEnabled(!str.isEmpty());
227         typeLA->setEnabled(!str.isEmpty());
228 }
229
230
231 void GuiRef::refSelected(QTreeWidgetItem * sel)
232 {
233         if (isBufferReadonly())
234                 return;
235
236         if (sel->childCount()) {
237                 sel->setExpanded(false);
238                 return;
239         }
240
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);
245
246         if (cur_item_selected)
247                 referenceED->setText(sel->text(0));
248         // <enter> or double click, inserts ref and closes dialog
249         slotOK();
250 }
251
252
253 void GuiRef::sortToggled()
254 {
255         redoRefs();
256 }
257
258
259 void GuiRef::groupToggled()
260 {
261         redoRefs();
262 }
263
264
265 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
266 {
267         switch (buttonBox->standardButton(button)) {
268         case QDialogButtonBox::Ok:
269                 slotOK();
270                 break;
271         case QDialogButtonBox::Apply:
272                 slotApply();
273                 break;
274         case QDialogButtonBox::Cancel:
275                 slotClose();
276                 resetDialog();
277                 break;
278         case QDialogButtonBox::Reset:
279                 updateClicked();
280                 break;
281         default:
282                 break;
283         }
284 }
285
286
287 void GuiRef::updateClicked()
288 {
289         updateRefs();
290 }
291
292
293 void GuiRef::dialogRejected()
294 {
295         resetDialog();
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();
299 }
300
301
302 void GuiRef::resetDialog()
303 {
304         at_ref_ = false;
305         setGotoRef();
306 }
307
308
309 void GuiRef::closeEvent(QCloseEvent * e)
310 {
311         slotClose();
312         resetDialog();
313         e->accept();
314 }
315
316
317 void GuiRef::updateContents()
318 {
319         QString const orig_type =
320                 typeCO->itemData(typeCO->currentIndex()).toString();
321
322         referenceED->clear();
323         nameED->clear();
324         typeCO->clear();
325
326         // FIXME Bring InsetMathRef on par with InsetRef
327         // (see #9798)
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");
337         } else
338                 typeCO->addItem(qt_("Formatted reference"), "prettyref");
339
340         referenceED->setText(toqstr(params_["reference"]));
341         nameED->setText(toqstr(params_["name"]));
342         nameED->setHidden(!nameAllowed());
343         nameL->setHidden(!nameAllowed());
344
345         // restore type settings for new insets
346         bool const new_inset = params_["reference"].empty();
347         if (new_inset) {
348                 int index = typeCO->findData(orig_type);
349                 if (index == -1)
350                         index = 0;
351                 typeCO->setCurrentIndex(index);
352         }
353         else
354                 typeCO->setCurrentIndex(
355                         typeCO->findData(toqstr(params_.getCmdName())));
356         typeCO->setEnabled(typeAllowed() && !isBufferReadonly());
357         if (!typeAllowed())
358                 typeCO->setCurrentIndex(0);
359
360         pluralCB->setChecked(params_["plural"] == "true");
361         capsCB->setChecked(params_["caps"] == "true");
362         noprefixCB->setChecked(params_["noprefix"] == "true");
363
364         // insert buffer list
365         bufferCO->clear();
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())));
370         }
371
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_);
377         else {
378                 int const num = theBufferList().bufferNum(buffer().fileName());
379                 bufferCO->setCurrentIndex(num);
380                 if (thebuffer != active_buffer_)
381                         restored_buffer_ = num;
382         }
383         active_buffer_ = thebuffer;
384
385         updateRefs();
386         enableBoxes();
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);
390 }
391
392
393 void GuiRef::applyView()
394 {
395         last_reference_ = referenceED->text();
396
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();
407 }
408
409
410 bool GuiRef::nameAllowed()
411 {
412         KernelDocType const doc_type = docType();
413         return doc_type != LATEX && doc_type != LITERATE;
414 }
415
416
417 bool GuiRef::typeAllowed()
418 {
419         return docType() != DOCBOOK;
420 }
421
422
423 void GuiRef::setGoBack()
424 {
425         gotoPB->setText(qt_("&Go Back"));
426         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
427 }
428
429
430 void GuiRef::setGotoRef()
431 {
432         gotoPB->setText(qt_("&Go to Label"));
433         gotoPB->setToolTip(qt_("Jump to the selected label"));
434 }
435
436
437 void GuiRef::gotoRef()
438 {
439         string ref = fromqstr(referenceED->text());
440
441         if (at_ref_) {
442                 // go back
443                 setGotoRef();
444                 gotoBookmark();
445         } else {
446                 // go to the ref
447                 setGoBack();
448                 gotoRef(ref);
449         }
450         at_ref_ = !at_ref_;
451 }
452
453 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
454 {
455         return s1.toLower() < s2.toLower();
456 }
457
458
459 void GuiRef::redoRefs()
460 {
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);
466
467         refsTW->clear();
468
469         // need this because Qt will send a highlight() here for
470         // the first item inserted
471         QString const oldSelection(referenceED->text());
472
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)) {
484                                         if (!pref.isEmpty())
485                                                 refsCategories.append(pref);
486                                         else
487                                                 noprefix = true;
488                                 }
489                         }
490                         else
491                                 noprefix = true;
492                 }
493         }
494         // sort categories case-intensively
495         qSort(refsCategories.begin(), refsCategories.end(),
496               caseInsensitiveLessThan /*defined above*/);
497         if (noprefix)
498                 refsCategories.insert(0, qt_("<No prefix>"));
499
500         QString const sort = sortingCO->isEnabled() ?
501                                 sortingCO->itemData(sortingCO->currentIndex()).toString()
502                                 : QString();
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());
508
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);
524                                 }
525                         }
526                         refsCats.append(item);
527                 }
528                 refsTW->addTopLevelItems(refsCats);
529         } else {
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);
535                 }
536                 refsTW->addTopLevelItems(refsItems);
537         }
538
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);
547                 while (*it) {
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;
554                                 break;
555                         }
556                         ++it;
557                 }
558         }
559         refsTW->setUpdatesEnabled(true);
560         refsTW->update();
561
562         // redo filter
563         filterLabels();
564
565         // Re-activate the emission of signals by these widgets.
566         refsTW->blockSignals(false);
567         referenceED->blockSignals(false);
568
569         gotoPB->setEnabled(!referenceED->text().isEmpty());
570         typeCO->setEnabled(!referenceED->text().isEmpty());
571         typeLA->setEnabled(!referenceED->text().isEmpty());
572 }
573
574
575 void GuiRef::updateRefs()
576 {
577         refs_.clear();
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_);
584         }
585         sortingCO->setEnabled(!refs_.empty());
586         refsTW->setEnabled(!refs_.empty());
587         groupCB->setEnabled(!refs_.empty());
588         redoRefs();
589 }
590
591
592 bool GuiRef::isValid()
593 {
594         return !referenceED->text().isEmpty();
595 }
596
597
598 void GuiRef::gotoRef(string const & ref)
599 {
600         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
601         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
602 }
603
604
605 void GuiRef::gotoBookmark()
606 {
607         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
608 }
609
610
611 void GuiRef::filterLabels()
612 {
613         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
614                 Qt::CaseSensitive : Qt::CaseInsensitive;
615         QTreeWidgetItemIterator it(refsTW);
616         while (*it) {
617                 (*it)->setHidden(
618                         (*it)->childCount() == 0
619                         && !(*it)->text(0).contains(filter_->text(), cs)
620                 );
621                 ++it;
622         }
623 }
624
625
626 void GuiRef::resetFilter()
627 {
628         filter_->setText(QString());
629         filterLabels();
630 }
631
632
633 bool GuiRef::initialiseParams(std::string const & sdata)
634 {
635         InsetCommand::string2params(sdata, params_);
636         return true;
637 }
638
639
640 void GuiRef::dispatchParams()
641 {
642         std::string const lfun = InsetCommand::params2string(params_);
643         dispatch(FuncRequest(getLfun(), lfun));
644 }
645
646
647
648 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
649
650
651 } // namespace frontend
652 } // namespace lyx
653
654 #include "moc_GuiRef.cpp"