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