diff --git a/kdevplatform/sublime/container.cpp b/kdevplatform/sublime/container.cpp index ba16c5dc58..29942dd7b9 100644 --- a/kdevplatform/sublime/container.cpp +++ b/kdevplatform/sublime/container.cpp @@ -1,827 +1,827 @@ /*************************************************************************** * Copyright 2006-2009 Alexander Dymo * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "container.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "view.h" #include "urldocument.h" #include namespace Sublime { // class ContainerTabBar class ContainerTabBar : public QTabBar { Q_OBJECT public: explicit ContainerTabBar(Container* container) : QTabBar(container), m_container(container) { if (QApplication::style()->objectName() == QLatin1String("macintosh")) { static QPointer qTabBarStyle = QStyleFactory::create(QStringLiteral("fusion")); if (qTabBarStyle) { setStyle(qTabBarStyle); } } // configure the QTabBar style so it behaves as appropriately as possible, // even if we end up using the native Macintosh style because the user's // Qt doesn't have the Fusion style installed. setDocumentMode(true); setUsesScrollButtons(true); setElideMode(Qt::ElideNone); installEventFilter(this); } bool event(QEvent* ev) override { if(ev->type() == QEvent::ToolTip) { ev->accept(); auto* helpEvent = static_cast(ev); int tab = tabAt(helpEvent->pos()); if(tab != -1) { m_container->showTooltipForTab(tab); } return true; } return QTabBar::event(ev); } void mousePressEvent(QMouseEvent* event) override { if (event->button() == Qt::MidButton) { // just close on midbutton, drag can still be done with left mouse button int tab = tabAt(event->pos()); if (tab != -1) { emit tabCloseRequested(tab); } return; } QTabBar::mousePressEvent(event); } bool eventFilter(QObject* obj, QEvent* event) override { if (obj != this) { return QObject::eventFilter(obj, event); } // TODO Qt6: Move to mouseDoubleClickEvent when fixme in qttabbar.cpp is resolved // see "fixme Qt 6: move to mouseDoubleClickEvent(), here for BC reasons." in qtabbar.cpp if (event->type() == QEvent::MouseButtonDblClick) { // block tabBarDoubleClicked signals with RMB, see https://bugs.kde.org/show_bug.cgi?id=356016 auto mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::MidButton) { return true; } } return QObject::eventFilter(obj, event); } Q_SIGNALS: void newTabRequested(); private: Container* const m_container; }; bool sortViews(const View* const lhs, const View* const rhs) { return lhs->document()->title().compare(rhs->document()->title(), Qt::CaseInsensitive) < 0; } #ifdef Q_OS_MACOS // only one of these per process: static QMenu* currentDockMenu = nullptr; #endif class ContainerPrivate { public: QBoxLayout* layout; QHash viewForWidget; ContainerTabBar *tabBar; QStackedWidget *stack; KSqueezedTextLabel *fileNameCorner; QLabel *shortcutHelpLabel; QLabel *fileStatus; KSqueezedTextLabel *statusCorner; QPointer leftCornerWidget; QToolButton* documentListButton; QMenu* documentListMenu; QHash documentListActionForView; /** * Updates the context menu which is shown when * the document list button in the tab bar is clicked. * * It shall build a popup menu which contains all currently * enabled views using the title their document provides. */ void updateDocumentListPopupMenu() { qDeleteAll(documentListActionForView); documentListActionForView.clear(); documentListMenu->clear(); // create a lexicographically sorted list QVector views; views.reserve(viewForWidget.size()); for (View* view : qAsConst(viewForWidget)) { views << view; } std::sort(views.begin(), views.end(), sortViews); for (int i = 0; i < views.size(); ++i) { View *view = views.at(i); QString visibleEntryTitle; // if filename is not unique, prepend containing directory if ((i < views.size() - 1 && view->document()->title() == views.at(i + 1)->document()->title()) || (i > 0 && view->document()->title() == views.at(i - 1)->document()->title()) ) { auto urlDoc = qobject_cast(view->document()); if (!urlDoc) { visibleEntryTitle = view->document()->title(); } else { auto url = urlDoc->url().toString(); int secondOffset = url.lastIndexOf(QLatin1Char('/')); secondOffset = url.lastIndexOf(QLatin1Char('/'), secondOffset - 1); visibleEntryTitle = url.right(url.length() - url.lastIndexOf(QLatin1Char('/'), secondOffset) - 1); } } else { visibleEntryTitle = view->document()->title(); } QAction* action = documentListMenu->addAction(visibleEntryTitle); action->setData(QVariant::fromValue(view)); documentListActionForView[view] = action; action->setIcon(view->document()->icon()); ///FIXME: push this code somehow into shell, such that we can access the project model for /// icons and also get a neat, short path like the document switcher. } setAsDockMenu(); } void setAsDockMenu() { #ifdef Q_OS_MACOS if (documentListMenu != currentDockMenu) { documentListMenu->setAsDockMenu(); currentDockMenu = documentListMenu; } #endif } ~ContainerPrivate() { #ifdef Q_OS_MACOS if (documentListMenu == currentDockMenu) { QMenu().setAsDockMenu(); currentDockMenu = nullptr; } #endif } }; class UnderlinedLabel: public KSqueezedTextLabel { Q_OBJECT public: explicit UnderlinedLabel(QTabBar *tabBar, QWidget* parent = nullptr) :KSqueezedTextLabel(parent), m_tabBar(tabBar) { } protected: void paintEvent(QPaintEvent *ev) override { #ifndef Q_OS_OSX // getting the underlining right on OS X is tricky; omitting // the underlining attracts the eye less than not getting it // exactly right. if (m_tabBar->isVisible() && m_tabBar->count() > 0) { QStylePainter p(this); QStyleOptionTabBarBase optTabBase; optTabBase.init(m_tabBar); optTabBase.shape = m_tabBar->shape(); optTabBase.tabBarRect = m_tabBar->rect(); optTabBase.tabBarRect.moveRight(0); QStyleOptionTab tabOverlap; tabOverlap.shape = m_tabBar->shape(); int overlap = style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, &tabOverlap, m_tabBar); if( overlap > 0 ) { QRect rect; rect.setRect(0, height()-overlap, width(), overlap); optTabBase.rect = rect; } if( m_tabBar->drawBase() ) { p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase); } } #endif KSqueezedTextLabel::paintEvent(ev); } QTabBar *m_tabBar; }; class StatusLabel: public UnderlinedLabel { Q_OBJECT public: explicit StatusLabel(QTabBar *tabBar, QWidget* parent = nullptr): UnderlinedLabel(tabBar, parent) { setAlignment(Qt::AlignRight | Qt::AlignVCenter); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); } QSize minimumSizeHint() const override { QRect rect = style()->itemTextRect(fontMetrics(), QRect(), Qt::AlignRight, true, i18n("Line: 00000 Col: 000")); rect.setHeight(m_tabBar->height()); return rect.size(); } }; // class Container Container::Container(QWidget *parent) : QWidget(parent) , d_ptr(new ContainerPrivate()) { Q_D(Container); KAcceleratorManager::setNoAccel(this); auto *l = new QBoxLayout(QBoxLayout::TopToBottom, this); l->setMargin(0); l->setSpacing(0); d->layout = new QBoxLayout(QBoxLayout::LeftToRight); d->layout->setMargin(0); d->layout->setSpacing(0); d->documentListMenu = new QMenu(this); d->documentListButton = new QToolButton(this); d->documentListButton->setIcon(QIcon::fromTheme(QStringLiteral("format-list-unordered"))); d->documentListButton->setMenu(d->documentListMenu); #ifdef Q_OS_MACOS // for maintaining the Dock menu: setFocusPolicy(Qt::StrongFocus); #endif d->documentListButton->setPopupMode(QToolButton::InstantPopup); d->documentListButton->setAutoRaise(true); - d->documentListButton->setToolTip(i18n("Show sorted list of opened documents")); + d->documentListButton->setToolTip(i18nc("@info:tooltip", "Show sorted list of opened documents")); d->documentListButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); d->layout->addWidget(d->documentListButton); d->tabBar = new ContainerTabBar(this); d->tabBar->setContextMenuPolicy(Qt::CustomContextMenu); d->layout->addWidget(d->tabBar); d->fileStatus = new QLabel( this ); d->fileStatus->setFixedSize( QSize( 16, 16 ) ); d->layout->addWidget(d->fileStatus); d->fileNameCorner = new UnderlinedLabel(d->tabBar, this); d->fileNameCorner->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); d->layout->addWidget(d->fileNameCorner); - d->shortcutHelpLabel = new QLabel(i18n("(Press Ctrl+Tab to switch)"), this); + d->shortcutHelpLabel = new QLabel(i18nc("@info", "(Press Ctrl+Tab to switch)"), this); auto font = d->shortcutHelpLabel->font(); font.setPointSize(font.pointSize() - 2); font.setItalic(true); d->shortcutHelpLabel->setFont(font); d->layout->addSpacerItem(new QSpacerItem(style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), 0, QSizePolicy::Fixed, QSizePolicy::Fixed)); d->shortcutHelpLabel->setAlignment(Qt::AlignCenter); d->layout->addWidget(d->shortcutHelpLabel); d->layout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding)); d->statusCorner = new StatusLabel(d->tabBar, this); d->layout->addWidget(d->statusCorner); l->addLayout(d->layout); d->stack = new QStackedWidget(this); l->addWidget(d->stack); connect(d->tabBar, &ContainerTabBar::currentChanged, this, &Container::widgetActivated); connect(d->tabBar, &ContainerTabBar::tabCloseRequested, this, QOverload::of(&Container::requestClose)); connect(d->tabBar, &ContainerTabBar::newTabRequested, this, &Container::newTabRequested); connect(d->tabBar, &ContainerTabBar::tabMoved, this, &Container::tabMoved); connect(d->tabBar, &ContainerTabBar::customContextMenuRequested, this, &Container::contextMenu); connect(d->tabBar, &ContainerTabBar::tabBarDoubleClicked, this, &Container::doubleClickTriggered); connect(d->documentListMenu, &QMenu::triggered, this, &Container::documentListActionTriggered); setTabBarHidden(!configTabBarVisible()); d->tabBar->setTabsClosable(configCloseButtonsOnTabs()); d->tabBar->setMovable(true); d->tabBar->setExpanding(false); d->tabBar->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab); } Container::~Container() = default; bool Container::configTabBarVisible() { KConfigGroup group = KSharedConfig::openConfig()->group("UiSettings"); return group.readEntry("TabBarVisibility", 1); } bool Container::configCloseButtonsOnTabs() { KConfigGroup group = KSharedConfig::openConfig()->group("UiSettings"); return group.readEntry("CloseButtonsOnTabs", 1); } void Container::setLeftCornerWidget(QWidget* widget) { Q_D(Container); if(d->leftCornerWidget.data() == widget) { if(d->leftCornerWidget) d->leftCornerWidget.data()->setParent(nullptr); }else{ delete d->leftCornerWidget.data(); d->leftCornerWidget.clear(); } d->leftCornerWidget = widget; if(!widget) return; widget->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); d->layout->insertWidget(0, widget); widget->show(); } QList Container::views() const { Q_D(const Container); return d->viewForWidget.values(); } void Container::requestClose(int idx) { emit requestClose(widget(idx)); } void Container::widgetActivated(int idx) { Q_D(Container); if (idx < 0) return; if (QWidget* w = d->stack->widget(idx)) { Sublime::View* view = d->viewForWidget.value(w); if(view) emit activateView(view); } } void Container::addWidget(View *view, int position) { Q_D(Container); QWidget *w = view->widget(this); int idx = 0; if (position != -1) { idx = d->stack->insertWidget(position, w); } else idx = d->stack->addWidget(w); d->tabBar->insertTab(idx, view->document()->statusIcon(), view->document()->title()); Q_ASSERT(view); d->viewForWidget[w] = view; // Update document list context menu. This has to be called before // setCurrentWidget, because we call the status icon and title update slots // already, which in turn need the document list menu to be setup. d->updateDocumentListPopupMenu(); setCurrentWidget(d->stack->currentWidget()); // This fixes a strange layouting bug, that could be reproduced like this: Open a few files in KDevelop, activate the rightmost tab. // Then temporarily switch to another area, and then switch back. After that, the tab-bar was gone. // The problem could only be fixed by closing/opening another view. d->tabBar->setMinimumHeight(d->tabBar->sizeHint().height()); connect(view, &View::statusChanged, this, &Container::statusChanged); connect(view->document(), &Document::statusIconChanged, this, &Container::statusIconChanged); connect(view->document(), &Document::titleChanged, this, &Container::documentTitleChanged); } void Container::statusChanged(Sublime::View* view) { Q_D(Container); const auto statusText = view->viewStatus(); d->statusCorner->setText(statusText); d->statusCorner->setVisible(!statusText.isEmpty()); } void Container::statusIconChanged(Document* doc) { Q_D(Container); QHashIterator it = d->viewForWidget; while (it.hasNext()) { if (it.next().value()->document() == doc) { d->fileStatus->setPixmap( doc->statusIcon().pixmap( QSize( 16,16 ) ) ); int tabIndex = d->stack->indexOf(it.key()); if (tabIndex != -1) { d->tabBar->setTabIcon(tabIndex, doc->statusIcon()); } // Update the document title's menu associated action // using the View* index map Q_ASSERT(d->documentListActionForView.contains(it.value())); d->documentListActionForView[it.value()]->setIcon(doc->icon()); break; } } } void Container::documentTitleChanged(Sublime::Document* doc) { Q_D(Container); QHashIterator it = d->viewForWidget; while (it.hasNext()) { Sublime::View* view = it.next().value(); if (view->document() == doc) { if (currentView() == view) { d->fileNameCorner->setText( doc->title(Document::Extended) ); // TODO KF6: remove this as soon as it is included upstream and we reqire // that version // see https://phabricator.kde.org/D7010 d->fileNameCorner->updateGeometry(); } int tabIndex = d->stack->indexOf(it.key()); if (tabIndex != -1) { d->tabBar->setTabText(tabIndex, doc->title()); } break; } } // Update document list popup title d->updateDocumentListPopupMenu(); } int Container::count() const { Q_D(const Container); return d->stack->count(); } QWidget* Container::currentWidget() const { Q_D(const Container); return d->stack->currentWidget(); } void Container::setCurrentWidget(QWidget* w) { Q_D(Container); if (d->stack->currentWidget() == w) { return; } d->stack->setCurrentWidget(w); d->tabBar->setCurrentIndex(d->stack->indexOf(w)); if (View* view = viewForWidget(w)) { statusChanged(view); if (!d->tabBar->isVisible()) { // repaint icon and document title only in tabbar-less mode // tabbar will do repainting for us statusIconChanged( view->document() ); documentTitleChanged( view->document() ); } } } QWidget* Container::widget(int i) const { Q_D(const Container); return d->stack->widget(i); } int Container::indexOf(QWidget* w) const { Q_D(const Container); return d->stack->indexOf(w); } void Container::removeWidget(QWidget *w) { Q_D(Container); if (w) { int widgetIdx = d->stack->indexOf(w); d->stack->removeWidget(w); d->tabBar->removeTab(widgetIdx); if (d->tabBar->currentIndex() != -1 && !d->tabBar->isVisible()) { // repaint icon and document title only in tabbar-less mode // tabbar will do repainting for us View* view = currentView(); if( view ) { statusIconChanged( view->document() ); documentTitleChanged( view->document() ); } } View* view = d->viewForWidget.take(w); if (view) { disconnect(view->document(), &Document::titleChanged, this, &Container::documentTitleChanged); disconnect(view->document(), &Document::statusIconChanged, this, &Container::statusIconChanged); disconnect(view, &View::statusChanged, this, &Container::statusChanged); // Update document list context menu Q_ASSERT(d->documentListActionForView.contains(view)); delete d->documentListActionForView.take(view); } } } bool Container::hasWidget(QWidget* w) const { Q_D(const Container); return d->stack->indexOf(w) != -1; } View *Container::viewForWidget(QWidget *w) const { Q_D(const Container); return d->viewForWidget.value(w); } void Container::setTabBarHidden(bool hide) { Q_D(Container); if (hide) { d->tabBar->hide(); d->fileStatus->show(); d->shortcutHelpLabel->show(); d->fileNameCorner->show(); } else { d->fileNameCorner->hide(); d->fileStatus->hide(); d->tabBar->show(); d->shortcutHelpLabel->hide(); } View* v = currentView(); if (v) { documentTitleChanged(v->document()); } } void Container::setCloseButtonsOnTabs(bool show) { Q_D(Container); d->tabBar->setTabsClosable(show); } void Container::resetTabColors(const QColor& color) { Q_D(Container); for (int i = 0; i < count(); i++){ d->tabBar->setTabTextColor(i, color); } } void Container::setTabColor(const View* view, const QColor& color) { Q_D(Container); for (int i = 0; i < count(); i++){ if (view == viewForWidget(widget(i))) { d->tabBar->setTabTextColor(i, color); } } } void Container::setTabColors(const QHash& colors) { Q_D(Container); for (int i = 0; i < count(); i++) { auto view = viewForWidget(widget(i)); auto color = colors[view]; if (color.isValid()) { d->tabBar->setTabTextColor(i, color); } } } void Container::tabMoved(int from, int to) { Q_D(Container); QWidget *w = d->stack->widget(from); d->stack->removeWidget(w); d->stack->insertWidget(to, w); d->viewForWidget[w]->notifyPositionChanged(to); } void Container::contextMenu( const QPoint& pos ) { Q_D(Container); QWidget* senderWidget = qobject_cast(sender()); Q_ASSERT(senderWidget); int currentTab = d->tabBar->tabAt(pos); QMenu menu; // At least for positioning on Wayland the window the menu belongs to // needs to be set. We cannot set senderWidget as parent because some actions (e.g. split view) // result in sync destruction of the senderWidget, which then would also prematurely // destruct the menu object // Workaround (best known currently, check again API of Qt >5.9): menu.winId(); // trigger being a native widget already, to ensure windowHandle created auto parentWindowHandle = senderWidget->windowHandle(); if (!parentWindowHandle) { parentWindowHandle = senderWidget->nativeParentWidget()->windowHandle(); } menu.windowHandle()->setTransientParent(parentWindowHandle); Sublime::View* view = viewForWidget(widget(currentTab)); emit tabContextMenuRequested(view, &menu); menu.addSeparator(); QAction* copyPathAction = nullptr; QAction* closeTabAction = nullptr; QAction* closeOtherTabsAction = nullptr; if (view) { copyPathAction = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-copy")), - i18n("Copy Filename")); + i18nc("@action:inmenu", "Copy Filename")); menu.addSeparator(); closeTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("document-close")), - i18n("Close")); + i18nc("@action:inmenu", "Close")); closeOtherTabsAction = menu.addAction(QIcon::fromTheme(QStringLiteral("document-close")), - i18n("Close All Other")); + i18nc("@action:inmenu", "Close All Other")); } - QAction* closeAllTabsAction = menu.addAction(QIcon::fromTheme(QStringLiteral("document-close")), i18n("Close All")); + QAction* closeAllTabsAction = menu.addAction(QIcon::fromTheme(QStringLiteral("document-close")), i18nc("@action:inmenu", "Close All")); QAction* triggered = menu.exec(senderWidget->mapToGlobal(pos)); if (triggered) { if ( triggered == closeTabAction ) { requestClose(currentTab); } else if ( triggered == closeOtherTabsAction ) { // activate the remaining tab widgetActivated(currentTab); // first get the widgets to be closed since otherwise the indices will be wrong QList otherTabs; for ( int i = 0; i < count(); ++i ) { if ( i != currentTab ) { otherTabs << widget(i); } } // finally close other tabs for (QWidget* tab : qAsConst(otherTabs)) { emit requestClose(tab); } } else if ( triggered == closeAllTabsAction ) { // activate last tab widgetActivated(count() - 1); // close all for ( int i = 0; i < count(); ++i ) { emit requestClose(widget(i)); } } else if( triggered == copyPathAction ) { auto view = viewForWidget( widget( currentTab ) ); auto urlDocument = qobject_cast( view->document() ); if( urlDocument ) { QString toCopy = urlDocument->url().toDisplayString(QUrl::PreferLocalFile); if (urlDocument->url().isLocalFile()) { toCopy = QDir::toNativeSeparators(toCopy); } QApplication::clipboard()->setText(toCopy); } } // else the action was handled by someone else } } void Container::showTooltipForTab(int tab) { emit tabToolTipRequested(viewForWidget(widget(tab)), this, tab); } bool Container::isCurrentTab(int tab) const { Q_D(const Container); return d->tabBar->currentIndex() == tab; } QRect Container::tabRect(int tab) const { Q_D(const Container); return d->tabBar->tabRect(tab).translated(d->tabBar->mapToGlobal(QPoint(0, 0))); } void Container::doubleClickTriggered(int tab) { if (tab == -1) { emit newTabRequested(); } else { emit tabDoubleClicked(viewForWidget(widget(tab))); } } void Container::documentListActionTriggered(QAction* action) { Q_D(Container); auto* view = action->data().value< Sublime::View* >(); Q_ASSERT(view); QWidget* widget = d->viewForWidget.key(view); Q_ASSERT(widget); setCurrentWidget(widget); } Sublime::View* Container::currentView() const { Q_D(const Container); return d->viewForWidget.value(widget( d->tabBar->currentIndex() )); } void Container::focusInEvent(QFocusEvent* event) { Q_D(Container); d->setAsDockMenu(); QWidget::focusInEvent(event); } } #include "container.moc" diff --git a/kdevplatform/sublime/idealbuttonbarwidget.cpp b/kdevplatform/sublime/idealbuttonbarwidget.cpp index 89430e52b2..b779dac344 100644 --- a/kdevplatform/sublime/idealbuttonbarwidget.cpp +++ b/kdevplatform/sublime/idealbuttonbarwidget.cpp @@ -1,369 +1,369 @@ /* Copyright 2007 Roberto Raggi Copyright 2007 Hamish Rodda Copyright 2011 Alexander Dymo Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "idealbuttonbarwidget.h" #include "mainwindow.h" #include "idealdockwidget.h" #include "ideallayout.h" #include "idealtoolbutton.h" #include "document.h" #include "view.h" #include #include #include #include #include using namespace Sublime; class ToolViewAction : public QAction { Q_OBJECT public: ToolViewAction(IdealDockWidget *dock, QObject* parent) : QAction(parent), m_dock(dock) { setCheckable(true); const QString title = dock->view()->document()->title(); setIcon(dock->windowIcon()); - setToolTip(i18n("Toggle '%1' tool view.", title)); + setToolTip(i18nc("@info:tooltip", "Toggle '%1' tool view", title)); setText(title); //restore tool view shortcut config KConfigGroup config = KSharedConfig::openConfig()->group("UI"); QStringList shortcutStrings = config.readEntry(QStringLiteral("Shortcut for %1").arg(title), QStringList()); setShortcuts({ QKeySequence::fromString(shortcutStrings.value(0)), QKeySequence::fromString(shortcutStrings.value(1)) }); dock->setWindowTitle(title); dock->view()->widget()->installEventFilter(this); refreshText(); } IdealDockWidget *dockWidget() const { Q_ASSERT(m_dock); return m_dock; } IdealToolButton* button() { return m_button; } void setButton(IdealToolButton* button) { m_button = button; refreshText(); } QString id() { return m_dock->view()->document()->documentSpecifier(); } private: bool eventFilter(QObject * watched, QEvent * event) override { // an event may arrive when m_dock->view()->widget() is already destroyed // so check for event type first. if (event->type() == QEvent::EnabledChange && watched == m_dock->view()->widget()) { refreshText(); } return QObject::eventFilter(watched, event); } void refreshText() { const auto widget = m_dock->view()->widget(); const QString title = m_dock->view()->document()->title(); setText(widget->isEnabled() ? title : QStringLiteral("(%1)").arg(title)); } QPointer m_dock; QPointer m_button; }; IdealButtonBarWidget::IdealButtonBarWidget(Qt::DockWidgetArea area, IdealController *controller, Sublime::MainWindow *parent) : QWidget(parent) , m_area(area) , m_controller(controller) , m_corner(nullptr) , m_showState(false) , m_buttonsLayout(nullptr) { setContextMenuPolicy(Qt::CustomContextMenu); setToolTip(i18nc("@info:tooltip", "Right click to add new tool views.")); m_buttonsLayout = new IdealButtonBarLayout(orientation(), this); if (area == Qt::BottomDockWidgetArea) { auto *statusLayout = new QBoxLayout(QBoxLayout::LeftToRight, this); statusLayout->setMargin(0); statusLayout->addLayout(m_buttonsLayout); statusLayout->addStretch(1); m_corner = new QWidget(this); auto *cornerLayout = new QBoxLayout(QBoxLayout::LeftToRight, m_corner); cornerLayout->setMargin(0); cornerLayout->setSpacing(0); statusLayout->addWidget(m_corner); } else { auto *superLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); superLayout->setMargin(0); superLayout->addLayout(m_buttonsLayout); superLayout->addStretch(1); } } QAction* IdealButtonBarWidget::addWidget(IdealDockWidget *dock, Area *area, View *view) { if (m_area == Qt::BottomDockWidgetArea || m_area == Qt::TopDockWidgetArea) dock->setFeatures( dock->features() | IdealDockWidget::DockWidgetVerticalTitleBar ); dock->setArea(area); dock->setView(view); dock->setDockWidgetArea(m_area); auto action = new ToolViewAction(dock, this); addAction(action); return action; } QWidget* IdealButtonBarWidget::corner() const { return m_corner; } void IdealButtonBarWidget::addAction(QAction* qaction) { QWidget::addAction(qaction); auto action = qobject_cast(qaction); if (!action || action->button()) { return; } bool wasEmpty = isEmpty(); auto *button = new IdealToolButton(m_area); //apol: here we set the usual width of a button for the vertical toolbars as the minimumWidth //this is done because otherwise when we remove all the buttons and re-add new ones we get all //the screen flickering. This is solved by not defaulting to a smaller width when it's empty int w = button->sizeHint().width(); if (orientation() == Qt::Vertical && w > minimumWidth()) { setMinimumWidth(w); } action->setButton(button); button->setDefaultAction(action); Q_ASSERT(action->dockWidget()); connect(action, &QAction::toggled, this, QOverload::of(&IdealButtonBarWidget::showWidget)); connect(button, &IdealToolButton::customContextMenuRequested, action->dockWidget(), &IdealDockWidget::contextMenuRequested); addButtonToOrder(button); applyOrderToLayout(); if (wasEmpty) { emit emptyChanged(); } } void IdealButtonBarWidget::removeAction(QAction* widgetAction) { QWidget::removeAction(widgetAction); auto action = static_cast(widgetAction); action->button()->deleteLater(); delete action; if (m_buttonsLayout->isEmpty()) { emit emptyChanged(); } } bool IdealButtonBarWidget::isEmpty() const { return actions().isEmpty(); } bool IdealButtonBarWidget::isShown() const { const auto actions = this->actions(); return std::any_of(actions.cbegin(), actions.cend(), [](const QAction* action){ return action->isChecked(); }); } void IdealButtonBarWidget::saveShowState() { m_showState = isShown(); } bool IdealButtonBarWidget::lastShowState() { return m_showState; } QString IdealButtonBarWidget::id(const IdealToolButton* button) const { const auto actions = this->actions(); for (QAction* a : actions) { auto tva = qobject_cast(a); if (tva && tva->button() == button) { return tva->id(); } } return QString(); } IdealToolButton* IdealButtonBarWidget::button(const QString& id) const { const auto actions = this->actions(); for (QAction* a : actions) { auto tva = qobject_cast(a); if (tva && tva->id() == id) { return tva->button(); } } return nullptr; } void IdealButtonBarWidget::addButtonToOrder(const IdealToolButton* button) { QString buttonId = id(button); if (!m_buttonsOrder.contains(buttonId)) { m_buttonsOrder.push_back(buttonId); } } void IdealButtonBarWidget::loadOrderSettings(const KConfigGroup& configGroup) { m_buttonsOrder = configGroup.readEntry(QStringLiteral("(%1) Tool Views Order").arg(m_area), QStringList()); applyOrderToLayout(); } void IdealButtonBarWidget::saveOrderSettings(KConfigGroup& configGroup) { takeOrderFromLayout(); configGroup.writeEntry(QStringLiteral("(%1) Tool Views Order").arg(m_area), m_buttonsOrder); } bool IdealButtonBarWidget::isLocked() const { KConfigGroup config = KSharedConfig::openConfig()->group("UI"); return config.readEntry(QStringLiteral("Toolview Bar (%1) Is Locked").arg(m_area), false); } void IdealButtonBarWidget::applyOrderToLayout() { // If widget already have some buttons in the layout then calling loadOrderSettings() may leads // to situations when loaded order does not contains all existing buttons. Therefore we should // fix this with using addToOrder() method. for (int i = 0; i < m_buttonsLayout->count(); ++i) { if (auto button = qobject_cast(m_buttonsLayout->itemAt(i)->widget())) { addButtonToOrder(button); m_buttonsLayout->removeWidget(button); } } for (const QString& id : qAsConst(m_buttonsOrder)) { if (auto b = button(id)) { m_buttonsLayout->addWidget(b); } } } void IdealButtonBarWidget::takeOrderFromLayout() { m_buttonsOrder.clear(); for (int i = 0; i < m_buttonsLayout->count(); ++i) { if (auto button = qobject_cast(m_buttonsLayout->itemAt(i)->widget())) { m_buttonsOrder += id(button); } } } Qt::Orientation IdealButtonBarWidget::orientation() const { if (m_area == Qt::LeftDockWidgetArea || m_area == Qt::RightDockWidgetArea) return Qt::Vertical; return Qt::Horizontal; } Qt::DockWidgetArea IdealButtonBarWidget::area() const { return m_area; } void IdealButtonBarWidget::showWidget(bool checked) { Q_ASSERT(parentWidget() != nullptr); auto *action = qobject_cast(sender()); Q_ASSERT(action); showWidget(action, checked); } void IdealButtonBarWidget::showWidget(QAction *action, bool checked) { auto widgetAction = static_cast(action); IdealToolButton* button = widgetAction->button(); Q_ASSERT(button); if (checked) { if ( !QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ) { // Make sure only one widget is visible at any time. // The alternative to use a QActionCollection and setting that to "exclusive" // has a big drawback: QActions in a collection that is exclusive cannot // be un-checked by the user, e.g. in the View -> Tool Views menu. const auto actions = this->actions(); for (QAction* otherAction : actions) { if ( otherAction != widgetAction && otherAction->isChecked() ) otherAction->setChecked(false); } } m_controller->lastDockWidget[m_area] = widgetAction->dockWidget(); } m_controller->showDockWidget(widgetAction->dockWidget(), checked); widgetAction->setChecked(checked); button->setChecked(checked); } IdealDockWidget * IdealButtonBarWidget::widgetForAction(QAction *_action) const { return static_cast(_action)->dockWidget(); } #include "idealbuttonbarwidget.moc" diff --git a/kdevplatform/sublime/idealcontroller.cpp b/kdevplatform/sublime/idealcontroller.cpp index 00f441aeb0..e160b99248 100644 --- a/kdevplatform/sublime/idealcontroller.cpp +++ b/kdevplatform/sublime/idealcontroller.cpp @@ -1,516 +1,516 @@ /* Copyright 2007 Roberto Raggi Copyright 2007 Hamish Rodda Copyright 2011 Alexander Dymo Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "idealcontroller.h" #include #include #include #include #include #include #include #include "area.h" #include "view.h" #include "document.h" #include "mainwindow.h" #include "ideallayout.h" #include "idealdockwidget.h" #include "idealbuttonbarwidget.h" using namespace Sublime; IdealController::IdealController(Sublime::MainWindow* mainWindow): QObject(mainWindow), m_mainWindow(mainWindow) { leftBarWidget = new IdealButtonBarWidget(Qt::LeftDockWidgetArea, this, m_mainWindow); connect(leftBarWidget, &IdealButtonBarWidget::customContextMenuRequested, this, &IdealController::slotDockBarContextMenuRequested); rightBarWidget = new IdealButtonBarWidget(Qt::RightDockWidgetArea, this, m_mainWindow); connect(rightBarWidget, &IdealButtonBarWidget::customContextMenuRequested, this, &IdealController::slotDockBarContextMenuRequested); bottomBarWidget = new IdealButtonBarWidget(Qt::BottomDockWidgetArea, this, m_mainWindow); bottomStatusBarLocation = bottomBarWidget->corner(); connect(bottomBarWidget, &IdealButtonBarWidget::customContextMenuRequested, this, &IdealController::slotDockBarContextMenuRequested); topBarWidget = new IdealButtonBarWidget(Qt::TopDockWidgetArea, this, m_mainWindow); connect(topBarWidget, &IdealButtonBarWidget::customContextMenuRequested, this, &IdealController::slotDockBarContextMenuRequested); m_docks = qobject_cast(mainWindow->action("docks_submenu")); m_showLeftDock = m_mainWindow->action("show_left_dock"); m_showRightDock = m_mainWindow->action("show_right_dock"); m_showBottomDock = m_mainWindow->action("show_bottom_dock"); // the 'show top dock' action got removed (IOW, it's never created) // (let's keep this code around if we ever want to reintroduce the feature... m_showTopDock = m_mainWindow->action("show_top_dock"); connect(m_mainWindow, &MainWindow::settingsLoaded, this, &IdealController::loadSettings); } void IdealController::addView(Qt::DockWidgetArea area, View* view) { auto *dock = new IdealDockWidget(this, m_mainWindow); // dock object name is used to store tool view settings QString dockObjectName = view->document()->title(); // support different configuration for same docks opened in different areas if (m_mainWindow->area()) dockObjectName += QLatin1Char('_') + m_mainWindow->area()->objectName(); dock->setObjectName(dockObjectName); KAcceleratorManager::setNoAccel(dock); QWidget *w = view->widget(dock); if (w->parent() == nullptr) { /* Could happen when we're moving the widget from one IdealDockWidget to another. See moveView below. In this case, we need to reparent the widget. */ w->setParent(dock); } QList toolBarActions = view->toolBarActions(); if (toolBarActions.isEmpty()) { dock->setWidget(w); } else { auto* toolView = new QMainWindow(); auto *toolBar = new QToolBar(toolView); int iconSize = m_mainWindow->style()->pixelMetric(QStyle::PM_SmallIconSize); toolBar->setIconSize(QSize(iconSize, iconSize)); toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); - toolBar->setWindowTitle(i18n("%1 Toolbar", w->windowTitle())); + toolBar->setWindowTitle(i18nc("@title:window", "%1 Toolbar", w->windowTitle())); toolBar->setFloatable(false); toolBar->setMovable(false); toolBar->addActions(toolBarActions); toolView->setCentralWidget(w); toolView->setFocusProxy(w); toolView->addToolBar(toolBar); dock->setWidget(toolView); KConfigGroup cg(KSharedConfig::openConfig(), "UiSettings/Docks/ToolbarEnabled"); toolBar->setVisible(cg.readEntry(dockObjectName, true)); connect(toolBar->toggleViewAction(), &QAction::toggled, this, [toolBar, dockObjectName](){ KConfigGroup cg(KSharedConfig::openConfig(), "UiSettings/Docks/ToolbarEnabled"); cg.writeEntry(dockObjectName, toolBar->toggleViewAction()->isChecked()); }); } dock->setWindowTitle(view->widget()->windowTitle()); dock->setWindowIcon(view->widget()->windowIcon()); dock->setFocusProxy(dock->widget()); if (IdealButtonBarWidget* bar = barForDockArea(area)) { QAction* action = bar->addWidget(dock, static_cast(parent())->area(), view); m_dockwidget_to_action[dock] = m_view_to_action[view] = action; m_docks->addAction(action); connect(dock, &IdealDockWidget::closeRequested, action, &QAction::toggle); } connect(dock, &IdealDockWidget::dockLocationChanged, this, &IdealController::dockLocationChanged); dock->hide(); docks.insert(dock); } void IdealController::dockLocationChanged(Qt::DockWidgetArea area) { // Seems since Qt 5.13 the signal QDockWidget::dockLocationChanged is emitted also when the dock changes // to be floating, with area = Qt::NoDockWidgetArea. The current code is not designed for this, // so just ignore the signal in that case for now if (area == Qt::NoDockWidgetArea) { return; } auto *dock = qobject_cast(sender()); View *view = dock->view(); QAction* action = m_view_to_action.value(view); if (dock->dockWidgetArea() == area) { // this event can happen even when dock changes its location within the same area // usecases: // 1) user drags to the same area // 2) user rearranges tool views inside the same area // 3) state restoration shows the dock widget // in 3rd case we need to show dock if we don't want it to be shown // TODO: adymo: invent a better solution for the restoration problem if (!action->isChecked() && dock->isVisible()) { dock->hide(); } return; } if (IdealButtonBarWidget* bar = barForDockArea(dock->dockWidgetArea())) bar->removeAction(action); docks.insert(dock); if (IdealButtonBarWidget* bar = barForDockArea(area)) { QAction* action = bar->addWidget(dock, static_cast(parent())->area(), view); m_dockwidget_to_action[dock] = m_view_to_action[view] = action; // at this point the dockwidget is visible (user dragged it) // properly set up UI state bar->showWidget(action, true); // the dock should now be the "last" opened in a new area, not in the old area for (auto& dockWidgetPtr : lastDockWidget) { if (dockWidgetPtr.data() == dock) { dockWidgetPtr.clear(); } } lastDockWidget[area] = dock; // after drag, the tool view loses focus, so focus it again dock->setFocus(Qt::ShortcutFocusReason); m_docks->addAction(action); } if (area == Qt::BottomDockWidgetArea || area == Qt::TopDockWidgetArea) dock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | IdealDockWidget::DockWidgetVerticalTitleBar); else dock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable); } IdealButtonBarWidget* IdealController::barForDockArea(Qt::DockWidgetArea area) const { switch (area) { case Qt::LeftDockWidgetArea: return leftBarWidget; case Qt::TopDockWidgetArea: return topBarWidget; case Qt::RightDockWidgetArea: return rightBarWidget; case Qt::BottomDockWidgetArea: return bottomBarWidget; default: Q_ASSERT(false); return nullptr; } } void IdealController::slotDockBarContextMenuRequested(const QPoint& position) { auto* bar = qobject_cast(sender()); Q_ASSERT(bar); emit dockBarContextMenuRequested(bar->area(), bar->mapToGlobal(position)); } void IdealController::raiseView(View* view, RaiseMode mode) { /// @todo GroupWithOtherViews is disabled for now by forcing "mode = HideOtherViews". /// for the release of KDevelop 4.3. /// Reason: Inherent bugs which need significant changes to be fixed. /// Example: Open two equal tool views (for example 2x konsole), /// activate one, switch area, switch back, -> Both are active instead of one. /// The problem is that views are identified purely by their factory-id, which is equal /// for tool views of the same type. mode = HideOtherViews; QAction* action = m_view_to_action.value(view); Q_ASSERT(action); QWidget *focusWidget = m_mainWindow->focusWidget(); action->setProperty("raise", mode); action->setChecked(true); // TODO: adymo: hack: focus needs to stay inside the previously // focused widget (setChecked will focus the tool view) if (focusWidget) focusWidget->setFocus(Qt::ShortcutFocusReason); } QList< IdealDockWidget* > IdealController::allDockWidgets() const { return docks.values(); } void IdealController::showDockWidget(IdealDockWidget* dock, bool show) { Q_ASSERT(docks.contains(dock)); Qt::DockWidgetArea area = dock->dockWidgetArea(); if (show) { m_mainWindow->addDockWidget(area, dock); dock->show(); } else { m_mainWindow->removeDockWidget(dock); } setShowDockStatus(area, show); emit dockShown(dock->view(), Sublime::dockAreaToPosition(area), show); if (!show) // Put the focus back on the editor if a dock was hidden focusEditor(); else { // focus the dock dock->setFocus(Qt::ShortcutFocusReason); } } void IdealController::focusEditor() { if (View* view = m_mainWindow->activeView()) if (view->hasWidget()) view->widget()->setFocus(Qt::ShortcutFocusReason); } QWidget* IdealController::statusBarLocation() const { return bottomStatusBarLocation; } QAction* IdealController::actionForView(View* view) const { return m_view_to_action.value(view); } void IdealController::setShowDockStatus(Qt::DockWidgetArea area, bool checked) { QAction* action = actionForArea(area); if (action->isChecked() != checked) { QSignalBlocker blocker(action); action->setChecked(checked); } } QAction* IdealController::actionForArea(Qt::DockWidgetArea area) const { switch (area) { case Qt::LeftDockWidgetArea: default: return m_showLeftDock; case Qt::RightDockWidgetArea: return m_showRightDock; case Qt::TopDockWidgetArea: return m_showTopDock; case Qt::BottomDockWidgetArea: return m_showBottomDock; } } void IdealController::removeView(View* view, bool nondestructive) { Q_ASSERT(m_view_to_action.contains(view)); QAction* action = m_view_to_action.value(view); QWidget *viewParent = view->widget()->parentWidget(); auto *dock = qobject_cast(viewParent); if (!dock) { // tool views with a toolbar live in a QMainWindow which lives in a Dock Q_ASSERT(qobject_cast(viewParent)); viewParent = viewParent->parentWidget(); dock = qobject_cast(viewParent); } Q_ASSERT(dock); /* Hide the view, first. This is a workaround -- if we try to remove IdealDockWidget without this, then eventually a call to IdealMainLayout::takeAt will be made, which method asserts immediately. */ action->setChecked(false); if (IdealButtonBarWidget* bar = barForDockArea(dock->dockWidgetArea())) bar->removeAction(action); m_view_to_action.remove(view); m_dockwidget_to_action.remove(dock); if (nondestructive) view->widget()->setParent(nullptr); delete dock; } void IdealController::moveView(View *view, Qt::DockWidgetArea area) { removeView(view); addView(area, view); } void IdealController::showBottomDock(bool show) { showDock(Qt::BottomDockWidgetArea, show); } void IdealController::showLeftDock(bool show) { showDock(Qt::LeftDockWidgetArea, show); } void IdealController::showRightDock(bool show) { showDock(Qt::RightDockWidgetArea, show); } void IdealController::hideDocks(IdealButtonBarWidget *bar) { const auto barActions = bar->actions(); for (QAction* action : barActions) { if (action->isChecked()) action->setChecked(false); } focusEditor(); } void IdealController::showDock(Qt::DockWidgetArea area, bool show) { IdealButtonBarWidget *bar = barForDockArea(area); if (!bar) return; IdealDockWidget *lastDock = lastDockWidget[area].data(); if (lastDock && lastDock->isVisible() && !lastDock->hasFocus()) { lastDock->setFocus(Qt::ShortcutFocusReason); // re-sync action state given we may have asked for the dock to be hidden QAction* action = actionForArea(area); if (!action->isChecked()) { QSignalBlocker blocker(action); action->setChecked(true); } return; } if (!show) { hideDocks(bar); } else { // open the last opened tool view (or the first one) and focus it if (lastDock) { if (QAction *action = m_dockwidget_to_action.value(lastDock)) action->setChecked(show); lastDock->setFocus(Qt::ShortcutFocusReason); return; } if (!barForDockArea(area)->actions().isEmpty()) barForDockArea(area)->actions().first()->setChecked(show); } } // returns currently focused dock widget (if any) IdealDockWidget* IdealController::currentDockWidget() const { QWidget *w = m_mainWindow->focusWidget(); while (true) { if (!w) break; auto *dockCandidate = qobject_cast(w); if (dockCandidate) return dockCandidate; w = w->parentWidget(); } return nullptr; } void IdealController::goPrevNextDock(IdealController::Direction direction) { IdealDockWidget *currentDock = currentDockWidget(); if (!currentDock) return; IdealButtonBarWidget *bar = barForDockArea(currentDock->dockWidgetArea()); int index = bar->actions().indexOf(m_dockwidget_to_action.value(currentDock)); int step = (direction == NextDock) ? 1 : -1; if (bar->area() == Qt::BottomDockWidgetArea) step = -step; index += step; if (index < 0) index = bar->actions().count() - 1; if (index > bar->actions().count() - 1) index = 0; bar->actions().at(index)->setChecked(true); } void IdealController::toggleDocksShown() { bool anyBarShown = (leftBarWidget->isShown() && !leftBarWidget->isLocked()) || (bottomBarWidget->isShown() && !bottomBarWidget->isLocked()) || (rightBarWidget->isShown() && !rightBarWidget->isLocked()); if (anyBarShown) { leftBarWidget->saveShowState(); bottomBarWidget->saveShowState(); rightBarWidget->saveShowState(); } if (!leftBarWidget->isLocked()) toggleDocksShown(leftBarWidget, !anyBarShown && leftBarWidget->lastShowState()); if (!bottomBarWidget->isLocked()) toggleDocksShown(bottomBarWidget, !anyBarShown && bottomBarWidget->lastShowState()); if (!rightBarWidget->isLocked()) toggleDocksShown(rightBarWidget, !anyBarShown && rightBarWidget->lastShowState()); } void IdealController::toggleDocksShown(IdealButtonBarWidget* bar, bool show) { if (!show) { hideDocks(bar); } else { IdealDockWidget *lastDock = lastDockWidget[bar->area()].data(); if (lastDock) m_dockwidget_to_action[lastDock]->setChecked(true); } } void IdealController::loadSettings() { KConfigGroup cg(KSharedConfig::openConfig(), "UiSettings"); int bottomOwnsBottomLeft = cg.readEntry("BottomLeftCornerOwner", 0); if (bottomOwnsBottomLeft) m_mainWindow->setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); else m_mainWindow->setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); int bottomOwnsBottomRight = cg.readEntry("BottomRightCornerOwner", 0); if (bottomOwnsBottomRight) m_mainWindow->setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); else m_mainWindow->setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); } diff --git a/kdevplatform/sublime/idealdockwidget.cpp b/kdevplatform/sublime/idealdockwidget.cpp index 4e688cf419..9477b288a2 100644 --- a/kdevplatform/sublime/idealdockwidget.cpp +++ b/kdevplatform/sublime/idealdockwidget.cpp @@ -1,213 +1,213 @@ /* Copyright 2007 Roberto Raggi Copyright 2007 Hamish Rodda Copyright 2011 Alexander Dymo Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "idealdockwidget.h" #include "mainwindow.h" #include "area.h" #include "document.h" #include "view.h" #include #include #include #include #include #include #include #include #include using namespace Sublime; IdealDockWidget::IdealDockWidget(IdealController *controller, Sublime::MainWindow *parent) : QDockWidget(parent), m_area(nullptr), m_view(nullptr), m_docking_area(Qt::NoDockWidgetArea), m_controller(controller) { setAutoFillBackground(true); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, &IdealDockWidget::customContextMenuRequested, this, &IdealDockWidget::contextMenuRequested); auto *closeButton = findChild(QStringLiteral("qt_dockwidget_closebutton")); if (closeButton) { disconnect(closeButton, &QAbstractButton::clicked, nullptr, nullptr); connect(closeButton, &QAbstractButton::clicked, this, &IdealDockWidget::closeRequested); } setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); // do not allow to move docks to the top dock area (no buttonbar there in our current UI) setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea); } IdealDockWidget::~IdealDockWidget() { } Area *IdealDockWidget::area() const { return m_area; } void IdealDockWidget::setArea(Area *area) { m_area = area; } View *IdealDockWidget::view() const { return m_view; } void IdealDockWidget::setView(View *view) { m_view = view; } Qt::DockWidgetArea IdealDockWidget::dockWidgetArea() const { return m_docking_area; } void IdealDockWidget::setDockWidgetArea(Qt::DockWidgetArea dockingArea) { m_docking_area = dockingArea; } void IdealDockWidget::slotRemove() { m_area->removeToolView(m_view); } void IdealDockWidget::contextMenuRequested(const QPoint &point) { QWidget* senderWidget = qobject_cast(sender()); Q_ASSERT(senderWidget); QMenu menu; menu.addSection(windowIcon(), m_view->document()->title()); const QList viewActions = m_view->contextMenuActions(); if(!viewActions.isEmpty()) { // add the view's actions to the context menu, // checking each if it can be represented for (const auto action : viewActions) { if (!action->text().isEmpty() && !action->iconText().isEmpty()) { // avoid adding empty menu items menu.addAction(action); } } menu.addSeparator(); } ///TODO: can this be cleaned up? if(auto* toolBar = widget()->findChild()) { menu.addAction(toolBar->toggleViewAction()); menu.addSeparator(); } /// start position menu - QMenu* positionMenu = menu.addMenu(i18n("Tool View Position")); + QMenu* positionMenu = menu.addMenu(i18nc("@title:menu", "Tool View Position")); auto* g = new QActionGroup(positionMenu); - auto* left = new QAction(i18nc("tool view position", "Left"), g); - auto* bottom = new QAction(i18nc("tool view position", "Bottom"), g); - auto* right = new QAction(i18nc("tool view position", "Right"), g); - auto* detach = new QAction(i18nc("tool view position", "Detached"), g); + auto* left = new QAction(i18nc("@option:radio tool view position", "Left"), g); + auto* bottom = new QAction(i18nc("@option:radio tool view position", "Bottom"), g); + auto* right = new QAction(i18nc("@option:radio tool view position", "Right"), g); + auto* detach = new QAction(i18nc("@option:radio tool view position", "Detached"), g); for (auto action : {left, bottom, right, detach}) { positionMenu->addAction(action); action->setCheckable(true); } if (isFloating()) { detach->setChecked(true); } else if (m_docking_area == Qt::BottomDockWidgetArea) bottom->setChecked(true); else if (m_docking_area == Qt::LeftDockWidgetArea) left->setChecked(true); else if (m_docking_area == Qt::RightDockWidgetArea) right->setChecked(true); /// end position menu menu.addSeparator(); - QAction *setShortcut = menu.addAction(QIcon::fromTheme(QStringLiteral("configure-shortcuts")), i18n("Assign Shortcut...")); - setShortcut->setToolTip(i18n("Use this shortcut to trigger visibility of the tool view.")); + QAction *setShortcut = menu.addAction(QIcon::fromTheme(QStringLiteral("configure-shortcuts")), i18nc("@action:inmenu", "Assign Shortcut...")); + setShortcut->setToolTip(i18nc("@info:tooltip", "Use this shortcut to trigger visibility of the tool view.")); menu.addSeparator(); - QAction* remove = menu.addAction(QIcon::fromTheme(QStringLiteral("dialog-close")), i18n("Remove Tool View")); + QAction* remove = menu.addAction(QIcon::fromTheme(QStringLiteral("dialog-close")), i18nc("@action:inmenu", "Remove Tool View")); QAction* triggered = menu.exec(senderWidget->mapToGlobal(point)); if (triggered) { if ( triggered == remove ) { slotRemove(); return; } else if ( triggered == setShortcut ) { auto* dialog = new QDialog(this); - dialog->setWindowTitle(i18n("Assign Shortcut For '%1' Tool View", m_view->document()->title())); + dialog->setWindowTitle(i18nc("@title:window", "Assign Shortcut For '%1' Tool View", m_view->document()->title())); auto *w = new KShortcutWidget(dialog); w->setShortcut(m_controller->actionForView(m_view)->shortcuts()); auto* dialogLayout = new QVBoxLayout(dialog); dialogLayout->addWidget(w); auto* buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ); dialogLayout->addWidget(buttonBox); connect(buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::reject); if (dialog->exec() == QDialog::Accepted) { m_controller->actionForView(m_view)->setShortcuts(w->shortcut()); //save shortcut config KConfigGroup config = KSharedConfig::openConfig()->group("UI"); const QStringList shortcuts{ w->shortcut().value(0).toString(), w->shortcut().value(1).toString(), }; config.writeEntry(QStringLiteral("Shortcut for %1").arg(m_view->document()->title()), shortcuts); config.sync(); } delete dialog; return; } else if ( triggered == detach ) { setFloating(true); m_area->raiseToolView(m_view); return; } if (isFloating()) { setFloating(false); } Sublime::Position pos; if (triggered == left) pos = Sublime::Left; else if (triggered == bottom) pos = Sublime::Bottom; else if (triggered == right) pos = Sublime::Right; else return; Area *area = m_area; View *view = m_view; /* This call will delete *this, so we no longer can access member variables. */ m_area->moveToolView(m_view, pos); area->raiseToolView(view); } } diff --git a/kdevplatform/sublime/mainwindow_p.cpp b/kdevplatform/sublime/mainwindow_p.cpp index c575dfa9f5..5cb4c89266 100644 --- a/kdevplatform/sublime/mainwindow_p.cpp +++ b/kdevplatform/sublime/mainwindow_p.cpp @@ -1,855 +1,855 @@ /*************************************************************************** * Copyright 2006-2009 Alexander Dymo * * Copyright 2012 Dominik Haumann * * Copyright 2020 Friedrich W. H. Kossebau * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "mainwindow_p.h" #include #include #include #include #include #include #include #include #include #include "area.h" #include "view.h" #include "areaindex.h" #include "document.h" #include "container.h" #include "controller.h" #include "mainwindow.h" #include "viewbarcontainer.h" #include "idealcontroller.h" #include "holdupdates.h" #include "idealbuttonbarwidget.h" #include "message.h" #include "messagewidget.h" #include class IdealToolBar : public QToolBar { Q_OBJECT public: explicit IdealToolBar(const QString& title, bool hideWhenEmpty, Sublime::IdealButtonBarWidget* buttons, QMainWindow* parent) : QToolBar(title, parent) , m_buttons(buttons) , m_hideWhenEmpty(hideWhenEmpty) { setMovable(false); setFloatable(false); setObjectName(title); layout()->setMargin(0); addWidget(m_buttons); if (m_hideWhenEmpty) { connect(m_buttons, &Sublime::IdealButtonBarWidget::emptyChanged, this, &IdealToolBar::updateVisibilty); } } private Q_SLOTS: void updateVisibilty() { setVisible(!m_buttons->isEmpty()); } private: Sublime::IdealButtonBarWidget* const m_buttons; const bool m_hideWhenEmpty; }; namespace Sublime { MainWindowPrivate::MainWindowPrivate(MainWindow *w, Controller* controller) :controller(controller), area(nullptr), activeView(nullptr), activeToolView(nullptr), bgCentralWidget(nullptr), ignoreDockShown(false), autoAreaSettingsSave(false), m_mainWindow(w) { KActionCollection *ac = m_mainWindow->actionCollection(); - m_concentrationModeAction = new QAction(i18n("Concentration Mode"), this); + m_concentrationModeAction = new QAction(i18nc("@option:check", "Concentration Mode"), this); m_concentrationModeAction->setIcon(QIcon::fromTheme(QStringLiteral("page-zoom"))); - m_concentrationModeAction->setToolTip(i18n("Removes most of the controls so you can focus on what matters.")); + m_concentrationModeAction->setToolTip(i18nc("@info:tooltip", "Remove most of the controls so you can focus on what matters")); m_concentrationModeAction->setCheckable(true); m_concentrationModeAction->setChecked(false); ac->setDefaultShortcut(m_concentrationModeAction, Qt::META | Qt::Key_C); connect(m_concentrationModeAction, &QAction::toggled, this, &MainWindowPrivate::restoreConcentrationMode); ac->addAction(QStringLiteral("toggle_concentration_mode"), m_concentrationModeAction); - auto* action = new QAction(i18n("Show Left Dock"), this); + auto* action = new QAction(i18nc("@option:check", "Show Left Dock"), this); action->setCheckable(true); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_Left); connect(action, &QAction::toggled, this, &MainWindowPrivate::showLeftDock); ac->addAction(QStringLiteral("show_left_dock"), action); - action = new QAction(i18n("Show Right Dock"), this); + action = new QAction(i18nc("@option:check", "Show Right Dock"), this); action->setCheckable(true); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_Right); connect(action, &QAction::toggled, this, &MainWindowPrivate::showRightDock); ac->addAction(QStringLiteral("show_right_dock"), action); - action = new QAction(i18n("Show Bottom Dock"), this); + action = new QAction(i18nc("@option:check", "Show Bottom Dock"), this); action->setCheckable(true); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_Down); connect(action, &QAction::toggled, this, &MainWindowPrivate::showBottomDock); ac->addAction(QStringLiteral("show_bottom_dock"), action); action = new QAction(i18nc("@action", "Focus Editor"), this); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_E); connect(action, &QAction::triggered, this, &MainWindowPrivate::focusEditor); ac->addAction(QStringLiteral("focus_editor"), action); - action = new QAction(i18n("Hide/Restore Docks"), this); + action = new QAction(i18nc("@action", "Hide/Restore Docks"), this); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_Up); connect(action, &QAction::triggered, this, &MainWindowPrivate::toggleDocksShown); ac->addAction(QStringLiteral("hide_all_docks"), action); - action = new QAction(i18n("Next Tool View"), this); + action = new QAction(i18nc("@action", "Next Tool View"), this); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_N); action->setIcon(QIcon::fromTheme(QStringLiteral("go-next"))); connect(action, &QAction::triggered, this, &MainWindowPrivate::selectNextDock); ac->addAction(QStringLiteral("select_next_dock"), action); - action = new QAction(i18n("Previous Tool View"), this); + action = new QAction(i18nc("@action", "Previous Tool View"), this); ac->setDefaultShortcut(action, Qt::META | Qt::CTRL | Qt::Key_P); action->setIcon(QIcon::fromTheme(QStringLiteral("go-previous"))); connect(action, &QAction::triggered, this, &MainWindowPrivate::selectPreviousDock); ac->addAction(QStringLiteral("select_previous_dock"), action); - action = new KActionMenu(i18n("Tool Views"), this); + action = new KActionMenu(i18nc("@title:menu", "Tool Views"), this); ac->addAction(QStringLiteral("docks_submenu"), action); idealController = new IdealController(m_mainWindow); m_leftToolBar = new IdealToolBar(i18n("Left Button Bar"), true, idealController->leftBarWidget, m_mainWindow); m_mainWindow->addToolBar(Qt::LeftToolBarArea, m_leftToolBar); m_rightToolBar = new IdealToolBar(i18n("Right Button Bar"), true, idealController->rightBarWidget, m_mainWindow); m_mainWindow->addToolBar(Qt::RightToolBarArea, m_rightToolBar); m_bottomToolBar = new IdealToolBar(i18n("Bottom Button Bar"), false, idealController->bottomBarWidget, m_mainWindow); m_mainWindow->addToolBar(Qt::BottomToolBarArea, m_bottomToolBar); // adymo: intentionally do not add a toolbar for top buttonbar // this doesn't work well with toolbars added via xmlgui centralWidget = new QWidget; centralWidget->setObjectName(QStringLiteral("centralWidget")); auto* layout = new QVBoxLayout(centralWidget); layout->setMargin(0); centralWidget->setLayout(layout); messageWidget = new MessageWidget(); layout->addWidget(messageWidget); splitterCentralWidget = new QSplitter(centralWidget); // take as much space as possible splitterCentralWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); layout->addWidget(splitterCentralWidget, 2); // this view bar container is used for the ktexteditor integration to show // all view bars at a central place, esp. for split view configurations viewBarContainer = new ViewBarContainer; viewBarContainer->setObjectName(QStringLiteral("viewBarContainer")); // hide by default viewBarContainer->setVisible(false); // only take as much as needed viewBarContainer->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); layout->addWidget(viewBarContainer); m_mainWindow->setCentralWidget(centralWidget); connect(idealController, &IdealController::dockShown, this, &MainWindowPrivate::slotDockShown); connect(idealController, &IdealController::dockBarContextMenuRequested, m_mainWindow, &MainWindow::dockBarContextMenuRequested); } MainWindowPrivate::~MainWindowPrivate() { // create working copy as messages are auto-removing themselves from the hash on destruction const auto messages = m_messageHash.keys(); qDeleteAll(messages); delete m_leftTabbarCornerWidget.data(); m_leftTabbarCornerWidget.clear(); } void MainWindowPrivate::disableConcentrationMode() { m_concentrationModeAction->setChecked(false); restoreConcentrationMode(); } void MainWindowPrivate::restoreConcentrationMode() { const bool concentrationModeOn = m_concentrationModeAction->isChecked(); QWidget* cornerWidget = nullptr; if (m_concentrateToolBar) { QLayout* l = m_concentrateToolBar->layout(); QLayoutItem* li = l->takeAt(1); //ensure the cornerWidget isn't destroyed with the toolbar if (li) { cornerWidget = li->widget(); delete li; } m_concentrateToolBar->deleteLater(); } m_mainWindow->menuBar()->setVisible(!concentrationModeOn); m_bottomToolBar->setVisible(!concentrationModeOn); m_leftToolBar->setVisible(!concentrationModeOn); m_rightToolBar->setVisible(!concentrationModeOn); if (concentrationModeOn) { m_concentrateToolBar = new QToolBar(m_mainWindow); m_concentrateToolBar->setObjectName(QStringLiteral("concentrateToolBar")); m_concentrateToolBar->addAction(m_concentrationModeAction); m_concentrateToolBar->toggleViewAction()->setVisible(false); auto *action = new QWidgetAction(this); action->setDefaultWidget(m_mainWindow->menuBar()->cornerWidget(Qt::TopRightCorner)); m_concentrateToolBar->addAction(action); m_concentrateToolBar->setMovable(false); m_mainWindow->addToolBar(Qt::TopToolBarArea, m_concentrateToolBar); m_mainWindow->menuBar()->setCornerWidget(nullptr, Qt::TopRightCorner); } else if (cornerWidget) { m_mainWindow->menuBar()->setCornerWidget(cornerWidget, Qt::TopRightCorner); cornerWidget->show(); } if (concentrationModeOn) { m_mainWindow->installEventFilter(this); } else { m_mainWindow->removeEventFilter(this); } } bool MainWindowPrivate::eventFilter(QObject* obj, QEvent* event) { Q_ASSERT(m_mainWindow == obj); if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { const auto ev = static_cast(event); Qt::KeyboardModifiers modifiers = ev->modifiers(); //QLineEdit banned mostly so that alt navigation can be used from QuickOpen const bool visible = modifiers == Qt::AltModifier && ev->type() == QEvent::KeyPress && !qApp->focusWidget()->inherits("QLineEdit"); m_mainWindow->menuBar()->setVisible(visible); } return false; } void MainWindowPrivate::showLeftDock(bool b) { idealController->showLeftDock(b); } void MainWindowPrivate::showBottomDock(bool b) { idealController->showBottomDock(b); } void MainWindowPrivate::showRightDock(bool b) { idealController->showRightDock(b); } void MainWindowPrivate::setBackgroundCentralWidget(QWidget* w) { delete bgCentralWidget; bgCentralWidget = w; if (bgCentralWidget) { auto* l = static_cast(centralWidget->layout()); l->addWidget(bgCentralWidget, 2); setBackgroundVisible(area->views().isEmpty()); } } void MainWindowPrivate::setBackgroundVisible(bool v) { if(!bgCentralWidget) return; bgCentralWidget->setVisible(v); splitterCentralWidget->setVisible(!v); } void MainWindowPrivate::focusEditor() { if (View* view = m_mainWindow->activeView()) if (view->hasWidget()) view->widget()->setFocus(Qt::ShortcutFocusReason); } void MainWindowPrivate::toggleDocksShown() { idealController->toggleDocksShown(); } void MainWindowPrivate::selectNextDock() { idealController->goPrevNextDock(IdealController::NextDock); } void MainWindowPrivate::selectPreviousDock() { idealController->goPrevNextDock(IdealController::PrevDock); } Area::WalkerMode MainWindowPrivate::IdealToolViewCreator::operator() (View *view, Sublime::Position position) { if (!d->docks.contains(view)) { d->docks << view; //add view d->idealController->addView(d->positionToDockArea(position), view); } return Area::ContinueWalker; } Area::WalkerMode MainWindowPrivate::ViewCreator::operator() (AreaIndex *index) { QSplitter *splitter = d->m_indexSplitters.value(index); if (!splitter) { //no splitter - we shall create it and populate with views if (!index->parent()) { qCDebug(SUBLIME) << "reconstructing root area"; //this is root area splitter = d->splitterCentralWidget; d->m_indexSplitters[index] = splitter; } else { if (!d->m_indexSplitters.value(index->parent())) { // can happen in working set code, as that adds a view to a child index first // hence, recursively reconstruct the parent indices first operator()(index->parent()); } QSplitter *parent = d->m_indexSplitters.value(index->parent()); splitter = new QSplitter(parent); d->m_indexSplitters[index] = splitter; if(index == index->parent()->first()) parent->insertWidget(0, splitter); else parent->addWidget(splitter); } Q_ASSERT(splitter); } if (index->isSplit()) //this is a visible splitter splitter->setOrientation(index->orientation()); else { Container *container = nullptr; while(splitter->count() && qobject_cast(splitter->widget(0))) { // After unsplitting, we might have to remove old splitters QWidget* widget = splitter->widget(0); qCDebug(SUBLIME) << "deleting" << widget; widget->setParent(nullptr); delete widget; } if (!splitter->widget(0)) { //we need to create view container container = new Container(splitter); connect(container, &Container::activateView, d->m_mainWindow, &MainWindow::activateViewAndFocus); connect(container, &Container::tabDoubleClicked, d->m_mainWindow, &MainWindow::tabDoubleClicked); connect(container, &Container::tabContextMenuRequested, d->m_mainWindow, &MainWindow::tabContextMenuRequested); connect(container, &Container::tabToolTipRequested, d->m_mainWindow, &MainWindow::tabToolTipRequested); connect(container, QOverload::of(&Container::requestClose), d, &MainWindowPrivate::widgetCloseRequest, Qt::QueuedConnection); connect(container, &Container::newTabRequested, d->m_mainWindow, &MainWindow::newTabRequested); splitter->addWidget(container); } else container = qobject_cast(splitter->widget(0)); container->show(); int position = 0; bool hadActiveView = false; Sublime::View* activeView = d->activeView; for (View* view : qAsConst(index->views())) { QWidget *widget = view->widget(container); if (widget) { if(!container->hasWidget(widget)) { container->addWidget(view, position); d->viewContainers[view] = container; d->widgetToView[widget] = view; } if(activeView == view) { hadActiveView = true; container->setCurrentWidget(widget); }else if(topViews.contains(view) && !hadActiveView) container->setCurrentWidget(widget); } position++; } } return Area::ContinueWalker; } void MainWindowPrivate::reconstructViews(const QList& topViews) { ViewCreator viewCreator(this, topViews); area->walkViews(viewCreator, area->rootIndex()); setBackgroundVisible(area->views().isEmpty()); } void MainWindowPrivate::reconstruct() { if(m_leftTabbarCornerWidget) { m_leftTabbarCornerWidget->hide(); m_leftTabbarCornerWidget->setParent(nullptr); } IdealToolViewCreator toolViewCreator(this); area->walkToolViews(toolViewCreator, Sublime::AllPositions); reconstructViews(); { QSignalBlocker blocker(m_mainWindow); qCDebug(SUBLIME) << "RECONSTRUCT" << area << area->shownToolViews(Sublime::Left); for (View* view : qAsConst(area->toolViews())) { QString id = view->document()->documentSpecifier(); if (!id.isEmpty()) { Sublime::Position pos = area->toolViewPosition(view); if (area->shownToolViews(pos).contains(id)) idealController->raiseView(view, IdealController::GroupWithOtherViews); } } } setTabBarLeftCornerWidget(m_leftTabbarCornerWidget.data()); } void MainWindowPrivate::clearArea() { if(m_leftTabbarCornerWidget) m_leftTabbarCornerWidget->setParent(nullptr); //reparent tool view widgets to nullptr to prevent their deletion together with dockwidgets for (View* view : qAsConst(area->toolViews())) { // FIXME should we really delete here?? bool nonDestructive = true; idealController->removeView(view, nonDestructive); if (view->hasWidget()) view->widget()->setParent(nullptr); } docks.clear(); //reparent all view widgets to 0 to prevent their deletion together with central //widget. this reparenting is necessary when switching areas inside the same mainwindow const auto views = area->views(); for (View* view : views) { if (view->hasWidget()) view->widget()->setParent(nullptr); } cleanCentralWidget(); m_mainWindow->setActiveView(nullptr); m_indexSplitters.clear(); area = nullptr; viewContainers.clear(); setTabBarLeftCornerWidget(m_leftTabbarCornerWidget.data()); } void MainWindowPrivate::cleanCentralWidget() { while(splitterCentralWidget->count()) delete splitterCentralWidget->widget(0); setBackgroundVisible(true); } struct ShownToolViewFinder { ShownToolViewFinder() {} Area::WalkerMode operator()(View *v, Sublime::Position /*position*/) { if (v->hasWidget() && v->widget()->isVisible()) views << v; return Area::ContinueWalker; } QList views; }; void MainWindowPrivate::slotDockShown(Sublime::View* /*view*/, Sublime::Position pos, bool /*shown*/) { if (ignoreDockShown) return; ShownToolViewFinder finder; m_mainWindow->area()->walkToolViews(finder, pos); QStringList ids; ids.reserve(finder.views.size()); for (View* v : qAsConst(finder.views)) { ids << v->document()->documentSpecifier(); } area->setShownToolViews(pos, ids); } void MainWindowPrivate::viewRemovedInternal(AreaIndex* index, View* view) { Q_UNUSED(index); Q_UNUSED(view); setBackgroundVisible(area->views().isEmpty()); } void MainWindowPrivate::viewAdded(Sublime::AreaIndex *index, Sublime::View *view) { if(m_leftTabbarCornerWidget) { m_leftTabbarCornerWidget->hide(); m_leftTabbarCornerWidget->setParent(nullptr); } // Remove container objects in the hierarchy from the parents, // because they are not needed anymore, and might lead to broken splitter hierarchy and crashes. for(Sublime::AreaIndex* current = index; current; current = current->parent()) { QSplitter *splitter = m_indexSplitters[current]; if (current->isSplit() && splitter) { // Also update the orientation splitter->setOrientation(current->orientation()); for(int w = 0; w < splitter->count(); ++w) { auto *container = qobject_cast(splitter->widget(w)); //we need to remove extra container before reconstruction //first reparent widgets in container so that they are not deleted if(container) { while (container->count()) { container->widget(0)->setParent(nullptr); } //and then delete the container delete container; } } } } ViewCreator viewCreator(this); area->walkViews(viewCreator, index); emit m_mainWindow->viewAdded( view ); setTabBarLeftCornerWidget(m_leftTabbarCornerWidget.data()); setBackgroundVisible(false); } void Sublime::MainWindowPrivate::raiseToolView(Sublime::View * view) { idealController->raiseView(view); } void MainWindowPrivate::aboutToRemoveView(Sublime::AreaIndex *index, Sublime::View *view) { QSplitter *splitter = m_indexSplitters[index]; if (!splitter) return; qCDebug(SUBLIME) << "index " << index << " root " << area->rootIndex(); qCDebug(SUBLIME) << "splitter " << splitter << " container " << splitter->widget(0); qCDebug(SUBLIME) << "structure: " << index->print() << " whole structure: " << area->rootIndex()->print(); //find the container for the view and remove the widget auto *container = qobject_cast(splitter->widget(0)); if (!container) { qCWarning(SUBLIME) << "Splitter does not have a left widget!"; return; } emit m_mainWindow->aboutToRemoveView( view ); if (view->widget()) widgetToView.remove(view->widget()); viewContainers.remove(view); const bool wasActive = m_mainWindow->activeView() == view; if (container->count() > 1) { //container is not empty or this is a root index //just remove a widget if( view->widget() ) { container->removeWidget(view->widget()); view->widget()->setParent(nullptr); //activate what is visible currently in the container if the removed view was active if (wasActive) { m_mainWindow->setActiveView(container->viewForWidget(container->currentWidget())); return; } } } else { if(m_leftTabbarCornerWidget) { m_leftTabbarCornerWidget->hide(); m_leftTabbarCornerWidget->setParent(nullptr); } // We've about to remove the last view of this container. It will // be empty, so have to delete it, as well. // If we have a container, then it should be the only child of // the splitter. Q_ASSERT(splitter->count() == 1); container->removeWidget(view->widget()); if (view->widget()) view->widget()->setParent(nullptr); else qCWarning(SUBLIME) << "View does not have a widget!"; Q_ASSERT(container->count() == 0); // We can be called from signal handler of container // (which is tab widget), so defer deleting it. container->deleteLater(); container->setParent(nullptr); /* If we're not at the top level, we get to collapse split views. */ if (index->parent()) { /* The splitter used to have container as the only child, now it's time to get rid of it. Make sure deleting splitter does not delete container -- per above comment, we'll delete it later. */ container->setParent(nullptr); m_indexSplitters.remove(index); delete splitter; AreaIndex *parent = index->parent(); QSplitter *parentSplitter = m_indexSplitters[parent]; AreaIndex *sibling = parent->first() == index ? parent->second() : parent->first(); QSplitter *siblingSplitter = m_indexSplitters[sibling]; if(siblingSplitter) { HoldUpdates du(parentSplitter); //save sizes and orientation of the sibling splitter parentSplitter->setOrientation(siblingSplitter->orientation()); QList sizes = siblingSplitter->sizes(); /* Parent has two children -- 'index' that we've deleted and 'sibling'. We move all children of 'sibling' into parent, and delete 'sibling'. sibling either contains a single Container instance, or a bunch of further QSplitters. */ while (siblingSplitter->count() > 0) { //reparent contents into parent splitter QWidget *siblingWidget = siblingSplitter->widget(0); siblingWidget->setParent(parentSplitter); parentSplitter->addWidget(siblingWidget); } m_indexSplitters.remove(sibling); delete siblingSplitter; parentSplitter->setSizes(sizes); } qCDebug(SUBLIME) << "after deletion " << parent << " has " << parentSplitter->count() << " elements"; //find the container somewhere to activate auto *containerToActivate = parentSplitter->findChild(); //activate the current view there if (containerToActivate) { m_mainWindow->setActiveView(containerToActivate->viewForWidget(containerToActivate->currentWidget())); setTabBarLeftCornerWidget(m_leftTabbarCornerWidget.data()); return; } } } setTabBarLeftCornerWidget(m_leftTabbarCornerWidget.data()); if ( wasActive ) { m_mainWindow->setActiveView(nullptr); } } void MainWindowPrivate::toolViewAdded(Sublime::View* /*toolView*/, Sublime::Position position) { IdealToolViewCreator toolViewCreator(this); area->walkToolViews(toolViewCreator, position); } void MainWindowPrivate::aboutToRemoveToolView(Sublime::View *toolView, Sublime::Position /*position*/) { if (!docks.contains(toolView)) return; idealController->removeView(toolView); // TODO are Views unique? docks.removeAll(toolView); } void MainWindowPrivate::toolViewMoved( Sublime::View *toolView, Sublime::Position position) { if (!docks.contains(toolView)) return; idealController->moveView(toolView, positionToDockArea(position)); } Qt::DockWidgetArea MainWindowPrivate::positionToDockArea(Position position) { switch (position) { case Sublime::Left: return Qt::LeftDockWidgetArea; case Sublime::Right: return Qt::RightDockWidgetArea; case Sublime::Bottom: return Qt::BottomDockWidgetArea; case Sublime::Top: return Qt::TopDockWidgetArea; default: return Qt::LeftDockWidgetArea; } } void MainWindowPrivate::updateAreaSwitcher(Sublime::Area *area) { QAction* action = m_areaActions.value(area); if (action) action->setChecked(true); } void MainWindowPrivate::activateFirstVisibleView() { QList views = area->views(); if (views.count() > 0) m_mainWindow->activateView(views.first()); } void MainWindowPrivate::widgetCloseRequest(QWidget* widget) { if (View *view = widgetToView.value(widget)) { area->closeView(view); } } void MainWindowPrivate::setTabBarLeftCornerWidget(QWidget* widget) { if(widget != m_leftTabbarCornerWidget.data()) { delete m_leftTabbarCornerWidget.data(); m_leftTabbarCornerWidget.clear(); } m_leftTabbarCornerWidget = widget; if(!widget || !area || viewContainers.isEmpty()) return; AreaIndex* putToIndex = area->rootIndex(); QSplitter* splitter = m_indexSplitters[putToIndex]; while(putToIndex->isSplit()) { putToIndex = putToIndex->first(); splitter = m_indexSplitters[putToIndex]; } // Q_ASSERT(splitter || putToIndex == area->rootIndex()); Container* c = nullptr; if(splitter) { c = qobject_cast(splitter->widget(0)); }else{ c = *viewContainers.constBegin(); } Q_ASSERT(c); c->setLeftCornerWidget(widget); } void MainWindowPrivate::postMessage(Message* message) { if (!message) { return; } message->setParent(this); // if there are no actions, add a close action by default if widget does not auto-hide if (message->actions().isEmpty() && message->autoHide() < 0) { auto* closeAction = new QAction(QIcon::fromTheme(QStringLiteral("window-close")), i18nc("@action", "Close")); closeAction->setToolTip(i18nc("@info:tooltip", "Close message")); message->addAction(closeAction); } // reparent actions, as we want full control over when they are deleted QVector> managedMessageActions; const auto messageActions = message->actions(); managedMessageActions.reserve(messageActions.size()); for (QAction* action : messageActions) { action->setParent(nullptr); managedMessageActions.append(QSharedPointer(action)); } m_messageHash.insert(message, managedMessageActions); // also catch if the user manually calls delete message connect(message, &Message::closed, this, &MainWindowPrivate::messageDestroyed); messageWidget->postMessage(message, managedMessageActions); } void MainWindowPrivate::messageDestroyed(Message* message) { // Message is already in destructor Q_ASSERT(m_messageHash.contains(message)); m_messageHash.remove(message); } } #include "mainwindow_p.moc" #include "moc_mainwindow_p.cpp"