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