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