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