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