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)
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_;
155 static QString category(QAbstractItemModel const & model, int row)
157 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
161 static int headerHeight(QStyleOptionViewItem const & opt)
163 return opt.fontMetrics.height() * 8 / 10;
167 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
168 QModelIndex const & index) const
170 QStyleOptionViewItem opt = option;
172 // default background
173 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
176 if (lyxrc.group_layouts) {
177 QSortFilterProxyModel const * model =
178 static_cast<QSortFilterProxyModel const *>(index.model());
180 QString stdCat = category(*model->sourceModel(), 0);
181 QString cat = category(*index.model(), index.row());
183 // not the standard layout and not the same as in the previous line?
185 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
188 // draw unselected background
189 QStyle::State state = opt.state;
190 opt.state = opt.state & ~QStyle::State_Selected;
191 drawBackground(painter, opt, index);
194 // draw category header
195 drawCategoryHeader(painter, opt,
196 category(*index.model(), index.row()));
198 // move rect down below header
199 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
205 QItemDelegate::paint(painter, opt, index);
209 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
210 const QRect & /*rect*/, const QString & text ) const
212 QString utext = underlineFilter(text);
214 // Draw the rich text.
216 QColor col = opt.palette.text().color();
217 if (opt.state & QStyle::State_Selected)
218 col = opt.palette.highlightedText().color();
219 QAbstractTextDocumentLayout::PaintContext context;
220 context.palette.setColor(QPalette::Text, col);
223 doc.setDefaultFont(opt.font);
226 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
228 doc.rootFrame()->setFrameFormat(fmt);
230 painter->translate(opt.rect.x() + 5,
231 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
232 doc.documentLayout()->draw(painter, context);
237 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
238 QModelIndex const & index) const
240 QSortFilterProxyModel const * model =
241 static_cast<QSortFilterProxyModel const *>(index.model());
242 QSize size = QItemDelegate::sizeHint(opt, index);
244 // Add space for the category headers here?
245 // Not for the standard layout though.
246 QString stdCat = category(*model->sourceModel(), 0);
247 QString cat = category(*index.model(), index.row());
248 if (lyxrc.group_layouts && stdCat != cat
249 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
250 size.setHeight(size.height() + headerHeight(opt));
257 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
258 QString const & category) const
260 // slightly blended color
261 QColor lcol = opt.palette.text().color();
263 painter->setPen(lcol);
265 // set 80% scaled, bold font
266 QFont font = opt.font;
268 font.setWeight(QFont::Black);
269 font.setPointSize(opt.font.pointSize() * 8 / 10);
270 painter->setFont(font);
272 // draw the centered text
273 QFontMetrics fm(font);
274 int w = fm.width(category);
275 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
276 int y = opt.rect.y() + fm.ascent();
279 painter->drawText(x, y, category);
281 // the vertical position of the line: middle of lower case chars
282 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
284 // draw the horizontal line
285 if (!category.isEmpty()) {
286 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
287 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
289 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
293 QString LayoutItemDelegate::underlineFilter(QString const & s) const
295 QString const & f = layout_->filter();
299 // step through data item and put "(x)" for every matching character
302 for (int i = 0; i < f.length(); ++i) {
303 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
306 if (lastp == p - 1 && lastp != -1) {
307 // remove ")" and append "x)"
308 r = r.left(r.length() - 4) + s[p] + "</u>";
311 r += s.mid(lastp + 1, p - lastp - 1);
312 r += QString("<u>") + s[p] + "</u>";
316 r += s.mid(lastp + 1);
321 static QString charFilterRegExp(QString const & filter)
324 for (int i = 0; i < filter.length(); ++i) {
327 re += "["+ QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
329 re += QRegExp::escape(c);
335 void LayoutBox::Private::setFilter(QString const & s)
337 // exit early if nothing has to be done
341 bool enabled = p->view()->updatesEnabled();
342 p->view()->setUpdatesEnabled(false);
344 // remember old selection
345 int sel = p->currentIndex();
347 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
350 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
353 // restore old selection
354 if (lastSel_ != -1) {
355 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
357 p->setCurrentIndex(i.row());
360 if (p->view()->isVisible()) {
361 p->QComboBox::showPopup();
363 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
364 "Press ESC to remove filter."),
365 qstring_to_ucs4(s)));
367 owner_.message(_("Enter characters to filter the layout list."));
370 p->view()->setUpdatesEnabled(enabled);
374 LayoutBox::LayoutBox(GuiView & owner)
375 : d(new Private(this, owner))
377 setSizeAdjustPolicy(QComboBox::AdjustToContents);
378 setFocusPolicy(Qt::ClickFocus);
379 setMinimumWidth(sizeHint().width());
380 setMaxVisibleItems(100);
382 setModel(d->filterModel_);
384 // for the filtering we have to intercept characters
385 view()->installEventFilter(this);
386 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
388 QObject::connect(this, SIGNAL(activated(int)),
389 this, SLOT(selected(int)));
391 updateContents(true);
395 LayoutBox::~LayoutBox() {
400 void LayoutBox::Private::countCategories()
402 int n = filterModel_->rowCount();
403 visibleCategories_ = 0;
404 if (n == 0 || !lyxrc.group_layouts)
407 // skip the "Standard" category
408 QString prevCat = model_->index(0, 2).data().toString();
411 for (int i = 0; i < n; ++i) {
412 QString cat = filterModel_->index(i, 2).data().toString();
414 ++visibleCategories_;
420 void LayoutBox::showPopup()
422 d->owner_.message(_("Enter characters to filter the layout list."));
424 bool enabled = view()->updatesEnabled();
425 view()->setUpdatesEnabled(false);
427 QComboBox::showPopup();
428 view()->setUpdatesEnabled(enabled);
432 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
434 if (e->type() != QEvent::KeyPress)
435 return QComboBox::eventFilter(o, e);
437 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
438 bool modified = (ke->modifiers() == Qt::ControlModifier)
439 || (ke->modifiers() == Qt::AltModifier)
440 || (ke->modifiers() == Qt::MetaModifier);
444 if (!modified && !d->filter_.isEmpty()) {
449 case Qt::Key_Backspace:
451 // cut off one character
452 d->setFilter(d->filter_.left(d->filter_.length() - 1));
456 if (modified || ke->text().isEmpty())
458 // find chars for the filter string
460 for (int i = 0; i < ke->text().length(); ++i) {
461 QChar c = ke->text()[i];
462 if (c.isLetterOrNumber()
465 || c.category() == QChar::Separator_Space) {
470 // append new chars to the filter string
471 d->setFilter(d->filter_ + s);
477 return QComboBox::eventFilter(o, e);
481 void LayoutBox::setIconSize(QSize size)
484 bool small = size.height() < 20;
485 setAttribute(Qt::WA_MacSmallSize, small);
486 setAttribute(Qt::WA_MacNormalSize, !small);
488 (void)size; // suppress warning
493 void LayoutBox::set(docstring const & layout)
500 if (!d->text_class_->hasLayout(layout))
503 Layout const & lay = (*d->text_class_)[layout];
504 QString newLayout = toqstr(lay.name());
506 // If the layout is obsolete, use the new one instead.
507 docstring const & obs = lay.obsoleted_by();
509 newLayout = toqstr(obs);
511 int const curItem = currentIndex();
512 QModelIndex const mindex =
513 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
514 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
515 if (newLayout == currentLayout) {
516 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
520 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
522 LYXERR0("Trying to select non existent layout type " << newLayout);
526 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
530 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
531 bool sorted, bool sortedByCat, bool unknown)
533 QString qitem = toqstr(item);
534 docstring const loc_item = translateIfPossible(item);
535 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
537 QString qcat = toqstr(translateIfPossible(category));
539 QList<QStandardItem *> row;
540 row.append(new QStandardItem(titem));
541 row.append(new QStandardItem(qitem));
542 row.append(new QStandardItem(qcat));
544 // the first entry is easy
545 int const end = d->model_->rowCount();
547 d->model_->appendRow(row);
554 while (i < end && d->model_->item(i, 2)->text() != qcat)
558 // skip the Standard layout
562 // the simple unsorted case
565 // jump to the end of the category group
566 while (i < end && d->model_->item(i, 2)->text() == qcat)
568 d->model_->insertRow(i, row);
570 d->model_->appendRow(row);
574 // find row to insert the item, after the separator if it exists
576 // find alphabetic position
578 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
579 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
583 d->model_->insertRow(i, row);
587 void LayoutBox::updateContents(bool reset)
590 BufferView const * bv = d->owner_.currentBufferView();
594 setMinimumWidth(sizeHint().width());
595 d->text_class_.reset();
599 // we'll only update the layout list if the text class has changed
600 // or we've moved from one inset to another
601 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
602 Inset const * inset = &(bv->cursor().innerText()->inset());
603 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
604 set(bv->cursor().innerParagraph().layout().name());
609 d->text_class_ = text_class;
612 DocumentClass::const_iterator lit = d->text_class_->begin();
613 DocumentClass::const_iterator len = d->text_class_->end();
615 for (; lit != len; ++lit) {
616 docstring const & name = lit->name();
617 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
618 // if this inset requires the empty layout, we skip the default
620 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
622 // if it doesn't require the empty layout, we skip it
623 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
625 // obsoleted layouts are skipped as well
626 if (!lit->obsoleted_by().empty())
628 addItemSort(name, lit->category(), lyxrc.sort_layouts,
629 lyxrc.group_layouts, lit->isUnknown());
632 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
633 d->countCategories();
635 setMinimumWidth(sizeHint().width());
636 setEnabled(!bv->buffer().isReadonly() &&
637 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
641 void LayoutBox::selected(int index)
644 QModelIndex mindex = d->filterModel_->mapToSource(
645 d->filterModel_->index(index, 1));
646 docstring layoutName = qstring_to_ucs4(
647 d->model_->itemFromIndex(mindex)->text());
648 d->owner_.setFocus();
650 if (!d->text_class_) {
651 updateContents(false);
656 // find corresponding text class
657 if (d->text_class_->hasLayout(layoutName)) {
658 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
660 updateContents(false);
664 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
668 QString const & LayoutBox::filter() const
673 } // namespace frontend
676 #include "moc_LayoutBox.cpp"