2 * Copyright (C) 2016-2017 Canonical, Ltd.
3 * Copyright 2019 UBports Foundation
5 * This program is free software: you can redistribute it and/or modify it under
6 * the terms of the GNU Lesser General Public License version 3, as published by
7 * the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
11 * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18#include "TopLevelWindowModel.h"
21#include <unity/shell/application/ApplicationInfoInterface.h>
22#include <unity/shell/application/ApplicationManagerInterface.h>
23#include <unity/shell/application/MirSurfaceInterface.h>
24#include <unity/shell/application/MirSurfaceListInterface.h>
25#include <unity/shell/application/SurfaceManagerInterface.h>
28#include <QGuiApplication>
34Q_LOGGING_CATEGORY(TOPLEVELWINDOWMODEL, "toplevelwindowmodel", QtInfoMsg)
36#define DEBUG_MSG qCDebug(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
37#define INFO_MSG qCInfo(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
39namespace unityapi = unity::shell::application;
41TopLevelWindowModel::TopLevelWindowModel()
42 : m_nullWindow(createNullWindow()),
43 m_maxWindowId(1000000),
44 m_surfaceManagerBusy(false)
46 connect(m_nullWindow, &Window::focusedChanged, this, [this] {
47 Q_EMIT rootFocusChanged();
51void TopLevelWindowModel::setApplicationManager(unityapi::ApplicationManagerInterface* value)
53 if (m_applicationManager == value) {
57 DEBUG_MSG << "(" << value << ")";
59 Q_ASSERT(m_modelState == IdleState);
60 m_modelState = ResettingState;
64 if (m_applicationManager) {
65 m_windowModel.clear();
66 disconnect(m_applicationManager, 0, this, 0);
69 m_applicationManager = value;
71 if (m_applicationManager) {
72 connect(m_applicationManager, &QAbstractItemModel::rowsInserted,
73 this, [this](const QModelIndex &/*parent*/, int first, int last) {
74 for (int i = first; i <= last; ++i) {
75 auto application = m_applicationManager->get(i);
76 addApplication(application);
80 connect(m_applicationManager, &QAbstractItemModel::rowsAboutToBeRemoved,
81 this, [this](const QModelIndex &/*parent*/, int first, int last) {
82 for (int i = first; i <= last; ++i) {
83 auto application = m_applicationManager->get(i);
84 removeApplication(application);
88 for (int i = 0; i < m_applicationManager->rowCount(); ++i) {
89 auto application = m_applicationManager->get(i);
90 addApplication(application);
95 m_modelState = IdleState;
98void TopLevelWindowModel::setSurfaceManager(unityapi::SurfaceManagerInterface *surfaceManager)
100 if (surfaceManager == m_surfaceManager) {
104 DEBUG_MSG << "(" << surfaceManager << ")";
106 if (m_surfaceManager) {
107 disconnect(m_surfaceManager, 0, this, 0);
110 m_surfaceManager = surfaceManager;
112 if (m_surfaceManager) {
113 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfaceCreated, this, &TopLevelWindowModel::onSurfaceCreated);
114 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfacesRaised, this, &TopLevelWindowModel::onSurfacesRaised);
115 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsStarted, this, &TopLevelWindowModel::onModificationsStarted);
116 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsEnded, this, &TopLevelWindowModel::onModificationsEnded);
119 Q_EMIT surfaceManagerChanged(m_surfaceManager);
122void TopLevelWindowModel::addApplication(unityapi::ApplicationInfoInterface *application)
124 DEBUG_MSG << "(" << application->appId() << ")";
126 if (application->state() != unityapi::ApplicationInfoInterface::Stopped && application->surfaceList()->count() == 0) {
127 prependPlaceholder(application);
131void TopLevelWindowModel::removeApplication(unityapi::ApplicationInfoInterface *application)
133 DEBUG_MSG << "(" << application->appId() << ")";
135 Q_ASSERT(m_modelState == IdleState);
138 while (i < m_windowModel.count()) {
139 if (m_windowModel.at(i).application == application) {
147void TopLevelWindowModel::prependPlaceholder(unityapi::ApplicationInfoInterface *application)
149 INFO_MSG << "(" << application->appId() << ")";
151 prependSurfaceHelper(nullptr, application);
154void TopLevelWindowModel::prependSurface(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
156 Q_ASSERT(surface != nullptr);
158 connectSurface(surface);
160 bool filledPlaceholder = false;
161 for (int i = 0; i < m_windowModel.count() && !filledPlaceholder; ++i) {
162 ModelEntry &entry = m_windowModel[i];
163 if (entry.application == application && entry.window->surface() == nullptr) {
164 entry.window->setSurface(surface);
165 INFO_MSG << " appId=" << application->appId() << " surface=" << surface
166 << ", filling out placeholder. after: " << toString();
167 filledPlaceholder = true;
171 if (!filledPlaceholder) {
172 INFO_MSG << " appId=" << application->appId() << " surface=" << surface << ", adding new row";
173 prependSurfaceHelper(surface, application);
177void TopLevelWindowModel::prependSurfaceHelper(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
180 Window *window = createWindow(surface);
182 connect(window, &Window::stateChanged, this, [=](Mir::State newState) {
183 if (newState == Mir::HiddenState) {
184 // Comply, removing it from our model. Just as if it didn't exist anymore.
185 removeAt(indexForId(window->id()));
187 if (indexForId(window->id()) == -1) {
188 // was probably hidden before. put it back on the list
189 auto *application = m_applicationManager->findApplicationWithSurface(window->surface());
190 Q_ASSERT(application);
191 prependWindow(window, application);
196 prependWindow(window, application);
199 activateEmptyWindow(window);
202 INFO_MSG << " after " << toString();
205void TopLevelWindowModel::prependWindow(Window *window, unityapi::ApplicationInfoInterface *application)
207 if (m_modelState == IdleState) {
208 m_modelState = InsertingState;
209 beginInsertRows(QModelIndex(), 0 /*first*/, 0 /*last*/);
211 Q_ASSERT(m_modelState == ResettingState);
212 // No point in signaling anything if we're resetting the whole model
215 m_windowModel.prepend(ModelEntry(window, application));
217 if (m_modelState == InsertingState) {
219 Q_EMIT countChanged();
220 Q_EMIT listChanged();
221 m_modelState = IdleState;
225void TopLevelWindowModel::connectWindow(Window *window)
227 connect(window, &Window::focusRequested, this, [this, window]() {
228 if (!window->surface()) {
229 activateEmptyWindow(window);
233 connect(window, &Window::focusedChanged, this, [this, window](bool focused) {
234 if (window->surface()) {
235 // Condense changes to the focused window
236 // eg: Do focusedWindow=A to focusedWindow=B instead of
237 // focusedWindow=A to focusedWindow=null to focusedWindow=B
239 Q_ASSERT(m_newlyFocusedWindow == nullptr);
240 m_focusedWindowChanged = true;
241 m_newlyFocusedWindow = window;
242 } else if (m_focusedWindow == window) {
243 m_focusedWindowChanged = true;
245 // don't clear the focused window if you were not there in the first place
246 // happens when a filled window gets replaced with an empty one (no surface) as the focused window.
251 connect(window, &Window::closeRequested, this, [this, window]() {
252 if (!window->surface()) {
253 // do things ourselves as miral doesn't know about this window
254 int id = window->id();
255 int index = indexForId(id);
256 bool focusOther = false;
257 Q_ASSERT(index >= 0);
258 if (window->focused()) {
261 m_windowModel[index].application->close();
263 activateTopMostWindowWithoutId(id);
268 connect(window, &Window::emptyWindowActivated, this, [this, window]() {
269 activateEmptyWindow(window);
272 connect(window, &Window::liveChanged, this, [this, window](bool isAlive) {
273 if (!isAlive && window->state() == Mir::HiddenState) {
274 // Hidden windows are not in the model. So just delete it right away.
280void TopLevelWindowModel::activateEmptyWindow(Window *window)
282 Q_ASSERT(!window->surface());
283 DEBUG_MSG << "(" << window << ")";
285 // miral doesn't know about empty windows (ie, windows that are not backed up by MirSurfaces)
286 // So we have to activate them ourselves (instead of asking SurfaceManager to do it for us).
288 window->setFocused(true);
289 raiseId(window->id());
290 Window *previousWindow = m_focusedWindow;
291 setFocusedWindow(window);
292 if (previousWindow && previousWindow->surface() && previousWindow->surface()->focused()) {
293 m_surfaceManager->activate(nullptr);
297void TopLevelWindowModel::connectSurface(unityapi::MirSurfaceInterface *surface)
299 connect(surface, &unityapi::MirSurfaceInterface::liveChanged, this, [this, surface](bool live){
301 onSurfaceDied(surface);
304 connect(surface, &QObject::destroyed, this, [this, surface](){ this->onSurfaceDestroyed(surface); });
307void TopLevelWindowModel::onSurfaceDied(unityapi::MirSurfaceInterface *surface)
309 if (surface->type() == Mir::InputMethodType) {
310 removeInputMethodWindow();
314 int i = indexOf(surface);
319 auto application = m_windowModel[i].application;
321 // can't be starting if it already has a surface
322 Q_ASSERT(application->state() != unityapi::ApplicationInfoInterface::Starting);
324 if (application->state() == unityapi::ApplicationInfoInterface::Running) {
325 m_windowModel[i].removeOnceSurfaceDestroyed = true;
327 // assume it got killed by the out-of-memory daemon.
329 // So leave entry in the model and only remove its surface, so shell can display a screenshot
331 m_windowModel[i].removeOnceSurfaceDestroyed = false;
335void TopLevelWindowModel::onSurfaceDestroyed(unityapi::MirSurfaceInterface *surface)
337 int i = indexOf(surface);
342 if (m_windowModel[i].removeOnceSurfaceDestroyed) {
345 auto window = m_windowModel[i].window;
346 window->setSurface(nullptr);
347 window->setFocused(false);
348 INFO_MSG << " Removed surface from entry. After: " << toString();
352Window *TopLevelWindowModel::createWindow(unityapi::MirSurfaceInterface *surface)
354 int id = generateId();
355 return createWindowWithId(surface, id);
358Window *TopLevelWindowModel::createNullWindow()
360 return createWindowWithId(nullptr, 0);
363Window *TopLevelWindowModel::createWindowWithId(unityapi::MirSurfaceInterface *surface, int id)
365 Window *qmlWindow = new Window(id, this);
366 connectWindow(qmlWindow);
368 qmlWindow->setSurface(surface);
373void TopLevelWindowModel::onSurfaceCreated(unityapi::MirSurfaceInterface *surface)
375 DEBUG_MSG << "(" << surface << ")";
377 if (surface->parentSurface()) {
378 // Wrap it in a Window so that we keep focusedWindow() up to date.
379 Window *window = createWindow(surface);
380 connect(surface, &QObject::destroyed, window, [=](){
381 window->setSurface(nullptr);
382 window->deleteLater();
385 if (surface->type() == Mir::InputMethodType) {
386 connectSurface(surface);
387 setInputMethodWindow(createWindow(surface));
389 auto *application = m_applicationManager->findApplicationWithSurface(surface);
391 if (surface->state() == Mir::HiddenState) {
392 // Ignore it until it's finally shown
393 connect(surface, &unityapi::MirSurfaceInterface::stateChanged, this, [=](Mir::State newState) {
394 Q_ASSERT(newState != Mir::HiddenState);
395 disconnect(surface, &unityapi::MirSurfaceInterface::stateChanged, this, 0);
396 prependSurface(surface, application);
399 prependSurface(surface, application);
402 // Must be a prompt session. No need to do add it as a prompt surface is not top-level.
403 // It will show up in the ApplicationInfoInterface::promptSurfaceList of some application.
404 // Still wrap it in a Window though, so that we keep focusedWindow() up to date.
405 Window *promptWindow = createWindow(surface);
406 connect(surface, &QObject::destroyed, promptWindow, [=](){
407 promptWindow->setSurface(nullptr);
408 promptWindow->deleteLater();
415void TopLevelWindowModel::deleteAt(int index)
417 auto window = m_windowModel[index].window;
421 window->setSurface(nullptr);
426void TopLevelWindowModel::removeAt(int index)
428 if (m_modelState == IdleState) {
429 beginRemoveRows(QModelIndex(), index, index);
430 m_modelState = RemovingState;
432 Q_ASSERT(m_modelState == ResettingState);
433 // No point in signaling anything if we're resetting the whole model
436 auto window = m_windowModel[index].window;
438 if (!window->surface()) {
439 window->setFocused(false);
442 m_windowModel.removeAt(index);
444 if (m_modelState == RemovingState) {
446 Q_EMIT countChanged();
447 Q_EMIT listChanged();
448 m_modelState = IdleState;
451 if (m_focusedWindow == window) {
452 setFocusedWindow(nullptr);
455 if (m_previousWindow == window) {
456 m_previousWindow = nullptr;
459 if (m_closingAllApps) {
460 if (m_windowModel.isEmpty()) {
461 Q_EMIT closedAllWindows();
465 INFO_MSG << " after " << toString() << " apps left " << m_windowModel.count();
468void TopLevelWindowModel::setInputMethodWindow(Window *window)
470 if (m_inputMethodWindow) {
471 qWarning("Multiple Input Method Surfaces created, removing the old one!");
472 delete m_inputMethodWindow;
474 m_inputMethodWindow = window;
475 Q_EMIT inputMethodSurfaceChanged(m_inputMethodWindow->surface());
478void TopLevelWindowModel::removeInputMethodWindow()
480 if (m_inputMethodWindow) {
481 delete m_inputMethodWindow;
482 m_inputMethodWindow = nullptr;
483 Q_EMIT inputMethodSurfaceChanged(nullptr);
487void TopLevelWindowModel::onSurfacesRaised(const QVector<unityapi::MirSurfaceInterface*> &surfaces)
489 DEBUG_MSG << "(" << surfaces << ")";
490 const int raiseCount = surfaces.size();
491 for (int i = 0; i < raiseCount; i++) {
492 int fromIndex = findIndexOf(surfaces[i]);
493 if (fromIndex != -1) {
499int TopLevelWindowModel::rowCount(const QModelIndex &/*parent*/) const
501 return m_windowModel.count();
504QVariant TopLevelWindowModel::data(const QModelIndex& index, int role) const
506 if (index.row() < 0 || index.row() >= m_windowModel.size())
509 if (role == WindowRole) {
510 Window *window = m_windowModel.at(index.row()).window;
511 return QVariant::fromValue(window);
512 } else if (role == ApplicationRole) {
513 return QVariant::fromValue(m_windowModel.at(index.row()).application);
519int TopLevelWindowModel::findIndexOf(const unityapi::MirSurfaceInterface *surface) const
521 for (int i=0; i<m_windowModel.count(); i++) {
522 if (m_windowModel[i].window->surface() == surface) {
529// Finds a unique integer identifier not greater than maxWindowId.
530int TopLevelWindowModel::generateId()
532 int candidateId = m_nextId.fetchAndAddAcquire(1);
534 // If the user opens two windows at the exact same time after opening
535 // maxWindowId windows, it is potentially possible that we issue the same
536 // ID for both. This is a risk we can accept.
537 if (candidateId > getMaxWindowId()) {
538 int originalCandidateId = candidateId;
541 while (indexForId(candidateId) != -1) {
544 if (candidateId == originalCandidateId) {
545 // The user has maxWindowId windows open somehow.
546 qFatal("TopLevelWindowModel: Ran out of window IDs!");
550 m_nextId.fetchAndStoreAcquire(candidateId + 1);
555QString TopLevelWindowModel::toString()
558 for (int i = 0; i < m_windowModel.count(); ++i) {
559 auto item = m_windowModel.at(i);
561 QString itemStr = QString("(index=%1,appId=%2,surface=0x%3,id=%4)")
562 .arg(QString::number(i),
563 item.application->appId(),
564 QString::number((qintptr)item.window->surface(), 16),
565 QString::number(item.window->id()));
575int TopLevelWindowModel::indexOf(unityapi::MirSurfaceInterface *surface)
577 for (int i = 0; i < m_windowModel.count(); ++i) {
578 if (m_windowModel.at(i).window->surface() == surface) {
585int TopLevelWindowModel::indexForId(int id) const
587 for (int i = 0; i < m_windowModel.count(); ++i) {
588 if (m_windowModel[i].window->id() == id) {
595Window *TopLevelWindowModel::windowAt(int index) const
597 if (index >=0 && index < m_windowModel.count()) {
598 return m_windowModel[index].window;
604unityapi::MirSurfaceInterface *TopLevelWindowModel::surfaceAt(int index) const
606 if (index >=0 && index < m_windowModel.count()) {
607 return m_windowModel[index].window->surface();
613unityapi::ApplicationInfoInterface *TopLevelWindowModel::applicationAt(int index) const
615 if (index >=0 && index < m_windowModel.count()) {
616 return m_windowModel[index].application;
622int TopLevelWindowModel::idAt(int index) const
624 if (index >=0 && index < m_windowModel.count()) {
625 return m_windowModel[index].window->id();
631void TopLevelWindowModel::raiseId(int id)
633 if (m_modelState == IdleState) {
634 DEBUG_MSG << "(id=" << id << ") - do it now.";
637 DEBUG_MSG << "(id=" << id << ") - Model busy (modelState=" << m_modelState << "). Try again in the next event loop.";
638 // The model has just signalled some change. If we have a Repeater responding to this update, it will get nuts
639 // if we perform yet another model change straight away.
641 // A bad sympton of this problem is a Repeater.itemAt(index) call returning null event though Repeater.count says
642 // the index is definitely within bounds.
643 QMetaObject::invokeMethod(this, "raiseId", Qt::QueuedConnection, Q_ARG(int, id));
647void TopLevelWindowModel::doRaiseId(int id)
649 int fromIndex = indexForId(id);
650 // can't raise something that doesn't exist or that it's already on top
651 if (fromIndex != -1 && fromIndex != 0) {
652 auto surface = m_windowModel[fromIndex].window->surface();
654 m_surfaceManager->raise(surface);
656 // move it ourselves. Since there's no mir::scene::Surface/miral::Window, there's nothing
657 // miral can do about it.
663void TopLevelWindowModel::setFocusedWindow(Window *window)
665 if (window != m_focusedWindow) {
666 INFO_MSG << "(" << window << ")";
668 m_previousWindow = m_focusedWindow;
670 m_focusedWindow = window;
671 Q_EMIT focusedWindowChanged(m_focusedWindow);
673 if (m_previousWindow && m_previousWindow->focused() && !m_previousWindow->surface()) {
674 // do it ourselves. miral doesn't know about this window
675 m_previousWindow->setFocused(false);
680 m_pendingActivation = false;
683unityapi::MirSurfaceInterface* TopLevelWindowModel::inputMethodSurface() const
685 return m_inputMethodWindow ? m_inputMethodWindow->surface() : nullptr;
688Window* TopLevelWindowModel::focusedWindow() const
690 return m_focusedWindow;
693void TopLevelWindowModel::move(int from, int to)
695 if (from == to) return;
696 DEBUG_MSG << " from=" << from << " to=" << to;
698 if (from >= 0 && from < m_windowModel.size() && to >= 0 && to < m_windowModel.size()) {
700 /* When moving an item down, the destination index needs to be incremented
701 by one, as explained in the documentation:
702 http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#beginMoveRows */
704 Q_ASSERT(m_modelState == IdleState);
705 m_modelState = MovingState;
707 beginMoveRows(parent, from, from, parent, to + (to > from ? 1 : 0));
708#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
709 const auto &window = m_windowModel.takeAt(from);
710 m_windowModel.insert(to, window);
712 m_windowModel.move(from, to);
716 Q_EMIT listChanged();
717 m_modelState = IdleState;
719 INFO_MSG << " after " << toString();
722void TopLevelWindowModel::onModificationsStarted()
724 m_surfaceManagerBusy = true;
727void TopLevelWindowModel::onModificationsEnded()
729 if (m_focusedWindowChanged) {
730 setFocusedWindow(m_newlyFocusedWindow);
733 m_focusedWindowChanged = false;
734 m_newlyFocusedWindow = nullptr;
735 m_surfaceManagerBusy = false;
738void TopLevelWindowModel::activateTopMostWindowWithoutId(int forbiddenId)
740 DEBUG_MSG << "(" << forbiddenId << ")";
742 for (int i = 0; i < m_windowModel.count(); ++i) {
743 Window *window = m_windowModel[i].window;
744 if (window->id() != forbiddenId) {
751void TopLevelWindowModel::closeAllWindows()
753 m_closingAllApps = true;
754 for (auto win : m_windowModel) {
758 // This is done after the for loop in the unlikely event that
759 // an app starts in between this
760 if (m_windowModel.isEmpty()) {
761 Q_EMIT closedAllWindows();
765bool TopLevelWindowModel::rootFocus()
767 return !m_nullWindow->focused();
770void TopLevelWindowModel::setRootFocus(bool focus)
772 INFO_MSG << "(" << focus << "), surfaceManagerBusy is " << m_surfaceManagerBusy;
774 if (m_surfaceManagerBusy) {
775 // Something else is probably being focused already, let's not add to
781 // Give focus back to previous focused window, only if null window is focused.
782 // If null window is not focused, a different app had taken the focus and we
783 // should repect that, or if a pendingActivation is going on.
784 if (m_previousWindow && !m_previousWindow->focused() && !m_pendingActivation &&
785 m_nullWindow == m_focusedWindow && m_previousWindow != m_nullWindow) {
786 m_previousWindow->activate();
787 } else if (!m_pendingActivation) {
788 // The previous window does not exist any more, focus top window.
789 activateTopMostWindowWithoutId(-1);
792 if (!m_nullWindow->focused()) {
793 m_nullWindow->activate();
798void TopLevelWindowModel::setMaxWindowId(int newMaxWindowId)
800 DEBUG_MSG << "(" << newMaxWindowId << ")";
801 if (m_maxWindowId != newMaxWindowId) {
802 m_maxWindowId = newMaxWindowId;
803 Q_EMIT maxWindowIdChanged();
807int TopLevelWindowModel::getMaxWindowId()
809 return m_maxWindowId;
812// Pending Activation will block refocus of previous focused window
813// this is needed since surface activation with miral is async,
814// and activation of placeholder is sync. This causes a race condition
815// between placeholder and prev window. This results in prev window
816// gets focused, as it will always be later than the placeholder.
817void TopLevelWindowModel::pendingActivation()
819 m_pendingActivation = true;
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list