]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiToolbar.cpp
Use <cstdint> instead of <boost/cstdint.hpp>
[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 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 "GuiToolbar.h"
19
20 #include "Action.h"
21 #include "Buffer.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "GuiApplication.h"
29 #include "GuiCommandBuffer.h"
30 #include "GuiView.h"
31 #include "IconPalette.h"
32 #include "InsertTableWidget.h"
33 #include "KeyMap.h"
34 #include "LayoutBox.h"
35 #include "LyX.h"
36 #include "LyXRC.h"
37 #include "qt_helpers.h"
38 #include "Session.h"
39 #include "Text.h"
40 #include "TextClass.h"
41 #include "Toolbars.h"
42
43 #include "insets/InsetText.h"
44
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/docstring_list.h"
48 #include "support/gettext.h"
49 #include "support/lstrings.h"
50
51 #include <QSettings>
52 #include <QShowEvent>
53 #include <QString>
54 #include <QToolBar>
55 #include <QToolButton>
56
57 #include "support/lassert.h"
58
59 using namespace std;
60 using namespace lyx::support;
61
62 namespace lyx {
63 namespace frontend {
64
65 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
66         : QToolBar(toqstr(tbinfo.gui_name), &owner), visibility_(0),
67           owner_(owner), command_buffer_(0), tbinfo_(tbinfo), filled_(false),
68           restored_(false)
69 {
70         setIconSize(owner.iconSize());
71         connect(&owner, SIGNAL(iconSizeChanged(QSize)), this,
72                 SLOT(setIconSize(QSize)));
73
74         // This is used by QMainWindow::restoreState for proper main window state
75         // restauration.
76         setObjectName(toqstr(tbinfo.name));
77         restoreSession();
78 }
79
80
81 void GuiToolbar::setVisible(bool visible)
82 {
83         // This is a hack to find out which toolbars have been restored by
84         // MainWindow::restoreState and which toolbars should be initialized
85         // by us (i.e., new toolbars)
86         restored_ = true;
87         QToolBar::setVisible(visible);
88 }
89
90
91 bool GuiToolbar::isRestored() const
92 {
93         return restored_;
94 }
95
96
97 void GuiToolbar::fill()
98 {
99         if (filled_)
100                 return;
101         ToolbarInfo::item_iterator it = tbinfo_.items.begin();
102         ToolbarInfo::item_iterator end = tbinfo_.items.end();
103         for (; it != end; ++it)
104                 add(*it);
105         filled_ = true;
106 }
107
108
109 void GuiToolbar::showEvent(QShowEvent * ev)
110 {
111         fill();
112         ev->accept();
113 }
114
115
116 void GuiToolbar::setVisibility(int visibility)
117 {
118         visibility_ = visibility;
119 }
120
121
122 Action * GuiToolbar::addItem(ToolbarItem const & item)
123 {
124         QString text = toqstr(item.label_);
125         // Get the keys bound to this action, but keep only the
126         // first one later
127         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*item.func_);
128         if (!bindings.empty())
129                 text += " [" + toqstr(bindings.begin()->print(KeySequence::ForGui)) + "]";
130
131         Action * act = new Action(item.func_, getIcon(*item.func_, false), text,
132                                   text, this);
133         actions_.append(act);
134         return act;
135 }
136
137 namespace {
138
139 class PaletteButton : public QToolButton
140 {
141 private:
142         GuiToolbar * bar_;
143         ToolbarItem const & tbitem_;
144         bool initialized_;
145 public:
146         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
147                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
148         {
149                 QString const label = qt_(to_ascii(tbitem_.label_));
150                 setToolTip(label);
151                 setStatusTip(label);
152                 setText(label);
153                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
154                         this, SLOT(setIconSize(QSize)));
155                 setCheckable(true);
156                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
157                 if (tbinfo)
158                         // use the icon of first action for the toolbar button
159                         setIcon(getIcon(*tbinfo->items.begin()->func_, true));
160         }
161
162         void mousePressEvent(QMouseEvent * e)
163         {
164                 if (initialized_) {
165                         QToolButton::mousePressEvent(e);
166                         return;
167                 }
168
169                 initialized_ = true;
170
171                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
172                 if (!tbinfo) {
173                         LYXERR0("Unknown toolbar " << tbitem_.name_);
174                         return;
175                 }
176                 IconPalette * panel = new IconPalette(this);
177                 QString const label = qt_(to_ascii(tbitem_.label_));
178                 panel->setWindowTitle(label);
179                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
180                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
181                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
182                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
183                 for (; it != end; ++it)
184                         if (!getStatus(*it->func_).unknown())
185                                 panel->addButton(bar_->addItem(*it));
186
187                 QToolButton::mousePressEvent(e);
188         }
189 };
190
191 } // namespace
192
193
194 MenuButtonBase::MenuButtonBase(GuiToolbar * bar, ToolbarItem const & item)
195         : QToolButton(bar), bar_(bar), tbitem_(item)
196 {
197         setPopupMode(QToolButton::InstantPopup);
198         QString const label = qt_(to_ascii(tbitem_.label_));
199         setToolTip(label);
200         setStatusTip(label);
201         setText(label);
202         QString const name = toqstr(tbitem_.name_);
203         QStringList imagedirs;
204         imagedirs << "images/math/" << "images/";
205         for (int i = 0; i < imagedirs.size(); ++i) {
206                 QString imagedir = imagedirs.at(i);
207                 FileName const fname = imageLibFileSearch(imagedir, name, "svgz,png",
208                         theGuiApp()->imageSearchMode());
209                 if (fname.exists()) {
210                         setIcon(QIcon(getPixmap(imagedir, name, "svgz,png")));
211                         break;
212                 }
213         }
214 }
215
216
217 void MenuButtonBase::actionTriggered(QAction * action)
218 {
219         QToolButton::setDefaultAction(action);
220         setPopupMode(QToolButton::DelayedPopup);
221 }
222
223
224 StaticMenuButton::StaticMenuButton(
225     GuiToolbar * bar, ToolbarItem const & item, bool const sticky)
226         : MenuButtonBase(bar, item)
227 {
228         if (sticky)
229                 connect(this, SIGNAL(triggered(QAction *)),
230                         this, SLOT(actionTriggered(QAction *)));
231         connect(bar, SIGNAL(iconSizeChanged(QSize)),
232                 this, SLOT(setIconSize(QSize)));
233         initialize();
234 }
235
236
237 void StaticMenuButton::initialize()
238 {
239         QString const label = qt_(to_ascii(tbitem_.label_));
240         ButtonMenu * m = new ButtonMenu(label, this);
241         m->setWindowTitle(label);
242         m->setTearOffEnabled(true);
243         connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
244         connect(bar_, SIGNAL(updated()), this, SLOT(updateTriggered()));
245         ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
246         if (!tbinfo) {
247                 LYXERR0("Unknown toolbar " << tbitem_.name_);
248                 return;
249         }
250         ToolbarInfo::item_iterator it = tbinfo->items.begin();
251         ToolbarInfo::item_iterator const end = tbinfo->items.end();
252         for (; it != end; ++it)
253                 if (!getStatus(*it->func_).unknown())
254                         m->add(bar_->addItem(*it));
255         setMenu(m);
256 }
257
258
259 void StaticMenuButton::updateTriggered()
260 {
261         if (!menu())
262                 return;
263
264         bool enabled = false;
265         QList<QAction *> acts = menu()->actions();
266         for (int i = 0; i < acts.size(); ++i)
267                 if (acts[i]->isEnabled()) {
268                         enabled = true;
269                         break;
270                 }
271         // Enable the MenuButton if at least one menu item is enabled
272         setEnabled(enabled);
273         // If a disabled item is default, switch to InstantPopup
274         // (this can happen if a user selects e.g. DVI and then
275         // turns non-TeX fonts on)
276         if (defaultAction() && !defaultAction()->isEnabled())
277                 setPopupMode(QToolButton::InstantPopup);
278 }
279
280
281 class DynamicMenuButton::Private
282 {
283         /// noncopyable
284         Private(Private const &);
285         void operator=(Private const &);
286 public:
287         Private() : inset_(0) {}
288         ///
289         DocumentClassConstPtr text_class_;
290         ///
291         InsetText const * inset_;
292 };
293
294
295 DynamicMenuButton::DynamicMenuButton(GuiToolbar * bar, ToolbarItem const & item)
296         : MenuButtonBase(bar, item), d(new Private())
297 {
298         initialize();
299 }
300
301
302 DynamicMenuButton::~DynamicMenuButton() 
303
304         delete d;
305 }
306
307
308 void DynamicMenuButton::initialize()
309 {
310         QString const label = qt_(to_ascii(tbitem_.label_));
311         ButtonMenu * m = new ButtonMenu(label, this);
312         m->setWindowTitle(label);
313         m->setTearOffEnabled(true);
314         connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
315         connect(bar_, SIGNAL(updated()), this, SLOT(updateTriggered()));
316         connect(bar_, SIGNAL(iconSizeChanged(QSize)),
317                 this, SLOT(setIconSize(QSize)));
318         setMenu(m);
319 }
320
321
322 bool DynamicMenuButton::isMenuType(string const & s)
323 {
324         return s == "dynamic-custom-insets"
325                 || s == "dynamic-char-styles"
326                 || s == "textstyle-apply"
327                 || s == "paste";
328 }
329
330
331 void DynamicMenuButton::updateTriggered()
332 {
333         QMenu * m = menu();
334         // the menu should exist by this point
335         // if not, we can at least avoid crashing in release mode
336         LASSERT(m, return);
337         GuiView const & owner = bar_->owner();
338         BufferView const * bv = owner.currentBufferView();
339
340         string const & menutype = tbitem_.name_;
341         if (menutype == "dynamic-custom-insets" || menutype == "dynamic-char-styles") {
342                 if (!bv) {
343                         m->clear();
344                         setEnabled(false);
345                         setMinimumWidth(sizeHint().width());
346                         d->text_class_.reset();
347                         d->inset_ = nullptr;
348                         return;
349                 }
350                 DocumentClassConstPtr text_class =
351                                 bv->buffer().params().documentClassPtr();
352                 InsetText const * inset = &(bv->cursor().innerText()->inset());
353                 // if the text class has changed, then we need to reload the menu
354                 if (d->text_class_ != text_class) {
355                         d->text_class_ = text_class;
356                         // at the moment, we can just call loadFlexInsets, and it will
357                         // handle both types. if there were more types of menus, then we
358                         // might need to have other options.
359                         loadFlexInsets();
360                 }
361                 // remember where we are
362                 d->inset_ = inset;
363                 // note that enabling here might need to be more subtle if there
364                 // were other kinds of menus.
365                 setEnabled(!bv->buffer().isReadonly()
366                            && !m->isEmpty()
367                            && inset->insetAllowed(FLEX_CODE));
368         } else if (menutype == "textstyle-apply") {
369                 m->clear();
370                 setPopupMode(QToolButton::MenuButtonPopup);
371                 if (!bv) {
372                         QToolButton::setIcon(getIcon(FuncRequest(LFUN_TEXTSTYLE_APPLY), false));
373                         setEnabled(false);
374                         return;
375                 }
376                 vector<docstring> ffList = bv->cursor().innerText()->getFreeFonts();
377                 unsigned int i = 0;
378                 Action * default_act = nullptr;
379                 for (auto const & f : ffList) {
380                         FuncRequest func(LFUN_TEXTSTYLE_APPLY, convert<docstring>(i),
381                                          FuncRequest::TOOLBAR);
382                         docstring const lb = char_type('&') + convert<docstring>(i)
383                                 + from_ascii(". ") + f ;
384                         Action * act = new Action(func, QIcon(), toqstr(lb), toqstr(f), this);
385                         m->addAction(act);
386                         // The most recent one is the default
387                         if (i == 0)
388                                 default_act = act;
389                         ++i;
390                 }
391                 // Add item to reset to defaults
392                 Action * reset_act = new Action(FuncRequest(LFUN_FONT_DEFAULT, FuncRequest::TOOLBAR),
393                                                 getIcon(FuncRequest(LFUN_UNDO), false),
394                                                 qt_("&Reset to default"),
395                                                 qt_("Reset all font settings to their defaults"), this);
396                 m->addAction(reset_act);
397                 if (default_act)
398                         QToolButton::setDefaultAction(default_act);
399                 QToolButton::setIcon(getIcon(FuncRequest(LFUN_TEXTSTYLE_APPLY), false));
400                 setEnabled(lyx::getStatus(FuncRequest(LFUN_TEXTSTYLE_APPLY)).enabled()
401                            || lyx::getStatus(FuncRequest(LFUN_FONT_DEFAULT)).enabled());
402         } else if (menutype == "paste") {
403                 m->clear();
404                 setPopupMode(QToolButton::MenuButtonPopup);
405                 Action * default_action = new Action(FuncRequest(LFUN_PASTE),
406                                                      getIcon(FuncRequest(LFUN_PASTE), false),
407                                                      qt_("Paste"), qt_("Paste"), this);
408                 if (!bv) {
409                         setEnabled(false);
410                         QToolButton::setDefaultAction(default_action);
411                         return;
412                 }
413                 docstring_list const sel = cap::availableSelections(&bv->buffer());
414
415                 docstring_list::const_iterator cit = sel.begin();
416                 docstring_list::const_iterator end = sel.end();
417
418                 for (unsigned int index = 0; cit != end; ++cit, ++index) {
419                         docstring const s = *cit;
420                         FuncRequest func(LFUN_PASTE, convert<docstring>(index),
421                                          FuncRequest::TOOLBAR);
422                         docstring const lb = char_type('&') + convert<docstring>(index)
423                                 + from_ascii(". ") + s ;
424                         Action * act = new Action(func, QIcon(), toqstr(lb), toqstr(s), this);
425                         m->addAction(act);
426                 }
427                 QToolButton::setDefaultAction(default_action);
428                 setEnabled(lyx::getStatus(FuncRequest(LFUN_PASTE)).enabled());
429         }
430 }
431
432
433 void DynamicMenuButton::loadFlexInsets()
434 {
435         QMenu * m = menu();
436         m->clear();
437         string const & menutype = tbitem_.name_;
438         InsetLayout::InsetLyXType ftype;
439         if (menutype == "dynamic-custom-insets")
440                 ftype = InsetLayout::CUSTOM;
441         else if (menutype == "dynamic-char-styles")
442                 ftype = InsetLayout::CHARSTYLE;
443         else {
444                 // this should have been taken care of earlier
445                 LASSERT(false, return);
446         }
447
448         TextClass::InsetLayouts const & inset_layouts = 
449                         d->text_class_->insetLayouts();
450         for (auto const & iit : inset_layouts) {
451                 InsetLayout const & il = iit.second;
452                 if (il.lyxtype() != ftype)
453                         continue;
454                 docstring const name = iit.first;
455                 QString const loc_item = toqstr(translateIfPossible(
456                                 prefixIs(name, from_ascii("Flex:")) ? 
457                                 name.substr(5) : name));
458                 FuncRequest func(LFUN_FLEX_INSERT, 
459                                 from_ascii("\"") + name + from_ascii("\""), FuncRequest::TOOLBAR);
460                 Action * act = 
461                                 new Action(func, getIcon(func, false), loc_item, loc_item, this);
462                 m->addAction(act);
463         }
464 }
465
466
467 void GuiToolbar::add(ToolbarItem const & item)
468 {
469         switch (item.type_) {
470         case ToolbarItem::SEPARATOR:
471                 addSeparator();
472                 break;
473         case ToolbarItem::LAYOUTS: {
474                 LayoutBox * layout = owner_.getLayoutDialog();
475                 QObject::connect(this, SIGNAL(iconSizeChanged(QSize)),
476                         layout, SLOT(setIconSize(QSize)));
477                 QAction * action = addWidget(layout);
478                 action->setVisible(true);
479                 break;
480         }
481         case ToolbarItem::MINIBUFFER:
482                 command_buffer_ = new GuiCommandBuffer(&owner_);
483                 addWidget(command_buffer_);
484                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
485                 //setHorizontalStretchable(true);
486                 break;
487         case ToolbarItem::TABLEINSERT: {
488                 QToolButton * tb = new QToolButton;
489                 tb->setCheckable(true);
490                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
491                 QString const label = qt_(to_ascii(item.label_));
492                 tb->setToolTip(label);
493                 tb->setStatusTip(label);
494                 tb->setText(label);
495                 InsertTableWidget * iv = new InsertTableWidget(tb);
496                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
497                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
498                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
499                 addWidget(tb);
500                 break;
501                 }
502         case ToolbarItem::ICONPALETTE:
503                 addWidget(new PaletteButton(this, item));
504                 break;
505         case ToolbarItem::POPUPMENU: {
506                 addWidget(new StaticMenuButton(this, item, false));
507                 break;
508                 }
509         case ToolbarItem::STICKYPOPUPMENU: {
510                 addWidget(new StaticMenuButton(this, item, true));
511                 break;
512                 }
513         case ToolbarItem::DYNAMICMENU: {
514                 // we only handle certain things
515                 if (DynamicMenuButton::isMenuType(item.name_))
516                         addWidget(new DynamicMenuButton(this, item));
517                 else
518                         LYXERR0("Unknown dynamic menu type: " << item.name_);
519                 break;
520         }
521         case ToolbarItem::COMMAND: {
522                 if (!getStatus(*item.func_).unknown())
523                         addAction(addItem(item));
524                 break;
525                 }
526         default:
527                 break;
528         }
529 }
530
531
532 void GuiToolbar::update(int context)
533 {
534         if (visibility_ & Toolbars::AUTO) {
535                 setVisible(visibility_ & context & Toolbars::ALLOWAUTO);
536                 if (isVisible() && commandBuffer() && (context & Toolbars::MINIBUFFER_FOCUS))
537                         commandBuffer()->setFocus();
538         }
539
540         // update visible toolbars only
541         if (!isVisible())
542                 return;
543
544         // This is a speed bottleneck because this is called on every keypress
545         // and update calls getStatus, which copies the cursor at least two times
546         for (int i = 0; i < actions_.size(); ++i)
547                 actions_[i]->update();
548
549         LayoutBox * layout = owner_.getLayoutDialog();
550         if (layout)
551                 layout->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
552
553         // emit signal
554         updated();
555 }
556
557
558 QString GuiToolbar::sessionKey() const
559 {
560         return "views/" + QString::number(owner_.id()) + "/" + objectName();
561 }
562
563
564 void GuiToolbar::saveSession(QSettings & settings) const
565 {
566         settings.setValue(sessionKey() + "/visibility", visibility_);
567         settings.setValue(sessionKey() + "/movability", isMovable());
568 }
569
570
571 void GuiToolbar::restoreSession()
572 {
573         QSettings settings;
574         int const error_val = -1;
575         int visibility =
576                 settings.value(sessionKey() + "/visibility", error_val).toInt();
577         if (visibility == error_val || visibility == 0) {
578                 // This should not happen, but in case we use the defaults
579                 LYXERR(Debug::GUI, "Session settings could not be found! Defaults are used instead.");
580                 visibility =
581                         guiApp->toolbars().defaultVisibility(fromqstr(objectName()));
582         }
583         setVisibility(visibility);
584
585         int movability = settings.value(sessionKey() + "/movability", true).toBool();
586         setMovable(movability);
587 }
588
589
590 void GuiToolbar::toggle()
591 {
592         docstring state;
593         if (visibility_ & Toolbars::ALLOWAUTO) {
594                 if (!(visibility_ & Toolbars::AUTO)) {
595                         visibility_ |= Toolbars::AUTO;
596                         hide();
597                         state = _("auto");
598                 } else {
599                         visibility_ &= ~Toolbars::AUTO;
600                         if (isVisible()) {
601                                 hide();
602                                 state = _("off");
603                         } else {
604                                 show();
605                                 state = _("on");
606                         }
607                 }
608         } else {
609                 if (isVisible()) {
610                         hide();
611                         state = _("off");
612                 } else {
613                         show();
614                         state = _("on");
615                 }
616         }
617
618         owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
619                 qstring_to_ucs4(windowTitle()), state));
620 }
621
622 void GuiToolbar::movable(bool silent)
623 {
624         // toggle movability
625         setMovable(!isMovable());
626
627         // manual update avoids bug in qt that the drag handle is not removed
628         // properly, e.g. in Windows
629         Q_EMIT update();
630
631         // silence for toggling of many toolbars for performance
632         if (!silent) {
633                 docstring state;
634                 if (isMovable())
635                         state = _("movable");
636                 else
637                         state = _("immovable");
638                 owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
639                         qstring_to_ucs4(windowTitle()), state));
640         }
641 }
642
643 } // namespace frontend
644 } // namespace lyx
645
646 #include "moc_GuiToolbar.cpp"