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