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