blob: 42999145e227e41a99a223fc512ed8eee3eafe3c [file] [log] [blame]
Ben Lin9fea3122016-10-10 18:32:26 -07001/*
2 * Copyright (C) 2016 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
17package com.android.documentsui;
18
Steve McKay30535bc2016-11-04 14:16:58 -070019import static com.android.documentsui.base.Shared.VERBOSE;
Garfield Tanf7df7152016-10-27 16:55:14 -070020
Ben Lin9fea3122016-10-10 18:32:26 -070021import android.annotation.MainThread;
22import android.annotation.Nullable;
Garfield Tanf7df7152016-10-27 16:55:14 -070023import android.util.Log;
Ben Lin9fea3122016-10-10 18:32:26 -070024
25import com.android.documentsui.base.Shared;
26import com.android.documentsui.selection.BandController;
27
28/**
29 * A lock used by {@link DirectoryLoader} and {@link BandController} to ensure refresh is blocked
30 * while Band Selection is active.
31 */
32public final class DirectoryReloadLock {
Garfield Tanf7df7152016-10-27 16:55:14 -070033 private static final String TAG = "DirectoryReloadLock";
34
Ben Lin9fea3122016-10-10 18:32:26 -070035 private int mPauseCount = 0;
36 private @Nullable Runnable mCallback;
37
38 /**
39 * Increment the block count by 1
40 */
41 @MainThread
42 public void block() {
43 Shared.checkMainLoop();
44 mPauseCount++;
Steve McKay30535bc2016-11-04 14:16:58 -070045 if (VERBOSE) Log.v(TAG, "Block count increments to " + mPauseCount + ".");
Ben Lin9fea3122016-10-10 18:32:26 -070046 }
47
48 /**
49 * Decrement the block count by 1; If no other object is trying to block and there exists some
50 * callback, that callback will be run
51 */
52 @MainThread
53 public void unblock() {
54 Shared.checkMainLoop();
Garfield Tan5a1c7b02016-10-27 13:30:14 -070055 assert(mPauseCount > 0);
Ben Lin9fea3122016-10-10 18:32:26 -070056 mPauseCount--;
Steve McKay30535bc2016-11-04 14:16:58 -070057 if (VERBOSE) Log.v(TAG, "Block count decrements to " + mPauseCount + ".");
Ben Lin9fea3122016-10-10 18:32:26 -070058 if (mPauseCount == 0 && mCallback != null) {
59 mCallback.run();
60 mCallback = null;
61 }
62 }
63
64 /**
65 * Attempts to run the given Runnable if not-blocked, or else the Runnable is set to be ran next
66 * (replacing any previous set Runnables).
67 */
68 public void tryUpdate(Runnable update) {
69 if (mPauseCount == 0) {
70 update.run();
71 } else {
72 mCallback = update;
73 }
74 }
Steve McKay30535bc2016-11-04 14:16:58 -070075}