on 4169ccd help sign in
unity8/plugins/WindowManager/TopLevelWindowModel.cpp
728 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 INFO_MSG << " after " << toString();
442void TopLevelWindowModel::setInputMethodWindow(Window *window)
444 if (m_inputMethodWindow) {
445 qWarning("Multiple Input Method Surfaces created, removing the old one!");
446 delete m_inputMethodWindow;
447 }
448 m_inputMethodWindow = window;
449 Q_EMIT inputMethodSurfaceChanged(m_inputMethodWindow->surface());
452void TopLevelWindowModel::removeInputMethodWindow()
454 if (m_inputMethodWindow) {
455 delete m_inputMethodWindow;
456 m_inputMethodWindow = nullptr;
457 Q_EMIT inputMethodSurfaceChanged(nullptr);
458 }
461void TopLevelWindowModel::onSurfacesRaised(const QVector<unityapi::MirSurfaceInterface*> &surfaces)
463 DEBUG_MSG << "(" << surfaces << ")";
464 const int raiseCount = surfaces.size();
465 for (int i = 0; i < raiseCount; i++) {
466 int fromIndex = findIndexOf(surfaces[i]);
467 if (fromIndex != -1) {
468 move(fromIndex, 0);
469 }
470 }
473int TopLevelWindowModel::rowCount(const QModelIndex &/*parent*/) const
475 return m_windowModel.count();
478QVariant TopLevelWindowModel::data(const QModelIndex& index, int role) const
480 if (index.row() < 0 || index.row() >= m_windowModel.size())
481 return QVariant();
483 if (role == WindowRole) {
484 Window *window = m_windowModel.at(index.row()).window;
485 return QVariant::fromValue(window);
486 } else if (role == ApplicationRole) {
487 return QVariant::fromValue(m_windowModel.at(index.row()).application);
488 } else {
489 return QVariant();
490 }
493int TopLevelWindowModel::findIndexOf(const unityapi::MirSurfaceInterface *surface) const
495 for (int i=0; i<m_windowModel.count(); i++) {
496 if (m_windowModel[i].window->surface() == surface) {
497 return i;
498 }
499 }
500 return -1;
503int TopLevelWindowModel::generateId()
505 int id = m_nextId;
506 m_nextId = nextFreeId(nextId(id), id);
507 return id;
510int TopLevelWindowModel::nextId(int id) const
512 if (id == m_maxId) {
513 return id = 1;
514 } else {
515 return id + 1;
516 }
519int TopLevelWindowModel::nextFreeId(int candidateId, const int latestId)
521 int firstCandidateId = candidateId;
523 while (indexForId(candidateId) != -1 || candidateId == latestId) {
524 candidateId = nextId(candidateId);
526 if (candidateId == firstCandidateId) {
527 qFatal("TopLevelWindowModel: run out of window ids.");
528 }
529 }
531 return candidateId;
534QString TopLevelWindowModel::toString()
536 QString str;
537 for (int i = 0; i < m_windowModel.count(); ++i) {
538 auto item = m_windowModel.at(i);
540 QString itemStr = QString("(index=%1,appId=%2,surface=0x%3,id=%4)")
541 .arg(QString::number(i),
542 item.application->appId(),
543 QString::number((qintptr)item.window->surface(), 16),
544 QString::number(item.window->id()));
546 if (i > 0) {
547 str.append(",");
548 }
549 str.append(itemStr);
550 }
551 return str;
554int TopLevelWindowModel::indexOf(unityapi::MirSurfaceInterface *surface)
556 for (int i = 0; i < m_windowModel.count(); ++i) {
557 if (m_windowModel.at(i).window->surface() == surface) {
558 return i;
559 }
560 }
561 return -1;
564int TopLevelWindowModel::indexForId(int id) const
566 for (int i = 0; i < m_windowModel.count(); ++i) {
567 if (m_windowModel[i].window->id() == id) {
568 return i;
569 }
570 }
571 return -1;
574Window *TopLevelWindowModel::windowAt(int index) const
576 if (index >=0 && index < m_windowModel.count()) {
577 return m_windowModel[index].window;
578 } else {
579 return nullptr;
580 }
583unityapi::MirSurfaceInterface *TopLevelWindowModel::surfaceAt(int index) const
585 if (index >=0 && index < m_windowModel.count()) {
586 return m_windowModel[index].window->surface();
587 } else {
588 return nullptr;
589 }
592unityapi::ApplicationInfoInterface *TopLevelWindowModel::applicationAt(int index) const
594 if (index >=0 && index < m_windowModel.count()) {
595 return m_windowModel[index].application;
596 } else {
597 return nullptr;
598 }
601int TopLevelWindowModel::idAt(int index) const
603 if (index >=0 && index < m_windowModel.count()) {
604 return m_windowModel[index].window->id();
605 } else {
606 return 0;
607 }
610void TopLevelWindowModel::raiseId(int id)
612 if (m_modelState == IdleState) {
613 DEBUG_MSG << "(id=" << id << ") - do it now.";
614 doRaiseId(id);
615 } else {
616 DEBUG_MSG << "(id=" << id << ") - Model busy (modelState=" << m_modelState << "). Try again in the next event loop.";
617 // The model has just signalled some change. If we have a Repeater responding to this update, it will get nuts
618 // if we perform yet another model change straight away.
619 //
620 // A bad sympton of this problem is a Repeater.itemAt(index) call returning null event though Repeater.count says
621 // the index is definitely within bounds.
622 QMetaObject::invokeMethod(this, "raiseId", Qt::QueuedConnection, Q_ARG(int, id));
623 }
626void TopLevelWindowModel::doRaiseId(int id)
628 int fromIndex = indexForId(id);
629 // can't raise something that doesn't exist or that it's already on top
630 if (fromIndex != -1 && fromIndex != 0) {
631 auto surface = m_windowModel[fromIndex].window->surface();
632 if (surface) {
633 m_surfaceManager->raise(surface);
634 } else {
635 // move it ourselves. Since there's no mir::scene::Surface/miral::Window, there's nothing
636 // miral can do about it.
637 move(fromIndex, 0);
638 }
639 }
642void TopLevelWindowModel::setFocusedWindow(Window *window)
644 if (window != m_focusedWindow) {
645 INFO_MSG << "(" << window << ")";
647 Window* previousWindow = m_focusedWindow;
649 m_focusedWindow = window;
650 Q_EMIT focusedWindowChanged(m_focusedWindow);
652 if (previousWindow && previousWindow->focused() && !previousWindow->surface()) {
653 // do it ourselves. miral doesn't know about this window
654 previousWindow->setFocused(false);
655 }
656 }
659unityapi::MirSurfaceInterface* TopLevelWindowModel::inputMethodSurface() const
661 return m_inputMethodWindow ? m_inputMethodWindow->surface() : nullptr;
664Window* TopLevelWindowModel::focusedWindow() const
666 return m_focusedWindow;
669void TopLevelWindowModel::move(int from, int to)
671 if (from == to) return;
672 DEBUG_MSG << " from=" << from << " to=" << to;
674 if (from >= 0 && from < m_windowModel.size() && to >= 0 && to < m_windowModel.size()) {
675 QModelIndex parent;
676 /* When moving an item down, the destination index needs to be incremented
677 by one, as explained in the documentation:
678 http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#beginMoveRows */
680 Q_ASSERT(m_modelState == IdleState);
681 m_modelState = MovingState;
683 beginMoveRows(parent, from, from, parent, to + (to > from ? 1 : 0));
684#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
685 const auto &window = m_windowModel.takeAt(from);
686 m_windowModel.insert(to, window);
687#else
688 m_windowModel.move(from, to);
689#endif
690 endMoveRows();
692 Q_EMIT listChanged();
693 m_modelState = IdleState;
695 INFO_MSG << " after " << toString();
696 }
698void TopLevelWindowModel::onModificationsStarted()
702void TopLevelWindowModel::onModificationsEnded()
704 if (m_focusedWindowChanged) {
705 setFocusedWindow(m_newlyFocusedWindow);
706 }
707 // reset
708 m_focusedWindowChanged = false;
709 m_newlyFocusedWindow = nullptr;
712void TopLevelWindowModel::activateTopMostWindowWithoutId(int forbiddenId)
714 DEBUG_MSG << "(" << forbiddenId << ")";
716 for (int i = 0; i < m_windowModel.count(); ++i) {
717 Window *window = m_windowModel[i].window;
718 if (window->id() != forbiddenId) {
719 window->activate();
720 }
721 }
724void TopLevelWindowModel::activateNullWindow()
726 if (!m_nullWindow->focused())
727 m_nullWindow->activate();