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