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