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 Abdelrazak Younes
12 * Full author contact details are available in file CREDITS.
18 #include "GuiCommandBuffer.h"
19 #include "GuiToolbar.h"
20 #include "LyXAction.h"
22 #include "qt_helpers.h"
23 #include "InsertTableWidget.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "IconPalette.h"
35 #include "Paragraph.h"
36 #include "TextClass.h"
37 #include "ToolbarBackend.h"
39 #include "support/debug.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/lyxalgo.h" // sorted
45 #include <QAbstractItemDelegate>
46 #include <QAbstractTextDocumentLayout>
47 #include <QApplication>
49 #include <QHeaderView>
54 #include <QSortFilterProxyModel>
55 #include <QStandardItem>
56 #include <QStandardItemModel>
57 #include <QTextDocument>
59 #include <QToolButton>
62 #include <boost/assert.hpp>
65 using namespace lyx::support;
67 static void initializeResources()
69 static bool initialized = false;
71 Q_INIT_RESOURCE(Resources);
88 bool operator<(PngMap const & lhs, PngMap const & rhs)
90 return strcmp(lhs.key, rhs.key) < 0;
96 CompareKey(string const & name) : name_(name) {}
97 bool operator()(PngMap const & other) const { return other.key == name_; }
103 PngMap sorted_png_map[] = {
104 { "Bumpeq", "bumpeq2" },
107 { "Delta", "delta2" },
108 { "Downarrow", "downarrow2" },
109 { "Gamma", "gamma2" },
110 { "Lambda", "lambda2" },
111 { "Leftarrow", "leftarrow2" },
112 { "Leftrightarrow", "leftrightarrow2" },
113 { "Longleftarrow", "longleftarrow2" },
114 { "Longleftrightarrow", "longleftrightarrow2" },
115 { "Longrightarrow", "longrightarrow2" },
116 { "Omega", "omega2" },
120 { "Rightarrow", "rightarrow2" },
121 { "Sigma", "sigma2" },
122 { "Subset", "subset2" },
123 { "Supset", "supset2" },
124 { "Theta", "theta2" },
125 { "Uparrow", "uparrow2" },
126 { "Updownarrow", "updownarrow2" },
127 { "Upsilon", "upsilon2" },
128 { "Vdash", "vdash3" },
130 { "nLeftarrow", "nleftarrow2" },
131 { "nLeftrightarrow", "nleftrightarrow2" },
132 { "nRightarrow", "nrightarrow2" },
133 { "nVDash", "nvdash3" },
134 { "nvDash", "nvdash2" },
135 { "textrm \\AA", "textrm_AA"},
136 { "textrm \\O", "textrm_O"},
137 { "vDash", "vdash2" }
140 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
143 string const find_png(string const & name)
145 PngMap const * const begin = sorted_png_map;
146 PngMap const * const end = begin + nr_sorted_png_map;
147 BOOST_ASSERT(sorted(begin, end));
149 PngMap const * const it = find_if(begin, end, CompareKey(name));
153 png_name = it->value;
155 png_name = subst(name, "_", "underscore");
156 png_name = subst(png_name, ' ', '_');
158 // This way we can have "math-delim { }" on the toolbar.
159 png_name = subst(png_name, "(", "lparen");
160 png_name = subst(png_name, ")", "rparen");
161 png_name = subst(png_name, "[", "lbracket");
162 png_name = subst(png_name, "]", "rbracket");
163 png_name = subst(png_name, "{", "lbrace");
164 png_name = subst(png_name, "}", "rbrace");
165 png_name = subst(png_name, "|", "bars");
166 png_name = subst(png_name, ",", "thinspace");
167 png_name = subst(png_name, ":", "mediumspace");
168 png_name = subst(png_name, ";", "thickspace");
169 png_name = subst(png_name, "!", "negthinspace");
172 LYXERR(Debug::GUI, "find_png(" << name << ")\n"
173 << "Looking for math PNG called \"" << png_name << '"');
180 /// return a icon for the given action
181 static QIcon getIcon(FuncRequest const & f, bool unknown)
183 initializeResources();
191 case LFUN_MATH_INSERT:
192 if (!f.argument().empty()) {
194 name1 = find_png(to_utf8(f.argument()).substr(1));
197 case LFUN_MATH_DELIM:
198 case LFUN_MATH_BIGDELIM:
200 name1 = find_png(to_utf8(f.argument()));
204 name1 = to_utf8(f.argument());
207 name2 = lyxaction.getActionName(f.action);
210 if (!f.argument().empty())
211 name1 = subst(name2 + ' ' + to_utf8(f.argument()), ' ', '_');
214 fullname = libFileSearch("images/" + path, name1, "png").absFilename();
215 if (pm.load(toqstr(fullname)))
218 fullname = libFileSearch("images/" + path, name2, "png").absFilename();
219 if (pm.load(toqstr(fullname)))
222 if (pm.load(":/images/" + toqstr(path + name1) + ".png"))
225 if (pm.load(":/images/" + toqstr(path + name2) + ".png"))
228 LYXERR(Debug::GUI, "Cannot find icon for command \""
229 << lyxaction.getActionName(f.action)
230 << '(' << to_utf8(f.argument()) << ")\"");
232 pm.load(":/images/unknown.png");
238 /////////////////////////////////////////////////////////////////////
242 /////////////////////////////////////////////////////////////////////
244 class FilterItemDelegate : public QAbstractItemDelegate {
247 explicit FilterItemDelegate(QObject * parent = 0)
248 : QAbstractItemDelegate(parent) {}
251 void paint(QPainter * painter, QStyleOptionViewItem const & option,
252 QModelIndex const & index) const {
253 QComboBox * combo = static_cast<QComboBox const *>(parent());
255 // Draw using the menu item style (this is how QComboBox does it).
256 // But for the rich text drawing below we will call it with an
257 // empty string, and later then draw over it the real string.
259 QStyleOptionMenuItem opt = getStyleOption(option, index);
260 QString text = underlineFilter(opt.text);
261 opt.text = QString();
262 painter->eraseRect(option.rect);
263 combo->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, combo->view());
266 // don't draw string for separator
267 if (opt.menuItemType == QStyleOptionMenuItem::Separator)
270 // Draw the rich text.
272 QColor col = opt.palette.text().color();
273 if (opt.state & QStyle::State_Selected)
274 col = opt.palette.highlightedText().color();
275 QAbstractTextDocumentLayout::PaintContext context;
276 context.palette.setColor(QPalette::Text, col);
279 doc.setDefaultFont(opt.font);
281 painter->translate(opt.rect.x() + 20, opt.rect.y());
282 doc.documentLayout()->draw(painter, context);
287 QSize sizeHint(QStyleOptionViewItem const & option,
288 QModelIndex const & index) const {
289 QComboBox * combo = static_cast<QComboBox const *>(parent());
291 QStyleOptionMenuItem opt = getStyleOption(option, index);
292 return combo->style()->sizeFromContents(
293 QStyle::CT_MenuItem, &opt, option.rect.size(), combo);
298 QString underlineFilter(QString const & s) const
301 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
302 QString const & f = p->filter();
306 // step through data item and put "(x)" for every matching character
310 for (int i = 0; i < f.length(); ++i) {
311 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
312 BOOST_ASSERT(p != -1);
313 if (lastp == p - 1 && lastp != -1) {
314 // remove ")" and append "x)"
315 r = r.left(r.length() - 4) + s[p] + "</u>";
318 r += s.mid(lastp + 1, p - lastp - 1);
319 r += QString("<u>") + s[p] + "</u>";
323 r += s.mid(lastp + 1);
328 QStyleOptionMenuItem getStyleOption(QStyleOptionViewItem const & option,
329 QModelIndex const & index) const
331 QComboBox * combo = static_cast<QComboBox const *>(parent());
333 // create the options for a menu item
334 QStyleOptionMenuItem menuOption;
335 menuOption.palette = QApplication::palette("QMenu");
336 menuOption.state = QStyle::State_Active | QStyle::State_Enabled;
337 if (option.state & QStyle::State_Selected)
338 menuOption.state |= QStyle::State_Selected;
339 menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
340 menuOption.checked = combo->currentIndex() == index.row();
341 menuOption.text = index.model()->data(index, Qt::DisplayRole).toString()
342 .replace(QLatin1Char('&'), QLatin1String("&&"));
343 if (menuOption.text.left(2) == "--")
344 menuOption.menuItemType = QStyleOptionMenuItem::Separator;
346 menuOption.menuItemType = QStyleOptionMenuItem::Normal;
347 menuOption.tabWidth = 0;
348 menuOption.menuRect = option.rect;
349 menuOption.rect = option.rect;
350 menuOption.font = combo->font();
351 menuOption.fontMetrics = QFontMetrics(menuOption.font);
358 class GuiFilterProxyModel : public QSortFilterProxyModel
362 GuiFilterProxyModel(QObject * parent)
363 : QSortFilterProxyModel(parent) {}
366 void setCharFilter(QString const & f)
368 setFilterRegExp(charFilterRegExp(f));
369 dataChanged(index(0, 0), index(rowCount() - 1, 1));
374 QString charFilterRegExp(QString const & filter)
377 for (int i = 0; i < filter.length(); ++i)
378 re += ".*" + QRegExp::escape(filter[i]);
384 GuiLayoutBox::GuiLayoutBox(GuiView & owner)
385 : owner_(owner), filterItemDelegate_(new FilterItemDelegate(this))
387 setSizeAdjustPolicy(QComboBox::AdjustToContents);
388 setFocusPolicy(Qt::ClickFocus);
389 setMinimumWidth(sizeHint().width());
390 setMaxVisibleItems(100);
392 // set the layout model with two columns
393 // 1st: translated layout names
394 // 2nd: raw layout names
395 model_ = new QStandardItemModel(0, 2, this);
396 filterModel_ = new GuiFilterProxyModel(this);
397 filterModel_->setSourceModel(model_);
398 filterModel_->setDynamicSortFilter(true);
399 filterModel_->setFilterCaseSensitivity(Qt::CaseInsensitive);
400 setModel(filterModel_);
402 // for the filtering we have to intercept characters
403 view()->installEventFilter(this);
404 view()->setItemDelegateForColumn(0, filterItemDelegate_);
406 QObject::connect(this, SIGNAL(activated(int)),
407 this, SLOT(selected(int)));
408 owner_.setLayoutDialog(this);
409 updateContents(true);
413 void GuiLayoutBox::setFilter(QString const & s)
415 // remember old selection
416 int sel = currentIndex();
418 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
421 filterModel_->setCharFilter(s);
423 // restore old selection
424 if (lastSel_ != -1) {
425 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
427 setCurrentIndex(i.row());
430 // Workaround to resize to content size
431 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
433 if (view()->isVisible())
434 QComboBox::showPopup();
438 void GuiLayoutBox::resetFilter()
440 setFilter(QString());
444 void GuiLayoutBox::showPopup()
447 owner_.message(_("Enter characters to filter the layout list."));
448 QComboBox::showPopup();
452 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
454 if (e->type() != QEvent::KeyPress)
455 return QComboBox::eventFilter(o, e);
457 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
458 bool modified = (ke->modifiers() == Qt::ControlModifier)
459 || (ke->modifiers() == Qt::AltModifier)
460 || (ke->modifiers() == Qt::MetaModifier);
464 if (!modified && !filter_.isEmpty()) {
469 case Qt::Key_Backspace:
471 // cut off one character
472 setFilter(filter_.left(filter_.length() - 1));
476 if (modified || ke->text().isEmpty())
478 // find chars for the filter string
480 for (int i = 0; i < ke->text().length(); ++i) {
481 QChar c = ke->text()[i];
482 if (c.isLetterOrNumber()
485 || c.category() == QChar::Separator_Space) {
490 // append new chars to the filter string
491 setFilter(filter_ + s);
497 return QComboBox::eventFilter(o, e);
501 void GuiLayoutBox::set(docstring const & layout)
508 QString const & name = toqstr((*text_class_)[layout]->name());
509 if (name == currentText())
512 QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
514 lyxerr << "Trying to select non existent layout type "
515 << fromqstr(name) << endl;
519 setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
523 void GuiLayoutBox::addItemSort(docstring const & item, bool sorted)
525 QString qitem = toqstr(item);
526 QString titem = toqstr(translateIfPossible(item));
528 QList<QStandardItem *> row;
529 row.append(new QStandardItem(titem));
530 row.append(new QStandardItem(qitem));
532 // the simple unsorted case
533 int const end = model_->rowCount();
534 if (!sorted || end < 2 || qitem[0].category() != QChar::Letter_Uppercase) {
535 model_->appendRow(row);
539 // find row to insert the item, after the separator if it exists
540 int i = 1; // skip the Standard layout
542 QList<QStandardItem *> sep = model_->findItems("--", Qt::MatchStartsWith);
544 i = sep.first()->index().row() + 1;
545 if (i < model_->rowCount()) {
546 // find alphabetic position
547 QString is = model_->item(i, 0)->text();
548 while (is.compare(titem) < 0) {
549 // e.g. --Separator--
550 if (is.at(0).category() != QChar::Letter_Uppercase)
555 is = model_->item(i, 0)->text();
559 model_->insertRow(i, row);
563 void GuiLayoutBox::updateContents(bool reset)
567 Buffer const * buffer = owner_.buffer();
576 // we'll only update the layout list if the text class has changed
577 // or we've moved from one inset to another
578 DocumentClass const * text_class = &buffer->params().documentClass();
579 Inset const * inset =
580 owner_.view()->cursor().innerParagraph().inInset();
581 if (!reset && text_class_ == text_class && inset_ == inset) {
582 set(owner_.view()->cursor().innerParagraph().layout()->name());
587 text_class_ = text_class;
590 for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
591 Layout const & lt = *text_class_->layout(i);
592 docstring const & name = lt.name();
593 // if this inset requires the empty layout, we skip the default
595 if (name == text_class_->defaultLayoutName() && inset &&
596 (inset->forceEmptyLayout() || inset->useEmptyLayout()))
598 // if it doesn't require the empty layout, we skip it
599 if (name == text_class_->emptyLayoutName() && inset &&
600 !inset->forceEmptyLayout() && !inset->useEmptyLayout())
602 addItemSort(name, lyxrc.sort_layouts);
605 set(owner_.view()->cursor().innerParagraph().layout()->name());
607 // needed to recalculate size hint
609 setMinimumWidth(sizeHint().width());
610 setEnabled(!buffer->isReadonly());
615 void GuiLayoutBox::selected(int index)
618 QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
619 docstring const name = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
624 updateContents(false);
629 // find corresponding text class
630 for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
631 docstring const & itname = text_class_->layout(i)->name();
632 if (itname == name) {
633 FuncRequest const func(LFUN_LAYOUT, itname,
634 FuncRequest::TOOLBAR);
635 theLyXFunc().setLyXView(&owner_);
637 updateContents(false);
642 lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
647 /////////////////////////////////////////////////////////////////////
651 /////////////////////////////////////////////////////////////////////
654 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
655 : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
656 layout_(0), command_buffer_(0)
658 // give visual separation between adjacent toolbars
661 // TODO: save toolbar position
664 ToolbarInfo::item_iterator it = tbinfo.items.begin();
665 ToolbarInfo::item_iterator end = tbinfo.items.end();
666 for (; it != end; ++it)
671 Action * GuiToolbar::addItem(ToolbarItem const & item)
673 Action * act = new Action(owner_,
674 getIcon(item.func_, false),
675 toqstr(item.label_), item.func_, toqstr(item.label_));
676 actions_.append(act);
682 class PaletteButton : public QToolButton
686 ToolbarItem const & tbitem_;
689 PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
690 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
692 QString const label = qt_(to_ascii(tbitem_.label_));
696 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
697 this, SLOT(setIconSize(QSize)));
699 ToolbarInfo const * tbinfo =
700 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
702 // use the icon of first action for the toolbar button
703 setIcon(getIcon(tbinfo->items.begin()->func_, true));
706 void mousePressEvent(QMouseEvent * e)
709 QToolButton::mousePressEvent(e);
715 ToolbarInfo const * tbinfo =
716 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
718 lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
721 IconPalette * panel = new IconPalette(this);
722 QString const label = qt_(to_ascii(tbitem_.label_));
723 panel->setWindowTitle(label);
724 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
725 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
726 ToolbarInfo::item_iterator it = tbinfo->items.begin();
727 ToolbarInfo::item_iterator const end = tbinfo->items.end();
728 for (; it != end; ++it)
729 if (!getStatus(it->func_).unknown())
730 panel->addButton(bar_->addItem(*it));
732 QToolButton::mousePressEvent(e);
736 class MenuButton : public QToolButton
740 ToolbarItem const & tbitem_;
743 MenuButton(GuiToolbar * bar, ToolbarItem const & item)
744 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
746 setPopupMode(QToolButton::InstantPopup);
747 QString const label = qt_(to_ascii(tbitem_.label_));
751 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
752 connect(bar, SIGNAL(iconSizeChanged(QSize)),
753 this, SLOT(setIconSize(QSize)));
756 void mousePressEvent(QMouseEvent * e)
759 QToolButton::mousePressEvent(e);
765 QString const label = qt_(to_ascii(tbitem_.label_));
766 ButtonMenu * m = new ButtonMenu(label, this);
767 m->setWindowTitle(label);
768 m->setTearOffEnabled(true);
769 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
770 ToolbarInfo const * tbinfo =
771 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
773 lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
776 ToolbarInfo::item_iterator it = tbinfo->items.begin();
777 ToolbarInfo::item_iterator const end = tbinfo->items.end();
778 for (; it != end; ++it)
779 if (!getStatus(it->func_).unknown())
780 m->add(bar_->addItem(*it));
783 QToolButton::mousePressEvent(e);
790 void GuiToolbar::add(ToolbarItem const & item)
792 switch (item.type_) {
793 case ToolbarItem::SEPARATOR:
796 case ToolbarItem::LAYOUTS:
797 layout_ = new GuiLayoutBox(owner_);
800 case ToolbarItem::MINIBUFFER:
801 command_buffer_ = new GuiCommandBuffer(&owner_);
802 addWidget(command_buffer_);
803 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
804 //setHorizontalStretchable(true);
806 case ToolbarItem::TABLEINSERT: {
807 QToolButton * tb = new QToolButton;
808 tb->setCheckable(true);
809 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
810 QString const label = qt_(to_ascii(item.label_));
811 tb->setToolTip(label);
812 tb->setStatusTip(label);
814 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
815 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
816 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
817 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
821 case ToolbarItem::ICONPALETTE:
822 addWidget(new PaletteButton(this, item));
825 case ToolbarItem::POPUPMENU: {
826 addWidget(new MenuButton(this, item));
829 case ToolbarItem::COMMAND: {
830 if (!getStatus(item.func_).unknown())
831 addAction(addItem(item));
840 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
842 // if tbinfo.state == auto *do not* set on/off
843 if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
844 if (GuiToolbar::isVisible())
845 tbinfo.state = ToolbarSection::ToolbarInfo::ON;
847 tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
850 // no need to save it here.
851 Qt::ToolBarArea loc = owner_.toolBarArea(this);
853 if (loc == Qt::TopToolBarArea)
854 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
855 else if (loc == Qt::BottomToolBarArea)
856 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
857 else if (loc == Qt::RightToolBarArea)
858 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
859 else if (loc == Qt::LeftToolBarArea)
860 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
862 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
864 // save toolbar position. They are not used to restore toolbar position
865 // now because move(x,y) does not work for toolbar.
866 tbinfo.posx = pos().x();
867 tbinfo.posy = pos().y();
871 void GuiToolbar::updateContents()
873 // update visible toolbars only
876 // This is a speed bottleneck because this is called on every keypress
877 // and update calls getStatus, which copies the cursor at least two times
878 for (int i = 0; i < actions_.size(); ++i)
879 actions_[i]->update();
882 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
889 } // namespace frontend
892 #include "GuiToolbar_moc.cpp"