]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiRef.cpp
Whitespace
[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         if (params_["reference"].empty())
255                 typeCO->setCurrentIndex(orig_type);
256         else
257                 typeCO->setCurrentIndex(InsetRef::getType(params_.getCmdName()));
258         typeCO->setEnabled(typeAllowed() && !isBufferReadonly());
259         if (!typeAllowed())
260                 typeCO->setCurrentIndex(0);
261
262         // insert buffer list
263         bufferCO->clear();
264         FileNameList const buffers(theBufferList().fileNames());
265         for (FileNameList::const_iterator it = buffers.begin();
266              it != buffers.end(); ++it) {
267                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
268         }
269
270         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
271         // restore the buffer combo setting for new insets
272         if (params_["reference"].empty() && restored_buffer_ != -1
273             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
274                 bufferCO->setCurrentIndex(restored_buffer_);
275         else {
276                 int const num = theBufferList().bufferNum(buffer().fileName());
277                 bufferCO->setCurrentIndex(num);
278                 if (thebuffer != active_buffer_)
279                         restored_buffer_ = num;
280         }
281         active_buffer_ = thebuffer;
282
283         updateRefs();
284         bc().setValid(false);
285 }
286
287
288 void GuiRef::applyView()
289 {
290         last_reference_ = referenceED->text();
291
292         params_.setCmdName(InsetRef::getName(typeCO->currentIndex()));
293         params_["reference"] = qstring_to_ucs4(last_reference_);
294         params_["name"] = qstring_to_ucs4(nameED->text());
295
296         restored_buffer_ = bufferCO->currentIndex();
297 }
298
299
300 bool GuiRef::nameAllowed()
301 {
302         KernelDocType const doc_type = docType();
303         return doc_type != LATEX && doc_type != LITERATE;
304 }
305
306
307 bool GuiRef::typeAllowed()
308 {
309         return docType() != DOCBOOK;
310 }
311
312
313 void GuiRef::setGoBack()
314 {
315         gotoPB->setText(qt_("&Go Back"));
316         gotoPB->setToolTip("");
317         gotoPB->setToolTip(qt_("Jump back"));
318 }
319
320
321 void GuiRef::setGotoRef()
322 {
323         gotoPB->setText(qt_("&Go to Label"));
324         gotoPB->setToolTip("");
325         gotoPB->setToolTip(qt_("Jump to label"));
326 }
327
328
329 void GuiRef::gotoRef()
330 {
331         string ref = fromqstr(referenceED->text());
332
333         if (at_ref_) {
334                 // go back
335                 setGotoRef();
336                 gotoBookmark();
337         } else {
338                 // go to the ref
339                 setGoBack();
340                 gotoRef(ref);
341         }
342         at_ref_ = !at_ref_;
343 }
344
345 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
346 {
347         return s1.toLower() < s2.toLower();
348 }
349
350
351 void GuiRef::redoRefs()
352 {
353         // Prevent these widgets from emitting any signals whilst
354         // we modify their state.
355         refsTW->blockSignals(true);
356         referenceED->blockSignals(true);
357         refsTW->setUpdatesEnabled(false);
358
359         refsTW->clear();
360
361         // need this because Qt will send a highlight() here for
362         // the first item inserted
363         QString const oldSelection(referenceED->text());
364
365         QStringList refsStrings;
366         QStringList refsCategories;
367         vector<docstring>::const_iterator iter;
368         bool noprefix = false;
369         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
370                 QString const lab = toqstr(*iter);
371                 refsStrings.append(lab);
372                 if (groupCB->isChecked()) {
373                         if (lab.contains(":")) {
374                                 QString const pref = lab.split(':')[0];
375                                 if (!refsCategories.contains(pref)) {
376                                         if (!pref.isEmpty())
377                                                 refsCategories.append(pref);
378                                         else
379                                                 noprefix = true;
380                                 }
381                         }
382                         else
383                                 noprefix = true;
384                 }
385         }
386         // sort categories case-intensively
387         qSort(refsCategories.begin(), refsCategories.end(),
388               caseInsensitiveLessThan /*defined above*/);
389         if (noprefix)
390                 refsCategories.insert(0, qt_("<No prefix>"));
391
392         if (sortCB->isEnabled() && sortCB->isChecked()) {
393                 if(caseSensitiveCB->isEnabled() && caseSensitiveCB->isChecked())
394                         qSort(refsStrings.begin(), refsStrings.end());
395                 else
396                         qSort(refsStrings.begin(), refsStrings.end(),
397                               caseInsensitiveLessThan /*defined above*/);
398         }
399
400         if (groupCB->isChecked()) {
401                 QList<QTreeWidgetItem *> refsCats;
402                 for (int i = 0; i < refsCategories.size(); ++i) {
403                         QString const cat = refsCategories.at(i);
404                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
405                         item->setText(0, cat);
406                         for (int i = 0; i < refsStrings.size(); ++i) {
407                                 QString const ref = refsStrings.at(i);
408                                 if ((ref.startsWith(cat + QString(":")))
409                                     || (cat == qt_("<No prefix>")
410                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
411                                                 QTreeWidgetItem * child =
412                                                         new QTreeWidgetItem(item);
413                                                 child->setText(0, ref);
414                                                 item->addChild(child);
415                                 }
416                         }
417                         refsCats.append(item);
418                 }
419                 refsTW->addTopLevelItems(refsCats);
420         } else {
421                 QList<QTreeWidgetItem *> refsItems;
422                 for (int i = 0; i < refsStrings.size(); ++i) {
423                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
424                         item->setText(0, refsStrings.at(i));
425                         refsItems.append(item);
426                 }
427                 refsTW->addTopLevelItems(refsItems);
428         }
429
430         // restore the last selection or, for new insets, highlight
431         // the previous selection
432         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
433                 bool const newInset = oldSelection.isEmpty();
434                 QString textToFind = newInset ? last_reference_ : oldSelection;
435                 referenceED->setText(textToFind);
436                 last_reference_.clear();
437                 QTreeWidgetItemIterator it(refsTW);
438                 while (*it) {
439                         if ((*it)->text(0) == textToFind) {
440                                 refsTW->setCurrentItem(*it);
441                                 refsTW->setItemSelected(*it, true);
442                                 //Make sure selected item is visible
443                                 refsTW->scrollToItem(*it);
444                                 last_reference_ = textToFind;
445                                 break;
446                         }
447                         ++it;
448                 }
449         }
450         refsTW->setUpdatesEnabled(true);
451         refsTW->update();
452
453         // redo filter
454         filterLabels();
455
456         // Re-activate the emission of signals by these widgets.
457         refsTW->blockSignals(false);
458         referenceED->blockSignals(false);
459 }
460
461
462 void GuiRef::updateRefs()
463 {
464         refs_.clear();
465         int const the_buffer = bufferCO->currentIndex();
466         if (the_buffer != -1) {
467                 FileNameList const names(theBufferList().fileNames());
468                 FileName const & name = names[the_buffer];
469                 Buffer const * buf = theBufferList().getBuffer(name);
470                 buf->getLabelList(refs_);
471         }
472         sortCB->setEnabled(!refs_.empty());
473         caseSensitiveCB->setEnabled(sortCB->isEnabled() && sortCB->isChecked());
474         refsTW->setEnabled(!refs_.empty());
475         groupCB->setEnabled(!refs_.empty());
476         // refsTW should only be the focus proxy when it is enabled
477         setFocusProxy(refs_.empty() ? 0 : refsTW);
478         gotoPB->setEnabled(!refs_.empty());
479         redoRefs();
480 }
481
482
483 bool GuiRef::isValid()
484 {
485         return !referenceED->text().isEmpty();
486 }
487
488
489 void GuiRef::gotoRef(string const & ref)
490 {
491         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
492         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
493 }
494
495
496 void GuiRef::gotoBookmark()
497 {
498         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
499 }
500
501
502 void GuiRef::filterLabels()
503 {
504         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
505                 Qt::CaseSensitive : Qt::CaseInsensitive;
506         QTreeWidgetItemIterator it(refsTW);
507         while (*it) {
508                 (*it)->setHidden(
509                         (*it)->childCount() == 0
510                         && !(*it)->text(0).contains(findLE->text(), cs)
511                 );
512                 ++it;
513         }
514 }
515
516
517 bool GuiRef::initialiseParams(std::string const & data)
518 {
519         InsetCommand::string2params(data, params_);
520         return true;
521 }
522
523
524 void GuiRef::dispatchParams()
525 {
526         std::string const lfun = InsetCommand::params2string(params_);
527         dispatch(FuncRequest(getLfun(), lfun));
528 }
529
530
531
532 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
533
534
535 } // namespace frontend
536 } // namespace lyx
537
538 #include "moc_GuiRef.cpp"