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
46 #include <QHeaderView>
50 #include <QSortFilterProxyModel>
51 #include <QStandardItem>
52 #include <QStandardItemModel>
54 #include <QToolButton>
57 #include <boost/assert.hpp>
60 using namespace lyx::support;
62 static void initializeResources()
64 static bool initialized = false;
66 Q_INIT_RESOURCE(Resources);
83 bool operator<(PngMap const & lhs, PngMap const & rhs)
85 return strcmp(lhs.key, rhs.key) < 0;
91 CompareKey(string const & name) : name_(name) {}
92 bool operator()(PngMap const & other) const { return other.key == name_; }
98 PngMap sorted_png_map[] = {
99 { "Bumpeq", "bumpeq2" },
102 { "Delta", "delta2" },
103 { "Downarrow", "downarrow2" },
104 { "Gamma", "gamma2" },
105 { "Lambda", "lambda2" },
106 { "Leftarrow", "leftarrow2" },
107 { "Leftrightarrow", "leftrightarrow2" },
108 { "Longleftarrow", "longleftarrow2" },
109 { "Longleftrightarrow", "longleftrightarrow2" },
110 { "Longrightarrow", "longrightarrow2" },
111 { "Omega", "omega2" },
115 { "Rightarrow", "rightarrow2" },
116 { "Sigma", "sigma2" },
117 { "Subset", "subset2" },
118 { "Supset", "supset2" },
119 { "Theta", "theta2" },
120 { "Uparrow", "uparrow2" },
121 { "Updownarrow", "updownarrow2" },
122 { "Upsilon", "upsilon2" },
123 { "Vdash", "vdash3" },
125 { "nLeftarrow", "nleftarrow2" },
126 { "nLeftrightarrow", "nleftrightarrow2" },
127 { "nRightarrow", "nrightarrow2" },
128 { "nVDash", "nvdash3" },
129 { "nvDash", "nvdash2" },
130 { "textrm \\AA", "textrm_AA"},
131 { "textrm \\O", "textrm_O"},
132 { "vDash", "vdash2" }
135 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
138 string const find_png(string const & name)
140 PngMap const * const begin = sorted_png_map;
141 PngMap const * const end = begin + nr_sorted_png_map;
142 BOOST_ASSERT(sorted(begin, end));
144 PngMap const * const it = find_if(begin, end, CompareKey(name));
148 png_name = it->value;
150 png_name = subst(name, "_", "underscore");
151 png_name = subst(png_name, ' ', '_');
153 // This way we can have "math-delim { }" on the toolbar.
154 png_name = subst(png_name, "(", "lparen");
155 png_name = subst(png_name, ")", "rparen");
156 png_name = subst(png_name, "[", "lbracket");
157 png_name = subst(png_name, "]", "rbracket");
158 png_name = subst(png_name, "{", "lbrace");
159 png_name = subst(png_name, "}", "rbrace");
160 png_name = subst(png_name, "|", "bars");
161 png_name = subst(png_name, ",", "thinspace");
162 png_name = subst(png_name, ":", "mediumspace");
163 png_name = subst(png_name, ";", "thickspace");
164 png_name = subst(png_name, "!", "negthinspace");
167 LYXERR(Debug::GUI, "find_png(" << name << ")\n"
168 << "Looking for math PNG called \"" << png_name << '"');
175 /// return a icon for the given action
176 static QIcon getIcon(FuncRequest const & f, bool unknown)
178 initializeResources();
186 case LFUN_MATH_INSERT:
187 if (!f.argument().empty()) {
189 name1 = find_png(to_utf8(f.argument()).substr(1));
192 case LFUN_MATH_DELIM:
193 case LFUN_MATH_BIGDELIM:
195 name1 = find_png(to_utf8(f.argument()));
199 name1 = to_utf8(f.argument());
202 name2 = lyxaction.getActionName(f.action);
205 if (!f.argument().empty())
206 name1 = subst(name2 + ' ' + to_utf8(f.argument()), ' ', '_');
209 fullname = libFileSearch("images/" + path, name1, "png").absFilename();
210 if (pm.load(toqstr(fullname)))
213 fullname = libFileSearch("images/" + path, name2, "png").absFilename();
214 if (pm.load(toqstr(fullname)))
217 if (pm.load(":/images/" + toqstr(path + name1) + ".png"))
220 if (pm.load(":/images/" + toqstr(path + name2) + ".png"))
223 LYXERR(Debug::GUI, "Cannot find icon for command \""
224 << lyxaction.getActionName(f.action)
225 << '(' << to_utf8(f.argument()) << ")\"");
227 pm.load(":/images/unknown.png");
233 /////////////////////////////////////////////////////////////////////
237 /////////////////////////////////////////////////////////////////////
239 class GuiFilterProxyModel : public QSortFilterProxyModel
243 GuiFilterProxyModel(QObject * parent)
244 : QSortFilterProxyModel(parent) {}
247 QVariant data(const QModelIndex & index, int role) const
249 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
250 QString const & f = p->filter();
252 if (!f.isEmpty() && index.isValid() && role == Qt::DisplayRole) {
253 // step through data item and put "(x)" for every matching character
254 QString s = QSortFilterProxyModel::data(index, role).toString();
258 for (int i = 0; i < f.length(); ++i) {
259 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
260 BOOST_ASSERT(p != -1);
261 if (lastp == p - 1 && lastp != -1) {
262 // remove ")" and append "x)"
263 r = r.left(r.length() - 1) + s[p] + ")";
266 r += s.mid(lastp + 1, p - lastp - 1);
267 r += "(" + s[p] + ")";
271 r += s.mid(lastp + 1);
275 return QSortFilterProxyModel::data(index, role);
279 void setCharFilter(QString const & f)
281 setFilterRegExp(charFilterRegExp(f));
287 QString charFilterRegExp(QString const & filter)
290 for (int i = 0; i < filter.length(); ++i)
291 re += ".*" + QRegExp::escape(filter[i]);
297 GuiLayoutBox::GuiLayoutBox(GuiView & owner)
300 setSizeAdjustPolicy(QComboBox::AdjustToContents);
301 setFocusPolicy(Qt::ClickFocus);
302 setMinimumWidth(sizeHint().width());
303 setMaxVisibleItems(100);
305 // set the layout model with two columns
306 // 1st: translated layout names
307 // 2nd: raw layout names
308 model_ = new QStandardItemModel(0, 2, this);
309 filterModel_ = new GuiFilterProxyModel(this);
310 filterModel_->setSourceModel(model_);
311 filterModel_->setDynamicSortFilter(true);
312 filterModel_->setFilterCaseSensitivity(Qt::CaseInsensitive);
313 setModel(filterModel_);
315 // for the filtering we have to intercept characters
316 view()->installEventFilter(this);
318 QObject::connect(this, SIGNAL(activated(int)),
319 this, SLOT(selected(int)));
320 owner_.setLayoutDialog(this);
321 updateContents(true);
325 void GuiLayoutBox::setFilter(QString const & s)
327 // remember old selection
328 int sel = currentIndex();
330 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
333 filterModel_->setCharFilter(s);
335 // restore old selection
336 if (lastSel_ != -1) {
337 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
339 setCurrentIndex(i.row());
344 void GuiLayoutBox::resetFilter()
346 setFilter(QString());
350 bool GuiLayoutBox::eventFilter(QObject *o, QEvent *e)
352 if (e->type() == QEvent::KeyPress) {
353 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
354 bool modified = (ke->modifiers() == Qt::ControlModifier)
355 || (ke->modifiers() == Qt::AltModifier)
356 || (ke->modifiers() == Qt::MetaModifier);
360 if (!modified && !filter_.isEmpty()) {
365 case Qt::Key_Backspace:
367 // cut off one character
368 setFilter(filter_.left(filter_.length() - 1));
372 if (modified || ke->text().isEmpty())
374 // find chars for the filter string
376 for (int i = 0; i < ke->text().length(); ++i) {
377 QChar c = ke->text()[i];
378 if (c.isLetterOrNumber()
381 || c.category() == QChar::Separator_Space) {
386 // append new chars to the filter string
387 setFilter(filter_ + s);
393 return QComboBox::eventFilter(o, e);
397 void GuiLayoutBox::set(docstring const & layout)
404 QString const & name = toqstr((*text_class_)[layout]->name());
405 if (name == currentText())
408 QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
410 lyxerr << "Trying to select non existent layout type "
411 << fromqstr(name) << endl;
415 setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
419 void GuiLayoutBox::addItemSort(docstring const & item, bool sorted)
421 QString qitem = toqstr(item);
422 QList<QStandardItem *> row;
423 row.append(new QStandardItem(toqstr(translateIfPossible(item))));
424 row.append(new QStandardItem(qitem));
426 // the simple unsorted case
427 int const end = model_->rowCount();
428 if (!sorted || end < 2 || qitem[0].category() != QChar::Letter_Uppercase) {
429 model_->appendRow(row);
433 // find row to insert the item
434 int i = 1; // skip the Standard layout
435 QString is = model_->item(i, 1)->text();
436 while (is.compare(qitem) < 0) {
437 // e.g. --Separator--
438 if (is[0].category() != QChar::Letter_Uppercase)
443 QString is = model_->item(i, 1)->text();
446 model_->insertRow(i, row);
450 void GuiLayoutBox::updateContents(bool reset)
454 Buffer const * buffer = owner_.buffer();
463 // we'll only update the layout list if the text class has changed
464 // or we've moved from one inset to another
465 DocumentClass const * text_class = &buffer->params().documentClass();
466 Inset const * inset =
467 owner_.view()->cursor().innerParagraph().inInset();
468 if (!reset && text_class_ == text_class && inset_ == inset) {
469 set(owner_.view()->cursor().innerParagraph().layout()->name());
474 text_class_ = text_class;
477 for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
478 Layout const & lt = *text_class_->layout(i);
479 docstring const & name = lt.name();
480 // if this inset requires the empty layout, we skip the default
482 if (name == text_class_->defaultLayoutName() && inset &&
483 (inset->forceEmptyLayout() || inset->useEmptyLayout()))
485 // if it doesn't require the empty layout, we skip it
486 if (name == text_class_->emptyLayoutName() && inset &&
487 !inset->forceEmptyLayout() && !inset->useEmptyLayout())
489 addItemSort(name, lyxrc.sort_layouts);
492 set(owner_.view()->cursor().innerParagraph().layout()->name());
494 // needed to recalculate size hint
496 setMinimumWidth(sizeHint().width());
497 setEnabled(!buffer->isReadonly());
502 void GuiLayoutBox::selected(int index)
505 QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
506 docstring const name = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
511 updateContents(false);
516 // find corresponding text class
517 for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
518 docstring const & itname = text_class_->layout(i)->name();
519 if (itname == name) {
520 FuncRequest const func(LFUN_LAYOUT, itname,
521 FuncRequest::TOOLBAR);
522 theLyXFunc().setLyXView(&owner_);
524 updateContents(false);
529 lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
534 /////////////////////////////////////////////////////////////////////
538 /////////////////////////////////////////////////////////////////////
541 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
542 : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
543 layout_(0), command_buffer_(0)
545 // give visual separation between adjacent toolbars
548 // TODO: save toolbar position
551 ToolbarInfo::item_iterator it = tbinfo.items.begin();
552 ToolbarInfo::item_iterator end = tbinfo.items.end();
553 for (; it != end; ++it)
558 Action * GuiToolbar::addItem(ToolbarItem const & item)
560 Action * act = new Action(owner_,
561 getIcon(item.func_, false),
562 toqstr(item.label_), item.func_, toqstr(item.label_));
563 actions_.append(act);
569 class PaletteButton : public QToolButton
573 ToolbarItem const & tbitem_;
576 PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
577 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
579 QString const label = qt_(to_ascii(tbitem_.label_));
583 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
584 this, SLOT(setIconSize(QSize)));
586 ToolbarInfo const * tbinfo =
587 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
589 // use the icon of first action for the toolbar button
590 setIcon(getIcon(tbinfo->items.begin()->func_, true));
593 void mousePressEvent(QMouseEvent * e)
596 QToolButton::mousePressEvent(e);
602 ToolbarInfo const * tbinfo =
603 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
605 lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
608 IconPalette * panel = new IconPalette(this);
609 QString const label = qt_(to_ascii(tbitem_.label_));
610 panel->setWindowTitle(label);
611 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
612 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
613 ToolbarInfo::item_iterator it = tbinfo->items.begin();
614 ToolbarInfo::item_iterator const end = tbinfo->items.end();
615 for (; it != end; ++it)
616 if (!getStatus(it->func_).unknown())
617 panel->addButton(bar_->addItem(*it));
619 QToolButton::mousePressEvent(e);
623 class MenuButton : public QToolButton
627 ToolbarItem const & tbitem_;
630 MenuButton(GuiToolbar * bar, ToolbarItem const & item)
631 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
633 setPopupMode(QToolButton::InstantPopup);
634 QString const label = qt_(to_ascii(tbitem_.label_));
638 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
639 connect(bar, SIGNAL(iconSizeChanged(QSize)),
640 this, SLOT(setIconSize(QSize)));
643 void mousePressEvent(QMouseEvent * e)
646 QToolButton::mousePressEvent(e);
652 QString const label = qt_(to_ascii(tbitem_.label_));
653 ButtonMenu * m = new ButtonMenu(label, this);
654 m->setWindowTitle(label);
655 m->setTearOffEnabled(true);
656 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
657 ToolbarInfo const * tbinfo =
658 toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
660 lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
663 ToolbarInfo::item_iterator it = tbinfo->items.begin();
664 ToolbarInfo::item_iterator const end = tbinfo->items.end();
665 for (; it != end; ++it)
666 if (!getStatus(it->func_).unknown())
667 m->add(bar_->addItem(*it));
670 QToolButton::mousePressEvent(e);
677 void GuiToolbar::add(ToolbarItem const & item)
679 switch (item.type_) {
680 case ToolbarItem::SEPARATOR:
683 case ToolbarItem::LAYOUTS:
684 layout_ = new GuiLayoutBox(owner_);
687 case ToolbarItem::MINIBUFFER:
688 command_buffer_ = new GuiCommandBuffer(&owner_);
689 addWidget(command_buffer_);
690 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
691 //setHorizontalStretchable(true);
693 case ToolbarItem::TABLEINSERT: {
694 QToolButton * tb = new QToolButton;
695 tb->setCheckable(true);
696 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
697 QString const label = qt_(to_ascii(item.label_));
698 tb->setToolTip(label);
699 tb->setStatusTip(label);
701 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
702 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
703 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
704 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
708 case ToolbarItem::ICONPALETTE:
709 addWidget(new PaletteButton(this, item));
712 case ToolbarItem::POPUPMENU: {
713 addWidget(new MenuButton(this, item));
716 case ToolbarItem::COMMAND: {
717 if (!getStatus(item.func_).unknown())
718 addAction(addItem(item));
727 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
729 // if tbinfo.state == auto *do not* set on/off
730 if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
731 if (GuiToolbar::isVisible())
732 tbinfo.state = ToolbarSection::ToolbarInfo::ON;
734 tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
737 // no need to save it here.
738 Qt::ToolBarArea loc = owner_.toolBarArea(this);
740 if (loc == Qt::TopToolBarArea)
741 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
742 else if (loc == Qt::BottomToolBarArea)
743 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
744 else if (loc == Qt::RightToolBarArea)
745 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
746 else if (loc == Qt::LeftToolBarArea)
747 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
749 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
751 // save toolbar position. They are not used to restore toolbar position
752 // now because move(x,y) does not work for toolbar.
753 tbinfo.posx = pos().x();
754 tbinfo.posy = pos().y();
758 void GuiToolbar::updateContents()
760 // update visible toolbars only
763 // This is a speed bottleneck because this is called on every keypress
764 // and update calls getStatus, which copies the cursor at least two times
765 for (int i = 0; i < actions_.size(); ++i)
766 actions_[i]->update();
769 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
776 } // namespace frontend
779 #include "GuiToolbar_moc.cpp"