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