]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
Replace the text class shared ptr by good old index-into-global-list.
[features.git] / src / frontends / qt4 / GuiToolbar.cpp
1 /**
2  * \file qt4/GuiToolbar.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Abdelrazak Younes
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiView.h"
18 #include "GuiCommandBuffer.h"
19 #include "GuiToolbar.h"
20 #include "LyXAction.h"
21 #include "Action.h"
22 #include "qt_helpers.h"
23 #include "InsertTableWidget.h"
24
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Cursor.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "IconPalette.h"
32 #include "Layout.h"
33 #include "LyXFunc.h"
34 #include "LyXRC.h"
35 #include "Paragraph.h"
36 #include "TextClass.h"
37 #include "ToolbarBackend.h"
38
39 #include "support/debug.h"
40 #include "support/filetools.h"
41 #include "support/gettext.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         //FIXME 
273         //Since we are only storing the text used for display, we have no choice
274         //below but to compare translated strings to figure out which layout the
275         //user wants. This is not ideal. A better way is the way module names are 
276         //handled in GuiDocument: viz, the untranslated name can be associated 
277         //with the item via QComboBox::setItemData(). It may be that this can
278         //even be done by passing: addItem(item, untransName).
279         int const end = count();
280         if (!sorted || end < 2 || item[0].category() != QChar::Letter_Uppercase) {
281                 addItem(item);
282                 return;
283         }
284
285         // Let the default one be at the beginning
286         int i = 1;
287         for (setCurrentIndex(i); currentText().localeAwareCompare(item) < 0; ) {
288                 // e.g. --Separator--
289                 if (currentText()[0].category() != QChar::Letter_Uppercase)
290                         break;
291                 if (++i == end)
292                         break;
293                 setCurrentIndex(i);
294         }
295
296         insertItem(i, item);
297 }
298
299
300 void GuiLayoutBox::updateContents(bool reset)
301 {
302         Buffer const * buffer = owner_.buffer();
303         if (!buffer) {
304                 clear();
305                 setEnabled(false);
306                 text_class_ = 0;
307                 inset_ = 0;
308                 return;
309         }
310
311         TextClass const * text_class = &buffer->params().textClass();
312         Inset const * inset = 
313                 owner_.view()->cursor().innerParagraph().inInset();
314
315         // we'll only update the layout list if the text class has changed
316         // or we've moved from one inset to another
317         if (!reset && text_class_ == text_class && inset_ == inset) {
318                 set(owner_.view()->cursor().innerParagraph().layout()->name());
319                 return;
320         }
321
322         inset_ = inset;
323         text_class_ = text_class;
324
325         clear();
326         TextClass::const_iterator it = text_class_->begin();
327         TextClass::const_iterator const end = text_class_->end();
328
329         for (; it != end; ++it) {
330                 docstring const & name = (*it)->name();
331                 // if this inset requires the empty layout, we skip the default
332                 // layout
333                 if (name == text_class_->defaultLayoutName() && inset &&
334                     (inset->forceEmptyLayout() || inset->useEmptyLayout()))
335                         continue;
336                 // if it doesn't require the empty layout, we skip it
337                 if (name == text_class_->emptyLayoutName() && inset &&
338                     !inset->forceEmptyLayout() && !inset->useEmptyLayout())
339                         continue;
340                 addItemSort(toqstr(translateIfPossible(name)), lyxrc.sort_layouts);
341         }
342
343         set(owner_.view()->cursor().innerParagraph().layout()->name());
344
345         // needed to recalculate size hint
346         hide();
347         setMinimumWidth(sizeHint().width());
348
349         setEnabled(!buffer->isReadonly());
350         show();
351 }
352
353
354 void GuiLayoutBox::selected(const QString & str)
355 {
356         owner_.setFocus();
357         updateContents(false);
358         if (!text_class_)
359                 return;
360
361         docstring const name = qstring_to_ucs4(str);
362         TextClass::const_iterator it  = text_class_->begin();
363         TextClass::const_iterator const end = text_class_->end();
364         for (; it != end; ++it) {
365                 docstring const & itname = (*it)->name();
366                 //FIXME Comparing translated strings is not ideal.
367                 //This should be done the way module names are handled
368                 //in GuiDocument: viz, the untranslated name should be
369                 //associated with the item via QComboBox::setItemData().
370                 if (translateIfPossible(itname) == name) {
371                         FuncRequest const func(LFUN_LAYOUT, itname,
372                                                FuncRequest::TOOLBAR);
373                         theLyXFunc().setLyXView(&owner_);
374                         lyx::dispatch(func);
375                         updateContents(false);
376                         return;
377                 }
378         }
379         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
380 }
381
382
383
384 /////////////////////////////////////////////////////////////////////
385 //
386 // GuiToolbar
387 //
388 /////////////////////////////////////////////////////////////////////
389
390
391 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
392         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
393           layout_(0), command_buffer_(0)
394 {
395         // give visual separation between adjacent toolbars
396         addSeparator();
397
398         // TODO: save toolbar position
399         setMovable(true);
400
401         ToolbarInfo::item_iterator it = tbinfo.items.begin();
402         ToolbarInfo::item_iterator end = tbinfo.items.end();
403         for (; it != end; ++it)
404                 add(*it);
405 }
406
407
408 Action * GuiToolbar::addItem(ToolbarItem const & item)
409 {
410         Action * act = new Action(owner_,
411                 getIcon(item.func_, false),
412           toqstr(item.label_), item.func_, toqstr(item.label_));
413         actions_.append(act);
414         return act;
415 }
416
417 namespace {
418
419 class PaletteButton : public QToolButton
420 {
421 private:
422         GuiToolbar * bar_;
423         ToolbarItem const & tbitem_;
424         bool initialized_;
425 public:
426         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
427                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
428         {
429                 QString const label = qt_(to_ascii(tbitem_.label_));
430                 setToolTip(label);
431                 setStatusTip(label);
432                 setText(label);
433                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
434                         this, SLOT(setIconSize(QSize)));
435                 setCheckable(true);
436                 ToolbarInfo const * tbinfo = 
437                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
438                 if (tbinfo)
439                         // use the icon of first action for the toolbar button
440                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
441         }
442
443         void mousePressEvent(QMouseEvent * e)
444         {
445                 if (initialized_) {
446                         QToolButton::mousePressEvent(e);
447                         return;
448                 }
449
450                 initialized_ = true;
451
452                 ToolbarInfo const * tbinfo = 
453                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
454                 if (!tbinfo) {
455                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
456                         return;
457                 }
458                 IconPalette * panel = new IconPalette(this);
459                 QString const label = qt_(to_ascii(tbitem_.label_));
460                 panel->setWindowTitle(label);
461                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
462                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
463                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
464                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
465                 for (; it != end; ++it)
466                         if (!getStatus(it->func_).unknown())
467                                 panel->addButton(bar_->addItem(*it));
468
469                 QToolButton::mousePressEvent(e);
470         }
471 };
472
473 class MenuButton : public QToolButton
474 {
475 private:
476         GuiToolbar * bar_;
477         ToolbarItem const & tbitem_;
478         bool initialized_;
479 public:
480         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
481                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
482         {
483                 setPopupMode(QToolButton::InstantPopup);
484                 QString const label = qt_(to_ascii(tbitem_.label_));
485                 setToolTip(label);
486                 setStatusTip(label);
487                 setText(label);
488                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
489                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
490                         this, SLOT(setIconSize(QSize)));
491         }
492
493         void mousePressEvent(QMouseEvent * e)
494         {
495                 if (initialized_) {
496                         QToolButton::mousePressEvent(e);
497                         return;
498                 }
499
500                 initialized_ = true;
501
502                 QString const label = qt_(to_ascii(tbitem_.label_));
503                 ButtonMenu * m = new ButtonMenu(label, this);
504                 m->setWindowTitle(label);
505                 m->setTearOffEnabled(true);
506                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
507                 ToolbarInfo const * tbinfo = 
508                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
509                 if (!tbinfo) {
510                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
511                         return;
512                 }
513                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
514                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
515                 for (; it != end; ++it)
516                         if (!getStatus(it->func_).unknown())
517                                 m->add(bar_->addItem(*it));
518                 setMenu(m);
519
520                 QToolButton::mousePressEvent(e);
521         }
522 };
523
524 }
525
526
527 void GuiToolbar::add(ToolbarItem const & item)
528 {
529         switch (item.type_) {
530         case ToolbarItem::SEPARATOR:
531                 addSeparator();
532                 break;
533         case ToolbarItem::LAYOUTS:
534                 layout_ = new GuiLayoutBox(owner_);
535                 addWidget(layout_);
536                 break;
537         case ToolbarItem::MINIBUFFER:
538                 command_buffer_ = new GuiCommandBuffer(&owner_);
539                 addWidget(command_buffer_);
540                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
541                 //setHorizontalStretchable(true);
542                 break;
543         case ToolbarItem::TABLEINSERT: {
544                 QToolButton * tb = new QToolButton;
545                 tb->setCheckable(true);
546                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
547                 QString const label = qt_(to_ascii(item.label_));
548                 tb->setToolTip(label);
549                 tb->setStatusTip(label);
550                 tb->setText(label);
551                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
552                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
553                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
554                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
555                 addWidget(tb);
556                 break;
557                 }
558         case ToolbarItem::ICONPALETTE:
559                 addWidget(new PaletteButton(this, item));
560                 break;
561
562         case ToolbarItem::POPUPMENU: {
563                 addWidget(new MenuButton(this, item));
564                 break;
565                 }
566         case ToolbarItem::COMMAND: {
567                 if (!getStatus(item.func_).unknown())
568                         addAction(addItem(item));
569                 break;
570                 }
571         default:
572                 break;
573         }
574 }
575
576
577 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
578 {
579         // if tbinfo.state == auto *do not* set on/off
580         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
581                 if (GuiToolbar::isVisible())
582                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
583                 else
584                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
585         }
586         //
587         // no need to save it here.
588         Qt::ToolBarArea loc = owner_.toolBarArea(this);
589
590         if (loc == Qt::TopToolBarArea)
591                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
592         else if (loc == Qt::BottomToolBarArea)
593                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
594         else if (loc == Qt::RightToolBarArea)
595                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
596         else if (loc == Qt::LeftToolBarArea)
597                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
598         else
599                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
600
601         // save toolbar position. They are not used to restore toolbar position
602         // now because move(x,y) does not work for toolbar.
603         tbinfo.posx = pos().x();
604         tbinfo.posy = pos().y();
605 }
606
607
608 void GuiToolbar::updateContents()
609 {
610         // update visible toolbars only
611         if (!isVisible())
612                 return;
613         // This is a speed bottleneck because this is called on every keypress
614         // and update calls getStatus, which copies the cursor at least two times
615         for (int i = 0; i < actions_.size(); ++i)
616                 actions_[i]->update();
617
618         if (layout_)
619                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
620
621         // emit signal
622         updated();
623 }
624
625
626 } // namespace frontend
627 } // namespace lyx
628
629 #include "GuiToolbar_moc.cpp"