]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
Disable the TOC when no document is open.
[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 "LyXFunc.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
72         // The toc types combo won't change its model.
73         typeCO->setModel(gui_view_.tocModels().nameModel());
74
75         // Make sure the buttons are disabled when first shown without a loaded
76         // Buffer.
77         enableControls(false);
78
79         // make us responsible for the context menu of the tabbar
80         setContextMenuPolicy(Qt::CustomContextMenu);
81         connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
82                 this, SLOT(showContextMenu(const QPoint &)));
83         connect(tocTV, SIGNAL(customContextMenuRequested(const QPoint &)),
84                 this, SLOT(showContextMenu(const QPoint &)));
85
86         init(QString());
87 }
88
89
90 void TocWidget::showContextMenu(const QPoint & pos)
91 {
92         std::string name = "context-toc-" + fromqstr(current_type_);
93         QMenu * menu = guiApp->menus().menu(toqstr(name), gui_view_);
94         if (!menu)
95                 return; 
96         menu->exec(mapToGlobal(pos));
97 }
98
99
100 Inset * TocWidget::itemInset() const
101 {
102         QModelIndex const & index = tocTV->currentIndex();
103         TocItem const & item =
104                 gui_view_.tocModels().currentItem(current_type_, index);
105         DocIterator const & dit = item.dit();
106         
107         Inset * inset = 0;
108         if (current_type_ == "label" 
109                   || current_type_ == "graphics"
110                   || current_type_ == "citation"
111                   || current_type_ == "child")
112                 inset = dit.nextInset();
113
114         else if (current_type_ == "branch"
115                          || current_type_ == "index"
116                          || current_type_ == "change")
117                 inset = &dit.inset();
118
119         else if (current_type_ == "table" 
120                      || current_type_ == "listing"
121                      || current_type_ == "figure") {
122                 DocIterator tmp_dit(dit);
123                 tmp_dit.pop_back();
124                 inset = &tmp_dit.inset();
125         }
126         return inset;
127 }
128
129
130 bool TocWidget::getStatus(Cursor & cur, FuncRequest const & cmd,
131         FuncStatus & status) const
132 {
133         Inset * inset = itemInset();
134         FuncRequest tmpcmd(cmd);
135
136         QModelIndex const & index = tocTV->currentIndex();
137         TocItem const & item =
138                 gui_view_.tocModels().currentItem(current_type_, index);
139
140         switch (cmd.action)
141         {
142         case LFUN_CHANGE_ACCEPT:
143         case LFUN_CHANGE_REJECT:
144         case LFUN_OUTLINE_UP:
145         case LFUN_OUTLINE_DOWN:
146         case LFUN_OUTLINE_IN:
147         case LFUN_OUTLINE_OUT:
148         case LFUN_SECTION_SELECT:
149                 status.setEnabled(true);
150                 return true;
151
152         case LFUN_LABEL_COPY_AS_REF: {
153                 // For labels in math, we need to supply the label as a string
154                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REF, item.asString());
155                 if (inset)
156                         return inset->getStatus(cur, label_copy, status);
157         }
158
159         default:
160                 if (inset)
161                         return inset->getStatus(cur, tmpcmd, status);
162         }
163
164         return false;
165 }
166
167
168 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd)
169 {
170         Inset * inset = itemInset();
171         FuncRequest tmpcmd(cmd);
172
173         QModelIndex const & index = tocTV->currentIndex();
174         TocItem const & item =
175                 gui_view_.tocModels().currentItem(current_type_, index);
176
177         switch (cmd.action)
178         {
179         case LFUN_CHANGE_ACCEPT:
180         case LFUN_CHANGE_REJECT:
181         case LFUN_SECTION_SELECT:
182                 dispatch(item.action());
183                 cur.dispatch(tmpcmd);
184                 break;
185
186         case LFUN_LABEL_COPY_AS_REF: {
187                 // For labels in math, we need to supply the label as a string
188                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REF, item.asString());
189                 if (inset)
190                         inset->dispatch(cur, label_copy);
191                 break;
192         }
193         
194         case LFUN_OUTLINE_UP:
195         case LFUN_OUTLINE_DOWN:
196         case LFUN_OUTLINE_IN:
197         case LFUN_OUTLINE_OUT:
198                 outline(cmd.action);
199                 break;
200
201         default:
202                 if (inset)
203                         inset->dispatch(cur, tmpcmd);
204         }
205 }
206
207
208 void TocWidget::on_tocTV_activated(QModelIndex const & index)
209 {
210         goTo(index);
211 }
212
213
214 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
215 {
216         Qt::MouseButtons const button = QApplication::mouseButtons();
217         if (button & Qt::LeftButton) {
218                 goTo(index);
219                 gui_view_.setFocus();
220         }
221 }
222
223
224 void TocWidget::goTo(QModelIndex const & index)
225 {
226         LYXERR(Debug::GUI, "goto " << index.row()
227                 << ", " << index.column());
228
229         gui_view_.tocModels().goTo(current_type_, index);
230 }
231
232
233 void TocWidget::on_updateTB_clicked()
234 {
235         // The backend update can take some time so we disable
236         // the controls while waiting.
237         enableControls(false);
238         gui_view_.tocModels().updateBackend();
239 }
240
241
242 void TocWidget::on_sortCB_stateChanged(int state)
243 {
244         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
245         updateView();
246 }
247
248
249 void TocWidget::on_persistentCB_stateChanged(int state)
250 {
251         persistent_ = state == Qt::Checked;
252 }
253
254
255 /* FIXME (Ugras 17/11/06):
256 I have implemented a indexDepth function to get the model indices. In my
257 opinion, somebody should derive a new qvariant class for tocModelItem
258 which saves the string data and depth information. That will save the
259 depth calculation.  */
260
261 static int indexDepth(QModelIndex const & index, int depth = -1)
262 {
263         ++depth;
264         return index.parent() == QModelIndex()
265                 ? depth : indexDepth(index.parent(), depth);
266 }
267
268
269 void TocWidget::on_depthSL_valueChanged(int depth)
270 {
271         if (depth == depth_)
272                 return;
273         setTreeDepth(depth);
274         gui_view_.setFocus();
275 }
276
277
278 void TocWidget::setTreeDepth(int depth)
279 {
280         depth_ = depth;
281         if (!tocTV->model())
282                 return;
283
284 #if QT_VERSION >= 0x040300
285         // this should be faster than our own code below
286         if (depth == 0)
287                 tocTV->collapseAll();
288         else
289                 tocTV->expandToDepth(depth - 1);
290 #else
291         // expanding and then collapsing is probably better,
292         // but my qt 4.1.2 doesn't have expandAll()..
293         //tocTV->expandAll();
294         QModelIndexList indices = tocTV->model()->match(
295                 tocTV->model()->index(0, 0),
296                 Qt::DisplayRole, "*", -1,
297                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
298
299         int size = indices.size();
300         for (int i = 0; i < size; i++) {
301                 QModelIndex index = indices[i];
302                 tocTV->setExpanded(index, indexDepth(index) < depth_);
303         }
304 #endif
305 }
306
307
308 void TocWidget::on_typeCO_currentIndexChanged(int index)
309 {
310         current_type_ = typeCO->itemData(index).toString();
311         updateView();
312         gui_view_.setFocus();
313 }
314
315
316 void TocWidget::outline(int func_code)
317 {
318         enableControls(false);
319         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
320         if (list.isEmpty())
321                 return;
322         enableControls(false);
323         goTo(list[0]);
324         dispatch(FuncRequest(static_cast<FuncCode>(func_code)));
325         enableControls(true);
326         gui_view_.setFocus();
327 }
328
329
330 void TocWidget::on_moveUpTB_clicked()
331 {
332         outline(LFUN_OUTLINE_UP);
333 }
334
335
336 void TocWidget::on_moveDownTB_clicked()
337 {
338         outline(LFUN_OUTLINE_DOWN);
339 }
340
341
342 void TocWidget::on_moveInTB_clicked()
343 {
344         outline(LFUN_OUTLINE_IN);
345 }
346
347
348 void TocWidget::on_moveOutTB_clicked()
349 {
350         outline(LFUN_OUTLINE_OUT);
351 }
352
353
354 void TocWidget::select(QModelIndex const & index)
355 {
356         if (!index.isValid()) {
357                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
358                 return;
359         }
360
361         tocTV->scrollTo(index);
362         tocTV->clearSelection();
363         tocTV->setCurrentIndex(index);
364 }
365
366
367 /// Test whether outlining operation is possible
368 static bool canOutline(QString const & type)
369 {
370         return type == "tableofcontents";
371 }
372
373
374 void TocWidget::enableControls(bool enable)
375 {
376         updateTB->setEnabled(enable);
377
378         if (!canOutline(current_type_))
379                 enable = false;
380
381         moveUpTB->setEnabled(enable);
382         moveDownTB->setEnabled(enable);
383         moveInTB->setEnabled(enable);
384         moveOutTB->setEnabled(enable);
385 }
386
387
388 /// Test whether synchronized navigation is possible
389 static bool canNavigate(QString const & type)
390 {
391         // It is not possible to have synchronous navigation in a correct
392         // and efficient way with the label and change type because Toc::item()
393         // does a linear search. Even when fixed, it might even not be desirable
394         // to do so if we want to support drag&drop of labels and references.
395         return type != "label" && type != "change";
396 }
397
398
399 /// Test whether sorting is possible
400 static bool isSortable(QString const & type)
401 {
402         return type != "tableofcontents";
403 }
404
405
406 void TocWidget::updateView()
407 {
408         if (!gui_view_.documentBufferView()) {
409                 enableControls(false);
410                 typeCO->setEnabled(false);
411                 tocTV->setModel(0);
412                 tocTV->setEnabled(false);
413                 depthSL->setMaximum(0);
414                 depthSL->setValue(0);
415                 persistentCB->setEnabled(false);
416                 sortCB->setEnabled(false);
417                 depthSL->setEnabled(false);
418                 return;
419         }
420         sortCB->setEnabled(isSortable(current_type_));
421         depthSL->setEnabled(true);
422         typeCO->setEnabled(true);
423         tocTV->setEnabled(false);
424         tocTV->setUpdatesEnabled(false);
425
426         QAbstractItemModel * toc_model = gui_view_.tocModels().model(current_type_);
427         if (tocTV->model() != toc_model) {
428                 tocTV->setModel(toc_model);
429                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
430                 if (persistent_)
431                         setTreeDepth(depth_);
432         }
433
434         sortCB->blockSignals(true);
435         sortCB->setChecked(isSortable(current_type_)
436                 && gui_view_.tocModels().isSorted(current_type_));
437         sortCB->blockSignals(false);
438
439         
440         bool const can_navigate_ = canNavigate(current_type_);
441         persistentCB->setEnabled(can_navigate_);
442
443         bool controls_enabled = toc_model && toc_model->rowCount() > 0
444                 && !gui_view_.documentBufferView()->buffer().isReadonly();
445         enableControls(controls_enabled);
446
447         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
448         depthSL->setValue(depth_);
449         if (!persistent_ && can_navigate_)
450                 setTreeDepth(depth_);
451         if (can_navigate_) {
452                 persistentCB->setChecked(persistent_);
453                 select(gui_view_.tocModels().currentIndex(current_type_));
454         }
455         tocTV->setEnabled(true);
456         tocTV->setUpdatesEnabled(true);
457 }
458
459
460 static QString decodeType(QString const & str)
461 {
462         QString type = str;
463         if (type.contains("tableofcontents")) {
464                 type = "tableofcontents";
465         } else if (type.contains("floatlist")) {
466                 if (type.contains("\"figure"))
467                         type = "figure";
468                 else if (type.contains("\"table"))
469                         type = "table";
470                 else if (type.contains("\"algorithm"))
471                         type = "algorithm";
472         }
473         return type;
474 }
475
476
477 void TocWidget::init(QString const & str)
478 {
479         int new_index;
480         if (str.isEmpty())
481                 new_index = typeCO->findData(current_type_);
482         else
483                 new_index = typeCO->findData(decodeType(str));
484
485         // If everything else fails, settle on the table of contents which is
486         // guaranted to exist.
487         if (new_index == -1) {
488                 current_type_ = "tableofcontents";
489                 new_index = typeCO->findData(current_type_);
490         } else {
491                 current_type_ = typeCO->itemData(new_index).toString();
492         }
493
494         typeCO->blockSignals(true);
495         typeCO->setCurrentIndex(new_index);
496         typeCO->blockSignals(false);
497 }
498
499 } // namespace frontend
500 } // namespace lyx
501
502 #include "moc_TocWidget.cpp"