]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
resuscitate Vert.png as vert2.png
[features.git] / src / frontends / qt4 / GuiToolbar.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "GuiView.h"
19 #include "GuiCommandBuffer.h"
20 #include "GuiToolbar.h"
21 #include "LyXAction.h"
22 #include "Action.h"
23 #include "qt_helpers.h"
24 #include "InsertTableWidget.h"
25
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "Cursor.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
32 #include "IconPalette.h"
33 #include "Layout.h"
34 #include "LyXFunc.h"
35 #include "LyXRC.h"
36 #include "Paragraph.h"
37 #include "TextClass.h"
38 #include "ToolbarBackend.h"
39
40 #include "support/debug.h"
41 #include "support/filetools.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/lyxalgo.h" // sorted
45
46 #include <QAbstractItemDelegate>
47 #include <QAbstractTextDocumentLayout>
48 #include <QApplication>
49 #include <QComboBox>
50 #include <QFontMetrics>
51 #include <QHeaderView>
52 #include <QItemDelegate>
53 #include <QKeyEvent>
54 #include <QList>
55 #include <QListView>
56 #include <QPainter>
57 #include <QPixmap>
58 #include <QSortFilterProxyModel>
59 #include <QStandardItem>
60 #include <QStandardItemModel>
61 #include <QTextDocument>
62 #include <QTextFrame>
63 #include <QToolBar>
64 #include <QToolButton>
65 #include <QVariant>
66
67 #include <boost/assert.hpp>
68
69 #include <map>
70 #include <vector>
71
72 using namespace std;
73 using namespace lyx::support;
74
75 static void initializeResources()
76 {
77         static bool initialized = false;
78         if (!initialized) {
79                 Q_INIT_RESOURCE(Resources); 
80                 initialized = true;
81         }
82 }
83
84
85 namespace lyx {
86 namespace frontend {
87
88 namespace {
89
90 struct PngMap {
91         QString key;
92         QString value;
93 };
94
95
96 bool operator<(PngMap const & lhs, PngMap const & rhs)
97 {
98                 return lhs.key < rhs.key;
99 }
100
101
102 class CompareKey {
103 public:
104         CompareKey(QString const & name) : name_(name) {}
105         bool operator()(PngMap const & other) const { return other.key == name_; }
106 private:
107         QString const name_;
108 };
109
110
111 PngMap sorted_png_map[] = {
112         { "Bumpeq", "bumpeq2" },
113         { "Cap", "cap2" },
114         { "Cup", "cup2" },
115         { "Delta", "delta2" },
116         { "Downarrow", "downarrow2" },
117         { "Gamma", "gamma2" },
118         { "Lambda", "lambda2" },
119         { "Leftarrow", "leftarrow2" },
120         { "Leftrightarrow", "leftrightarrow2" },
121         { "Longleftarrow", "longleftarrow2" },
122         { "Longleftrightarrow", "longleftrightarrow2" },
123         { "Longrightarrow", "longrightarrow2" },
124         { "Omega", "omega2" },
125         { "Phi", "phi2" },
126         { "Pi", "pi2" },
127         { "Psi", "psi2" },
128         { "Rightarrow", "rightarrow2" },
129         { "Sigma", "sigma2" },
130         { "Subset", "subset2" },
131         { "Supset", "supset2" },
132         { "Theta", "theta2" },
133         { "Uparrow", "uparrow2" },
134         { "Updownarrow", "updownarrow2" },
135         { "Upsilon", "upsilon2" },
136         { "Vdash", "vdash3" },
137         { "Xi", "xi2" },
138         { "nLeftarrow", "nleftarrow2" },
139         { "nLeftrightarrow", "nleftrightarrow2" },
140         { "nRightarrow", "nrightarrow2" },
141         { "nVDash", "nvdash3" },
142         { "nvDash", "nvdash2" },
143         { "textrm \\AA", "textrm_AA"},
144         { "textrm \\O", "textrm_O"},
145         { "vDash", "vdash2" },
146         { "Vert", "vert2" }
147 };
148
149 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
150
151
152 QString findPng(QString const & name)
153 {
154         PngMap const * const begin = sorted_png_map;
155         PngMap const * const end = begin + nr_sorted_png_map;
156         BOOST_ASSERT(sorted(begin, end));
157
158         PngMap const * const it = find_if(begin, end, CompareKey(name));
159
160         QString png_name;
161         if (it != end) {
162                 png_name = it->value;
163         } else {
164                 png_name = name;
165                 png_name.replace('_', "underscore");
166                 png_name.replace(' ', '_');
167
168                 // This way we can have "math-delim { }" on the toolbar.
169                 png_name.replace('(', "lparen");
170                 png_name.replace(')', "rparen");
171                 png_name.replace('[', "lbracket");
172                 png_name.replace(']', "rbracket");
173                 png_name.replace('{', "lbrace");
174                 png_name.replace('}', "rbrace");
175                 png_name.replace('|', "bars");
176                 png_name.replace(',', "thinspace");
177                 png_name.replace(':', "mediumspace");
178                 png_name.replace(';', "thickspace");
179                 png_name.replace('!', "negthinspace");
180         }
181
182         LYXERR(Debug::GUI, "findPng(" << fromqstr(name) << ")\n"
183                 << "Looking for math PNG called \"" << fromqstr(png_name) << '"');
184         return png_name;
185 }
186
187 } // namespace anon
188
189
190 /// return a icon for the given action
191 static QIcon getIcon(FuncRequest const & f, bool unknown)
192 {
193         initializeResources();
194         QPixmap pm;
195         QString name1;
196         QString name2;
197         QString path;
198         switch (f.action) {
199         case LFUN_MATH_INSERT:
200                 if (!f.argument().empty()) {
201                         path = "math/";
202                         name1 = findPng(toqstr(f.argument()).mid(1));
203                 }
204                 break;
205         case LFUN_MATH_DELIM:
206         case LFUN_MATH_BIGDELIM:
207                 path = "math/";
208                 name1 = findPng(toqstr(f.argument()));
209                 break;
210         case LFUN_CALL:
211                 path = "commands/";
212                 name1 = toqstr(f.argument());
213                 break;
214         default:
215                 name2 = toqstr(lyxaction.getActionName(f.action));
216                 name1 = name2;
217
218                 if (!f.argument().empty()) {
219                         name1 = name2 + ' ' + toqstr(f.argument());
220                         name1.replace(' ', '_');
221                 }
222         }
223
224         string fullname = libFileSearch("images/" + path, name1, "png").absFilename();
225         if (pm.load(toqstr(fullname)))
226                 return pm;
227
228         fullname = libFileSearch("images/" + path, name2, "png").absFilename();
229         if (pm.load(toqstr(fullname)))
230                 return pm;
231
232         if (pm.load(":/images/" + path + name1 + ".png"))
233                 return pm;
234
235         if (pm.load(":/images/" + path + name2 + ".png"))
236                 return pm;
237
238         LYXERR(Debug::GUI, "Cannot find icon for command \""
239                            << lyxaction.getActionName(f.action)
240                            << '(' << to_utf8(f.argument()) << ")\"");
241         if (unknown)
242                 pm.load(":/images/unknown.png");
243
244         return pm;
245 }
246
247
248 /////////////////////////////////////////////////////////////////////
249 //
250 // GuiLayoutBox
251 //
252 /////////////////////////////////////////////////////////////////////
253
254 class LayoutItemDelegate : public QItemDelegate {
255 public:
256         ///
257         explicit LayoutItemDelegate(QObject * parent = 0)
258                 : QItemDelegate(parent)
259         {}
260         
261         ///
262         void paint(QPainter * painter, QStyleOptionViewItem const & option,
263                 QModelIndex const & index) const
264         {
265                 QStyleOptionViewItem opt = option;
266                 
267                 // default background
268                 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
269                 
270                 // category header?
271                 if (lyxrc.group_layouts) {
272                         QSortFilterProxyModel const * model
273                         = static_cast<QSortFilterProxyModel const *>(index.model());
274                         
275                         QString stdCat = category(*model->sourceModel(), 0);
276                         QString cat = category(*index.model(), index.row());
277                         
278                         // not the standard layout and not the same as in the previous line?
279                         if (stdCat != cat
280                             && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
281                                 painter->save();
282                                 
283                                 // draw unselected background
284                                 QStyle::State state = opt.state;
285                                 opt.state = opt.state & ~QStyle::State_Selected;
286                                 drawBackground(painter, opt, index);
287                                 opt.state = state;
288                                 
289                                 // draw category header
290                                 drawCategoryHeader(painter, opt, 
291                                         category(*index.model(), index.row()));
292
293                                 // move rect down below header
294                                 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
295                                 
296                                 painter->restore();
297                         }
298                 }
299
300                 QItemDelegate::paint(painter, opt, index);
301         }
302         
303         ///
304         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
305                          const QRect & /*rect*/, const QString & text ) const
306         {
307                 QString utext = underlineFilter(text);
308
309                 // Draw the rich text.
310                 painter->save();
311                 QColor col = opt.palette.text().color();
312                 if (opt.state & QStyle::State_Selected)
313                         col = opt.palette.highlightedText().color();
314                 QAbstractTextDocumentLayout::PaintContext context;
315                 context.palette.setColor(QPalette::Text, col);
316                 
317                 QTextDocument doc;
318                 doc.setDefaultFont(opt.font);
319                 doc.setHtml(utext);
320                 
321                 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
322                 fmt.setMargin(0);
323                 doc.rootFrame()->setFrameFormat(fmt);
324                 
325                 painter->translate(opt.rect.x() + 5,
326                         opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
327                 doc.documentLayout()->draw(painter, context);
328                 painter->restore();
329         }
330         
331         ///
332         QSize sizeHint(QStyleOptionViewItem const & opt,
333                 QModelIndex const & index) const
334         {
335                 GuiLayoutBox * combo = static_cast<GuiLayoutBox *>(parent());
336                 QSortFilterProxyModel const * model
337                 = static_cast<QSortFilterProxyModel const *>(index.model());    
338                 QSize size = QItemDelegate::sizeHint(opt, index);
339                 
340                 /// QComboBox uses the first row height to estimate the
341                 /// complete popup height during QComboBox::showPopup().
342                 /// To avoid scrolling we have to sneak in space for the headers.
343                 /// So we tweak this value accordingly. It's not nice, but the
344                 /// only possible way it seems.
345                 if (lyxrc.group_layouts && index.row() == 0 && combo->inShowPopup_) {
346                         int itemHeight = size.height();
347                         
348                         // we have to show \c cats many headers:
349                         unsigned cats = combo->visibleCategories_;
350                         
351                         // and we have \c n items to distribute the needed space over
352                         unsigned n = combo->model()->rowCount();
353                         
354                         // so the needed average height (rounded upwards) is:
355                         size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n); 
356                         return size;
357                 }
358
359                 // Add space for the category headers here?
360                 // Not for the standard layout though.
361                 QString stdCat = category(*model->sourceModel(), 0);
362                 QString cat = category(*index.model(), index.row());
363                 if (lyxrc.group_layouts && stdCat != cat
364                     && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
365                         size.setHeight(size.height() + headerHeight(opt));
366                 }
367
368                 return size;
369         }
370         
371 private:
372         ///
373         QString category(QAbstractItemModel const & model, int row) const
374         {
375                 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
376         }
377                 
378         ///
379         int headerHeight(QStyleOptionViewItem const & opt) const
380         {
381                 return opt.fontMetrics.height() * 8 / 10;
382         }
383         ///
384         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
385                 QString const & category) const
386         {
387                 // slightly blended color
388                 QColor lcol = opt.palette.text().color();
389                 lcol.setAlpha(127);
390                 painter->setPen(lcol);
391                 
392                 // set 80% scaled, bold font
393                 QFont font = opt.font;
394                 font.setBold(true);
395                 font.setWeight(QFont::Black);
396                 font.setPointSize(opt.font.pointSize() * 8 / 10);
397                 painter->setFont(font);
398                 
399                 // draw the centered text
400                 QFontMetrics fm(font);
401                 int w = fm.width(category);
402                 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
403                 int y = opt.rect.y() + fm.ascent();
404                 int left = x;
405                 int right = x + w;
406                 painter->drawText(x, y, category);
407                 
408                 // the vertical position of the line: middle of lower case chars
409                 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
410                 
411                 // draw the horizontal line
412                 if (!category.isEmpty()) {
413                         painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
414                         painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
415                 } else
416                         painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
417         }
418
419         
420         ///
421         QString underlineFilter(QString const & s) const
422         {
423                 // get filter
424                 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
425                 QString const & f = p->filter();
426                 if (f.isEmpty())
427                         return s;
428                 
429                 // step through data item and put "(x)" for every matching character
430                 QString r;
431                 int lastp = -1;
432                 p->filter();
433                 for (int i = 0; i < f.length(); ++i) {
434                         int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
435                         BOOST_ASSERT(p != -1);
436                         if (lastp == p - 1 && lastp != -1) {
437                                 // remove ")" and append "x)"
438                                 r = r.left(r.length() - 4) + s[p] + "</u>";
439                         } else {
440                                 // append "(x)"
441                                 r += s.mid(lastp + 1, p - lastp - 1);
442                                 r += QString("<u>") + s[p] + "</u>";
443                         }
444                         lastp = p;
445                 }
446                 r += s.mid(lastp + 1);
447                 return r;
448         }
449 };
450
451
452 class GuiLayoutFilterModel : public QSortFilterProxyModel {
453 public:
454         ///
455         GuiLayoutFilterModel(QObject * parent = 0)
456                 : QSortFilterProxyModel(parent)
457         {}
458         
459         ///
460         void triggerLayoutChange()
461         {
462                 layoutAboutToBeChanged();
463                 layoutChanged();
464         }
465 };
466
467
468 GuiLayoutBox::GuiLayoutBox(GuiToolbar * bar, GuiView & owner)
469         : owner_(owner), bar_(bar), lastSel_(-1),
470           layoutItemDelegate_(new LayoutItemDelegate(this)),
471           visibleCategories_(0), inShowPopup_(false)
472 {
473         setSizeAdjustPolicy(QComboBox::AdjustToContents);
474         setFocusPolicy(Qt::ClickFocus);
475         setMinimumWidth(sizeHint().width());
476         setMaxVisibleItems(100);
477
478         // set the layout model with two columns
479         // 1st: translated layout names
480         // 2nd: raw layout names
481         model_ = new QStandardItemModel(0, 2, this);
482         filterModel_ = new GuiLayoutFilterModel(this);
483         filterModel_->setSourceModel(model_);
484         setModel(filterModel_);
485
486         // for the filtering we have to intercept characters
487         view()->installEventFilter(this);
488         view()->setItemDelegateForColumn(0, layoutItemDelegate_);
489         
490         QObject::connect(this, SIGNAL(activated(int)),
491                 this, SLOT(selected(int)));
492         QObject::connect(bar_, SIGNAL(iconSizeChanged(QSize)),
493                 this, SLOT(setIconSize(QSize)));
494
495         owner_.setLayoutDialog(this);
496         updateContents(true);
497 }
498
499
500 void GuiLayoutBox::setFilter(QString const & s)
501 {
502         bool enabled = view()->updatesEnabled();
503         view()->setUpdatesEnabled(false);
504
505         // remember old selection
506         int sel = currentIndex();
507         if (sel != -1)
508                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
509
510         filter_ = s;
511         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
512         countCategories();
513         
514         // restore old selection
515         if (lastSel_ != -1) {
516                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
517                 if (i.isValid())
518                         setCurrentIndex(i.row());
519         }
520         
521         // Workaround to resize to content size
522         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
523         //        does not help.
524         if (view()->isVisible()) {
525                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
526                 // the hack in the item delegate to make space for the headers.
527                 // We do not call our implementation of showPopup because that
528                 // would reset the filter again. This is only needed if the user clicks
529                 // on the QComboBox.
530                 BOOST_ASSERT(!inShowPopup_);
531                 inShowPopup_ = true;
532                 QComboBox::showPopup();
533                 inShowPopup_ = false;
534
535                 // The item delegate hack is off again. So trigger a relayout of the popup.
536                 filterModel_->triggerLayoutChange();
537                 
538                 if (!s.isEmpty())
539                         owner_.message(_("Filtering layouts with \"" + fromqstr(s) + "\". "
540                                          "Press ESC to remove filter."));
541                 else
542                         owner_.message(_("Enter characters to filter the layout list."));
543         }
544         
545         view()->setUpdatesEnabled(enabled);
546 }
547
548
549 void GuiLayoutBox::countCategories()
550 {
551         int n = filterModel_->rowCount();
552         visibleCategories_ = 0;
553         if (n == 0 || !lyxrc.group_layouts)
554                 return;
555
556         // skip the "Standard" category
557         QString prevCat = model_->index(0, 2).data().toString(); 
558
559         // count categories
560         for (int i = 0; i < n; ++i) {
561                 QString cat = filterModel_->index(i, 2).data().toString();
562                 if (cat != prevCat)
563                         ++visibleCategories_;
564                 prevCat = cat;
565         }
566 }
567
568
569 QString GuiLayoutBox::charFilterRegExp(QString const & filter)
570 {
571         QString re;
572         for (int i = 0; i < filter.length(); ++i) {
573                 QChar c = filter[i];
574                 if (c.isLower())
575                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
576                 else
577                         re += ".*" + QRegExp::escape(c);
578         }
579         return re;
580 }
581
582
583 void GuiLayoutBox::resetFilter()
584 {
585         setFilter(QString());
586 }
587
588
589 void GuiLayoutBox::showPopup()
590 {
591         owner_.message(_("Enter characters to filter the layout list."));
592
593         bool enabled = view()->updatesEnabled();
594         view()->setUpdatesEnabled(false);
595
596         resetFilter();
597
598         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
599         // the hack in the item delegate to make space for the headers.
600         BOOST_ASSERT(!inShowPopup_);
601         inShowPopup_ = true;
602         QComboBox::showPopup();
603         inShowPopup_ = false;
604         
605         // The item delegate hack is off again. So trigger a relayout of the popup.
606         filterModel_->triggerLayoutChange();
607         
608         view()->setUpdatesEnabled(enabled);
609 }
610
611
612 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
613 {
614         if (e->type() != QEvent::KeyPress)
615                 return QComboBox::eventFilter(o, e);
616
617         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
618         bool modified = (ke->modifiers() == Qt::ControlModifier)
619                 || (ke->modifiers() == Qt::AltModifier)
620                 || (ke->modifiers() == Qt::MetaModifier);
621         
622         switch (ke->key()) {
623         case Qt::Key_Escape:
624                 if (!modified && !filter_.isEmpty()) {
625                         resetFilter();
626                         return true;
627                 }
628                 break;
629         case Qt::Key_Backspace:
630                 if (!modified) {
631                         // cut off one character
632                         setFilter(filter_.left(filter_.length() - 1));
633                 }
634                 break;
635         default:
636                 if (modified || ke->text().isEmpty())
637                         break;
638                 // find chars for the filter string
639                 QString s;
640                 for (int i = 0; i < ke->text().length(); ++i) {
641                         QChar c = ke->text()[i];
642                         if (c.isLetterOrNumber()
643                             || c.isSymbol()
644                             || c.isPunct()
645                             || c.category() == QChar::Separator_Space) {
646                                 s += c;
647                         }
648                 }
649                 if (!s.isEmpty()) {
650                         // append new chars to the filter string
651                         setFilter(filter_ + s);
652                         return true;
653                 }
654                 break;
655         }
656
657         return QComboBox::eventFilter(o, e);
658 }
659
660         
661 void GuiLayoutBox::setIconSize(QSize size)
662 {
663 #ifdef Q_WS_MACX
664         bool small = size.height() < 20;
665         setAttribute(Qt::WA_MacSmallSize, small);
666         setAttribute(Qt::WA_MacNormalSize, !small);
667 #endif
668 }
669
670
671 void GuiLayoutBox::set(docstring const & layout)
672 {
673         resetFilter();
674         
675         if (!text_class_)
676                 return;
677
678         QString const & name = toqstr((*text_class_)[layout].name());
679         if (name == currentText())
680                 return;
681
682         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
683         if (r.empty()) {
684                 lyxerr << "Trying to select non existent layout type "
685                         << fromqstr(name) << endl;
686                 return;
687         }
688
689         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
690 }
691
692
693 void GuiLayoutBox::addItemSort(docstring const & item, docstring const & category,
694         bool sorted, bool sortedByCat)
695 {
696         QString qitem = toqstr(item);
697         QString titem = toqstr(translateIfPossible(item));
698         QString qcat = toqstr(translateIfPossible(category));
699
700         QList<QStandardItem *> row;
701         row.append(new QStandardItem(titem));
702         row.append(new QStandardItem(qitem));
703         row.append(new QStandardItem(qcat));
704
705         // the first entry is easy
706         int const end = model_->rowCount();
707         if (end == 0) {
708                 model_->appendRow(row);
709                 return;
710         }
711
712         // find category
713         int i = 0;
714         if (sortedByCat) {
715                 while (i < end && model_->item(i, 2)->text() != qcat)
716                         ++i;
717         }
718
719         // skip the Standard layout
720         if (i == 0)
721                 ++i;
722         
723         // the simple unsorted case
724         if (!sorted) {
725                 if (sortedByCat) {
726                         // jump to the end of the category group
727                         while (i < end && model_->item(i, 2)->text() == qcat)
728                                 ++i;
729                         model_->insertRow(i, row);
730                 } else
731                         model_->appendRow(row);
732                 return;
733         }
734
735         // find row to insert the item, after the separator if it exists
736         if (i < end) {
737                 // find alphabetic position
738                 while (i != end
739                        && model_->item(i, 0)->text().compare(titem) < 0 
740                        && (!sortedByCat || model_->item(i, 2)->text() == qcat))
741                         ++i;
742         }
743
744         model_->insertRow(i, row);
745 }
746
747
748 void GuiLayoutBox::updateContents(bool reset)
749 {
750         resetFilter();
751         
752         Buffer const * buffer = owner_.buffer();
753         if (!buffer) {
754                 model_->clear();
755                 setEnabled(false);
756                 text_class_ = 0;
757                 inset_ = 0;
758                 return;
759         }
760
761         // we'll only update the layout list if the text class has changed
762         // or we've moved from one inset to another
763         DocumentClass const * text_class = &buffer->params().documentClass();
764         Inset const * inset = 
765                 owner_.view()->cursor().innerParagraph().inInset();
766         if (!reset && text_class_ == text_class && inset_ == inset) {
767                 set(owner_.view()->cursor().innerParagraph().layout().name());
768                 return;
769         }
770
771         inset_ = inset;
772         text_class_ = text_class;
773
774         model_->clear();
775         DocumentClass::const_iterator lit = text_class_->begin();
776         DocumentClass::const_iterator len = text_class_->end();
777
778         for (; lit != len; ++lit) {
779                 docstring const & name = lit->name();
780                 bool const useEmpty = inset_->forceEmptyLayout() || inset_->useEmptyLayout();
781                 // if this inset requires the empty layout, we skip the default
782                 // layout
783                 if (name == text_class_->defaultLayoutName() && inset_ && useEmpty)
784                         continue;
785                 // if it doesn't require the empty layout, we skip it
786                 if (name == text_class_->emptyLayoutName() && inset_ && !useEmpty)
787                         continue;
788                 addItemSort(name, lit->category(), lyxrc.sort_layouts, lyxrc.group_layouts);
789         }
790
791         set(owner_.view()->cursor().innerParagraph().layout().name());
792         countCategories();
793         
794         // needed to recalculate size hint
795         hide();
796         setMinimumWidth(sizeHint().width());
797         setEnabled(!buffer->isReadonly());
798         show();
799 }
800
801
802 void GuiLayoutBox::selected(int index)
803 {
804         // get selection
805         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
806         docstring const layoutName = 
807                 qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
808
809         owner_.setFocus();
810
811         if (!text_class_) {
812                 updateContents(false);
813                 resetFilter();
814                 return;
815         }
816
817         // find corresponding text class
818         if (text_class_->hasLayout(layoutName)) {
819                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
820                 theLyXFunc().setLyXView(&owner_);
821                 lyx::dispatch(func);
822                 updateContents(false);
823                 resetFilter();
824                 return;
825         }
826         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
827 }
828
829
830
831 /////////////////////////////////////////////////////////////////////
832 //
833 // GuiToolbar
834 //
835 /////////////////////////////////////////////////////////////////////
836
837
838 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
839         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
840           layout_(0), command_buffer_(0)
841 {
842         // give visual separation between adjacent toolbars
843         addSeparator();
844
845         // TODO: save toolbar position
846         setMovable(true);
847
848         ToolbarInfo::item_iterator it = tbinfo.items.begin();
849         ToolbarInfo::item_iterator end = tbinfo.items.end();
850         for (; it != end; ++it)
851                 add(*it);
852 }
853
854
855 Action * GuiToolbar::addItem(ToolbarItem const & item)
856 {
857         Action * act = new Action(&owner_, getIcon(item.func_, false),
858                 toqstr(item.label_), item.func_, toqstr(item.label_), this);
859         actions_.append(act);
860         return act;
861 }
862
863 namespace {
864
865 class PaletteButton : public QToolButton
866 {
867 private:
868         GuiToolbar * bar_;
869         ToolbarItem const & tbitem_;
870         bool initialized_;
871 public:
872         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
873                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
874         {
875                 QString const label = qt_(to_ascii(tbitem_.label_));
876                 setToolTip(label);
877                 setStatusTip(label);
878                 setText(label);
879                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
880                         this, SLOT(setIconSize(QSize)));
881                 setCheckable(true);
882                 ToolbarInfo const * tbinfo = 
883                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
884                 if (tbinfo)
885                         // use the icon of first action for the toolbar button
886                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
887         }
888
889         void mousePressEvent(QMouseEvent * e)
890         {
891                 if (initialized_) {
892                         QToolButton::mousePressEvent(e);
893                         return;
894                 }
895
896                 initialized_ = true;
897
898                 ToolbarInfo const * tbinfo = 
899                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
900                 if (!tbinfo) {
901                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
902                         return;
903                 }
904                 IconPalette * panel = new IconPalette(this);
905                 QString const label = qt_(to_ascii(tbitem_.label_));
906                 panel->setWindowTitle(label);
907                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
908                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
909                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
910                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
911                 for (; it != end; ++it)
912                         if (!getStatus(it->func_).unknown())
913                                 panel->addButton(bar_->addItem(*it));
914
915                 QToolButton::mousePressEvent(e);
916         }
917 };
918
919 class MenuButton : public QToolButton
920 {
921 private:
922         GuiToolbar * bar_;
923         ToolbarItem const & tbitem_;
924         bool initialized_;
925 public:
926         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
927                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
928         {
929                 setPopupMode(QToolButton::InstantPopup);
930                 QString const label = qt_(to_ascii(tbitem_.label_));
931                 setToolTip(label);
932                 setStatusTip(label);
933                 setText(label);
934                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
935                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
936                         this, SLOT(setIconSize(QSize)));
937         }
938
939         void mousePressEvent(QMouseEvent * e)
940         {
941                 if (initialized_) {
942                         QToolButton::mousePressEvent(e);
943                         return;
944                 }
945
946                 initialized_ = true;
947
948                 QString const label = qt_(to_ascii(tbitem_.label_));
949                 ButtonMenu * m = new ButtonMenu(label, this);
950                 m->setWindowTitle(label);
951                 m->setTearOffEnabled(true);
952                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
953                 ToolbarInfo const * tbinfo = 
954                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
955                 if (!tbinfo) {
956                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
957                         return;
958                 }
959                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
960                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
961                 for (; it != end; ++it)
962                         if (!getStatus(it->func_).unknown())
963                                 m->add(bar_->addItem(*it));
964                 setMenu(m);
965
966                 QToolButton::mousePressEvent(e);
967         }
968 };
969
970 }
971
972
973 void GuiToolbar::add(ToolbarItem const & item)
974 {
975         switch (item.type_) {
976         case ToolbarItem::SEPARATOR:
977                 addSeparator();
978                 break;
979         case ToolbarItem::LAYOUTS:
980                 layout_ = new GuiLayoutBox(this, owner_);
981                 addWidget(layout_);
982                 break;
983         case ToolbarItem::MINIBUFFER:
984                 command_buffer_ = new GuiCommandBuffer(&owner_);
985                 addWidget(command_buffer_);
986                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
987                 //setHorizontalStretchable(true);
988                 break;
989         case ToolbarItem::TABLEINSERT: {
990                 QToolButton * tb = new QToolButton;
991                 tb->setCheckable(true);
992                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
993                 QString const label = qt_(to_ascii(item.label_));
994                 tb->setToolTip(label);
995                 tb->setStatusTip(label);
996                 tb->setText(label);
997                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
998                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
999                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
1000                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
1001                 addWidget(tb);
1002                 break;
1003                 }
1004         case ToolbarItem::ICONPALETTE:
1005                 addWidget(new PaletteButton(this, item));
1006                 break;
1007
1008         case ToolbarItem::POPUPMENU: {
1009                 addWidget(new MenuButton(this, item));
1010                 break;
1011                 }
1012         case ToolbarItem::COMMAND: {
1013                 if (!getStatus(item.func_).unknown())
1014                         addAction(addItem(item));
1015                 break;
1016                 }
1017         default:
1018                 break;
1019         }
1020 }
1021
1022
1023 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
1024 {
1025         // if tbinfo.state == auto *do not* set on/off
1026         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
1027                 if (GuiToolbar::isVisible())
1028                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
1029                 else
1030                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
1031         }
1032         //
1033         // no need to save it here.
1034         Qt::ToolBarArea loc = owner_.toolBarArea(this);
1035
1036         if (loc == Qt::TopToolBarArea)
1037                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
1038         else if (loc == Qt::BottomToolBarArea)
1039                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
1040         else if (loc == Qt::RightToolBarArea)
1041                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
1042         else if (loc == Qt::LeftToolBarArea)
1043                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
1044         else
1045                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
1046
1047         // save toolbar position. They are not used to restore toolbar position
1048         // now because move(x,y) does not work for toolbar.
1049         tbinfo.posx = pos().x();
1050         tbinfo.posy = pos().y();
1051 }
1052
1053
1054 void GuiToolbar::updateContents()
1055 {
1056         // update visible toolbars only
1057         if (!isVisible())
1058                 return;
1059         // This is a speed bottleneck because this is called on every keypress
1060         // and update calls getStatus, which copies the cursor at least two times
1061         for (int i = 0; i < actions_.size(); ++i)
1062                 actions_[i]->update();
1063
1064         if (layout_)
1065                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
1066
1067         // emit signal
1068         updated();
1069 }
1070
1071
1072 } // namespace frontend
1073 } // namespace lyx
1074
1075 #include "GuiToolbar_moc.cpp"