2 * \file qt4/GuiToolbar.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 "GuiToolbar.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
24 #include "IconPalette.h"
25 #include "InsertTableWidget.h"
26 #include "qt_helpers.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
38 #include "Paragraph.h"
39 #include "TextClass.h"
41 #include "support/debug.h"
42 #include "support/filetools.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
46 #include <QAbstractItemDelegate>
47 #include <QAbstractTextDocumentLayout>
48 #include <QApplication>
50 #include <QFontMetrics>
51 #include <QHeaderView>
52 #include <QItemDelegate>
59 #include <QSortFilterProxyModel>
60 #include <QStandardItem>
61 #include <QStandardItemModel>
63 #include <QTextDocument>
66 #include <QToolButton>
69 #include "support/lassert.h"
72 using namespace lyx::support;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 class LayoutItemDelegate : public QItemDelegate {
86 explicit LayoutItemDelegate(QObject * parent = 0)
87 : QItemDelegate(parent)
91 void paint(QPainter * painter, QStyleOptionViewItem const & option,
92 QModelIndex const & index) const
94 QStyleOptionViewItem opt = option;
97 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
100 if (lyxrc.group_layouts) {
101 QSortFilterProxyModel const * model
102 = static_cast<QSortFilterProxyModel const *>(index.model());
104 QString stdCat = category(*model->sourceModel(), 0);
105 QString cat = category(*index.model(), index.row());
107 // not the standard layout and not the same as in the previous line?
109 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
112 // draw unselected background
113 QStyle::State state = opt.state;
114 opt.state = opt.state & ~QStyle::State_Selected;
115 drawBackground(painter, opt, index);
118 // draw category header
119 drawCategoryHeader(painter, opt,
120 category(*index.model(), index.row()));
122 // move rect down below header
123 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
129 QItemDelegate::paint(painter, opt, index);
133 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
134 const QRect & /*rect*/, const QString & text ) const
136 QString utext = underlineFilter(text);
138 // Draw the rich text.
140 QColor col = opt.palette.text().color();
141 if (opt.state & QStyle::State_Selected)
142 col = opt.palette.highlightedText().color();
143 QAbstractTextDocumentLayout::PaintContext context;
144 context.palette.setColor(QPalette::Text, col);
147 doc.setDefaultFont(opt.font);
150 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
152 doc.rootFrame()->setFrameFormat(fmt);
154 painter->translate(opt.rect.x() + 5,
155 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
156 doc.documentLayout()->draw(painter, context);
161 QSize sizeHint(QStyleOptionViewItem const & opt,
162 QModelIndex const & index) const
164 GuiLayoutBox * combo = static_cast<GuiLayoutBox *>(parent());
165 QSortFilterProxyModel const * model
166 = static_cast<QSortFilterProxyModel const *>(index.model());
167 QSize size = QItemDelegate::sizeHint(opt, index);
169 /// QComboBox uses the first row height to estimate the
170 /// complete popup height during QComboBox::showPopup().
171 /// To avoid scrolling we have to sneak in space for the headers.
172 /// So we tweak this value accordingly. It's not nice, but the
173 /// only possible way it seems.
174 if (lyxrc.group_layouts && index.row() == 0 && combo->inShowPopup_) {
175 int itemHeight = size.height();
177 // we have to show \c cats many headers:
178 unsigned cats = combo->visibleCategories_;
180 // and we have \c n items to distribute the needed space over
181 unsigned n = combo->model()->rowCount();
183 // so the needed average height (rounded upwards) is:
184 size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n);
188 // Add space for the category headers here?
189 // Not for the standard layout though.
190 QString stdCat = category(*model->sourceModel(), 0);
191 QString cat = category(*index.model(), index.row());
192 if (lyxrc.group_layouts && stdCat != cat
193 && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
194 size.setHeight(size.height() + headerHeight(opt));
202 QString category(QAbstractItemModel const & model, int row) const
204 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
208 int headerHeight(QStyleOptionViewItem const & opt) const
210 return opt.fontMetrics.height() * 8 / 10;
213 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
214 QString const & category) const
216 // slightly blended color
217 QColor lcol = opt.palette.text().color();
219 painter->setPen(lcol);
221 // set 80% scaled, bold font
222 QFont font = opt.font;
224 font.setWeight(QFont::Black);
225 font.setPointSize(opt.font.pointSize() * 8 / 10);
226 painter->setFont(font);
228 // draw the centered text
229 QFontMetrics fm(font);
230 int w = fm.width(category);
231 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
232 int y = opt.rect.y() + fm.ascent();
235 painter->drawText(x, y, category);
237 // the vertical position of the line: middle of lower case chars
238 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
240 // draw the horizontal line
241 if (!category.isEmpty()) {
242 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
243 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
245 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
250 QString underlineFilter(QString const & s) const
253 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
254 QString const & f = p->filter();
258 // step through data item and put "(x)" for every matching character
262 for (int i = 0; i < f.length(); ++i) {
263 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
264 LASSERT(p != -1, /**/);
265 if (lastp == p - 1 && lastp != -1) {
266 // remove ")" and append "x)"
267 r = r.left(r.length() - 4) + s[p] + "</u>";
270 r += s.mid(lastp + 1, p - lastp - 1);
271 r += QString("<u>") + s[p] + "</u>";
275 r += s.mid(lastp + 1);
281 class GuiLayoutFilterModel : public QSortFilterProxyModel {
284 GuiLayoutFilterModel(QObject * parent = 0)
285 : QSortFilterProxyModel(parent)
289 void triggerLayoutChange()
291 layoutAboutToBeChanged();
297 GuiLayoutBox::GuiLayoutBox(GuiToolbar * bar, GuiView & owner)
298 : owner_(owner), bar_(bar), lastSel_(-1),
299 layoutItemDelegate_(new LayoutItemDelegate(this)),
300 visibleCategories_(0), inShowPopup_(false)
302 setSizeAdjustPolicy(QComboBox::AdjustToContents);
303 setFocusPolicy(Qt::ClickFocus);
304 setMinimumWidth(sizeHint().width());
305 setMaxVisibleItems(100);
307 // set the layout model with two columns
308 // 1st: translated layout names
309 // 2nd: raw layout names
310 model_ = new QStandardItemModel(0, 2, this);
311 filterModel_ = new GuiLayoutFilterModel(this);
312 filterModel_->setSourceModel(model_);
313 setModel(filterModel_);
315 // for the filtering we have to intercept characters
316 view()->installEventFilter(this);
317 view()->setItemDelegateForColumn(0, layoutItemDelegate_);
319 QObject::connect(this, SIGNAL(activated(int)),
320 this, SLOT(selected(int)));
321 QObject::connect(bar_, SIGNAL(iconSizeChanged(QSize)),
322 this, SLOT(setIconSize(QSize)));
324 owner_.setLayoutDialog(this);
325 updateContents(true);
329 void GuiLayoutBox::setFilter(QString const & s)
331 bool enabled = view()->updatesEnabled();
332 view()->setUpdatesEnabled(false);
334 // remember old selection
335 int sel = currentIndex();
337 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
340 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
343 // restore old selection
344 if (lastSel_ != -1) {
345 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
347 setCurrentIndex(i.row());
350 // Workaround to resize to content size
351 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
353 if (view()->isVisible()) {
354 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
355 // the hack in the item delegate to make space for the headers.
356 // We do not call our implementation of showPopup because that
357 // would reset the filter again. This is only needed if the user clicks
359 LASSERT(!inShowPopup_, /**/);
361 QComboBox::showPopup();
362 inShowPopup_ = false;
364 // The item delegate hack is off again. So trigger a relayout of the popup.
365 filterModel_->triggerLayoutChange();
368 owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
369 "Press ESC to remove filter."),
370 qstring_to_ucs4(s)));
372 owner_.message(_("Enter characters to filter the layout list."));
375 view()->setUpdatesEnabled(enabled);
379 void GuiLayoutBox::countCategories()
381 int n = filterModel_->rowCount();
382 visibleCategories_ = 0;
383 if (n == 0 || !lyxrc.group_layouts)
386 // skip the "Standard" category
387 QString prevCat = model_->index(0, 2).data().toString();
390 for (int i = 0; i < n; ++i) {
391 QString cat = filterModel_->index(i, 2).data().toString();
393 ++visibleCategories_;
399 QString GuiLayoutBox::charFilterRegExp(QString const & filter)
402 for (int i = 0; i < filter.length(); ++i) {
405 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
407 re += ".*" + QRegExp::escape(c);
413 void GuiLayoutBox::resetFilter()
415 setFilter(QString());
419 void GuiLayoutBox::showPopup()
421 owner_.message(_("Enter characters to filter the layout list."));
423 bool enabled = view()->updatesEnabled();
424 view()->setUpdatesEnabled(false);
428 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
429 // the hack in the item delegate to make space for the headers.
430 LASSERT(!inShowPopup_, /**/);
432 QComboBox::showPopup();
433 inShowPopup_ = false;
435 // The item delegate hack is off again. So trigger a relayout of the popup.
436 filterModel_->triggerLayoutChange();
438 view()->setUpdatesEnabled(enabled);
442 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
444 if (e->type() != QEvent::KeyPress)
445 return QComboBox::eventFilter(o, e);
447 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
448 bool modified = (ke->modifiers() == Qt::ControlModifier)
449 || (ke->modifiers() == Qt::AltModifier)
450 || (ke->modifiers() == Qt::MetaModifier);
454 if (!modified && !filter_.isEmpty()) {
459 case Qt::Key_Backspace:
461 // cut off one character
462 setFilter(filter_.left(filter_.length() - 1));
466 if (modified || ke->text().isEmpty())
468 // find chars for the filter string
470 for (int i = 0; i < ke->text().length(); ++i) {
471 QChar c = ke->text()[i];
472 if (c.isLetterOrNumber()
475 || c.category() == QChar::Separator_Space) {
480 // append new chars to the filter string
481 setFilter(filter_ + s);
487 return QComboBox::eventFilter(o, e);
491 void GuiLayoutBox::setIconSize(QSize size)
494 bool small = size.height() < 20;
495 setAttribute(Qt::WA_MacSmallSize, small);
496 setAttribute(Qt::WA_MacNormalSize, !small);
498 (void)size; // suppress warning
503 void GuiLayoutBox::set(docstring const & layout)
510 Layout const & lay = (*text_class_)[layout];
511 QString newLayout = toqstr(lay.name());
513 // If the layout is obsolete, use the new one instead.
514 docstring const & obs = lay.obsoleted_by();
516 newLayout = toqstr(obs);
518 int const curItem = currentIndex();
519 QModelIndex const mindex =
520 filterModel_->mapToSource(filterModel_->index(curItem, 1));
521 QString const & currentLayout = model_->itemFromIndex(mindex)->text();
522 if (newLayout == currentLayout) {
523 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
527 QList<QStandardItem *> r = model_->findItems(newLayout, Qt::MatchExactly, 1);
529 LYXERR0("Trying to select non existent layout type " << newLayout);
533 setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
537 void GuiLayoutBox::addItemSort(docstring const & item, docstring const & category,
538 bool sorted, bool sortedByCat, bool unknown)
540 QString qitem = toqstr(item);
541 // FIXME This is wrong for RTL, I'd suppose.
542 QString titem = toqstr(translateIfPossible(item) +
543 (unknown ? _(" (unknown)") : from_ascii("")));
544 QString qcat = toqstr(translateIfPossible(category));
546 QList<QStandardItem *> row;
547 row.append(new QStandardItem(titem));
548 row.append(new QStandardItem(qitem));
549 row.append(new QStandardItem(qcat));
551 // the first entry is easy
552 int const end = model_->rowCount();
554 model_->appendRow(row);
561 while (i < end && model_->item(i, 2)->text() != qcat)
565 // skip the Standard layout
569 // the simple unsorted case
572 // jump to the end of the category group
573 while (i < end && model_->item(i, 2)->text() == qcat)
575 model_->insertRow(i, row);
577 model_->appendRow(row);
581 // find row to insert the item, after the separator if it exists
583 // find alphabetic position
585 && model_->item(i, 0)->text().localeAwareCompare(titem) < 0
586 && (!sortedByCat || model_->item(i, 2)->text() == qcat))
590 model_->insertRow(i, row);
594 void GuiLayoutBox::updateContents(bool reset)
598 Buffer const * buffer = owner_.buffer();
607 // we'll only update the layout list if the text class has changed
608 // or we've moved from one inset to another
609 DocumentClass const * text_class = &buffer->params().documentClass();
610 Inset const * inset =
611 &(owner_.view()->cursor().innerParagraph().inInset());
612 if (!reset && text_class_ == text_class && inset_ == inset) {
613 set(owner_.view()->cursor().innerParagraph().layout().name());
618 text_class_ = text_class;
621 DocumentClass::const_iterator lit = text_class_->begin();
622 DocumentClass::const_iterator len = text_class_->end();
624 for (; lit != len; ++lit) {
625 docstring const & name = lit->name();
626 bool const useEmpty = inset_->forcePlainLayout() || inset_->usePlainLayout();
627 // if this inset requires the empty layout, we skip the default
629 if (name == text_class_->defaultLayoutName() && inset_ && useEmpty)
631 // if it doesn't require the empty layout, we skip it
632 if (name == text_class_->plainLayoutName() && inset_ && !useEmpty)
634 // obsoleted layouts are skipped as well
635 if (!lit->obsoleted_by().empty())
637 addItemSort(name, lit->category(), lyxrc.sort_layouts,
638 lyxrc.group_layouts, lit->isUnknown());
641 set(owner_.view()->cursor().innerParagraph().layout().name());
644 // needed to recalculate size hint
646 setMinimumWidth(sizeHint().width());
647 setEnabled(!buffer->isReadonly() &&
648 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
653 void GuiLayoutBox::selected(int index)
656 QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
657 docstring layoutName = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
661 updateContents(false);
666 // find corresponding text class
667 if (text_class_->hasLayout(layoutName)) {
668 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
669 theLyXFunc().setLyXView(&owner_);
671 updateContents(false);
675 LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
680 /////////////////////////////////////////////////////////////////////
684 /////////////////////////////////////////////////////////////////////
687 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
688 : QToolBar(toqstr(tbinfo.gui_name), &owner), visibility_(0),
689 allowauto_(false), owner_(owner), layout_(0), command_buffer_(0),
690 tbinfo_(tbinfo), filled_(false)
692 setIconSize(owner.iconSize());
693 connect(&owner, SIGNAL(iconSizeChanged(QSize)), this,
694 SLOT(setIconSize(QSize)));
696 // Toolbar dragging is allowed.
698 // This is used by QMainWindow::restoreState for proper main window state
700 setObjectName(toqstr(tbinfo.name));
705 void GuiToolbar::fill()
709 ToolbarInfo::item_iterator it = tbinfo_.items.begin();
710 ToolbarInfo::item_iterator end = tbinfo_.items.end();
711 for (; it != end; ++it)
717 void GuiToolbar::showEvent(QShowEvent * ev)
724 void GuiToolbar::setVisibility(int visibility)
726 visibility_ = visibility;
727 allowauto_ = visibility_ >= Toolbars::MATH;
731 Action * GuiToolbar::addItem(ToolbarItem const & item)
733 Action * act = new Action(&owner_, getIcon(item.func_, false),
734 toqstr(item.label_), item.func_, toqstr(item.label_), this);
735 actions_.append(act);
741 class PaletteButton : public QToolButton
745 ToolbarItem const & tbitem_;
748 PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
749 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
751 QString const label = qt_(to_ascii(tbitem_.label_));
755 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
756 this, SLOT(setIconSize(QSize)));
758 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
760 // use the icon of first action for the toolbar button
761 setIcon(getIcon(tbinfo->items.begin()->func_, true));
764 void mousePressEvent(QMouseEvent * e)
767 QToolButton::mousePressEvent(e);
773 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
775 LYXERR0("Unknown toolbar " << tbitem_.name_);
778 IconPalette * panel = new IconPalette(this);
779 QString const label = qt_(to_ascii(tbitem_.label_));
780 panel->setWindowTitle(label);
781 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
782 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
783 ToolbarInfo::item_iterator it = tbinfo->items.begin();
784 ToolbarInfo::item_iterator const end = tbinfo->items.end();
785 for (; it != end; ++it)
786 if (!getStatus(it->func_).unknown())
787 panel->addButton(bar_->addItem(*it));
789 QToolButton::mousePressEvent(e);
793 class MenuButton : public QToolButton
797 ToolbarItem const & tbitem_;
800 MenuButton(GuiToolbar * bar, ToolbarItem const & item)
801 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
803 setPopupMode(QToolButton::InstantPopup);
804 QString const label = qt_(to_ascii(tbitem_.label_));
808 setIcon(QIcon(getPixmap("images/math/", toqstr(tbitem_.name_), "png")));
809 connect(bar, SIGNAL(iconSizeChanged(QSize)),
810 this, SLOT(setIconSize(QSize)));
813 void mousePressEvent(QMouseEvent * e)
816 QToolButton::mousePressEvent(e);
822 QString const label = qt_(to_ascii(tbitem_.label_));
823 ButtonMenu * m = new ButtonMenu(label, this);
824 m->setWindowTitle(label);
825 m->setTearOffEnabled(true);
826 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
827 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
829 LYXERR0("Unknown toolbar " << tbitem_.name_);
832 ToolbarInfo::item_iterator it = tbinfo->items.begin();
833 ToolbarInfo::item_iterator const end = tbinfo->items.end();
834 for (; it != end; ++it)
835 if (!getStatus(it->func_).unknown())
836 m->add(bar_->addItem(*it));
839 QToolButton::mousePressEvent(e);
846 void GuiToolbar::add(ToolbarItem const & item)
848 switch (item.type_) {
849 case ToolbarItem::SEPARATOR:
852 case ToolbarItem::LAYOUTS:
853 layout_ = new GuiLayoutBox(this, owner_);
856 case ToolbarItem::MINIBUFFER:
857 command_buffer_ = new GuiCommandBuffer(&owner_);
858 addWidget(command_buffer_);
859 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
860 //setHorizontalStretchable(true);
862 case ToolbarItem::TABLEINSERT: {
863 QToolButton * tb = new QToolButton;
864 tb->setCheckable(true);
865 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
866 QString const label = qt_(to_ascii(item.label_));
867 tb->setToolTip(label);
868 tb->setStatusTip(label);
870 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
871 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
872 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
873 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
877 case ToolbarItem::ICONPALETTE:
878 addWidget(new PaletteButton(this, item));
881 case ToolbarItem::POPUPMENU: {
882 addWidget(new MenuButton(this, item));
885 case ToolbarItem::COMMAND: {
886 if (!getStatus(item.func_).unknown())
887 addAction(addItem(item));
896 void GuiToolbar::update(bool in_math, bool in_table, bool in_review,
897 bool in_mathmacrotemplate)
899 if (visibility_ & Toolbars::AUTO) {
900 bool show_it = (in_math && (visibility_ & Toolbars::MATH))
901 || (in_table && (visibility_ & Toolbars::TABLE))
902 || (in_review && (visibility_ & Toolbars::REVIEW))
903 || (in_mathmacrotemplate && (visibility_ & Toolbars::MATHMACROTEMPLATE));
907 // update visible toolbars only
911 // This is a speed bottleneck because this is called on every keypress
912 // and update calls getStatus, which copies the cursor at least two times
913 for (int i = 0; i < actions_.size(); ++i)
914 actions_[i]->update();
917 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
924 QString GuiToolbar::sessionKey() const
926 return "views/" + QString::number(owner_.id()) + "/" + objectName();
930 void GuiToolbar::saveSession() const
933 settings.setValue(sessionKey() + "/visibility", visibility_);
937 void GuiToolbar::restoreSession()
940 setVisibility(settings.value(sessionKey() + "/visibility").toInt());
944 void GuiToolbar::toggle()
948 if (!(visibility_ & Toolbars::AUTO)) {
949 visibility_ |= Toolbars::AUTO;
953 visibility_ &= ~Toolbars::AUTO;
972 owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
973 qstring_to_ucs4(windowTitle()), state));
976 } // namespace frontend
979 #include "moc_GuiToolbar.cpp"