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