3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Abdelrazak Younes
9 * Full author contact details are available in file CREDITS.
14 #include "TocWidget.h"
16 #include "GuiApplication.h"
18 #include "qt_helpers.h"
20 #include "FancyLineEdit.h"
23 #include "BufferView.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
30 #include "TocBackend.h"
32 #include "insets/InsetCommand.h"
33 #include "insets/InsetRef.h"
35 #include "support/debug.h"
36 #include "support/lassert.h"
38 #include <QHeaderView>
49 TocWidget::TocWidget(GuiView & gui_view, QWidget * parent)
50 : QWidget(parent), depth_(0), persistent_(false), keep_expanded_(false),
51 gui_view_(gui_view), timer_(new QTimer(this))
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")));
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);
69 tocTV->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
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);
79 // Only one item selected at a time.
80 tocTV->setSelectionMode(QAbstractItemView::SingleSelection);
82 // The toc types combo won't change its model.
83 typeCO->setModel(gui_view_.tocModels().nameModel());
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_);
93 // Make sure the buttons are disabled when first shown without a loaded
95 enableControls(false);
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()));
110 // setting the update timer
111 timer_->setSingleShot(true);
112 connect(timer_, SIGNAL(timeout()), this, SLOT(finishUpdateView()));
118 void TocWidget::showContextMenu(const QPoint & pos)
120 std::string name = "context-toc-" + fromqstr(current_type_);
121 QMenu * menu = guiApp->menus().menu(toqstr(name), gui_view_);
124 menu->exec(mapToGlobal(pos));
128 Inset * TocWidget::itemInset() const
130 QModelIndex const & index = tocTV->currentIndex();
131 TocItem const & item =
132 gui_view_.tocModels().currentItem(current_type_, index);
133 DocIterator const & dit = item.dit();
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();
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();
154 bool TocWidget::getStatus(Cursor & cur, FuncRequest const & cmd,
155 FuncStatus & status) const
157 Inset * inset = itemInset();
158 FuncRequest tmpcmd(cmd);
160 QModelIndex const & index = tocTV->currentIndex();
161 TocItem const & item =
162 gui_view_.tocModels().currentItem(current_type_, index);
164 switch (cmd.action())
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());
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());
180 return inset->getStatus(cur, label_copy, status);
186 return inset->getStatus(cur, tmpcmd, status);
193 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd,
197 Inset * inset = itemInset();
199 QModelIndex const & index = tocTV->currentIndex();
200 TocItem const & item =
201 gui_view_.tocModels().currentItem(current_type_, index);
203 // Start an undo group.
204 cur.beginUndoGroup();
206 switch (cmd.action())
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);
221 dr.forceBufferUpdate();
225 case LFUN_SECTION_SELECT:
226 dispatch(item.action());
228 // necessary to get the selection drawn.
229 cur.buffer()->changed(true);
230 gui_view_.setFocus();
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());
237 inset->dispatch(cur, label_copy);
241 case LFUN_OUTLINE_UP:
242 case LFUN_OUTLINE_DOWN:
243 case LFUN_OUTLINE_IN:
244 case LFUN_OUTLINE_OUT:
245 outline(cmd.action());
249 FuncRequest tmpcmd(cmd);
251 inset->dispatch(cur, tmpcmd);
258 void TocWidget::on_tocTV_activated(QModelIndex const & index)
264 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
266 DocIterator const & dit = gui_view_.documentBufferView()->cursor();
267 keep_expanded_ = gui_view_.tocModels().currentIndex(current_type_, dit) == index;
268 Qt::MouseButtons const button = QApplication::mouseButtons();
269 if (button & Qt::LeftButton) {
271 gui_view_.setFocus();
272 gui_view_.activateWindow();
277 void TocWidget::on_tocTV_doubleClicked(QModelIndex const &)
279 keep_expanded_ = true;
283 void TocWidget::goTo(QModelIndex const & index)
285 LYXERR(Debug::GUI, "goto " << index.row()
286 << ", " << index.column());
288 sendDispatch(gui_view_.tocModels().goTo(current_type_, index));
292 void TocWidget::on_updateTB_clicked()
294 // The backend update can take some time so we disable
295 // the controls while waiting.
296 enableControls(false);
297 gui_view_.currentBufferView()->buffer().updateBuffer();
301 void TocWidget::on_sortCB_stateChanged(int state)
303 gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
308 void TocWidget::on_persistentCB_stateChanged(int state)
310 persistent_ = state == Qt::Checked;
315 /* FIXME (Ugras 17/11/06):
316 I have implemented a indexDepth function to get the model indices. In my
317 opinion, somebody should derive a new qvariant class for tocModelItem
318 which saves the string data and depth information. That will save the
319 depth calculation. */
321 static int indexDepth(QModelIndex const & index, int depth = -1)
324 return index.parent() == QModelIndex()
325 ? depth : indexDepth(index.parent(), depth);
329 void TocWidget::on_depthSL_valueChanged(int depth)
334 gui_view_.setFocus();
338 void TocWidget::setTreeDepth(int depth)
345 tocTV->collapseAll();
347 tocTV->expandToDepth(depth - 1);
351 void TocWidget::on_typeCO_activated(int index)
355 current_type_ = typeCO->itemData(index).toString();
357 if (typeCO->hasFocus())
358 gui_view_.setFocus();
362 void TocWidget::outline(FuncCode func_code)
364 QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
368 //if another window is active, this attempt will fail,
369 //but it will work at least for the second attempt
370 gui_view_.activateWindow();
372 enableControls(false);
374 sendDispatch(FuncRequest(func_code));
375 enableControls(true);
376 gui_view_.setFocus();
380 void TocWidget::sendDispatch(FuncRequest fr)
383 fr.setViewOrigin(&gui_view_);
384 GuiWorkArea * old_wa = gui_view_.currentWorkArea();
385 GuiWorkArea * doc_wa = gui_view_.currentMainWorkArea();
386 /* The ToC command should be dispatched to the document work area,
387 * not the Adv. Find&Replace (which is the only other know
390 if (doc_wa != nullptr && doc_wa != old_wa)
391 gui_view_.setCurrentWorkArea(doc_wa);
392 DispatchResult const & dr = dispatch(fr);
393 /* If the current workarea has not explicitely changed, and the
394 * original one is still visible, let's reset it.
396 if (gui_view_.currentWorkArea() == doc_wa
397 && gui_view_.hasVisibleWorkArea(old_wa)
399 gui_view_.setCurrentWorkArea(old_wa);
401 gui_view_.message(dr.message());
405 void TocWidget::on_moveUpTB_clicked()
407 outline(LFUN_OUTLINE_UP);
411 void TocWidget::on_moveDownTB_clicked()
413 outline(LFUN_OUTLINE_DOWN);
417 void TocWidget::on_moveInTB_clicked()
419 outline(LFUN_OUTLINE_IN);
423 void TocWidget::on_moveOutTB_clicked()
425 outline(LFUN_OUTLINE_OUT);
429 void TocWidget::select(QModelIndex const & index)
431 if (!index.isValid()) {
432 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
436 tocTV->scrollTo(index);
437 tocTV->clearSelection();
438 tocTV->setCurrentIndex(index);
442 void TocWidget::enableControls(bool enable)
444 updateTB->setEnabled(enable);
449 moveUpTB->setEnabled(enable);
450 moveDownTB->setEnabled(enable);
451 moveInTB->setEnabled(enable);
452 moveOutTB->setEnabled(enable);
456 void TocWidget::updateView()
458 if (!gui_view_.documentBufferView()) {
459 tocTV->setModel(nullptr);
460 depthSL->setMaximum(0);
461 depthSL->setValue(0);
466 bool const is_sortable = isSortable();
467 sortCB->setEnabled(is_sortable);
468 bool focus = tocTV->hasFocus();
469 tocTV->setEnabled(false);
470 tocTV->setUpdatesEnabled(false);
472 QAbstractItemModel * toc_model =
473 gui_view_.tocModels().model(current_type_);
474 if (tocTV->model() != toc_model) {
475 tocTV->setModel(toc_model);
476 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
478 setTreeDepth(depth_);
481 sortCB->blockSignals(true);
482 sortCB->setChecked(is_sortable
483 && gui_view_.tocModels().isSorted(current_type_));
484 sortCB->blockSignals(false);
486 persistentCB->setEnabled(canNavigate());
488 bool controls_enabled = toc_model && toc_model->rowCount() > 0
489 && !gui_view_.documentBufferView()->buffer().isReadonly();
490 enableControls(controls_enabled);
492 depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
493 depthSL->setValue(depth_);
494 tocTV->setEnabled(true);
495 tocTV->setUpdatesEnabled(true);
499 // Expensive operations are on a timer. We finish the update immediately
500 // for sparse edition actions, i.e. there was no edition/cursor movement
501 // recently, then every 300ms.
502 if (!timer_->isActive() && !keep_expanded_) {
506 keep_expanded_ = false;
510 void TocWidget::updateViewNow()
517 void TocWidget::finishUpdateView()
519 // Profiling shows that this is the expensive stuff in the context of typing
520 // text and moving with arrows. For bigger operations, this is negligible,
521 // and outweighted by TocModels::reset() anyway.
523 if (!persistent_ && !keep_expanded_)
524 setTreeDepth(depth_);
525 keep_expanded_ = false;
526 persistentCB->setChecked(persistent_);
527 // select the item at current cursor location
528 if (gui_view_.documentBufferView()) {
529 DocIterator const & dit = gui_view_.documentBufferView()->cursor();
530 select(gui_view_.tocModels().currentIndex(current_type_, dit));
537 void TocWidget::filterContents()
542 QModelIndexList indices = tocTV->model()->match(
543 tocTV->model()->index(0, 0),
544 Qt::DisplayRole, ".*", -1,
545 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
546 Qt::MatchFlags(Qt::MatchRegularExpression|Qt::MatchRecursive));
548 // deprecated in Qt 5.15.
549 Qt::MatchFlags(Qt::MatchRegExp|Qt::MatchRecursive));
552 bool const show_active =
553 activeFilterCO->currentIndex() != 2;
554 bool const show_inactive =
555 activeFilterCO->currentIndex() != 1;
557 int size = indices.size();
558 QString const matchstring = filter_ ? filter_->text() : QString();
559 for (int i = 0; i < size; i++) {
560 QModelIndex index = indices[i];
561 bool matches = index.data().toString().contains(
562 matchstring, Qt::CaseInsensitive);
563 TocItem const & item =
564 gui_view_.tocModels().currentItem(current_type_, index);
565 matches &= (show_active && item.isOutput()) || (show_inactive && !item.isOutput());
566 tocTV->setRowHidden(index.row(), index.parent(), !matches);
568 // recursively unhide parents of unhidden children
569 for (int i = size - 1; i >= 0; i--) {
570 QModelIndex index = indices[i];
571 if (!tocTV->isRowHidden(index.row(), index.parent())
572 && index.parent() != QModelIndex())
573 tocTV->setRowHidden(index.parent().row(),
574 index.parent().parent(), false);
579 static QString decodeType(QString const & str)
582 if (type.contains("tableofcontents"))
583 type = "tableofcontents";
584 else if (type.contains("lstlistoflistings"))
586 else if (type.contains("floatlist")) {
587 if (type.contains("\"figure"))
589 else if (type.contains("\"table"))
591 else if (type.contains("\"algorithm"))
598 void TocWidget::init(QString const & str)
602 new_index = typeCO->findData(current_type_);
604 new_index = typeCO->findData(decodeType(str));
606 // If everything else fails, settle on the table of contents which is
607 // guaranteed to exist.
608 if (new_index == -1) {
609 current_type_ = "tableofcontents";
610 new_index = typeCO->findData(current_type_);
612 current_type_ = typeCO->itemData(new_index).toString();
615 typeCO->blockSignals(true);
616 typeCO->setCurrentIndex(new_index);
617 typeCO->blockSignals(false);
621 } // namespace frontend
624 #include "moc_TocWidget.cpp"