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.
6 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
10 * \author Stefan Schimanski
11 * \author Abdelrazak Younes
13 * Full author contact details are available in file CREDITS.
18 #include "LayoutBox.h"
21 #include "qt_helpers.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
27 #include "DocumentClassPtr.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
32 #include "Paragraph.h"
33 #include "TextClass.h"
35 #include "insets/InsetText.h"
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
42 #include <QAbstractTextDocumentLayout>
43 #include <QHeaderView>
44 #include <QItemDelegate>
46 #include <QSortFilterProxyModel>
47 #include <QStandardItemModel>
51 using namespace lyx::support;
57 class LayoutItemDelegate : public QItemDelegate {
60 explicit LayoutItemDelegate(LayoutBox * layout)
61 : QItemDelegate(layout), layout_(layout)
64 void paint(QPainter * painter, QStyleOptionViewItem const & option,
65 QModelIndex const & index) const;
67 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
68 const QRect & /*rect*/, const QString & text ) const;
70 QSize sizeHint(QStyleOptionViewItem const & opt,
71 QModelIndex const & index) const;
75 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
76 QString const & category) const;
78 QString underlineFilter(QString const & s) const;
84 class GuiLayoutFilterModel : public QSortFilterProxyModel {
87 GuiLayoutFilterModel(QObject * parent = 0)
88 : QSortFilterProxyModel(parent)
92 void triggerLayoutChange()
94 layoutAboutToBeChanged();
100 /////////////////////////////////////////////////////////////////////
102 // LayoutBox::Private
104 /////////////////////////////////////////////////////////////////////
106 class LayoutBox::Private
109 Private(Private const &);
110 void operator=(Private const &);
112 Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
114 // set the layout model with two columns
115 // 1st: translated layout names
116 // 2nd: raw layout names
117 model_(new QStandardItemModel(0, 2, p)),
118 filterModel_(new GuiLayoutFilterModel(p)),
120 layoutItemDelegate_(new LayoutItemDelegate(parent)),
121 visibleCategories_(0), inShowPopup_(false)
123 filterModel_->setSourceModel(model_);
126 void resetFilter() { setFilter(QString()); }
128 void setFilter(QString const & s);
130 void countCategories();
136 DocumentClassConstPtr text_class_;
138 Inset const * inset_;
140 /// the layout model: 1st column translated, 2nd column raw layout name
141 QStandardItemModel * model_;
142 /// the proxy model filtering \c model_
143 GuiLayoutFilterModel * filterModel_;
144 /// the (model-) index of the last successful selection
146 /// the character filter
149 LayoutItemDelegate * layoutItemDelegate_;
151 unsigned visibleCategories_;
157 static QString category(QAbstractItemModel const & model, int row)
159 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
163 static int headerHeight(QStyleOptionViewItem const & opt)
165 return opt.fontMetrics.height() * 8 / 10;
169 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
170 QModelIndex const & index) const
172 QStyleOptionViewItem opt = option;
174 // default background
175 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
178 if (lyxrc.group_layouts) {
179 QSortFilterProxyModel const * model =
180 static_cast<QSortFilterProxyModel const *>(index.model());
182 QString stdCat = category(*model->sourceModel(), 0);
183 QString cat = category(*index.model(), index.row());
185 // not the standard layout and not the same as in the previous line?
187 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
190 // draw unselected background
191 QStyle::State state = opt.state;
192 opt.state = opt.state & ~QStyle::State_Selected;
193 drawBackground(painter, opt, index);
196 // draw category header
197 drawCategoryHeader(painter, opt,
198 category(*index.model(), index.row()));
200 // move rect down below header
201 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
207 QItemDelegate::paint(painter, opt, index);
211 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
212 const QRect & /*rect*/, const QString & text ) const
214 QString utext = underlineFilter(text);
216 // Draw the rich text.
218 QColor col = opt.palette.text().color();
219 if (opt.state & QStyle::State_Selected)
220 col = opt.palette.highlightedText().color();
221 QAbstractTextDocumentLayout::PaintContext context;
222 context.palette.setColor(QPalette::Text, col);
225 doc.setDefaultFont(opt.font);
228 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
230 doc.rootFrame()->setFrameFormat(fmt);
232 painter->translate(opt.rect.x() + 5,
233 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
234 doc.documentLayout()->draw(painter, context);
239 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
240 QModelIndex const & index) const
242 QSortFilterProxyModel const * model =
243 static_cast<QSortFilterProxyModel const *>(index.model());
244 QSize size = QItemDelegate::sizeHint(opt, index);
246 /// QComboBox uses the first row height to estimate the
247 /// complete popup height during QComboBox::showPopup().
248 /// To avoid scrolling we have to sneak in space for the headers.
249 /// So we tweak this value accordingly. It's not nice, but the
250 /// only possible way it seems.
251 if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
252 int itemHeight = size.height();
254 // we have to show \c cats many headers:
255 unsigned cats = layout_->d->visibleCategories_;
257 // and we have \c n items to distribute the needed space over
258 unsigned n = layout_->model()->rowCount();
260 // so the needed average height (rounded upwards) is:
261 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
265 // Add space for the category headers here?
266 // Not for the standard layout though.
267 QString stdCat = category(*model->sourceModel(), 0);
268 QString cat = category(*index.model(), index.row());
269 if (lyxrc.group_layouts && stdCat != cat
270 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
271 size.setHeight(size.height() + headerHeight(opt));
278 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
279 QString const & category) const
281 // slightly blended color
282 QColor lcol = opt.palette.text().color();
284 painter->setPen(lcol);
286 // set 80% scaled, bold font
287 QFont font = opt.font;
289 font.setWeight(QFont::Black);
290 font.setPointSize(opt.font.pointSize() * 8 / 10);
291 painter->setFont(font);
293 // draw the centered text
294 QFontMetrics fm(font);
295 int w = fm.width(category);
296 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
297 int y = opt.rect.y() + fm.ascent();
300 painter->drawText(x, y, category);
302 // the vertical position of the line: middle of lower case chars
303 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
305 // draw the horizontal line
306 if (!category.isEmpty()) {
307 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
308 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
310 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
314 QString LayoutItemDelegate::underlineFilter(QString const & s) const
316 QString const & f = layout_->filter();
320 // step through data item and put "(x)" for every matching character
323 for (int i = 0; i < f.length(); ++i) {
324 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
327 if (lastp == p - 1 && lastp != -1) {
328 // remove ")" and append "x)"
329 r = r.left(r.length() - 4) + s[p] + "</u>";
332 r += s.mid(lastp + 1, p - lastp - 1);
333 r += QString("<u>") + s[p] + "</u>";
337 r += s.mid(lastp + 1);
342 static QString charFilterRegExp(QString const & filter)
345 for (int i = 0; i < filter.length(); ++i) {
348 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
350 re += ".*" + QRegExp::escape(c);
356 void LayoutBox::Private::setFilter(QString const & s)
358 // exit early if nothing has to be done
362 bool enabled = p->view()->updatesEnabled();
363 p->view()->setUpdatesEnabled(false);
365 // remember old selection
366 int sel = p->currentIndex();
368 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
371 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
374 // restore old selection
375 if (lastSel_ != -1) {
376 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
378 p->setCurrentIndex(i.row());
381 // Workaround to resize to content size
382 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
384 if (p->view()->isVisible()) {
385 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
386 // the hack in the item delegate to make space for the headers.
387 // We do not call our implementation of showPopup because that
388 // would reset the filter again. This is only needed if the user clicks
390 LATTEST(!inShowPopup_);
392 p->QComboBox::showPopup();
393 inShowPopup_ = false;
395 // The item delegate hack is off again. So trigger a relayout of the popup.
396 filterModel_->triggerLayoutChange();
399 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
400 "Press ESC to remove filter."),
401 qstring_to_ucs4(s)));
403 owner_.message(_("Enter characters to filter the layout list."));
406 p->view()->setUpdatesEnabled(enabled);
410 LayoutBox::LayoutBox(GuiView & owner)
411 : d(new Private(this, owner))
413 setSizeAdjustPolicy(QComboBox::AdjustToContents);
414 setFocusPolicy(Qt::ClickFocus);
415 setMinimumWidth(sizeHint().width());
416 setMaxVisibleItems(100);
418 setModel(d->filterModel_);
420 // for the filtering we have to intercept characters
421 view()->installEventFilter(this);
422 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
424 QObject::connect(this, SIGNAL(activated(int)),
425 this, SLOT(selected(int)));
427 updateContents(true);
431 LayoutBox::~LayoutBox() {
436 void LayoutBox::Private::countCategories()
438 int n = filterModel_->rowCount();
439 visibleCategories_ = 0;
440 if (n == 0 || !lyxrc.group_layouts)
443 // skip the "Standard" category
444 QString prevCat = model_->index(0, 2).data().toString();
447 for (int i = 0; i < n; ++i) {
448 QString cat = filterModel_->index(i, 2).data().toString();
450 ++visibleCategories_;
456 void LayoutBox::showPopup()
458 d->owner_.message(_("Enter characters to filter the layout list."));
460 bool enabled = view()->updatesEnabled();
461 view()->setUpdatesEnabled(false);
465 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
466 // the hack in the item delegate to make space for the headers.
467 LATTEST(!d->inShowPopup_);
468 d->inShowPopup_ = true;
469 QComboBox::showPopup();
470 d->inShowPopup_ = false;
472 // The item delegate hack is off again. So trigger a relayout of the popup.
473 d->filterModel_->triggerLayoutChange();
475 view()->setUpdatesEnabled(enabled);
479 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
481 if (e->type() != QEvent::KeyPress)
482 return QComboBox::eventFilter(o, e);
484 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
485 bool modified = (ke->modifiers() == Qt::ControlModifier)
486 || (ke->modifiers() == Qt::AltModifier)
487 || (ke->modifiers() == Qt::MetaModifier);
491 if (!modified && !d->filter_.isEmpty()) {
496 case Qt::Key_Backspace:
498 // cut off one character
499 d->setFilter(d->filter_.left(d->filter_.length() - 1));
503 if (modified || ke->text().isEmpty())
505 // find chars for the filter string
507 for (int i = 0; i < ke->text().length(); ++i) {
508 QChar c = ke->text()[i];
509 if (c.isLetterOrNumber()
512 || c.category() == QChar::Separator_Space) {
517 // append new chars to the filter string
518 d->setFilter(d->filter_ + s);
524 return QComboBox::eventFilter(o, e);
528 void LayoutBox::setIconSize(QSize size)
531 bool small = size.height() < 20;
532 setAttribute(Qt::WA_MacSmallSize, small);
533 setAttribute(Qt::WA_MacNormalSize, !small);
535 (void)size; // suppress warning
540 void LayoutBox::set(docstring const & layout)
547 if (!d->text_class_->hasLayout(layout))
550 Layout const & lay = (*d->text_class_)[layout];
551 QString newLayout = toqstr(lay.name());
553 // If the layout is obsolete, use the new one instead.
554 docstring const & obs = lay.obsoleted_by();
556 newLayout = toqstr(obs);
558 int const curItem = currentIndex();
559 QModelIndex const mindex =
560 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
561 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
562 if (newLayout == currentLayout) {
563 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
567 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
569 LYXERR0("Trying to select non existent layout type " << newLayout);
573 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
577 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
578 bool sorted, bool sortedByCat, bool unknown)
580 QString qitem = toqstr(item);
581 docstring const loc_item = translateIfPossible(item);
582 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
584 QString qcat = toqstr(translateIfPossible(category));
586 QList<QStandardItem *> row;
587 row.append(new QStandardItem(titem));
588 row.append(new QStandardItem(qitem));
589 row.append(new QStandardItem(qcat));
591 // the first entry is easy
592 int const end = d->model_->rowCount();
594 d->model_->appendRow(row);
601 while (i < end && d->model_->item(i, 2)->text() != qcat)
605 // skip the Standard layout
609 // the simple unsorted case
612 // jump to the end of the category group
613 while (i < end && d->model_->item(i, 2)->text() == qcat)
615 d->model_->insertRow(i, row);
617 d->model_->appendRow(row);
621 // find row to insert the item, after the separator if it exists
623 // find alphabetic position
625 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
626 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
630 d->model_->insertRow(i, row);
634 void LayoutBox::updateContents(bool reset)
637 BufferView const * bv = d->owner_.currentBufferView();
641 setMinimumWidth(sizeHint().width());
642 d->text_class_.reset();
646 // we'll only update the layout list if the text class has changed
647 // or we've moved from one inset to another
648 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
649 Inset const * inset = &(bv->cursor().innerText()->inset());
650 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
651 set(bv->cursor().innerParagraph().layout().name());
656 d->text_class_ = text_class;
659 DocumentClass::const_iterator lit = d->text_class_->begin();
660 DocumentClass::const_iterator len = d->text_class_->end();
662 for (; lit != len; ++lit) {
663 docstring const & name = lit->name();
664 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
665 // if this inset requires the empty layout, we skip the default
667 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
669 // if it doesn't require the empty layout, we skip it
670 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
672 // obsoleted layouts are skipped as well
673 if (!lit->obsoleted_by().empty())
675 addItemSort(name, lit->category(), lyxrc.sort_layouts,
676 lyxrc.group_layouts, lit->isUnknown());
679 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
680 d->countCategories();
682 setMinimumWidth(sizeHint().width());
683 setEnabled(!bv->buffer().isReadonly() &&
684 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
688 void LayoutBox::selected(int index)
691 QModelIndex mindex = d->filterModel_->mapToSource(
692 d->filterModel_->index(index, 1));
693 docstring layoutName = qstring_to_ucs4(
694 d->model_->itemFromIndex(mindex)->text());
695 d->owner_.setFocus();
697 if (!d->text_class_) {
698 updateContents(false);
703 // find corresponding text class
704 if (d->text_class_->hasLayout(layoutName)) {
705 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
707 updateContents(false);
711 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
715 QString const & LayoutBox::filter() const
720 } // namespace frontend
723 #include "moc_LayoutBox.cpp"