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 struct LayoutBox::Private
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)),
115 layoutItemDelegate_(new LayoutItemDelegate(parent)),
116 visibleCategories_(0), inShowPopup_(false)
118 filterModel_->setSourceModel(model_);
121 void resetFilter() { setFilter(QString()); }
123 void setFilter(QString const & s);
125 void countCategories();
131 DocumentClassConstPtr text_class_;
133 Inset const * inset_;
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
141 /// the character filter
144 LayoutItemDelegate * layoutItemDelegate_;
146 unsigned visibleCategories_;
152 static QString category(QAbstractItemModel const & model, int row)
154 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
158 static int headerHeight(QStyleOptionViewItem const & opt)
160 return opt.fontMetrics.height() * 8 / 10;
164 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
165 QModelIndex const & index) const
167 QStyleOptionViewItem opt = option;
169 // default background
170 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
173 if (lyxrc.group_layouts) {
174 QSortFilterProxyModel const * model =
175 static_cast<QSortFilterProxyModel const *>(index.model());
177 QString stdCat = category(*model->sourceModel(), 0);
178 QString cat = category(*index.model(), index.row());
180 // not the standard layout and not the same as in the previous line?
182 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
185 // draw unselected background
186 QStyle::State state = opt.state;
187 opt.state = opt.state & ~QStyle::State_Selected;
188 drawBackground(painter, opt, index);
191 // draw category header
192 drawCategoryHeader(painter, opt,
193 category(*index.model(), index.row()));
195 // move rect down below header
196 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
202 QItemDelegate::paint(painter, opt, index);
206 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
207 const QRect & /*rect*/, const QString & text ) const
209 QString utext = underlineFilter(text);
211 // Draw the rich text.
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);
220 doc.setDefaultFont(opt.font);
223 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
225 doc.rootFrame()->setFrameFormat(fmt);
227 painter->translate(opt.rect.x() + 5,
228 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
229 doc.documentLayout()->draw(painter, context);
234 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
235 QModelIndex const & index) const
237 QSortFilterProxyModel const * model =
238 static_cast<QSortFilterProxyModel const *>(index.model());
239 QSize size = QItemDelegate::sizeHint(opt, index);
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();
249 // we have to show \c cats many headers:
250 unsigned cats = layout_->d->visibleCategories_;
252 // and we have \c n items to distribute the needed space over
253 unsigned n = layout_->model()->rowCount();
255 // so the needed average height (rounded upwards) is:
256 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
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));
273 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
274 QString const & category) const
276 // slightly blended color
277 QColor lcol = opt.palette.text().color();
279 painter->setPen(lcol);
281 // set 80% scaled, bold font
282 QFont font = opt.font;
284 font.setWeight(QFont::Black);
285 font.setPointSize(opt.font.pointSize() * 8 / 10);
286 painter->setFont(font);
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();
295 painter->drawText(x, y, category);
297 // the vertical position of the line: middle of lower case chars
298 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
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);
305 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
309 QString LayoutItemDelegate::underlineFilter(QString const & s) const
311 QString const & f = layout_->filter();
315 // step through data item and put "(x)" for every matching character
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>";
327 r += s.mid(lastp + 1, p - lastp - 1);
328 r += QString("<u>") + s[p] + "</u>";
332 r += s.mid(lastp + 1);
337 static QString charFilterRegExp(QString const & filter)
340 for (int i = 0; i < filter.length(); ++i) {
343 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
345 re += ".*" + QRegExp::escape(c);
351 void LayoutBox::Private::setFilter(QString const & s)
353 // exit early if nothing has to be done
357 bool enabled = p->view()->updatesEnabled();
358 p->view()->setUpdatesEnabled(false);
360 // remember old selection
361 int sel = p->currentIndex();
363 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
366 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
369 // restore old selection
370 if (lastSel_ != -1) {
371 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
373 p->setCurrentIndex(i.row());
376 // Workaround to resize to content size
377 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
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
385 LASSERT(!inShowPopup_, /**/);
387 p->QComboBox::showPopup();
388 inShowPopup_ = false;
390 // The item delegate hack is off again. So trigger a relayout of the popup.
391 filterModel_->triggerLayoutChange();
394 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
395 "Press ESC to remove filter."),
396 qstring_to_ucs4(s)));
398 owner_.message(_("Enter characters to filter the layout list."));
401 p->view()->setUpdatesEnabled(enabled);
405 LayoutBox::LayoutBox(GuiView & owner)
406 : d(new Private(this, owner))
408 setSizeAdjustPolicy(QComboBox::AdjustToContents);
409 setFocusPolicy(Qt::ClickFocus);
410 setMinimumWidth(sizeHint().width());
411 setMaxVisibleItems(100);
413 setModel(d->filterModel_);
415 // for the filtering we have to intercept characters
416 view()->installEventFilter(this);
417 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
419 QObject::connect(this, SIGNAL(activated(int)),
420 this, SLOT(selected(int)));
422 updateContents(true);
426 LayoutBox::~LayoutBox() {
431 void LayoutBox::Private::countCategories()
433 int n = filterModel_->rowCount();
434 visibleCategories_ = 0;
435 if (n == 0 || !lyxrc.group_layouts)
438 // skip the "Standard" category
439 QString prevCat = model_->index(0, 2).data().toString();
442 for (int i = 0; i < n; ++i) {
443 QString cat = filterModel_->index(i, 2).data().toString();
445 ++visibleCategories_;
451 void LayoutBox::showPopup()
453 d->owner_.message(_("Enter characters to filter the layout list."));
455 bool enabled = view()->updatesEnabled();
456 view()->setUpdatesEnabled(false);
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 LASSERT(!d->inShowPopup_, /**/);
463 d->inShowPopup_ = true;
464 QComboBox::showPopup();
465 d->inShowPopup_ = false;
467 // The item delegate hack is off again. So trigger a relayout of the popup.
468 d->filterModel_->triggerLayoutChange();
470 view()->setUpdatesEnabled(enabled);
474 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
476 if (e->type() != QEvent::KeyPress)
477 return QComboBox::eventFilter(o, e);
479 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
480 bool modified = (ke->modifiers() == Qt::ControlModifier)
481 || (ke->modifiers() == Qt::AltModifier)
482 || (ke->modifiers() == Qt::MetaModifier);
486 if (!modified && !d->filter_.isEmpty()) {
491 case Qt::Key_Backspace:
493 // cut off one character
494 d->setFilter(d->filter_.left(d->filter_.length() - 1));
498 if (modified || ke->text().isEmpty())
500 // find chars for the filter string
502 for (int i = 0; i < ke->text().length(); ++i) {
503 QChar c = ke->text()[i];
504 if (c.isLetterOrNumber()
507 || c.category() == QChar::Separator_Space) {
512 // append new chars to the filter string
513 d->setFilter(d->filter_ + s);
519 return QComboBox::eventFilter(o, e);
523 void LayoutBox::setIconSize(QSize size)
526 bool small = size.height() < 20;
527 setAttribute(Qt::WA_MacSmallSize, small);
528 setAttribute(Qt::WA_MacNormalSize, !small);
530 (void)size; // suppress warning
535 void LayoutBox::set(docstring const & layout)
542 if (!d->text_class_->hasLayout(layout))
545 Layout const & lay = (*d->text_class_)[layout];
546 QString newLayout = toqstr(lay.name());
548 // If the layout is obsolete, use the new one instead.
549 docstring const & obs = lay.obsoleted_by();
551 newLayout = toqstr(obs);
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.");
562 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
564 LYXERR0("Trying to select non existent layout type " << newLayout);
568 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
572 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
573 bool sorted, bool sortedByCat, bool unknown)
575 QString qitem = toqstr(item);
576 docstring const loc_item = translateIfPossible(item);
577 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
579 QString qcat = toqstr(translateIfPossible(category));
581 QList<QStandardItem *> row;
582 row.append(new QStandardItem(titem));
583 row.append(new QStandardItem(qitem));
584 row.append(new QStandardItem(qcat));
586 // the first entry is easy
587 int const end = d->model_->rowCount();
589 d->model_->appendRow(row);
596 while (i < end && d->model_->item(i, 2)->text() != qcat)
600 // skip the Standard layout
604 // the simple unsorted case
607 // jump to the end of the category group
608 while (i < end && d->model_->item(i, 2)->text() == qcat)
610 d->model_->insertRow(i, row);
612 d->model_->appendRow(row);
616 // find row to insert the item, after the separator if it exists
618 // find alphabetic position
620 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
621 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
625 d->model_->insertRow(i, row);
629 void LayoutBox::updateContents(bool reset)
632 BufferView const * bv = d->owner_.currentBufferView();
636 d->text_class_.reset();
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());
650 d->text_class_ = text_class;
653 DocumentClass::const_iterator lit = d->text_class_->begin();
654 DocumentClass::const_iterator len = d->text_class_->end();
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
661 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
663 // if it doesn't require the empty layout, we skip it
664 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
666 // obsoleted layouts are skipped as well
667 if (!lit->obsoleted_by().empty())
669 addItemSort(name, lit->category(), lyxrc.sort_layouts,
670 lyxrc.group_layouts, lit->isUnknown());
673 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
674 d->countCategories();
676 // needed to recalculate size hint
678 setMinimumWidth(sizeHint().width());
679 setEnabled(!bv->buffer().isReadonly() &&
680 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
685 void LayoutBox::selected(int index)
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();
694 if (!d->text_class_) {
695 updateContents(false);
700 // find corresponding text class
701 if (d->text_class_->hasLayout(layoutName)) {
702 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
704 updateContents(false);
708 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
712 QString const & LayoutBox::filter() const
717 } // namespace frontend
720 #include "moc_LayoutBox.cpp"