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