@@ -63,17 +63,23 @@ Rectangle {
6363 spread.state = "";
6464 }
6565
66− ApplicationManager.requestFocusApplication(appId)
66+ priv.addToFocusStack(appId);
67+ priv.focusFirstInStack();
68+ }
69+
70+ onApplicationRemoved: {
71+ priv.removeAndFocusPreviousInStack(appId);
6772 }
6873
6974 onFocusRequested: {
7075 var appIndex = priv.indexOf(appId);
7176 var appDelegate = appRepeater.itemAt(appIndex);
7277 appDelegate.minimized = false;
73− ApplicationManager.focusApplication(appId)
78+ ApplicationManager.focusApplication(appId);
79+ priv.addToFocusStack(appId);
7480
7581 if (spread.state == "altTab") {
76− spread.cancel()
82+ spread.cancel();
7783 }
7884 }
7985 }
@@ -88,7 +94,7 @@ Rectangle {
8894 }
8995 onFocusedAppDelegateChanged: { // restore the window from minimization when we focus it (e.g. using spread)
9096 if (priv.focusedAppDelegate && priv.focusedAppDelegate.minimized) {
91− priv.focusedAppDelegate.unmaximize()
97+ priv.focusedAppDelegate.restore()
9298 }
9399 }
94100
@@ -100,6 +106,35 @@ Rectangle {
100106 }
101107 return -1;
102108 }
109+
110+ property var focusStack: []
111+
112+ function addToFocusStack(appId) {
113+ if (appId === "unity8-dash")
114+ return;
115+ priv.focusStack.unshift(appId); // append to the top of the focus stack
116+ }
117+
118+ function removeAndFocusPreviousInStack(appId) {
119+ if (appId === "unity8-dash")
120+ return;
121+
122+ var removedIndex = priv.focusStack.indexOf(appId);
123+ if (removedIndex != -1) {
124+ priv.focusStack.splice(removedIndex, 1); // remove one item from the focus stack
125+ if (removedIndex > 1)
126+ ApplicationManager.focusApplication(priv.focusStack[removedIndex-1]); // focus the previous one
127+ else
128+ focusFirstInStack(); // focus the next/first one
129+ }
130+ }
131+
132+ function focusFirstInStack() {
133+ var newHead = priv.focusStack[0];
134+ if (newHead !== "") {
135+ ApplicationManager.focusApplication(newHead);
136+ }
137+ }
103138 }
104139
105140 Connections {
@@ -108,7 +143,7 @@ Rectangle {
108143 ApplicationManager.stopApplication(ApplicationManager.focusedApplicationId)
109144 }
110145 onMinimize: appRepeater.itemAt(0).minimize();
111− onMaximize: appRepeater.itemAt(0).unmaximize();
146+ onMaximize: appRepeater.itemAt(0).restore();
112147 }
113148
114149 Binding {
@@ -170,10 +205,12 @@ Rectangle {
170205 function minimize() {
171206 maximized = false;
172207 minimized = true;
208+ priv.removeAndFocusPreviousInStack(model.appId);
173209 }
174− function unmaximize() {
210+ function restore() {
175211 minimized = false;
176212 maximized = false;
213+ priv.addToFocusStack(model.appId);
177214 }
178215
179216 states: [