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