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