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