1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app.servertransaction;
18 
19 import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
20 import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
21 import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
22 import static android.app.servertransaction.ActivityLifecycleItem.ON_RESTART;
23 import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
24 import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
25 import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
26 import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
27 import static android.app.servertransaction.ActivityLifecycleItem.UNDEFINED;
28 
29 import android.app.Activity;
30 import android.app.ActivityThread.ActivityClientRecord;
31 import android.app.ClientTransactionHandler;
32 import android.os.IBinder;
33 import android.util.IntArray;
34 
35 import com.android.internal.annotations.VisibleForTesting;
36 
37 import java.io.PrintWriter;
38 import java.io.StringWriter;
39 import java.util.List;
40 
41 /**
42  * Helper class for {@link TransactionExecutor} that contains utils for lifecycle path resolution.
43  * @hide
44  */
45 public class TransactionExecutorHelper {
46     // A penalty applied to path with destruction when looking for the shortest one.
47     private static final int DESTRUCTION_PENALTY = 10;
48 
49     private static final int[] ON_RESUME_PRE_EXCUTION_STATES = new int[] { ON_START, ON_PAUSE };
50 
51     // Temp holder for lifecycle path.
52     // No direct transition between two states should take more than one complete cycle of 6 states.
53     @ActivityLifecycleItem.LifecycleState
54     private IntArray mLifecycleSequence = new IntArray(6);
55 
56     /**
57      * Calculate the path through main lifecycle states for an activity and fill
58      * @link #mLifecycleSequence} with values starting with the state that follows the initial
59      * state.
60      * <p>NOTE: The returned value is used internally in this class and is not a copy. It's contents
61      * may change after calling other methods of this class.</p>
62      */
63     @VisibleForTesting
getLifecyclePath(int start, int finish, boolean excludeLastState)64     public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
65         if (start == UNDEFINED || finish == UNDEFINED) {
66             throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
67         }
68         if (start == ON_RESTART || finish == ON_RESTART) {
69             throw new IllegalArgumentException(
70                     "Can't start or finish in intermittent RESTART state");
71         }
72         if (finish == PRE_ON_CREATE && start != finish) {
73             throw new IllegalArgumentException("Can only start in pre-onCreate state");
74         }
75 
76         mLifecycleSequence.clear();
77         if (finish >= start) {
78             // just go there
79             for (int i = start + 1; i <= finish; i++) {
80                 mLifecycleSequence.add(i);
81             }
82         } else { // finish < start, can't just cycle down
83             if (start == ON_PAUSE && finish == ON_RESUME) {
84                 // Special case when we can just directly go to resumed state.
85                 mLifecycleSequence.add(ON_RESUME);
86             } else if (start <= ON_STOP && finish >= ON_START) {
87                 // Restart and go to required state.
88 
89                 // Go to stopped state first.
90                 for (int i = start + 1; i <= ON_STOP; i++) {
91                     mLifecycleSequence.add(i);
92                 }
93                 // Restart
94                 mLifecycleSequence.add(ON_RESTART);
95                 // Go to required state
96                 for (int i = ON_START; i <= finish; i++) {
97                     mLifecycleSequence.add(i);
98                 }
99             } else {
100                 // Relaunch and go to required state
101 
102                 // Go to destroyed state first.
103                 for (int i = start + 1; i <= ON_DESTROY; i++) {
104                     mLifecycleSequence.add(i);
105                 }
106                 // Go to required state
107                 for (int i = ON_CREATE; i <= finish; i++) {
108                     mLifecycleSequence.add(i);
109                 }
110             }
111         }
112 
113         // Remove last transition in case we want to perform it with some specific params.
114         if (excludeLastState && mLifecycleSequence.size() != 0) {
115             mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
116         }
117 
118         return mLifecycleSequence;
119     }
120 
121     /**
122      * Pick a state that goes before provided post-execution state and would require the least
123      * lifecycle transitions to get to.
124      * It will also make sure to try avoiding a path with activity destruction and relaunch if
125      * possible.
126      * @param r An activity that we're trying to resolve the transition for.
127      * @param postExecutionState Post execution state to compute for.
128      * @return One of states that precede the provided post-execution state, or
129      *         {@link ActivityLifecycleItem#UNDEFINED} if there is not path.
130      */
131     @VisibleForTesting
getClosestPreExecutionState(ActivityClientRecord r, int postExecutionState)132     public int getClosestPreExecutionState(ActivityClientRecord r,
133             int postExecutionState) {
134         switch (postExecutionState) {
135             case UNDEFINED:
136                 return UNDEFINED;
137             case ON_RESUME:
138                 return getClosestOfStates(r, ON_RESUME_PRE_EXCUTION_STATES);
139             default:
140                 throw new UnsupportedOperationException("Pre-execution states for state: "
141                         + postExecutionState + " is not supported.");
142         }
143     }
144 
145     /**
146      * Pick a state that would require the least lifecycle transitions to get to.
147      * It will also make sure to try avoiding a path with activity destruction and relaunch if
148      * possible.
149      * @param r An activity that we're trying to resolve the transition for.
150      * @param finalStates An array of valid final states.
151      * @return One of the provided final states, or {@link ActivityLifecycleItem#UNDEFINED} if none
152      *         were provided or there is not path.
153      */
154     @VisibleForTesting
getClosestOfStates(ActivityClientRecord r, int[] finalStates)155     public int getClosestOfStates(ActivityClientRecord r, int[] finalStates) {
156         if (finalStates == null || finalStates.length == 0) {
157             return UNDEFINED;
158         }
159 
160         final int currentState = r.getLifecycleState();
161         int closestState = UNDEFINED;
162         for (int i = 0, shortestPath = Integer.MAX_VALUE, pathLength; i < finalStates.length; i++) {
163             getLifecyclePath(currentState, finalStates[i], false /* excludeLastState */);
164             pathLength = mLifecycleSequence.size();
165             if (pathInvolvesDestruction(mLifecycleSequence)) {
166                 pathLength += DESTRUCTION_PENALTY;
167             }
168             if (shortestPath > pathLength) {
169                 shortestPath = pathLength;
170                 closestState = finalStates[i];
171             }
172         }
173         return closestState;
174     }
175 
176     /** Get the lifecycle state request to match the current state in the end of a transaction. */
getLifecycleRequestForCurrentState(ActivityClientRecord r)177     public static ActivityLifecycleItem getLifecycleRequestForCurrentState(ActivityClientRecord r) {
178         final int prevState = r.getLifecycleState();
179         final ActivityLifecycleItem lifecycleItem;
180         switch (prevState) {
181             // TODO(lifecycler): Extend to support all possible states.
182             case ON_PAUSE:
183                 lifecycleItem = PauseActivityItem.obtain();
184                 break;
185             case ON_STOP:
186                 lifecycleItem = StopActivityItem.obtain(r.isVisibleFromServer(),
187                         0 /* configChanges */);
188                 break;
189             default:
190                 lifecycleItem = ResumeActivityItem.obtain(false /* isForward */);
191                 break;
192         }
193 
194         return lifecycleItem;
195     }
196 
197     /**
198      * Check if there is a destruction involved in the path. We want to avoid a lifecycle sequence
199      * that involves destruction and recreation if there is another path.
200      */
pathInvolvesDestruction(IntArray lifecycleSequence)201     private static boolean pathInvolvesDestruction(IntArray lifecycleSequence) {
202         final int size = lifecycleSequence.size();
203         for (int i = 0; i < size; i++) {
204             if (lifecycleSequence.get(i) == ON_DESTROY) {
205                 return true;
206             }
207         }
208         return false;
209     }
210 
211     /**
212      * Return the index of the last callback that requests the state in which activity will be after
213      * execution. If there is a group of callbacks in the end that requests the same specific state
214      * or doesn't request any - we will find the first one from such group.
215      *
216      * E.g. ActivityResult requests RESUMED post-execution state, Configuration does not request any
217      * specific state. If there is a sequence
218      *   Configuration - ActivityResult - Configuration - ActivityResult
219      * index 1 will be returned, because ActivityResult request on position 1 will be the last
220      * request that moves activity to the RESUMED state where it will eventually end.
221      */
lastCallbackRequestingState(ClientTransaction transaction)222     static int lastCallbackRequestingState(ClientTransaction transaction) {
223         final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
224         if (callbacks == null || callbacks.size() == 0) {
225             return -1;
226         }
227 
228         // Go from the back of the list to front, look for the request closes to the beginning that
229         // requests the state in which activity will end after all callbacks are executed.
230         int lastRequestedState = UNDEFINED;
231         int lastRequestingCallback = -1;
232         for (int i = callbacks.size() - 1; i >= 0; i--) {
233             final ClientTransactionItem callback = callbacks.get(i);
234             final int postExecutionState = callback.getPostExecutionState();
235             if (postExecutionState != UNDEFINED) {
236                 // Found a callback that requests some post-execution state.
237                 if (lastRequestedState == UNDEFINED || lastRequestedState == postExecutionState) {
238                     // It's either a first-from-end callback that requests state or it requests
239                     // the same state as the last one. In both cases, we will use it as the new
240                     // candidate.
241                     lastRequestedState = postExecutionState;
242                     lastRequestingCallback = i;
243                 } else {
244                     break;
245                 }
246             }
247         }
248 
249         return lastRequestingCallback;
250     }
251 
252     /** Dump transaction to string. */
transactionToString(ClientTransaction transaction, ClientTransactionHandler transactionHandler)253     static String transactionToString(ClientTransaction transaction,
254             ClientTransactionHandler transactionHandler) {
255         final StringWriter stringWriter = new StringWriter();
256         final PrintWriter pw = new PrintWriter(stringWriter);
257         final String prefix = tId(transaction);
258         transaction.dump(prefix, pw);
259         pw.append(prefix + "Target activity: ")
260                 .println(getActivityName(transaction.getActivityToken(), transactionHandler));
261         return stringWriter.toString();
262     }
263 
264     /** @return A string in format "tId:<transaction hashcode> ". */
tId(ClientTransaction transaction)265     static String tId(ClientTransaction transaction) {
266         return "tId:" + transaction.hashCode() + " ";
267     }
268 
269     /** Get activity string name for provided token. */
getActivityName(IBinder token, ClientTransactionHandler transactionHandler)270     static String getActivityName(IBinder token, ClientTransactionHandler transactionHandler) {
271         final Activity activity = getActivityForToken(token, transactionHandler);
272         if (activity != null) {
273             return activity.getComponentName().getClassName();
274         }
275         return "Not found for token: " + token;
276     }
277 
278     /** Get short activity class name for provided token. */
getShortActivityName(IBinder token, ClientTransactionHandler transactionHandler)279     static String getShortActivityName(IBinder token, ClientTransactionHandler transactionHandler) {
280         final Activity activity = getActivityForToken(token, transactionHandler);
281         if (activity != null) {
282             return activity.getComponentName().getShortClassName();
283         }
284         return "Not found for token: " + token;
285     }
286 
getActivityForToken(IBinder token, ClientTransactionHandler transactionHandler)287     private static Activity getActivityForToken(IBinder token,
288             ClientTransactionHandler transactionHandler) {
289         if (token == null) {
290             return null;
291         }
292         return transactionHandler.getActivity(token);
293     }
294 
295     /** Get lifecycle state string name. */
getStateName(int state)296     static String getStateName(int state) {
297         switch (state) {
298             case UNDEFINED:
299                 return "UNDEFINED";
300             case PRE_ON_CREATE:
301                 return "PRE_ON_CREATE";
302             case ON_CREATE:
303                 return "ON_CREATE";
304             case ON_START:
305                 return "ON_START";
306             case ON_RESUME:
307                 return "ON_RESUME";
308             case ON_PAUSE:
309                 return "ON_PAUSE";
310             case ON_STOP:
311                 return "ON_STOP";
312             case ON_DESTROY:
313                 return "ON_DESTROY";
314             case ON_RESTART:
315                 return "ON_RESTART";
316             default:
317                 throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
318         }
319     }
320 }
321