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