on 32458de help sign in
unity8/plugins/WindowManager/TopLevelWindowModel.cpp
677 lines 21 kB history raw
1/*
2 * Copyright (C) 2016 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()
44void TopLevelWindowModel::setApplicationManager(unityapi::ApplicationManagerInterface* value)
46 if (m_applicationManager == value) {
47 return;
48 }
50 DEBUG_MSG << "(" << value << ")";
52 Q_ASSERT(m_modelState == IdleState);
53 m_modelState = ResettingState;
55 beginResetModel();
57 if (m_applicationManager) {
58 m_windowModel.clear();
59 disconnect(m_applicationManager, 0, this, 0);
60 }
62 m_applicationManager = value;
64 if (m_applicationManager) {
65 connect(m_applicationManager, &QAbstractItemModel::rowsInserted,
66 this, [this](const QModelIndex &/*parent*/, int first, int last) {
67 for (int i = first; i <= last; ++i) {
68 auto application = m_applicationManager->get(i);
69 addApplication(application);
70 }
71 });
73 connect(m_applicationManager, &QAbstractItemModel::rowsAboutToBeRemoved,
74 this, [this](const QModelIndex &/*parent*/, int first, int last) {
75 for (int i = first; i <= last; ++i) {
76 auto application = m_applicationManager->get(i);
77 removeApplication(application);
78 }
79 });
81 for (int i = 0; i < m_applicationManager->rowCount(); ++i) {
82 auto application = m_applicationManager->get(i);
83 addApplication(application);
84 }
85 }
87 endResetModel();
88 m_modelState = IdleState;
91void TopLevelWindowModel::setSurfaceManager(unityapi::SurfaceManagerInterface *surfaceManager)
93 if (surfaceManager == m_surfaceManager) {
94 return;
95 }
97 DEBUG_MSG << "(" << surfaceManager << ")";
99 if (m_surfaceManager) {
100 disconnect(m_surfaceManager, 0, this, 0);
101 }
103 m_surfaceManager = surfaceManager;
105 if (m_surfaceManager) {
106 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfaceCreated, this, &TopLevelWindowModel::onSurfaceCreated);
107 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::surfacesRaised, this, &TopLevelWindowModel::onSurfacesRaised);
108 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsStarted, this, &TopLevelWindowModel::onModificationsStarted);
109 connect(m_surfaceManager, &unityapi::SurfaceManagerInterface::modificationsEnded, this, &TopLevelWindowModel::onModificationsEnded);
110 }
112 Q_EMIT surfaceManagerChanged(m_surfaceManager);
115void TopLevelWindowModel::addApplication(unityapi::ApplicationInfoInterface *application)
117 DEBUG_MSG << "(" << application->appId() << ")";
119 if (application->state() != unityapi::ApplicationInfoInterface::Stopped && application->surfaceList()->count() == 0) {
120 prependPlaceholder(application);
121 }
124void TopLevelWindowModel::removeApplication(unityapi::ApplicationInfoInterface *application)
126 DEBUG_MSG << "(" << application->appId() << ")";
128 Q_ASSERT(m_modelState == IdleState);
130 int i = 0;
131 while (i < m_windowModel.count()) {
132 if (m_windowModel.at(i).application == application) {
133 removeAt(i);
134 } else {
135 ++i;
136 }
137 }
140void TopLevelWindowModel::prependPlaceholder(unityapi::ApplicationInfoInterface *application)
142 INFO_MSG << "(" << application->appId() << ")";
144 prependSurfaceHelper(nullptr, application);
147void TopLevelWindowModel::prependSurface(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
149 Q_ASSERT(surface != nullptr);
151 bool filledPlaceholder = false;
152 for (int i = 0; i < m_windowModel.count() && !filledPlaceholder; ++i) {
153 ModelEntry &entry = m_windowModel[i];
154 if (entry.application == application && entry.window->surface() == nullptr) {
155 entry.window->setSurface(surface);
156 connectSurface(surface);
157 INFO_MSG << " appId=" << application->appId() << " surface=" << surface
158 << ", filling out placeholder. after: " << toString();
159 filledPlaceholder = true;
160 }
161 }
163 if (!filledPlaceholder) {
164 INFO_MSG << " appId=" << application->appId() << " surface=" << surface << ", adding new row";
165 prependSurfaceHelper(surface, application);
166 }
169void TopLevelWindowModel::prependSurfaceHelper(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
171 if (m_modelState == IdleState) {
172 m_modelState = InsertingState;
173 beginInsertRows(QModelIndex(), 0 /*first*/, 0 /*last*/);
174 } else {
175 Q_ASSERT(m_modelState == ResettingState);
176 // No point in signaling anything if we're resetting the whole model
177 }
179 Window *window = createWindow(surface);
181 m_windowModel.prepend(ModelEntry(window, application));
182 if (surface) {
183 connectSurface(surface);
184 }
186 if (m_modelState == InsertingState) {
187 endInsertRows();
188 Q_EMIT countChanged();
189 Q_EMIT listChanged();
190 m_modelState = IdleState;
191 }
193 if (!surface) {
194 activateEmptyWindow(window);
195 }
197 INFO_MSG << " after " << toString();
200void TopLevelWindowModel::connectWindow(Window *window)
202 connect(window, &Window::focusRequested, this, [this, window]() {
203 if (!window->surface()) {
204 activateEmptyWindow(window);
205 }
206 });
208 connect(window, &Window::focusedChanged, this, [this, window](bool focused) {
209 if (window->surface()) {
210 // Condense changes to the focused window
211 // eg: Do focusedWindow=A to focusedWindow=B instead of
212 // focusedWindow=A to focusedWindow=null to focusedWindow=B
213 if (focused) {
214 Q_ASSERT(m_newlyFocusedWindow == nullptr);
215 m_focusedWindowChanged = true;
216 m_newlyFocusedWindow = window;
217 } else if (m_focusedWindow == window) {
218 m_focusedWindowChanged = true;
219 } else {
220 // don't clear the focused window if you were not there in the first place
221 // happens when a filled window gets replaced with an empty one (no surface) as the focused window.
222 }
223 }
224 });
226 connect(window, &Window::closeRequested, this, [this, window]() {
227 if (!window->surface()) {
228 // do things ourselves as miral doesn't know about this window
229 int id = window->id();
230 int index = indexForId(id);
231 bool focusOther = false;
232 Q_ASSERT(index >= 0);
233 if (window->focused()) {
234 focusOther = true;
235 }
236 m_windowModel[index].application->close();
237 if (focusOther) {
238 activateTopMostWindowWithoutId(id);
239 }
240 }
241 });
243 connect(window, &Window::emptyWindowActivated, this, [this, window]() {
244 activateEmptyWindow(window);
245 });
248void TopLevelWindowModel::activateEmptyWindow(Window *window)
250 Q_ASSERT(!window->surface());
251 DEBUG_MSG << "(" << window << ")";
253 // miral doesn't know about empty windows (ie, windows that are not backed up by MirSurfaces)
254 // So we have to activate them ourselves (instead of asking SurfaceManager to do it for us).
256 window->setFocused(true);
257 raiseId(window->id());
258 Window *previousWindow = m_focusedWindow;
259 setFocusedWindow(window);
260 if (previousWindow && previousWindow->surface() && previousWindow->surface()->focused()) {
261 m_surfaceManager->activate(nullptr);
262 }
265void TopLevelWindowModel::connectSurface(unityapi::MirSurfaceInterface *surface)
267 connect(surface, &unityapi::MirSurfaceInterface::liveChanged, this, [this, surface](bool live){
268 if (!live) {
269 onSurfaceDied(surface);
270 }
271 });
272 connect(surface, &QObject::destroyed, this, [this, surface](){ this->onSurfaceDestroyed(surface); });
275void TopLevelWindowModel::onSurfaceDied(unityapi::MirSurfaceInterface *surface)
277 if (surface->type() == Mir::InputMethodType) {
278 removeInputMethodWindow();
279 return;
280 }
282 int i = indexOf(surface);
283 if (i == -1) {
284 return;
285 }
287 auto application = m_windowModel[i].application;
289 // can't be starting if it already has a surface
290 Q_ASSERT(application->state() != unityapi::ApplicationInfoInterface::Starting);
292 if (application->state() == unityapi::ApplicationInfoInterface::Running) {
293 m_windowModel[i].removeOnceSurfaceDestroyed = true;
294 } else {
295 // assume it got killed by the out-of-memory daemon.
296 //
297 // So leave entry in the model and only remove its surface, so shell can display a screenshot
298 // in its place.
299 m_windowModel[i].removeOnceSurfaceDestroyed = false;
300 }
303void TopLevelWindowModel::onSurfaceDestroyed(unityapi::MirSurfaceInterface *surface)
305 int i = indexOf(surface);
306 if (i == -1) {
307 return;
308 }
310 if (m_windowModel[i].removeOnceSurfaceDestroyed) {
311 removeAt(i);
312 } else {
313 auto window = m_windowModel[i].window;
314 window->setSurface(nullptr);
315 window->setFocused(false);
316 INFO_MSG << " Removed surface from entry. After: " << toString();
317 }
320Window *TopLevelWindowModel::createWindow(unityapi::MirSurfaceInterface *surface)
322 int id = generateId();
323 Window *qmlWindow = new Window(id, this);
324 connectWindow(qmlWindow);
325 if (surface) {
326 qmlWindow->setSurface(surface);
327 }
328 return qmlWindow;
331void TopLevelWindowModel::onSurfaceCreated(unityapi::MirSurfaceInterface *surface)
333 DEBUG_MSG << "(" << surface << ")";
335 if (surface->parentSurface()) {
336 // Wrap it in a Window so that we keep focusedWindow() up to date.
337 Window *window = createWindow(surface);
338 connect(surface, &QObject::destroyed, window, [=](){
339 window->setSurface(nullptr);
340 window->deleteLater();
341 });
342 } else {
343 if (surface->type() == Mir::InputMethodType) {
344 connectSurface(surface);
345 setInputMethodWindow(createWindow(surface));
346 } else {
347 auto *application = m_applicationManager->findApplicationWithSurface(surface);
348 if (application) {
349 prependSurface(surface, application);
350 } else {
351 // Must be a prompt session. No need to do add it as a prompt surface is not top-level.
352 // It will show up in the ApplicationInfoInterface::promptSurfaceList of some application.
353 // Still wrap it in a Window though, so that we keep focusedWindow() up to date.
354 Window *promptWindow = createWindow(surface);
355 connect(surface, &QObject::destroyed, promptWindow, [=](){
356 promptWindow->setSurface(nullptr);
357 promptWindow->deleteLater();
358 });
359 }
360 }
361 }
364void TopLevelWindowModel::removeAt(int index)
366 if (m_modelState == IdleState) {
367 beginRemoveRows(QModelIndex(), index, index);
368 m_modelState = RemovingState;
369 } else {
370 Q_ASSERT(m_modelState == ResettingState);
371 // No point in signaling anything if we're resetting the whole model
372 }
374 auto window = m_windowModel[index].window;
376 window->setSurface(nullptr);
377 window->setFocused(false);
379 m_windowModel.removeAt(index);
381 if (m_modelState == RemovingState) {
382 endRemoveRows();
383 Q_EMIT countChanged();
384 Q_EMIT listChanged();
385 m_modelState = IdleState;
386 }
388 disconnect(window, 0, this, 0);
389 if (m_focusedWindow == window) {
390 setFocusedWindow(nullptr);
391 }
392 delete window;
394 INFO_MSG << " after " << toString();
397void TopLevelWindowModel::setInputMethodWindow(Window *window)
399 if (m_inputMethodWindow) {
400 qWarning("Multiple Input Method Surfaces created, removing the old one!");
401 delete m_inputMethodWindow;
402 }
403 m_inputMethodWindow = window;
404 Q_EMIT inputMethodSurfaceChanged(m_inputMethodWindow->surface());
407void TopLevelWindowModel::removeInputMethodWindow()
409 if (m_inputMethodWindow) {
410 delete m_inputMethodWindow;
411 m_inputMethodWindow = nullptr;
412 Q_EMIT inputMethodSurfaceChanged(nullptr);
413 }
416void TopLevelWindowModel::onSurfacesRaised(const QVector<unityapi::MirSurfaceInterface*> &surfaces)
418 DEBUG_MSG << "(" << surfaces << ")";
419 const int raiseCount = surfaces.size();
420 for (int i = 0; i < raiseCount; i++) {
421 int fromIndex = findIndexOf(surfaces[i]);
422 if (fromIndex != -1) {
423 move(fromIndex, 0);
424 }
425 }
428int TopLevelWindowModel::rowCount(const QModelIndex &/*parent*/) const
430 return m_windowModel.count();
433QVariant TopLevelWindowModel::data(const QModelIndex& index, int role) const
435 if (index.row() < 0 || index.row() >= m_windowModel.size())
436 return QVariant();
438 if (role == WindowRole) {
439 Window *window = m_windowModel.at(index.row()).window;
440 return QVariant::fromValue(window);
441 } else if (role == ApplicationRole) {
442 return QVariant::fromValue(m_windowModel.at(index.row()).application);
443 } else {
444 return QVariant();
445 }
448int TopLevelWindowModel::findIndexOf(const unityapi::MirSurfaceInterface *surface) const
450 for (int i=0; i<m_windowModel.count(); i++) {
451 if (m_windowModel[i].window->surface() == surface) {
452 return i;
453 }
454 }
455 return -1;
458int TopLevelWindowModel::generateId()
460 int id = m_nextId;
461 m_nextId = nextFreeId(nextId(id), id);
462 return id;
465int TopLevelWindowModel::nextId(int id) const
467 if (id == m_maxId) {
468 return id = 1;
469 } else {
470 return id + 1;
471 }
474int TopLevelWindowModel::nextFreeId(int candidateId, const int latestId)
476 int firstCandidateId = candidateId;
478 while (indexForId(candidateId) != -1 || candidateId == latestId) {
479 candidateId = nextId(candidateId);
481 if (candidateId == firstCandidateId) {
482 qFatal("TopLevelWindowModel: run out of window ids.");
483 }
484 }
486 return candidateId;
489QString TopLevelWindowModel::toString()
491 QString str;
492 for (int i = 0; i < m_windowModel.count(); ++i) {
493 auto item = m_windowModel.at(i);
495 QString itemStr = QString("(index=%1,appId=%2,surface=0x%3,id=%4)")
496 .arg(QString::number(i),
497 item.application->appId(),
498 QString::number((qintptr)item.window->surface(), 16),
499 QString::number(item.window->id()));
501 if (i > 0) {
502 str.append(",");
503 }
504 str.append(itemStr);
505 }
506 return str;
509int TopLevelWindowModel::indexOf(unityapi::MirSurfaceInterface *surface)
511 for (int i = 0; i < m_windowModel.count(); ++i) {
512 if (m_windowModel.at(i).window->surface() == surface) {
513 return i;
514 }
515 }
516 return -1;
519int TopLevelWindowModel::indexForId(int id) const
521 for (int i = 0; i < m_windowModel.count(); ++i) {
522 if (m_windowModel[i].window->id() == id) {
523 return i;
524 }
525 }
526 return -1;
529Window *TopLevelWindowModel::windowAt(int index) const
531 if (index >=0 && index < m_windowModel.count()) {
532 return m_windowModel[index].window;
533 } else {
534 return nullptr;
535 }
538unityapi::MirSurfaceInterface *TopLevelWindowModel::surfaceAt(int index) const
540 if (index >=0 && index < m_windowModel.count()) {
541 return m_windowModel[index].window->surface();
542 } else {
543 return nullptr;
544 }
547unityapi::ApplicationInfoInterface *TopLevelWindowModel::applicationAt(int index) const
549 if (index >=0 && index < m_windowModel.count()) {
550 return m_windowModel[index].application;
551 } else {
552 return nullptr;
553 }
556int TopLevelWindowModel::idAt(int index) const
558 if (index >=0 && index < m_windowModel.count()) {
559 return m_windowModel[index].window->id();
560 } else {
561 return 0;
562 }
565void TopLevelWindowModel::raiseId(int id)
567 if (m_modelState == IdleState) {
568 DEBUG_MSG << "(id=" << id << ") - do it now.";
569 doRaiseId(id);
570 } else {
571 DEBUG_MSG << "(id=" << id << ") - Model busy (modelState=" << m_modelState << "). Try again in the next event loop.";
572 // The model has just signalled some change. If we have a Repeater responding to this update, it will get nuts
573 // if we perform yet another model change straight away.
574 //
575 // A bad sympton of this problem is a Repeater.itemAt(index) call returning null event though Repeater.count says
576 // the index is definitely within bounds.
577 QMetaObject::invokeMethod(this, "raiseId", Qt::QueuedConnection, Q_ARG(int, id));
578 }
581void TopLevelWindowModel::doRaiseId(int id)
583 int fromIndex = indexForId(id);
584 // can't raise something that doesn't exist or that it's already on top
585 if (fromIndex != -1 && fromIndex != 0) {
586 auto surface = m_windowModel[fromIndex].window->surface();
587 if (surface) {
588 m_surfaceManager->raise(surface);
589 } else {
590 // move it ourselves. Since there's no mir::scene::Surface/miral::Window, there's nothing
591 // miral can do about it.
592 move(fromIndex, 0);
593 }
594 }
597void TopLevelWindowModel::setFocusedWindow(Window *window)
599 if (window != m_focusedWindow) {
600 INFO_MSG << "(" << window << ")";
602 Window* previousWindow = m_focusedWindow;
604 m_focusedWindow = window;
605 Q_EMIT focusedWindowChanged(m_focusedWindow);
607 if (previousWindow && previousWindow->focused() && !previousWindow->surface()) {
608 // do it ourselves. miral doesn't know about this window
609 previousWindow->setFocused(false);
610 }
611 }
614unityapi::MirSurfaceInterface* TopLevelWindowModel::inputMethodSurface() const
616 return m_inputMethodWindow ? m_inputMethodWindow->surface() : nullptr;
619Window* TopLevelWindowModel::focusedWindow() const
621 return m_focusedWindow;
624void TopLevelWindowModel::move(int from, int to)
626 if (from == to) return;
627 DEBUG_MSG << " from=" << from << " to=" << to;
629 if (from >= 0 && from < m_windowModel.size() && to >= 0 && to < m_windowModel.size()) {
630 QModelIndex parent;
631 /* When moving an item down, the destination index needs to be incremented
632 by one, as explained in the documentation:
633 http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#beginMoveRows */
635 Q_ASSERT(m_modelState == IdleState);
636 m_modelState = MovingState;
638 beginMoveRows(parent, from, from, parent, to + (to > from ? 1 : 0));
639#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
640 const auto &window = m_windowModel.takeAt(from);
641 m_windowModel.insert(to, window);
642#else
643 m_windowModel.move(from, to);
644#endif
645 endMoveRows();
647 Q_EMIT listChanged();
648 m_modelState = IdleState;
650 INFO_MSG << " after " << toString();
651 }
653void TopLevelWindowModel::onModificationsStarted()
657void TopLevelWindowModel::onModificationsEnded()
659 if (m_focusedWindowChanged) {
660 setFocusedWindow(m_newlyFocusedWindow);
661 }
662 // reset
663 m_focusedWindowChanged = false;
664 m_newlyFocusedWindow = nullptr;
667void TopLevelWindowModel::activateTopMostWindowWithoutId(int forbiddenId)
669 DEBUG_MSG << "(" << forbiddenId << ")";
671 for (int i = 0; i < m_windowModel.count(); ++i) {
672 Window *window = m_windowModel[i].window;
673 if (window->id() != forbiddenId) {
674 window->activate();
675 }
676 }