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