]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/TocWidget.cpp
573e232993d80705f92e33134343f8b70984d752
[lyx.git] / src / frontends / qt / TocWidget.cpp
1 /**
2  * \file TocWidget.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 Abdelrazak Younes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "TocWidget.h"
15
16 #include "GuiApplication.h"
17 #include "GuiView.h"
18 #include "qt_helpers.h"
19 #include "TocModel.h"
20 #include "FancyLineEdit.h"
21
22 #include "Buffer.h"
23 #include "BufferView.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LyX.h"
29 #include "Menus.h"
30 #include "TocBackend.h"
31
32 #include "insets/InsetCommand.h"
33 #include "insets/InsetRef.h"
34
35 #include "support/debug.h"
36 #include "support/lassert.h"
37
38 #include <QHeaderView>
39 #include <QMenu>
40 #include <QTimer>
41
42 #include <vector>
43
44 using namespace std;
45
46 namespace lyx {
47 namespace frontend {
48
49 TocWidget::TocWidget(GuiView & gui_view, QWidget * parent)
50         : QWidget(parent), depth_(0), persistent_(false), gui_view_(gui_view),
51           timer_(new QTimer(this))
52 {
53         setupUi(this);
54
55         moveOutTB->setIcon(QIcon(getPixmap("images/", "outline-out", "svgz,png")));
56         moveInTB->setIcon(QIcon(getPixmap("images/", "outline-in", "svgz,png")));
57         moveUpTB->setIcon(QIcon(getPixmap("images/", "outline-up", "svgz,png")));
58         moveDownTB->setIcon(QIcon(getPixmap("images/", "outline-down", "svgz,png")));
59         updateTB->setIcon(QIcon(getPixmap("images/", "reload", "svgz,png")));
60
61         QSize icon_size = gui_view.iconSize();
62         moveOutTB->setIconSize(icon_size);
63         moveInTB->setIconSize(icon_size);
64         moveUpTB->setIconSize(icon_size);
65         moveDownTB->setIconSize(icon_size);
66         updateTB->setIconSize(icon_size);
67
68         // avoid flickering
69         tocTV->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
70
71         tocTV->showColumn(0);
72
73         // hide the pointless QHeader for now
74         // in the future, new columns may appear
75         // like labels, bookmarks, etc...
76         // tocTV->header()->hide();
77         tocTV->header()->setVisible(false);
78
79         // Only one item selected at a time.
80         tocTV->setSelectionMode(QAbstractItemView::SingleSelection);
81
82         // The toc types combo won't change its model.
83         typeCO->setModel(gui_view_.tocModels().nameModel());
84
85         // The filter bar
86         filter_ = new FancyLineEdit(this);
87         filter_->setClearButton(true);
88         filter_->setPlaceholderText(qt_("All items"));
89         filterBarL->addWidget(filter_, 0);
90         filterLA->setBuddy(filter_);
91         setFocusProxy(filter_);
92
93         // Make sure the buttons are disabled when first shown without a loaded
94         // Buffer.
95         enableControls(false);
96
97         // make us responsible for the context menu of the tabbar
98         setContextMenuPolicy(Qt::CustomContextMenu);
99         connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
100                 this, SLOT(showContextMenu(const QPoint &)));
101         connect(tocTV, SIGNAL(customContextMenuRequested(const QPoint &)),
102                 this, SLOT(showContextMenu(const QPoint &)));
103         connect(filter_, SIGNAL(textEdited(QString)),
104                 this, SLOT(filterContents()));
105 #if (QT_VERSION < 0x050000)
106         connect(filter_, SIGNAL(downPressed()),
107                 tocTV, SLOT(setFocus()));
108 #else
109         connect(filter_, &FancyLineEdit::downPressed,
110                 tocTV, [this](){ focusAndHighlight(tocTV); });
111 #endif
112         connect(activeFilterCO, SIGNAL(activated(int)),
113                 this, SLOT(filterContents()));
114
115         // setting the update timer
116         timer_->setSingleShot(true);
117         connect(timer_, SIGNAL(timeout()), this, SLOT(finishUpdateView()));
118
119         init(QString());
120 }
121
122
123 void TocWidget::showContextMenu(const QPoint & pos)
124 {
125         std::string name = "context-toc-" + fromqstr(current_type_);
126         QMenu * menu = guiApp->menus().menu(toqstr(name), gui_view_);
127         if (!menu)
128                 return;
129         menu->exec(mapToGlobal(pos));
130 }
131
132
133 Inset * TocWidget::itemInset() const
134 {
135         QModelIndex const & index = tocTV->currentIndex();
136         TocItem const & item =
137                 gui_view_.tocModels().currentItem(current_type_, index);
138         DocIterator const & dit = item.dit();
139
140         Inset * inset = nullptr;
141         if (current_type_ == "label"
142                   || current_type_ == "graphics"
143                   || current_type_ == "citation"
144                   || current_type_ == "child")
145                 inset = dit.nextInset();
146
147         else if (current_type_ == "branch"
148                          || current_type_ == "index"
149                          || current_type_ == "change"
150                          || current_type_ == "table"
151                      || current_type_ == "listing"
152                      || current_type_ == "figure")
153                 inset = &dit.inset();
154
155         return inset;
156 }
157
158
159 bool TocWidget::getStatus(Cursor & cur, FuncRequest const & cmd,
160         FuncStatus & status) const
161 {
162         Inset * inset = itemInset();
163         FuncRequest tmpcmd(cmd);
164
165         QModelIndex const & index = tocTV->currentIndex();
166         TocItem const & item =
167                 gui_view_.tocModels().currentItem(current_type_, index);
168
169         switch (cmd.action())
170         {
171         case LFUN_CHANGE_ACCEPT:
172         case LFUN_CHANGE_REJECT:
173         case LFUN_OUTLINE_UP:
174         case LFUN_OUTLINE_DOWN:
175         case LFUN_OUTLINE_IN:
176         case LFUN_OUTLINE_OUT:
177         case LFUN_SECTION_SELECT:
178                 status.setEnabled((bool)item.dit());
179                 return true;
180
181         case LFUN_LABEL_COPY_AS_REFERENCE: {
182                 // For labels in math, we need to supply the label as a string
183                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.str());
184                 if (inset)
185                         return inset->getStatus(cur, label_copy, status);
186                 break;
187         }
188
189         default:
190                 if (inset)
191                         return inset->getStatus(cur, tmpcmd, status);
192         }
193
194         return false;
195 }
196
197
198 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd,
199                 DispatchResult & dr)
200 {
201
202         Inset * inset = itemInset();
203
204         QModelIndex const & index = tocTV->currentIndex();
205         TocItem const & item =
206                 gui_view_.tocModels().currentItem(current_type_, index);
207
208         // Start an undo group.
209         cur.beginUndoGroup();
210
211         switch (cmd.action())
212         {
213         case LFUN_CHANGE_ACCEPT:
214         case LFUN_CHANGE_REJECT: {
215                 // The action is almost always LYX_UNKNOWN_ACTION, which will
216                 // have the effect of moving the cursor to the location of
217                 // the change. (See TocItem::action.)
218                 dispatch(item.action());
219                 // If we do not reset the origin, then the request will be sent back
220                 // here, and we are in an infinite loop. But we need the dispatch
221                 // machinery to clean up for us, if the cursor is in an inset that
222                 // will be deleted. See bug #10316.
223                 FuncRequest tmpcmd(cmd);
224                 tmpcmd.setOrigin(FuncRequest::INTERNAL);
225                 dispatch(tmpcmd);
226                 dr.forceBufferUpdate();
227                 break;
228         }
229
230         case LFUN_SECTION_SELECT:
231                 dispatch(item.action());
232                 cur.dispatch(cmd);
233                 // necessary to get the selection drawn.
234                 cur.buffer()->changed(true);
235                 gui_view_.setFocus();
236                 break;
237
238         case LFUN_LABEL_COPY_AS_REFERENCE: {
239                 // For labels in math, we need to supply the label as a string
240                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.str());
241                 if (inset)
242                         inset->dispatch(cur, label_copy);
243                 break;
244         }
245
246         case LFUN_OUTLINE_UP:
247         case LFUN_OUTLINE_DOWN:
248         case LFUN_OUTLINE_IN:
249         case LFUN_OUTLINE_OUT:
250                 outline(cmd.action());
251                 break;
252
253         default: {
254                 FuncRequest tmpcmd(cmd);
255                 if (inset)
256                         inset->dispatch(cur, tmpcmd);
257         }
258         }
259         cur.endUndoGroup();
260 }
261
262
263 void TocWidget::on_tocTV_activated(QModelIndex const & index)
264 {
265         goTo(index);
266 }
267
268
269 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
270 {
271
272         Qt::MouseButtons const button = QApplication::mouseButtons();
273         if (button & Qt::LeftButton) {
274                 goTo(index);
275                 gui_view_.setFocus();
276                 gui_view_.activateWindow();
277         }
278 }
279
280
281 void TocWidget::goTo(QModelIndex const & index)
282 {
283         LYXERR(Debug::GUI, "goto " << index.row()
284                 << ", " << index.column());
285
286         sendDispatch(gui_view_.tocModels().goTo(current_type_, index));
287 }
288
289
290 void TocWidget::on_updateTB_clicked()
291 {
292         // The backend update can take some time so we disable
293         // the controls while waiting.
294         enableControls(false);
295         gui_view_.currentBufferView()->buffer().updateBuffer();
296 }
297
298
299 void TocWidget::on_sortCB_stateChanged(int state)
300 {
301         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
302         updateViewNow();
303 }
304
305
306 void TocWidget::on_persistentCB_stateChanged(int state)
307 {
308         persistent_ = state == Qt::Checked;
309 }
310
311
312 #if 0
313 /* FIXME (Ugras 17/11/06):
314 I have implemented a indexDepth function to get the model indices. In my
315 opinion, somebody should derive a new qvariant class for tocModelItem
316 which saves the string data and depth information. That will save the
317 depth calculation.  */
318
319 static int indexDepth(QModelIndex const & index, int depth = -1)
320 {
321         ++depth;
322         return index.parent() == QModelIndex()
323                 ? depth : indexDepth(index.parent(), depth);
324 }
325 #endif
326
327 void TocWidget::on_depthSL_valueChanged(int depth)
328 {
329         if (depth == depth_)
330                 return;
331         setTreeDepth(depth);
332         gui_view_.setFocus();
333 }
334
335
336 void TocWidget::setTreeDepth(int depth)
337 {
338         depth_ = depth;
339         if (!tocTV->model())
340                 return;
341
342         if (depth == 0)
343                 tocTV->collapseAll();
344         else
345                 tocTV->expandToDepth(depth - 1);
346 }
347
348
349 void TocWidget::on_typeCO_activated(int index)
350 {
351         if (index == -1)
352                 return;
353         current_type_ = typeCO->itemData(index).toString();
354         updateViewNow();
355         if (typeCO->hasFocus())
356                 gui_view_.setFocus();
357 }
358
359
360 void TocWidget::outline(FuncCode func_code)
361 {
362         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
363         if (list.isEmpty())
364                 return;
365
366         //if another window is active, this attempt will fail,
367         //but it will work at least for the second attempt
368         gui_view_.activateWindow();
369
370         enableControls(false);
371         goTo(list[0]);
372         sendDispatch(FuncRequest(func_code));
373         enableControls(true);
374         gui_view_.setFocus();
375 }
376
377
378 void TocWidget::sendDispatch(FuncRequest fr)
379 {
380
381         fr.setViewOrigin(&gui_view_);
382         GuiWorkArea * old_wa = gui_view_.currentWorkArea();
383         GuiWorkArea * doc_wa = gui_view_.currentMainWorkArea();
384         /* The ToC command should be dispatched to the document work area,
385          * not the Adv. Find&Replace (which is the only other know
386          * possibility.
387          */
388         if (doc_wa != nullptr && doc_wa != old_wa)
389                 gui_view_.setCurrentWorkArea(doc_wa);
390         DispatchResult const & dr = dispatch(fr);
391         /* If the current workarea has not explicitely changed, and the
392          * original one is still visible, let's reset it.
393          */
394         if (gui_view_.currentWorkArea() == doc_wa
395              && gui_view_.hasVisibleWorkArea(old_wa)
396              && doc_wa != old_wa)
397                 gui_view_.setCurrentWorkArea(old_wa);
398         if (dr.error())
399                 gui_view_.message(dr.message());
400 }
401
402
403 void TocWidget::on_moveUpTB_clicked()
404 {
405         outline(LFUN_OUTLINE_UP);
406 }
407
408
409 void TocWidget::on_moveDownTB_clicked()
410 {
411         outline(LFUN_OUTLINE_DOWN);
412 }
413
414
415 void TocWidget::on_moveInTB_clicked()
416 {
417         outline(LFUN_OUTLINE_IN);
418 }
419
420
421 void TocWidget::on_moveOutTB_clicked()
422 {
423         outline(LFUN_OUTLINE_OUT);
424 }
425
426
427 void TocWidget::select(QModelIndex const & index)
428 {
429         if (!index.isValid()) {
430                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
431                 return;
432         }
433
434         tocTV->scrollTo(index);
435         tocTV->clearSelection();
436         tocTV->setCurrentIndex(index);
437 }
438
439
440 void TocWidget::enableControls(bool enable)
441 {
442         updateTB->setEnabled(enable);
443
444         if (!canOutline())
445                 enable = false;
446
447         moveUpTB->setEnabled(enable);
448         moveDownTB->setEnabled(enable);
449         moveInTB->setEnabled(enable);
450         moveOutTB->setEnabled(enable);
451 }
452
453
454 void TocWidget::updateView()
455 {
456         if (!gui_view_.documentBufferView()) {
457                 tocTV->setModel(nullptr);
458                 depthSL->setMaximum(0);
459                 depthSL->setValue(0);
460                 setEnabled(false);
461                 return;
462         }
463         setEnabled(true);
464         bool const is_sortable = isSortable();
465         sortCB->setEnabled(is_sortable);
466         bool focus = tocTV->hasFocus();
467         tocTV->setEnabled(false);
468         tocTV->setUpdatesEnabled(false);
469
470         QAbstractItemModel * toc_model =
471                         gui_view_.tocModels().model(current_type_);
472         if (tocTV->model() != toc_model) {
473                 tocTV->setModel(toc_model);
474                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
475                 if (persistent_)
476                         setTreeDepth(depth_);
477         }
478
479         sortCB->blockSignals(true);
480         sortCB->setChecked(is_sortable
481                 && gui_view_.tocModels().isSorted(current_type_));
482         sortCB->blockSignals(false);
483
484         persistentCB->setEnabled(canNavigate());
485
486         bool controls_enabled = toc_model && toc_model->rowCount() > 0
487                 && !gui_view_.documentBufferView()->buffer().isReadonly();
488         enableControls(controls_enabled);
489
490         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
491         depthSL->setValue(depth_);
492         tocTV->setEnabled(true);
493         tocTV->setUpdatesEnabled(true);
494         if (focus)
495                 tocTV->setFocus();
496
497         // Expensive operations are on a timer.  We finish the update immediately
498         // for sparse edition actions, i.e. there was no edition/cursor movement
499         // recently, then every 300ms.
500         if (!timer_->isActive()) {
501                 finishUpdateView();
502                 timer_->start(300);
503         }
504 }
505
506
507 void TocWidget::updateViewNow()
508 {
509         timer_->stop();
510         updateView();
511 }
512
513
514 void TocWidget::finishUpdateView()
515 {
516         // Profiling shows that this is the expensive stuff in the context of typing
517         // text and moving with arrows. For bigger operations, this is negligible,
518         // and outweighted by TocModels::reset() anyway.
519         if (canNavigate()) {
520                 if (!persistent_)
521                         setTreeDepth(depth_);
522                 persistentCB->setChecked(persistent_);
523                 // select the item at current cursor location
524                 if (gui_view_.documentBufferView()) {
525                         DocIterator const & dit = gui_view_.documentBufferView()->cursor();
526                         select(gui_view_.tocModels().currentIndex(current_type_, dit));
527                 }
528         }
529         filterContents();
530 }
531
532
533 void TocWidget::filterContents()
534 {
535         if (!tocTV->model())
536                 return;
537
538         QModelIndexList indices = tocTV->model()->match(
539                 tocTV->model()->index(0, 0),
540                 Qt::DisplayRole, ".*", -1,
541 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
542                 Qt::MatchFlags(Qt::MatchRegularExpression|Qt::MatchRecursive));
543 #else
544                 // deprecated in Qt 5.15.
545                 Qt::MatchFlags(Qt::MatchRegExp|Qt::MatchRecursive));
546 #endif
547
548         bool const show_active =
549                 activeFilterCO->currentIndex() != 2;
550         bool const show_inactive =
551                 activeFilterCO->currentIndex() != 1;
552
553         int size = indices.size();
554         QString const matchstring = filter_ ? filter_->text() : QString();
555         for (int i = 0; i < size; i++) {
556                 QModelIndex index = indices[i];
557                 bool matches = index.data().toString().contains(
558                                         matchstring, Qt::CaseInsensitive);
559                 TocItem const & item =
560                         gui_view_.tocModels().currentItem(current_type_, index);
561                 matches &= (show_active && item.isOutput()) || (show_inactive && !item.isOutput());
562                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
563         }
564         // recursively unhide parents of unhidden children
565         for (int i = size - 1; i >= 0; i--) {
566                 QModelIndex index = indices[i];
567                 if (!tocTV->isRowHidden(index.row(), index.parent())
568                     && index.parent() != QModelIndex())
569                         tocTV->setRowHidden(index.parent().row(),
570                                             index.parent().parent(), false);
571         }
572 }
573
574
575 static QString decodeType(QString const & str)
576 {
577         QString type = str;
578         if (type.contains("tableofcontents"))
579                 type = "tableofcontents";
580         else if (type.contains("lstlistoflistings"))
581                 type = "listing";
582         else if (type.contains("floatlist")) {
583                 if (type.contains("\"figure"))
584                         type = "figure";
585                 else if (type.contains("\"table"))
586                         type = "table";
587                 else if (type.contains("\"algorithm"))
588                         type = "algorithm";
589         }
590         return type;
591 }
592
593
594 void TocWidget::init(QString const & str)
595 {
596         int new_index;
597         if (str.isEmpty())
598                 new_index = typeCO->findData(current_type_);
599         else
600                 new_index = typeCO->findData(decodeType(str));
601
602         // If everything else fails, settle on the table of contents which is
603         // guaranteed to exist.
604         if (new_index == -1) {
605                 current_type_ = "tableofcontents";
606                 new_index = typeCO->findData(current_type_);
607         } else {
608                 current_type_ = typeCO->itemData(new_index).toString();
609         }
610
611         typeCO->blockSignals(true);
612         typeCO->setCurrentIndex(new_index);
613         typeCO->blockSignals(false);
614         updateViewNow();
615 }
616
617 } // namespace frontend
618 } // namespace lyx
619
620 #include "moc_TocWidget.cpp"