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