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