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