]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
Line length, again.
[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         // In Qt 4.6.x, we can end up here programmatically, when the
319         // model is rebuilt. But the Buffer may not be ready for us to
320         // reset focus, start the cursor, etc. So we check to see if the
321         // combo box has focus. It will, if the user has changed the 
322         // value.
323         if (typeCO->hasFocus())
324                 gui_view_.setFocus();
325 }
326
327
328 void TocWidget::outline(FuncCode func_code)
329 {
330         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
331         if (list.isEmpty())
332                 return;
333         enableControls(false);
334         goTo(list[0]);
335         dispatch(FuncRequest(func_code));
336         enableControls(true);
337         gui_view_.setFocus();
338 }
339
340
341 void TocWidget::on_moveUpTB_clicked()
342 {
343         outline(LFUN_OUTLINE_UP);
344 }
345
346
347 void TocWidget::on_moveDownTB_clicked()
348 {
349         outline(LFUN_OUTLINE_DOWN);
350 }
351
352
353 void TocWidget::on_moveInTB_clicked()
354 {
355         outline(LFUN_OUTLINE_IN);
356 }
357
358
359 void TocWidget::on_moveOutTB_clicked()
360 {
361         outline(LFUN_OUTLINE_OUT);
362 }
363
364
365 void TocWidget::select(QModelIndex const & index)
366 {
367         if (!index.isValid()) {
368                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
369                 return;
370         }
371
372         tocTV->scrollTo(index);
373         tocTV->clearSelection();
374         tocTV->setCurrentIndex(index);
375 }
376
377
378 void TocWidget::enableControls(bool enable)
379 {
380         updateTB->setEnabled(enable);
381
382         if (!canOutline())
383                 enable = false;
384
385         moveUpTB->setEnabled(enable);
386         moveDownTB->setEnabled(enable);
387         moveInTB->setEnabled(enable);
388         moveOutTB->setEnabled(enable);
389 }
390
391
392 void TocWidget::updateView()
393 {
394         if (!gui_view_.documentBufferView()) {
395                 enableControls(false);
396                 typeCO->setEnabled(false);
397                 tocTV->setModel(0);
398                 tocTV->setEnabled(false);
399                 depthSL->setMaximum(0);
400                 depthSL->setValue(0);
401                 persistentCB->setEnabled(false);
402                 sortCB->setEnabled(false);
403                 depthSL->setEnabled(false);
404                 return;
405         }
406         bool const is_sortable = isSortable();
407         sortCB->setEnabled(is_sortable);
408         depthSL->setEnabled(true);
409         typeCO->setEnabled(true);
410         tocTV->setEnabled(false);
411         tocTV->setUpdatesEnabled(false);
412
413         QAbstractItemModel * toc_model = 
414                         gui_view_.tocModels().model(current_type_);
415         if (tocTV->model() != toc_model) {
416                 tocTV->setModel(toc_model);
417                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
418                 if (persistent_)
419                         setTreeDepth(depth_);
420         }
421
422         sortCB->blockSignals(true);
423         sortCB->setChecked(is_sortable
424                 && gui_view_.tocModels().isSorted(current_type_));
425         sortCB->blockSignals(false);
426
427         bool const can_navigate_ = canNavigate();
428         persistentCB->setEnabled(can_navigate_);
429
430         bool controls_enabled = toc_model && toc_model->rowCount() > 0
431                 && !gui_view_.documentBufferView()->buffer().isReadonly();
432         enableControls(controls_enabled);
433
434         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
435         depthSL->setValue(depth_);
436         if (!persistent_ && can_navigate_)
437                 setTreeDepth(depth_);
438         if (can_navigate_) {
439                 persistentCB->setChecked(persistent_);
440                 select(gui_view_.tocModels().currentIndex(current_type_));
441         }
442         filterContents();
443         tocTV->setEnabled(true);
444         tocTV->setUpdatesEnabled(true);
445 }
446
447
448 void TocWidget::filterContents()
449 {
450         if (!tocTV->model())
451                 return;
452
453         QModelIndexList indices = tocTV->model()->match(
454                 tocTV->model()->index(0, 0),
455                 Qt::DisplayRole, "*", -1,
456                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
457
458         int size = indices.size();
459         for (int i = 0; i < size; i++) {
460                 QModelIndex index = indices[i];
461                 bool const matches =
462                         index.data().toString().contains(
463                                 filterLE->text(), Qt::CaseSensitive);
464                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
465         }
466         // recursively unhide parents of unhidden children 
467         for (int i = size - 1; i >= 0; i--) {
468                 QModelIndex index = indices[i];
469                 if (!tocTV->isRowHidden(index.row(), index.parent())
470                     && index.parent() != QModelIndex())
471                         tocTV->setRowHidden(index.parent().row(),
472                                             index.parent().parent(), false);
473         }
474 }
475
476
477 static QString decodeType(QString const & str)
478 {
479         QString type = str;
480         if (type.contains("tableofcontents")) {
481                 type = "tableofcontents";
482         } else if (type.contains("floatlist")) {
483                 if (type.contains("\"figure"))
484                         type = "figure";
485                 else if (type.contains("\"table"))
486                         type = "table";
487                 else if (type.contains("\"algorithm"))
488                         type = "algorithm";
489         }
490         return type;
491 }
492
493
494 void TocWidget::init(QString const & str)
495 {
496         int new_index;
497         if (str.isEmpty())
498                 new_index = typeCO->findData(current_type_);
499         else
500                 new_index = typeCO->findData(decodeType(str));
501
502         // If everything else fails, settle on the table of contents which is
503         // guaranted to exist.
504         if (new_index == -1) {
505                 current_type_ = "tableofcontents";
506                 new_index = typeCO->findData(current_type_);
507         } else {
508                 current_type_ = typeCO->itemData(new_index).toString();
509         }
510
511         typeCO->blockSignals(true);
512         typeCO->setCurrentIndex(new_index);
513         typeCO->blockSignals(false);
514 }
515
516 } // namespace frontend
517 } // namespace lyx
518
519 #include "moc_TocWidget.cpp"