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