summaryrefslogtreecommitdiff
path: root/src/com/android/settings/SidecarFragment.java
blob: 1a69c03f48dbdbbf2be87a009aa1d6eec35adba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.CallSuper;
import androidx.annotation.IntDef;

import com.android.settingslib.utils.ThreadUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * A headless fragment encapsulating a long-running action such as a network RPC surviving rotation.
 *
 * <p>Subclasses should implement their own state machine, updating the state on each state change
 * via {@link #setState(int, int)}. They can define their own states, however, it is suggested that
 * the pre-defined {@link @State} constants are used and customizations are implemented via
 * substates. Custom states must be outside the range of pre-defined states.
 *
 * <p>It is safe to update the state at any time, but state updates must originate from the main
 * thread.
 *
 * <p>A listener can be attached that receives state updates while it's registered. Note that state
 * change events can occur at any point in time and hence a registered listener should unregister if
 * it cannot act upon the state change (typically a non-resumed fragment).
 *
 * <p>Listeners can receive state changes for the same state/substate combination, so listeners
 * should make sure to be idempotent during state change events.
 *
 * <p>If a SidecarFragment is only relevant during the lifetime of another fragment (for example, a
 * sidecar performing a details request for a DetailsFragment), that fragment needs to become the
 * managing fragment of the sidecar.
 *
 * <h2>Managing fragment responsibilities</h2>
 *
 * <ol>
 *   <li>Instantiates the sidecar fragment when necessary, preferably in {@link #onStart}.
 *   <li>Removes the sidecar fragment when it's no longer used or when itself is removed. Removal of
 *       the managing fragment can be detected by checking {@link #isRemoving} in {@link #onStop}.
 *       <br>
 *   <li>Registers as a listener in {@link #onResume()}, unregisters in {@link #onPause()}.
 *   <li>Starts the long-running operation by calling into the sidecar.
 *   <li>Receives state updates via {@link Listener#onStateChange(SidecarFragment)} and updates the
 *       UI accordingly.
 * </ol>
 *
 * <h2>Managing fragment example</h2>
 *
 * <pre>
 *     public class MainFragment implements SidecarFragment.Listener {
 *         private static final String TAG_SOME_SIDECAR = ...;
 *         private static final String KEY_SOME_SIDECAR_STATE = ...;
 *
 *         private SomeSidecarFragment mSidecar;
 *
 *         &#064;Override
 *         public void onStart() {
 *             super.onStart();
 *             Bundle args = ...; // optional args
 *             mSidecar = SidecarFragment.get(getFragmentManager(), TAG_SOME_SIDECAR,
 *                     SidecarFragment.class, args);
 *         }
 *
 *         &#064;Override
 *         public void onResume() {
 *             mSomeSidecar.addListener(this);
 *         }
 *
 *         &#064;Override
 *         public void onPause() {
 *             mSomeSidecar.removeListener(this):
 *         }
 *     }
 * </pre>
 */
public class SidecarFragment extends Fragment {

    private static final String TAG = "SidecarFragment";

    /**
     * Get an instance of this sidecar.
     *
     * <p>Will return the existing instance if one is already present. Note that the args will not
     * be used in this situation, so args must be constant for any particular fragment manager and
     * tag.
     */
    @SuppressWarnings("unchecked")
    protected static <T extends SidecarFragment> T get(
            FragmentManager fm, String tag, Class<T> clazz, Bundle args) {
        T fragment = (T) fm.findFragmentByTag(tag);
        if (fragment == null) {
            try {
                fragment = clazz.newInstance();
            } catch (java.lang.InstantiationException e) {
                throw new InstantiationException("Unable to create fragment", e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Unable to create fragment", e);
            }
            if (args != null) {
                fragment.setArguments(args);
            }
            fm.beginTransaction().add(fragment, tag).commit();
            // No real harm in doing this here - get() should generally only be called from onCreate
            // which is on the main thread - and it allows us to start running the sidecar on this
            // instance immediately rather than having to wait until the transaction commits.
            fm.executePendingTransactions();
        }

        return fragment;
    }

    /** State definitions. @see {@link #getState} */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({State.INIT, State.RUNNING, State.SUCCESS, State.ERROR})
    public @interface State {
        /** Initial idling state. */
        int INIT = 0;

        /** The long-running operation is in progress. */
        int RUNNING = 1;

        /** The long-running operation has succeeded. */
        int SUCCESS = 2;

        /** The long-running operation has failed. */
        int ERROR = 3;
    }

    /** Substate definitions. @see {@link #getSubstate} */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({
        Substate.UNUSED,
        Substate.RUNNING_BIND_SERVICE,
        Substate.RUNNING_GET_ACTIVATION_CODE,
    })
    public @interface Substate {
        // Unknown/unused substate.
        int UNUSED = 0;
        int RUNNING_BIND_SERVICE = 1;
        int RUNNING_GET_ACTIVATION_CODE = 2;

        // Future tags: 3+
    }

    /** **************************************** */
    private Set<Listener> mListeners = new CopyOnWriteArraySet<>();

    // Used to track whether onCreate has been called yet.
    private boolean mCreated;

    @State private int mState;
    @Substate private int mSubstate;

    /** A listener receiving state change events. */
    public interface Listener {

        /**
         * Called upon any state or substate change.
         *
         * <p>The new state can be queried through {@link #getState} and {@link #getSubstate}.
         *
         * <p>Called from the main thread.
         *
         * @param fragment the SidecarFragment that changed its state
         */
        void onStateChange(SidecarFragment fragment);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        mCreated = true;
        setState(State.INIT, Substate.UNUSED);
    }

    @Override
    public void onDestroy() {
        mCreated = false;
        super.onDestroy();
    }

    /**
     * Registers a listener that will receive subsequent state changes.
     *
     * <p>A {@link Listener#onStateChange(SidecarFragment)} event is fired as part of this call
     * unless {@link #onCreate} has not yet been called (which means that it's unsafe to access this
     * fragment as it has not been setup or restored completely). In that case, the future call to
     * onCreate will trigger onStateChange on registered listener.
     *
     * <p>Must be called from the main thread.
     *
     * @param listener a listener, or null for unregistering the current listener
     */
    public void addListener(Listener listener) {
        ThreadUtils.ensureMainThread();
        mListeners.add(listener);
        if (mCreated) {
            notifyListener(listener);
        }
    }

    /**
     * Removes a previously registered listener.
     *
     * @return {@code true} if the listener was removed, {@code false} if there was no such listener
     *     registered.
     */
    public boolean removeListener(Listener listener) {
        ThreadUtils.ensureMainThread();
        return mListeners.remove(listener);
    }

    /** Returns the current state. */
    @State
    public int getState() {
        return mState;
    }

    /** Returns the current substate. */
    @Substate
    public int getSubstate() {
        return mSubstate;
    }

    /**
     * Resets the sidecar to its initial state.
     *
     * <p>Implementers can override this method to perform additional reset tasks, but must call the
     * super method.
     */
    @CallSuper
    public void reset() {
        setState(State.INIT, Substate.UNUSED);
    }

    /**
     * Updates the state and substate and notifies the registered listener.
     *
     * <p>Must be called from the main thread.
     *
     * @param state the state to transition to
     * @param substate the substate to transition to
     */
    protected void setState(@State int state, @Substate int substate) {
        ThreadUtils.ensureMainThread();

        mState = state;
        mSubstate = substate;
        notifyAllListeners();
        printState();
    }

    private void notifyAllListeners() {
        for (Listener listener : mListeners) {
            notifyListener(listener);
        }
    }

    private void notifyListener(Listener listener) {
        listener.onStateChange(this);
    }

    /** Prints the state of the sidecar. */
    public void printState() {
        StringBuilder sb =
                new StringBuilder("SidecarFragment.setState(): Sidecar Class: ")
                        .append(getClass().getCanonicalName());
        sb.append(", State: ");
        switch (mState) {
            case SidecarFragment.State.INIT:
                sb.append("State.INIT");
                break;
            case SidecarFragment.State.RUNNING:
                sb.append("State.RUNNING");
                break;
            case SidecarFragment.State.SUCCESS:
                sb.append("State.SUCCESS");
                break;
            case SidecarFragment.State.ERROR:
                sb.append("State.ERROR");
                break;
            default:
                sb.append(mState);
                break;
        }
        switch (mSubstate) {
            case SidecarFragment.Substate.UNUSED:
                sb.append(", Substate.UNUSED");
                break;
            default:
                sb.append(", ").append(mSubstate);
                break;
        }

        Log.v(TAG, sb.toString());
    }

    @Override
    public String toString() {
        return String.format(
                Locale.US,
                "SidecarFragment[mState=%d, mSubstate=%d]: %s",
                mState,
                mSubstate,
                super.toString());
    }

    /** The State of the sidecar status. */
    public static final class States {
        public static final States SUCCESS = States.create(State.SUCCESS, Substate.UNUSED);
        public static final States ERROR = States.create(State.ERROR, Substate.UNUSED);

        @State public final int state;
        @Substate public final int substate;

        /** Creates a new sidecar state. */
        public static States create(@State int state, @Substate int substate) {
            return new States(state, substate);
        }

        public States(@State int state, @Substate int substate) {
            this.state = state;
            this.substate = substate;
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof States)) {
                return false;
            }
            States other = (States) o;
            return this.state == other.state && this.substate == other.substate;
        }

        @Override
        public int hashCode() {
            return state * 31 + substate;
        }
    }
}