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