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