]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/TocWidget.cpp
QDialogButtonBox for the remaining dialogs.
[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
182         Inset * inset = itemInset();
183         FuncRequest tmpcmd(cmd);
184
185         QModelIndex const & index = tocTV->currentIndex();
186         TocItem const & item =
187                 gui_view_.tocModels().currentItem(current_type_, index);
188
189         // Start an undo group.
190         cur.beginUndoGroup();
191
192         switch (cmd.action())
193         {
194         case LFUN_CHANGE_ACCEPT:
195         case LFUN_CHANGE_REJECT:
196                 dispatch(item.action());
197                 cur.dispatch(tmpcmd);
198                 break;
199
200         case LFUN_SECTION_SELECT:
201                 dispatch(item.action());
202                 cur.dispatch(tmpcmd);
203                 // necessary to get the selection drawn.
204                 cur.buffer()->changed(true);
205                 gui_view_.setFocus();
206                 break;
207
208         case LFUN_LABEL_COPY_AS_REFERENCE: {
209                 // For labels in math, we need to supply the label as a string
210                 FuncRequest label_copy(LFUN_LABEL_COPY_AS_REFERENCE, item.str());
211                 if (inset)
212                         inset->dispatch(cur, label_copy);
213                 break;
214         }
215
216         case LFUN_OUTLINE_UP:
217         case LFUN_OUTLINE_DOWN:
218         case LFUN_OUTLINE_IN:
219         case LFUN_OUTLINE_OUT:
220                 outline(cmd.action());
221                 break;
222
223         default:
224                 if (inset)
225                         inset->dispatch(cur, tmpcmd);
226         }
227         cur.endUndoGroup();
228 }
229
230
231 void TocWidget::on_tocTV_activated(QModelIndex const & index)
232 {
233         goTo(index);
234 }
235
236
237 void TocWidget::on_tocTV_pressed(QModelIndex const & index)
238 {
239
240         Qt::MouseButtons const button = QApplication::mouseButtons();
241         if (button & Qt::LeftButton) {
242                 goTo(index);
243                 gui_view_.setFocus();
244                 gui_view_.activateWindow();
245         }
246 }
247
248
249 void TocWidget::goTo(QModelIndex const & index)
250 {
251         LYXERR(Debug::GUI, "goto " << index.row()
252                 << ", " << index.column());
253
254         sendDispatch(gui_view_.tocModels().goTo(current_type_, index));
255 }
256
257
258 void TocWidget::on_updateTB_clicked()
259 {
260         // The backend update can take some time so we disable
261         // the controls while waiting.
262         enableControls(false);
263         gui_view_.currentBufferView()->buffer().updateBuffer();
264 }
265
266
267 void TocWidget::on_sortCB_stateChanged(int state)
268 {
269         gui_view_.tocModels().sort(current_type_, state == Qt::Checked);
270         updateViewNow();
271 }
272
273
274 void TocWidget::on_persistentCB_stateChanged(int state)
275 {
276         persistent_ = state == Qt::Checked;
277 }
278
279
280 #if 0
281 /* FIXME (Ugras 17/11/06):
282 I have implemented a indexDepth function to get the model indices. In my
283 opinion, somebody should derive a new qvariant class for tocModelItem
284 which saves the string data and depth information. That will save the
285 depth calculation.  */
286
287 static int indexDepth(QModelIndex const & index, int depth = -1)
288 {
289         ++depth;
290         return index.parent() == QModelIndex()
291                 ? depth : indexDepth(index.parent(), depth);
292 }
293 #endif
294
295 void TocWidget::on_depthSL_valueChanged(int depth)
296 {
297         if (depth == depth_)
298                 return;
299         setTreeDepth(depth);
300         gui_view_.setFocus();
301 }
302
303
304 void TocWidget::setTreeDepth(int depth)
305 {
306         depth_ = depth;
307         if (!tocTV->model())
308                 return;
309
310         if (depth == 0)
311                 tocTV->collapseAll();
312         else
313                 tocTV->expandToDepth(depth - 1);
314 }
315
316
317 void TocWidget::on_typeCO_currentIndexChanged(int index)
318 {
319
320         if (index == -1)
321                 return;
322         current_type_ = typeCO->itemData(index).toString();
323         updateViewNow();
324         if (typeCO->hasFocus())
325                 gui_view_.setFocus();
326 }
327
328
329 void TocWidget::outline(FuncCode func_code)
330 {
331         QModelIndexList const & list = tocTV->selectionModel()->selectedIndexes();
332         if (list.isEmpty())
333                 return;
334
335         //if another window is active, this attempt will fail,
336         //but it will work at least for the second attempt
337         gui_view_.activateWindow(); 
338
339         enableControls(false);
340         goTo(list[0]);
341         sendDispatch(FuncRequest(func_code));
342         enableControls(true);
343         gui_view_.setFocus();
344 }
345
346
347 void TocWidget::sendDispatch(FuncRequest fr)
348 {
349
350         fr.setViewOrigin(&gui_view_);
351         DispatchResult dr=dispatch(fr);
352         if (dr.error())
353                 gui_view_.message(dr.message());
354 }
355
356
357 void TocWidget::on_moveUpTB_clicked()
358 {
359         outline(LFUN_OUTLINE_UP);
360 }
361
362
363 void TocWidget::on_moveDownTB_clicked()
364 {
365         outline(LFUN_OUTLINE_DOWN);
366 }
367
368
369 void TocWidget::on_moveInTB_clicked()
370 {
371         outline(LFUN_OUTLINE_IN);
372 }
373
374
375 void TocWidget::on_moveOutTB_clicked()
376 {
377         outline(LFUN_OUTLINE_OUT);
378 }
379
380
381 void TocWidget::select(QModelIndex const & index)
382 {
383         if (!index.isValid()) {
384                 LYXERR(Debug::GUI, "TocWidget::select(): QModelIndex is invalid!");
385                 return;
386         }
387
388         tocTV->scrollTo(index);
389         tocTV->clearSelection();
390         tocTV->setCurrentIndex(index);
391 }
392
393
394 void TocWidget::enableControls(bool enable)
395 {
396         updateTB->setEnabled(enable);
397
398         if (!canOutline())
399                 enable = false;
400
401         moveUpTB->setEnabled(enable);
402         moveDownTB->setEnabled(enable);
403         moveInTB->setEnabled(enable);
404         moveOutTB->setEnabled(enable);
405 }
406
407
408 void TocWidget::updateView()
409 {
410         if (!gui_view_.documentBufferView()) {
411                 tocTV->setModel(0);
412                 depthSL->setMaximum(0);
413                 depthSL->setValue(0);
414                 setEnabled(false);
415                 return;
416         }
417         setEnabled(true);
418         bool const is_sortable = isSortable();
419         sortCB->setEnabled(is_sortable);
420         bool focus = tocTV->hasFocus();
421         tocTV->setEnabled(false);
422         tocTV->setUpdatesEnabled(false);
423
424         QAbstractItemModel * toc_model =
425                         gui_view_.tocModels().model(current_type_);
426         if (tocTV->model() != toc_model) {
427                 tocTV->setModel(toc_model);
428                 tocTV->setEditTriggers(QAbstractItemView::NoEditTriggers);
429                 if (persistent_)
430                         setTreeDepth(depth_);
431         }
432
433         sortCB->blockSignals(true);
434         sortCB->setChecked(is_sortable
435                 && gui_view_.tocModels().isSorted(current_type_));
436         sortCB->blockSignals(false);
437
438         persistentCB->setEnabled(canNavigate());
439
440         bool controls_enabled = toc_model && toc_model->rowCount() > 0
441                 && !gui_view_.documentBufferView()->buffer().isReadonly();
442         enableControls(controls_enabled);
443
444         depthSL->setMaximum(gui_view_.tocModels().depth(current_type_));
445         depthSL->setValue(depth_);
446         tocTV->setEnabled(true);
447         tocTV->setUpdatesEnabled(true);
448         if (focus)
449                 tocTV->setFocus();
450
451         // Expensive operations are on a timer.  We finish the update immediately
452         // for sparse edition actions, i.e. there was no edition/cursor movement
453         // recently, then every 300ms.
454         if (!timer_->isActive()) {
455                 finishUpdateView();
456                 timer_->start(300);
457         }
458 }
459
460
461 void TocWidget::updateViewNow()
462 {
463         timer_->stop();
464         updateView();
465 }
466
467
468 void TocWidget::finishUpdateView()
469 {
470         // Profiling shows that this is the expensive stuff in the context of typing
471         // text and moving with arrows. For bigger operations, this is negligible,
472         // and outweighted by TocModels::reset() anyway.
473         if (canNavigate()) {
474                 if (!persistent_)
475                         setTreeDepth(depth_);
476                 persistentCB->setChecked(persistent_);
477                 // select the item at current cursor location
478                 if (gui_view_.documentBufferView()) {
479                         DocIterator const & dit = gui_view_.documentBufferView()->cursor();
480                         select(gui_view_.tocModels().currentIndex(current_type_, dit));
481                 }
482         }
483         filterContents();
484 }
485
486
487 void TocWidget::filterContents()
488 {
489         if (!tocTV->model())
490                 return;
491
492         QModelIndexList indices = tocTV->model()->match(
493                 tocTV->model()->index(0, 0),
494                 Qt::DisplayRole, "*", -1,
495                 Qt::MatchFlags(Qt::MatchWildcard|Qt::MatchRecursive));
496
497         int size = indices.size();
498         for (int i = 0; i < size; i++) {
499                 QModelIndex index = indices[i];
500                 bool const matches =
501                         index.data().toString().contains(
502                                 filterLE->text(), Qt::CaseInsensitive);
503                 tocTV->setRowHidden(index.row(), index.parent(), !matches);
504         }
505         // recursively unhide parents of unhidden children
506         for (int i = size - 1; i >= 0; i--) {
507                 QModelIndex index = indices[i];
508                 if (!tocTV->isRowHidden(index.row(), index.parent())
509                     && index.parent() != QModelIndex())
510                         tocTV->setRowHidden(index.parent().row(),
511                                             index.parent().parent(), false);
512         }
513 }
514
515
516 static QString decodeType(QString const & str)
517 {
518         QString type = str;
519         if (type.contains("tableofcontents"))
520                 type = "tableofcontents";
521         else if (type.contains("lstlistoflistings"))
522                 type = "listing";
523         else if (type.contains("floatlist")) {
524                 if (type.contains("\"figure"))
525                         type = "figure";
526                 else if (type.contains("\"table"))
527                         type = "table";
528                 else if (type.contains("\"algorithm"))
529                         type = "algorithm";
530         }
531         return type;
532 }
533
534
535 void TocWidget::init(QString const & str)
536 {
537         int new_index;
538         if (str.isEmpty())
539                 new_index = typeCO->findData(current_type_);
540         else
541                 new_index = typeCO->findData(decodeType(str));
542
543         // If everything else fails, settle on the table of contents which is
544         // guaranteed to exist.
545         if (new_index == -1) {
546                 current_type_ = "tableofcontents";
547                 new_index = typeCO->findData(current_type_);
548         } else {
549                 current_type_ = typeCO->itemData(new_index).toString();
550         }
551
552         typeCO->blockSignals(true);
553         typeCO->setCurrentIndex(new_index);
554         typeCO->blockSignals(false);
555         updateViewNow();
556 }
557
558 } // namespace frontend
559 } // namespace lyx
560
561 #include "moc_TocWidget.cpp"