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 "FuncRequest.h"
28 #include "FuncStatus.h"
31 #include "Paragraph.h"
32 #include "TextClass.h"
34 #include "insets/InsetText.h"
36 #include "support/debug.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
41 #include <QAbstractTextDocumentLayout>
42 #include <QHeaderView>
43 #include <QItemDelegate>
45 #include <QSortFilterProxyModel>
46 #include <QStandardItemModel>
50 using namespace lyx::support;
56 class LayoutItemDelegate : public QItemDelegate {
59 explicit LayoutItemDelegate(LayoutBox * layout)
60 : QItemDelegate(layout), layout_(layout)
63 void paint(QPainter * painter, QStyleOptionViewItem const & option,
64 QModelIndex const & index) const;
66 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
67 const QRect & /*rect*/, const QString & text ) const;
69 QSize sizeHint(QStyleOptionViewItem const & opt,
70 QModelIndex const & index) const;
74 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
75 QString const & category) const;
77 QString underlineFilter(QString const & s) const;
83 class GuiLayoutFilterModel : public QSortFilterProxyModel {
86 GuiLayoutFilterModel(QObject * parent = 0)
87 : QSortFilterProxyModel(parent)
91 void triggerLayoutChange()
93 layoutAboutToBeChanged();
99 /////////////////////////////////////////////////////////////////////
101 // LayoutBox::Private
103 /////////////////////////////////////////////////////////////////////
105 struct LayoutBox::Private
107 Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
108 // set the layout model with two columns
109 // 1st: translated layout names
110 // 2nd: raw layout names
111 model_(new QStandardItemModel(0, 2, p)),
112 filterModel_(new GuiLayoutFilterModel(p)),
114 layoutItemDelegate_(new LayoutItemDelegate(parent)),
115 visibleCategories_(0), inShowPopup_(false)
117 filterModel_->setSourceModel(model_);
120 void resetFilter() { setFilter(QString()); }
122 void setFilter(QString const & s);
124 void countCategories();
130 DocumentClass const * text_class_;
132 Inset const * inset_;
134 /// the layout model: 1st column translated, 2nd column raw layout name
135 QStandardItemModel * model_;
136 /// the proxy model filtering \c model_
137 GuiLayoutFilterModel * filterModel_;
138 /// the (model-) index of the last successful selection
140 /// the character filter
143 LayoutItemDelegate * layoutItemDelegate_;
145 unsigned visibleCategories_;
151 static QString category(QAbstractItemModel const & model, int row)
153 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
157 static int headerHeight(QStyleOptionViewItem const & opt)
159 return opt.fontMetrics.height() * 8 / 10;
163 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
164 QModelIndex const & index) const
166 QStyleOptionViewItem opt = option;
168 // default background
169 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
172 if (lyxrc.group_layouts) {
173 QSortFilterProxyModel const * model =
174 static_cast<QSortFilterProxyModel const *>(index.model());
176 QString stdCat = category(*model->sourceModel(), 0);
177 QString cat = category(*index.model(), index.row());
179 // not the standard layout and not the same as in the previous line?
181 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
184 // draw unselected background
185 QStyle::State state = opt.state;
186 opt.state = opt.state & ~QStyle::State_Selected;
187 drawBackground(painter, opt, index);
190 // draw category header
191 drawCategoryHeader(painter, opt,
192 category(*index.model(), index.row()));
194 // move rect down below header
195 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
201 QItemDelegate::paint(painter, opt, index);
205 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
206 const QRect & /*rect*/, const QString & text ) const
208 QString utext = underlineFilter(text);
210 // Draw the rich text.
212 QColor col = opt.palette.text().color();
213 if (opt.state & QStyle::State_Selected)
214 col = opt.palette.highlightedText().color();
215 QAbstractTextDocumentLayout::PaintContext context;
216 context.palette.setColor(QPalette::Text, col);
219 doc.setDefaultFont(opt.font);
222 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
224 doc.rootFrame()->setFrameFormat(fmt);
226 painter->translate(opt.rect.x() + 5,
227 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
228 doc.documentLayout()->draw(painter, context);
233 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
234 QModelIndex const & index) const
236 QSortFilterProxyModel const * model =
237 static_cast<QSortFilterProxyModel const *>(index.model());
238 QSize size = QItemDelegate::sizeHint(opt, index);
240 /// QComboBox uses the first row height to estimate the
241 /// complete popup height during QComboBox::showPopup().
242 /// To avoid scrolling we have to sneak in space for the headers.
243 /// So we tweak this value accordingly. It's not nice, but the
244 /// only possible way it seems.
245 if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
246 int itemHeight = size.height();
248 // we have to show \c cats many headers:
249 unsigned cats = layout_->d->visibleCategories_;
251 // and we have \c n items to distribute the needed space over
252 unsigned n = layout_->model()->rowCount();
254 // so the needed average height (rounded upwards) is:
255 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
259 // Add space for the category headers here?
260 // Not for the standard layout though.
261 QString stdCat = category(*model->sourceModel(), 0);
262 QString cat = category(*index.model(), index.row());
263 if (lyxrc.group_layouts && stdCat != cat
264 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
265 size.setHeight(size.height() + headerHeight(opt));
272 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
273 QString const & category) const
275 // slightly blended color
276 QColor lcol = opt.palette.text().color();
278 painter->setPen(lcol);
280 // set 80% scaled, bold font
281 QFont font = opt.font;
283 font.setWeight(QFont::Black);
284 font.setPointSize(opt.font.pointSize() * 8 / 10);
285 painter->setFont(font);
287 // draw the centered text
288 QFontMetrics fm(font);
289 int w = fm.width(category);
290 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
291 int y = opt.rect.y() + fm.ascent();
294 painter->drawText(x, y, category);
296 // the vertical position of the line: middle of lower case chars
297 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
299 // draw the horizontal line
300 if (!category.isEmpty()) {
301 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
302 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
304 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
308 QString LayoutItemDelegate::underlineFilter(QString const & s) const
310 QString const & f = layout_->filter();
314 // step through data item and put "(x)" for every matching character
318 for (int i = 0; i < f.length(); ++i) {
319 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
320 LASSERT(p != -1, /**/);
321 if (lastp == p - 1 && lastp != -1) {
322 // remove ")" and append "x)"
323 r = r.left(r.length() - 4) + s[p] + "</u>";
326 r += s.mid(lastp + 1, p - lastp - 1);
327 r += QString("<u>") + s[p] + "</u>";
331 r += s.mid(lastp + 1);
336 static QString charFilterRegExp(QString const & filter)
339 for (int i = 0; i < filter.length(); ++i) {
342 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
344 re += ".*" + QRegExp::escape(c);
350 void LayoutBox::Private::setFilter(QString const & s)
352 bool enabled = p->view()->updatesEnabled();
353 p->view()->setUpdatesEnabled(false);
355 // remember old selection
356 int sel = p->currentIndex();
358 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
361 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
364 // restore old selection
365 if (lastSel_ != -1) {
366 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
368 p->setCurrentIndex(i.row());
371 // Workaround to resize to content size
372 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
374 if (p->view()->isVisible()) {
375 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
376 // the hack in the item delegate to make space for the headers.
377 // We do not call our implementation of showPopup because that
378 // would reset the filter again. This is only needed if the user clicks
380 LASSERT(!inShowPopup_, /**/);
382 p->QComboBox::showPopup();
383 inShowPopup_ = false;
385 // The item delegate hack is off again. So trigger a relayout of the popup.
386 filterModel_->triggerLayoutChange();
389 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
390 "Press ESC to remove filter."),
391 qstring_to_ucs4(s)));
393 owner_.message(_("Enter characters to filter the layout list."));
396 p->view()->setUpdatesEnabled(enabled);
400 LayoutBox::LayoutBox(GuiView & owner)
401 : d(new Private(this, owner))
403 setSizeAdjustPolicy(QComboBox::AdjustToContents);
404 setFocusPolicy(Qt::ClickFocus);
405 setMinimumWidth(sizeHint().width());
406 setMaxVisibleItems(100);
408 setModel(d->filterModel_);
410 // for the filtering we have to intercept characters
411 view()->installEventFilter(this);
412 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
414 QObject::connect(this, SIGNAL(activated(int)),
415 this, SLOT(selected(int)));
417 updateContents(true);
421 LayoutBox::~LayoutBox() {
426 void LayoutBox::Private::countCategories()
428 int n = filterModel_->rowCount();
429 visibleCategories_ = 0;
430 if (n == 0 || !lyxrc.group_layouts)
433 // skip the "Standard" category
434 QString prevCat = model_->index(0, 2).data().toString();
437 for (int i = 0; i < n; ++i) {
438 QString cat = filterModel_->index(i, 2).data().toString();
440 ++visibleCategories_;
446 void LayoutBox::showPopup()
448 d->owner_.message(_("Enter characters to filter the layout list."));
450 bool enabled = view()->updatesEnabled();
451 view()->setUpdatesEnabled(false);
455 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
456 // the hack in the item delegate to make space for the headers.
457 LASSERT(!d->inShowPopup_, /**/);
458 d->inShowPopup_ = true;
459 QComboBox::showPopup();
460 d->inShowPopup_ = false;
462 // The item delegate hack is off again. So trigger a relayout of the popup.
463 d->filterModel_->triggerLayoutChange();
465 view()->setUpdatesEnabled(enabled);
469 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
471 if (e->type() != QEvent::KeyPress)
472 return QComboBox::eventFilter(o, e);
474 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
475 bool modified = (ke->modifiers() == Qt::ControlModifier)
476 || (ke->modifiers() == Qt::AltModifier)
477 || (ke->modifiers() == Qt::MetaModifier);
481 if (!modified && !d->filter_.isEmpty()) {
486 case Qt::Key_Backspace:
488 // cut off one character
489 d->setFilter(d->filter_.left(d->filter_.length() - 1));
493 if (modified || ke->text().isEmpty())
495 // find chars for the filter string
497 for (int i = 0; i < ke->text().length(); ++i) {
498 QChar c = ke->text()[i];
499 if (c.isLetterOrNumber()
502 || c.category() == QChar::Separator_Space) {
507 // append new chars to the filter string
508 d->setFilter(d->filter_ + s);
514 return QComboBox::eventFilter(o, e);
518 void LayoutBox::setIconSize(QSize size)
521 bool small = size.height() < 20;
522 setAttribute(Qt::WA_MacSmallSize, small);
523 setAttribute(Qt::WA_MacNormalSize, !small);
525 (void)size; // suppress warning
530 void LayoutBox::set(docstring const & layout)
537 if (!(*d->text_class_).hasLayout(layout))
540 Layout const & lay = (*d->text_class_)[layout];
541 QString newLayout = toqstr(lay.name());
543 // If the layout is obsolete, use the new one instead.
544 docstring const & obs = lay.obsoleted_by();
546 newLayout = toqstr(obs);
548 int const curItem = currentIndex();
549 QModelIndex const mindex =
550 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
551 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
552 if (newLayout == currentLayout) {
553 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
557 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
559 LYXERR0("Trying to select non existent layout type " << newLayout);
563 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
567 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
568 bool sorted, bool sortedByCat, bool unknown)
570 QString qitem = toqstr(item);
571 // FIXME This is wrong for RTL, I'd suppose.
572 QString titem = toqstr(translateIfPossible(item) +
573 (unknown ? _(" (unknown)") : from_ascii("")));
574 QString qcat = toqstr(translateIfPossible(category));
576 QList<QStandardItem *> row;
577 row.append(new QStandardItem(titem));
578 row.append(new QStandardItem(qitem));
579 row.append(new QStandardItem(qcat));
581 // the first entry is easy
582 int const end = d->model_->rowCount();
584 d->model_->appendRow(row);
591 while (i < end && d->model_->item(i, 2)->text() != qcat)
595 // skip the Standard layout
599 // the simple unsorted case
602 // jump to the end of the category group
603 while (i < end && d->model_->item(i, 2)->text() == qcat)
605 d->model_->insertRow(i, row);
607 d->model_->appendRow(row);
611 // find row to insert the item, after the separator if it exists
613 // find alphabetic position
615 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
616 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
620 d->model_->insertRow(i, row);
624 void LayoutBox::updateContents(bool reset)
627 BufferView const * bv = d->owner_.currentBufferView();
635 // we'll only update the layout list if the text class has changed
636 // or we've moved from one inset to another
637 DocumentClass const * text_class = &(bv->buffer().params().documentClass());
638 Inset const * inset = &(bv->cursor().innerText()->inset());
639 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
640 set(bv->cursor().innerParagraph().layout().name());
645 d->text_class_ = text_class;
648 DocumentClass::const_iterator lit = d->text_class_->begin();
649 DocumentClass::const_iterator len = d->text_class_->end();
651 for (; lit != len; ++lit) {
652 docstring const & name = lit->name();
653 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
654 // if this inset requires the empty layout, we skip the default
656 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
658 // if it doesn't require the empty layout, we skip it
659 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
661 // obsoleted layouts are skipped as well
662 if (!lit->obsoleted_by().empty())
664 addItemSort(name, lit->category(), lyxrc.sort_layouts,
665 lyxrc.group_layouts, lit->isUnknown());
668 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
669 d->countCategories();
671 // needed to recalculate size hint
673 setMinimumWidth(sizeHint().width());
674 setEnabled(!bv->buffer().isReadonly() &&
675 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
680 void LayoutBox::selected(int index)
683 QModelIndex mindex = d->filterModel_->mapToSource(
684 d->filterModel_->index(index, 1));
685 docstring layoutName = qstring_to_ucs4(
686 d->model_->itemFromIndex(mindex)->text());
687 d->owner_.setFocus();
689 if (!d->text_class_) {
690 updateContents(false);
695 // find corresponding text class
696 if (d->text_class_->hasLayout(layoutName)) {
697 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
699 updateContents(false);
703 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
707 QString const & LayoutBox::filter() const
712 } // namespace frontend
715 #include "moc_LayoutBox.cpp"