]> 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           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                 gui_view_.activateWindow();
250         }
251 }
252
253
254 void TocWidget::goTo(QModelIndex const & index)
255 {
256         LYXERR(Debug::GUI, "goto " << index.row()
257                 << ", " << index.column());
258
259         gui_view_.tocModels().goTo(current_type_, index);
260 }
261
262
263 void TocWidget::on_updateTB_clicked()
264 {
265         // The backend update can take some time so we disable
266         // the controls while waiting.
267         enableControls(false);
268         gui_view_.currentBufferView()->buffer().updateBuffer();
269 }
270
271
272 void TocWidget::on_sortCB_stateChanged(int state)
273 {
274         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
275         updateViewNow();
276 }
277
278
279 void TocWidget::on_persistentCB_stateChanged(int state)
280 {
281         persistent_ = state == Qt::Checked;
282 }
283
284
285 #if 0
286 /* FIXME (Ugras 17/11/06):
287 I have implemented a indexDepth function to get the model indices. In my
288 opinion, somebody should derive a new qvariant class for tocModelItem
289 which saves the string data and depth information. That will save the
290 depth calculation.  */
291
292 static int indexDepth(QModelIndex const & index, int depth = -1)
293 {
294         ++depth;
295         return index.parent() == QModelIndex()
296                 ? depth : indexDepth(index.parent(), depth);
297 }
298 #endif
299
300 void TocWidget::on_depthSL_valueChanged(int depth)
301 {
302         if (depth == depth_)
303                 return;
304         setTreeDepth(depth);
305         gui_view_.setFocus();
306 }
307
308
309 void TocWidget::setTreeDepth(int depth)
310 {
311         depth_ = depth;
312         if (!tocTV->model())
313                 return;
314
315         if (depth == 0)
316                 tocTV->collapseAll();
317         else
318                 tocTV->expandToDepth(depth - 1);
319 }
320
321
322 void TocWidget::on_typeCO_currentIndexChanged(int index)
323 {
324         if (index == -1)
325                 return;
326         current_type_ = typeCO->itemData(index).toString();
327         updateViewNow();
328         if (typeCO->hasFocus())
329                 gui_view_.setFocus();
330 }
331
332
333 void TocWidget::outline(FuncCode func_code)
334 {
335         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
336         if (list.isEmpty())
337                 return;
338         enableControls(false);
339         goTo(list[0]);
340         dispatch(FuncRequest(func_code));
341         enableControls(true);
342         gui_view_.setFocus();
343 }
344
345
346 void TocWidget::on_moveUpTB_clicked()
347 {
348         outline(LFUN_OUTLINE_UP);
349 }
350
351
352 void TocWidget::on_moveDownTB_clicked()
353 {
354         outline(LFUN_OUTLINE_DOWN);
355 }
356
357
358 void TocWidget::on_moveInTB_clicked()
359 {
360         outline(LFUN_OUTLINE_IN);
361 }
362
363
364 void TocWidget::on_moveOutTB_clicked()
365 {
366         outline(LFUN_OUTLINE_OUT);
367 }
368
369
370 void TocWidget::select(QModelIndex const & index)
371 {
372         if (!index.isValid()) {
373                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
374                 return;
375         }
376
377         tocTV->scrollTo(index);
378         tocTV->clearSelection();
379         tocTV->setCurrentIndex(index);
380 }
381
382
383 void TocWidget::enableControls(bool enable)
384 {
385         updateTB->setEnabled(enable);
386
387         if (!canOutline())
388                 enable = false;
389
390         moveUpTB->setEnabled(enable);
391         moveDownTB->setEnabled(enable);
392         moveInTB->setEnabled(enable);
393         moveOutTB->setEnabled(enable);
394 }
395
396
397 void TocWidget::updateView()
398 {
399         // Subtler optimization for having the delay more UI invisible.
400         // We trigger update immediately for sparse editation actions,
401         // i.e. there was no editation/cursor movement in last 2 sec.
402         // At worst there will be +1 redraw after 2s in a such "calm" mode.
403         if (!update_timer_long_->isActive())
404                 update_timer_short_->start();
405         // resets the timer to trigger after 2s
406         update_timer_long_->start();
407 }
408
409
410 void TocWidget::updateViewNow()
411 {
412         update_timer_long_->stop();
413         update_timer_short_->start();
414 }
415
416
417 void TocWidget::realUpdateView()
418 {
419         if (!gui_view_.documentBufferView()) {
420                 tocTV->setModel(0);
421                 depthSL->setMaximum(0);
422                 depthSL->setValue(0);
423                 setEnabled(false);
424                 return;
425         }
426         setEnabled(true);
427         bool const is_sortable = isSortable();
428         sortCB->setEnabled(is_sortable);
429         bool focus_ = tocTV->hasFocus();
430         tocTV->setEnabled(false);
431         tocTV->setUpdatesEnabled(false);
432
433         QAbstractItemModel * toc_model =
434                         gui_view_.tocModels().model(current_type_);
435         if (tocTV->model() != toc_model) {
436                 tocTV->setModel(toc_model);
437                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
438                 if (persistent_)
439                         setTreeDepth(depth_);
440         }
441
442         sortCB->blockSignals(true);
443         sortCB->setChecked(is_sortable
444                 && gui_view_.tocModels().isSorted(current_type_));
445         sortCB->blockSignals(false);
446
447         bool const can_navigate_ = canNavigate();
448         persistentCB->setEnabled(can_navigate_);
449
450         bool controls_enabled = toc_model && toc_model->rowCount() > 0
451                 && !gui_view_.documentBufferView()->buffer().isReadonly();
452         enableControls(controls_enabled);
453
454         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
455         depthSL->setValue(depth_);
456         if (!persistent_ && can_navigate_)
457                 setTreeDepth(depth_);
458         if (can_navigate_) {
459                 persistentCB->setChecked(persistent_);
460                 select(gui_view_.tocModels().currentIndex(current_type_));
461         }
462         filterContents();
463         tocTV->setEnabled(true);
464         tocTV->setUpdatesEnabled(true);
465         if (focus_)
466                 tocTV->setFocus();
467 }
468
469
470 void TocWidget::checkModelChanged()
471 {
472         if (!gui_view_.documentBufferView() ||
473             gui_view_.tocModels().model(current_type_) != tocTV->model())
474                 realUpdateView();
475 }
476
477
478 void TocWidget::filterContents()
479 {
480         if (!tocTV->model())
481                 return;
482
483         QModelIndexList indices = tocTV->model()->match(
484                 tocTV->model()->index(0, 0),
485                 Qt::DisplayRole, "*", -1,
486                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
487
488         int size = indices.size();
489         for (int i = 0; i < size; i++) {
490                 QModelIndex index = indices[i];
491                 bool const matches =
492                         index.data().toString().contains(
493                                 filterLE->text(), Qt::CaseInsensitive);
494                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
495         }
496         // recursively unhide parents of unhidden children
497         for (int i = size - 1; i >= 0; i--) {
498                 QModelIndex index = indices[i];
499                 if (!tocTV->isRowHidden(index.row(), index.parent())
500                     && index.parent() != QModelIndex())
501                         tocTV->setRowHidden(index.parent().row(),
502                                             index.parent().parent(), false);
503         }
504 }
505
506
507 static QString decodeType(QString const & str)
508 {
509         QString type = str;
510         if (type.contains("tableofcontents"))
511                 type = "tableofcontents";
512         else if (type.contains("lstlistoflistings"))
513                 type = "listing";
514         else if (type.contains("floatlist")) {
515                 if (type.contains("\"figure"))
516                         type = "figure";
517                 else if (type.contains("\"table"))
518                         type = "table";
519                 else if (type.contains("\"algorithm"))
520                         type = "algorithm";
521         }
522         return type;
523 }
524
525
526 void TocWidget::init(QString const & str)
527 {
528         int new_index;
529         if (str.isEmpty())
530                 new_index = typeCO->findData(current_type_);
531         else
532                 new_index = typeCO->findData(decodeType(str));
533
534         // If everything else fails, settle on the table of contents which is
535         // guaranteed to exist.
536         if (new_index == -1) {
537                 current_type_ = "tableofcontents";
538                 new_index = typeCO->findData(current_type_);
539         } else {
540                 current_type_ = typeCO->itemData(new_index).toString();
541         }
542
543         typeCO->blockSignals(true);
544         typeCO->setCurrentIndex(new_index);
545         typeCO->blockSignals(false);
546 }
547
548 } // namespace frontend
549 } // namespace lyx
550
551 #include "moc_TocWidget.cpp"