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