@@ -38,7 +38,8 @@ Q_LOGGING_CATEGORY(TOPLEVELWINDOWMODEL, "toplevelwindowmodel", QtInfoMsg)
3838namespace unityapi = unity::shell::application;
3939
4040TopLevelWindowModel::TopLevelWindowModel()
41− : m_nullWindow(createWindow(nullptr))
41+ : m_nullWindow(createWindow(nullptr)),
42+ m_surfaceManagerBusy(false)
4243{
4344 connect(m_nullWindow, &Window::focusedChanged, this, [this] {
4445 Q_EMIT rootFocusChanged();
@@ -439,6 +440,10 @@ void TopLevelWindowModel::removeAt(int index)
439440 setFocusedWindow(nullptr);
440441 }
441442
443+ if (m_previousWindow == window) {
444+ m_previousWindow = nullptr;
445+ }
446+
442447 if (m_closingAllApps) {
443448 if (m_windowModel.isEmpty()) {
444449 Q_EMIT closedAllWindows();
@@ -709,6 +714,7 @@ void TopLevelWindowModel::move(int from, int to)
709714}
710715void TopLevelWindowModel::onModificationsStarted()
711716{
717+ m_surfaceManagerBusy = true;
712718}
713719
714720void TopLevelWindowModel::onModificationsEnded()
@@ -719,6 +725,7 @@ void TopLevelWindowModel::onModificationsEnded()
719725 // reset
720726 m_focusedWindowChanged = false;
721727 m_newlyFocusedWindow = nullptr;
728+ m_surfaceManagerBusy = false;
722729}
723730
724731void TopLevelWindowModel::activateTopMostWindowWithoutId(int forbiddenId)
@@ -754,7 +761,14 @@ bool TopLevelWindowModel::rootFocus()
754761
755762void TopLevelWindowModel::setRootFocus(bool focus)
756763{
757− INFO_MSG << "(" << focus << ")";
764+ INFO_MSG << "(" << focus << "), surfaceManagerBusy is " << m_surfaceManagerBusy;
765+
766+ if (m_surfaceManagerBusy) {
767+ // Something else is probably being focused already, let's not add to
768+ // the noise.
769+ return;
770+ }
771+
758772 if (focus) {
759773 // Give focus back to previous focused window, only if null window is focused.
760774 // If null window is not focused, a different app had taken the focus and we
@@ -762,6 +776,9 @@ void TopLevelWindowModel::setRootFocus(bool focus)
762776 if (m_previousWindow && !m_previousWindow->focused() && !m_pendingActivation &&
763777 m_nullWindow == m_focusedWindow && m_previousWindow != m_nullWindow) {
764778 m_previousWindow->activate();
779+ } else if (!m_pendingActivation) {
780+ // The previous window does not exist any more, focus top window.
781+ activateTopMostWindowWithoutId(-1);
765782 }
766783 } else {
767784 if (!m_nullWindow->focused()) {