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