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