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 "FuncRequest.h"
28 #include "FuncStatus.h"
31 #include "Paragraph.h"
32 #include "TextClass.h"
34 #include "insets/InsetText.h"
36 #include "support/debug.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
41 #include <QAbstractTextDocumentLayout>
42 #include <QHeaderView>
43 #include <QItemDelegate>
45 #include <QSortFilterProxyModel>
46 #include <QStandardItemModel>
50 using namespace lyx::support;
56 class LayoutItemDelegate : public QItemDelegate {
59 explicit LayoutItemDelegate(LayoutBox * layout)
60 : QItemDelegate(layout), layout_(layout)
63 void paint(QPainter * painter, QStyleOptionViewItem const & option,
64 QModelIndex const & index) const;
66 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
67 const QRect & /*rect*/, const QString & text ) const;
69 QSize sizeHint(QStyleOptionViewItem const & opt,
70 QModelIndex const & index) const;
74 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
75 QString const & category) const;
77 QString underlineFilter(QString const & s) const;
83 class GuiLayoutFilterModel : public QSortFilterProxyModel {
86 GuiLayoutFilterModel(QObject * parent = 0)
87 : QSortFilterProxyModel(parent)
91 void triggerLayoutChange()
93 layoutAboutToBeChanged();
99 /////////////////////////////////////////////////////////////////////
101 // LayoutBox::Private
103 /////////////////////////////////////////////////////////////////////
105 struct LayoutBox::Private
107 Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
108 // set the layout model with two columns
109 // 1st: translated layout names
110 // 2nd: raw layout names
111 model_(new QStandardItemModel(0, 2, p)),
112 filterModel_(new GuiLayoutFilterModel(p)),
114 layoutItemDelegate_(new LayoutItemDelegate(parent)),
115 visibleCategories_(0), inShowPopup_(false)
117 filterModel_->setSourceModel(model_);
120 void resetFilter() { setFilter(QString()); }
122 void setFilter(QString const & s);
124 void countCategories();
130 DocumentClass const * text_class_;
132 Inset const * inset_;
134 /// the layout model: 1st column translated, 2nd column raw layout name
135 QStandardItemModel * model_;
136 /// the proxy model filtering \c model_
137 GuiLayoutFilterModel * filterModel_;
138 /// the (model-) index of the last successful selection
140 /// the character filter
143 LayoutItemDelegate * layoutItemDelegate_;
145 unsigned visibleCategories_;
151 static QString category(QAbstractItemModel const & model, int row)
153 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
157 static int headerHeight(QStyleOptionViewItem const & opt)
159 return opt.fontMetrics.height() * 8 / 10;
163 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
164 QModelIndex const & index) const
166 QStyleOptionViewItem opt = option;
168 // default background
169 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
172 if (lyxrc.group_layouts) {
173 QSortFilterProxyModel const * model =
174 static_cast<QSortFilterProxyModel const *>(index.model());
176 QString stdCat = category(*model->sourceModel(), 0);
177 QString cat = category(*index.model(), index.row());
179 // not the standard layout and not the same as in the previous line?
181 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
184 // draw unselected background
185 QStyle::State state = opt.state;
186 opt.state = opt.state & ~QStyle::State_Selected;
187 drawBackground(painter, opt, index);
190 // draw category header
191 drawCategoryHeader(painter, opt,
192 category(*index.model(), index.row()));
194 // move rect down below header
195 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
201 QItemDelegate::paint(painter, opt, index);
205 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
206 const QRect & /*rect*/, const QString & text ) const
208 QString utext = underlineFilter(text);
210 // Draw the rich text.
212 QColor col = opt.palette.text().color();
213 if (opt.state & QStyle::State_Selected)
214 col = opt.palette.highlightedText().color();
215 QAbstractTextDocumentLayout::PaintContext context;
216 context.palette.setColor(QPalette::Text, col);
219 doc.setDefaultFont(opt.font);
222 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
224 doc.rootFrame()->setFrameFormat(fmt);
226 painter->translate(opt.rect.x() + 5,
227 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
228 doc.documentLayout()->draw(painter, context);
233 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
234 QModelIndex const & index) const
236 QSortFilterProxyModel const * model =
237 static_cast<QSortFilterProxyModel const *>(index.model());
238 QSize size = QItemDelegate::sizeHint(opt, index);
240 /// QComboBox uses the first row height to estimate the
241 /// complete popup height during QComboBox::showPopup().
242 /// To avoid scrolling we have to sneak in space for the headers.
243 /// So we tweak this value accordingly. It's not nice, but the
244 /// only possible way it seems.
245 if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
246 int itemHeight = size.height();
248 // we have to show \c cats many headers:
249 unsigned cats = layout_->d->visibleCategories_;
251 // and we have \c n items to distribute the needed space over
252 unsigned n = layout_->model()->rowCount();
254 // so the needed average height (rounded upwards) is:
255 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
259 // Add space for the category headers here?
260 // Not for the standard layout though.
261 QString stdCat = category(*model->sourceModel(), 0);
262 QString cat = category(*index.model(), index.row());
263 if (lyxrc.group_layouts && stdCat != cat
264 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
265 size.setHeight(size.height() + headerHeight(opt));
272 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
273 QString const & category) const
275 // slightly blended color
276 QColor lcol = opt.palette.text().color();
278 painter->setPen(lcol);
280 // set 80% scaled, bold font
281 QFont font = opt.font;
283 font.setWeight(QFont::Black);
284 font.setPointSize(opt.font.pointSize() * 8 / 10);
285 painter->setFont(font);
287 // draw the centered text
288 QFontMetrics fm(font);
289 int w = fm.width(category);
290 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
291 int y = opt.rect.y() + fm.ascent();
294 painter->drawText(x, y, category);
296 // the vertical position of the line: middle of lower case chars
297 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
299 // draw the horizontal line
300 if (!category.isEmpty()) {
301 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
302 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
304 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
308 QString LayoutItemDelegate::underlineFilter(QString const & s) const
310 QString const & f = layout_->filter();
314 // step through data item and put "(x)" for every matching character
318 for (int i = 0; i < f.length(); ++i) {
319 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
320 LASSERT(p != -1, /**/);
321 if (lastp == p - 1 && lastp != -1) {
322 // remove ")" and append "x)"
323 r = r.left(r.length() - 4) + s[p] + "</u>";
326 r += s.mid(lastp + 1, p - lastp - 1);
327 r += QString("<u>") + s[p] + "</u>";
331 r += s.mid(lastp + 1);
336 static QString charFilterRegExp(QString const & filter)
339 for (int i = 0; i < filter.length(); ++i) {
342 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
344 re += ".*" + QRegExp::escape(c);
350 void LayoutBox::Private::setFilter(QString const & s)
352 bool enabled = p->view()->updatesEnabled();
353 p->view()->setUpdatesEnabled(false);
355 // remember old selection
356 int sel = p->currentIndex();
358 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
361 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
364 // restore old selection
365 if (lastSel_ != -1) {
366 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
368 p->setCurrentIndex(i.row());
371 // Workaround to resize to content size
372 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
374 if (p->view()->isVisible()) {
375 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
376 // the hack in the item delegate to make space for the headers.
377 // We do not call our implementation of showPopup because that
378 // would reset the filter again. This is only needed if the user clicks
380 LASSERT(!inShowPopup_, /**/);
382 p->QComboBox::showPopup();
383 inShowPopup_ = false;
385 // The item delegate hack is off again. So trigger a relayout of the popup.
386 filterModel_->triggerLayoutChange();
389 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
390 "Press ESC to remove filter."),
391 qstring_to_ucs4(s)));
393 owner_.message(_("Enter characters to filter the layout list."));
396 p->view()->setUpdatesEnabled(enabled);
400 LayoutBox::LayoutBox(GuiView & owner)
401 : d(new Private(this, owner))
403 setSizeAdjustPolicy(QComboBox::AdjustToContents);
404 setFocusPolicy(Qt::ClickFocus);
405 setMinimumWidth(sizeHint().width());
406 setMaxVisibleItems(100);
408 setModel(d->filterModel_);
410 // for the filtering we have to intercept characters
411 view()->installEventFilter(this);
412 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
414 QObject::connect(this, SIGNAL(activated(int)),
415 this, SLOT(selected(int)));
417 updateContents(true);
421 void LayoutBox::Private::countCategories()
423 int n = filterModel_->rowCount();
424 visibleCategories_ = 0;
425 if (n == 0 || !lyxrc.group_layouts)
428 // skip the "Standard" category
429 QString prevCat = model_->index(0, 2).data().toString();
432 for (int i = 0; i < n; ++i) {
433 QString cat = filterModel_->index(i, 2).data().toString();
435 ++visibleCategories_;
441 void LayoutBox::showPopup()
443 d->owner_.message(_("Enter characters to filter the layout list."));
445 bool enabled = view()->updatesEnabled();
446 view()->setUpdatesEnabled(false);
450 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
451 // the hack in the item delegate to make space for the headers.
452 LASSERT(!d->inShowPopup_, /**/);
453 d->inShowPopup_ = true;
454 QComboBox::showPopup();
455 d->inShowPopup_ = false;
457 // The item delegate hack is off again. So trigger a relayout of the popup.
458 d->filterModel_->triggerLayoutChange();
460 view()->setUpdatesEnabled(enabled);
464 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
466 if (e->type() != QEvent::KeyPress)
467 return QComboBox::eventFilter(o, e);
469 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
470 bool modified = (ke->modifiers() == Qt::ControlModifier)
471 || (ke->modifiers() == Qt::AltModifier)
472 || (ke->modifiers() == Qt::MetaModifier);
476 if (!modified && !d->filter_.isEmpty()) {
481 case Qt::Key_Backspace:
483 // cut off one character
484 d->setFilter(d->filter_.left(d->filter_.length() - 1));
488 if (modified || ke->text().isEmpty())
490 // find chars for the filter string
492 for (int i = 0; i < ke->text().length(); ++i) {
493 QChar c = ke->text()[i];
494 if (c.isLetterOrNumber()
497 || c.category() == QChar::Separator_Space) {
502 // append new chars to the filter string
503 d->setFilter(d->filter_ + s);
509 return QComboBox::eventFilter(o, e);
513 void LayoutBox::setIconSize(QSize size)
516 bool small = size.height() < 20;
517 setAttribute(Qt::WA_MacSmallSize, small);
518 setAttribute(Qt::WA_MacNormalSize, !small);
520 (void)size; // suppress warning
525 void LayoutBox::set(docstring const & layout)
532 Layout const & lay = (*d->text_class_)[layout];
533 QString newLayout = toqstr(lay.name());
535 // If the layout is obsolete, use the new one instead.
536 docstring const & obs = lay.obsoleted_by();
538 newLayout = toqstr(obs);
540 int const curItem = currentIndex();
541 QModelIndex const mindex =
542 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
543 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
544 if (newLayout == currentLayout) {
545 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
549 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
551 LYXERR0("Trying to select non existent layout type " << newLayout);
555 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
559 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
560 bool sorted, bool sortedByCat, bool unknown)
562 QString qitem = toqstr(item);
563 // FIXME This is wrong for RTL, I'd suppose.
564 QString titem = toqstr(translateIfPossible(item) +
565 (unknown ? _(" (unknown)") : from_ascii("")));
566 QString qcat = toqstr(translateIfPossible(category));
568 QList<QStandardItem *> row;
569 row.append(new QStandardItem(titem));
570 row.append(new QStandardItem(qitem));
571 row.append(new QStandardItem(qcat));
573 // the first entry is easy
574 int const end = d->model_->rowCount();
576 d->model_->appendRow(row);
583 while (i < end && d->model_->item(i, 2)->text() != qcat)
587 // skip the Standard layout
591 // the simple unsorted case
594 // jump to the end of the category group
595 while (i < end && d->model_->item(i, 2)->text() == qcat)
597 d->model_->insertRow(i, row);
599 d->model_->appendRow(row);
603 // find row to insert the item, after the separator if it exists
605 // find alphabetic position
607 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
608 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
612 d->model_->insertRow(i, row);
616 void LayoutBox::updateContents(bool reset)
619 BufferView const * bv = d->owner_.currentBufferView();
627 // we'll only update the layout list if the text class has changed
628 // or we've moved from one inset to another
629 DocumentClass const * text_class = &(bv->buffer().params().documentClass());
630 Inset const * inset = &(bv->cursor().innerText()->inset());
631 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
632 set(bv->cursor().innerParagraph().layout().name());
637 d->text_class_ = text_class;
640 DocumentClass::const_iterator lit = d->text_class_->begin();
641 DocumentClass::const_iterator len = d->text_class_->end();
643 for (; lit != len; ++lit) {
644 docstring const & name = lit->name();
645 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
646 // if this inset requires the empty layout, we skip the default
648 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
650 // if it doesn't require the empty layout, we skip it
651 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
653 // obsoleted layouts are skipped as well
654 if (!lit->obsoleted_by().empty())
656 addItemSort(name, lit->category(), lyxrc.sort_layouts,
657 lyxrc.group_layouts, lit->isUnknown());
660 set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
661 d->countCategories();
663 // needed to recalculate size hint
665 setMinimumWidth(sizeHint().width());
666 setEnabled(!bv->buffer().isReadonly() &&
667 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
672 void LayoutBox::selected(int index)
675 QModelIndex mindex = d->filterModel_->mapToSource(
676 d->filterModel_->index(index, 1));
677 docstring layoutName = qstring_to_ucs4(
678 d->model_->itemFromIndex(mindex)->text());
679 d->owner_.setFocus();
681 if (!d->text_class_) {
682 updateContents(false);
687 // find corresponding text class
688 if (d->text_class_->hasLayout(layoutName)) {
689 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
691 updateContents(false);
695 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
699 QString const & LayoutBox::filter() const
704 } // namespace frontend
707 #include "moc_LayoutBox.cpp"