]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
* fix spelling in comments to please John.
[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         // Start an undo group.
178         cur.beginUndoGroup();
179
180         switch (cmd.action)
181         {
182         case LFUN_CHANGE_ACCEPT:
183         case LFUN_CHANGE_REJECT:
184         case LFUN_SECTION_SELECT:
185                 dispatch(item.action());
186                 cur.dispatch(tmpcmd);
187                 break;
188
189         case LFUN_LABEL_COPY_AS_REF: {
190                 // For labels in math, we need to supply the label as a string
191                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REF, item.asString());
192                 if (inset)
193                         inset->dispatch(cur, label_copy);
194                 break;
195         }
196         
197         case LFUN_OUTLINE_UP:
198         case LFUN_OUTLINE_DOWN:
199         case LFUN_OUTLINE_IN:
200         case LFUN_OUTLINE_OUT:
201                 outline(cmd.action);
202                 break;
203
204         default:
205                 if (inset)
206                         inset->dispatch(cur, tmpcmd);
207         }
208         cur.endUndoGroup();
209 }
210
211
212 void TocWidget::on_tocTV_activated(QModelIndex const & index)
213 {
214         goTo(index);
215 }
216
217
218 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
219 {
220         Qt::MouseButtons const button = QApplication::mouseButtons();
221         if (button & Qt::LeftButton) {
222                 goTo(index);
223                 gui_view_.setFocus();
224         }
225 }
226
227
228 void TocWidget::goTo(QModelIndex const & index)
229 {
230         LYXERR(Debug::GUI, "goto " << index.row()
231                 << ", " << index.column());
232
233         gui_view_.tocModels().goTo(current_type_, index);
234 }
235
236
237 void TocWidget::on_updateTB_clicked()
238 {
239         // The backend update can take some time so we disable
240         // the controls while waiting.
241         enableControls(false);
242         gui_view_.tocModels().updateBackend();
243 }
244
245
246 void TocWidget::on_sortCB_stateChanged(int state)
247 {
248         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
249         updateView();
250 }
251
252
253 void TocWidget::on_persistentCB_stateChanged(int state)
254 {
255         persistent_ = state == Qt::Checked;
256 }
257
258
259 /* FIXME (Ugras 17/11/06):
260 I have implemented a indexDepth function to get the model indices. In my
261 opinion, somebody should derive a new qvariant class for tocModelItem
262 which saves the string data and depth information. That will save the
263 depth calculation.  */
264
265 static int indexDepth(QModelIndex const & index, int depth = -1)
266 {
267         ++depth;
268         return index.parent() == QModelIndex()
269                 ? depth : indexDepth(index.parent(), depth);
270 }
271
272
273 void TocWidget::on_depthSL_valueChanged(int depth)
274 {
275         if (depth == depth_)
276                 return;
277         setTreeDepth(depth);
278         gui_view_.setFocus();
279 }
280
281
282 void TocWidget::setTreeDepth(int depth)
283 {
284         depth_ = depth;
285         if (!tocTV->model())
286                 return;
287
288 #if QT_VERSION >= 0x040300
289         // this should be faster than our own code below
290         if (depth == 0)
291                 tocTV->collapseAll();
292         else
293                 tocTV->expandToDepth(depth - 1);
294 #else
295         // expanding and then collapsing is probably better,
296         // but my qt 4.1.2 doesn't have expandAll()..
297         //tocTV->expandAll();
298         QModelIndexList indices = tocTV->model()->match(
299                 tocTV->model()->index(0, 0),
300                 Qt::DisplayRole, "*", -1,
301                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
302
303         int size = indices.size();
304         for (int i = 0; i < size; i++) {
305                 QModelIndex index = indices[i];
306                 tocTV->setExpanded(index, indexDepth(index) < depth_);
307         }
308 #endif
309 }
310
311
312 void TocWidget::on_typeCO_currentIndexChanged(int index)
313 {
314         current_type_ = typeCO->itemData(index).toString();
315         updateView();
316         gui_view_.setFocus();
317 }
318
319
320 void TocWidget::outline(int func_code)
321 {
322         enableControls(false);
323         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
324         if (list.isEmpty())
325                 return;
326         enableControls(false);
327         goTo(list[0]);
328         dispatch(FuncRequest(static_cast<FuncCode>(func_code)));
329         enableControls(true);
330         gui_view_.setFocus();
331 }
332
333
334 void TocWidget::on_moveUpTB_clicked()
335 {
336         outline(LFUN_OUTLINE_UP);
337 }
338
339
340 void TocWidget::on_moveDownTB_clicked()
341 {
342         outline(LFUN_OUTLINE_DOWN);
343 }
344
345
346 void TocWidget::on_moveInTB_clicked()
347 {
348         outline(LFUN_OUTLINE_IN);
349 }
350
351
352 void TocWidget::on_moveOutTB_clicked()
353 {
354         outline(LFUN_OUTLINE_OUT);
355 }
356
357
358 void TocWidget::select(QModelIndex const & index)
359 {
360         if (!index.isValid()) {
361                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
362                 return;
363         }
364
365         tocTV->scrollTo(index);
366         tocTV->clearSelection();
367         tocTV->setCurrentIndex(index);
368 }
369
370
371 /// Test whether outlining operation is possible
372 static bool canOutline(QString const & type)
373 {
374         return type == "tableofcontents";
375 }
376
377
378 void TocWidget::enableControls(bool enable)
379 {
380         updateTB->setEnabled(enable);
381
382         if (!canOutline(current_type_))
383                 enable = false;
384
385         moveUpTB->setEnabled(enable);
386         moveDownTB->setEnabled(enable);
387         moveInTB->setEnabled(enable);
388         moveOutTB->setEnabled(enable);
389 }
390
391
392 /// Test whether synchronized navigation is possible
393 static bool canNavigate(QString const & type)
394 {
395         // It is not possible to have synchronous navigation in a correct
396         // and efficient way with the label and change type because Toc::item()
397         // does a linear search. Even when fixed, it might even not be desirable
398         // to do so if we want to support drag&drop of labels and references.
399         return type != "label" && type != "change";
400 }
401
402
403 /// Test whether sorting is possible
404 static bool isSortable(QString const & type)
405 {
406         return type != "tableofcontents";
407 }
408
409
410 void TocWidget::updateView()
411 {
412         if (!gui_view_.documentBufferView()) {
413                 enableControls(false);
414                 typeCO->setEnabled(false);
415                 tocTV->setModel(0);
416                 tocTV->setEnabled(false);
417                 depthSL->setMaximum(0);
418                 depthSL->setValue(0);
419                 persistentCB->setEnabled(false);
420                 sortCB->setEnabled(false);
421                 depthSL->setEnabled(false);
422                 return;
423         }
424         sortCB->setEnabled(isSortable(current_type_));
425         depthSL->setEnabled(true);
426         typeCO->setEnabled(true);
427         tocTV->setEnabled(false);
428         tocTV->setUpdatesEnabled(false);
429
430         QAbstractItemModel * toc_model = gui_view_.tocModels().model(current_type_);
431         if (tocTV->model() != toc_model) {
432                 tocTV->setModel(toc_model);
433                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
434                 if (persistent_)
435                         setTreeDepth(depth_);
436         }
437
438         sortCB->blockSignals(true);
439         sortCB->setChecked(isSortable(current_type_)
440                 && gui_view_.tocModels().isSorted(current_type_));
441         sortCB->blockSignals(false);
442
443         
444         bool const can_navigate_ = canNavigate(current_type_);
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         tocTV->setEnabled(true);
460         tocTV->setUpdatesEnabled(true);
461 }
462
463
464 static QString decodeType(QString const & str)
465 {
466         QString type = str;
467         if (type.contains("tableofcontents")) {
468                 type = "tableofcontents";
469         } else if (type.contains("floatlist")) {
470                 if (type.contains("\"figure"))
471                         type = "figure";
472                 else if (type.contains("\"table"))
473                         type = "table";
474                 else if (type.contains("\"algorithm"))
475                         type = "algorithm";
476         }
477         return type;
478 }
479
480
481 void TocWidget::init(QString const & str)
482 {
483         int new_index;
484         if (str.isEmpty())
485                 new_index = typeCO->findData(current_type_);
486         else
487                 new_index = typeCO->findData(decodeType(str));
488
489         // If everything else fails, settle on the table of contents which is
490         // guaranted to exist.
491         if (new_index == -1) {
492                 current_type_ = "tableofcontents";
493                 new_index = typeCO->findData(current_type_);
494         } else {
495                 current_type_ = typeCO->itemData(new_index).toString();
496         }
497
498         typeCO->blockSignals(true);
499         typeCO->setCurrentIndex(new_index);
500         typeCO->blockSignals(false);
501 }
502
503 } // namespace frontend
504 } // namespace lyx
505
506 #include "moc_TocWidget.cpp"