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