]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiRef.cpp
On Linux show in crash message box the backtrace
[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         gotoRef();
118 }
119
120
121 void GuiRef::selectionChanged()
122 {
123         if (isBufferReadonly())
124                 return;
125
126         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
127         if (selections.isEmpty())
128                 return;
129         QTreeWidgetItem * sel = selections.first();
130         refHighlighted(sel);
131         return;
132 }
133
134
135 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
136 {
137         if (sel->childCount() > 0) {
138                 sel->setExpanded(true);
139                 return;
140         }
141
142 /*      int const cur_item = refsTW->currentRow();
143         bool const cur_item_selected = cur_item >= 0 ?
144                 refsLB->isSelected(cur_item) : false;*/
145         bool const cur_item_selected = refsTW->isItemSelected(sel);
146
147         if (cur_item_selected)
148                 referenceED->setText(sel->text(0));
149
150         if (at_ref_)
151                 gotoRef();
152         gotoPB->setEnabled(true);
153         if (typeAllowed() && !isBufferReadonly())
154                 typeCO->setEnabled(true);
155         nameED->setHidden(!nameAllowed());
156         nameL->setHidden(!nameAllowed());
157 }
158
159
160 void GuiRef::refSelected(QTreeWidgetItem * sel)
161 {
162         if (isBufferReadonly())
163                 return;
164
165         if (sel->childCount()) {
166                 sel->setExpanded(false);
167                 return;
168         }
169
170 /*      int const cur_item = refsTW->currentRow();
171         bool const cur_item_selected = cur_item >= 0 ?
172                 refsLB->isSelected(cur_item) : false;*/
173         bool const cur_item_selected = refsTW->isItemSelected(sel);
174
175         if (cur_item_selected)
176                 referenceED->setText(sel->text(0));
177         // <enter> or double click, inserts ref and closes dialog
178         slotOK();
179 }
180
181
182 void GuiRef::sortToggled()
183 {
184         caseSensitiveCB->setEnabled(sortCB->isChecked());
185         redoRefs();
186 }
187
188
189 void GuiRef::caseSensitiveToggled()
190 {
191         redoRefs();
192 }
193
194
195 void GuiRef::groupToggled()
196 {
197         redoRefs();
198 }
199
200
201 void GuiRef::updateClicked()
202 {
203         updateRefs();
204 }
205
206
207 void GuiRef::dialogRejected()
208 {
209         resetDialog();
210         // We have to do this manually, instead of calling slotClose(), because
211         // the dialog has already been made invisible before rejected() triggers.
212         Dialog::disconnect();
213 }
214
215
216 void GuiRef::resetDialog()
217 {
218         at_ref_ = false;
219         setGotoRef();
220 }
221
222
223 void GuiRef::closeEvent(QCloseEvent * e)
224 {
225         slotClose();
226         resetDialog();
227         e->accept();
228 }
229
230
231 void GuiRef::updateContents()
232 {
233         int orig_type = typeCO->currentIndex();
234
235         referenceED->clear();
236         nameED->clear();
237
238         referenceED->setText(toqstr(params_["reference"]));
239         nameED->setText(toqstr(params_["name"]));
240         nameED->setHidden(!nameAllowed());
241         nameL->setHidden(!nameAllowed());
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         vector<docstring>::const_iterator iter;
358         bool noprefix = false;
359         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
360                 QString const lab = toqstr(*iter);
361                 refsStrings.append(lab);
362                 if (groupCB->isChecked()) {
363                         if (lab.contains(":")) {
364                                 QString const pref = lab.split(':')[0];
365                                 if (!refsCategories.contains(pref)) {
366                                         if (!pref.isEmpty())
367                                                 refsCategories.append(pref);
368                                         else
369                                                 noprefix = true;
370                                 }
371                         }
372                         else
373                                 noprefix = true;
374                 }
375         }
376         // sort categories case-intensively
377         qSort(refsCategories.begin(), refsCategories.end(),
378               caseInsensitiveLessThan /*defined above*/);
379         if (noprefix)
380                 refsCategories.insert(0, qt_("<No prefix>"));
381
382         if (sortCB->isEnabled() && sortCB->isChecked()) {
383                 if(caseSensitiveCB->isEnabled() && caseSensitiveCB->isChecked())
384                         qSort(refsStrings.begin(), refsStrings.end());
385                 else
386                         qSort(refsStrings.begin(), refsStrings.end(),
387                               caseInsensitiveLessThan /*defined above*/);
388         }
389         
390         if (groupCB->isChecked()) {
391                 QList<QTreeWidgetItem *> refsCats;
392                 for (int i = 0; i < refsCategories.size(); ++i) {
393                         QString const cat = refsCategories.at(i);
394                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
395                         item->setText(0, cat);
396                         for (int i = 0; i < refsStrings.size(); ++i) {
397                                 QString const ref = refsStrings.at(i);
398                                 if ((ref.startsWith(cat + QString(":")))
399                                     || (cat == qt_("<No prefix>")
400                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
401                                                 QTreeWidgetItem * child =
402                                                         new QTreeWidgetItem(item);
403                                                 child->setText(0, ref);
404                                                 item->addChild(child);
405                                 }
406                         }
407                         refsCats.append(item);
408                 }
409                 refsTW->addTopLevelItems(refsCats);
410         } else {
411                 QList<QTreeWidgetItem *> refsItems;
412                 for (int i = 0; i < refsStrings.size(); ++i) {
413                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
414                         item->setText(0, refsStrings.at(i));
415                         refsItems.append(item);
416                 }
417                 refsTW->addTopLevelItems(refsItems);
418         }
419
420         referenceED->setText(oldSelection);
421
422         // restore the last selection or, for new insets, highlight
423         // the previous selection
424         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
425                 bool const newInset = oldSelection.isEmpty();
426                 QString textToFind = newInset ? last_reference_ : oldSelection;
427                 last_reference_.clear();
428                 QTreeWidgetItemIterator it(refsTW);
429                 while (*it) {
430                         if ((*it)->text(0) == textToFind) {
431                                 refsTW->setCurrentItem(*it);
432                                 refsTW->setItemSelected(*it, !newInset);
433                                 //Make sure selected item is visible
434                                 refsTW->scrollToItem(*it);
435                                 last_reference_ = textToFind;
436                                 break;
437                         }
438                         ++it;
439                 }
440         }
441         refsTW->setUpdatesEnabled(true);
442         refsTW->update();
443
444         // redo filter
445         filterLabels();
446
447         // Re-activate the emission of signals by these widgets.
448         refsTW->blockSignals(false);
449         referenceED->blockSignals(false);
450 }
451
452
453 void GuiRef::updateRefs()
454 {
455         refs_.clear();
456         int const the_buffer = bufferCO->currentIndex();
457         if (the_buffer != -1) {
458                 FileName const & name = theBufferList().fileNames()[the_buffer];
459                 Buffer const * buf = theBufferList().getBuffer(name);
460                 buf->getLabelList(refs_);
461         }
462         sortCB->setEnabled(!refs_.empty());
463         caseSensitiveCB->setEnabled(sortCB->isEnabled() && sortCB->isChecked());
464         refsTW->setEnabled(!refs_.empty());
465         groupCB->setEnabled(!refs_.empty());
466         // refsTW should only be the focus proxy when it is enabled
467         setFocusProxy(refs_.empty() ? 0 : refsTW);
468         gotoPB->setEnabled(!refs_.empty());
469         redoRefs();
470 }
471
472
473 bool GuiRef::isValid()
474 {
475         return !referenceED->text().isEmpty();
476 }
477
478
479 void GuiRef::gotoRef(string const & ref)
480 {
481         dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
482         dispatch(FuncRequest(LFUN_LABEL_GOTO, ref));
483 }
484
485
486 void GuiRef::gotoBookmark()
487 {
488         dispatch(FuncRequest(LFUN_BOOKMARK_GOTO, "0"));
489 }
490
491
492 void GuiRef::filterLabels()
493 {
494         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
495                 Qt::CaseSensitive : Qt::CaseInsensitive;
496         QTreeWidgetItemIterator it(refsTW);
497         while (*it) {
498                 (*it)->setHidden(
499                         (*it)->childCount() == 0
500                         && !(*it)->text(0).contains(findLE->text(), cs)
501                 );
502                 ++it;
503         }
504 }
505
506
507 bool GuiRef::initialiseParams(std::string const & data)
508 {
509         InsetCommand::string2params(data, params_);
510         return true;
511 }
512
513
514 void GuiRef::dispatchParams()
515 {
516         std::string const lfun = InsetCommand::params2string(params_);
517         dispatch(FuncRequest(getLfun(), lfun));
518 }
519
520
521
522 Dialog * createGuiRef(GuiView & lv) { return new GuiRef(lv); }
523
524
525 } // namespace frontend
526 } // namespace lyx
527
528 #include "moc_GuiRef.cpp"