]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
Introduce class PaletteButton in order to delay the icon palette initialisation up...
[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 Abdelrazak Younes
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "Cursor.h"
21 #include "support/debug.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "support/gettext.h"
25 #include "IconPalette.h"
26 #include "Layout.h"
27 #include "LyXFunc.h"
28 #include "Paragraph.h"
29 #include "TextClass.h"
30 #include "ToolbarBackend.h"
31
32 #include "GuiView.h"
33 #include "GuiCommandBuffer.h"
34 #include "GuiToolbar.h"
35 #include "LyXAction.h"
36 #include "Action.h"
37 #include "qt_helpers.h"
38 #include "InsertTableWidget.h"
39 #include "LyXRC.h"
40
41 #include "support/filetools.h"
42 #include "support/lstrings.h"
43 #include "support/lyxalgo.h" // sorted
44
45 #include <QComboBox>
46 #include <QToolBar>
47 #include <QToolButton>
48 #include <QAction>
49 #include <QPixmap>
50
51 #include <boost/assert.hpp>
52
53 using namespace std;
54 using namespace lyx::support;
55
56 static void initializeResources()
57 {
58         static bool initialized = false;
59         if (!initialized) {
60                 Q_INIT_RESOURCE(Resources); 
61                 initialized = true;
62         }
63 }
64
65
66 namespace lyx {
67 namespace frontend {
68
69 namespace {
70
71 struct PngMap {
72         char const * key;
73         char const * value;
74 };
75
76
77 bool operator<(PngMap const & lhs, PngMap const & rhs)
78 {
79                 return strcmp(lhs.key, rhs.key) < 0;
80 }
81
82
83 class CompareKey {
84 public:
85         CompareKey(string const & name) : name_(name) {}
86         bool operator()(PngMap const & other) const { return other.key == name_; }
87 private:
88         string const name_;
89 };
90
91
92 PngMap sorted_png_map[] = {
93         { "Bumpeq", "bumpeq2" },
94         { "Cap", "cap2" },
95         { "Cup", "cup2" },
96         { "Delta", "delta2" },
97         { "Downarrow", "downarrow2" },
98         { "Gamma", "gamma2" },
99         { "Lambda", "lambda2" },
100         { "Leftarrow", "leftarrow2" },
101         { "Leftrightarrow", "leftrightarrow2" },
102         { "Longleftarrow", "longleftarrow2" },
103         { "Longleftrightarrow", "longleftrightarrow2" },
104         { "Longrightarrow", "longrightarrow2" },
105         { "Omega", "omega2" },
106         { "Phi", "phi2" },
107         { "Pi", "pi2" },
108         { "Psi", "psi2" },
109         { "Rightarrow", "rightarrow2" },
110         { "Sigma", "sigma2" },
111         { "Subset", "subset2" },
112         { "Supset", "supset2" },
113         { "Theta", "theta2" },
114         { "Uparrow", "uparrow2" },
115         { "Updownarrow", "updownarrow2" },
116         { "Upsilon", "upsilon2" },
117         { "Vdash", "vdash3" },
118         { "Xi", "xi2" },
119         { "nLeftarrow", "nleftarrow2" },
120         { "nLeftrightarrow", "nleftrightarrow2" },
121         { "nRightarrow", "nrightarrow2" },
122         { "nVDash", "nvdash3" },
123         { "nvDash", "nvdash2" },
124         { "textrm \\AA", "textrm_AA"},
125         { "textrm \\O", "textrm_O"},
126         { "vDash", "vdash2" }
127 };
128
129 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
130
131
132 string const find_png(string const & name)
133 {
134         PngMap const * const begin = sorted_png_map;
135         PngMap const * const end = begin + nr_sorted_png_map;
136         BOOST_ASSERT(sorted(begin, end));
137
138         PngMap const * const it = find_if(begin, end, CompareKey(name));
139
140         string png_name;
141         if (it != end)
142                 png_name = it->value;
143         else {
144                 png_name = subst(name, "_", "underscore");
145                 png_name = subst(png_name, ' ', '_');
146
147                 // This way we can have "math-delim { }" on the toolbar.
148                 png_name = subst(png_name, "(", "lparen");
149                 png_name = subst(png_name, ")", "rparen");
150                 png_name = subst(png_name, "[", "lbracket");
151                 png_name = subst(png_name, "]", "rbracket");
152                 png_name = subst(png_name, "{", "lbrace");
153                 png_name = subst(png_name, "}", "rbrace");
154                 png_name = subst(png_name, "|", "bars");
155                 png_name = subst(png_name, ",", "thinspace");
156                 png_name = subst(png_name, ":", "mediumspace");
157                 png_name = subst(png_name, ";", "thickspace");
158                 png_name = subst(png_name, "!", "negthinspace");
159         }
160
161         LYXERR(Debug::GUI, "find_png(" << name << ")\n"
162                 << "Looking for math PNG called \"" << png_name << '"');
163         return png_name;
164 }
165
166 } // namespace anon
167
168
169 /// return a icon for the given action
170 static QIcon getIcon(FuncRequest const & f, bool unknown)
171 {
172         initializeResources();
173         QPixmap pm;
174         string name1;
175         string name2;
176         string path;
177         string fullname;
178
179         switch (f.action) {
180         case LFUN_MATH_INSERT:
181                 if (!f.argument().empty()) {
182                         path = "math/";
183                         name1 = find_png(to_utf8(f.argument()).substr(1));
184                 }
185                 break;
186         case LFUN_MATH_DELIM:
187         case LFUN_MATH_BIGDELIM:
188                 path = "math/";
189                 name1 = find_png(to_utf8(f.argument()));
190                 break;
191         case LFUN_CALL:
192                 path = "commands/";
193                 name1 = to_utf8(f.argument());
194                 break;
195         default:
196                 name2 = lyxaction.getActionName(f.action);
197                 name1 = name2;
198
199                 if (!f.argument().empty())
200                         name1 = subst(name2 + ' ' + to_utf8(f.argument()), ' ', '_');
201         }
202
203         fullname = libFileSearch("images/" + path, name1, "png").absFilename();
204         if (pm.load(toqstr(fullname)))
205                 return pm;
206
207         fullname = libFileSearch("images/" + path, name2, "png").absFilename();
208         if (pm.load(toqstr(fullname)))
209                 return pm;
210
211         if (pm.load(":/images/" + toqstr(path + name1) + ".png"))
212                 return pm;
213
214         if (pm.load(":/images/" + toqstr(path + name2) + ".png"))
215                 return pm;
216
217         LYXERR(Debug::GUI, "Cannot find icon for command \""
218                            << lyxaction.getActionName(f.action)
219                            << '(' << to_utf8(f.argument()) << ")\"");
220         if (unknown)
221                 pm.load(":/images/unknown.png");
222
223         return pm;
224 }
225
226
227 /////////////////////////////////////////////////////////////////////
228 //
229 // GuiLayoutBox
230 //
231 /////////////////////////////////////////////////////////////////////
232
233 GuiLayoutBox::GuiLayoutBox(GuiView & owner)
234         : owner_(owner)
235 {
236         setSizeAdjustPolicy(QComboBox::AdjustToContents);
237         setFocusPolicy(Qt::ClickFocus);
238         setMinimumWidth(sizeHint().width());
239         setMaxVisibleItems(100);
240
241         QObject::connect(this, SIGNAL(activated(QString)),
242                          this, SLOT(selected(QString)));
243         owner_.setLayoutDialog(this);
244         updateContents(true);
245 }
246
247
248 void GuiLayoutBox::set(docstring const & layout)
249 {
250         if (!text_class_)
251                 return;
252
253         QString const & name = toqstr(translateIfPossible(
254                 (*text_class_)[layout]->name()));
255
256         if (name == currentText())
257                 return;
258
259         int i = findText(name);
260         if (i == -1) {
261                 lyxerr << "Trying to select non existent layout type "
262                         << fromqstr(name) << endl;
263                 return;
264         }
265
266         setCurrentIndex(i);
267 }
268
269
270 void GuiLayoutBox::addItemSort(QString const & item, bool sorted)
271 {
272         int const end = count();
273         if (!sorted || end < 2 || item[0].category() != QChar::Letter_Uppercase) {
274                 addItem(item);
275                 return;
276         }
277
278         // Let the default one be at the beginning
279         int i = 1;
280         for (setCurrentIndex(i); currentText() < item;) {
281                 // e.g. --Separator--
282                 if (currentText()[0].category() != QChar::Letter_Uppercase)
283                         break;
284                 if (++i == end)
285                         break;
286                 setCurrentIndex(i);
287         }
288
289         insertItem(i, item);
290 }
291
292
293 void GuiLayoutBox::updateContents(bool reset)
294 {
295         Buffer const * buffer = owner_.buffer();
296         if (!buffer) {
297                 clear();
298                 setEnabled(false);
299                 text_class_ = 0;
300                 return;
301         }
302
303         setEnabled(true);
304         TextClass const * text_class = &buffer->params().getTextClass();
305         if (!reset && text_class_ == text_class) {
306                 set(owner_.view()->cursor().innerParagraph().layout()->name());
307                 return;
308         }
309
310         text_class_ = text_class;
311
312         setUpdatesEnabled(false);
313         clear();
314
315         TextClass::const_iterator it = text_class_->begin();
316         TextClass::const_iterator const end = text_class_->end();
317         for (; it != end; ++it) {
318                 // ignore obsolete entries
319                 addItemSort(toqstr(translateIfPossible((*it)->name())), lyxrc.sort_layouts);
320         }
321
322         setCurrentIndex(0);
323
324         // needed to recalculate size hint
325         hide();
326         setMinimumWidth(sizeHint().width());
327         set(owner_.view()->cursor().innerParagraph().layout()->name());
328         show();
329
330         setUpdatesEnabled(true);
331 }
332
333
334 void GuiLayoutBox::selected(const QString & str)
335 {
336         owner_.setFocus();
337         updateContents(false);
338         if (!text_class_)
339                 return;
340
341         docstring const name = qstring_to_ucs4(str);
342         TextClass::const_iterator it  = text_class_->begin();
343         TextClass::const_iterator const end = text_class_->end();
344         for (; it != end; ++it) {
345                 docstring const & itname = (*it)->name();
346                 if (translateIfPossible(itname) == name) {
347                         FuncRequest const func(LFUN_LAYOUT, itname,
348                                                FuncRequest::TOOLBAR);
349                         theLyXFunc().setLyXView(&owner_);
350                         lyx::dispatch(func);
351                         return;
352                 }
353         }
354         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
355 }
356
357
358
359 /////////////////////////////////////////////////////////////////////
360 //
361 // GuiToolbar
362 //
363 /////////////////////////////////////////////////////////////////////
364
365
366 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
367         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
368           layout_(0), command_buffer_(0)
369 {
370         // give visual separation between adjacent toolbars
371         addSeparator();
372
373         // TODO: save toolbar position
374         setMovable(true);
375
376         ToolbarInfo::item_iterator it = tbinfo.items.begin();
377         ToolbarInfo::item_iterator end = tbinfo.items.end();
378         for (; it != end; ++it)
379                 add(*it);
380 }
381
382
383 Action * GuiToolbar::addItem(ToolbarItem const & item)
384 {
385         Action * act = new Action(owner_,
386                 getIcon(item.func_, false),
387           toqstr(item.label_), item.func_, toqstr(item.label_));
388         actions_.append(act);
389         return act;
390 }
391
392 namespace {
393
394 class PaletteButton : public QToolButton
395 {
396 private:
397         GuiToolbar * bar_;
398         ToolbarItem const & tbitem_;
399         IconPalette * panel_;
400         bool initialized_;
401 public:
402         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
403                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
404         {
405                 setToolTip(qt_(to_ascii(tbitem_.label_)));
406                 setStatusTip(qt_(to_ascii(tbitem_.label_)));
407                 setText(qt_(to_ascii(tbitem_.label_)));
408                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
409                         this, SLOT(setIconSize(QSize)));
410                 panel_ = new IconPalette(this);
411                 panel_->setWindowTitle(qt_(to_ascii(tbitem_.label_)));
412                 connect(bar_, SIGNAL(updated()), panel_, SLOT(updateParent()));
413                 setCheckable(true);
414                 connect(this, SIGNAL(clicked(bool)), panel_, SLOT(setVisible(bool)));
415                 connect(panel_, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
416         }
417
418         void showEvent(QShowEvent * e)
419         {
420                 if (initialized_) {
421                         QToolButton::showEvent(e);
422                         return;
423                 }
424
425                 initialized_ = true;
426
427                 ToolbarInfo const * tbinfo = 
428                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
429                 if (!tbinfo) {
430                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
431                         return;
432                 }
433                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
434                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
435                 for (; it != end; ++it) {
436                         if (!getStatus(it->func_).unknown()) {
437                                 panel_->addButton(bar_->addItem(*it));
438                                 // use the icon of first action for the toolbar button
439                                 if (it == tbinfo->items.begin())
440                                         setIcon(getIcon(it->func_, true));
441                         }
442                 }
443                 QToolButton::showEvent(e);
444         }
445 };
446
447 }
448
449 void GuiToolbar::add(ToolbarItem const & item)
450 {
451         switch (item.type_) {
452         case ToolbarItem::SEPARATOR:
453                 addSeparator();
454                 break;
455         case ToolbarItem::LAYOUTS:
456                 layout_ = new GuiLayoutBox(owner_);
457                 addWidget(layout_);
458                 break;
459         case ToolbarItem::MINIBUFFER:
460                 command_buffer_ = new GuiCommandBuffer(&owner_);
461                 addWidget(command_buffer_);
462                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
463                 //setHorizontalStretchable(true);
464                 break;
465         case ToolbarItem::TABLEINSERT: {
466                 QToolButton * tb = new QToolButton;
467                 tb->setCheckable(true);
468                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
469                 tb->setToolTip(qt_(to_ascii(item.label_)));
470                 tb->setStatusTip(qt_(to_ascii(item.label_)));
471                 tb->setText(qt_(to_ascii(item.label_)));
472                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
473                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
474                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
475                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
476                 addWidget(tb);
477                 break;
478                 }
479         case ToolbarItem::ICONPALETTE:
480                 addWidget(new PaletteButton(this, item));
481                 break;
482
483         case ToolbarItem::POPUPMENU: {
484                 QToolButton * tb = new QToolButton;
485                 tb->setPopupMode(QToolButton::InstantPopup);
486                 tb->setToolTip(qt_(to_ascii(item.label_)));
487                 tb->setStatusTip(qt_(to_ascii(item.label_)));
488                 tb->setText(qt_(to_ascii(item.label_)));
489                 tb->setIcon(QPixmap(":images/math/" + toqstr(item.name_) + ".png"));
490                 connect(this, SIGNAL(iconSizeChanged(QSize)),
491                         tb, SLOT(setIconSize(QSize)));
492
493                 ButtonMenu * m = new ButtonMenu(qt_(to_ascii(item.label_)), tb);
494                 m->setWindowTitle(qt_(to_ascii(item.label_)));
495                 m->setTearOffEnabled(true);
496                 connect(this, SIGNAL(updated()), m, SLOT(updateParent()));
497                 ToolbarInfo const * tbinfo = toolbarbackend.getDefinedToolbarInfo(item.name_);
498                 if (!tbinfo) {
499                         lyxerr << "Unknown toolbar " << item.name_ << endl;
500                         break;
501                 }
502                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
503                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
504                 for (; it != end; ++it)
505                         if (!getStatus(it->func_).unknown())
506                                 m->add(addItem(*it));
507                 tb->setMenu(m);
508                 addWidget(tb);
509                 break;
510                 }
511         case ToolbarItem::COMMAND: {
512                 if (!getStatus(item.func_).unknown())
513                         addAction(addItem(item));
514                 break;
515                 }
516         default:
517                 break;
518         }
519 }
520
521
522 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
523 {
524         // if tbinfo.state == auto *do not* set on/off
525         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
526                 if (GuiToolbar::isVisible())
527                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
528                 else
529                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
530         }
531         //
532         // no need to save it here.
533         Qt::ToolBarArea loc = owner_.toolBarArea(this);
534
535         if (loc == Qt::TopToolBarArea)
536                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
537         else if (loc == Qt::BottomToolBarArea)
538                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
539         else if (loc == Qt::RightToolBarArea)
540                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
541         else if (loc == Qt::LeftToolBarArea)
542                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
543         else
544                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
545
546         // save toolbar position. They are not used to restore toolbar position
547         // now because move(x,y) does not work for toolbar.
548         tbinfo.posx = pos().x();
549         tbinfo.posy = pos().y();
550 }
551
552
553 void GuiToolbar::updateContents()
554 {
555         // update visible toolbars only
556         if (!isVisible())
557                 return;
558         // This is a speed bottleneck because this is called on every keypress
559         // and update calls getStatus, which copies the cursor at least two times
560         for (int i = 0; i < actions_.size(); ++i)
561                 actions_[i]->update();
562
563         if (layout_)
564                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
565
566         // emit signal
567         updated();
568 }
569
570
571 } // namespace frontend
572 } // namespace lyx
573
574 #include "GuiToolbar_moc.cpp"