]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/LayoutBox.cpp
Fix assertion that was revealed in my tree.
[lyx.git] / src / frontends / qt4 / LayoutBox.cpp
1 /**
2  * \file qt4/LayoutBox.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "LayoutBox.h"
19
20 #include "GuiView.h"
21 #include "qt_helpers.h"
22
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "Cursor.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LyXFunc.h"
30 #include "LyXRC.h"
31 #include "Paragraph.h"
32 #include "TextClass.h"
33
34 #include "insets/InsetText.h"
35
36 #include "support/debug.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
40
41 #include <QAbstractTextDocumentLayout>
42 #include <QHeaderView>
43 #include <QItemDelegate>
44 #include <QPainter>
45 #include <QSortFilterProxyModel>
46 #include <QStandardItemModel>
47 #include <QTextFrame>
48 #include <QToolBar>
49
50 using namespace std;
51 using namespace lyx::support;
52
53 namespace lyx {
54 namespace frontend {
55
56         
57 class LayoutItemDelegate : public QItemDelegate {
58 public:
59         ///
60         explicit LayoutItemDelegate(LayoutBox * layout)
61                 : QItemDelegate(layout), layout_(layout)
62         {}
63         ///
64         void paint(QPainter * painter, QStyleOptionViewItem const & option,
65                 QModelIndex const & index) const;
66         ///
67         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
68                 const QRect & /*rect*/, const QString & text ) const;
69         ///
70         QSize sizeHint(QStyleOptionViewItem const & opt,
71                 QModelIndex const & index) const;
72         
73 private:
74         ///
75         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
76                 QString const & category) const;        
77         ///
78         QString underlineFilter(QString const & s) const;
79         ///
80         LayoutBox * layout_;
81 };
82
83
84 class GuiLayoutFilterModel : public QSortFilterProxyModel {
85 public:
86         ///
87         GuiLayoutFilterModel(QObject * parent = 0)
88                 : QSortFilterProxyModel(parent)
89         {}
90         
91         ///
92         void triggerLayoutChange()
93         {
94                 layoutAboutToBeChanged();
95                 layoutChanged();
96         }
97 };
98
99
100 /////////////////////////////////////////////////////////////////////
101 //
102 // LayoutBox::Private
103 //
104 /////////////////////////////////////////////////////////////////////
105
106 struct LayoutBox::Private
107 {
108         Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
109                 // set the layout model with two columns
110                 // 1st: translated layout names
111                 // 2nd: raw layout names
112                 model_(new QStandardItemModel(0, 2, p)),
113                 filterModel_(new GuiLayoutFilterModel(p)),
114                 lastSel_(-1),
115                 layoutItemDelegate_(new LayoutItemDelegate(parent)),
116                 visibleCategories_(0), inShowPopup_(false)
117         {
118                 filterModel_->setSourceModel(model_);
119         }
120
121         void resetFilter() { setFilter(QString()); }
122         ///
123         void setFilter(QString const & s);
124         ///
125         void countCategories();
126         ///
127         LayoutBox * p;
128         ///
129         GuiView & owner_;
130         ///
131         DocumentClass const * text_class_;
132         ///
133         Inset const * inset_;
134         
135         /// the layout model: 1st column translated, 2nd column raw layout name
136         QStandardItemModel * model_;
137         /// the proxy model filtering \c model_
138         GuiLayoutFilterModel * filterModel_;
139         /// the (model-) index of the last successful selection
140         int lastSel_;
141         /// the character filter
142         QString filter_;
143         ///
144         LayoutItemDelegate * layoutItemDelegate_;
145         ///
146         unsigned visibleCategories_;
147         ///
148         bool inShowPopup_;
149 };
150
151
152 static QString category(QAbstractItemModel const & model, int row)
153 {
154         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
155 }
156
157
158 static int headerHeight(QStyleOptionViewItem const & opt)
159 {
160         return opt.fontMetrics.height() * 8 / 10;
161 }
162
163
164 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
165                                                            QModelIndex const & index) const
166 {
167         QStyleOptionViewItem opt = option;
168
169         // default background
170         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
171
172         // category header?
173         if (lyxrc.group_layouts) {
174                 QSortFilterProxyModel const * model =
175                         static_cast<QSortFilterProxyModel const *>(index.model());
176
177                 QString stdCat = category(*model->sourceModel(), 0);
178                 QString cat = category(*index.model(), index.row());
179
180                 // not the standard layout and not the same as in the previous line?
181                 if (stdCat != cat
182                         && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
183                         painter->save();
184
185                         // draw unselected background
186                         QStyle::State state = opt.state;
187                         opt.state = opt.state & ~QStyle::State_Selected;
188                         drawBackground(painter, opt, index);
189                         opt.state = state;
190
191                         // draw category header
192                         drawCategoryHeader(painter, opt, 
193                                 category(*index.model(), index.row()));
194
195                         // move rect down below header
196                         opt.rect.setTop(opt.rect.top() + headerHeight(opt));
197
198                         painter->restore();
199                 }
200         }
201
202         QItemDelegate::paint(painter, opt, index);
203 }
204
205
206 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
207                                                                          const QRect & /*rect*/, const QString & text ) const
208 {
209         QString utext = underlineFilter(text);
210
211         // Draw the rich text.
212         painter->save();
213         QColor col = opt.palette.text().color();
214         if (opt.state & QStyle::State_Selected)
215                 col = opt.palette.highlightedText().color();
216         QAbstractTextDocumentLayout::PaintContext context;
217         context.palette.setColor(QPalette::Text, col);
218
219         QTextDocument doc;
220         doc.setDefaultFont(opt.font);
221         doc.setHtml(utext);
222
223         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
224         fmt.setMargin(0);
225         doc.rootFrame()->setFrameFormat(fmt);
226
227         painter->translate(opt.rect.x() + 5,
228                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
229         doc.documentLayout()->draw(painter, context);
230         painter->restore();
231 }
232
233
234 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
235                                                                    QModelIndex const & index) const
236 {
237         QSortFilterProxyModel const * model =
238                 static_cast<QSortFilterProxyModel const *>(index.model());      
239         QSize size = QItemDelegate::sizeHint(opt, index);
240
241         /// QComboBox uses the first row height to estimate the
242         /// complete popup height during QComboBox::showPopup().
243         /// To avoid scrolling we have to sneak in space for the headers.
244         /// So we tweak this value accordingly. It's not nice, but the
245         /// only possible way it seems.
246         if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
247                 int itemHeight = size.height();
248
249                 // we have to show \c cats many headers:
250                 unsigned cats = layout_->d->visibleCategories_;
251
252                 // and we have \c n items to distribute the needed space over
253                 unsigned n = layout_->model()->rowCount();
254
255                 // so the needed average height (rounded upwards) is:
256                 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n); 
257                 return size;
258         }
259
260         // Add space for the category headers here?
261         // Not for the standard layout though.
262         QString stdCat = category(*model->sourceModel(), 0);
263         QString cat = category(*index.model(), index.row());
264         if (lyxrc.group_layouts && stdCat != cat
265                 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
266                 size.setHeight(size.height() + headerHeight(opt));
267         }
268
269         return size;
270 }
271
272
273 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
274                                                                                         QString const & category) const
275 {
276         // slightly blended color
277         QColor lcol = opt.palette.text().color();
278         lcol.setAlpha(127);
279         painter->setPen(lcol);
280
281         // set 80% scaled, bold font
282         QFont font = opt.font;
283         font.setBold(true);
284         font.setWeight(QFont::Black);
285         font.setPointSize(opt.font.pointSize() * 8 / 10);
286         painter->setFont(font);
287
288         // draw the centered text
289         QFontMetrics fm(font);
290         int w = fm.width(category);
291         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
292         int y = opt.rect.y() + fm.ascent();
293         int left = x;
294         int right = x + w;
295         painter->drawText(x, y, category);
296
297         // the vertical position of the line: middle of lower case chars
298         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
299
300         // draw the horizontal line
301         if (!category.isEmpty()) {
302                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
303                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
304         } else
305                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
306 }
307
308
309 QString LayoutItemDelegate::underlineFilter(QString const & s) const
310 {
311         QString const & f = layout_->filter();
312         if (f.isEmpty())
313                 return s;
314
315         // step through data item and put "(x)" for every matching character
316         QString r;
317         int lastp = -1;
318         layout_->filter();
319         for (int i = 0; i < f.length(); ++i) {
320                 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
321                 LASSERT(p != -1, /**/);
322                 if (lastp == p - 1 && lastp != -1) {
323                         // remove ")" and append "x)"
324                         r = r.left(r.length() - 4) + s[p] + "</u>";
325                 } else {
326                         // append "(x)"
327                         r += s.mid(lastp + 1, p - lastp - 1);
328                         r += QString("<u>") + s[p] + "</u>";
329                 }
330                 lastp = p;
331         }
332         r += s.mid(lastp + 1);
333         return r;
334 }
335
336
337 static QString charFilterRegExp(QString const & filter)
338 {
339         QString re;
340         for (int i = 0; i < filter.length(); ++i) {
341                 QChar c = filter[i];
342                 if (c.isLower())
343                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
344                 else
345                         re += ".*" + QRegExp::escape(c);
346         }
347         return re;
348 }
349
350
351 void LayoutBox::Private::setFilter(QString const & s)
352 {
353         bool enabled = p->view()->updatesEnabled();
354         p->view()->setUpdatesEnabled(false);
355
356         // remember old selection
357         int sel = p->currentIndex();
358         if (sel != -1)
359                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
360
361         filter_ = s;
362         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
363         countCategories();
364         
365         // restore old selection
366         if (lastSel_ != -1) {
367                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
368                 if (i.isValid())
369                         p->setCurrentIndex(i.row());
370         }
371         
372         // Workaround to resize to content size
373         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
374         //        does not help.
375         if (p->view()->isVisible()) {
376                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
377                 // the hack in the item delegate to make space for the headers.
378                 // We do not call our implementation of showPopup because that
379                 // would reset the filter again. This is only needed if the user clicks
380                 // on the QComboBox.
381                 LASSERT(!inShowPopup_, /**/);
382                 inShowPopup_ = true;
383                 p->QComboBox::showPopup();
384                 inShowPopup_ = false;
385
386                 // The item delegate hack is off again. So trigger a relayout of the popup.
387                 filterModel_->triggerLayoutChange();
388                 
389                 if (!s.isEmpty())
390                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
391                                                  "Press ESC to remove filter."),
392                                                qstring_to_ucs4(s)));
393                 else
394                         owner_.message(_("Enter characters to filter the layout list."));
395         }
396         
397         p->view()->setUpdatesEnabled(enabled);
398 }
399
400
401 LayoutBox::LayoutBox(QToolBar * bar, GuiView & owner)
402         : d(new Private(this, owner))
403 {
404         setSizeAdjustPolicy(QComboBox::AdjustToContents);
405         setFocusPolicy(Qt::ClickFocus);
406         setMinimumWidth(sizeHint().width());
407         setMaxVisibleItems(100);
408
409         setModel(d->filterModel_);
410
411         // for the filtering we have to intercept characters
412         view()->installEventFilter(this);
413         view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
414         
415         QObject::connect(this, SIGNAL(activated(int)),
416                 this, SLOT(selected(int)));
417         QObject::connect(bar, SIGNAL(iconSizeChanged(QSize)),
418                 this, SLOT(setIconSize(QSize)));
419
420         d->owner_.setLayoutDialog(this);
421         updateContents(true);
422 }
423
424
425 void LayoutBox::Private::countCategories()
426 {
427         int n = filterModel_->rowCount();
428         visibleCategories_ = 0;
429         if (n == 0 || !lyxrc.group_layouts)
430                 return;
431
432         // skip the "Standard" category
433         QString prevCat = model_->index(0, 2).data().toString(); 
434
435         // count categories
436         for (int i = 0; i < n; ++i) {
437                 QString cat = filterModel_->index(i, 2).data().toString();
438                 if (cat != prevCat)
439                         ++visibleCategories_;
440                 prevCat = cat;
441         }
442 }
443
444
445 void LayoutBox::showPopup()
446 {
447         d->owner_.message(_("Enter characters to filter the layout list."));
448
449         bool enabled = view()->updatesEnabled();
450         view()->setUpdatesEnabled(false);
451
452         d->resetFilter();
453
454         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
455         // the hack in the item delegate to make space for the headers.
456         LASSERT(!d->inShowPopup_, /**/);
457         d->inShowPopup_ = true;
458         QComboBox::showPopup();
459         d->inShowPopup_ = false;
460         
461         // The item delegate hack is off again. So trigger a relayout of the popup.
462         d->filterModel_->triggerLayoutChange();
463         
464         view()->setUpdatesEnabled(enabled);
465 }
466
467
468 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
469 {
470         if (e->type() != QEvent::KeyPress)
471                 return QComboBox::eventFilter(o, e);
472
473         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
474         bool modified = (ke->modifiers() == Qt::ControlModifier)
475                 || (ke->modifiers() == Qt::AltModifier)
476                 || (ke->modifiers() == Qt::MetaModifier);
477         
478         switch (ke->key()) {
479         case Qt::Key_Escape:
480                 if (!modified && !d->filter_.isEmpty()) {
481                         d->resetFilter();
482                         return true;
483                 }
484                 break;
485         case Qt::Key_Backspace:
486                 if (!modified) {
487                         // cut off one character
488                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
489                 }
490                 break;
491         default:
492                 if (modified || ke->text().isEmpty())
493                         break;
494                 // find chars for the filter string
495                 QString s;
496                 for (int i = 0; i < ke->text().length(); ++i) {
497                         QChar c = ke->text()[i];
498                         if (c.isLetterOrNumber()
499                             || c.isSymbol()
500                             || c.isPunct()
501                             || c.category() == QChar::Separator_Space) {
502                                 s += c;
503                         }
504                 }
505                 if (!s.isEmpty()) {
506                         // append new chars to the filter string
507                         d->setFilter(d->filter_ + s);
508                         return true;
509                 }
510                 break;
511         }
512
513         return QComboBox::eventFilter(o, e);
514 }
515
516         
517 void LayoutBox::setIconSize(QSize size)
518 {
519 #ifdef Q_WS_MACX
520         bool small = size.height() < 20;
521         setAttribute(Qt::WA_MacSmallSize, small);
522         setAttribute(Qt::WA_MacNormalSize, !small);
523 #else
524         (void)size; // suppress warning
525 #endif
526 }
527
528
529 void LayoutBox::set(docstring const & layout)
530 {
531         d->resetFilter();
532         
533         if (!d->text_class_)
534                 return;
535
536         Layout const & lay = (*d->text_class_)[layout];
537         QString newLayout = toqstr(lay.name());
538
539         // If the layout is obsolete, use the new one instead.
540         docstring const & obs = lay.obsoleted_by();
541         if (!obs.empty())
542                 newLayout = toqstr(obs);
543
544         int const curItem = currentIndex();
545         QModelIndex const mindex =
546                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
547         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
548         if (newLayout == currentLayout) {
549                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
550                 return;
551         }
552
553         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
554         if (r.empty()) {
555                 LYXERR0("Trying to select non existent layout type " << newLayout);
556                 return;
557         }
558
559         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
560 }
561
562
563 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
564         bool sorted, bool sortedByCat, bool unknown)
565 {
566         QString qitem = toqstr(item);
567         // FIXME This is wrong for RTL, I'd suppose.
568         QString titem = toqstr(translateIfPossible(item) +
569                                (unknown ? _(" (unknown)") : from_ascii("")));
570         QString qcat = toqstr(translateIfPossible(category));
571
572         QList<QStandardItem *> row;
573         row.append(new QStandardItem(titem));
574         row.append(new QStandardItem(qitem));
575         row.append(new QStandardItem(qcat));
576
577         // the first entry is easy
578         int const end = d->model_->rowCount();
579         if (end == 0) {
580                 d->model_->appendRow(row);
581                 return;
582         }
583
584         // find category
585         int i = 0;
586         if (sortedByCat) {
587                 while (i < end && d->model_->item(i, 2)->text() != qcat)
588                         ++i;
589         }
590
591         // skip the Standard layout
592         if (i == 0)
593                 ++i;
594         
595         // the simple unsorted case
596         if (!sorted) {
597                 if (sortedByCat) {
598                         // jump to the end of the category group
599                         while (i < end && d->model_->item(i, 2)->text() == qcat)
600                                 ++i;
601                         d->model_->insertRow(i, row);
602                 } else
603                         d->model_->appendRow(row);
604                 return;
605         }
606
607         // find row to insert the item, after the separator if it exists
608         if (i < end) {
609                 // find alphabetic position
610                 while (i != end
611                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
612                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
613                         ++i;
614         }
615
616         d->model_->insertRow(i, row);
617 }
618
619
620 void LayoutBox::updateContents(bool reset)
621 {
622         d->resetFilter();
623         
624         Buffer const * buffer = d->owner_.buffer();
625         if (!buffer) {
626                 d->model_->clear();
627                 setEnabled(false);
628                 d->text_class_ = 0;
629                 d->inset_ = 0;
630                 return;
631         }
632
633         // we'll only update the layout list if the text class has changed
634         // or we've moved from one inset to another
635         DocumentClass const * text_class = &buffer->params().documentClass();
636         Inset const * inset = 
637                 &(d->owner_.view()->cursor().innerText()->inset());
638         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
639                 set(d->owner_.view()->cursor().innerParagraph().layout().name());
640                 return;
641         }
642
643         d->inset_ = inset;
644         d->text_class_ = text_class;
645
646         d->model_->clear();
647         DocumentClass::const_iterator lit = d->text_class_->begin();
648         DocumentClass::const_iterator len = d->text_class_->end();
649
650         for (; lit != len; ++lit) {
651                 docstring const & name = lit->name();
652                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
653                 // if this inset requires the empty layout, we skip the default
654                 // layout
655                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
656                         continue;
657                 // if it doesn't require the empty layout, we skip it
658                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
659                         continue;
660                 // obsoleted layouts are skipped as well
661                 if (!lit->obsoleted_by().empty())
662                         continue;
663                 addItemSort(name, lit->category(), lyxrc.sort_layouts, 
664                                 lyxrc.group_layouts, lit->isUnknown());
665         }
666
667         set(d->owner_.view()->cursor().innerParagraph().layout().name());
668         d->countCategories();
669         
670         // needed to recalculate size hint
671         hide();
672         setMinimumWidth(sizeHint().width());
673         setEnabled(!buffer->isReadonly() &&
674                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
675         show();
676 }
677
678
679 void LayoutBox::selected(int index)
680 {
681         // get selection
682         QModelIndex mindex = d->filterModel_->mapToSource(
683                 d->filterModel_->index(index, 1));
684         docstring layoutName = qstring_to_ucs4(
685                 d->model_->itemFromIndex(mindex)->text());
686         d->owner_.setFocus();
687
688         if (!d->text_class_) {
689                 updateContents(false);
690                 d->resetFilter();
691                 return;
692         }
693
694         // find corresponding text class
695         if (d->text_class_->hasLayout(layoutName)) {
696                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
697                 theLyXFunc().setLyXView(&d->owner_);
698                 lyx::dispatch(func);
699                 updateContents(false);
700                 d->resetFilter();
701                 return;
702         }
703         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
704 }
705
706
707 QString const & LayoutBox::filter() const
708 {
709         return d->filter_;
710 }
711
712 } // namespace frontend
713 } // namespace lyx
714
715 #include "moc_LayoutBox.cpp"