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 bool enabled = p->view()->updatesEnabled();
354 p->view()->setUpdatesEnabled(false);
356 // remember old selection
357 int sel = p->currentIndex();
359 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
362 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
365 // restore old selection
366 if (lastSel_ != -1) {
367 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
369 p->setCurrentIndex(i.row());
372 // Workaround to resize to content size
373 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
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
381 LASSERT(!inShowPopup_, /**/);
383 p->QComboBox::showPopup();
384 inShowPopup_ = false;
386 // The item delegate hack is off again. So trigger a relayout of the popup.
387 filterModel_->triggerLayoutChange();
390 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
391 "Press ESC to remove filter."),
392 qstring_to_ucs4(s)));
394 owner_.message(_("Enter characters to filter the layout list."));
397 p->view()->setUpdatesEnabled(enabled);
401 LayoutBox::LayoutBox(GuiView & owner)
402 : d(new Private(this, owner))
404 setSizeAdjustPolicy(QComboBox::AdjustToContents);
405 setFocusPolicy(Qt::ClickFocus);
406 setMinimumWidth(sizeHint().width());
407 setMaxVisibleItems(100);
409 setModel(d->filterModel_);
411 // for the filtering we have to intercept characters
412 view()->installEventFilter(this);
413 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
415 QObject::connect(this, SIGNAL(activated(int)),
416 this, SLOT(selected(int)));
418 updateContents(true);
422 LayoutBox::~LayoutBox() {
427 void LayoutBox::Private::countCategories()
429 int n = filterModel_->rowCount();
430 visibleCategories_ = 0;
431 if (n == 0 || !lyxrc.group_layouts)
434 // skip the "Standard" category
435 QString prevCat = model_->index(0, 2).data().toString();
438 for (int i = 0; i < n; ++i) {
439 QString cat = filterModel_->index(i, 2).data().toString();
441 ++visibleCategories_;
447 void LayoutBox::showPopup()
449 d->owner_.message(_("Enter characters to filter the layout list."));
451 bool enabled = view()->updatesEnabled();
452 view()->setUpdatesEnabled(false);
456 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
457 // the hack in the item delegate to make space for the headers.
458 LASSERT(!d->inShowPopup_, /**/);
459 d->inShowPopup_ = true;
460 QComboBox::showPopup();
461 d->inShowPopup_ = false;
463 // The item delegate hack is off again. So trigger a relayout of the popup.
464 d->filterModel_->triggerLayoutChange();
466 view()->setUpdatesEnabled(enabled);
470 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
472 if (e->type() != QEvent::KeyPress)
473 return QComboBox::eventFilter(o, e);
475 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
476 bool modified = (ke->modifiers() == Qt::ControlModifier)
477 || (ke->modifiers() == Qt::AltModifier)
478 || (ke->modifiers() == Qt::MetaModifier);
482 if (!modified && !d->filter_.isEmpty()) {
487 case Qt::Key_Backspace:
489 // cut off one character
490 d->setFilter(d->filter_.left(d->filter_.length() - 1));
494 if (modified || ke->text().isEmpty())
496 // find chars for the filter string
498 for (int i = 0; i < ke->text().length(); ++i) {
499 QChar c = ke->text()[i];
500 if (c.isLetterOrNumber()
503 || c.category() == QChar::Separator_Space) {
508 // append new chars to the filter string
509 d->setFilter(d->filter_ + s);
515 return QComboBox::eventFilter(o, e);
519 void LayoutBox::setIconSize(QSize size)
522 bool small = size.height() < 20;
523 setAttribute(Qt::WA_MacSmallSize, small);
524 setAttribute(Qt::WA_MacNormalSize, !small);
526 (void)size; // suppress warning
531 void LayoutBox::set(docstring const & layout)
535 if (!d->text_class_.get())
538 if (!d->text_class_->hasLayout(layout))
541 Layout const & lay = (*d->text_class_)[layout];
542 QString newLayout = toqstr(lay.name());
544 // If the layout is obsolete, use the new one instead.
545 docstring const & obs = lay.obsoleted_by();
547 newLayout = toqstr(obs);
549 int const curItem = currentIndex();
550 QModelIndex const mindex =
551 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
552 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
553 if (newLayout == currentLayout) {
554 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
558 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
560 LYXERR0("Trying to select non existent layout type " << newLayout);
564 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
568 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
569 bool sorted, bool sortedByCat, bool unknown)
571 QString qitem = toqstr(item);
572 // FIXME This is wrong for RTL, I'd suppose.
573 QString titem = toqstr(translateIfPossible(item) +
574 (unknown ? _(" (unknown)") : from_ascii("")));
575 QString qcat = toqstr(translateIfPossible(category));
577 QList<QStandardItem *> row;
578 row.append(new QStandardItem(titem));
579 row.append(new QStandardItem(qitem));
580 row.append(new QStandardItem(qcat));
582 // the first entry is easy
583 int const end = d->model_->rowCount();
585 d->model_->appendRow(row);
592 while (i < end && d->model_->item(i, 2)->text() != qcat)
596 // skip the Standard layout
600 // the simple unsorted case
603 // jump to the end of the category group
604 while (i < end && d->model_->item(i, 2)->text() == qcat)
606 d->model_->insertRow(i, row);
608 d->model_->appendRow(row);
612 // find row to insert the item, after the separator if it exists
614 // find alphabetic position
616 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
617 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
621 d->model_->insertRow(i, row);
625 void LayoutBox::updateContents(bool reset)
628 BufferView const * bv = d->owner_.currentBufferView();
632 d->text_class_.reset();
636 // we'll only update the layout list if the text class has changed
637 // or we've moved from one inset to another
638 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
639 Inset const * inset = &(bv->cursor().innerText()->inset());
640 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
641 set(bv->cursor().innerParagraph().layout().name());
646 d->text_class_ = text_class;
649 DocumentClass::const_iterator lit = d->text_class_->begin();
650 DocumentClass::const_iterator len = d->text_class_->end();
652 for (; lit != len; ++lit) {
653 docstring const & name = lit->name();
654 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
655 // if this inset requires the empty layout, we skip the default
657 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
659 // if it doesn't require the empty layout, we skip it
660 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
662 // obsoleted layouts are skipped as well
663 if (!lit->obsoleted_by().empty())
665 addItemSort(name, lit->category(), lyxrc.sort_layouts,
666 lyxrc.group_layouts, lit->isUnknown());
669 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
670 d->countCategories();
672 // needed to recalculate size hint
674 setMinimumWidth(sizeHint().width());
675 setEnabled(!bv->buffer().isReadonly() &&
676 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
681 void LayoutBox::selected(int index)
684 QModelIndex mindex = d->filterModel_->mapToSource(
685 d->filterModel_->index(index, 1));
686 docstring layoutName = qstring_to_ucs4(
687 d->model_->itemFromIndex(mindex)->text());
688 d->owner_.setFocus();
690 if (!d->text_class_.get()) {
691 updateContents(false);
696 // find corresponding text class
697 if (d->text_class_->hasLayout(layoutName)) {
698 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
700 updateContents(false);
704 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
708 QString const & LayoutBox::filter() const
713 } // namespace frontend
716 #include "moc_LayoutBox.cpp"