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