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 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.width(category);
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 // step through data item and put "(x)" for every matching character
305 for (int i = 0; i < f.length(); ++i) {
306 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
309 if (lastp == p - 1 && lastp != -1) {
310 // remove ")" and append "x)"
311 r = r.left(r.length() - 4) + s[p] + "</u>";
314 r += s.mid(lastp + 1, p - lastp - 1);
315 r += QString("<u>") + s[p] + "</u>";
319 r += s.mid(lastp + 1);
324 static QString charFilterRegExp(QString const & filter)
327 for (int i = 0; i < filter.length(); ++i) {
330 re += "["+ QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
332 re += QRegExp::escape(c);
338 void LayoutBox::Private::setFilter(QString const & s)
340 // exit early if nothing has to be done
344 bool enabled = p->view()->updatesEnabled();
345 p->view()->setUpdatesEnabled(false);
347 // remember old selection
348 int sel = p->currentIndex();
350 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
353 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
356 // restore old selection
357 if (lastSel_ != -1) {
358 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
360 p->setCurrentIndex(i.row());
363 if (p->view()->isVisible()) {
364 p->QComboBox::showPopup();
366 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
367 "Press ESC to remove filter."),
368 qstring_to_ucs4(s)));
370 owner_.message(_("Enter characters to filter the layout list."));
373 p->view()->setUpdatesEnabled(enabled);
377 LayoutBox::LayoutBox(GuiView & owner)
378 : d(new Private(this, owner))
380 setSizeAdjustPolicy(QComboBox::AdjustToContents);
381 setFocusPolicy(Qt::ClickFocus);
382 setMinimumWidth(sizeHint().width());
383 setMaxVisibleItems(100);
385 setModel(d->filterModel_);
387 // for the filtering we have to intercept characters
388 view()->installEventFilter(this);
389 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
391 QObject::connect(this, SIGNAL(activated(int)),
392 this, SLOT(selected(int)));
394 updateContents(true);
398 LayoutBox::~LayoutBox() {
403 void LayoutBox::Private::countCategories()
405 int n = filterModel_->rowCount();
406 visibleCategories_ = 0;
407 if (n == 0 || !lyxrc.group_layouts)
410 // skip the "Standard" category
411 QString prevCat = model_->index(0, 2).data().toString();
414 for (int i = 0; i < n; ++i) {
415 QString cat = filterModel_->index(i, 2).data().toString();
417 ++visibleCategories_;
423 void LayoutBox::showPopup()
425 d->owner_.message(_("Enter characters to filter the layout list."));
427 bool enabled = view()->updatesEnabled();
428 view()->setUpdatesEnabled(false);
430 QComboBox::showPopup();
431 view()->setUpdatesEnabled(enabled);
435 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
437 if (e->type() != QEvent::KeyPress)
438 return QComboBox::eventFilter(o, e);
440 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
441 bool modified = (ke->modifiers() == Qt::ControlModifier)
442 || (ke->modifiers() == Qt::AltModifier)
443 || (ke->modifiers() == Qt::MetaModifier);
447 if (!modified && !d->filter_.isEmpty()) {
452 case Qt::Key_Backspace:
454 // cut off one character
455 d->setFilter(d->filter_.left(d->filter_.length() - 1));
459 if (modified || ke->text().isEmpty())
461 // find chars for the filter string
463 for (int i = 0; i < ke->text().length(); ++i) {
464 QChar c = ke->text()[i];
465 if (c.isLetterOrNumber()
468 || c.category() == QChar::Separator_Space) {
473 // append new chars to the filter string
474 d->setFilter(d->filter_ + s);
480 return QComboBox::eventFilter(o, e);
484 void LayoutBox::setIconSize(QSize size)
487 bool small = size.height() < 20;
488 setAttribute(Qt::WA_MacSmallSize, small);
489 setAttribute(Qt::WA_MacNormalSize, !small);
491 (void)size; // suppress warning
496 void LayoutBox::set(docstring const & layout)
503 if (!d->text_class_->hasLayout(layout))
506 Layout const & lay = (*d->text_class_)[layout];
507 QString newLayout = toqstr(lay.name());
509 // If the layout is obsolete, use the new one instead.
510 docstring const & obs = lay.obsoleted_by();
512 newLayout = toqstr(obs);
514 int const curItem = currentIndex();
515 QModelIndex const mindex =
516 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
517 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
518 if (newLayout == currentLayout) {
519 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
523 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
525 LYXERR0("Trying to select non existent layout type " << newLayout);
529 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
533 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
534 bool sorted, bool sortedByCat, bool unknown)
536 QString qitem = toqstr(item);
537 docstring const loc_item = translateIfPossible(item);
538 QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
540 QString qcat = toqstr(translateIfPossible(category));
542 QList<QStandardItem *> row;
543 row.append(new QStandardItem(titem));
544 row.append(new QStandardItem(qitem));
545 row.append(new QStandardItem(qcat));
547 // the first entry is easy
548 int const end = d->model_->rowCount();
550 d->model_->appendRow(row);
557 while (i < end && d->model_->item(i, 2)->text() != qcat)
561 // skip the Standard layout
565 // the simple unsorted case
568 // jump to the end of the category group
569 while (i < end && d->model_->item(i, 2)->text() == qcat)
571 d->model_->insertRow(i, row);
573 d->model_->appendRow(row);
577 // find row to insert the item, after the separator if it exists
579 // find alphabetic position
581 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
582 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
586 d->model_->insertRow(i, row);
590 void LayoutBox::updateContents(bool reset)
593 BufferView const * bv = d->owner_.currentBufferView();
597 setMinimumWidth(sizeHint().width());
598 d->text_class_.reset();
602 // we'll only update the layout list if the text class has changed
603 // or we've moved from one inset to another
604 DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
605 Inset const * inset = &(bv->cursor().innerText()->inset());
606 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
607 set(bv->cursor().innerParagraph().layout().name());
612 d->text_class_ = text_class;
615 DocumentClass::const_iterator lit = d->text_class_->begin();
616 DocumentClass::const_iterator len = d->text_class_->end();
618 for (; lit != len; ++lit) {
619 docstring const & name = lit->name();
620 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
621 // if this inset requires the empty layout, we skip the default
623 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
625 // if it doesn't require the empty layout, we skip it
626 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
628 // obsoleted layouts are skipped as well
629 if (!lit->obsoleted_by().empty())
631 addItemSort(name, lit->category(), lyxrc.sort_layouts,
632 lyxrc.group_layouts, lit->isUnknown());
635 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
636 d->countCategories();
638 setMinimumWidth(sizeHint().width());
639 setEnabled(!bv->buffer().isReadonly() &&
640 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
644 void LayoutBox::selected(int index)
647 QModelIndex mindex = d->filterModel_->mapToSource(
648 d->filterModel_->index(index, 1));
649 docstring layoutName = qstring_to_ucs4(
650 d->model_->itemFromIndex(mindex)->text());
651 d->owner_.setFocus();
653 if (!d->text_class_) {
654 updateContents(false);
659 // find corresponding text class
660 if (d->text_class_->hasLayout(layoutName)) {
661 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
663 updateContents(false);
667 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
671 QString const & LayoutBox::filter() const
676 } // namespace frontend
679 #include "moc_LayoutBox.cpp"