]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiToolbar.cpp
39e4812276bfc1ab3de46ab053ea0ef293951891
[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         if (!bv) {
340                 m->clear();
341                 setEnabled(false);
342                 setMinimumWidth(sizeHint().width());
343                 d->text_class_.reset();
344                 d->inset_ = nullptr;
345                 return;
346         }
347
348         string const & menutype = tbitem_.name_;
349         if (menutype == "dynamic-custom-insets" || menutype == "dynamic-char-styles") {
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                 vector<docstring> ffList = bv->cursor().innerText()->getFreeFonts();
371                 unsigned int i = 0;
372                 Action * default_act = nullptr;
373                 for (auto const & f : ffList) {
374                         FuncRequest func(LFUN_TEXTSTYLE_APPLY, convert<docstring>(i),
375                                          FuncRequest::TOOLBAR);
376                         docstring const lb = char_type('&') + convert<docstring>(i)
377                                 + from_ascii(". ") + f ;
378                         Action * act = new Action(func, QIcon(), toqstr(lb), toqstr(f), this);
379                         m->addAction(act);
380                         // The most recent one is the default
381                         if (i == 0)
382                                 default_act = act;
383                         ++i;
384                 }
385                 // Add item to reset to defaults
386                 Action * reset_act = new Action(FuncRequest(LFUN_FONT_DEFAULT, FuncRequest::TOOLBAR),
387                                                 getIcon(FuncRequest(LFUN_UNDO), false),
388                                                 qt_("&Reset to default"),
389                                                 qt_("Reset all font settings to their defaults"), this);
390                 m->addAction(reset_act);
391                 if (default_act)
392                         QToolButton::setDefaultAction(default_act);
393
394                 QToolButton::setIcon(getIcon(FuncRequest(LFUN_TEXTSTYLE_APPLY), false));
395
396                 setPopupMode(QToolButton::MenuButtonPopup);
397                 setEnabled(lyx::getStatus(FuncRequest(LFUN_TEXTSTYLE_APPLY)).enabled()
398                            || lyx::getStatus(FuncRequest(LFUN_FONT_DEFAULT)).enabled());
399         } else if (menutype == "paste") {
400                 m->clear();
401                 docstring_list const sel = cap::availableSelections(&bv->buffer());
402
403                 docstring_list::const_iterator cit = sel.begin();
404                 docstring_list::const_iterator end = sel.end();
405
406                 for (unsigned int index = 0; cit != end; ++cit, ++index) {
407                         docstring const s = *cit;
408                         FuncRequest func(LFUN_PASTE, convert<docstring>(index),
409                                          FuncRequest::TOOLBAR);
410                         docstring const lb = char_type('&') + convert<docstring>(index)
411                                 + from_ascii(". ") + s ;
412                         Action * act = new Action(func, QIcon(), toqstr(lb), toqstr(s), this);
413                         m->addAction(act);
414                 }
415                 Action * default_action = new Action(FuncRequest(LFUN_PASTE),
416                                                      getIcon(FuncRequest(LFUN_PASTE), false),
417                                                      qt_("Paste"), qt_("Paste"), this);
418                 QToolButton::setDefaultAction(default_action);
419                 setPopupMode(QToolButton::MenuButtonPopup);
420                 setEnabled(lyx::getStatus(FuncRequest(LFUN_PASTE)).enabled());
421         }
422 }
423
424
425 void DynamicMenuButton::loadFlexInsets()
426 {
427         QMenu * m = menu();
428         m->clear();
429         string const & menutype = tbitem_.name_;
430         InsetLayout::InsetLyXType ftype;
431         if (menutype == "dynamic-custom-insets")
432                 ftype = InsetLayout::CUSTOM;
433         else if (menutype == "dynamic-char-styles")
434                 ftype = InsetLayout::CHARSTYLE;
435         else {
436                 // this should have been taken care of earlier
437                 LASSERT(false, return);
438         }
439
440         TextClass::InsetLayouts const & inset_layouts = 
441                         d->text_class_->insetLayouts();
442         for (auto const & iit : inset_layouts) {
443                 InsetLayout const & il = iit.second;
444                 if (il.lyxtype() != ftype)
445                         continue;
446                 docstring const name = iit.first;
447                 QString const loc_item = toqstr(translateIfPossible(
448                                 prefixIs(name, from_ascii("Flex:")) ? 
449                                 name.substr(5) : name));
450                 FuncRequest func(LFUN_FLEX_INSERT, 
451                                 from_ascii("\"") + name + from_ascii("\""), FuncRequest::TOOLBAR);
452                 Action * act = 
453                                 new Action(func, getIcon(func, false), loc_item, loc_item, this);
454                 m->addAction(act);
455         }
456 }
457
458
459 void GuiToolbar::add(ToolbarItem const & item)
460 {
461         switch (item.type_) {
462         case ToolbarItem::SEPARATOR:
463                 addSeparator();
464                 break;
465         case ToolbarItem::LAYOUTS: {
466                 LayoutBox * layout = owner_.getLayoutDialog();
467                 QObject::connect(this, SIGNAL(iconSizeChanged(QSize)),
468                         layout, SLOT(setIconSize(QSize)));
469                 QAction * action = addWidget(layout);
470                 action->setVisible(true);
471                 break;
472         }
473         case ToolbarItem::MINIBUFFER:
474                 command_buffer_ = new GuiCommandBuffer(&owner_);
475                 addWidget(command_buffer_);
476                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
477                 //setHorizontalStretchable(true);
478                 break;
479         case ToolbarItem::TABLEINSERT: {
480                 QToolButton * tb = new QToolButton;
481                 tb->setCheckable(true);
482                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
483                 QString const label = qt_(to_ascii(item.label_));
484                 tb->setToolTip(label);
485                 tb->setStatusTip(label);
486                 tb->setText(label);
487                 InsertTableWidget * iv = new InsertTableWidget(tb);
488                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
489                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
490                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
491                 addWidget(tb);
492                 break;
493                 }
494         case ToolbarItem::ICONPALETTE:
495                 addWidget(new PaletteButton(this, item));
496                 break;
497         case ToolbarItem::POPUPMENU: {
498                 addWidget(new StaticMenuButton(this, item, false));
499                 break;
500                 }
501         case ToolbarItem::STICKYPOPUPMENU: {
502                 addWidget(new StaticMenuButton(this, item, true));
503                 break;
504                 }
505         case ToolbarItem::DYNAMICMENU: {
506                 // we only handle certain things
507                 if (DynamicMenuButton::isMenuType(item.name_))
508                         addWidget(new DynamicMenuButton(this, item));
509                 else
510                         LYXERR0("Unknown dynamic menu type: " << item.name_);
511                 break;
512         }
513         case ToolbarItem::COMMAND: {
514                 if (!getStatus(*item.func_).unknown())
515                         addAction(addItem(item));
516                 break;
517                 }
518         default:
519                 break;
520         }
521 }
522
523
524 void GuiToolbar::update(int context)
525 {
526         if (visibility_ & Toolbars::AUTO) {
527                 setVisible(visibility_ & context & Toolbars::ALLOWAUTO);
528                 if (isVisible() && commandBuffer() && (context & Toolbars::MINIBUFFER_FOCUS))
529                         commandBuffer()->setFocus();
530         }
531
532         // update visible toolbars only
533         if (!isVisible())
534                 return;
535
536         // This is a speed bottleneck because this is called on every keypress
537         // and update calls getStatus, which copies the cursor at least two times
538         for (int i = 0; i < actions_.size(); ++i)
539                 actions_[i]->update();
540
541         LayoutBox * layout = owner_.getLayoutDialog();
542         if (layout)
543                 layout->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
544
545         // emit signal
546         updated();
547 }
548
549
550 QString GuiToolbar::sessionKey() const
551 {
552         return "views/" + QString::number(owner_.id()) + "/" + objectName();
553 }
554
555
556 void GuiToolbar::saveSession(QSettings & settings) const
557 {
558         settings.setValue(sessionKey() + "/visibility", visibility_);
559         settings.setValue(sessionKey() + "/movability", isMovable());
560 }
561
562
563 void GuiToolbar::restoreSession()
564 {
565         QSettings settings;
566         int const error_val = -1;
567         int visibility =
568                 settings.value(sessionKey() + "/visibility", error_val).toInt();
569         if (visibility == error_val || visibility == 0) {
570                 // This should not happen, but in case we use the defaults
571                 LYXERR(Debug::GUI, "Session settings could not be found! Defaults are used instead.");
572                 visibility =
573                         guiApp->toolbars().defaultVisibility(fromqstr(objectName()));
574         }
575         setVisibility(visibility);
576
577         int movability = settings.value(sessionKey() + "/movability", true).toBool();
578         setMovable(movability);
579 }
580
581
582 void GuiToolbar::toggle()
583 {
584         docstring state;
585         if (visibility_ & Toolbars::ALLOWAUTO) {
586                 if (!(visibility_ & Toolbars::AUTO)) {
587                         visibility_ |= Toolbars::AUTO;
588                         hide();
589                         state = _("auto");
590                 } else {
591                         visibility_ &= ~Toolbars::AUTO;
592                         if (isVisible()) {
593                                 hide();
594                                 state = _("off");
595                         } else {
596                                 show();
597                                 state = _("on");
598                         }
599                 }
600         } else {
601                 if (isVisible()) {
602                         hide();
603                         state = _("off");
604                 } else {
605                         show();
606                         state = _("on");
607                 }
608         }
609
610         owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
611                 qstring_to_ucs4(windowTitle()), state));
612 }
613
614 void GuiToolbar::movable(bool silent)
615 {
616         // toggle movability
617         setMovable(!isMovable());
618
619         // manual update avoids bug in qt that the drag handle is not removed
620         // properly, e.g. in Windows
621         Q_EMIT update();
622
623         // silence for toggling of many toolbars for performance
624         if (!silent) {
625                 docstring state;
626                 if (isMovable())
627                         state = _("movable");
628                 else
629                         state = _("immovable");
630                 owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
631                         qstring_to_ucs4(windowTitle()), state));
632         }
633 }
634
635 } // namespace frontend
636 } // namespace lyx
637
638 #include "moc_GuiToolbar.cpp"