]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
Amend f441590c
[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/", "outline-out", "svgz,png")));
56         moveInTB->setIcon(QIcon(getPixmap("images/", "outline-in", "svgz,png")));
57         moveUpTB->setIcon(QIcon(getPixmap("images/", "outline-up", "svgz,png")));
58         moveDownTB->setIcon(QIcon(getPixmap("images/", "outline-down", "svgz,png")));
59         updateTB->setIcon(QIcon(getPixmap("images/", "reload", "svgz,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                          || current_type_ == "table" 
124                      || current_type_ == "listing"
125                      || current_type_ == "figure")
126                 inset = &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(item.dit() != 0);
152                 return true;
153
154         case LFUN_LABEL_COPY_AS_REFERENCE: {
155                 // For labels in math, we need to supply the label as a string
156                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.str());
157                 if (inset)
158                         return inset->getStatus(cur, label_copy, status);
159                 break;
160         }
161
162         default:
163                 if (inset)
164                         return inset->getStatus(cur, tmpcmd, status);
165         }
166
167         return false;
168 }
169
170
171 void TocWidget::doDispatch(Cursor & cur, FuncRequest const & cmd)
172 {
173         Inset * inset = itemInset();
174         FuncRequest tmpcmd(cmd);
175
176         QModelIndex const & index = tocTV->currentIndex();
177         TocItem const & item =
178                 gui_view_.tocModels().currentItem(current_type_, index);
179
180         // Start an undo group.
181         cur.beginUndoGroup();
182
183         switch (cmd.action())
184         {
185         case LFUN_CHANGE_ACCEPT:
186         case LFUN_CHANGE_REJECT:
187                 dispatch(item.action());
188                 cur.dispatch(tmpcmd);
189                 break;
190
191         case LFUN_SECTION_SELECT:
192                 dispatch(item.action());
193                 cur.dispatch(tmpcmd);
194                 // necessary to get the selection drawn.
195                 cur.buffer()->changed(true);
196                 gui_view_.setFocus();
197                 break;
198
199         case LFUN_LABEL_COPY_AS_REFERENCE: {
200                 // For labels in math, we need to supply the label as a string
201                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.str());
202                 if (inset)
203                         inset->dispatch(cur, label_copy);
204                 break;
205         }
206
207         case LFUN_OUTLINE_UP:
208         case LFUN_OUTLINE_DOWN:
209         case LFUN_OUTLINE_IN:
210         case LFUN_OUTLINE_OUT:
211                 outline(cmd.action());
212                 break;
213
214         default:
215                 if (inset)
216                         inset->dispatch(cur, tmpcmd);
217         }
218         cur.endUndoGroup();
219 }
220
221
222 void TocWidget::on_tocTV_activated(QModelIndex const & index)
223 {
224         goTo(index);
225 }
226
227
228 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
229 {
230         Qt::MouseButtons const button = QApplication::mouseButtons();
231         if (button & Qt::LeftButton) {
232                 goTo(index);
233                 gui_view_.setFocus();
234         }
235 }
236
237
238 void TocWidget::goTo(QModelIndex const & index)
239 {
240         LYXERR(Debug::GUI, "goto " << index.row()
241                 << ", " << index.column());
242
243         gui_view_.tocModels().goTo(current_type_, index);
244 }
245
246
247 void TocWidget::on_updateTB_clicked()
248 {
249         // The backend update can take some time so we disable
250         // the controls while waiting.
251         enableControls(false);
252         gui_view_.currentBufferView()->buffer().updateBuffer();
253 }
254
255
256 void TocWidget::on_sortCB_stateChanged(int state)
257 {
258         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
259         updateViewForce();
260 }
261
262
263 void TocWidget::on_persistentCB_stateChanged(int state)
264 {
265         persistent_ = state == Qt::Checked;
266 }
267
268
269 #if 0
270 /* FIXME (Ugras 17/11/06):
271 I have implemented a indexDepth function to get the model indices. In my
272 opinion, somebody should derive a new qvariant class for tocModelItem
273 which saves the string data and depth information. That will save the
274 depth calculation.  */
275
276 static int indexDepth(QModelIndex const & index, int depth = -1)
277 {
278         ++depth;
279         return index.parent() == QModelIndex()
280                 ? depth : indexDepth(index.parent(), depth);
281 }
282 #endif
283
284 void TocWidget::on_depthSL_valueChanged(int depth)
285 {
286         if (depth == depth_)
287                 return;
288         setTreeDepth(depth);
289         gui_view_.setFocus();
290 }
291
292
293 void TocWidget::setTreeDepth(int depth)
294 {
295         depth_ = depth;
296         if (!tocTV->model())
297                 return;
298
299         if (depth == 0)
300                 tocTV->collapseAll();
301         else
302                 tocTV->expandToDepth(depth - 1);
303 }
304
305
306 void TocWidget::on_typeCO_currentIndexChanged(int index)
307 {
308         if (index == -1)
309                 return;
310         current_type_ = typeCO->itemData(index).toString();
311         updateViewForce();
312         if (typeCO->hasFocus())
313                 gui_view_.setFocus();
314 }
315
316
317 void TocWidget::outline(FuncCode func_code)
318 {
319         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
320         if (list.isEmpty())
321                 return;
322         enableControls(false);
323         goTo(list[0]);
324         dispatch(FuncRequest(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 void TocWidget::enableControls(bool enable)
368 {
369         updateTB->setEnabled(enable);
370
371         if (!canOutline())
372                 enable = false;
373
374         moveUpTB->setEnabled(enable);
375         moveDownTB->setEnabled(enable);
376         moveInTB->setEnabled(enable);
377         moveOutTB->setEnabled(enable);
378 }
379
380
381 void TocWidget::updateView()
382 {
383 // Enable if you dont want the delaying business, cf #7138.
384 #ifndef DELAY_UPDATE_VIEW
385         updateViewForce();
386         return;
387 #endif
388         // already scheduled?
389         if (update_delay_ == -1)
390                 return;
391         QTimer::singleShot(update_delay_, this, SLOT(updateViewForce()));
392         // Subtler optimization for having the delay more UI invisible.
393         // We trigger update immediately for sparse editation actions,
394         // i.e. there was no editation/cursor movement in last 2 sec.
395         // At worst there will be +1 redraw after 2s in a such "calm" mode.
396         if (update_delay_ != 0)
397                 updateViewForce();
398         update_delay_ = -1;
399 }
400
401 void TocWidget::updateViewForce()
402 {
403         update_delay_ = 2000;
404         if (!gui_view_.documentBufferView()) {
405                 tocTV->setModel(0);
406                 depthSL->setMaximum(0);
407                 depthSL->setValue(0);
408                 setEnabled(false);
409                 return;
410         }
411         setEnabled(true);
412         bool const is_sortable = isSortable();
413         sortCB->setEnabled(is_sortable);
414         bool focus_ = tocTV->hasFocus();
415         tocTV->setEnabled(false);
416         tocTV->setUpdatesEnabled(false);
417
418         QAbstractItemModel * toc_model = 
419                         gui_view_.tocModels().model(current_type_);
420         if (tocTV->model() != toc_model) {
421                 tocTV->setModel(toc_model);
422                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
423                 if (persistent_)
424                         setTreeDepth(depth_);
425         }
426
427         sortCB->blockSignals(true);
428         sortCB->setChecked(is_sortable
429                 && gui_view_.tocModels().isSorted(current_type_));
430         sortCB->blockSignals(false);
431
432         bool const can_navigate_ = canNavigate();
433         persistentCB->setEnabled(can_navigate_);
434
435         bool controls_enabled = toc_model && toc_model->rowCount() > 0
436                 && !gui_view_.documentBufferView()->buffer().isReadonly();
437         enableControls(controls_enabled);
438
439         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
440         depthSL->setValue(depth_);
441         if (!persistent_ && can_navigate_)
442                 setTreeDepth(depth_);
443         if (can_navigate_) {
444                 persistentCB->setChecked(persistent_);
445                 select(gui_view_.tocModels().currentIndex(current_type_));
446         }
447         filterContents();
448         tocTV->setEnabled(true);
449         tocTV->setUpdatesEnabled(true);
450         if (focus_)
451                 tocTV->setFocus();
452 }
453
454
455 void TocWidget::filterContents()
456 {
457         if (!tocTV->model())
458                 return;
459
460         QModelIndexList indices = tocTV->model()->match(
461                 tocTV->model()->index(0, 0),
462                 Qt::DisplayRole, "*", -1,
463                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
464
465         int size = indices.size();
466         for (int i = 0; i < size; i++) {
467                 QModelIndex index = indices[i];
468                 bool const matches =
469                         index.data().toString().contains(
470                                 filterLE->text(), Qt::CaseInsensitive);
471                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
472         }
473         // recursively unhide parents of unhidden children 
474         for (int i = size - 1; i >= 0; i--) {
475                 QModelIndex index = indices[i];
476                 if (!tocTV->isRowHidden(index.row(), index.parent())
477                     && index.parent() != QModelIndex())
478                         tocTV->setRowHidden(index.parent().row(),
479                                             index.parent().parent(), false);
480         }
481 }
482
483
484 static QString decodeType(QString const & str)
485 {
486         QString type = str;
487         if (type.contains("tableofcontents"))
488                 type = "tableofcontents";
489         else if (type.contains("lstlistoflistings"))
490                 type = "listing";
491         else if (type.contains("floatlist")) {
492                 if (type.contains("\"figure"))
493                         type = "figure";
494                 else if (type.contains("\"table"))
495                         type = "table";
496                 else if (type.contains("\"algorithm"))
497                         type = "algorithm";
498         }
499         return type;
500 }
501
502
503 void TocWidget::init(QString const & str)
504 {
505         int new_index;
506         if (str.isEmpty())
507                 new_index = typeCO->findData(current_type_);
508         else
509                 new_index = typeCO->findData(decodeType(str));
510
511         // If everything else fails, settle on the table of contents which is
512         // guaranteed to exist.
513         if (new_index == -1) {
514                 current_type_ = "tableofcontents";
515                 new_index = typeCO->findData(current_type_);
516         } else {
517                 current_type_ = typeCO->itemData(new_index).toString();
518         }
519
520         typeCO->blockSignals(true);
521         typeCO->setCurrentIndex(new_index);
522         typeCO->blockSignals(false);
523
524         // no delay when the whole outliner is reseted.
525         update_delay_ = 0;
526 }
527
528 } // namespace frontend
529 } // namespace lyx
530
531 #include "moc_TocWidget.cpp"