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