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