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