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