]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiRef.cpp
Keep dialog connected to cross-ref inset after Apply.
[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         bool const intext = bufferview()->cursor().inTexted();
153         pluralCB->setEnabled(intext && isFormatted && usingRefStyle);
154         capsCB->setEnabled(intext && isFormatted && usingRefStyle);
155         noprefixCB->setEnabled(intext && 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 #11104)
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         typeCO->addItem(qt_("Formatted reference"), "formatted");
329         typeCO->addItem(qt_("Label only"), "labelonly");
330
331         referenceED->setText(toqstr(params_["reference"]));
332
333         // restore type settings for new insets
334         bool const new_inset = params_["reference"].empty();
335         if (new_inset) {
336                 int index = typeCO->findData(orig_type);
337                 if (index == -1)
338                         index = 0;
339                 typeCO->setCurrentIndex(index);
340         }
341         else
342                 typeCO->setCurrentIndex(
343                         typeCO->findData(toqstr(params_.getCmdName())));
344         typeCO->setEnabled(!isBufferReadonly());
345
346         pluralCB->setChecked(params_["plural"] == "true");
347         capsCB->setChecked(params_["caps"] == "true");
348         noprefixCB->setChecked(params_["noprefix"] == "true");
349
350         // insert buffer list
351         bufferCO->clear();
352         FileNameList const buffers(theBufferList().fileNames());
353         for (FileNameList::const_iterator it = buffers.begin();
354              it != buffers.end(); ++it) {
355                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
356         }
357
358         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
359         // restore the buffer combo setting for new insets
360         if (new_inset && restored_buffer_ != -1
361             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
362                 bufferCO->setCurrentIndex(restored_buffer_);
363         else {
364                 int const num = theBufferList().bufferNum(buffer().fileName());
365                 bufferCO->setCurrentIndex(num);
366                 if (thebuffer != active_buffer_)
367                         restored_buffer_ = num;
368         }
369         active_buffer_ = thebuffer;
370
371         updateRefs();
372         enableBoxes();
373         // Activate OK/Apply buttons if the users inserts a new ref
374         // and we have a valid pre-setting.
375         bc().setValid(isValid() && new_inset);
376 }
377
378
379 void GuiRef::applyView()
380 {
381         last_reference_ = referenceED->text();
382
383         params_.setCmdName(fromqstr(typeCO->itemData(typeCO->currentIndex()).toString()));
384         params_["reference"] = qstring_to_ucs4(last_reference_);
385         params_["plural"] = pluralCB->isChecked() ?
386               from_ascii("true") : from_ascii("false");
387         params_["caps"] = capsCB->isChecked() ?
388               from_ascii("true") : from_ascii("false");
389         params_["noprefix"] = noprefixCB->isChecked() ?
390               from_ascii("true") : from_ascii("false");
391         restored_buffer_ = bufferCO->currentIndex();
392 }
393
394
395 void GuiRef::setGoBack()
396 {
397         gotoPB->setText(qt_("&Go Back"));
398         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
399 }
400
401
402 void GuiRef::setGotoRef()
403 {
404         gotoPB->setText(qt_("&Go to Label"));
405         gotoPB->setToolTip(qt_("Jump to the selected label"));
406 }
407
408
409 void GuiRef::gotoRef()
410 {
411         string ref = fromqstr(referenceED->text());
412
413         if (at_ref_) {
414                 // go back
415                 setGotoRef();
416                 gotoBookmark();
417         } else {
418                 // go to the ref
419                 setGoBack();
420                 gotoRef(ref);
421         }
422         at_ref_ = !at_ref_;
423 }
424
425 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
426 {
427         return s1.toLower() < s2.toLower();
428 }
429
430
431 void GuiRef::redoRefs()
432 {
433         // Prevent these widgets from emitting any signals whilst
434         // we modify their state.
435         refsTW->blockSignals(true);
436         referenceED->blockSignals(true);
437         refsTW->setUpdatesEnabled(false);
438
439         refsTW->clear();
440
441         // need this because Qt will send a highlight() here for
442         // the first item inserted
443         QString const oldSelection(referenceED->text());
444
445         QStringList refsStrings;
446         QStringList refsCategories;
447         vector<docstring>::const_iterator iter;
448         bool noprefix = false;
449         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
450                 QString const lab = toqstr(*iter);
451                 refsStrings.append(lab);
452                 if (groupCB->isChecked()) {
453                         if (lab.contains(":")) {
454                                 QString const pref = lab.split(':')[0];
455                                 if (!refsCategories.contains(pref)) {
456                                         if (!pref.isEmpty())
457                                                 refsCategories.append(pref);
458                                         else
459                                                 noprefix = true;
460                                 }
461                         }
462                         else
463                                 noprefix = true;
464                 }
465         }
466         // sort categories case-intensively
467         sort(refsCategories.begin(), refsCategories.end(),
468                   caseInsensitiveLessThan /*defined above*/);
469         if (noprefix)
470                 refsCategories.insert(0, qt_("<No prefix>"));
471
472         QString const sort_method = sortingCO->isEnabled() ?
473                                         sortingCO->itemData(sortingCO->currentIndex()).toString()
474                                         : QString();
475         if (sort_method == "nocase")
476                 sort(refsStrings.begin(), refsStrings.end(),
477                           caseInsensitiveLessThan /*defined above*/);
478         else if (sort_method == "case")
479                 sort(refsStrings.begin(), refsStrings.end());
480
481         if (groupCB->isChecked()) {
482                 QList<QTreeWidgetItem *> refsCats;
483                 for (int i = 0; i < refsCategories.size(); ++i) {
484                         QString const & cat = refsCategories.at(i);
485                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
486                         item->setText(0, cat);
487                         for (int j = 0; j < refsStrings.size(); ++j) {
488                                 QString const & ref = refsStrings.at(j);
489                                 if ((ref.startsWith(cat + QString(":")))
490                                     || (cat == qt_("<No prefix>")
491                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
492                                                 QTreeWidgetItem * child =
493                                                         new QTreeWidgetItem(item);
494                                                 child->setText(0, ref);
495                                                 item->addChild(child);
496                                 }
497                         }
498                         refsCats.append(item);
499                 }
500                 refsTW->addTopLevelItems(refsCats);
501         } else {
502                 QList<QTreeWidgetItem *> refsItems;
503                 for (int i = 0; i < refsStrings.size(); ++i) {
504                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
505                         item->setText(0, refsStrings.at(i));
506                         refsItems.append(item);
507                 }
508                 refsTW->addTopLevelItems(refsItems);
509         }
510
511         // restore the last selection or, for new insets, highlight
512         // the previous selection
513         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
514                 bool const newInset = oldSelection.isEmpty();
515                 QString textToFind = newInset ? last_reference_ : oldSelection;
516                 referenceED->setText(textToFind);
517                 last_reference_.clear();
518                 QTreeWidgetItemIterator it(refsTW);
519                 while (*it) {
520                         if ((*it)->text(0) == textToFind) {
521                                 refsTW->setCurrentItem(*it);
522                                 (*it)->setSelected(true);
523                                 //Make sure selected item is visible
524                                 refsTW->scrollToItem(*it);
525                                 last_reference_ = textToFind;
526                                 break;
527                         }
528                         ++it;
529                 }
530         }
531         refsTW->setUpdatesEnabled(true);
532         refsTW->update();
533
534         // redo filter
535         filterLabels();
536
537         // Re-activate the emission of signals by these widgets.
538         refsTW->blockSignals(false);
539         referenceED->blockSignals(false);
540
541         gotoPB->setEnabled(!referenceED->text().isEmpty());
542         typeCO->setEnabled(!referenceED->text().isEmpty());
543         typeLA->setEnabled(!referenceED->text().isEmpty());
544 }
545
546
547 void GuiRef::updateRefs()
548 {
549         refs_.clear();
550         int const the_buffer = bufferCO->currentIndex();
551         if (the_buffer != -1) {
552                 FileNameList const names(theBufferList().fileNames());
553                 FileName const & name = names[the_buffer];
554                 Buffer const * buf = theBufferList().getBuffer(name);
555                 buf->getLabelList(refs_);
556         }
557         sortingCO->setEnabled(!refs_.empty());
558         refsTW->setEnabled(!refs_.empty());
559         groupCB->setEnabled(!refs_.empty());
560         redoRefs();
561 }
562
563
564 bool GuiRef::isValid()
565 {
566         return !referenceED->text().isEmpty();
567 }
568
569
570 void GuiRef::gotoRef(string const & ref)
571 {
572         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
573         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
574 }
575
576
577 void GuiRef::gotoBookmark()
578 {
579         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
580 }
581
582
583 void GuiRef::filterLabels()
584 {
585         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
586                 Qt::CaseSensitive : Qt::CaseInsensitive;
587         QTreeWidgetItemIterator it(refsTW);
588         while (*it) {
589                 (*it)->setHidden(
590                         (*it)->childCount() == 0
591                         && !(*it)->text(0).contains(filter_->text(), cs)
592                 );
593                 ++it;
594         }
595 }
596
597
598 void GuiRef::resetFilter()
599 {
600         filter_->setText(QString());
601         filterLabels();
602 }
603
604
605 bool GuiRef::initialiseParams(std::string const & sdata)
606 {
607         InsetCommand::string2params(sdata, params_);
608         return true;
609 }
610
611
612 void GuiRef::dispatchParams()
613 {
614         std::string const lfun = InsetCommand::params2string(params_);
615         dispatch(FuncRequest(getLfun(), lfun));
616         connectToNewInset();
617 }
618
619
620 } // namespace frontend
621 } // namespace lyx
622
623 #include "moc_GuiRef.cpp"