]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiRef.cpp
Make a string translatable
[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         setFocusProxy(filter_);
135 }
136
137
138 void GuiRef::enableView(bool enable)
139 {
140         if (!enable)
141                 // In the opposite case, updateContents() will be called anyway.
142                 updateContents();
143         GuiDialog::enableView(enable);
144 }
145
146
147 void GuiRef::enableBoxes()
148 {
149         bool const isFormatted = 
150             (InsetRef::getName(typeCO->currentIndex()) == "formatted");
151         bool const isLabelOnly = 
152             (InsetRef::getName(typeCO->currentIndex()) == "labelonly");
153         bool const usingRefStyle = buffer().params().use_refstyle;
154         pluralCB->setEnabled(isFormatted && usingRefStyle);
155         capsCB->setEnabled(isFormatted && usingRefStyle);
156         noprefixCB->setEnabled(isLabelOnly);
157 }
158
159
160 void GuiRef::changed_adaptor()
161 {
162         changed();
163         enableBoxes();
164 }
165
166
167 void GuiRef::gotoClicked()
168 {
169         // By setting last_reference_, we ensure that the reference
170         // to which we are going (or from which we are returning) is
171         // restored in the dialog. It's a bit of a hack, but it works,
172         // and no-one seems to have any better idea.
173         bool const toggled = 
174                 last_reference_.isEmpty() || last_reference_.isNull();
175         if (toggled)
176                 last_reference_ = referenceED->text();
177         gotoRef();
178         if (toggled)
179                 last_reference_.clear();
180 }
181
182
183 void GuiRef::selectionChanged()
184 {
185         if (isBufferReadonly())
186                 return;
187
188         QList<QTreeWidgetItem *> selections = refsTW->selectedItems();
189         if (selections.isEmpty())
190                 return;
191         QTreeWidgetItem * sel = selections.first();
192         refHighlighted(sel);
193         return;
194 }
195
196
197 void GuiRef::refHighlighted(QTreeWidgetItem * sel)
198 {
199         if (sel->childCount() > 0) {
200                 sel->setExpanded(true);
201                 return;
202         }
203
204 /*      int const cur_item = refsTW->currentRow();
205         bool const cur_item_selected = cur_item >= 0 ?
206                 refsLB->isSelected(cur_item) : false;*/
207         bool const cur_item_selected = refsTW->isItemSelected(sel);
208
209         if (cur_item_selected)
210                 referenceED->setText(sel->text(0));
211
212         if (at_ref_)
213                 gotoRef();
214         gotoPB->setEnabled(true);
215         if (typeAllowed() && !isBufferReadonly())
216                 typeCO->setEnabled(true);
217         nameED->setHidden(!nameAllowed());
218         nameL->setHidden(!nameAllowed());
219 }
220
221
222 void GuiRef::refTextChanged(QString const & str)
223 {
224         gotoPB->setEnabled(!str.isEmpty());
225         typeCO->setEnabled(!str.isEmpty());
226         typeLA->setEnabled(!str.isEmpty());
227 }
228
229
230 void GuiRef::refSelected(QTreeWidgetItem * sel)
231 {
232         if (isBufferReadonly())
233                 return;
234
235         if (sel->childCount()) {
236                 sel->setExpanded(false);
237                 return;
238         }
239
240 /*      int const cur_item = refsTW->currentRow();
241         bool const cur_item_selected = cur_item >= 0 ?
242                 refsLB->isSelected(cur_item) : false;*/
243         bool const cur_item_selected = refsTW->isItemSelected(sel);
244
245         if (cur_item_selected)
246                 referenceED->setText(sel->text(0));
247         // <enter> or double click, inserts ref and closes dialog
248         slotOK();
249 }
250
251
252 void GuiRef::sortToggled()
253 {
254         redoRefs();
255 }
256
257
258 void GuiRef::groupToggled()
259 {
260         redoRefs();
261 }
262
263
264 void GuiRef::updateClicked()
265 {
266         updateRefs();
267 }
268
269
270 void GuiRef::dialogRejected()
271 {
272         resetDialog();
273         // We have to do this manually, instead of calling slotClose(), because
274         // the dialog has already been made invisible before rejected() triggers.
275         Dialog::disconnect();
276 }
277
278
279 void GuiRef::resetDialog()
280 {
281         at_ref_ = false;
282         setGotoRef();
283 }
284
285
286 void GuiRef::closeEvent(QCloseEvent * e)
287 {
288         slotClose();
289         resetDialog();
290         e->accept();
291 }
292
293
294 void GuiRef::updateContents()
295 {
296         int orig_type = typeCO->currentIndex();
297
298         referenceED->clear();
299         nameED->clear();
300
301         referenceED->setText(toqstr(params_["reference"]));
302         nameED->setText(toqstr(params_["name"]));
303         nameED->setHidden(!nameAllowed());
304         nameL->setHidden(!nameAllowed());
305
306         // restore type settings for new insets
307         bool const new_inset = params_["reference"].empty();
308         if (new_inset)
309                 typeCO->setCurrentIndex(orig_type);
310         else
311                 typeCO->setCurrentIndex(InsetRef::getType(params_.getCmdName()));
312         typeCO->setEnabled(typeAllowed() && !isBufferReadonly());
313         if (!typeAllowed())
314                 typeCO->setCurrentIndex(0);
315
316         pluralCB->setChecked(params_["plural"] == "true");
317         capsCB->setChecked(params_["caps"] == "true");
318         noprefixCB->setChecked(params_["noprefix"] == "true");
319
320         // insert buffer list
321         bufferCO->clear();
322         FileNameList const buffers(theBufferList().fileNames());
323         for (FileNameList::const_iterator it = buffers.begin();
324              it != buffers.end(); ++it) {
325                 bufferCO->addItem(toqstr(makeDisplayPath(it->absFileName())));
326         }
327
328         int const thebuffer = theBufferList().bufferNum(buffer().fileName());
329         // restore the buffer combo setting for new insets
330         if (new_inset && restored_buffer_ != -1
331             && restored_buffer_ < bufferCO->count() && thebuffer == active_buffer_)
332                 bufferCO->setCurrentIndex(restored_buffer_);
333         else {
334                 int const num = theBufferList().bufferNum(buffer().fileName());
335                 bufferCO->setCurrentIndex(num);
336                 if (thebuffer != active_buffer_)
337                         restored_buffer_ = num;
338         }
339         active_buffer_ = thebuffer;
340
341         updateRefs();
342         enableBoxes();
343         // Activate OK/Apply buttons if the users inserts a new ref
344         // and we have a valid pre-setting.
345         bc().setValid(isValid() && new_inset);
346 }
347
348
349 void GuiRef::applyView()
350 {
351         last_reference_ = referenceED->text();
352
353         params_.setCmdName(InsetRef::getName(typeCO->currentIndex()));
354         params_["reference"] = qstring_to_ucs4(last_reference_);
355         params_["name"] = qstring_to_ucs4(nameED->text());
356         params_["plural"] = pluralCB->isChecked() ? 
357               from_ascii("true") : from_ascii("false");
358         params_["caps"] = capsCB->isChecked() ? 
359               from_ascii("true") : from_ascii("false");
360         params_["noprefix"] = noprefixCB->isChecked() ? 
361               from_ascii("true") : from_ascii("false");
362         restored_buffer_ = bufferCO->currentIndex();
363 }
364
365
366 bool GuiRef::nameAllowed()
367 {
368         KernelDocType const doc_type = docType();
369         return doc_type != LATEX && doc_type != LITERATE;
370 }
371
372
373 bool GuiRef::typeAllowed()
374 {
375         return docType() != DOCBOOK;
376 }
377
378
379 void GuiRef::setGoBack()
380 {
381         gotoPB->setText(qt_("&Go Back"));
382         gotoPB->setToolTip(qt_("Jump back to the original cursor location"));
383 }
384
385
386 void GuiRef::setGotoRef()
387 {
388         gotoPB->setText(qt_("&Go to Label"));
389         gotoPB->setToolTip(qt_("Jump to the selected label"));
390 }
391
392
393 void GuiRef::gotoRef()
394 {
395         string ref = fromqstr(referenceED->text());
396
397         if (at_ref_) {
398                 // go back
399                 setGotoRef();
400                 gotoBookmark();
401         } else {
402                 // go to the ref
403                 setGoBack();
404                 gotoRef(ref);
405         }
406         at_ref_ = !at_ref_;
407 }
408
409 inline bool caseInsensitiveLessThan(QString const & s1, QString const & s2)
410 {
411         return s1.toLower() < s2.toLower();
412 }
413
414
415 void GuiRef::redoRefs()
416 {
417         // Prevent these widgets from emitting any signals whilst
418         // we modify their state.
419         refsTW->blockSignals(true);
420         referenceED->blockSignals(true);
421         refsTW->setUpdatesEnabled(false);
422
423         refsTW->clear();
424
425         // need this because Qt will send a highlight() here for
426         // the first item inserted
427         QString const oldSelection(referenceED->text());
428
429         QStringList refsStrings;
430         QStringList refsCategories;
431         vector<docstring>::const_iterator iter;
432         bool noprefix = false;
433         for (iter = refs_.begin(); iter != refs_.end(); ++iter) {
434                 QString const lab = toqstr(*iter);
435                 refsStrings.append(lab);
436                 if (groupCB->isChecked()) {
437                         if (lab.contains(":")) {
438                                 QString const pref = lab.split(':')[0];
439                                 if (!refsCategories.contains(pref)) {
440                                         if (!pref.isEmpty())
441                                                 refsCategories.append(pref);
442                                         else
443                                                 noprefix = true;
444                                 }
445                         }
446                         else
447                                 noprefix = true;
448                 }
449         }
450         // sort categories case-intensively
451         qSort(refsCategories.begin(), refsCategories.end(),
452               caseInsensitiveLessThan /*defined above*/);
453         if (noprefix)
454                 refsCategories.insert(0, qt_("<No prefix>"));
455
456         QString const sort = sortingCO->isEnabled() ?
457                                 sortingCO->itemData(sortingCO->currentIndex()).toString()
458                                 : QString();
459         if (sort == "nocase")
460                 qSort(refsStrings.begin(), refsStrings.end(),
461                       caseInsensitiveLessThan /*defined above*/);
462         else if (sort == "case")
463                 qSort(refsStrings.begin(), refsStrings.end());
464
465         if (groupCB->isChecked()) {
466                 QList<QTreeWidgetItem *> refsCats;
467                 for (int i = 0; i < refsCategories.size(); ++i) {
468                         QString const cat = refsCategories.at(i);
469                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
470                         item->setText(0, cat);
471                         for (int i = 0; i < refsStrings.size(); ++i) {
472                                 QString const ref = refsStrings.at(i);
473                                 if ((ref.startsWith(cat + QString(":")))
474                                     || (cat == qt_("<No prefix>")
475                                        && (!ref.mid(1).contains(":") || ref.left(1).contains(":")))) {
476                                                 QTreeWidgetItem * child =
477                                                         new QTreeWidgetItem(item);
478                                                 child->setText(0, ref);
479                                                 item->addChild(child);
480                                 }
481                         }
482                         refsCats.append(item);
483                 }
484                 refsTW->addTopLevelItems(refsCats);
485         } else {
486                 QList<QTreeWidgetItem *> refsItems;
487                 for (int i = 0; i < refsStrings.size(); ++i) {
488                         QTreeWidgetItem * item = new QTreeWidgetItem(refsTW);
489                         item->setText(0, refsStrings.at(i));
490                         refsItems.append(item);
491                 }
492                 refsTW->addTopLevelItems(refsItems);
493         }
494
495         // restore the last selection or, for new insets, highlight
496         // the previous selection
497         if (!oldSelection.isEmpty() || !last_reference_.isEmpty()) {
498                 bool const newInset = oldSelection.isEmpty();
499                 QString textToFind = newInset ? last_reference_ : oldSelection;
500                 referenceED->setText(textToFind);
501                 last_reference_.clear();
502                 QTreeWidgetItemIterator it(refsTW);
503                 while (*it) {
504                         if ((*it)->text(0) == textToFind) {
505                                 refsTW->setCurrentItem(*it);
506                                 refsTW->setItemSelected(*it, true);
507                                 //Make sure selected item is visible
508                                 refsTW->scrollToItem(*it);
509                                 last_reference_ = textToFind;
510                                 break;
511                         }
512                         ++it;
513                 }
514         }
515         refsTW->setUpdatesEnabled(true);
516         refsTW->update();
517
518         // redo filter
519         filterLabels();
520
521         // Re-activate the emission of signals by these widgets.
522         refsTW->blockSignals(false);
523         referenceED->blockSignals(false);
524
525         gotoPB->setEnabled(!referenceED->text().isEmpty());
526         typeCO->setEnabled(!referenceED->text().isEmpty());
527         typeLA->setEnabled(!referenceED->text().isEmpty());
528 }
529
530
531 void GuiRef::updateRefs()
532 {
533         refs_.clear();
534         int const the_buffer = bufferCO->currentIndex();
535         if (the_buffer != -1) {
536                 FileNameList const names(theBufferList().fileNames());
537                 FileName const & name = names[the_buffer];
538                 Buffer const * buf = theBufferList().getBuffer(name);
539                 buf->getLabelList(refs_);
540         }
541         sortingCO->setEnabled(!refs_.empty());
542         refsTW->setEnabled(!refs_.empty());
543         groupCB->setEnabled(!refs_.empty());
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"