2 * \file qt/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>
47 #include <QSortFilterProxyModel>
48 #include <QStandardItemModel>
52 using namespace lyx::support;
58 class LayoutItemDelegate : public QItemDelegate {
61 explicit LayoutItemDelegate(LayoutBox * layout)
62 : QItemDelegate(layout), layout_(layout)
65 void paint(QPainter * painter, QStyleOptionViewItem const & option,
66 QModelIndex const & index) const override;
68 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
69 const QRect & /*rect*/, const QString & text ) const override;
71 QSize sizeHint(QStyleOptionViewItem const & opt,
72 QModelIndex const & index) const override;
76 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
77 QString const & category) const;
79 QString underlineFilter(QString const & s) const;
85 class GuiLayoutFilterModel : public QSortFilterProxyModel {
88 GuiLayoutFilterModel(QObject * parent = nullptr)
89 : QSortFilterProxyModel(parent)
93 void triggerLayoutChange()
95 layoutAboutToBeChanged();
101 /////////////////////////////////////////////////////////////////////
103 // LayoutBox::Private
105 /////////////////////////////////////////////////////////////////////
107 class LayoutBox::Private
110 Private(Private const &);
111 void operator=(Private const &);
113 Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
115 // set the layout model with two columns
116 // 1st: translated layout names
117 // 2nd: raw layout names
118 model_(new QStandardItemModel(0, 2, p)),
119 filterModel_(new GuiLayoutFilterModel(p)),
121 layoutItemDelegate_(new LayoutItemDelegate(parent)),
122 visibleCategories_(0)
124 filterModel_->setSourceModel(model_);
127 void resetFilter() { setFilter(QString()); }
129 void setFilter(QString const & s);
131 void countCategories();
137 DocumentClassConstPtr text_class_;
139 Inset const * inset_;
141 /// the layout model: 1st column translated, 2nd column raw layout name
142 QStandardItemModel * model_;
143 /// the proxy model filtering \c model_
144 GuiLayoutFilterModel * filterModel_;
145 /// the (model-) index of the last successful selection
147 /// the character filter
150 LayoutItemDelegate * layoutItemDelegate_;
152 unsigned visibleCategories_;
156 static QString category(QAbstractItemModel const & model, int row)
158 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
162 static int headerHeight(QStyleOptionViewItem const & opt)
164 return opt.fontMetrics.height() * 8 / 10;
168 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
169 QModelIndex const & index) const
171 QStyleOptionViewItem opt = option;
173 // default background
174 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
177 if (lyxrc.group_layouts) {
178 QSortFilterProxyModel const * model =
179 static_cast<QSortFilterProxyModel const *>(index.model());
181 QString stdCat = category(*model->sourceModel(), 0);
182 QString cat = category(*index.model(), index.row());
184 // not the standard layout and not the same as in the previous line?
186 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
189 // draw unselected background
190 QStyle::State state = opt.state;
191 opt.state = opt.state & ~QStyle::State_Selected;
192 drawBackground(painter, opt, index);
195 // draw category header
196 drawCategoryHeader(painter, opt,
197 category(*index.model(), index.row()));
199 // move rect down below header
200 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
206 QItemDelegate::paint(painter, opt, index);
210 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
211 const QRect & /*rect*/, const QString & text ) const
213 QString utext = underlineFilter(text);
215 // Draw the rich text.
217 QColor col = opt.palette.text().color();
218 if (opt.state & QStyle::State_Selected)
219 col = opt.palette.highlightedText().color();
220 QAbstractTextDocumentLayout::PaintContext context;
221 context.palette.setColor(QPalette::Text, col);
224 doc.setDefaultFont(opt.font);
227 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
229 doc.rootFrame()->setFrameFormat(fmt);
231 painter->translate(opt.rect.x() + 5,
232 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
233 doc.documentLayout()->draw(painter, context);
238 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
239 QModelIndex const & index) const
241 QSize size = QItemDelegate::sizeHint(opt, index);
242 if (!lyxrc.group_layouts)
245 // Add space for the category headers.
246 QSortFilterProxyModel const * const model =
247 static_cast<QSortFilterProxyModel const *>(index.model());
248 QString const stdCat = category(*model->sourceModel(), 0);
249 QString const cat = category(*index.model(), index.row());
251 // There is no header for the stuff at the top.
255 if (index.row() == 0 || cat != category(*index.model(), index.row() - 1))
256 size.setHeight(size.height() + headerHeight(opt));
261 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
262 QString const & category) const
264 // slightly blended color
265 QColor lcol = opt.palette.text().color();
267 painter->setPen(lcol);
269 // set 80% scaled, bold font
270 QFont font = opt.font;
272 font.setWeight(QFont::Black);
273 font.setPointSize(opt.font.pointSize() * 8 / 10);
274 painter->setFont(font);
276 // draw the centered text
277 QFontMetrics fm(font);
278 int w = fm.boundingRect(category).width();
279 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
280 int y = opt.rect.y() + fm.ascent();
283 painter->drawText(x, y, category);
285 // the vertical position of the line: middle of lower case chars
286 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
288 // draw the horizontal line
289 if (!category.isEmpty()) {
290 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
291 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
293 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
297 QString LayoutItemDelegate::underlineFilter(QString const & s) const
299 QString const & f = layout_->filter();
303 #if QT_VERSION < 0x060000
304 QRegExp pattern(charFilterRegExpC(f));
306 QRegularExpression pattern(charFilterRegExpC(f));
308 r.replace(pattern, "<u><b>\\1</b></u>");
313 void LayoutBox::Private::setFilter(QString const & s)
315 // exit early if nothing has to be done
319 bool enabled = p->view()->updatesEnabled();
320 p->view()->setUpdatesEnabled(false);
322 // remember old selection
323 int sel = p->currentIndex();
325 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
328 #if QT_VERSION < 0x060000
329 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
331 filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
335 // restore old selection
336 if (lastSel_ != -1) {
337 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
339 p->setCurrentIndex(i.row());
342 if (p->view()->isVisible()) {
343 p->QComboBox::showPopup();
345 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
346 "Press ESC to remove filter."),
347 qstring_to_ucs4(s)));
349 owner_.message(_("Enter characters to filter the layout list."));
352 p->view()->setUpdatesEnabled(enabled);
356 LayoutBox::LayoutBox(GuiView & owner)
357 : d(new Private(this, owner))
359 setSizeAdjustPolicy(QComboBox::AdjustToContents);
360 setFocusPolicy(Qt::ClickFocus);
361 setMinimumWidth(sizeHint().width());
362 setMaxVisibleItems(100);
364 setModel(d->filterModel_);
366 // for the filtering we have to intercept characters
367 view()->installEventFilter(this);
368 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
370 QObject::connect(this, SIGNAL(activated(int)),
371 this, SLOT(selected(int)));
373 updateContents(true);
377 LayoutBox::~LayoutBox() {
382 void LayoutBox::Private::countCategories()
384 int n = filterModel_->rowCount();
385 visibleCategories_ = 0;
386 if (n == 0 || !lyxrc.group_layouts)
389 // skip the "Standard" category
390 QString prevCat = model_->index(0, 2).data().toString();
393 for (int i = 0; i < n; ++i) {
394 QString cat = filterModel_->index(i, 2).data().toString();
396 ++visibleCategories_;
402 void LayoutBox::showPopup()
404 d->owner_.message(_("Enter characters to filter the layout list."));
406 bool enabled = view()->updatesEnabled();
407 view()->setUpdatesEnabled(false);
409 QComboBox::showPopup();
410 view()->setUpdatesEnabled(enabled);
414 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
416 if (e->type() != QEvent::KeyPress)
417 return QComboBox::eventFilter(o, e);
419 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
420 bool modified = (ke->modifiers() == Qt::ControlModifier)
421 || (ke->modifiers() == Qt::AltModifier)
422 || (ke->modifiers() == Qt::MetaModifier);
426 if (!modified && !d->filter_.isEmpty()) {
431 case Qt::Key_Backspace:
433 // cut off one character
434 d->setFilter(d->filter_.left(d->filter_.length() - 1));
438 if (modified || ke->text().isEmpty())
440 // find chars for the filter string
442 for (int i = 0; i < ke->text().length(); ++i) {
443 QChar c = ke->text()[i];
444 if (c.isLetterOrNumber()
447 || c.category() == QChar::Separator_Space) {
452 // append new chars to the filter string
453 d->setFilter(d->filter_ + s);
459 return QComboBox::eventFilter(o, e);
463 void LayoutBox::setIconSize(QSize size)
466 bool small = size.height() < 20;
467 setAttribute(Qt::WA_MacSmallSize, small);
468 setAttribute(Qt::WA_MacNormalSize, !small);
470 (void)size; // suppress warning
475 void LayoutBox::set(docstring const & layout)
482 if (!d->text_class_->hasLayout(layout))
485 Layout const & lay = (*d->text_class_)[layout];
486 QString newLayout = toqstr(lay.name());
488 // If the layout is obsolete, use the new one instead.
489 docstring const & obs = lay.obsoleted_by();
491 newLayout = toqstr(obs);
493 int const curItem = currentIndex();
494 QModelIndex const mindex =
495 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
496 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
497 if (newLayout == currentLayout) {
498 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
502 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
504 LYXERR0("Trying to select non existent layout type " << newLayout);
508 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
512 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
513 bool sorted, bool sortedByCat, bool unknown)
515 QString qitem = toqstr(item);
516 docstring const loc_item = translateIfPossible(item);
517 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
519 QString qcat = toqstr(translateIfPossible(category));
521 QList<QStandardItem *> row;
522 row.append(new QStandardItem(titem));
523 row.append(new QStandardItem(qitem));
524 row.append(new QStandardItem(qcat));
526 // the first entry is easy
527 int const end = d->model_->rowCount();
529 d->model_->appendRow(row);
536 while (i < end && d->model_->item(i, 2)->text() != qcat)
540 // skip the Standard layout
544 // the simple unsorted case
547 // jump to the end of the category group
548 while (i < end && d->model_->item(i, 2)->text() == qcat)
550 d->model_->insertRow(i, row);
552 d->model_->appendRow(row);
556 // find row to insert the item, after the separator if it exists
558 // find alphabetic position
560 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
561 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
565 d->model_->insertRow(i, row);
569 void LayoutBox::updateContents(bool reset)
572 BufferView const * bv = d->owner_.currentBufferView();
576 setMinimumWidth(sizeHint().width());
577 d->text_class_.reset();
581 // we'll only update the layout list if the text class has changed
582 // or we've moved from one inset to another
583 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
584 Inset const * inset = &(bv->cursor().innerText()->inset());
585 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
586 set(bv->cursor().innerParagraph().layout().name());
591 d->text_class_ = text_class;
594 DocumentClass::const_iterator lit = d->text_class_->begin();
595 DocumentClass::const_iterator len = d->text_class_->end();
597 for (; lit != len; ++lit) {
598 docstring const & name = lit->name();
599 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
600 // if this inset requires the empty layout, we skip the default
602 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
604 // if it doesn't require the empty layout, we skip it
605 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
607 // obsoleted layouts are skipped as well
608 if (!lit->obsoleted_by().empty())
610 addItemSort(name, lit->category(), lyxrc.sort_layouts,
611 lyxrc.group_layouts, lit->isUnknown());
614 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
615 d->countCategories();
617 setMinimumWidth(sizeHint().width());
618 setEnabled(!bv->buffer().isReadonly() &&
619 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
623 void LayoutBox::selected(int index)
626 QModelIndex mindex = d->filterModel_->mapToSource(
627 d->filterModel_->index(index, 1));
628 docstring layoutName = qstring_to_ucs4(
629 d->model_->itemFromIndex(mindex)->text());
630 d->owner_.setFocus();
632 if (!d->text_class_) {
633 updateContents(false);
638 // find corresponding text class
639 if (d->text_class_->hasLayout(layoutName)) {
640 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
642 updateContents(false);
646 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
650 QString const & LayoutBox::filter() const
655 } // namespace frontend
658 #include "moc_LayoutBox.cpp"