on 35e53ef help sign in
unity8/plugins/WindowManager/TopLevelWindowModel.cpp
742 lines 23 kB history raw
1/*
2 * Copyright (C) 2016-2017 Canonical, Ltd.
3 *
4 * This program is free software: you can redistribute it and/or modify it under
5 * the terms of the GNU Lesser General Public License version 3, as published by
6 * the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
10 * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
17#include "TopLevelWindowModel.h"
19// unity-api
20#include <unity/shell/application/ApplicationInfoInterface.h>
21#include <unity/shell/application/ApplicationManagerInterface.h>
22#include <unity/shell/application/MirSurfaceInterface.h>
23#include <unity/shell/application/MirSurfaceListInterface.h>
24#include <unity/shell/application/SurfaceManagerInterface.h>
26// Qt
27#include <QGuiApplication>
28#include <QDebug>
30// local
31#include "Window.h"
33Q_LOGGING_CATEGORY(TOPLEVELWINDOWMODEL, "toplevelwindowmodel", QtInfoMsg)
35#define DEBUG_MSG qCDebug(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
36#define INFO_MSG qCInfo(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
38namespace unityapi = unity::shell::application;
40TopLevelWindowModel::TopLevelWindowModel()
41 : m_nullWindow(createWindow(nullptr))
45void TopLevelWindowModel::setApplicationManager(unityapi::ApplicationManagerInterface* value)
47 if (m_applicationManager == value) {
48 return;
49 }
51 DEBUG_MSG << "(" << value << ")";
53 Q_ASSERT(m_modelState == IdleState);
54 m_modelState = ResettingState;
56 beginResetModel();
58 if (m_applicationManager) {
59 m_windowModel.clear();
60 disconnect(m_applicationManager, 0, this, 0);
61 }
63 m_applicationManager = value;
65 if (m_applicationManager) {
66 connect(m_applicationManager, &QAbstractItemModel::rowsInserted,
67 this, [this](const QModelIndex &/*parent*/, int first, int last) {
68 for (int i = first; i <= last; ++i) {
69 auto application = m_applicationManager->get(i);
70 addApplication(application);
71 }
72 });
74 connect(m_applicationManager, &QAbstractItemModel::rowsAboutToBeRemoved,
75 this, [this](const QModelIndex &/*parent*/, int first, int last) {
76 for (int i = first; i <= last; ++i) {
77 auto application = m_applicationManager->get(i);
78 removeApplication(application);
79 }
80 });
82 for (int i = 0; i < m_applicationManager->rowCount(); ++i) {
83 auto application = m_applicationManager->get(i);
84 addApplication(application);
85 }
86 }
88 endResetModel();
89 m_modelState = IdleState;
92void TopLevelWindowModel::setSurfaceManager(unityapi::SurfaceManagerInterface *surfaceManager)
94 if (surfaceManager == m_surfaceManager) {
95 return;
96 }
98 DEBUG_MSG << "(" << surfaceManager << ")";
100 if (m_surfaceManager) {
101 disconnect(m_surfaceManager, 0, this, 0);
102 }
104 m_surfaceManager = surfaceManager;
106 if (m_surfaceManager) {
107 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfaceCreated, this, &TopLevelWindowModel::onSurfaceCreated);
108 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfacesRaised, this, &TopLevelWindowModel::onSurfacesRaised);
109 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsStarted, this, &TopLevelWindowModel::onModificationsStarted);
110 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsEnded, this, &TopLevelWindowModel::onModificationsEnded);
111 }
113 Q_EMIT surfaceManagerChanged(m_surfaceManager);
116void TopLevelWindowModel::addApplication(unityapi::ApplicationInfoInterface *application)
118 DEBUG_MSG << "(" << application->appId() << ")";
120 if (application->state() != unityapi::ApplicationInfoInterface::Stopped && application->surfaceList()->count() == 0) {
121 prependPlaceholder(application);
122 }
125void TopLevelWindowModel::removeApplication(unityapi::ApplicationInfoInterface *application)
127 DEBUG_MSG << "(" << application->appId() << ")";
129 Q_ASSERT(m_modelState == IdleState);
131 int i = 0;
132 while (i < m_windowModel.count()) {
133 if (m_windowModel.at(i).application == application) {
134 deleteAt(i);
135 } else {
136 ++i;
137 }
138 }
141void TopLevelWindowModel::prependPlaceholder(unityapi::ApplicationInfoInterface *application)
143 INFO_MSG << "(" << application->appId() << ")";
145 prependSurfaceHelper(nullptr, application);
148void TopLevelWindowModel::prependSurface(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
150 Q_ASSERT(surface != nullptr);
152 connectSurface(surface);
154 bool filledPlaceholder = false;
155 for (int i = 0; i < m_windowModel.count() && !filledPlaceholder; ++i) {
156 ModelEntry &entry = m_windowModel[i];
157 if (entry.application == application && entry.window->surface() == nullptr) {
158 entry.window->setSurface(surface);
159 INFO_MSG << " appId=" << application->appId() << " surface=" << surface
160 << ", filling out placeholder. after: " << toString();
161 filledPlaceholder = true;
162 }
163 }
165 if (!filledPlaceholder) {
166 INFO_MSG << " appId=" << application->appId() << " surface=" << surface << ", adding new row";
167 prependSurfaceHelper(surface, application);
168 }
171void TopLevelWindowModel::prependSurfaceHelper(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
174 Window *window = createWindow(surface);
176 connect(window, &Window::stateChanged, this, [=](Mir::State newState) {
177 if (newState == Mir::HiddenState) {
178 // Comply, removing it from our model. Just as if it didn't exist anymore.
179 removeAt(indexForId(window->id()));
180 } else {
181 if (indexForId(window->id()) == -1) {
182 // was probably hidden before. put it back on the list
183 auto *application = m_applicationManager->findApplicationWithSurface(window->surface());
184 Q_ASSERT(application);
185 prependWindow(window, application);
186 }
187 }
188 });
190 prependWindow(window, application);
192 if (!surface) {
193 activateEmptyWindow(window);
194 }
196 INFO_MSG << " after " << toString();
199void TopLevelWindowModel::prependWindow(Window *window, unityapi::ApplicationInfoInterface *application)
201 if (m_modelState == IdleState) {
202 m_modelState = InsertingState;
203 beginInsertRows(QModelIndex(), 0 /*first*/, 0 /*last*/);
204 } else {
205 Q_ASSERT(m_modelState == ResettingState);
206 // No point in signaling anything if we're resetting the whole model
207 }
209 m_windowModel.prepend(ModelEntry(window, application));
211 if (m_modelState == InsertingState) {
212 endInsertRows();
213 Q_EMIT countChanged();
214 Q_EMIT listChanged();
215 m_modelState = IdleState;
216 }
219void TopLevelWindowModel::connectWindow(Window *window)
221 connect(window, &Window::focusRequested, this, [this, window]() {
222 if (!window->surface()) {
223 activateEmptyWindow(window);
224 }
225 });
227 connect(window, &Window::focusedChanged, this, [this, window](bool focused) {
228 if (window->surface()) {
229 // Condense changes to the focused window
230 // eg: Do focusedWindow=A to focusedWindow=B instead of
231 // focusedWindow=A to focusedWindow=null to focusedWindow=B
232 if (focused) {
233 Q_ASSERT(m_newlyFocusedWindow == nullptr);
234 m_focusedWindowChanged = true;
235 m_newlyFocusedWindow = window;
236 } else if (m_focusedWindow == window) {
237 m_focusedWindowChanged = true;
238 } else {
239 // don't clear the focused window if you were not there in the first place
240 // happens when a filled window gets replaced with an empty one (no surface) as the focused window.
241 }
242 }
243 });
245 connect(window, &Window::closeRequested, this, [this, window]() {
246 if (!window->surface()) {
247 // do things ourselves as miral doesn't know about this window
248 int id = window->id();
249 int index = indexForId(id);
250 bool focusOther = false;
251 Q_ASSERT(index >= 0);
252 if (window->focused()) {
253 focusOther = true;
254 }
255 m_windowModel[index].application->close();
256 if (focusOther) {
257 activateTopMostWindowWithoutId(id);
258 }
259 }
260 });
262 connect(window, &Window::emptyWindowActivated, this, [this, window]() {
263 activateEmptyWindow(window);
264 });
266 connect(window, &Window::liveChanged, this, [this, window](bool isAlive) {
267 if (!isAlive && window->state() == Mir::HiddenState) {
268 // Hidden windows are not in the model. So just delete it right away.
269 delete window;
270 }
271 });
274void TopLevelWindowModel::activateEmptyWindow(Window *window)
276 Q_ASSERT(!window->surface());
277 DEBUG_MSG << "(" << window << ")";
279 // miral doesn't know about empty windows (ie, windows that are not backed up by MirSurfaces)
280 // So we have to activate them ourselves (instead of asking SurfaceManager to do it for us).
282 window->setFocused(true);
283 raiseId(window->id());
284 Window *previousWindow = m_focusedWindow;
285 setFocusedWindow(window);
286 if (previousWindow && previousWindow->surface() && previousWindow->surface()->focused()) {
287 m_surfaceManager->activate(nullptr);
288 }
291void TopLevelWindowModel::connectSurface(unityapi::MirSurfaceInterface *surface)
293 connect(surface, &unityapi::MirSurfaceInterface::liveChanged, this, [this, surface](bool live){
294 if (!live) {
295 onSurfaceDied(surface);
296 }
297 });
298 connect(surface, &QObject::destroyed, this, [this, surface](){ this->onSurfaceDestroyed(surface); });
301void TopLevelWindowModel::onSurfaceDied(unityapi::MirSurfaceInterface *surface)
303 if (surface->type() == Mir::InputMethodType) {
304 removeInputMethodWindow();
305 return;
306 }
308 int i = indexOf(surface);
309 if (i == -1) {
310 return;
311 }
313 auto application = m_windowModel[i].application;
315 // can't be starting if it already has a surface
316 Q_ASSERT(application->state() != unityapi::ApplicationInfoInterface::Starting);
318 if (application->state() == unityapi::ApplicationInfoInterface::Running) {
319 m_windowModel[i].removeOnceSurfaceDestroyed = true;
320 } else {
321 // assume it got killed by the out-of-memory daemon.
322 //
323 // So leave entry in the model and only remove its surface, so shell can display a screenshot
324 // in its place.
325 m_windowModel[i].removeOnceSurfaceDestroyed = false;
326 }
329void TopLevelWindowModel::onSurfaceDestroyed(unityapi::MirSurfaceInterface *surface)
331 int i = indexOf(surface);
332 if (i == -1) {
333 return;
334 }
336 if (m_windowModel[i].removeOnceSurfaceDestroyed) {
337 deleteAt(i);
338 } else {
339 auto window = m_windowModel[i].window;
340 window->setSurface(nullptr);
341 window->setFocused(false);
342 INFO_MSG << " Removed surface from entry. After: " << toString();
343 }
346Window *TopLevelWindowModel::createWindow(unityapi::MirSurfaceInterface *surface)
348 int id = generateId();
349 Window *qmlWindow = new Window(id, this);
350 connectWindow(qmlWindow);
351 if (surface) {
352 qmlWindow->setSurface(surface);
353 }
354 return qmlWindow;
357void TopLevelWindowModel::onSurfaceCreated(unityapi::MirSurfaceInterface *surface)
359 DEBUG_MSG << "(" << surface << ")";
361 if (surface->parentSurface()) {
362 // Wrap it in a Window so that we keep focusedWindow() up to date.
363 Window *window = createWindow(surface);
364 connect(surface, &QObject::destroyed, window, [=](){
365 window->setSurface(nullptr);
366 window->deleteLater();
367 });
368 } else {
369 if (surface->type() == Mir::InputMethodType) {
370 connectSurface(surface);
371 setInputMethodWindow(createWindow(surface));
372 } else {
373 auto *application = m_applicationManager->findApplicationWithSurface(surface);
374 if (application) {
375 if (surface->state() == Mir::HiddenState) {
376 // Ignore it until it's finally shown
377 connect(surface, &unityapi::MirSurfaceInterface::stateChanged, this, [=](Mir::State newState) {
378 Q_ASSERT(newState != Mir::HiddenState);
379 disconnect(surface, &unityapi::MirSurfaceInterface::stateChanged, this, 0);
380 prependSurface(surface, application);
381 });
382 } else {
383 prependSurface(surface, application);
384 }
385 } else {
386 // Must be a prompt session. No need to do add it as a prompt surface is not top-level.
387 // It will show up in the ApplicationInfoInterface::promptSurfaceList of some application.
388 // Still wrap it in a Window though, so that we keep focusedWindow() up to date.
389 Window *promptWindow = createWindow(surface);
390 connect(surface, &QObject::destroyed, promptWindow, [=](){
391 promptWindow->setSurface(nullptr);
392 promptWindow->deleteLater();
393 });
394 }
395 }
396 }
399void TopLevelWindowModel::deleteAt(int index)
401 auto window = m_windowModel[index].window;
403 removeAt(index);
405 window->setSurface(nullptr);
407 delete window;
410void TopLevelWindowModel::removeAt(int index)
412 if (m_modelState == IdleState) {
413 beginRemoveRows(QModelIndex(), index, index);
414 m_modelState = RemovingState;
415 } else {
416 Q_ASSERT(m_modelState == ResettingState);
417 // No point in signaling anything if we're resetting the whole model
418 }
420 auto window = m_windowModel[index].window;
422 if (!window->surface()) {
423 window->setFocused(false);
424 }
426 m_windowModel.removeAt(index);
428 if (m_modelState == RemovingState) {
429 endRemoveRows();
430 Q_EMIT countChanged();
431 Q_EMIT listChanged();
432 m_modelState = IdleState;
433 }
435 if (m_focusedWindow == window) {
436 setFocusedWindow(nullptr);
437 }
439 if (m_closingAllApps) {
440 if (m_windowModel.isEmpty()) {
441 Q_EMIT closedAllWindows();
442 }
443 }
445 INFO_MSG << " after " << toString() << " apps left " << m_windowModel.count();
448void TopLevelWindowModel::setInputMethodWindow(Window *window)
450 if (m_inputMethodWindow) {
451 qWarning("Multiple Input Method Surfaces created, removing the old one!");
452 delete m_inputMethodWindow;
453 }
454 m_inputMethodWindow = window;
455 Q_EMIT inputMethodSurfaceChanged(m_inputMethodWindow->surface());
458void TopLevelWindowModel::removeInputMethodWindow()
460 if (m_inputMethodWindow) {
461 delete m_inputMethodWindow;
462 m_inputMethodWindow = nullptr;
463 Q_EMIT inputMethodSurfaceChanged(nullptr);
464 }
467void TopLevelWindowModel::onSurfacesRaised(const QVector<unityapi::MirSurfaceInterface*> &surfaces)
469 DEBUG_MSG << "(" << surfaces << ")";
470 const int raiseCount = surfaces.size();
471 for (int i = 0; i < raiseCount; i++) {
472 int fromIndex = findIndexOf(surfaces[i]);
473 if (fromIndex != -1) {
474 move(fromIndex, 0);
475 }
476 }
479int TopLevelWindowModel::rowCount(const QModelIndex &/*parent*/) const
481 return m_windowModel.count();
484QVariant TopLevelWindowModel::data(const QModelIndex& index, int role) const
486 if (index.row() < 0 || index.row() >= m_windowModel.size())
487 return QVariant();
489 if (role == WindowRole) {
490 Window *window = m_windowModel.at(index.row()).window;
491 return QVariant::fromValue(window);
492 } else if (role == ApplicationRole) {
493 return QVariant::fromValue(m_windowModel.at(index.row()).application);
494 } else {
495 return QVariant();
496 }
499int TopLevelWindowModel::findIndexOf(const unityapi::MirSurfaceInterface *surface) const
501 for (int i=0; i<m_windowModel.count(); i++) {
502 if (m_windowModel[i].window->surface() == surface) {
503 return i;
504 }
505 }
506 return -1;
509int TopLevelWindowModel::generateId()
511 int id = m_nextId;
512 m_nextId = nextFreeId(nextId(id), id);
513 return id;
516int TopLevelWindowModel::nextId(int id) const
518 if (id == m_maxId) {
519 return id = 1;
520 } else {
521 return id + 1;
522 }
525int TopLevelWindowModel::nextFreeId(int candidateId, const int latestId)
527 int firstCandidateId = candidateId;
529 while (indexForId(candidateId) != -1 || candidateId == latestId) {
530 candidateId = nextId(candidateId);
532 if (candidateId == firstCandidateId) {
533 qFatal("TopLevelWindowModel: run out of window ids.");
534 }
535 }
537 return candidateId;
540QString TopLevelWindowModel::toString()
542 QString str;
543 for (int i = 0; i < m_windowModel.count(); ++i) {
544 auto item = m_windowModel.at(i);
546 QString itemStr = QString("(index=%1,appId=%2,surface=0x%3,id=%4)")
547 .arg(QString::number(i),
548 item.application->appId(),
549 QString::number((qintptr)item.window->surface(), 16),
550 QString::number(item.window->id()));
552 if (i > 0) {
553 str.append(",");
554 }
555 str.append(itemStr);
556 }
557 return str;
560int TopLevelWindowModel::indexOf(unityapi::MirSurfaceInterface *surface)
562 for (int i = 0; i < m_windowModel.count(); ++i) {
563 if (m_windowModel.at(i).window->surface() == surface) {
564 return i;
565 }
566 }
567 return -1;
570int TopLevelWindowModel::indexForId(int id) const
572 for (int i = 0; i < m_windowModel.count(); ++i) {
573 if (m_windowModel[i].window->id() == id) {
574 return i;
575 }
576 }
577 return -1;
580Window *TopLevelWindowModel::windowAt(int index) const
582 if (index >=0 && index < m_windowModel.count()) {
583 return m_windowModel[index].window;
584 } else {
585 return nullptr;
586 }
589unityapi::MirSurfaceInterface *TopLevelWindowModel::surfaceAt(int index) const
591 if (index >=0 && index < m_windowModel.count()) {
592 return m_windowModel[index].window->surface();
593 } else {
594 return nullptr;
595 }
598unityapi::ApplicationInfoInterface *TopLevelWindowModel::applicationAt(int index) const
600 if (index >=0 && index < m_windowModel.count()) {
601 return m_windowModel[index].application;
602 } else {
603 return nullptr;
604 }
607int TopLevelWindowModel::idAt(int index) const
609 if (index >=0 && index < m_windowModel.count()) {
610 return m_windowModel[index].window->id();
611 } else {
612 return 0;
613 }
616void TopLevelWindowModel::raiseId(int id)
618 if (m_modelState == IdleState) {
619 DEBUG_MSG << "(id=" << id << ") - do it now.";
620 doRaiseId(id);
621 } else {
622 DEBUG_MSG << "(id=" << id << ") - Model busy (modelState=" << m_modelState << "). Try again in the next event loop.";
623 // The model has just signalled some change. If we have a Repeater responding to this update, it will get nuts
624 // if we perform yet another model change straight away.
625 //
626 // A bad sympton of this problem is a Repeater.itemAt(index) call returning null event though Repeater.count says
627 // the index is definitely within bounds.
628 QMetaObject::invokeMethod(this, "raiseId", Qt::QueuedConnection, Q_ARG(int, id));
629 }
632void TopLevelWindowModel::doRaiseId(int id)
634 int fromIndex = indexForId(id);
635 // can't raise something that doesn't exist or that it's already on top
636 if (fromIndex != -1 && fromIndex != 0) {
637 auto surface = m_windowModel[fromIndex].window->surface();
638 if (surface) {
639 m_surfaceManager->raise(surface);
640 } else {
641 // move it ourselves. Since there's no mir::scene::Surface/miral::Window, there's nothing
642 // miral can do about it.
643 move(fromIndex, 0);
644 }
645 }
648void TopLevelWindowModel::setFocusedWindow(Window *window)
650 if (window != m_focusedWindow) {
651 INFO_MSG << "(" << window << ")";
653 Window* previousWindow = m_focusedWindow;
655 m_focusedWindow = window;
656 Q_EMIT focusedWindowChanged(m_focusedWindow);
658 if (previousWindow && previousWindow->focused() && !previousWindow->surface()) {
659 // do it ourselves. miral doesn't know about this window
660 previousWindow->setFocused(false);
661 }
662 }
665unityapi::MirSurfaceInterface* TopLevelWindowModel::inputMethodSurface() const
667 return m_inputMethodWindow ? m_inputMethodWindow->surface() : nullptr;
670Window* TopLevelWindowModel::focusedWindow() const
672 return m_focusedWindow;
675void TopLevelWindowModel::move(int from, int to)
677 if (from == to) return;
678 DEBUG_MSG << " from=" << from << " to=" << to;
680 if (from >= 0 && from < m_windowModel.size() && to >= 0 && to < m_windowModel.size()) {
681 QModelIndex parent;
682 /* When moving an item down, the destination index needs to be incremented
683 by one, as explained in the documentation:
684 http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#beginMoveRows */
686 Q_ASSERT(m_modelState == IdleState);
687 m_modelState = MovingState;
689 beginMoveRows(parent, from, from, parent, to + (to > from ? 1 : 0));
690#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
691 const auto &window = m_windowModel.takeAt(from);
692 m_windowModel.insert(to, window);
693#else
694 m_windowModel.move(from, to);
695#endif
696 endMoveRows();
698 Q_EMIT listChanged();
699 m_modelState = IdleState;
701 INFO_MSG << " after " << toString();
702 }
704void TopLevelWindowModel::onModificationsStarted()
708void TopLevelWindowModel::onModificationsEnded()
710 if (m_focusedWindowChanged) {
711 setFocusedWindow(m_newlyFocusedWindow);
712 }
713 // reset
714 m_focusedWindowChanged = false;
715 m_newlyFocusedWindow = nullptr;
718void TopLevelWindowModel::activateTopMostWindowWithoutId(int forbiddenId)
720 DEBUG_MSG << "(" << forbiddenId << ")";
722 for (int i = 0; i < m_windowModel.count(); ++i) {
723 Window *window = m_windowModel[i].window;
724 if (window->id() != forbiddenId) {
725 window->activate();
726 }
727 }
730void TopLevelWindowModel::activateNullWindow()
732 if (!m_nullWindow->focused())
733 m_nullWindow->activate();
736void TopLevelWindowModel::closeAllWindows()
738 m_closingAllApps = true;
739 for (auto win : m_windowModel) {
740 win.window->close();
741 }