Debian Codegraph @

src/Gui/ToolBarManager.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QAction>
25 #include <QApplication>
26 #include <QHBoxLayout>
27 #include <QMenuBar>
28 #include <QMouseEvent>
29 #include <QPainter>
30 #include <QPointer>
31 #include <QStatusBar>
32 #include <QToolBar>
33 #include <QToolButton>
34 #include <QStyleOption>
35
36
37 #include <boost/algorithm/string/predicate.hpp>
38
39 #include <Base/Tools.h>
40
41 #include "ToolBarManager.h"
42 #include "ToolBarAreaWidget.h"
43 #include "Application.h"
44 #include "Command.h"
45 #include "MainWindow.h"
46 #include "OverlayWidgets.h"
47 #include "WidgetFactory.h"
48
49
50 using namespace Gui;
51
52 ToolBarItem::ToolBarItem()
53 : visibilityPolicy(DefaultVisibility::Visible)
54 {}
55
56 ToolBarItem::ToolBarItem(ToolBarItem* item, DefaultVisibility visibilityPolicy)
57 : visibilityPolicy(visibilityPolicy)
58 {
59 if (item) {
60 item->appendItem(this);
61 }
62 }
63
64 ToolBarItem::~ToolBarItem()
65 {
66 clear();
67 }
68
69 void ToolBarItem::setCommand(const std::string& name)
70 {
71 _name = name;
72 }
73
74 const std::string& ToolBarItem::command() const
75 {
76 return _name;
77 }
78
79 bool ToolBarItem::hasItems() const
80 {
81 return !_items.isEmpty();
82 }
83
84 ToolBarItem* ToolBarItem::findItem(const std::string& name)
85 {
86 if (_name == name) {
87 return this;
88 }
89
90 for (auto it : std::as_const(_items)) {
91 if (it->_name == name) {
92 return it;
93 }
94 }
95
96 return nullptr;
97 }
98
99 ToolBarItem* ToolBarItem::copy() const
100 {
101 auto root = new ToolBarItem;
102 root->setCommand(command());
103
104 QList<ToolBarItem*> items = getItems();
105 for (auto it : items) {
106 root->appendItem(it->copy());
107 }
108
109 return root;
110 }
111
112 uint ToolBarItem::count() const
113 {
114 return _items.count();
115 }
116
117 void ToolBarItem::appendItem(ToolBarItem* item)
118 {
119 _items.push_back(item);
120 }
121
122 bool ToolBarItem::insertItem(ToolBarItem* before, ToolBarItem* item)
123 {
124 int pos = _items.indexOf(before);
125 if (pos != -1) {
126 _items.insert(pos, item);
127 return true;
128 }
129
130 return false;
131 }
132
133 void ToolBarItem::removeItem(ToolBarItem* item)
134 {
135 int pos = _items.indexOf(item);
136 if (pos != -1) {
137 _items.removeAt(pos);
138 }
139 }
140
141 void ToolBarItem::clear()
142 {
143 for (auto it : std::as_const(_items)) {
144 delete it;
145 }
146
147 _items.clear();
148 }
149
150 ToolBarItem& ToolBarItem::operator<<(ToolBarItem* item)
151 {
152 appendItem(item);
153 return *this;
154 }
155
156 ToolBarItem& ToolBarItem::operator<<(const std::string& command)
157 {
158 auto item = new ToolBarItem(this);
159 item->setCommand(command);
160 return *this;
161 }
162
163 QList<ToolBarItem*> ToolBarItem::getItems() const
164 {
165 return _items;
166 }
167
168 // -----------------------------------------------------------
169
170 ToolBar::ToolBar()
171 : QToolBar()
172 {
173 setupConnections();
174 }
175
176 ToolBar::ToolBar(QWidget* parent)
177 : QToolBar(parent)
178 {
179 setupConnections();
180 }
181
182 void ToolBar::undock()
183 {
184 {
185 // We want to block only some signals - topLevelChanged should still be propagated
186 QSignalBlocker blocker(this);
187
188 if (auto area = ToolBarManager::getInstance()->toolBarAreaWidget(this)) {
189 area->removeWidget(this);
190 getMainWindow()->addToolBar(this);
191 }
192
193 setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
194 adjustSize();
195 setVisible(true);
196 }
197
198 Q_EMIT topLevelChanged(true);
199 }
200
201 void ToolBar::updateCustomGripVisibility()
202 {
203 auto area = ToolBarManager::getInstance()->toolBarAreaWidget(this);
204 auto grip = findChild<ToolBarGrip*>();
205
206 auto customGripIsRequired = isMovable() && area;
207
208 if (grip && !customGripIsRequired) {
209 grip->detach();
210 grip->deleteLater();
211 }
212 else if (!grip && customGripIsRequired) {
213 grip = new ToolBarGrip(this);
214 grip->attach();
215 }
216 else {
217 // either grip is present and should be present
218 // or is not present and should not be - nothing to do
219 return;
220 }
221 }
222
223 void Gui::ToolBar::setupConnections()
224 {
225 connect(this, &QToolBar::topLevelChanged, this, &ToolBar::updateCustomGripVisibility);
226 connect(this, &QToolBar::movableChanged, this, &ToolBar::updateCustomGripVisibility);
227 }
228
229 // -----------------------------------------------------------
230
231 ToolBarGrip::ToolBarGrip(QToolBar* parent)
232 : QWidget(parent)
233 {
234 updateSize();
235 }
236
237 void ToolBarGrip::attach()
238 {
239 if (isAttached()) {
240 return;
241 }
242
243 auto parent = qobject_cast<ToolBar*>(parentWidget());
244
245 if (!parent) {
246 return;
247 }
248
249 auto actions = parent->actions();
250
251 _action = parent->insertWidget(
252 // ensure that grip is always placed as the first widget in the toolbar
253 actions.isEmpty() ? nullptr : actions[0],
254 this
255 );
256
257 setCursor(Qt::OpenHandCursor);
258 setMouseTracking(true);
259 setVisible(true);
260 }
261
262 void ToolBarGrip::detach()
263 {
264 if (!isAttached()) {
265 return;
266 }
267
268 auto parent = qobject_cast<ToolBar*>(parentWidget());
269
270 if (!parent) {
271 return;
272 }
273
274 parent->removeAction(_action);
275 }
276
277 bool ToolBarGrip::isAttached() const
278 {
279 return _action != nullptr;
280 }
281
282 void ToolBarGrip::paintEvent(QPaintEvent*)
283 {
284 QPainter painter(this);
285
286 if (auto toolbar = qobject_cast<ToolBar*>(parentWidget())) {
287 QStyle* style = toolbar->style();
288 QStyleOptionToolBar opt;
289
290 toolbar->initStyleOption(&opt);
291
292 opt.features = QStyleOptionToolBar::Movable;
293 opt.rect = rect();
294
295 style->drawPrimitive(QStyle::PE_IndicatorToolBarHandle, &opt, &painter, toolbar);
296 }
297 }
298
299 void ToolBarGrip::mouseMoveEvent(QMouseEvent* me)
300 {
301 auto toolbar = qobject_cast<ToolBar*>(parentWidget());
302 if (!toolbar) {
303 return;
304 }
305
306 auto area = ToolBarManager::getInstance()->toolBarAreaWidget(toolbar);
307 if (!area) {
308 return;
309 }
310
311 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
312 QPoint pos = me->globalPos();
313 #else
314 QPoint pos = me->globalPosition().toPoint();
315 #endif
316 QRect rect(toolbar->mapToGlobal(QPoint(0, 0)), toolbar->size());
317
318 // if mouse did not leave the area of toolbar do not continue with undocking it
319 if (rect.contains(pos)) {
320 return;
321 }
322
323 toolbar->undock();
324
325 // After removing from area, this grip will be deleted. In order to
326 // continue toolbar dragging (because the mouse button is still pressed),
327 // we fake mouse events and send to toolbar. For some reason,
328 // send/postEvent() does not work, only timer works.
329 QPointer tb(toolbar);
330 QTimer::singleShot(0, [tb] {
331 auto modifiers = QApplication::queryKeyboardModifiers();
332 auto buttons = QApplication::mouseButtons();
333 if (buttons != Qt::LeftButton || QWidget::mouseGrabber() || modifiers != Qt::NoModifier
334 || !tb) {
335 return;
336 }
337
338 QPoint pos(10, 10);
339 QPoint globalPos(tb->mapToGlobal(pos));
340 QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, globalPos, Qt::LeftButton, buttons, modifiers);
341 QApplication::sendEvent(tb, &mouseEvent);
342
343 // Mouse follow the mouse press event with mouse move with some offset
344 // in order to activate toolbar dragging.
345 QPoint offset(30, 30);
346 QMouseEvent mouseMoveEvent(
347 QEvent::MouseMove,
348 pos + offset,
349 globalPos + offset,
350 Qt::LeftButton,
351 buttons,
352 modifiers
353 );
354 QApplication::sendEvent(tb, &mouseMoveEvent);
355 });
356 }
357
358 void ToolBarGrip::mousePressEvent(QMouseEvent*)
359 {
360 setCursor(Qt::ClosedHandCursor);
361 }
362
363 void ToolBarGrip::mouseReleaseEvent(QMouseEvent*)
364 {
365 setCursor(Qt::OpenHandCursor);
366 }
367
368 void ToolBarGrip::updateSize()
369 {
370 auto parent = qobject_cast<ToolBar*>(parentWidget());
371
372 if (!parent) {
373 return;
374 }
375
376 QStyle* style = parent->style();
377 QStyleOptionToolBar opt;
378
379 parent->initStyleOption(&opt);
380 opt.features = QStyleOptionToolBar::Movable;
381
382 setFixedWidth(style->subElementRect(QStyle::SE_ToolBarHandle, &opt, parent).width() + 4);
383 }
384
385 // -----------------------------------------------------------
386
387 ToolBarManager* ToolBarManager::_instance = nullptr; // NOLINT
388
389 ToolBarManager* ToolBarManager::getInstance()
390 {
391 if (!_instance) {
392 _instance = new ToolBarManager;
393 }
394 return _instance;
395 }
396
397 void ToolBarManager::destruct()
398 {
399 delete _instance;
400 _instance = nullptr;
401 }
402
403 ToolBarManager::ToolBarManager()
404 {
405 setupParameters();
406 setupStatusBar();
407 setupMenuBar();
408
409 setupSizeTimer();
410 setupResizeTimer();
411 setupConnection();
412 setupTimer();
413 setupMenuBarTimer();
414
415 setupWidgetProducers();
416 }
417
418 ToolBarManager::~ToolBarManager() = default;
419
420 void ToolBarManager::setupParameters()
421 {
422 auto& mgr = App::GetApplication().GetUserParameter();
423 hGeneral = mgr.GetGroup("BaseApp/Preferences/General");
424 hStatusBar = mgr.GetGroup("BaseApp/MainWindow/StatusBar");
425 hMenuBarRight = mgr.GetGroup("BaseApp/MainWindow/MenuBarRight");
426 hMenuBarLeft = mgr.GetGroup("BaseApp/MainWindow/MenuBarLeft");
427 hPref = mgr.GetGroup("BaseApp/MainWindow/Toolbars");
428 }
429
430 void ToolBarManager::setupStatusBar()
431 {
432 if (auto sb = getMainWindow()->statusBar()) {
433 sb->installEventFilter(this);
434 statusBarAreaWidget
435 = new ToolBarAreaWidget(sb, ToolBarArea::StatusBarToolBarArea, hStatusBar, connParam);
436 statusBarAreaWidget->setObjectName(QStringLiteral("StatusBarArea"));
437 sb->insertPermanentWidget(2, statusBarAreaWidget);
438 statusBarAreaWidget->show();
439 }
440 }
441
442 void ToolBarManager::setupMenuBar()
443 {
444 if (auto mb = getMainWindow()->menuBar()) {
445 mb->installEventFilter(this);
446 menuBarLeftAreaWidget = new ToolBarAreaWidget(
447 mb,
448 ToolBarArea::LeftMenuToolBarArea,
449 hMenuBarLeft,
450 connParam,
451 &menuBarTimer
452 );
453 menuBarLeftAreaWidget->setObjectName(QStringLiteral("MenuBarLeftArea"));
454 mb->setCornerWidget(menuBarLeftAreaWidget, Qt::TopLeftCorner);
455 menuBarLeftAreaWidget->show();
456 menuBarRightAreaWidget = new ToolBarAreaWidget(
457 mb,
458 ToolBarArea::RightMenuToolBarArea,
459 hMenuBarRight,
460 connParam,
461 &menuBarTimer
462 );
463 menuBarRightAreaWidget->setObjectName(QStringLiteral("MenuBarRightArea"));
464 mb->setCornerWidget(menuBarRightAreaWidget, Qt::TopRightCorner);
465 menuBarRightAreaWidget->show();
466 }
467 }
468
469 void ToolBarManager::setupConnection()
470 {
471 auto refreshParams = [this](const char* name) {
472 bool sizeChanged = false;
473 if (!name || boost::equals(name, "ToolbarIconSize")) {
474 _toolBarIconSize = hGeneral->GetInt("ToolbarIconSize", 24);
475 sizeChanged = true;
476 }
477 if (!name || boost::equals(name, "StatusBarIconSize")) {
478 _statusBarIconSize = hGeneral->GetInt("StatusBarIconSize", 0);
479 sizeChanged = true;
480 }
481 if (!name || boost::equals(name, "MenuBarIconSize")) {
482 _menuBarIconSize = hGeneral->GetInt("MenuBarIconSize", 0);
483 sizeChanged = true;
484 }
485 if (sizeChanged) {
486 sizeTimer.start(100);
487 }
488 };
489
490 refreshParams(nullptr);
491 connParam = App::GetApplication().GetUserParameter().signalParamChanged.connect(
492 [this,
493 refreshParams](ParameterGrp* hParam, ParameterGrp::ParamType, const char* name, const char*) {
494 if (hParam == hGeneral && name) {
495 refreshParams(name);
496 }
497 if (hParam == hPref || hParam == hStatusBar || hParam == hMenuBarRight
498 || hParam == hMenuBarLeft) {
499 if (blockRestore) {
500 blockRestore = false;
501 }
502 else {
503 timer.start(100);
504 }
505 }
506 }
507 );
508 }
509
510 void ToolBarManager::setupTimer()
511 {
512 timer.setSingleShot(true);
513 connect(&timer, &QTimer::timeout, [this] { onTimer(); });
514 }
515
516 void ToolBarManager::setupSizeTimer()
517 {
518 sizeTimer.setSingleShot(true);
519 connect(&sizeTimer, &QTimer::timeout, [this] { setupToolBarIconSize(); });
520 }
521
522 void ToolBarManager::setupResizeTimer()
523 {
524 resizeTimer.setSingleShot(true);
525 connect(&resizeTimer, &QTimer::timeout, [this] {
526 for (const auto& [toolbar, guard] : resizingToolbars) {
527 if (guard) {
528 setToolBarIconSize(toolbar);
529 }
530 }
531 resizingToolbars.clear();
532 });
533 }
534
535 void ToolBarManager::setupMenuBarTimer()
536 {
537 menuBarTimer.setSingleShot(true);
538 QObject::connect(&menuBarTimer, &QTimer::timeout, [] {
539 if (auto menuBar = getMainWindow()->menuBar()) {
540 menuBar->adjustSize();
541 }
542 });
543 }
544
545 void Gui::ToolBarManager::setupWidgetProducers()
546 {
547 new WidgetProducer<Gui::ToolBar>;
548 }
549
550 ToolBarArea ToolBarManager::toolBarArea(QWidget* widget) const
551 {
552 if (auto toolBar = qobject_cast<QToolBar*>(widget)) {
553 if (toolBar->isFloating()) {
554 return ToolBarArea::NoToolBarArea;
555 }
556
557 auto qtToolBarArea = getMainWindow()->toolBarArea(toolBar);
558 switch (qtToolBarArea) {
559 case Qt::LeftToolBarArea:
560 return ToolBarArea::LeftToolBarArea;
561 case Qt::RightToolBarArea:
562 return ToolBarArea::RightToolBarArea;
563 case Qt::TopToolBarArea:
564 return ToolBarArea::TopToolBarArea;
565 case Qt::BottomToolBarArea:
566 return ToolBarArea::BottomToolBarArea;
567 default:
568 // no-op
569 break;
570 }
571 }
572
573 if (auto areaWidget = toolBarAreaWidget(widget)) {
574 return areaWidget->area();
575 }
576
577 return ToolBarArea::NoToolBarArea;
578 }
579
580 ToolBarAreaWidget* ToolBarManager::toolBarAreaWidget(QWidget* widget) const
581 {
582 for (auto& areaWidget : {statusBarAreaWidget, menuBarLeftAreaWidget, menuBarRightAreaWidget}) {
583 if (areaWidget->indexOf(widget) >= 0) {
584 return areaWidget;
585 }
586 }
587
588 return nullptr;
589 }
590
591 namespace
592 {
593 QPointer<QWidget> createActionWidget()
594 {
595 static QPointer<QWidget> actionWidget;
596 if (!actionWidget) {
597 actionWidget = new QWidget(getMainWindow());
598 actionWidget->setObjectName(QStringLiteral("_fc_action_widget_"));
599 /* TODO This is a temporary hack until a longterm solution
600 is found, thanks to @realthunder for this pointer.
601 Although actionWidget has zero size, it somehow has a
602 'phantom' size without any visible content and will block the top
603 left tool buttons and menus of the application main window.
604 Therefore it is moved out of the way. */
605 actionWidget->move(QPoint(-100, -100));
606 }
607 else {
608 auto actions = actionWidget->actions();
609 for (auto action : actions) {
610 actionWidget->removeAction(action);
611 }
612 }
613
614 return actionWidget;
615 }
616 } // namespace
617
618 int ToolBarManager::toolBarIconSize(QWidget* widget) const
619 {
620 int s = _toolBarIconSize;
621 if (widget) {
622 if (widget->parentWidget() == statusBarAreaWidget) {
623 if (_statusBarIconSize > 0) {
624 s = _statusBarIconSize;
625 }
626 else {
627 s *= 0.6;
628 }
629 }
630 else if (widget->parentWidget() == menuBarLeftAreaWidget
631 || widget->parentWidget() == menuBarRightAreaWidget) {
632 if (_menuBarIconSize > 0) {
633 s = _menuBarIconSize;
634 }
635 else {
636 s *= 0.6;
637 }
638 }
639 }
640 return std::max(s, 5);
641 }
642
643 void ToolBarManager::setupToolBarIconSize()
644 {
645 int s = toolBarIconSize();
646 getMainWindow()->setIconSize(QSize(s, s));
647 // Most of the the toolbar will have explicit icon size, so the above call
648 // to QMainWindow::setIconSize() will have no effect. We need to explicitly
649 // change the icon size.
650 QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>();
651 for (auto toolbar : std::as_const(bars)) {
652 setToolBarIconSize(toolbar);
653 }
654 }
655
656 void ToolBarManager::setToolBarIconSize(QToolBar* toolbar)
657 {
658 int s = toolBarIconSize(toolbar);
659 toolbar->setIconSize(QSize(s, s));
660 if (toolbar->parentWidget() == menuBarLeftAreaWidget) {
661 menuBarLeftAreaWidget->adjustParent();
662 }
663 else if (toolbar->parentWidget() == menuBarRightAreaWidget) {
664 menuBarRightAreaWidget->adjustParent();
665 }
666 }
667
668 void ToolBarManager::setup(ToolBarItem* toolBarItems)
669 {
670 if (!toolBarItems) {
671 return; // empty menu bar
672 }
673
674 QPointer<QWidget> actionWidget = createActionWidget();
675
676 saveState();
677 this->toolbarNames.clear();
678
679 int max_width = getMainWindow()->width();
680 int top_width = 0;
681
682 bool nameAsToolTip = App::GetApplication()
683 .GetUserParameter()
684 .GetGroup("BaseApp")
685 ->GetGroup("Preferences")
686 ->GetGroup("MainWindow")
687 ->GetBool("ToolBarNameAsToolTip", true);
688
689 QList<ToolBarItem*> items = toolBarItems->getItems();
690 QList<ToolBar*> toolbars = toolBars();
691
692 for (ToolBarItem* it : items) {
693 // search for the toolbar
694 QString name = QString::fromUtf8(it->command().c_str());
695 this->toolbarNames << name;
696 ToolBar* toolbar = findToolBar(toolbars, name);
697 std::string toolbarName = it->command();
698 bool toolbar_added = false;
699
700 if (!toolbar) {
701 toolbar = new ToolBar(getMainWindow());
702 toolbar->setWindowTitle(QApplication::translate("Workbench", toolbarName.c_str()));
703 toolbar->setObjectName(name);
704
705 getMainWindow()->addToolBar(toolbar);
706
707 if (nameAsToolTip) {
708 auto tooltip = QChar::fromLatin1('[')
709 + QApplication::translate("Workbench", toolbarName.c_str())
710 + QChar::fromLatin1(']');
711 toolbar->setToolTip(tooltip);
712 }
713 toolbar_added = true;
714 }
715 else {
716 int index = toolbars.indexOf(toolbar);
717 toolbars.removeAt(index);
718 }
719
720 bool visible = false;
721
722 // If visibility policy is custom, the toolbar is initialised as not visible, and the
723 // toggleViewAction to control its visibility is not visible either.
724 //
725 // Both are managed under the responsibility of the client code
726 if (it->visibilityPolicy != ToolBarItem::DefaultVisibility::Unavailable) {
727 bool defaultvisibility = it->visibilityPolicy == ToolBarItem::DefaultVisibility::Visible;
728
729 visible = hPref->GetBool(toolbarName.c_str(), defaultvisibility);
730
731 // Enable automatic handling of visibility via, for example, (contextual) menu
732 toolbar->toggleViewAction()->setVisible(true);
733 }
734 else {
735 // ToolBarItem::DefaultVisibility::Unavailable
736 // Prevent that the action to show/hide a toolbar appears on the (contextual) menus.
737 // This is also managed by the client code for a toolbar with custom policy
738 toolbar->toggleViewAction()->setVisible(false);
739 }
740
741 // Initialise toolbar item visibility
742 toolbar->setVisible(visible);
743
744 // Store item visibility policy within the action
745 QAction* toggle = toolbar->toggleViewAction();
746 toggle->setProperty("DefaultVisibility", static_cast<int>(it->visibilityPolicy));
747
748 // setup the toolbar
749 setup(it, toolbar);
750 auto actions = toolbar->actions();
751 for (auto action : actions) {
752 actionWidget->addAction(action);
753 }
754
755 // try to add some breaks to avoid to have all toolbars in one line
756 if (toolbar_added) {
757 if (top_width > 0 && getMainWindow()->toolBarBreak(toolbar)) {
758 top_width = 0;
759 }
760
761 // the width() of a toolbar doesn't return useful results so we estimate
762 // its size by the number of buttons and the icon size
763 QList<QToolButton*> btns = toolbar->findChildren<QToolButton*>();
764 top_width += (btns.size() * toolbar->iconSize().width());
765 if (top_width > max_width) {
766 top_width = 0;
767 getMainWindow()->insertToolBarBreak(toolbar);
768 }
769 }
770 }
771 // hide all unneeded toolbars
772 for (QToolBar* it : std::as_const(toolbars)) {
773 // make sure that the main window has the focus when hiding the toolbar with
774 // the combo box inside
775 QWidget* fw = QApplication::focusWidget();
776 while (fw && !fw->isWindow()) {
777 if (fw == it) {
778 getMainWindow()->setFocus();
779 break;
780 }
781 fw = fw->parentWidget();
782 }
783 // ignore toolbars which do not belong to the previously active workbench
784 // QByteArray toolbarName = it->objectName().toUtf8();
785 if (!it->toggleViewAction()->isVisible()) {
786 continue;
787 }
788 // hPref->SetBool(toolbarName.constData(), it->isVisible());
789 it->hide();
790 it->toggleViewAction()->setVisible(false);
791 }
792
793 setMovable(!areToolBarsLocked());
794 }
795
796 void ToolBarManager::setup(ToolBarItem* item, QToolBar* toolbar) const
797 {
798 CommandManager& mgr = Application::Instance->commandManager();
799 QList<ToolBarItem*> items = item->getItems();
800 QList<QAction*> actions = toolbar->actions();
801 for (ToolBarItem* it : items) {
802 // search for the action item
803 QAction* action = findAction(actions, QString::fromLatin1(it->command().c_str()));
804 if (!action) {
805 if (it->command() == "Separator") {
806 action = toolbar->addSeparator();
807 }
808 else {
809 // Check if action was added successfully
810 if (mgr.addTo(it->command().c_str(), toolbar)) {
811 action = toolbar->actions().constLast();
812 }
813 }
814
815 // set the tool button user data
816 if (action) {
817 action->setData(QString::fromLatin1(it->command().c_str()));
818 }
819 }
820 else {
821 // Note: For toolbars we do not remove and re-add the actions
822 // because this causes flicker effects. So, it could happen that the order of
823 // buttons doesn't match with the order of commands in the workbench.
824 int index = actions.indexOf(action);
825 actions.removeAt(index);
826 }
827 }
828
829 // remove all tool buttons which we don't need for the moment
830 for (QAction* it : std::as_const(actions)) {
831 toolbar->removeAction(it);
832 }
833 }
834
835 void ToolBarManager::onTimer()
836 {
837 restoreState();
838 }
839
840 void ToolBarManager::saveState() const
841 {
842 auto ignoreSave = [](QAction* action) {
843 // If the toggle action is invisible then it's controlled by the application.
844 // In this case the current state is not saved.
845 if (!action->isVisible()) {
846 return true;
847 }
848
849 QVariant property = action->property("DefaultVisibility");
850 if (property.isNull()) {
851 return false;
852 }
853
854 // If DefaultVisibility is Unavailable then never save the state because it's
855 // always controlled by the client code.
856 auto value = static_cast<ToolBarItem::DefaultVisibility>(property.toInt());
857 return value == ToolBarItem::DefaultVisibility::Unavailable;
858 };
859
860 QList<ToolBar*> toolbars = toolBars();
861 for (const QString& it : toolbarNames) {
862 ToolBar* toolbar = findToolBar(toolbars, it);
863
864 if (toolbar) {
865 if (ignoreSave(toolbar->toggleViewAction())) {
866 continue;
867 }
868
869 QByteArray toolbarName = toolbar->objectName().toUtf8();
870 hPref->SetBool(toolbarName.constData(), toolbar->isVisible());
871 }
872 }
873 }
874
875 void ToolBarManager::restoreState() const
876 {
877 std::map<int, QToolBar*> sbToolBars;
878 std::map<int, QToolBar*> mbRightToolBars;
879 std::map<int, QToolBar*> mbLeftToolBars;
880 QList<ToolBar*> toolbars = toolBars();
881 for (const QString& it : toolbarNames) {
882 QToolBar* toolbar = findToolBar(toolbars, it);
883 if (toolbar) {
884 QByteArray toolbarName = toolbar->objectName().toUtf8();
885 if (getToolbarPolicy(toolbar) != ToolBarItem::DefaultVisibility::Unavailable) {
886 toolbar->setVisible(hPref->GetBool(toolbarName.constData(), toolbar->isVisible()));
887 }
888
889 int idx = hStatusBar->GetInt(toolbarName, -1);
890 if (idx >= 0) {
891 sbToolBars[idx] = toolbar;
892 continue;
893 }
894 idx = hMenuBarLeft->GetInt(toolbarName, -1);
895 if (idx >= 0) {
896 mbLeftToolBars[idx] = toolbar;
897 continue;
898 }
899 idx = hMenuBarRight->GetInt(toolbarName, -1);
900 if (idx >= 0) {
901 mbRightToolBars[idx] = toolbar;
902 continue;
903 }
904 if (toolbar->parentWidget() != getMainWindow()) {
905 getMainWindow()->addToolBar(toolbar);
906 }
907 }
908 }
909
910 setMovable(!areToolBarsLocked());
911
912 statusBarAreaWidget->restoreState(sbToolBars);
913 menuBarRightAreaWidget->restoreState(mbRightToolBars);
914 menuBarLeftAreaWidget->restoreState(mbLeftToolBars);
915 }
916
917 bool ToolBarManager::addToolBarToArea(QObject* source, QMouseEvent* ev)
918 {
919 auto statusBar = getMainWindow()->statusBar();
920 if (!statusBar || !statusBar->isVisible()) {
921 statusBar = nullptr;
922 }
923
924 auto menuBar = getMainWindow()->menuBar();
925 if (!menuBar || !menuBar->isVisible()) {
926 if (!statusBar) {
927 return false;
928 }
929 menuBar = nullptr;
930 }
931
932 auto tb = qobject_cast<QToolBar*>(source);
933 if (!tb || !tb->isFloating()) {
934 return false;
935 }
936
937 static QPointer<OverlayDragFrame> tbPlaceholder;
938 static QPointer<ToolBarAreaWidget> lastArea;
939 static int tbIndex = -1;
940 if (ev->type() == QEvent::MouseMove) {
941 if (tb->orientation() != Qt::Horizontal || ev->buttons() != Qt::LeftButton) {
942 if (tbIndex >= 0) {
943 if (lastArea) {
944 lastArea->removeWidget(tbPlaceholder);
945 lastArea = nullptr;
946 }
947 tbPlaceholder->hide();
948 tbIndex = -1;
949 }
950 return false;
951 }
952 }
953
954 if (ev->type() == QEvent::MouseButtonRelease && ev->button() != Qt::LeftButton) {
955 return false;
956 }
957
958 QPoint pos = QCursor::pos();
959 ToolBarAreaWidget* area = nullptr;
960 if (statusBar) {
961 QRect rect(statusBar->mapToGlobal(QPoint(0, 0)), statusBar->size());
962 if (rect.contains(pos)) {
963 area = statusBarAreaWidget;
964 }
965 }
966 if (!area) {
967 if (!menuBar) {
968 return false;
969 }
970 QRect rect(menuBar->mapToGlobal(QPoint(0, 0)), menuBar->size());
971 if (rect.contains(pos)) {
972 if (pos.x() - rect.left() < menuBar->width() / 2) {
973 area = menuBarLeftAreaWidget;
974 }
975 else {
976 area = menuBarRightAreaWidget;
977 }
978 }
979 else {
980 if (tbPlaceholder) {
981 if (lastArea) {
982 lastArea->removeWidget(tbPlaceholder);
983 lastArea = nullptr;
984 }
985 tbPlaceholder->hide();
986 tbIndex = -1;
987 }
988 return false;
989 }
990 }
991
992 int idx = 0;
993 for (int c = area->count(); idx < c; ++idx) {
994 auto widget = area->widgetAt(idx);
995 if (!widget || widget->isHidden()) {
996 continue;
997 }
998 int p = widget->mapToGlobal(widget->rect().center()).x();
999 if (pos.x() < p) {
1000 break;
1001 }
1002 }
1003 if (tbIndex >= 0 && tbIndex == idx - 1) {
1004 idx = tbIndex;
1005 }
1006 if (ev->type() == QEvent::MouseMove) {
1007 if (!tbPlaceholder) {
1008 tbPlaceholder = new OverlayDragFrame(getMainWindow());
1009 tbPlaceholder->hide();
1010 tbIndex = -1;
1011 }
1012 if (tbIndex != idx) {
1013 tbIndex = idx;
1014 tbPlaceholder->setSizePolicy(tb->sizePolicy());
1015 tbPlaceholder->setMinimumWidth(tb->minimumWidth());
1016 tbPlaceholder->resize(tb->size());
1017 area->insertWidget(idx, tbPlaceholder);
1018 lastArea = area;
1019 tbPlaceholder->adjustSize();
1020 tbPlaceholder->show();
1021 }
1022 }
1023 else {
1024 tbIndex = idx;
1025 QTimer::singleShot(10, tb, [tb]() {
1026 if (!lastArea) {
1027 return;
1028 }
1029
1030 {
1031 tbPlaceholder->hide();
1032 QSignalBlocker block(tb);
1033 lastArea->removeWidget(tbPlaceholder);
1034 getMainWindow()->removeToolBar(tb);
1035 tb->setOrientation(Qt::Horizontal);
1036 lastArea->insertWidget(tbIndex, tb);
1037 tb->setVisible(true);
1038 lastArea = nullptr;
1039 }
1040
1041 Q_EMIT tb->topLevelChanged(false);
1042 tbIndex = -1;
1043 });
1044 }
1045 return false;
1046 }
1047
1048 bool ToolBarManager::showContextMenu(QObject* source)
1049 {
1050 QMenu menu;
1051 QLayout* layout = nullptr;
1052 ToolBarAreaWidget* area = nullptr;
1053 if (getMainWindow()->statusBar() == source) {
1054 area = statusBarAreaWidget;
1055 layout = findLayoutOfObject(source, area);
1056 }
1057 else if (getMainWindow()->menuBar() == source) {
1058 area = findToolBarAreaWidget();
1059 if (!area) {
1060 return false;
1061 }
1062 }
1063 else {
1064 return false;
1065 }
1066
1067 auto addMenuVisibleItem = [&](QToolBar* toolbar, int, ToolBarAreaWidget*) {
1068 auto action = toolbar->toggleViewAction();
1069 if ((action->isVisible() || toolbar->isVisible()) && action->text().size()) {
1070 action->setVisible(true);
1071 menu.addAction(action);
1072 }
1073 };
1074
1075 if (layout) {
1076 addToMenu(layout, area, &menu);
1077 }
1078
1079 area->foreachToolBar(addMenuVisibleItem);
1080
1081 menu.exec(QCursor::pos());
1082 return true;
1083 }
1084
1085 QLayout* ToolBarManager::findLayoutOfObject(QObject* source, QWidget* area) const
1086 {
1087 QLayout* layout = nullptr;
1088 auto layouts = source->findChildren<QHBoxLayout*>();
1089 for (auto l : std::as_const(layouts)) {
1090 if (l->indexOf(area) >= 0) {
1091 layout = l;
1092 break;
1093 }
1094 }
1095 return layout;
1096 }
1097
1098 ToolBarAreaWidget* ToolBarManager::findToolBarAreaWidget() const
1099 {
1100 ToolBarAreaWidget* area = nullptr;
1101
1102 QPoint pos = QCursor::pos();
1103 QRect rect(menuBarLeftAreaWidget->mapToGlobal(QPoint(0, 0)), menuBarLeftAreaWidget->size());
1104 if (rect.contains(pos)) {
1105 area = menuBarLeftAreaWidget;
1106 }
1107 else {
1108 rect = QRect(menuBarRightAreaWidget->mapToGlobal(QPoint(0, 0)), menuBarRightAreaWidget->size());
1109 if (rect.contains(pos)) {
1110 area = menuBarRightAreaWidget;
1111 }
1112 }
1113
1114 return area;
1115 }
1116
1117 void ToolBarManager::addToMenu(QLayout* layout, QWidget* area, QMenu* menu)
1118 {
1119 for (int i = 0, c = layout->count(); i < c; ++i) {
1120 auto widget = layout->itemAt(i)->widget();
1121 if (!widget || widget == area || widget->objectName().isEmpty()
1122 || widget->objectName().startsWith(QStringLiteral("*"))) {
1123 continue;
1124 }
1125 QString name = widget->windowTitle();
1126 if (name.isEmpty()) {
1127 name = widget->objectName();
1128 name.replace(QLatin1Char('_'), QLatin1Char(' '));
1129 name = name.simplified();
1130 }
1131
1132 auto action = new QAction(menu);
1133 action->setText(name);
1134 action->setCheckable(true);
1135 action->setChecked(widget->isVisible());
1136 menu->addAction(action);
1137
1138 auto onToggle = [widget, this](bool visible) {
1139 onToggleStatusBarWidget(widget, visible);
1140 };
1141 QObject::connect(action, &QAction::triggered, onToggle);
1142 }
1143 }
1144
1145 void ToolBarManager::onToggleStatusBarWidget(QWidget* widget, bool visible)
1146 {
1147 Base::ConnectionBlocker block(connParam);
1148 widget->setVisible(visible);
1149 hStatusBar->SetBool(widget->objectName().toUtf8().constData(), widget->isVisible());
1150 }
1151
1152 bool ToolBarManager::eventFilter(QObject* source, QEvent* ev)
1153 {
1154 bool res = false;
1155 switch (ev->type()) {
1156 case QEvent::Show:
1157 case QEvent::Hide:
1158 if (auto toolbar = qobject_cast<QToolBar*>(source)) {
1159 auto parent = toolbar->parentWidget();
1160 if (parent == menuBarLeftAreaWidget || parent == menuBarRightAreaWidget) {
1161 menuBarTimer.start(10);
1162 }
1163 }
1164 break;
1165 case QEvent::MouseButtonRelease: {
1166 auto mev = static_cast<QMouseEvent*>(ev);
1167 if (mev->button() == Qt::RightButton) {
1168 if (showContextMenu(source)) {
1169 return true;
1170 }
1171 }
1172 }
1173 // fall through
1174 case QEvent::MouseMove:
1175 res = addToolBarToArea(source, static_cast<QMouseEvent*>(ev));
1176 break;
1177 case QEvent::ParentChange:
1178 if (auto toolbar = qobject_cast<QToolBar*>(source)) {
1179 resizingToolbars[toolbar] = toolbar;
1180 resizeTimer.start(100);
1181 }
1182 break;
1183 default:
1184 break;
1185 }
1186 return res;
1187 }
1188
1189 void ToolBarManager::retranslate() const
1190 {
1191 QList<ToolBar*> toolbars = toolBars();
1192 for (ToolBar* it : toolbars) {
1193 QByteArray toolbarName = it->objectName().toUtf8();
1194 it->setWindowTitle(QApplication::translate("Workbench", (const char*)toolbarName));
1195 }
1196 }
1197
1198 bool Gui::ToolBarManager::areToolBarsLocked() const
1199 {
1200 return hGeneral->GetBool("LockToolBars", false);
1201 }
1202
1203 void Gui::ToolBarManager::setToolBarsLocked(bool locked) const
1204 {
1205 hGeneral->SetBool("LockToolBars", locked);
1206
1207 setMovable(!locked);
1208 }
1209
1210 void Gui::ToolBarManager::setMovable(bool movable) const
1211 {
1212 for (auto& tb : toolBars()) {
1213 tb->setMovable(movable);
1214 tb->updateCustomGripVisibility();
1215 }
1216 }
1217
1218 ToolBar* ToolBarManager::findToolBar(const QList<ToolBar*>& toolbars, const QString& item) const
1219 {
1220 for (ToolBar* it : toolbars) {
1221 if (it->objectName() == item) {
1222 return it;
1223 }
1224 }
1225
1226 return nullptr; // no item with the user data found
1227 }
1228
1229 QAction* ToolBarManager::findAction(const QList<QAction*>& acts, const QString& item) const
1230 {
1231 for (QAction* it : acts) {
1232 if (it->data().toString() == item) {
1233 return it;
1234 }
1235 }
1236
1237 return nullptr; // no item with the user data found
1238 }
1239
1240 QList<ToolBar*> ToolBarManager::toolBars() const
1241 {
1242 auto mw = getMainWindow();
1243
1244 QList<ToolBar*> tb;
1245 QList<ToolBar*> bars = getMainWindow()->findChildren<ToolBar*>();
1246
1247 for (ToolBar* it : bars) {
1248 auto parent = it->parentWidget();
1249 if (parent == mw || parent == mw->statusBar() || parent == statusBarAreaWidget
1250 || parent == menuBarLeftAreaWidget || parent == menuBarRightAreaWidget) {
1251 tb.push_back(it);
1252 it->installEventFilter(const_cast<ToolBarManager*>(this));
1253 }
1254 }
1255
1256 return tb;
1257 }
1258
1259 ToolBarItem::DefaultVisibility ToolBarManager::getToolbarPolicy(const QToolBar* toolbar) const
1260 {
1261 auto* action = toolbar->toggleViewAction();
1262
1263 QVariant property = action->property("DefaultVisibility");
1264 if (property.isNull()) {
1265 return ToolBarItem::DefaultVisibility::Visible;
1266 }
1267
1268 return static_cast<ToolBarItem::DefaultVisibility>(property.toInt());
1269 }
1270
1271 void ToolBarManager::setState(const QList<QString>& names, State state)
1272 {
1273 for (auto& name : names) {
1274 setState(name, state);
1275 }
1276 }
1277
1278 void ToolBarManager::setState(const QString& name, State state)
1279 {
1280 auto visibility = [this, name](bool defaultvalue) {
1281 return hPref->GetBool(name.toStdString().c_str(), defaultvalue);
1282 };
1283
1284 auto saveVisibility = [this, visibility, name](bool value, ToolBarItem::DefaultVisibility policy) {
1285 auto show = visibility(policy == ToolBarItem::DefaultVisibility::Visible);
1286
1287 if (show != value) {
1288 blockRestore = true;
1289 hPref->SetBool(name.toStdString().c_str(), value);
1290 }
1291 };
1292
1293 auto showhide = [visibility](QToolBar* toolbar, ToolBarItem::DefaultVisibility policy) {
1294 auto show = visibility(policy == ToolBarItem::DefaultVisibility::Visible);
1295
1296 if (show) {
1297 toolbar->show();
1298 }
1299 else {
1300 toolbar->hide();
1301 }
1302 };
1303
1304 QToolBar* tb = findToolBar(toolBars(), name);
1305 if (tb) {
1306
1307 auto policy = getToolbarPolicy(tb);
1308
1309 if (state == State::RestoreDefault) {
1310 if (policy == ToolBarItem::DefaultVisibility::Unavailable) {
1311 tb->hide();
1312 tb->toggleViewAction()->setVisible(false);
1313 }
1314 else {
1315 tb->toggleViewAction()->setVisible(true);
1316
1317 showhide(tb, policy);
1318 }
1319 }
1320 else if (state == State::ForceAvailable) {
1321 tb->toggleViewAction()->setVisible(true);
1322
1323 // Unavailable policy defaults to a Visible toolbars when made available
1324 auto show = visibility(
1325 policy == ToolBarItem::DefaultVisibility::Visible
1326 || policy == ToolBarItem::DefaultVisibility::Unavailable
1327 );
1328
1329 if (show) {
1330 tb->show();
1331 }
1332 else {
1333 tb->hide();
1334 }
1335 }
1336 else if (state == State::ForceHidden) {
1337 tb->toggleViewAction()->setVisible(false); // not visible in context menus
1338 tb->hide(); // toolbar not visible
1339 }
1340 else if (state == State::SaveState) {
1341 auto show = tb->isVisible();
1342 saveVisibility(show, policy);
1343 }
1344 }
1345 }
1346
1347 #include "moc_ToolBarManager.cpp"