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"
22 #include "qt_helpers.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
34 #include "Paragraph.h"
35 #include "TextClass.h"
37 #include "insets/InsetText.h"
39 #include "support/debug.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
44 #include <QAbstractItemDelegate>
45 #include <QAbstractTextDocumentLayout>
46 #include <QApplication>
48 #include <QFontMetrics>
49 #include <QHeaderView>
50 #include <QItemDelegate>
57 #include <QSortFilterProxyModel>
58 #include <QStandardItem>
59 #include <QStandardItemModel>
61 #include <QTextDocument>
66 #include "support/lassert.h"
69 using namespace lyx::support;
75 class LayoutItemDelegate : public QItemDelegate {
78 explicit LayoutItemDelegate(LayoutBox * layout)
79 : QItemDelegate(layout), layout_(layout)
82 void paint(QPainter * painter, QStyleOptionViewItem const & option,
83 QModelIndex const & index) const;
85 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
86 const QRect & /*rect*/, const QString & text ) const;
88 QSize sizeHint(QStyleOptionViewItem const & opt,
89 QModelIndex const & index) const;
93 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
94 QString const & category) const;
96 QString underlineFilter(QString const & s) const;
102 class GuiLayoutFilterModel : public QSortFilterProxyModel {
105 GuiLayoutFilterModel(QObject * parent = 0)
106 : QSortFilterProxyModel(parent)
110 void triggerLayoutChange()
112 layoutAboutToBeChanged();
118 /////////////////////////////////////////////////////////////////////
120 // LayoutBox::Private
122 /////////////////////////////////////////////////////////////////////
124 struct LayoutBox::Private
126 Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
127 // set the layout model with two columns
128 // 1st: translated layout names
129 // 2nd: raw layout names
130 model_(new QStandardItemModel(0, 2, p)),
131 filterModel_(new GuiLayoutFilterModel(p)),
133 layoutItemDelegate_(new LayoutItemDelegate(parent)),
134 visibleCategories_(0), inShowPopup_(false)
136 filterModel_->setSourceModel(model_);
139 void resetFilter() { setFilter(QString()); }
141 void setFilter(QString const & s);
143 void countCategories();
149 DocumentClass const * text_class_;
151 Inset const * inset_;
153 /// the layout model: 1st column translated, 2nd column raw layout name
154 QStandardItemModel * model_;
155 /// the proxy model filtering \c model_
156 GuiLayoutFilterModel * filterModel_;
157 /// the (model-) index of the last successful selection
159 /// the character filter
162 LayoutItemDelegate * layoutItemDelegate_;
164 unsigned visibleCategories_;
170 static QString category(QAbstractItemModel const & model, int row)
172 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
176 static int headerHeight(QStyleOptionViewItem const & opt)
178 return opt.fontMetrics.height() * 8 / 10;
182 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
183 QModelIndex const & index) const
185 QStyleOptionViewItem opt = option;
187 // default background
188 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
191 if (lyxrc.group_layouts) {
192 QSortFilterProxyModel const * model =
193 static_cast<QSortFilterProxyModel const *>(index.model());
195 QString stdCat = category(*model->sourceModel(), 0);
196 QString cat = category(*index.model(), index.row());
198 // not the standard layout and not the same as in the previous line?
200 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
203 // draw unselected background
204 QStyle::State state = opt.state;
205 opt.state = opt.state & ~QStyle::State_Selected;
206 drawBackground(painter, opt, index);
209 // draw category header
210 drawCategoryHeader(painter, opt,
211 category(*index.model(), index.row()));
213 // move rect down below header
214 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
220 QItemDelegate::paint(painter, opt, index);
224 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
225 const QRect & /*rect*/, const QString & text ) const
227 QString utext = underlineFilter(text);
229 // Draw the rich text.
231 QColor col = opt.palette.text().color();
232 if (opt.state & QStyle::State_Selected)
233 col = opt.palette.highlightedText().color();
234 QAbstractTextDocumentLayout::PaintContext context;
235 context.palette.setColor(QPalette::Text, col);
238 doc.setDefaultFont(opt.font);
241 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
243 doc.rootFrame()->setFrameFormat(fmt);
245 painter->translate(opt.rect.x() + 5,
246 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
247 doc.documentLayout()->draw(painter, context);
252 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
253 QModelIndex const & index) const
255 QSortFilterProxyModel const * model =
256 static_cast<QSortFilterProxyModel const *>(index.model());
257 QSize size = QItemDelegate::sizeHint(opt, index);
259 /// QComboBox uses the first row height to estimate the
260 /// complete popup height during QComboBox::showPopup().
261 /// To avoid scrolling we have to sneak in space for the headers.
262 /// So we tweak this value accordingly. It's not nice, but the
263 /// only possible way it seems.
264 if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
265 int itemHeight = size.height();
267 // we have to show \c cats many headers:
268 unsigned cats = layout_->d->visibleCategories_;
270 // and we have \c n items to distribute the needed space over
271 unsigned n = layout_->model()->rowCount();
273 // so the needed average height (rounded upwards) is:
274 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
278 // Add space for the category headers here?
279 // Not for the standard layout though.
280 QString stdCat = category(*model->sourceModel(), 0);
281 QString cat = category(*index.model(), index.row());
282 if (lyxrc.group_layouts && stdCat != cat
283 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
284 size.setHeight(size.height() + headerHeight(opt));
291 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
292 QString const & category) const
294 // slightly blended color
295 QColor lcol = opt.palette.text().color();
297 painter->setPen(lcol);
299 // set 80% scaled, bold font
300 QFont font = opt.font;
302 font.setWeight(QFont::Black);
303 font.setPointSize(opt.font.pointSize() * 8 / 10);
304 painter->setFont(font);
306 // draw the centered text
307 QFontMetrics fm(font);
308 int w = fm.width(category);
309 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
310 int y = opt.rect.y() + fm.ascent();
313 painter->drawText(x, y, category);
315 // the vertical position of the line: middle of lower case chars
316 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
318 // draw the horizontal line
319 if (!category.isEmpty()) {
320 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
321 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
323 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
327 QString LayoutItemDelegate::underlineFilter(QString const & s) const
329 QString const & f = layout_->filter();
333 // step through data item and put "(x)" for every matching character
337 for (int i = 0; i < f.length(); ++i) {
338 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
339 LASSERT(p != -1, /**/);
340 if (lastp == p - 1 && lastp != -1) {
341 // remove ")" and append "x)"
342 r = r.left(r.length() - 4) + s[p] + "</u>";
345 r += s.mid(lastp + 1, p - lastp - 1);
346 r += QString("<u>") + s[p] + "</u>";
350 r += s.mid(lastp + 1);
355 static QString charFilterRegExp(QString const & filter)
358 for (int i = 0; i < filter.length(); ++i) {
361 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
363 re += ".*" + QRegExp::escape(c);
369 void LayoutBox::Private::setFilter(QString const & s)
371 bool enabled = p->view()->updatesEnabled();
372 p->view()->setUpdatesEnabled(false);
374 // remember old selection
375 int sel = p->currentIndex();
377 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
380 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
383 // restore old selection
384 if (lastSel_ != -1) {
385 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
387 p->setCurrentIndex(i.row());
390 // Workaround to resize to content size
391 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
393 if (p->view()->isVisible()) {
394 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
395 // the hack in the item delegate to make space for the headers.
396 // We do not call our implementation of showPopup because that
397 // would reset the filter again. This is only needed if the user clicks
399 LASSERT(!inShowPopup_, /**/);
402 inShowPopup_ = false;
404 // The item delegate hack is off again. So trigger a relayout of the popup.
405 filterModel_->triggerLayoutChange();
408 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
409 "Press ESC to remove filter."),
410 qstring_to_ucs4(s)));
412 owner_.message(_("Enter characters to filter the layout list."));
415 p->view()->setUpdatesEnabled(enabled);
419 LayoutBox::LayoutBox(QToolBar * bar, GuiView & owner)
420 : d(new Private(this, owner))
422 setSizeAdjustPolicy(QComboBox::AdjustToContents);
423 setFocusPolicy(Qt::ClickFocus);
424 setMinimumWidth(sizeHint().width());
425 setMaxVisibleItems(100);
427 setModel(d->filterModel_);
429 // for the filtering we have to intercept characters
430 view()->installEventFilter(this);
431 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
433 QObject::connect(this, SIGNAL(activated(int)),
434 this, SLOT(selected(int)));
435 QObject::connect(bar, SIGNAL(iconSizeChanged(QSize)),
436 this, SLOT(setIconSize(QSize)));
438 d->owner_.setLayoutDialog(this);
439 updateContents(true);
443 void LayoutBox::Private::countCategories()
445 int n = filterModel_->rowCount();
446 visibleCategories_ = 0;
447 if (n == 0 || !lyxrc.group_layouts)
450 // skip the "Standard" category
451 QString prevCat = model_->index(0, 2).data().toString();
454 for (int i = 0; i < n; ++i) {
455 QString cat = filterModel_->index(i, 2).data().toString();
457 ++visibleCategories_;
463 void LayoutBox::showPopup()
465 d->owner_.message(_("Enter characters to filter the layout list."));
467 bool enabled = view()->updatesEnabled();
468 view()->setUpdatesEnabled(false);
472 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
473 // the hack in the item delegate to make space for the headers.
474 LASSERT(!d->inShowPopup_, /**/);
475 d->inShowPopup_ = true;
476 QComboBox::showPopup();
477 d->inShowPopup_ = false;
479 // The item delegate hack is off again. So trigger a relayout of the popup.
480 d->filterModel_->triggerLayoutChange();
482 view()->setUpdatesEnabled(enabled);
486 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
488 if (e->type() != QEvent::KeyPress)
489 return QComboBox::eventFilter(o, e);
491 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
492 bool modified = (ke->modifiers() == Qt::ControlModifier)
493 || (ke->modifiers() == Qt::AltModifier)
494 || (ke->modifiers() == Qt::MetaModifier);
498 if (!modified && !d->filter_.isEmpty()) {
503 case Qt::Key_Backspace:
505 // cut off one character
506 d->setFilter(d->filter_.left(d->filter_.length() - 1));
510 if (modified || ke->text().isEmpty())
512 // find chars for the filter string
514 for (int i = 0; i < ke->text().length(); ++i) {
515 QChar c = ke->text()[i];
516 if (c.isLetterOrNumber()
519 || c.category() == QChar::Separator_Space) {
524 // append new chars to the filter string
525 d->setFilter(d->filter_ + s);
531 return QComboBox::eventFilter(o, e);
535 void LayoutBox::setIconSize(QSize size)
538 bool small = size.height() < 20;
539 setAttribute(Qt::WA_MacSmallSize, small);
540 setAttribute(Qt::WA_MacNormalSize, !small);
542 (void)size; // suppress warning
547 void LayoutBox::set(docstring const & layout)
554 Layout const & lay = (*d->text_class_)[layout];
555 QString newLayout = toqstr(lay.name());
557 // If the layout is obsolete, use the new one instead.
558 docstring const & obs = lay.obsoleted_by();
560 newLayout = toqstr(obs);
562 int const curItem = currentIndex();
563 QModelIndex const mindex =
564 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
565 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
566 if (newLayout == currentLayout) {
567 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
571 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
573 LYXERR0("Trying to select non existent layout type " << newLayout);
577 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
581 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
582 bool sorted, bool sortedByCat, bool unknown)
584 QString qitem = toqstr(item);
585 // FIXME This is wrong for RTL, I'd suppose.
586 QString titem = toqstr(translateIfPossible(item) +
587 (unknown ? _(" (unknown)") : from_ascii("")));
588 QString qcat = toqstr(translateIfPossible(category));
590 QList<QStandardItem *> row;
591 row.append(new QStandardItem(titem));
592 row.append(new QStandardItem(qitem));
593 row.append(new QStandardItem(qcat));
595 // the first entry is easy
596 int const end = d->model_->rowCount();
598 d->model_->appendRow(row);
605 while (i < end && d->model_->item(i, 2)->text() != qcat)
609 // skip the Standard layout
613 // the simple unsorted case
616 // jump to the end of the category group
617 while (i < end && d->model_->item(i, 2)->text() == qcat)
619 d->model_->insertRow(i, row);
621 d->model_->appendRow(row);
625 // find row to insert the item, after the separator if it exists
627 // find alphabetic position
629 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
630 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
634 d->model_->insertRow(i, row);
638 void LayoutBox::updateContents(bool reset)
642 Buffer const * buffer = d->owner_.buffer();
651 // we'll only update the layout list if the text class has changed
652 // or we've moved from one inset to another
653 DocumentClass const * text_class = &buffer->params().documentClass();
654 Inset const * inset =
655 &(d->owner_.view()->cursor().innerText()->inset());
656 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
657 set(d->owner_.view()->cursor().innerParagraph().layout().name());
662 d->text_class_ = text_class;
665 DocumentClass::const_iterator lit = d->text_class_->begin();
666 DocumentClass::const_iterator len = d->text_class_->end();
668 for (; lit != len; ++lit) {
669 docstring const & name = lit->name();
670 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
671 // if this inset requires the empty layout, we skip the default
673 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
675 // if it doesn't require the empty layout, we skip it
676 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
678 // obsoleted layouts are skipped as well
679 if (!lit->obsoleted_by().empty())
681 addItemSort(name, lit->category(), lyxrc.sort_layouts,
682 lyxrc.group_layouts, lit->isUnknown());
685 set(d->owner_.view()->cursor().innerParagraph().layout().name());
686 d->countCategories();
688 // needed to recalculate size hint
690 setMinimumWidth(sizeHint().width());
691 setEnabled(!buffer->isReadonly() &&
692 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
697 void LayoutBox::selected(int index)
700 QModelIndex mindex = d->filterModel_->mapToSource(
701 d->filterModel_->index(index, 1));
702 docstring layoutName = qstring_to_ucs4(
703 d->model_->itemFromIndex(mindex)->text());
704 d->owner_.setFocus();
706 if (!d->text_class_) {
707 updateContents(false);
712 // find corresponding text class
713 if (d->text_class_->hasLayout(layoutName)) {
714 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
715 theLyXFunc().setLyXView(&d->owner_);
717 updateContents(false);
721 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
725 QString const & LayoutBox::filter() const
730 } // namespace frontend
733 #include "moc_LayoutBox.cpp"