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