@@ -0,0 +1,644 @@
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+ */
16+
17+#include "TopLevelWindowModel.h"
18+
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>
25+
26+// Qt
27+#include <QGuiApplication>
28+#include <QDebug>
29+
30+// local
31+#include "Window.h"
32+
33+Q_LOGGING_CATEGORY(TOPLEVELWINDOWMODEL, "toplevelwindowmodel", QtInfoMsg)
34+
35+#define DEBUG_MSG qCDebug(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
36+#define INFO_MSG qCInfo(TOPLEVELWINDOWMODEL).nospace().noquote() << __func__
37+
38+namespace unityapi = unity::shell::application;
39+
40+TopLevelWindowModel::TopLevelWindowModel()
41+{
42+}
43+
44+void TopLevelWindowModel::setApplicationManager(unityapi::ApplicationManagerInterface* value)
45+{
46+ if (m_applicationManager == value) {
47+ return;
48+ }
49+
50+ DEBUG_MSG << "(" << value << ")";
51+
52+ Q_ASSERT(m_modelState == IdleState);
53+ m_modelState = ResettingState;
54+
55+ beginResetModel();
56+
57+ if (m_applicationManager) {
58+ m_windowModel.clear();
59+ disconnect(m_applicationManager, 0, this, 0);
60+ }
61+
62+ m_applicationManager = value;
63+
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+ });
72+
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+ });
80+
81+ for (int i = 0; i < m_applicationManager->rowCount(); ++i) {
82+ auto application = m_applicationManager->get(i);
83+ addApplication(application);
84+ }
85+ }
86+
87+ endResetModel();
88+ m_modelState = IdleState;
89+}
90+
91+void TopLevelWindowModel::setSurfaceManager(unityapi::SurfaceManagerInterface *surfaceManager)
92+{
93+ if (surfaceManager == m_surfaceManager) {
94+ return;
95+ }
96+
97+ DEBUG_MSG << "(" << surfaceManager << ")";
98+
99+ if (m_surfaceManager) {
100+ disconnect(m_surfaceManager, 0, this, 0);
101+ }
102+
103+ m_surfaceManager = surfaceManager;
104+
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+ }
111+
112+ Q_EMIT surfaceManagerChanged(m_surfaceManager);
113+}
114+
115+void TopLevelWindowModel::addApplication(unityapi::ApplicationInfoInterface *application)
116+{
117+ DEBUG_MSG << "(" << application->appId() << ")";
118+
119+ if (application->state() != unityapi::ApplicationInfoInterface::Stopped && application->surfaceList()->count() == 0) {
120+ prependPlaceholder(application);
121+ }
122+}
123+
124+void TopLevelWindowModel::removeApplication(unityapi::ApplicationInfoInterface *application)
125+{
126+ DEBUG_MSG << "(" << application->appId() << ")";
127+
128+ Q_ASSERT(m_modelState == IdleState);
129+
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+ }
138+}
139+
140+void TopLevelWindowModel::prependPlaceholder(unityapi::ApplicationInfoInterface *application)
141+{
142+ INFO_MSG << "(" << application->appId() << ")";
143+
144+ prependSurfaceHelper(nullptr, application);
145+}
146+
147+void TopLevelWindowModel::prependSurface(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
148+{
149+ Q_ASSERT(surface != nullptr);
150+
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+ }
162+
163+ if (!filledPlaceholder) {
164+ INFO_MSG << " appId=" << application->appId() << " surface=" << surface << ", adding new row";
165+ prependSurfaceHelper(surface, application);
166+ }
167+}
168+
169+void TopLevelWindowModel::prependSurfaceHelper(unityapi::MirSurfaceInterface *surface, unityapi::ApplicationInfoInterface *application)
170+{
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+ }
178+
179+ int id = generateId();
180+ Window *window = new Window(id, this);
181+ if (surface) {
182+ window->setSurface(surface);
183+ }
184+ m_windowModel.prepend(ModelEntry(window, application));
185+ if (surface) {
186+ connectSurface(surface);
187+ }
188+
189+ connectWindow(window);
190+
191+ if (m_modelState == InsertingState) {
192+ endInsertRows();
193+ Q_EMIT countChanged();
194+ Q_EMIT listChanged();
195+ m_modelState = IdleState;
196+ }
197+
198+ if (!surface) {
199+ // focus the newly added window. miral can't help with that as it doesn't know about it.
200+ window->setFocused(true);
201+ if (m_focusedWindow && m_focusedWindow->surface()) {
202+ m_surfaceManager->activate(nullptr);
203+ }
204+ }
205+
206+ INFO_MSG << " after " << toString();
207+}
208+
209+void TopLevelWindowModel::connectWindow(Window *window)
210+{
211+ connect(window, &Window::focusRequested, this, [this, window]() {
212+ if (!window->surface()) {
213+ activateEmptyWindow(window);
214+ }
215+ });
216+
217+ connect(window, &Window::focusedChanged, this, [this, window](bool focused) {
218+ if (window->surface()) {
219+ // Condense changes to the focused window
220+ // eg: Do focusedWindow=A to focusedWindow=B instead of
221+ // focusedWindow=A to focusedWindow=null to focusedWindow=B
222+ m_focusedWindowChanged = true;
223+ if (focused) {
224+ Q_ASSERT(m_newlyFocusedWindow == nullptr);
225+ m_newlyFocusedWindow = window;
226+ }
227+ }
228+ });
229+
230+ connect(window, &Window::closeRequested, this, [this, window]() {
231+ if (!window->surface()) {
232+ int index = indexForId(window->id());
233+ Q_ASSERT(index >= 0);
234+ m_windowModel[index].application->close();
235+ }
236+ });
237+
238+ connect(window, &Window::emptyWindowActivated, this, [this, window]() {
239+ activateEmptyWindow(window);
240+ });
241+}
242+
243+void TopLevelWindowModel::activateEmptyWindow(Window *window)
244+{
245+ Q_ASSERT(!window->surface());
246+
247+ // miral doesn't know about empty windows (ie, windows that are not backed up by MirSurfaces)
248+ // So we have to activate them ourselves (instead of asking SurfaceManager to do it for us).
249+
250+ window->setFocused(true);
251+ raiseId(window->id());
252+ Window *previousWindow = m_focusedWindow;
253+ setFocusedWindow(window);
254+ if (previousWindow && previousWindow->surface() && previousWindow->surface()->focused()) {
255+ m_surfaceManager->activate(nullptr);
256+ }
257+}
258+
259+void TopLevelWindowModel::connectSurface(unityapi::MirSurfaceInterface *surface)
260+{
261+ connect(surface, &unityapi::MirSurfaceInterface::liveChanged, this, [this, surface](bool live){
262+ if (!live) {
263+ onSurfaceDied(surface);
264+ }
265+ });
266+ connect(surface, &QObject::destroyed, this, [this, surface](){ this->onSurfaceDestroyed(surface); });
267+}
268+
269+void TopLevelWindowModel::onSurfaceDied(unityapi::MirSurfaceInterface *surface)
270+{
271+ if (surface->type() == Mir::InputMethodType) {
272+ removeInputMethodWindow();
273+ return;
274+ }
275+
276+ int i = indexOf(surface);
277+ if (i == -1) {
278+ return;
279+ }
280+
281+ auto application = m_windowModel[i].application;
282+
283+ // can't be starting if it already has a surface
284+ Q_ASSERT(application->state() != unityapi::ApplicationInfoInterface::Starting);
285+
286+ if (application->state() == unityapi::ApplicationInfoInterface::Running) {
287+ m_windowModel[i].removeOnceSurfaceDestroyed = true;
288+ } else {
289+ // assume it got killed by the out-of-memory daemon.
290+ //
291+ // So leave entry in the model and only remove its surface, so shell can display a screenshot
292+ // in its place.
293+ m_windowModel[i].removeOnceSurfaceDestroyed = false;
294+ }
295+}
296+
297+void TopLevelWindowModel::onSurfaceDestroyed(unityapi::MirSurfaceInterface *surface)
298+{
299+ int i = indexOf(surface);
300+ if (i == -1) {
301+ return;
302+ }
303+
304+ if (m_windowModel[i].removeOnceSurfaceDestroyed) {
305+ removeAt(i);
306+ } else {
307+ auto window = m_windowModel[i].window;
308+ window->setSurface(nullptr);
309+ window->setFocused(false);
310+ INFO_MSG << " Removed surface from entry. After: " << toString();
311+ }
312+}
313+
314+void TopLevelWindowModel::onSurfaceCreated(unityapi::MirSurfaceInterface *surface)
315+{
316+ DEBUG_MSG << "(" << surface << ")";
317+ if (surface->type() == Mir::InputMethodType) {
318+ int id = generateId();
319+ Window *qmlWindow = new Window(id, this);
320+ connectWindow(qmlWindow);
321+ qmlWindow->setSurface(surface);
322+ setInputMethodWindow(qmlWindow);
323+ } else {
324+ auto application = m_applicationManager->findApplicationWithSurface(surface);
325+ if (application) {
326+ prependSurface(surface, application);
327+ } else {
328+ // Must be a prompt session. No need to do add it as a prompt surface is not top-level.
329+ // It will show up in the ApplicationInfoInterface::promptSurfaceList of some application.
330+ // Still wrap it in a Window though, so that we keep focusedWindow() up to date.
331+ int id = generateId();
332+ Window *promptWindow = new Window(id, this);
333+ connectWindow(promptWindow);
334+ promptWindow->setSurface(surface);
335+ connect(surface, &QObject::destroyed, promptWindow, [=](){
336+ promptWindow->setSurface(nullptr);
337+ promptWindow->deleteLater();
338+ });
339+ }
340+ }
341+ // TODO: handle surfaces that are neither top-level windows nor input method. eg: child dialogs, popups, menus
342+}
343+
344+void TopLevelWindowModel::removeAt(int index)
345+{
346+ if (m_modelState == IdleState) {
347+ beginRemoveRows(QModelIndex(), index, index);
348+ m_modelState = RemovingState;
349+ } else {
350+ Q_ASSERT(m_modelState == ResettingState);
351+ // No point in signaling anything if we're resetting the whole model
352+ }
353+
354+ auto window = m_windowModel[index].window;
355+
356+ window->setSurface(nullptr);
357+ window->setFocused(false);
358+
359+ m_windowModel.removeAt(index);
360+
361+ if (m_modelState == RemovingState) {
362+ endRemoveRows();
363+ Q_EMIT countChanged();
364+ Q_EMIT listChanged();
365+ m_modelState = IdleState;
366+ }
367+
368+ disconnect(window, 0, this, 0);
369+ if (m_focusedWindow == window) {
370+ setFocusedWindow(nullptr);
371+ }
372+ delete window;
373+
374+ INFO_MSG << " after " << toString();
375+}
376+
377+void TopLevelWindowModel::setInputMethodWindow(Window *window)
378+{
379+ if (m_inputMethodWindow) {
380+ qWarning("Multiple Input Method Surfaces created, removing the old one!");
381+ delete m_inputMethodWindow;
382+ }
383+ m_inputMethodWindow = window;
384+ Q_EMIT inputMethodSurfaceChanged(m_inputMethodWindow->surface());
385+}
386+
387+void TopLevelWindowModel::removeInputMethodWindow()
388+{
389+ if (m_inputMethodWindow) {
390+ delete m_inputMethodWindow;
391+ m_inputMethodWindow = nullptr;
392+ Q_EMIT inputMethodSurfaceChanged(nullptr);
393+ }
394+}
395+
396+void TopLevelWindowModel::onSurfacesRaised(const QVector<unityapi::MirSurfaceInterface*> &surfaces)
397+{
398+ DEBUG_MSG << "(" << surfaces << ")";
399+ const int raiseCount = surfaces.size();
400+ for (int i = 0; i < raiseCount; i++) {
401+ int fromIndex = findIndexOf(surfaces[i]);
402+ if (fromIndex != -1) {
403+ move(fromIndex, 0);
404+ }
405+ }
406+}
407+
408+int TopLevelWindowModel::rowCount(const QModelIndex &/*parent*/) const
409+{
410+ return m_windowModel.count();
411+}
412+
413+QVariant TopLevelWindowModel::data(const QModelIndex& index, int role) const
414+{
415+ if (index.row() < 0 || index.row() >= m_windowModel.size())
416+ return QVariant();
417+
418+ if (role == WindowRole) {
419+ Window *window = m_windowModel.at(index.row()).window;
420+ return QVariant::fromValue(window);
421+ } else if (role == ApplicationRole) {
422+ return QVariant::fromValue(m_windowModel.at(index.row()).application);
423+ } else {
424+ return QVariant();
425+ }
426+}
427+
428+int TopLevelWindowModel::findIndexOf(const unityapi::MirSurfaceInterface *surface) const
429+{
430+ for (int i=0; i<m_windowModel.count(); i++) {
431+ if (m_windowModel[i].window->surface() == surface) {
432+ return i;
433+ }
434+ }
435+ return -1;
436+}
437+
438+int TopLevelWindowModel::generateId()
439+{
440+ int id = m_nextId;
441+ m_nextId = nextFreeId(nextId(id), id);
442+ return id;
443+}
444+
445+int TopLevelWindowModel::nextId(int id) const
446+{
447+ if (id == m_maxId) {
448+ return id = 1;
449+ } else {
450+ return id + 1;
451+ }
452+}
453+
454+int TopLevelWindowModel::nextFreeId(int candidateId, const int latestId)
455+{
456+ int firstCandidateId = candidateId;
457+
458+ while (indexForId(candidateId) != -1 || candidateId == latestId) {
459+ candidateId = nextId(candidateId);
460+
461+ if (candidateId == firstCandidateId) {
462+ qFatal("TopLevelWindowModel: run out of window ids.");
463+ }
464+ }
465+
466+ return candidateId;
467+}
468+
469+QString TopLevelWindowModel::toString()
470+{
471+ QString str;
472+ for (int i = 0; i < m_windowModel.count(); ++i) {
473+ auto item = m_windowModel.at(i);
474+
475+ QString itemStr = QString("(index=%1,appId=%2,surface=0x%3,id=%4)")
476+ .arg(QString::number(i),
477+ item.application->appId(),
478+ QString::number((qintptr)item.window->surface(), 16),
479+ QString::number(item.window->id()));
480+
481+ if (i > 0) {
482+ str.append(",");
483+ }
484+ str.append(itemStr);
485+ }
486+ return str;
487+}
488+
489+int TopLevelWindowModel::indexOf(unityapi::MirSurfaceInterface *surface)
490+{
491+ for (int i = 0; i < m_windowModel.count(); ++i) {
492+ if (m_windowModel.at(i).window->surface() == surface) {
493+ return i;
494+ }
495+ }
496+ return -1;
497+}
498+
499+int TopLevelWindowModel::indexForId(int id) const
500+{
501+ for (int i = 0; i < m_windowModel.count(); ++i) {
502+ if (m_windowModel[i].window->id() == id) {
503+ return i;
504+ }
505+ }
506+ return -1;
507+}
508+
509+Window *TopLevelWindowModel::windowAt(int index) const
510+{
511+ if (index >=0 && index < m_windowModel.count()) {
512+ return m_windowModel[index].window;
513+ } else {
514+ return nullptr;
515+ }
516+}
517+
518+unityapi::MirSurfaceInterface *TopLevelWindowModel::surfaceAt(int index) const
519+{
520+ if (index >=0 && index < m_windowModel.count()) {
521+ return m_windowModel[index].window->surface();
522+ } else {
523+ return nullptr;
524+ }
525+}
526+
527+unityapi::ApplicationInfoInterface *TopLevelWindowModel::applicationAt(int index) const
528+{
529+ if (index >=0 && index < m_windowModel.count()) {
530+ return m_windowModel[index].application;
531+ } else {
532+ return nullptr;
533+ }
534+}
535+
536+int TopLevelWindowModel::idAt(int index) const
537+{
538+ if (index >=0 && index < m_windowModel.count()) {
539+ return m_windowModel[index].window->id();
540+ } else {
541+ return 0;
542+ }
543+}
544+
545+void TopLevelWindowModel::raiseId(int id)
546+{
547+ if (m_modelState == IdleState) {
548+ DEBUG_MSG << "(id=" << id << ") - do it now.";
549+ doRaiseId(id);
550+ } else {
551+ DEBUG_MSG << "(id=" << id << ") - Model busy (modelState=" << m_modelState << "). Try again in the next event loop.";
552+ // The model has just signalled some change. If we have a Repeater responding to this update, it will get nuts
553+ // if we perform yet another model change straight away.
554+ //
555+ // A bad sympton of this problem is a Repeater.itemAt(index) call returning null event though Repeater.count says
556+ // the index is definitely within bounds.
557+ QMetaObject::invokeMethod(this, "raiseId", Qt::QueuedConnection, Q_ARG(int, id));
558+ }
559+}
560+
561+void TopLevelWindowModel::doRaiseId(int id)
562+{
563+ int fromIndex = indexForId(id);
564+ if (fromIndex != -1) {
565+ auto surface = m_windowModel[fromIndex].window->surface();
566+ if (surface) {
567+ m_surfaceManager->raise(surface);
568+ } else {
569+ // move it ourselves. Since there's no mir::scene::Surface/miral::Window, there's nothing
570+ // miral can do about it.
571+ move(fromIndex, 0);
572+ }
573+ }
574+}
575+
576+void TopLevelWindowModel::setFocusedWindow(Window *window)
577+{
578+ if (window != m_focusedWindow) {
579+ INFO_MSG << "(" << window << ")";
580+
581+ Window* previousWindow = m_focusedWindow;
582+
583+ m_focusedWindow = window;
584+ Q_EMIT focusedWindowChanged(m_focusedWindow);
585+
586+ if (previousWindow && previousWindow->focused() && !previousWindow->surface()) {
587+ // do it ourselves. miral doesn't know about this window
588+ previousWindow->setFocused(false);
589+ }
590+ }
591+}
592+
593+unityapi::MirSurfaceInterface* TopLevelWindowModel::inputMethodSurface() const
594+{
595+ return m_inputMethodWindow ? m_inputMethodWindow->surface() : nullptr;
596+}
597+
598+Window* TopLevelWindowModel::focusedWindow() const
599+{
600+ return m_focusedWindow;
601+}
602+
603+void TopLevelWindowModel::move(int from, int to)
604+{
605+ if (from == to) return;
606+ DEBUG_MSG << " from=" << from << " to=" << to;
607+
608+ if (from >= 0 && from < m_windowModel.size() && to >= 0 && to < m_windowModel.size()) {
609+ QModelIndex parent;
610+ /* When moving an item down, the destination index needs to be incremented
611+ by one, as explained in the documentation:
612+ http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#beginMoveRows */
613+
614+ Q_ASSERT(m_modelState == IdleState);
615+ m_modelState = MovingState;
616+
617+ beginMoveRows(parent, from, from, parent, to + (to > from ? 1 : 0));
618+#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
619+ const auto &window = m_windowModel.takeAt(from);
620+ m_windowModel.insert(to, window);
621+#else
622+ m_windowModel.move(from, to);
623+#endif
624+ endMoveRows();
625+
626+ Q_EMIT listChanged();
627+ m_modelState = IdleState;
628+
629+ INFO_MSG << " after " << toString();
630+ }
631+}
632+void TopLevelWindowModel::onModificationsStarted()
633+{
634+}
635+
636+void TopLevelWindowModel::onModificationsEnded()
637+{
638+ if (m_focusedWindowChanged) {
639+ setFocusedWindow(m_newlyFocusedWindow);
640+ }
641+ // reset
642+ m_focusedWindowChanged = false;
643+ m_newlyFocusedWindow = nullptr;
644+}