]> git.lyx.org Git - features.git/blob - src/frontends/qt4/TocWidget.cpp
Fix bug #3871: Shortcut to switch from TOC to text pane.
[features.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 using namespace std;
43
44 namespace lyx {
45 namespace frontend {
46
47 TocWidget::TocWidget(GuiView & gui_view, QWidget * parent)
48         : QWidget(parent), depth_(0), persistent_(false), gui_view_(gui_view)
49 {
50         setupUi(this);
51
52         moveOutTB->setIcon(QIcon(getPixmap("images/", "promote", "png")));
53         moveInTB->setIcon(QIcon(getPixmap("images/", "demote", "png")));
54         moveUpTB->setIcon(QIcon(getPixmap("images/", "up", "png")));
55         moveDownTB->setIcon(QIcon(getPixmap("images/", "down", "png")));
56         updateTB->setIcon(QIcon(getPixmap("images/", "reload", "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         init(QString());
90 }
91
92
93 void TocWidget::showContextMenu(const QPoint & pos)
94 {
95         std::string name = "context-toc-" + fromqstr(current_type_);
96         QMenu * menu = guiApp->menus().menu(toqstr(name), gui_view_);
97         if (!menu)
98                 return; 
99         menu->exec(mapToGlobal(pos));
100 }
101
102
103 Inset * TocWidget::itemInset() const
104 {
105         QModelIndex const & index = tocTV->currentIndex();
106         TocItem const & item =
107                 gui_view_.tocModels().currentItem(current_type_, index);
108         DocIterator const & dit = item.dit();
109         
110         Inset * inset = 0;
111         if (current_type_ == "label" 
112                   || current_type_ == "graphics"
113                   || current_type_ == "citation"
114                   || current_type_ == "child")
115                 inset = dit.nextInset();
116
117         else if (current_type_ == "branch"
118                          || current_type_ == "index"
119                          || current_type_ == "change")
120                 inset = &dit.inset();
121
122         else if (current_type_ == "table" 
123                      || current_type_ == "listing"
124                      || current_type_ == "figure") {
125                 DocIterator tmp_dit(dit);
126                 tmp_dit.pop_back();
127                 inset = &tmp_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(true);
153                 return true;
154
155         case LFUN_LABEL_COPY_AS_REF: {
156                 // For labels in math, we need to supply the label as a string
157                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REF, item.asString());
158                 if (inset)
159                         return inset->getStatus(cur, label_copy, status);
160         }
161
162         default:
163                 if (inset)
164                         return inset->getStatus(cur, tmpcmd, status);
165         }
166
167         return false;
168 }
169
170
171 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd)
172 {
173         Inset * inset = itemInset();
174         FuncRequest tmpcmd(cmd);
175
176         QModelIndex const & index = tocTV->currentIndex();
177         TocItem const & item =
178                 gui_view_.tocModels().currentItem(current_type_, index);
179
180         // Start an undo group.
181         cur.beginUndoGroup();
182
183         switch (cmd.action())
184         {
185         case LFUN_CHANGE_ACCEPT:
186         case LFUN_CHANGE_REJECT:
187         case LFUN_SECTION_SELECT:
188                 dispatch(item.action());
189                 cur.dispatch(tmpcmd);
190                 break;
191
192         case LFUN_LABEL_COPY_AS_REF: {
193                 // For labels in math, we need to supply the label as a string
194                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REF, item.asString());
195                 if (inset)
196                         inset->dispatch(cur, label_copy);
197                 break;
198         }
199         
200         case LFUN_OUTLINE_UP:
201         case LFUN_OUTLINE_DOWN:
202         case LFUN_OUTLINE_IN:
203         case LFUN_OUTLINE_OUT:
204                 outline(cmd.action());
205                 break;
206
207         default:
208                 if (inset)
209                         inset->dispatch(cur, tmpcmd);
210         }
211         cur.endUndoGroup();
212 }
213
214
215 void TocWidget::on_tocTV_activated(QModelIndex const & index)
216 {
217         goTo(index);
218 }
219
220
221 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
222 {
223         Qt::MouseButtons const button = QApplication::mouseButtons();
224         if (button & Qt::LeftButton) {
225                 goTo(index);
226                 gui_view_.setFocus();
227         }
228 }
229
230
231 void TocWidget::goTo(QModelIndex const & index)
232 {
233         LYXERR(Debug::GUI, "goto " << index.row()
234                 << ", " << index.column());
235
236         gui_view_.tocModels().goTo(current_type_, index);
237 }
238
239
240 void TocWidget::on_updateTB_clicked()
241 {
242         // The backend update can take some time so we disable
243         // the controls while waiting.
244         enableControls(false);
245         gui_view_.tocModels().updateBackend();
246 }
247
248
249 void TocWidget::on_sortCB_stateChanged(int state)
250 {
251         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
252         updateView();
253 }
254
255
256 void TocWidget::on_persistentCB_stateChanged(int state)
257 {
258         persistent_ = state == Qt::Checked;
259 }
260
261
262 /* FIXME (Ugras 17/11/06):
263 I have implemented a indexDepth function to get the model indices. In my
264 opinion, somebody should derive a new qvariant class for tocModelItem
265 which saves the string data and depth information. That will save the
266 depth calculation.  */
267
268 static int indexDepth(QModelIndex const & index, int depth = -1)
269 {
270         ++depth;
271         return index.parent() == QModelIndex()
272                 ? depth : indexDepth(index.parent(), depth);
273 }
274
275
276 void TocWidget::on_depthSL_valueChanged(int depth)
277 {
278         if (depth == depth_)
279                 return;
280         setTreeDepth(depth);
281         gui_view_.setFocus();
282 }
283
284
285 void TocWidget::setTreeDepth(int depth)
286 {
287         depth_ = depth;
288         if (!tocTV->model())
289                 return;
290
291 #if QT_VERSION >= 0x040300
292         // this should be faster than our own code below
293         if (depth == 0)
294                 tocTV->collapseAll();
295         else
296                 tocTV->expandToDepth(depth - 1);
297 #else
298         // expanding and then collapsing is probably better,
299         // but my qt 4.1.2 doesn't have expandAll()..
300         //tocTV->expandAll();
301         QModelIndexList indices = tocTV->model()->match(
302                 tocTV->model()->index(0, 0),
303                 Qt::DisplayRole, "*", -1,
304                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
305
306         int size = indices.size();
307         for (int i = 0; i < size; i++) {
308                 QModelIndex index = indices[i];
309                 tocTV->setExpanded(index, indexDepth(index) < depth_);
310         }
311 #endif
312 }
313
314
315 void TocWidget::on_typeCO_currentIndexChanged(int index)
316 {
317         current_type_ = typeCO->itemData(index).toString();
318         updateView();
319         if (typeCO->hasFocus())
320                 gui_view_.setFocus();
321 }
322
323
324 void TocWidget::outline(FuncCode func_code)
325 {
326         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
327         if (list.isEmpty())
328                 return;
329         enableControls(false);
330         goTo(list[0]);
331         dispatch(FuncRequest(func_code));
332         enableControls(true);
333         gui_view_.setFocus();
334 }
335
336
337 void TocWidget::on_moveUpTB_clicked()
338 {
339         outline(LFUN_OUTLINE_UP);
340 }
341
342
343 void TocWidget::on_moveDownTB_clicked()
344 {
345         outline(LFUN_OUTLINE_DOWN);
346 }
347
348
349 void TocWidget::on_moveInTB_clicked()
350 {
351         outline(LFUN_OUTLINE_IN);
352 }
353
354
355 void TocWidget::on_moveOutTB_clicked()
356 {
357         outline(LFUN_OUTLINE_OUT);
358 }
359
360
361 void TocWidget::select(QModelIndex const & index)
362 {
363         if (!index.isValid()) {
364                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
365                 return;
366         }
367
368         tocTV->scrollTo(index);
369         tocTV->clearSelection();
370         tocTV->setCurrentIndex(index);
371 }
372
373
374 void TocWidget::enableControls(bool enable)
375 {
376         updateTB->setEnabled(enable);
377
378         if (!canOutline())
379                 enable = false;
380
381         moveUpTB->setEnabled(enable);
382         moveDownTB->setEnabled(enable);
383         moveInTB->setEnabled(enable);
384         moveOutTB->setEnabled(enable);
385 }
386
387
388 void TocWidget::updateView()
389 {
390         if (!gui_view_.documentBufferView()) {
391                 enableControls(false);
392                 typeCO->setEnabled(false);
393                 tocTV->setModel(0);
394                 tocTV->setEnabled(false);
395                 depthSL->setMaximum(0);
396                 depthSL->setValue(0);
397                 persistentCB->setEnabled(false);
398                 sortCB->setEnabled(false);
399                 depthSL->setEnabled(false);
400                 return;
401         }
402         bool const is_sortable = isSortable();
403         sortCB->setEnabled(is_sortable);
404         depthSL->setEnabled(true);
405         typeCO->setEnabled(true);
406         bool focus_ = tocTV->hasFocus();
407         tocTV->setEnabled(false);
408         tocTV->setUpdatesEnabled(false);
409
410         QAbstractItemModel * toc_model = 
411                         gui_view_.tocModels().model(current_type_);
412         if (tocTV->model() != toc_model) {
413                 tocTV->setModel(toc_model);
414                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
415                 if (persistent_)
416                         setTreeDepth(depth_);
417         }
418
419         sortCB->blockSignals(true);
420         sortCB->setChecked(is_sortable
421                 && gui_view_.tocModels().isSorted(current_type_));
422         sortCB->blockSignals(false);
423
424         bool const can_navigate_ = canNavigate();
425         persistentCB->setEnabled(can_navigate_);
426
427         bool controls_enabled = toc_model && toc_model->rowCount() > 0
428                 && !gui_view_.documentBufferView()->buffer().isReadonly();
429         enableControls(controls_enabled);
430
431         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
432         depthSL->setValue(depth_);
433         if (!persistent_ && can_navigate_)
434                 setTreeDepth(depth_);
435         if (can_navigate_) {
436                 persistentCB->setChecked(persistent_);
437                 select(gui_view_.tocModels().currentIndex(current_type_));
438         }
439         filterContents();
440         tocTV->setEnabled(true);
441         tocTV->setUpdatesEnabled(true);
442         if (focus_)
443                 tocTV->setFocus();
444 }
445
446
447 void TocWidget::filterContents()
448 {
449         if (!tocTV->model())
450                 return;
451
452         QModelIndexList indices = tocTV->model()->match(
453                 tocTV->model()->index(0, 0),
454                 Qt::DisplayRole, "*", -1,
455                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
456
457         int size = indices.size();
458         for (int i = 0; i < size; i++) {
459                 QModelIndex index = indices[i];
460                 bool const matches =
461                         index.data().toString().contains(
462                                 filterLE->text(), Qt::CaseInsensitive);
463                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
464         }
465         // recursively unhide parents of unhidden children 
466         for (int i = size - 1; i >= 0; i--) {
467                 QModelIndex index = indices[i];
468                 if (!tocTV->isRowHidden(index.row(), index.parent())
469                     && index.parent() != QModelIndex())
470                         tocTV->setRowHidden(index.parent().row(),
471                                             index.parent().parent(), false);
472         }
473 }
474
475
476 static QString decodeType(QString const & str)
477 {
478         QString type = str;
479         if (type.contains("tableofcontents")) {
480                 type = "tableofcontents";
481         } else if (type.contains("floatlist")) {
482                 if (type.contains("\"figure"))
483                         type = "figure";
484                 else if (type.contains("\"table"))
485                         type = "table";
486                 else if (type.contains("\"algorithm"))
487                         type = "algorithm";
488         }
489         return type;
490 }
491
492
493 void TocWidget::init(QString const & str)
494 {
495         int new_index;
496         if (str.isEmpty())
497                 new_index = typeCO->findData(current_type_);
498         else
499                 new_index = typeCO->findData(decodeType(str));
500
501         // If everything else fails, settle on the table of contents which is
502         // guaranted to exist.
503         if (new_index == -1) {
504                 current_type_ = "tableofcontents";
505                 new_index = typeCO->findData(current_type_);
506         } else {
507                 current_type_ = typeCO->itemData(new_index).toString();
508         }
509
510         typeCO->blockSignals(true);
511         typeCO->setCurrentIndex(new_index);
512         typeCO->blockSignals(false);
513 }
514
515 } // namespace frontend
516 } // namespace lyx
517
518 #include "moc_TocWidget.cpp"