]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiRef.cpp
Guard against possible referencing null.
[features.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 "FancyLineEdit.h"
24 #include "FuncRequest.h"
25
26 #include "qt_helpers.h"
27
28 #include "insets/InsetRef.h"
29
30 #include "support/FileName.h"
31 #include "support/FileNameList.h"
32 #include "support/filetools.h" // makeAbsPath, makeDisplayPath
33
34 #include <QLineEdit>
35 #include <QCheckBox>
36 #include <QTreeWidget>
37 #include <QTreeWidgetItem>
38 #include <QPushButton>
39 #include <QToolTip>
40 #include <QCloseEvent>
41 #include <QHeaderView>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47 namespace frontend {
48
49 GuiRef::GuiRef(GuiView & lv)
50         : GuiDialog(lv, "ref", qt_("Cross-reference")),
51           params_(insetCode("ref"))
52 {
53         setupUi(this);
54
55         at_ref_ = false;
56
57         // The filter bar
58         filter_ = new FancyLineEdit(this);
59         filter_->setClearButton(true);
60         filter_->setPlaceholderText(qt_("All available labels"));
61         filter_->setToolTip(qt_("Enter string to filter the list of available labels"));
62 #if (QT_VERSION < 0x050000)
63         connect(filter_, SIGNAL(downPressed()),
64                 refsTW, SLOT(setFocus()));
65 #else
66         connect(filter_, &FancyLineEdit::downPressed,
67                 refsTW, [this](){ focusAndHighlight(refsTW); });
68 #endif
69
70         filterBarL->addWidget(filter_, 0);
71         findKeysLA->setBuddy(filter_);
72
73         sortingCO->addItem(qt_("By Occurrence"), "unsorted");
74         sortingCO->addItem(qt_("Alphabetically (Case-Insensitive)"), "nocase");
75         sortingCO->addItem(qt_("Alphabetically (Case-Sensitive)"), "case");
76
77         buttonBox->button(QDialogButtonBox::Reset)->setText(qt_("&Update"));
78         buttonBox->button(QDialogButtonBox::Reset)->setToolTip(qt_("Update the label list"));
79
80         refsTW->setColumnCount(1);
81         refsTW->header()->setVisible(false);
82
83         connect(this, SIGNAL(rejected()), this, SLOT(dialogRejected()));
84
85         connect(typeCO, SIGNAL(activated(int)),
86                 this, SLOT(changed_adaptor()));
87         connect(referenceED, SIGNAL(textChanged(QString)),
88                 this, SLOT(refTextChanged(QString)));
89         connect(referenceED, SIGNAL(textChanged(QString)),
90                 this, SLOT(changed_adaptor()));
91         connect(filter_, SIGNAL(textEdited(QString)),
92                 this, SLOT(filterLabels()));
93         connect(filter_, SIGNAL(rightButtonClicked()),
94                 this, SLOT(resetFilter()));
95         connect(csFindCB, SIGNAL(clicked()),
96                 this, SLOT(filterLabels()));
97         connect(refsTW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
98                 this, SLOT(refHighlighted(QTreeWidgetItem *)));
99         connect(refsTW, SIGNAL(itemSelectionChanged()),
100                 this, SLOT(selectionChanged()));
101         connect(refsTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
102                 this, SLOT(refSelected(QTreeWidgetItem *)));
103         connect(sortingCO, SIGNAL(activated(int)),
104                 this, SLOT(sortToggled()));
105         connect(groupCB, SIGNAL(clicked()),
106                 this, SLOT(groupToggled()));
107         connect(gotoPB, SIGNAL(clicked()),
108                 this, SLOT(gotoClicked()));
109         connect(bufferCO, SIGNAL(activated(int)),
110                 this, SLOT(updateClicked()));
111         connect(pluralCB, SIGNAL(clicked()),
112                 this, SLOT(changed_adaptor()));
113         connect(capsCB, SIGNAL(clicked()),
114                 this, SLOT(changed_adaptor()));
115         connect(noprefixCB, SIGNAL(clicked()),
116                 this, SLOT(changed_adaptor()));
117
118         enableBoxes();
119
120         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
121         bc().setOK(buttonBox->button(QDialogButtonBox::Ok));
122         bc().setApply(buttonBox->button(QDialogButtonBox::Apply));
123         bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
124         bc().addReadOnly(typeCO);
125
126         restored_buffer_ = -1;
127         active_buffer_ = -1;
128
129         setFocusProxy(filter_);
130 }
131
132
133 void GuiRef::enableView(bool enable)
134 {
135         if (!enable)
136                 // In the opposite case, updateContents() will be called anyway.
137                 updateContents();
138         GuiDialog::enableView(enable);
139 }
140
141
142 void GuiRef::enableBoxes()
143 {
144         QString const reftype =
145             typeCO->itemData(typeCO->currentIndex()).toString();
146         bool const isFormatted = (reftype == "formatted");
147         bool const isLabelOnly = (reftype == "labelonly");
148         bool const usingRefStyle = buffer().params().use_refstyle;
149         bool const intext = bufferview()->cursor().inTexted();
150         pluralCB->setEnabled(intext && isFormatted && usingRefStyle);
151         capsCB->setEnabled(intext && isFormatted && usingRefStyle);
152         noprefixCB->setEnabled(intext && isLabelOnly);
153 }
154
155
156 void GuiRef::changed_adaptor()
157 {
158         changed();
159         enableBoxes();
160 }
161
162
163 void GuiRef::gotoClicked()
164 {
165         // By setting last_reference_, we ensure that the reference
166         // to which we are going (or from which we are returning) is
167         // restored in the dialog. It's a bit of a hack, but it works,
168         // and no-one seems to have any better idea.
169         bool const toggled =
170                 last_reference_.isEmpty() || last_reference_.isNull();
171         if (toggled)
172                 last_reference_ = referenceED->text();
173         gotoRef();
174         if (toggled)
175                 last_reference_.clear();
176 }
177
178
179 void GuiRef::selectionChanged()
180 {
181         if (isBufferReadonly())
182                 return;
183
184         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
185         if (selections.isEmpty())
186                 return;
187         QTreeWidgetItem * sel = selections.first();
188         refHighlighted(sel);
189 }
190
191
192 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
193 {
194         if (sel->childCount() > 0) {
195                 sel->setExpanded(true);
196                 return;
197         }
198
199 /*      int const cur_item = refsTW->currentRow();
200         bool const cur_item_selected = cur_item >= 0 ?
201                 refsLB->isSelected(cur_item) : false;*/
202         bool const cur_item_selected = sel->isSelected();
203
204         if (cur_item_selected)
205                 referenceED->setText(sel->text(0));
206
207         if (at_ref_)
208                 gotoRef();
209         gotoPB->setEnabled(true);
210         if (!isBufferReadonly())
211                 typeCO->setEnabled(true);
212 }
213
214
215 void GuiRef::refTextChanged(QString const & str)
216 {
217         gotoPB->setEnabled(!str.isEmpty());
218         typeCO->setEnabled(!str.isEmpty());
219         typeLA->setEnabled(!str.isEmpty());
220 }
221
222
223 void GuiRef::refSelected(QTreeWidgetItem * sel)
224 {
225         if (isBufferReadonly())
226                 return;
227
228         if (sel->childCount()) {
229                 sel->setExpanded(false);
230                 return;
231         }
232
233 /*      int const cur_item = refsTW->currentRow();
234         bool const cur_item_selected = cur_item >= 0 ?
235                 refsLB->isSelected(cur_item) : false;*/
236         bool const cur_item_selected = sel->isSelected();
237
238         if (cur_item_selected)
239                 referenceED->setText(sel->text(0));
240         // <enter> or double click, inserts ref and closes dialog
241         slotOK();
242 }
243
244
245 void GuiRef::sortToggled()
246 {
247         redoRefs();
248 }
249
250
251 void GuiRef::groupToggled()
252 {
253         redoRefs();
254 }
255
256
257 void GuiRef::on_buttonBox_clicked(QAbstractButton * button)
258 {
259         switch (buttonBox->standardButton(button)) {
260         case QDialogButtonBox::Ok:
261                 slotOK();
262                 break;
263         case QDialogButtonBox::Apply:
264                 slotApply();
265                 break;
266         case QDialogButtonBox::Cancel:
267                 slotClose();
268                 resetDialog();
269                 break;
270         case QDialogButtonBox::Reset:
271                 updateClicked();
272                 break;
273         default:
274                 break;
275         }
276 }
277
278
279 void GuiRef::updateClicked()
280 {
281         updateRefs();
282 }
283
284
285 void GuiRef::dialogRejected()
286 {
287         resetDialog();
288         // We have to do this manually, instead of calling slotClose(), because
289         // the dialog has already been made invisible before rejected() triggers.
290         Dialog::disconnect();
291 }
292
293
294 void GuiRef::resetDialog()
295 {
296         at_ref_ = false;
297         setGotoRef();
298 }
299
300
301 void GuiRef::closeEvent(QCloseEvent * e)
302 {
303         slotClose();
304         resetDialog();
305         e->accept();
306 }
307
308
309 void GuiRef::updateContents()
310 {
311         QString const orig_type =
312                 typeCO->itemData(typeCO->currentIndex()).toString();
313
314         referenceED->clear();
315         typeCO->clear();
316
317         // FIXME Bring InsetMathRef on par with InsetRef
318         // (see #11104)
319         typeCO->addItem(qt_("<reference>"), "ref");
320         typeCO->addItem(qt_("(<reference>)"), "eqref");
321         typeCO->addItem(qt_("<page>"), "pageref");
322         typeCO->addItem(qt_("on page <page>"), "vpageref");
323         typeCO->addItem(qt_("<reference> on page <page>"), "vref");
324         typeCO->addItem(qt_("Textual reference"), "nameref");
325         typeCO->addItem(qt_("Formatted reference"), "formatted");
326         typeCO->addItem(qt_("Label only"), "labelonly");
327
328         referenceED->setText(toqstr(params_["reference"]));
329
330         // restore type settings for new insets
331         bool const new_inset = params_["reference"].empty();
332         if (new_inset) {
333                 int index = typeCO->findData(orig_type);
334                 if (index == -1)
335                         index = 0;
336                 typeCO->setCurrentIndex(index);
337         }
338         else
339                 typeCO->setCurrentIndex(
340                         typeCO->findData(toqstr(params_.getCmdName())));
341         typeCO->setEnabled(!isBufferReadonly());
342
343         pluralCB->setChecked(params_["plural"] == "true");
344         capsCB->setChecked(params_["caps"] == "true");
345         noprefixCB->setChecked(params_["noprefix"] == "true");
346
347         // insert buffer list
348         bufferCO->clear();
349         FileNameList const buffers(theBufferList().fileNames());
350         for (FileNameList::const_iterator it = buffers.begin();
351              it != buffers.end(); ++it) {
352                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
353         }
354
355         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
356         // restore the buffer combo setting for new insets
357         if (new_inset && restored_buffer_ != -1
358             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
359                 bufferCO->setCurrentIndex(restored_buffer_);
360         else {
361                 int const num = theBufferList().bufferNum(buffer().fileName());
362                 bufferCO->setCurrentIndex(num);
363                 if (thebuffer != active_buffer_)
364                         restored_buffer_ = num;
365         }
366         active_buffer_ = thebuffer;
367
368         updateRefs();
369         enableBoxes();
370         // Activate OK/Apply buttons if the users inserts a new ref
371         // and we have a valid pre-setting.
372         bc().setValid(isValid() && new_inset);
373 }
374
375
376 void GuiRef::applyView()
377 {
378         last_reference_ = referenceED->text();
379
380         params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
381         params_["reference"] = qstring_to_ucs4(last_reference_);
382         params_["plural"] = pluralCB->isChecked() ?
383               from_ascii("true") : from_ascii("false");
384         params_["caps"] = capsCB->isChecked() ?
385               from_ascii("true") : from_ascii("false");
386         params_["noprefix"] = noprefixCB->isChecked() ?
387               from_ascii("true") : from_ascii("false");
388         restored_buffer_ = bufferCO->currentIndex();
389 }
390
391
392 void GuiRef::setGoBack()
393 {
394         gotoPB->setText(qt_("&Go Back"));
395         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
396 }
397
398
399 void GuiRef::setGotoRef()
400 {
401         gotoPB->setText(qt_("&Go to Label"));
402         gotoPB->setToolTip(qt_("Jump to the selected label"));
403 }
404
405
406 void GuiRef::gotoRef()
407 {
408         string ref = fromqstr(referenceED->text());
409
410         if (at_ref_) {
411                 // go back
412                 setGotoRef();
413                 gotoBookmark();
414         } else {
415                 // go to the ref
416                 setGoBack();
417                 gotoRef(ref);
418         }
419         at_ref_ = !at_ref_;
420 }
421
422 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
423 {
424         return s1.toLower() < s2.toLower();
425 }
426
427
428 void GuiRef::redoRefs()
429 {
430         // Prevent these widgets from emitting any signals whilst
431         // we modify their state.
432         refsTW->blockSignals(true);
433         referenceED->blockSignals(true);
434         refsTW->setUpdatesEnabled(false);
435
436         refsTW->clear();
437
438         // need this because Qt will send a highlight() here for
439         // the first item inserted
440         QString const oldSelection(referenceED->text());
441
442         QStringList refsStrings;
443         QStringList refsCategories;
444         vector<docstring>::const_iterator iter;
445         bool noprefix = false;
446         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
447                 QString const lab = toqstr(*iter);
448                 refsStrings.append(lab);
449                 if (groupCB->isChecked()) {
450                         if (lab.contains(":")) {
451                                 QString const pref = lab.split(':')[0];
452                                 if (!refsCategories.contains(pref)) {
453                                         if (!pref.isEmpty())
454                                                 refsCategories.append(pref);
455                                         else
456                                                 noprefix = true;
457                                 }
458                         }
459                         else
460                                 noprefix = true;
461                 }
462         }
463         // sort categories case-intensively
464         sort(refsCategories.begin(), refsCategories.end(),
465                   caseInsensitiveLessThan /*defined above*/);
466         if (noprefix)
467                 refsCategories.insert(0, qt_("<No prefix>"));
468
469         QString const sort_method = sortingCO->isEnabled() ?
470                                         sortingCO->itemData(sortingCO->currentIndex()).toString()
471                                         : QString();
472         if (sort_method == "nocase")
473                 sort(refsStrings.begin(), refsStrings.end(),
474                           caseInsensitiveLessThan /*defined above*/);
475         else if (sort_method == "case")
476                 sort(refsStrings.begin(), refsStrings.end());
477
478         if (groupCB->isChecked()) {
479                 QList<QTreeWidgetItem *> refsCats;
480                 for (int i = 0; i < refsCategories.size(); ++i) {
481                         QString const & cat = refsCategories.at(i);
482                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
483                         item->setText(0, cat);
484                         for (int j = 0; j < refsStrings.size(); ++j) {
485                                 QString const & ref = refsStrings.at(j);
486                                 if ((ref.startsWith(cat + QString(":")))
487                                     || (cat == qt_("<No prefix>")
488                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
489                                                 QTreeWidgetItem * child =
490                                                         new QTreeWidgetItem(item);
491                                                 child->setText(0, ref);
492                                                 item->addChild(child);
493                                 }
494                         }
495                         refsCats.append(item);
496                 }
497                 refsTW->addTopLevelItems(refsCats);
498         } else {
499                 QList<QTreeWidgetItem *> refsItems;
500                 for (int i = 0; i < refsStrings.size(); ++i) {
501                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
502                         item->setText(0, refsStrings.at(i));
503                         refsItems.append(item);
504                 }
505                 refsTW->addTopLevelItems(refsItems);
506         }
507
508         // restore the last selection or, for new insets, highlight
509         // the previous selection
510         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
511                 bool const newInset = oldSelection.isEmpty();
512                 QString textToFind = newInset ? last_reference_ : oldSelection;
513                 referenceED->setText(textToFind);
514                 last_reference_.clear();
515                 QTreeWidgetItemIterator it(refsTW);
516                 while (*it) {
517                         if ((*it)->text(0) == textToFind) {
518                                 refsTW->setCurrentItem(*it);
519                                 (*it)->setSelected(true);
520                                 //Make sure selected item is visible
521                                 refsTW->scrollToItem(*it);
522                                 last_reference_ = textToFind;
523                                 break;
524                         }
525                         ++it;
526                 }
527         }
528         refsTW->setUpdatesEnabled(true);
529         refsTW->update();
530
531         // redo filter
532         filterLabels();
533
534         // Re-activate the emission of signals by these widgets.
535         refsTW->blockSignals(false);
536         referenceED->blockSignals(false);
537
538         gotoPB->setEnabled(!referenceED->text().isEmpty());
539         typeCO->setEnabled(!referenceED->text().isEmpty());
540         typeLA->setEnabled(!referenceED->text().isEmpty());
541 }
542
543
544 void GuiRef::updateRefs()
545 {
546         refs_.clear();
547         int const the_buffer = bufferCO->currentIndex();
548         if (the_buffer != -1) {
549                 FileNameList const names(theBufferList().fileNames());
550                 FileName const & name = names[the_buffer];
551                 Buffer const * buf = theBufferList().getBuffer(name);
552                 buf->getLabelList(refs_);
553         }
554         sortingCO->setEnabled(!refs_.empty());
555         refsTW->setEnabled(!refs_.empty());
556         groupCB->setEnabled(!refs_.empty());
557         redoRefs();
558 }
559
560
561 bool GuiRef::isValid()
562 {
563         return !referenceED->text().isEmpty();
564 }
565
566
567 void GuiRef::gotoRef(string const & ref)
568 {
569         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
570         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
571 }
572
573
574 void GuiRef::gotoBookmark()
575 {
576         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
577 }
578
579
580 void GuiRef::filterLabels()
581 {
582         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
583                 Qt::CaseSensitive : Qt::CaseInsensitive;
584         QTreeWidgetItemIterator it(refsTW);
585         while (*it) {
586                 (*it)->setHidden(
587                         (*it)->childCount() == 0
588                         && !(*it)->text(0).contains(filter_->text(), cs)
589                 );
590                 ++it;
591         }
592 }
593
594
595 void GuiRef::resetFilter()
596 {
597         filter_->setText(QString());
598         filterLabels();
599 }
600
601
602 bool GuiRef::initialiseParams(std::string const & sdata)
603 {
604         InsetCommand::string2params(sdata, params_);
605         return true;
606 }
607
608
609 void GuiRef::dispatchParams()
610 {
611         std::string const lfun = InsetCommand::params2string(params_);
612         dispatch(FuncRequest(getLfun(), lfun));
613         connectToNewInset();
614 }
615
616
617 } // namespace frontend
618 } // namespace lyx
619
620 #include "moc_GuiRef.cpp"