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