]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiRef.cpp
Regenerate previews after zoom (#11919)
[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->data(0, Qt::UserRole).toString());
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->data(0, Qt::UserRole).toString());
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 refsNames;
443         QStringList refsAsStrings;
444         QStringList refsCategories;
445         vector<std::pair<docstring, docstring>>::const_iterator iter;
446         bool noprefix = false;
447         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
448                 // the plain label name
449                 QString const lab = toqstr((*iter).first);
450                 refsNames.append(lab);
451                 // the label as gui string
452                 refsAsStrings.append(toqstr((*iter).second));
453                 if (groupCB->isChecked()) {
454                         if (lab.contains(":")) {
455                                 QString const pref = lab.split(':')[0];
456                                 if (!refsCategories.contains(pref)) {
457                                         if (!pref.isEmpty())
458                                                 refsCategories.append(pref);
459                                         else
460                                                 noprefix = true;
461                                 }
462                         }
463                         else
464                                 noprefix = true;
465                 }
466         }
467         // sort categories case-intensively
468         sort(refsCategories.begin(), refsCategories.end(),
469                   caseInsensitiveLessThan /*defined above*/);
470         if (noprefix)
471                 refsCategories.insert(0, qt_("<No prefix>"));
472
473         QString const sort_method = sortingCO->isEnabled() ?
474                                         sortingCO->itemData(sortingCO->currentIndex()).toString()
475                                         : QString();
476         if (sort_method == "nocase")
477                 sort(refsNames.begin(), refsNames.end(),
478                           caseInsensitiveLessThan /*defined above*/);
479         else if (sort_method == "case")
480                 sort(refsNames.begin(), refsNames.end());
481
482         if (groupCB->isChecked()) {
483                 QList<QTreeWidgetItem *> refsCats;
484                 for (int i = 0; i < refsCategories.size(); ++i) {
485                         QString const & cat = refsCategories.at(i);
486                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
487                         item->setText(0, cat);
488                         for (int j = 0; j < refsNames.size(); ++j) {
489                                 QString const & ref = refsNames.at(j);
490                                 if ((ref.startsWith(cat + QString(":")))
491                                     || (cat == qt_("<No prefix>")
492                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
493                                                 QTreeWidgetItem * child =
494                                                         new QTreeWidgetItem(item);
495                                                 item->setText(0, refsAsStrings.at(j));
496                                                 item->setData(0, Qt::UserRole, ref);
497                                                 item->addChild(child);
498                                 }
499                         }
500                         refsCats.append(item);
501                 }
502                 refsTW->addTopLevelItems(refsCats);
503         } else {
504                 QList<QTreeWidgetItem *> refsItems;
505                 for (int i = 0; i < refsNames.size(); ++i) {
506                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
507                         QString const & ref = refsNames.at(i);
508                         item->setText(0, refsAsStrings.at(i));
509                         item->setData(0, Qt::UserRole, ref);
510                         refsItems.append(item);
511                 }
512                 refsTW->addTopLevelItems(refsItems);
513         }
514
515         // restore the last selection or, for new insets, highlight
516         // the previous selection
517         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
518                 bool const newInset = oldSelection.isEmpty();
519                 QString textToFind = newInset ? last_reference_ : oldSelection;
520                 referenceED->setText(textToFind);
521                 last_reference_.clear();
522                 QTreeWidgetItemIterator it(refsTW);
523                 while (*it) {
524                         if ((*it)->text(0) == textToFind) {
525                                 refsTW->setCurrentItem(*it);
526                                 (*it)->setSelected(true);
527                                 //Make sure selected item is visible
528                                 refsTW->scrollToItem(*it);
529                                 last_reference_ = textToFind;
530                                 break;
531                         }
532                         ++it;
533                 }
534         }
535         refsTW->setUpdatesEnabled(true);
536         refsTW->update();
537
538         // redo filter
539         filterLabels();
540
541         // Re-activate the emission of signals by these widgets.
542         refsTW->blockSignals(false);
543         referenceED->blockSignals(false);
544
545         gotoPB->setEnabled(!referenceED->text().isEmpty());
546         typeCO->setEnabled(!referenceED->text().isEmpty());
547         typeLA->setEnabled(!referenceED->text().isEmpty());
548 }
549
550
551 void GuiRef::updateRefs()
552 {
553         refs_.clear();
554         int const the_buffer = bufferCO->currentIndex();
555         if (the_buffer != -1) {
556                 FileNameList const names(theBufferList().fileNames());
557                 FileName const & name = names[the_buffer];
558                 Buffer const * buf = theBufferList().getBuffer(name);
559                 buf->getLabelList(refs_);
560         }
561         sortingCO->setEnabled(!refs_.empty());
562         refsTW->setEnabled(!refs_.empty());
563         groupCB->setEnabled(!refs_.empty());
564         redoRefs();
565 }
566
567
568 bool GuiRef::isValid()
569 {
570         return !referenceED->text().isEmpty();
571 }
572
573
574 void GuiRef::gotoRef(string const & ref)
575 {
576         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
577         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
578 }
579
580
581 void GuiRef::gotoBookmark()
582 {
583         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
584 }
585
586
587 void GuiRef::filterLabels()
588 {
589         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
590                 Qt::CaseSensitive : Qt::CaseInsensitive;
591         QTreeWidgetItemIterator it(refsTW);
592         while (*it) {
593                 (*it)->setHidden(
594                         (*it)->childCount() == 0
595                         && !(*it)->text(0).contains(filter_->text(), cs)
596                 );
597                 ++it;
598         }
599 }
600
601
602 void GuiRef::resetFilter()
603 {
604         filter_->setText(QString());
605         filterLabels();
606 }
607
608
609 bool GuiRef::initialiseParams(std::string const & sdata)
610 {
611         InsetCommand::string2params(sdata, params_);
612         return true;
613 }
614
615
616 void GuiRef::dispatchParams()
617 {
618         std::string const lfun = InsetCommand::params2string(params_);
619         dispatch(FuncRequest(getLfun(), lfun));
620         connectToNewInset();
621 }
622
623
624 } // namespace frontend
625 } // namespace lyx
626
627 #include "moc_GuiRef.cpp"