]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
On Linux show in crash message box the backtrace
[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 #define DELAY_UPDATE_VIEW
43
44 using namespace std;
45
46 namespace lyx {
47 namespace frontend {
48
49 TocWidget::TocWidget(GuiView & gui_view, QWidget * parent)
50         : QWidget(parent), depth_(0), persistent_(false), gui_view_(gui_view), update_delay_(0)
51
52 {
53         setupUi(this);
54
55         moveOutTB->setIcon(QIcon(getPixmap("images/", "promote", "png")));
56         moveInTB->setIcon(QIcon(getPixmap("images/", "demote", "png")));
57         moveUpTB->setIcon(QIcon(getPixmap("images/", "up", "png")));
58         moveDownTB->setIcon(QIcon(getPixmap("images/", "down", "png")));
59         updateTB->setIcon(QIcon(getPixmap("images/", "reload", "png")));
60
61         // avoid flickering
62         tocTV->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
63
64         tocTV->showColumn(0);
65
66         // hide the pointless QHeader for now
67         // in the future, new columns may appear
68         // like labels, bookmarks, etc...
69         // tocTV->header()->hide();
70         tocTV->header()->setVisible(false);
71
72         // Only one item selected at a time.
73         tocTV->setSelectionMode(QAbstractItemView::SingleSelection);
74         setFocusProxy(tocTV);
75
76         // The toc types combo won't change its model.
77         typeCO->setModel(gui_view_.tocModels().nameModel());
78
79         // Make sure the buttons are disabled when first shown without a loaded
80         // Buffer.
81         enableControls(false);
82
83         // make us responsible for the context menu of the tabbar
84         setContextMenuPolicy(Qt::CustomContextMenu);
85         connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
86                 this, SLOT(showContextMenu(const QPoint &)));
87         connect(tocTV, SIGNAL(customContextMenuRequested(const QPoint &)),
88                 this, SLOT(showContextMenu(const QPoint &)));
89         connect(filterLE, SIGNAL(textEdited(QString)), 
90                 this, SLOT(filterContents()));
91
92         init(QString());
93 }
94
95
96 void TocWidget::showContextMenu(const QPoint & pos)
97 {
98         std::string name = "context-toc-" + fromqstr(current_type_);
99         QMenu * menu = guiApp->menus().menu(toqstr(name), gui_view_);
100         if (!menu)
101                 return; 
102         menu->exec(mapToGlobal(pos));
103 }
104
105
106 Inset * TocWidget::itemInset() const
107 {
108         QModelIndex const & index = tocTV->currentIndex();
109         TocItem const & item =
110                 gui_view_.tocModels().currentItem(current_type_, index);
111         DocIterator const & dit = item.dit();
112         
113         Inset * inset = 0;
114         if (current_type_ == "label" 
115                   || current_type_ == "graphics"
116                   || current_type_ == "citation"
117                   || current_type_ == "child")
118                 inset = dit.nextInset();
119
120         else if (current_type_ == "branch"
121                          || current_type_ == "index"
122                          || current_type_ == "change")
123                 inset = &dit.inset();
124
125         else if (current_type_ == "table" 
126                      || current_type_ == "listing"
127                      || current_type_ == "figure") {
128                 DocIterator tmp_dit(dit);
129                 tmp_dit.pop_back();
130                 inset = &tmp_dit.inset();
131         }
132         return inset;
133 }
134
135
136 bool TocWidget::getStatus(Cursor & cur, FuncRequest const & cmd,
137         FuncStatus & status) const
138 {
139         Inset * inset = itemInset();
140         FuncRequest tmpcmd(cmd);
141
142         QModelIndex const & index = tocTV->currentIndex();
143         TocItem const & item =
144                 gui_view_.tocModels().currentItem(current_type_, index);
145
146         switch (cmd.action())
147         {
148         case LFUN_CHANGE_ACCEPT:
149         case LFUN_CHANGE_REJECT:
150         case LFUN_OUTLINE_UP:
151         case LFUN_OUTLINE_DOWN:
152         case LFUN_OUTLINE_IN:
153         case LFUN_OUTLINE_OUT:
154         case LFUN_SECTION_SELECT:
155                 status.setEnabled(item.dit() != 0);
156                 return true;
157
158         case LFUN_LABEL_COPY_AS_REFERENCE: {
159                 // For labels in math, we need to supply the label as a string
160                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.asString());
161                 if (inset)
162                         return inset->getStatus(cur, label_copy, status);
163         }
164
165         default:
166                 if (inset)
167                         return inset->getStatus(cur, tmpcmd, status);
168         }
169
170         return false;
171 }
172
173
174 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd)
175 {
176         Inset * inset = itemInset();
177         FuncRequest tmpcmd(cmd);
178
179         QModelIndex const & index = tocTV->currentIndex();
180         TocItem const & item =
181                 gui_view_.tocModels().currentItem(current_type_, index);
182
183         // Start an undo group.
184         cur.beginUndoGroup();
185
186         switch (cmd.action())
187         {
188         case LFUN_CHANGE_ACCEPT:
189         case LFUN_CHANGE_REJECT:
190                 dispatch(item.action());
191                 cur.dispatch(tmpcmd);
192                 break;
193
194         case LFUN_SECTION_SELECT:
195                 dispatch(item.action());
196                 cur.dispatch(tmpcmd);
197                 // necessary to get the selection drawn.
198                 cur.buffer()->changed(true);
199                 gui_view_.setFocus();
200                 break;
201
202         case LFUN_LABEL_COPY_AS_REFERENCE: {
203                 // For labels in math, we need to supply the label as a string
204                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.asString());
205                 if (inset)
206                         inset->dispatch(cur, label_copy);
207                 break;
208         }
209
210         case LFUN_OUTLINE_UP:
211         case LFUN_OUTLINE_DOWN:
212         case LFUN_OUTLINE_IN:
213         case LFUN_OUTLINE_OUT:
214                 outline(cmd.action());
215                 break;
216
217         default:
218                 if (inset)
219                         inset->dispatch(cur, tmpcmd);
220         }
221         cur.endUndoGroup();
222 }
223
224
225 void TocWidget::on_tocTV_activated(QModelIndex const & index)
226 {
227         goTo(index);
228 }
229
230
231 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
232 {
233         Qt::MouseButtons const button = QApplication::mouseButtons();
234         if (button & Qt::LeftButton) {
235                 goTo(index);
236                 gui_view_.setFocus();
237         }
238 }
239
240
241 void TocWidget::goTo(QModelIndex const & index)
242 {
243         LYXERR(Debug::GUI, "goto " << index.row()
244                 << ", " << index.column());
245
246         gui_view_.tocModels().goTo(current_type_, index);
247 }
248
249
250 void TocWidget::on_updateTB_clicked()
251 {
252         // The backend update can take some time so we disable
253         // the controls while waiting.
254         enableControls(false);
255         gui_view_.currentBufferView()->buffer().updateBuffer();
256 }
257
258
259 void TocWidget::on_sortCB_stateChanged(int state)
260 {
261         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
262         updateViewForce();
263 }
264
265
266 void TocWidget::on_persistentCB_stateChanged(int state)
267 {
268         persistent_ = state == Qt::Checked;
269 }
270
271
272 #if 0
273 /* FIXME (Ugras 17/11/06):
274 I have implemented a indexDepth function to get the model indices. In my
275 opinion, somebody should derive a new qvariant class for tocModelItem
276 which saves the string data and depth information. That will save the
277 depth calculation.  */
278
279 static int indexDepth(QModelIndex const & index, int depth = -1)
280 {
281         ++depth;
282         return index.parent() == QModelIndex()
283                 ? depth : indexDepth(index.parent(), depth);
284 }
285 #endif
286
287 void TocWidget::on_depthSL_valueChanged(int depth)
288 {
289         if (depth == depth_)
290                 return;
291         setTreeDepth(depth);
292         gui_view_.setFocus();
293 }
294
295
296 void TocWidget::setTreeDepth(int depth)
297 {
298         depth_ = depth;
299         if (!tocTV->model())
300                 return;
301
302         if (depth == 0)
303                 tocTV->collapseAll();
304         else
305                 tocTV->expandToDepth(depth - 1);
306 }
307
308
309 void TocWidget::on_typeCO_currentIndexChanged(int index)
310 {
311         if (index == -1)
312                 return;
313         current_type_ = typeCO->itemData(index).toString();
314         updateViewForce();
315         if (typeCO->hasFocus())
316                 gui_view_.setFocus();
317 }
318
319
320 void TocWidget::outline(FuncCode func_code)
321 {
322         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
323         if (list.isEmpty())
324                 return;
325         enableControls(false);
326         goTo(list[0]);
327         dispatch(FuncRequest(func_code));
328         enableControls(true);
329         gui_view_.setFocus();
330 }
331
332
333 void TocWidget::on_moveUpTB_clicked()
334 {
335         outline(LFUN_OUTLINE_UP);
336 }
337
338
339 void TocWidget::on_moveDownTB_clicked()
340 {
341         outline(LFUN_OUTLINE_DOWN);
342 }
343
344
345 void TocWidget::on_moveInTB_clicked()
346 {
347         outline(LFUN_OUTLINE_IN);
348 }
349
350
351 void TocWidget::on_moveOutTB_clicked()
352 {
353         outline(LFUN_OUTLINE_OUT);
354 }
355
356
357 void TocWidget::select(QModelIndex const & index)
358 {
359         if (!index.isValid()) {
360                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
361                 return;
362         }
363
364         tocTV->scrollTo(index);
365         tocTV->clearSelection();
366         tocTV->setCurrentIndex(index);
367 }
368
369
370 void TocWidget::enableControls(bool enable)
371 {
372         updateTB->setEnabled(enable);
373
374         if (!canOutline())
375                 enable = false;
376
377         moveUpTB->setEnabled(enable);
378         moveDownTB->setEnabled(enable);
379         moveInTB->setEnabled(enable);
380         moveOutTB->setEnabled(enable);
381 }
382
383
384 void TocWidget::updateView()
385 {
386 // Enable if you dont want the delaying business, cf #7138.
387 #ifndef DELAY_UPDATE_VIEW
388         updateViewForce();
389         return;
390 #endif
391         // already scheduled?
392         if (update_delay_ == -1)
393                 return;
394         QTimer::singleShot(update_delay_, this, SLOT(updateViewForce()));
395         // Subtler optimization for having the delay more UI invisible.
396         // We trigger update immediately for sparse editation actions,
397         // i.e. there was no editation/cursor movement in last 2 sec.
398         // At worst there will be +1 redraw after 2s in a such "calm" mode.
399         if (update_delay_ != 0)
400                 updateViewForce();
401         update_delay_ = -1;
402 }
403
404 void TocWidget::updateViewForce()
405 {
406         update_delay_ = 2000;
407         if (!gui_view_.documentBufferView()) {
408                 tocTV->setModel(0);
409                 depthSL->setMaximum(0);
410                 depthSL->setValue(0);
411                 setEnabled(false);
412                 return;
413         }
414         setEnabled(true);
415         bool const is_sortable = isSortable();
416         sortCB->setEnabled(is_sortable);
417         bool focus_ = tocTV->hasFocus();
418         tocTV->setEnabled(false);
419         tocTV->setUpdatesEnabled(false);
420
421         QAbstractItemModel * toc_model = 
422                         gui_view_.tocModels().model(current_type_);
423         if (tocTV->model() != toc_model) {
424                 tocTV->setModel(toc_model);
425                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
426                 if (persistent_)
427                         setTreeDepth(depth_);
428         }
429
430         sortCB->blockSignals(true);
431         sortCB->setChecked(is_sortable
432                 && gui_view_.tocModels().isSorted(current_type_));
433         sortCB->blockSignals(false);
434
435         bool const can_navigate_ = canNavigate();
436         persistentCB->setEnabled(can_navigate_);
437
438         bool controls_enabled = toc_model && toc_model->rowCount() > 0
439                 && !gui_view_.documentBufferView()->buffer().isReadonly();
440         enableControls(controls_enabled);
441
442         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
443         depthSL->setValue(depth_);
444         if (!persistent_ && can_navigate_)
445                 setTreeDepth(depth_);
446         if (can_navigate_) {
447                 persistentCB->setChecked(persistent_);
448                 select(gui_view_.tocModels().currentIndex(current_type_));
449         }
450         filterContents();
451         tocTV->setEnabled(true);
452         tocTV->setUpdatesEnabled(true);
453         if (focus_)
454                 tocTV->setFocus();
455 }
456
457
458 void TocWidget::filterContents()
459 {
460         if (!tocTV->model())
461                 return;
462
463         QModelIndexList indices = tocTV->model()->match(
464                 tocTV->model()->index(0, 0),
465                 Qt::DisplayRole, "*", -1,
466                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
467
468         int size = indices.size();
469         for (int i = 0; i < size; i++) {
470                 QModelIndex index = indices[i];
471                 bool const matches =
472                         index.data().toString().contains(
473                                 filterLE->text(), Qt::CaseInsensitive);
474                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
475         }
476         // recursively unhide parents of unhidden children 
477         for (int i = size - 1; i >= 0; i--) {
478                 QModelIndex index = indices[i];
479                 if (!tocTV->isRowHidden(index.row(), index.parent())
480                     && index.parent() != QModelIndex())
481                         tocTV->setRowHidden(index.parent().row(),
482                                             index.parent().parent(), false);
483         }
484 }
485
486
487 static QString decodeType(QString const & str)
488 {
489         QString type = str;
490         if (type.contains("tableofcontents"))
491                 type = "tableofcontents";
492         else if (type.contains("lstlistoflistings"))
493                 type = "listing";
494         else if (type.contains("floatlist")) {
495                 if (type.contains("\"figure"))
496                         type = "figure";
497                 else if (type.contains("\"table"))
498                         type = "table";
499                 else if (type.contains("\"algorithm"))
500                         type = "algorithm";
501         }
502         return type;
503 }
504
505
506 void TocWidget::init(QString const & str)
507 {
508         int new_index;
509         if (str.isEmpty())
510                 new_index = typeCO->findData(current_type_);
511         else
512                 new_index = typeCO->findData(decodeType(str));
513
514         // If everything else fails, settle on the table of contents which is
515         // guaranteed to exist.
516         if (new_index == -1) {
517                 current_type_ = "tableofcontents";
518                 new_index = typeCO->findData(current_type_);
519         } else {
520                 current_type_ = typeCO->itemData(new_index).toString();
521         }
522
523         typeCO->blockSignals(true);
524         typeCO->setCurrentIndex(new_index);
525         typeCO->blockSignals(false);
526
527         // no delay when the whole outliner is reseted.
528         update_delay_ = 0;
529 }
530
531 } // namespace frontend
532 } // namespace lyx
533
534 #include "moc_TocWidget.cpp"