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 lastSel_(-1), visibleCategories_(0), inShowPopup_(false),
128 layoutItemDelegate_(new LayoutItemDelegate(parent)),
129 // set the layout model with two columns
130 // 1st: translated layout names
131 // 2nd: raw layout names
132 model_(new QStandardItemModel(0, 2, p)),
133 filterModel_(new GuiLayoutFilterModel(p))
135 filterModel_->setSourceModel(model_);
138 void resetFilter() { setFilter(QString()); }
140 void setFilter(QString const & s);
142 void countCategories();
148 DocumentClass const * text_class_;
150 Inset const * inset_;
152 /// the layout model: 1st column translated, 2nd column raw layout name
153 QStandardItemModel * model_;
154 /// the proxy model filtering \c model_
155 GuiLayoutFilterModel * filterModel_;
156 /// the (model-) index of the last successful selection
158 /// the character filter
161 LayoutItemDelegate * layoutItemDelegate_;
163 unsigned visibleCategories_;
169 static QString category(QAbstractItemModel const & model, int row)
171 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
175 static int headerHeight(QStyleOptionViewItem const & opt)
177 return opt.fontMetrics.height() * 8 / 10;
181 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
182 QModelIndex const & index) const
184 QStyleOptionViewItem opt = option;
186 // default background
187 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
190 if (lyxrc.group_layouts) {
191 QSortFilterProxyModel const * model =
192 static_cast<QSortFilterProxyModel const *>(index.model());
194 QString stdCat = category(*model->sourceModel(), 0);
195 QString cat = category(*index.model(), index.row());
197 // not the standard layout and not the same as in the previous line?
199 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
202 // draw unselected background
203 QStyle::State state = opt.state;
204 opt.state = opt.state & ~QStyle::State_Selected;
205 drawBackground(painter, opt, index);
208 // draw category header
209 drawCategoryHeader(painter, opt,
210 category(*index.model(), index.row()));
212 // move rect down below header
213 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
219 QItemDelegate::paint(painter, opt, index);
223 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
224 const QRect & /*rect*/, const QString & text ) const
226 QString utext = underlineFilter(text);
228 // Draw the rich text.
230 QColor col = opt.palette.text().color();
231 if (opt.state & QStyle::State_Selected)
232 col = opt.palette.highlightedText().color();
233 QAbstractTextDocumentLayout::PaintContext context;
234 context.palette.setColor(QPalette::Text, col);
237 doc.setDefaultFont(opt.font);
240 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
242 doc.rootFrame()->setFrameFormat(fmt);
244 painter->translate(opt.rect.x() + 5,
245 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
246 doc.documentLayout()->draw(painter, context);
251 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
252 QModelIndex const & index) const
254 QSortFilterProxyModel const * model =
255 static_cast<QSortFilterProxyModel const *>(index.model());
256 QSize size = QItemDelegate::sizeHint(opt, index);
258 /// QComboBox uses the first row height to estimate the
259 /// complete popup height during QComboBox::showPopup().
260 /// To avoid scrolling we have to sneak in space for the headers.
261 /// So we tweak this value accordingly. It's not nice, but the
262 /// only possible way it seems.
263 if (lyxrc.group_layouts && index.row() == 0 && layout_->d->inShowPopup_) {
264 int itemHeight = size.height();
266 // we have to show \c cats many headers:
267 unsigned cats = layout_->d->visibleCategories_;
269 // and we have \c n items to distribute the needed space over
270 unsigned n = layout_->model()->rowCount();
272 // so the needed average height (rounded upwards) is:
273 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
277 // Add space for the category headers here?
278 // Not for the standard layout though.
279 QString stdCat = category(*model->sourceModel(), 0);
280 QString cat = category(*index.model(), index.row());
281 if (lyxrc.group_layouts && stdCat != cat
282 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
283 size.setHeight(size.height() + headerHeight(opt));
290 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
291 QString const & category) const
293 // slightly blended color
294 QColor lcol = opt.palette.text().color();
296 painter->setPen(lcol);
298 // set 80% scaled, bold font
299 QFont font = opt.font;
301 font.setWeight(QFont::Black);
302 font.setPointSize(opt.font.pointSize() * 8 / 10);
303 painter->setFont(font);
305 // draw the centered text
306 QFontMetrics fm(font);
307 int w = fm.width(category);
308 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
309 int y = opt.rect.y() + fm.ascent();
312 painter->drawText(x, y, category);
314 // the vertical position of the line: middle of lower case chars
315 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
317 // draw the horizontal line
318 if (!category.isEmpty()) {
319 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
320 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
322 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
326 QString LayoutItemDelegate::underlineFilter(QString const & s) const
328 QString const & f = layout_->filter();
332 // step through data item and put "(x)" for every matching character
336 for (int i = 0; i < f.length(); ++i) {
337 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
338 LASSERT(p != -1, /**/);
339 if (lastp == p - 1 && lastp != -1) {
340 // remove ")" and append "x)"
341 r = r.left(r.length() - 4) + s[p] + "</u>";
344 r += s.mid(lastp + 1, p - lastp - 1);
345 r += QString("<u>") + s[p] + "</u>";
349 r += s.mid(lastp + 1);
354 static QString charFilterRegExp(QString const & filter)
357 for (int i = 0; i < filter.length(); ++i) {
360 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
362 re += ".*" + QRegExp::escape(c);
368 void LayoutBox::Private::setFilter(QString const & s)
370 bool enabled = p->view()->updatesEnabled();
371 p->view()->setUpdatesEnabled(false);
373 // remember old selection
374 int sel = p->currentIndex();
376 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
379 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
382 // restore old selection
383 if (lastSel_ != -1) {
384 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
386 p->setCurrentIndex(i.row());
389 // Workaround to resize to content size
390 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
392 if (p->view()->isVisible()) {
393 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
394 // the hack in the item delegate to make space for the headers.
395 // We do not call our implementation of showPopup because that
396 // would reset the filter again. This is only needed if the user clicks
398 LASSERT(!inShowPopup_, /**/);
401 inShowPopup_ = false;
403 // The item delegate hack is off again. So trigger a relayout of the popup.
404 filterModel_->triggerLayoutChange();
407 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
408 "Press ESC to remove filter."),
409 qstring_to_ucs4(s)));
411 owner_.message(_("Enter characters to filter the layout list."));
414 p->view()->setUpdatesEnabled(enabled);
418 LayoutBox::LayoutBox(QToolBar * bar, GuiView & owner)
419 : d(new Private(this, owner))
421 setSizeAdjustPolicy(QComboBox::AdjustToContents);
422 setFocusPolicy(Qt::ClickFocus);
423 setMinimumWidth(sizeHint().width());
424 setMaxVisibleItems(100);
426 setModel(d->filterModel_);
428 // for the filtering we have to intercept characters
429 view()->installEventFilter(this);
430 view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
432 QObject::connect(this, SIGNAL(activated(int)),
433 this, SLOT(selected(int)));
434 QObject::connect(bar, SIGNAL(iconSizeChanged(QSize)),
435 this, SLOT(setIconSize(QSize)));
437 d->owner_.setLayoutDialog(this);
438 updateContents(true);
442 void LayoutBox::Private::countCategories()
444 int n = filterModel_->rowCount();
445 visibleCategories_ = 0;
446 if (n == 0 || !lyxrc.group_layouts)
449 // skip the "Standard" category
450 QString prevCat = model_->index(0, 2).data().toString();
453 for (int i = 0; i < n; ++i) {
454 QString cat = filterModel_->index(i, 2).data().toString();
456 ++visibleCategories_;
462 void LayoutBox::showPopup()
464 d->owner_.message(_("Enter characters to filter the layout list."));
466 bool enabled = view()->updatesEnabled();
467 view()->setUpdatesEnabled(false);
471 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
472 // the hack in the item delegate to make space for the headers.
473 LASSERT(!d->inShowPopup_, /**/);
474 d->inShowPopup_ = true;
475 QComboBox::showPopup();
476 d->inShowPopup_ = false;
478 // The item delegate hack is off again. So trigger a relayout of the popup.
479 d->filterModel_->triggerLayoutChange();
481 view()->setUpdatesEnabled(enabled);
485 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
487 if (e->type() != QEvent::KeyPress)
488 return QComboBox::eventFilter(o, e);
490 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
491 bool modified = (ke->modifiers() == Qt::ControlModifier)
492 || (ke->modifiers() == Qt::AltModifier)
493 || (ke->modifiers() == Qt::MetaModifier);
497 if (!modified && !d->filter_.isEmpty()) {
502 case Qt::Key_Backspace:
504 // cut off one character
505 d->setFilter(d->filter_.left(d->filter_.length() - 1));
509 if (modified || ke->text().isEmpty())
511 // find chars for the filter string
513 for (int i = 0; i < ke->text().length(); ++i) {
514 QChar c = ke->text()[i];
515 if (c.isLetterOrNumber()
518 || c.category() == QChar::Separator_Space) {
523 // append new chars to the filter string
524 d->setFilter(d->filter_ + s);
530 return QComboBox::eventFilter(o, e);
534 void LayoutBox::setIconSize(QSize size)
537 bool small = size.height() < 20;
538 setAttribute(Qt::WA_MacSmallSize, small);
539 setAttribute(Qt::WA_MacNormalSize, !small);
541 (void)size; // suppress warning
546 void LayoutBox::set(docstring const & layout)
553 Layout const & lay = (*d->text_class_)[layout];
554 QString newLayout = toqstr(lay.name());
556 // If the layout is obsolete, use the new one instead.
557 docstring const & obs = lay.obsoleted_by();
559 newLayout = toqstr(obs);
561 int const curItem = currentIndex();
562 QModelIndex const mindex =
563 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
564 QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
565 if (newLayout == currentLayout) {
566 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
570 QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
572 LYXERR0("Trying to select non existent layout type " << newLayout);
576 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
580 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
581 bool sorted, bool sortedByCat, bool unknown)
583 QString qitem = toqstr(item);
584 // FIXME This is wrong for RTL, I'd suppose.
585 QString titem = toqstr(translateIfPossible(item) +
586 (unknown ? _(" (unknown)") : from_ascii("")));
587 QString qcat = toqstr(translateIfPossible(category));
589 QList<QStandardItem *> row;
590 row.append(new QStandardItem(titem));
591 row.append(new QStandardItem(qitem));
592 row.append(new QStandardItem(qcat));
594 // the first entry is easy
595 int const end = d->model_->rowCount();
597 d->model_->appendRow(row);
604 while (i < end && d->model_->item(i, 2)->text() != qcat)
608 // skip the Standard layout
612 // the simple unsorted case
615 // jump to the end of the category group
616 while (i < end && d->model_->item(i, 2)->text() == qcat)
618 d->model_->insertRow(i, row);
620 d->model_->appendRow(row);
624 // find row to insert the item, after the separator if it exists
626 // find alphabetic position
628 && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
629 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
633 d->model_->insertRow(i, row);
637 void LayoutBox::updateContents(bool reset)
641 Buffer const * buffer = d->owner_.buffer();
650 // we'll only update the layout list if the text class has changed
651 // or we've moved from one inset to another
652 DocumentClass const * text_class = &buffer->params().documentClass();
653 Inset const * inset =
654 &(d->owner_.view()->cursor().innerText()->inset());
655 if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
656 set(d->owner_.view()->cursor().innerParagraph().layout().name());
661 d->text_class_ = text_class;
664 DocumentClass::const_iterator lit = d->text_class_->begin();
665 DocumentClass::const_iterator len = d->text_class_->end();
667 for (; lit != len; ++lit) {
668 docstring const & name = lit->name();
669 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
670 // if this inset requires the empty layout, we skip the default
672 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
674 // if it doesn't require the empty layout, we skip it
675 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
677 // obsoleted layouts are skipped as well
678 if (!lit->obsoleted_by().empty())
680 addItemSort(name, lit->category(), lyxrc.sort_layouts,
681 lyxrc.group_layouts, lit->isUnknown());
684 set(d->owner_.view()->cursor().innerParagraph().layout().name());
685 d->countCategories();
687 // needed to recalculate size hint
689 setMinimumWidth(sizeHint().width());
690 setEnabled(!buffer->isReadonly() &&
691 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
696 void LayoutBox::selected(int index)
699 QModelIndex mindex = d->filterModel_->mapToSource(
700 d->filterModel_->index(index, 1));
701 docstring layoutName = qstring_to_ucs4(
702 d->model_->itemFromIndex(mindex)->text());
703 d->owner_.setFocus();
705 if (!d->text_class_) {
706 updateContents(false);
711 // find corresponding text class
712 if (d->text_class_->hasLayout(layoutName)) {
713 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
714 theLyXFunc().setLyXView(&d->owner_);
716 updateContents(false);
720 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
724 QString const & LayoutBox::filter() const
729 } // namespace frontend
732 #include "moc_LayoutBox.cpp"