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