]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/LayoutBox.cpp
On Linux show in crash message box the backtrace
[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 "DocumentClassPtr.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LyX.h"
31 #include "LyXRC.h"
32 #include "Paragraph.h"
33 #include "TextClass.h"
34
35 #include "insets/InsetText.h"
36
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41
42 #include <QAbstractTextDocumentLayout>
43 #include <QHeaderView>
44 #include <QItemDelegate>
45 #include <QPainter>
46 #include <QSortFilterProxyModel>
47 #include <QStandardItemModel>
48 #include <QTextFrame>
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         DocumentClassConstPtr 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, continue);
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         // exit early if nothing has to be done
354         if (filter_ == s)
355                 return;
356
357         bool enabled = p->view()->updatesEnabled();
358         p->view()->setUpdatesEnabled(false);
359
360         // remember old selection
361         int sel = p->currentIndex();
362         if (sel != -1)
363                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
364
365         filter_ = s;
366         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
367         countCategories();
368         
369         // restore old selection
370         if (lastSel_ != -1) {
371                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
372                 if (i.isValid())
373                         p->setCurrentIndex(i.row());
374         }
375         
376         // Workaround to resize to content size
377         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
378         //        does not help.
379         if (p->view()->isVisible()) {
380                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
381                 // the hack in the item delegate to make space for the headers.
382                 // We do not call our implementation of showPopup because that
383                 // would reset the filter again. This is only needed if the user clicks
384                 // on the QComboBox.
385                 LATTEST(!inShowPopup_);
386                 inShowPopup_ = true;
387                 p->QComboBox::showPopup();
388                 inShowPopup_ = false;
389
390                 // The item delegate hack is off again. So trigger a relayout of the popup.
391                 filterModel_->triggerLayoutChange();
392                 
393                 if (!s.isEmpty())
394                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
395                                                  "Press ESC to remove filter."),
396                                                qstring_to_ucs4(s)));
397                 else
398                         owner_.message(_("Enter characters to filter the layout list."));
399         }
400         
401         p->view()->setUpdatesEnabled(enabled);
402 }
403
404
405 LayoutBox::LayoutBox(GuiView & owner)
406         : d(new Private(this, owner))
407 {
408         setSizeAdjustPolicy(QComboBox::AdjustToContents);
409         setFocusPolicy(Qt::ClickFocus);
410         setMinimumWidth(sizeHint().width());
411         setMaxVisibleItems(100);
412
413         setModel(d->filterModel_);
414
415         // for the filtering we have to intercept characters
416         view()->installEventFilter(this);
417         view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
418         
419         QObject::connect(this, SIGNAL(activated(int)),
420                 this, SLOT(selected(int)));
421
422         updateContents(true);
423 }
424
425
426 LayoutBox::~LayoutBox() {
427         delete d;
428 }
429
430
431 void LayoutBox::Private::countCategories()
432 {
433         int n = filterModel_->rowCount();
434         visibleCategories_ = 0;
435         if (n == 0 || !lyxrc.group_layouts)
436                 return;
437
438         // skip the "Standard" category
439         QString prevCat = model_->index(0, 2).data().toString(); 
440
441         // count categories
442         for (int i = 0; i < n; ++i) {
443                 QString cat = filterModel_->index(i, 2).data().toString();
444                 if (cat != prevCat)
445                         ++visibleCategories_;
446                 prevCat = cat;
447         }
448 }
449
450
451 void LayoutBox::showPopup()
452 {
453         d->owner_.message(_("Enter characters to filter the layout list."));
454
455         bool enabled = view()->updatesEnabled();
456         view()->setUpdatesEnabled(false);
457
458         d->resetFilter();
459
460         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
461         // the hack in the item delegate to make space for the headers.
462         LATTEST(!d->inShowPopup_);
463         d->inShowPopup_ = true;
464         QComboBox::showPopup();
465         d->inShowPopup_ = false;
466         
467         // The item delegate hack is off again. So trigger a relayout of the popup.
468         d->filterModel_->triggerLayoutChange();
469         
470         view()->setUpdatesEnabled(enabled);
471 }
472
473
474 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
475 {
476         if (e->type() != QEvent::KeyPress)
477                 return QComboBox::eventFilter(o, e);
478
479         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
480         bool modified = (ke->modifiers() == Qt::ControlModifier)
481                 || (ke->modifiers() == Qt::AltModifier)
482                 || (ke->modifiers() == Qt::MetaModifier);
483         
484         switch (ke->key()) {
485         case Qt::Key_Escape:
486                 if (!modified && !d->filter_.isEmpty()) {
487                         d->resetFilter();
488                         return true;
489                 }
490                 break;
491         case Qt::Key_Backspace:
492                 if (!modified) {
493                         // cut off one character
494                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
495                 }
496                 break;
497         default:
498                 if (modified || ke->text().isEmpty())
499                         break;
500                 // find chars for the filter string
501                 QString s;
502                 for (int i = 0; i < ke->text().length(); ++i) {
503                         QChar c = ke->text()[i];
504                         if (c.isLetterOrNumber()
505                             || c.isSymbol()
506                             || c.isPunct()
507                             || c.category() == QChar::Separator_Space) {
508                                 s += c;
509                         }
510                 }
511                 if (!s.isEmpty()) {
512                         // append new chars to the filter string
513                         d->setFilter(d->filter_ + s);
514                         return true;
515                 }
516                 break;
517         }
518
519         return QComboBox::eventFilter(o, e);
520 }
521
522         
523 void LayoutBox::setIconSize(QSize size)
524 {
525 #ifdef Q_WS_MACX
526         bool small = size.height() < 20;
527         setAttribute(Qt::WA_MacSmallSize, small);
528         setAttribute(Qt::WA_MacNormalSize, !small);
529 #else
530         (void)size; // suppress warning
531 #endif
532 }
533
534
535 void LayoutBox::set(docstring const & layout)
536 {
537         d->resetFilter();
538
539         if (!d->text_class_)
540                 return;
541
542         if (!d->text_class_->hasLayout(layout))
543                 return;
544
545         Layout const & lay = (*d->text_class_)[layout];
546         QString newLayout = toqstr(lay.name());
547
548         // If the layout is obsolete, use the new one instead.
549         docstring const & obs = lay.obsoleted_by();
550         if (!obs.empty())
551                 newLayout = toqstr(obs);
552
553         int const curItem = currentIndex();
554         QModelIndex const mindex =
555                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
556         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
557         if (newLayout == currentLayout) {
558                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
559                 return;
560         }
561
562         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
563         if (r.empty()) {
564                 LYXERR0("Trying to select non existent layout type " << newLayout);
565                 return;
566         }
567
568         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
569 }
570
571
572 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
573         bool sorted, bool sortedByCat, bool unknown)
574 {
575         QString qitem = toqstr(item);
576         docstring const loc_item = translateIfPossible(item);
577         QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
578                                 : toqstr(loc_item);
579         QString qcat = toqstr(translateIfPossible(category));
580
581         QList<QStandardItem *> row;
582         row.append(new QStandardItem(titem));
583         row.append(new QStandardItem(qitem));
584         row.append(new QStandardItem(qcat));
585
586         // the first entry is easy
587         int const end = d->model_->rowCount();
588         if (end == 0) {
589                 d->model_->appendRow(row);
590                 return;
591         }
592
593         // find category
594         int i = 0;
595         if (sortedByCat) {
596                 while (i < end && d->model_->item(i, 2)->text() != qcat)
597                         ++i;
598         }
599
600         // skip the Standard layout
601         if (i == 0)
602                 ++i;
603         
604         // the simple unsorted case
605         if (!sorted) {
606                 if (sortedByCat) {
607                         // jump to the end of the category group
608                         while (i < end && d->model_->item(i, 2)->text() == qcat)
609                                 ++i;
610                         d->model_->insertRow(i, row);
611                 } else
612                         d->model_->appendRow(row);
613                 return;
614         }
615
616         // find row to insert the item, after the separator if it exists
617         if (i < end) {
618                 // find alphabetic position
619                 while (i != end
620                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
621                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
622                         ++i;
623         }
624
625         d->model_->insertRow(i, row);
626 }
627
628
629 void LayoutBox::updateContents(bool reset)
630 {
631         d->resetFilter();
632         BufferView const * bv = d->owner_.currentBufferView();
633         if (!bv) {
634                 d->model_->clear();
635                 setEnabled(false);
636                 d->text_class_.reset();
637                 d->inset_ = 0;
638                 return;
639         }
640         // we'll only update the layout list if the text class has changed
641         // or we've moved from one inset to another
642         DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
643         Inset const * inset = &(bv->cursor().innerText()->inset());
644         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
645                 set(bv->cursor().innerParagraph().layout().name());
646                 return;
647         }
648
649         d->inset_ = inset;
650         d->text_class_ = text_class;
651
652         d->model_->clear();
653         DocumentClass::const_iterator lit = d->text_class_->begin();
654         DocumentClass::const_iterator len = d->text_class_->end();
655
656         for (; lit != len; ++lit) {
657                 docstring const & name = lit->name();
658                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
659                 // if this inset requires the empty layout, we skip the default
660                 // layout
661                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
662                         continue;
663                 // if it doesn't require the empty layout, we skip it
664                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
665                         continue;
666                 // obsoleted layouts are skipped as well
667                 if (!lit->obsoleted_by().empty())
668                         continue;
669                 addItemSort(name, lit->category(), lyxrc.sort_layouts, 
670                                 lyxrc.group_layouts, lit->isUnknown());
671         }
672
673         set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
674         d->countCategories();
675         
676         // needed to recalculate size hint
677         hide();
678         setMinimumWidth(sizeHint().width());
679         setEnabled(!bv->buffer().isReadonly() &&
680                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
681         show();
682 }
683
684
685 void LayoutBox::selected(int index)
686 {
687         // get selection
688         QModelIndex mindex = d->filterModel_->mapToSource(
689                 d->filterModel_->index(index, 1));
690         docstring layoutName = qstring_to_ucs4(
691                 d->model_->itemFromIndex(mindex)->text());
692         d->owner_.setFocus();
693
694         if (!d->text_class_) {
695                 updateContents(false);
696                 d->resetFilter();
697                 return;
698         }
699
700         // find corresponding text class
701         if (d->text_class_->hasLayout(layoutName)) {
702                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
703                 lyx::dispatch(func);
704                 updateContents(false);
705                 d->resetFilter();
706                 return;
707         }
708         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
709 }
710
711
712 QString const & LayoutBox::filter() const
713 {
714         return d->filter_;
715 }
716
717 } // namespace frontend
718 } // namespace lyx
719
720 #include "moc_LayoutBox.cpp"