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>
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 override;
67 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
68 const QRect & /*rect*/, const QString & text ) const override;
70 QSize sizeHint(QStyleOptionViewItem const & opt,
71 QModelIndex const & index) const override;
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 = nullptr)
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 QSize size = QItemDelegate::sizeHint(opt, index);
241 if (!lyxrc.group_layouts)
244 // Add space for the category headers.
245 QSortFilterProxyModel const * const model =
246 static_cast<QSortFilterProxyModel const *>(index.model());
247 QString const stdCat = category(*model->sourceModel(), 0);
248 QString const cat = category(*index.model(), index.row());
250 // There is no header for the stuff at the top.
254 if (index.row() == 0 || cat != category(*index.model(), index.row() - 1))
255 size.setHeight(size.height() + headerHeight(opt));
260 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
261 QString const & category) const
263 // slightly blended color
264 QColor lcol = opt.palette.text().color();
266 painter->setPen(lcol);
268 // set 80% scaled, bold font
269 QFont font = opt.font;
271 font.setWeight(QFont::Black);
272 font.setPointSize(opt.font.pointSize() * 8 / 10);
273 painter->setFont(font);
275 // draw the centered text
276 QFontMetrics fm(font);
277 int w = fm.boundingRect(category).width();
278 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
279 int y = opt.rect.y() + fm.ascent();
282 painter->drawText(x, y, category);
284 // the vertical position of the line: middle of lower case chars
285 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
287 // draw the horizontal line
288 if (!category.isEmpty()) {
289 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
290 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
292 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
296 QString LayoutItemDelegate::underlineFilter(QString const & s) const
298 QString const & f = layout_->filter();
302 QRegularExpression pattern(charFilterRegExpC(f));
303 r.replace(pattern, "<u><b>\\1</b></u>");
308 void LayoutBox::Private::setFilter(QString const & s)
310 // exit early if nothing has to be done
314 bool enabled = p->view()->updatesEnabled();
315 p->view()->setUpdatesEnabled(false);
317 // remember old selection
318 int sel = p->currentIndex();
320 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
323 #if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
324 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
326 filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
330 // restore old selection
331 if (lastSel_ != -1) {
332 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
334 p->setCurrentIndex(i.row());
337 if (p->view()->isVisible()) {
338 p->QComboBox::showPopup();
340 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
341 "Press ESC to remove filter."),
342 qstring_to_ucs4(s)));
344 owner_.message(_("Enter characters to filter the layout list."));
347 p->view()->setUpdatesEnabled(enabled);
351 LayoutBox::LayoutBox(GuiView & owner)
352 : d(new Private(this, owner))
354 setSizeAdjustPolicy(QComboBox::AdjustToContents);
355 setFocusPolicy(Qt::ClickFocus);
356 setMinimumWidth(sizeHint().width());
357 setMaxVisibleItems(100);
359 setModel(d->filterModel_);
361 // for the filtering we have to intercept characters
362 view()->installEventFilter(this);
363 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
365 QObject::connect(this, SIGNAL(activated(int)),
366 this, SLOT(selected(int)));
368 updateContents(true);
372 LayoutBox::~LayoutBox() {
377 void LayoutBox::Private::countCategories()
379 int n = filterModel_->rowCount();
380 visibleCategories_ = 0;
381 if (n == 0 || !lyxrc.group_layouts)
384 // skip the "Standard" category
385 QString prevCat = model_->index(0, 2).data().toString();
388 for (int i = 0; i < n; ++i) {
389 QString cat = filterModel_->index(i, 2).data().toString();
391 ++visibleCategories_;
397 void LayoutBox::showPopup()
399 lastCurrentIndex_ = currentIndex();
400 d->owner_.message(_("Enter characters to filter the layout list."));
402 bool enabled = view()->updatesEnabled();
403 view()->setUpdatesEnabled(false);
405 QComboBox::showPopup();
406 view()->setUpdatesEnabled(enabled);
410 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
412 if (e->type() != QEvent::KeyPress)
413 return QComboBox::eventFilter(o, e);
415 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
416 bool modified = (ke->modifiers() == Qt::ControlModifier)
417 || (ke->modifiers() == Qt::AltModifier)
418 || (ke->modifiers() == Qt::MetaModifier);
422 if (!modified && !d->filter_.isEmpty()) {
424 setCurrentIndex(lastCurrentIndex_);
428 case Qt::Key_Backspace:
430 // cut off one character
431 d->setFilter(d->filter_.left(d->filter_.length() - 1));
435 if (modified || ke->text().isEmpty())
437 // find chars for the filter string
439 for (int i = 0; i < ke->text().length(); ++i) {
440 QChar c = ke->text()[i];
441 if (c.isLetterOrNumber()
444 || c.category() == QChar::Separator_Space) {
449 // append new chars to the filter string
450 d->setFilter(d->filter_ + s);
456 return QComboBox::eventFilter(o, e);
460 void LayoutBox::setIconSize(QSize size)
463 bool small = size.height() < 20;
464 setAttribute(Qt::WA_MacSmallSize, small);
465 setAttribute(Qt::WA_MacNormalSize, !small);
467 (void)size; // suppress warning
472 void LayoutBox::set(docstring const & layout)
479 if (!d->text_class_->hasLayout(layout))
482 Layout const & lay = (*d->text_class_)[layout];
483 QString newLayout = toqstr(lay.name());
485 // If the layout is obsolete, use the new one instead.
486 docstring const & obs = lay.obsoleted_by();
488 newLayout = toqstr(obs);
490 int const curItem = currentIndex();
491 QModelIndex const mindex =
492 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
493 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
494 if (newLayout == currentLayout) {
495 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
499 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
501 LYXERR0("Trying to select non existent layout type " << newLayout);
505 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
509 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
510 bool sorted, bool sortedByCat, bool unknown)
512 QString qitem = toqstr(item);
513 docstring const loc_item = translateIfPossible(item);
514 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
516 QString qcat = toqstr(translateIfPossible(category));
518 QList<QStandardItem *> row;
519 row.append(new QStandardItem(titem));
520 row.append(new QStandardItem(qitem));
521 row.append(new QStandardItem(qcat));
523 // the first entry is easy
524 int const end = d->model_->rowCount();
526 d->model_->appendRow(row);
533 while (i < end && d->model_->item(i, 2)->text() != qcat)
537 // skip the Standard layout
541 // the simple unsorted case
544 // jump to the end of the category group
545 while (i < end && d->model_->item(i, 2)->text() == qcat)
547 d->model_->insertRow(i, row);
549 d->model_->appendRow(row);
553 // find row to insert the item, after the separator if it exists
555 // find alphabetic position
557 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
558 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
562 d->model_->insertRow(i, row);
566 void LayoutBox::updateContents(bool reset)
569 BufferView const * bv = d->owner_.currentBufferView();
573 setMinimumWidth(sizeHint().width());
574 d->text_class_.reset();
578 // we'll only update the layout list if the text class has changed
579 // or we've moved from one inset to another
580 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
581 Inset const * inset = &(bv->cursor().innerText()->inset());
582 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
583 set(bv->cursor().innerParagraph().layout().name());
588 d->text_class_ = text_class;
591 DocumentClass::const_iterator lit = d->text_class_->begin();
592 DocumentClass::const_iterator len = d->text_class_->end();
593 for (; lit != len; ++lit) {
594 docstring const & name = lit->name();
595 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
596 // if this inset requires the empty layout, we skip the default
598 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
600 // if it doesn't require the empty layout, we skip it
601 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
603 // obsoleted layouts are skipped as well
604 if (!lit->obsoleted_by().empty())
606 addItemSort(name, lit->category(), lyxrc.sort_layouts,
607 lyxrc.group_layouts, lit->isUnknown());
610 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
611 d->countCategories();
613 setMinimumWidth(sizeHint().width());
614 setEnabled(!bv->buffer().isReadonly() &&
615 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
619 void LayoutBox::selected(int index)
621 d->owner_.setFocus();
622 if (!d->text_class_) {
623 updateContents(false);
629 // get the index of the untranslated layout name (which is in column 1)
630 QModelIndex const lindex = d->filterModel_->index(index, 1);
631 QModelIndex const mindex = d->filterModel_->mapToSource(lindex);
632 QString const qlayout = d->model_->itemFromIndex(mindex)->text();
633 docstring const layoutName = qstring_to_ucs4(qlayout);
635 // find corresponding text class
636 if (d->text_class_->hasLayout(layoutName)) {
637 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
639 updateContents(false);
643 LYXERR0("ERROR (LayoutBox::Selected): layout " << layoutName << " not found!");
647 QString const & LayoutBox::filter() const
652 } // namespace frontend
655 #include "moc_LayoutBox.cpp"