Commit 6b89aa8d authored by Marcin Wiacek's avatar Marcin Wiacek Committed by Commit Bot

@IntDef cleanup in the chrome/java

@IntDef/@StringDef annotation are preferred way for declaring
set of String/int values:

1. they need less space in APK than enum, see
https://developer.android.com/topic/performance/reduce-apk-size#remove-enums
2. they give more control over allowed values than "static final" values

Main goal of patch is writing "static final" values, enum
and some classes in one common @IntDef/@StringDef form:

1. with @IntDef/@StringDef first, @Retention second
   and related @interface third
2. with values inside @interface
3. with NUM_ENTRIES declaring number of entries if necessary
4. with comment about numbering from 0 without gaps when necessary
5. with @Retention(RetentionPolicy.SOURCE)
6. without "static final" in the @interface

Additionally there are done some other trivial cleanups.

Change-Id: Id50845175a85cb5fc5919c8b79c1cd492f0d994d
Reviewed-on: https://chromium-review.googlesource.com/1136879
Commit-Queue: Tommy Nyquist <nyquist@chromium.org>
Reviewed-by: default avatarTommy Nyquist <nyquist@chromium.org>
Cr-Commit-Position: refs/heads/master@{#576172}
parent 1e8ff9d4
......@@ -79,9 +79,7 @@ public abstract class AppHooks {
@CalledByNative
public static AppHooks get() {
if (sInstance == null) {
sInstance = new AppHooksImpl();
}
if (sInstance == null) sInstance = new AppHooksImpl();
return sInstance;
}
......@@ -354,9 +352,7 @@ public abstract class AppHooks {
ContextUtils.getApplicationContext().getPackageManager().getPackageInfo(
GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, /* flags= */ 0);
int apkVersion = gmsPackageInfo.versionCode;
if (apkVersion >= minApkVersion) {
return ConnectionResult.SUCCESS;
}
if (apkVersion >= minApkVersion) return ConnectionResult.SUCCESS;
} catch (PackageManager.NameNotFoundException e) {
return ConnectionResult.SERVICE_MISSING;
}
......
......@@ -5,6 +5,7 @@
package org.chromium.chrome.browser;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.util.LruCache;
import org.chromium.base.Callback;
......@@ -20,6 +21,9 @@ import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.content_public.browser.WebContents;
import org.chromium.services.service_manager.InterfaceProvider;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* This is the top-level CopylessPaste metadata extraction for AppIndexing.
*/
......@@ -35,10 +39,14 @@ public class AppIndexingUtil {
// Constants used to log UMA "enum" histograms about the cache state.
// The values should not be changed or reused, and CACHE_HISTOGRAM_BOUNDARY should be the last.
private static final int CACHE_HIT_WITH_ENTITY = 0;
private static final int CACHE_HIT_WITHOUT_ENTITY = 1;
private static final int CACHE_MISS = 2;
private static final int CACHE_HISTOGRAM_BOUNDARY = 3;
@IntDef({CacheHit.WITH_ENTITY, CacheHit.WITHOUT_ENTITY, CacheHit.MISS})
@Retention(RetentionPolicy.SOURCE)
private @interface CacheHit {
int WITH_ENTITY = 0;
int WITHOUT_ENTITY = 1;
int MISS = 2;
int NUM_ENTRIES = 3;
}
/**
* Extracts entities from document metadata and reports it to on-device App Indexing.
......@@ -61,17 +69,17 @@ public class AppIndexingUtil {
if (lastPageVisitContainedEntity(url)) {
// Condition 1
RecordHistogram.recordEnumeratedHistogram(
"CopylessPaste.CacheHit", CACHE_HIT_WITH_ENTITY, CACHE_HISTOGRAM_BOUNDARY);
"CopylessPaste.CacheHit", CacheHit.WITH_ENTITY, CacheHit.NUM_ENTRIES);
getAppIndexingReporter().reportWebPageView(url, tab.getTitle());
return;
}
// Condition 2
RecordHistogram.recordEnumeratedHistogram(
"CopylessPaste.CacheHit", CACHE_HIT_WITHOUT_ENTITY, CACHE_HISTOGRAM_BOUNDARY);
"CopylessPaste.CacheHit", CacheHit.WITHOUT_ENTITY, CacheHit.NUM_ENTRIES);
} else {
// Condition 3
RecordHistogram.recordEnumeratedHistogram(
"CopylessPaste.CacheHit", CACHE_MISS, CACHE_HISTOGRAM_BOUNDARY);
"CopylessPaste.CacheHit", CacheHit.MISS, CacheHit.NUM_ENTRIES);
CopylessPaste copylessPaste = getCopylessPasteInterface(tab);
if (copylessPaste == null) {
return;
......@@ -94,9 +102,7 @@ public class AppIndexingUtil {
}
private boolean wasPageVisitedRecently(String url) {
if (url == null) {
return false;
}
if (url == null) return false;
CacheEntry entry = getPageCache().get(url);
if (entry == null || (getElapsedTime() - entry.lastSeenTimeMs > CACHE_VISIT_CUTOFF_MS)) {
return false;
......@@ -109,9 +115,7 @@ public class AppIndexingUtil {
* parsed.
*/
private boolean lastPageVisitContainedEntity(String url) {
if (url == null) {
return false;
}
if (url == null) return false;
CacheEntry entry = getPageCache().get(url);
if (entry == null || !entry.containedEntity) {
return false;
......
......@@ -53,9 +53,7 @@ public abstract class BasicNativePage extends EmptyTabObserver implements Native
mTopMargin = res.getDimensionPixelSize(R.dimen.tab_strip_height)
+ res.getDimensionPixelSize(R.dimen.toolbar_height_no_shadow);
if (host.getActiveTab() != null) {
host.getActiveTab().addObserver(this);
}
if (host.getActiveTab() != null) host.getActiveTab().addObserver(this);
updateMargins(host.getActiveTab() != null
? host.getActiveTab().getBrowserControlsStateConstraints()
......
......@@ -103,9 +103,7 @@ public class BitmapCache {
public void putBitmap(@NonNull String key, @Nullable Bitmap bitmap) {
ThreadUtils.assertOnUiThread();
if (bitmap == null) return;
if (!SysUtils.isLowEndDevice()) {
getBitmapCache().put(key, bitmap);
}
if (!SysUtils.isLowEndDevice()) getBitmapCache().put(key, bitmap);
maybeScheduleDeduplicationCache();
sDeduplicationCache.put(key, new WeakReference<>(bitmap));
}
......
......@@ -51,14 +51,23 @@ public class BluetoothChooserDialog
// These constants match BluetoothChooserAndroid::ShowDiscoveryState, and are used in
// notifyDiscoveryState().
static final int DISCOVERY_FAILED_TO_START = 0;
static final int DISCOVERING = 1;
static final int DISCOVERY_IDLE = 2;
@IntDef({DiscoveryMode.DISCOVERY_FAILED_TO_START, DiscoveryMode.DISCOVERING,
DiscoveryMode.DISCOVERY_IDLE})
@Retention(RetentionPolicy.SOURCE)
@interface DiscoveryMode {
int DISCOVERY_FAILED_TO_START = 0;
int DISCOVERING = 1;
int DISCOVERY_IDLE = 2;
}
// Values passed to nativeOnDialogFinished:eventType, and only used in the native function.
static final int DIALOG_FINISHED_DENIED_PERMISSION = 0;
static final int DIALOG_FINISHED_CANCELLED = 1;
static final int DIALOG_FINISHED_SELECTED = 2;
@IntDef({DialogFinished.DENIED_PERMISSION, DialogFinished.CANCELLED, DialogFinished.SELECTED})
@Retention(RetentionPolicy.SOURCE)
@interface DialogFinished {
int DENIED_PERMISSION = 0;
int CANCELLED = 1;
int SELECTED = 2;
}
// The window that owns this dialog.
final WindowAndroid mWindowAndroid;
......@@ -226,18 +235,16 @@ public class BluetoothChooserDialog
@Override
public void onItemSelected(String id) {
if (id.isEmpty()) {
finishDialog(DIALOG_FINISHED_CANCELLED, "");
finishDialog(DialogFinished.CANCELLED, "");
} else {
finishDialog(DIALOG_FINISHED_SELECTED, id);
finishDialog(DialogFinished.SELECTED, id);
}
}
@Override
public void onRequestPermissionsResult(String[] permissions, int[] grantResults) {
// The chooser might have been closed during the request.
if (mNativeBluetoothChooserDialogPtr == 0) {
return;
}
if (mNativeBluetoothChooserDialogPtr == 0) return;
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
......@@ -262,7 +269,7 @@ public class BluetoothChooserDialog
Manifest.permission.ACCESS_COARSE_LOCATION)) {
// Immediately close the dialog because the user has asked Chrome not to request the
// location permission.
finishDialog(DIALOG_FINISHED_DENIED_PERMISSION, "");
finishDialog(DialogFinished.DENIED_PERMISSION, "");
return false;
}
......@@ -308,9 +315,7 @@ public class BluetoothChooserDialog
}
private void onBluetoothLinkClick(View view, @LinkType int linkType) {
if (mNativeBluetoothChooserDialogPtr == 0) {
return;
}
if (mNativeBluetoothChooserDialogPtr == 0) return;
switch (linkType) {
case LinkType.EXPLAIN_BLUETOOTH:
......@@ -415,16 +420,16 @@ public class BluetoothChooserDialog
@VisibleForTesting
@CalledByNative
void notifyDiscoveryState(int discoveryState) {
void notifyDiscoveryState(@DiscoveryMode int discoveryState) {
switch (discoveryState) {
case DISCOVERY_FAILED_TO_START: {
case DiscoveryMode.DISCOVERY_FAILED_TO_START: {
// FAILED_TO_START might be caused by a missing Location
// permission or by the Location service being turned off.
// Check, and show a request if so.
checkLocationServicesAndPermission();
break;
}
case DISCOVERY_IDLE: {
case DiscoveryMode.DISCOVERY_IDLE: {
mItemChooserDialog.setIdleState();
break;
}
......
......@@ -52,9 +52,7 @@ public class ChromeApplication extends Application {
@Override
protected void attachBaseContext(Context context) {
boolean browserProcess = ContextUtils.isMainProcess();
if (browserProcess) {
UmaUtils.recordMainEntryPointTime();
}
if (browserProcess) UmaUtils.recordMainEntryPointTime();
super.attachBaseContext(context);
ContextUtils.initApplicationContext(this);
......
......@@ -77,9 +77,7 @@ public class ChromeBackgroundService extends GcmTaskService {
}
private void handleSnippetsOnPersistentSchedulerWakeUp(Context context, String tag) {
if (!SnippetsLauncher.hasInstance()) {
launchBrowser(context, tag);
}
if (!SnippetsLauncher.hasInstance()) launchBrowser(context, tag);
snippetsOnPersistentSchedulerWakeUp();
}
......
......@@ -59,22 +59,24 @@ public class ChromeBackupAgent extends BackupAgent {
// Restore status is used to pass the result of any restore to Chrome's first run, so that
// it can be recorded as a histogram.
@IntDef({RestoreStatus.NO_RESTORE, RestoreStatus.RESTORE_COMPLETED,
RestoreStatus.RESTORE_AFTER_FIRST_RUN, RestoreStatus.BROWSER_STARTUP_FAILED,
RestoreStatus.NOT_SIGNED_IN, RestoreStatus.RESTORE_STATUS_RECORDED})
@Retention(RetentionPolicy.SOURCE)
@IntDef({NO_RESTORE, RESTORE_COMPLETED, RESTORE_AFTER_FIRST_RUN, BROWSER_STARTUP_FAILED,
NOT_SIGNED_IN, RESTORE_STATUS_RECORDED})
public @interface RestoreStatus {}
// Values must match those in histogram.xml AndroidRestoreResult.
static final int NO_RESTORE = 0;
static final int RESTORE_COMPLETED = 1;
static final int RESTORE_AFTER_FIRST_RUN = 2;
static final int BROWSER_STARTUP_FAILED = 3;
static final int NOT_SIGNED_IN = 4;
static final int RESTORE_HISTOGRAM_BOUNDARY = 5;
// Set RESTORE_STATUS_RECORDED when the histogram has been recorded; so that it is only recorded
// once.
public static final int RESTORE_STATUS_RECORDED = 5;
public @interface RestoreStatus {
// Values must match those in histogram.xml AndroidRestoreResult.
int NO_RESTORE = 0;
int RESTORE_COMPLETED = 1;
int RESTORE_AFTER_FIRST_RUN = 2;
int BROWSER_STARTUP_FAILED = 3;
int NOT_SIGNED_IN = 4;
int NUM_ENTRIES = 5;
// Set RESTORE_STATUS_RECORDED when the histogram has been recorded; so that it is only
// recorded once.
int RESTORE_STATUS_RECORDED = 5;
}
private static final String RESTORE_STATUS = "android_restore_status";
......@@ -285,7 +287,7 @@ public class ChromeBackupAgent extends BackupAgent {
SharedPreferences sharedPrefs = ContextUtils.getAppSharedPreferences();
if (FirstRunStatus.getFirstRunFlowComplete()
|| FirstRunStatus.getLightweightFirstRunFlowComplete()) {
setRestoreStatus(RESTORE_AFTER_FIRST_RUN);
setRestoreStatus(RestoreStatus.RESTORE_AFTER_FIRST_RUN);
Log.w(TAG, "Restore attempted after first run");
return;
}
......@@ -342,13 +344,13 @@ public class ChromeBackupAgent extends BackupAgent {
});
if (!browserStarted) {
// Something went wrong starting Chrome, skip the restore.
setRestoreStatus(BROWSER_STARTUP_FAILED);
setRestoreStatus(RestoreStatus.BROWSER_STARTUP_FAILED);
return;
}
// If the user hasn't signed in, or can't sign in, then don't restore anything.
if (restoredUserName == null || !accountExistsOnDevice(restoredUserName)) {
setRestoreStatus(NOT_SIGNED_IN);
setRestoreStatus(RestoreStatus.NOT_SIGNED_IN);
Log.i(TAG, "Chrome was not signed in with a known account name, not restoring");
return;
}
......@@ -395,7 +397,7 @@ public class ChromeBackupAgent extends BackupAgent {
// The silent first run will change things, so there is no point in trying to prevent
// additional backups at this stage. Don't write anything to |newState|.
setRestoreStatus(RESTORE_COMPLETED);
setRestoreStatus(RestoreStatus.RESTORE_COMPLETED);
Log.i(TAG, "Restore complete");
}
......@@ -425,7 +427,8 @@ public class ChromeBackupAgent extends BackupAgent {
@VisibleForTesting
@RestoreStatus
static int getRestoreStatus() {
return ContextUtils.getAppSharedPreferences().getInt(RESTORE_STATUS, NO_RESTORE);
return ContextUtils.getAppSharedPreferences().getInt(
RESTORE_STATUS, RestoreStatus.NO_RESTORE);
}
/**
......@@ -442,12 +445,13 @@ public class ChromeBackupAgent extends BackupAgent {
* Record the restore histogram. To be called from Chrome itself once it is running.
*/
public static void recordRestoreHistogram() {
@RestoreStatus
int restoreStatus = getRestoreStatus();
// Ensure restore status is only recorded once
if (restoreStatus != RESTORE_STATUS_RECORDED) {
if (restoreStatus != RestoreStatus.RESTORE_STATUS_RECORDED) {
RecordHistogram.recordEnumeratedHistogram(
HISTOGRAM_ANDROID_RESTORE_RESULT, restoreStatus, RESTORE_HISTOGRAM_BOUNDARY);
setRestoreStatus(RESTORE_STATUS_RECORDED);
HISTOGRAM_ANDROID_RESTORE_RESULT, restoreStatus, RestoreStatus.NUM_ENTRIES);
setRestoreStatus(RestoreStatus.RESTORE_STATUS_RECORDED);
}
}
......
......@@ -68,13 +68,9 @@ public class ChromeHttpAuthHandler {
@CalledByNative
private void showDialog(WindowAndroid windowAndroid) {
if (windowAndroid == null) {
cancel();
}
if (windowAndroid == null) cancel();
Activity activity = windowAndroid.getActivity().get();
if (activity == null) {
cancel();
}
if (activity == null) cancel();
LoginPrompt authDialog = new LoginPrompt(activity, this);
setAutofillObserver(authDialog);
authDialog.show();
......
......@@ -22,6 +22,8 @@ import org.chromium.chrome.R;
import org.chromium.chrome.browser.preferences.ChromePreferenceManager;
import org.chromium.content_public.browser.BrowserStartupController;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
......@@ -41,22 +43,18 @@ public final class DefaultBrowserInfo {
* Additions should be treated as APPEND ONLY to keep the UMA metric semantics the same over
* time.
*/
@IntDef({
MobileDefaultBrowserState.NO_DEFAULT,
MobileDefaultBrowserState.CHROME_SYSTEM_DEFAULT,
@IntDef({MobileDefaultBrowserState.NO_DEFAULT, MobileDefaultBrowserState.CHROME_SYSTEM_DEFAULT,
MobileDefaultBrowserState.CHROME_INSTALLED_DEFAULT,
MobileDefaultBrowserState.OTHER_SYSTEM_DEFAULT,
MobileDefaultBrowserState.OTHER_INSTALLED_DEFAULT,
MobileDefaultBrowserState.BOUNDARY,
})
MobileDefaultBrowserState.OTHER_INSTALLED_DEFAULT})
@Retention(RetentionPolicy.SOURCE)
private @interface MobileDefaultBrowserState {
int NO_DEFAULT = 0;
int CHROME_SYSTEM_DEFAULT = 1;
int CHROME_INSTALLED_DEFAULT = 2;
int OTHER_SYSTEM_DEFAULT = 3;
int OTHER_INSTALLED_DEFAULT = 4;
int BOUNDARY = 5;
int NUM_ENTRIES = 5;
}
/**
......@@ -221,7 +219,7 @@ public final class DefaultBrowserInfo {
RecordHistogram.recordCount100Histogram(
getDefaultBrowserCountUmaName(info), info.browserCount);
RecordHistogram.recordEnumeratedHistogram("Mobile.DefaultBrowser.State",
getDefaultBrowserUmaState(info), MobileDefaultBrowserState.BOUNDARY);
getDefaultBrowserUmaState(info), MobileDefaultBrowserState.NUM_ENTRIES);
}
}
.executeOnExecutor(
......
......@@ -127,9 +127,7 @@ public class LaunchIntentDispatcher implements IntentHandler.IntentHandlerDelega
*/
public static @Action int dispatchToCustomTabActivity(Activity currentActivity, Intent intent) {
LaunchIntentDispatcher dispatcher = new LaunchIntentDispatcher(currentActivity, intent);
if (!dispatcher.mIsCustomTabIntent) {
return Action.CONTINUE;
}
if (!dispatcher.mIsCustomTabIntent) return Action.CONTINUE;
dispatcher.launchCustomTabActivity();
return Action.FINISH_ACTIVITY;
}
......
......@@ -10,6 +10,7 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.IntDef;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ApplicationStatus;
......@@ -19,6 +20,8 @@ import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.invalidation.DelayedInvalidationsController;
import org.chromium.chrome.browser.omaha.OmahaBase;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.concurrent.atomic.AtomicBoolean;
/**
......@@ -50,10 +53,14 @@ public class PowerBroadcastReceiver extends BroadcastReceiver {
*/
@VisibleForTesting
public static class ServiceRunnable implements Runnable {
static final int STATE_UNINITIALIZED = 0;
static final int STATE_POSTED = 1;
static final int STATE_CANCELED = 2;
static final int STATE_COMPLETED = 3;
@IntDef({State.UNINITIALIZED, State.POSTED, State.CANCELED, State.COMPLETED})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
int UNINITIALIZED = 0;
int POSTED = 1;
int CANCELED = 2;
int COMPLETED = 3;
}
/**
* ANRs are triggered if the app fails to respond to a touch event within 5 seconds. Posting
......@@ -63,33 +70,33 @@ public class PowerBroadcastReceiver extends BroadcastReceiver {
private static final long MS_DELAY_TO_RUN = 5000;
private final Handler mHandler = new Handler(Looper.getMainLooper());
private int mState = STATE_UNINITIALIZED;
private @State int mState = State.UNINITIALIZED;
public int getState() {
return mState;
}
public void post() {
if (mState == STATE_POSTED) return;
setState(STATE_POSTED);
if (mState == State.POSTED) return;
setState(State.POSTED);
mHandler.postDelayed(this, getDelayToRun());
}
public void cancel() {
if (mState != STATE_POSTED) return;
setState(STATE_CANCELED);
if (mState != State.POSTED) return;
setState(State.CANCELED);
mHandler.removeCallbacks(this);
}
/** Unless testing, do not override this function. */
@Override
public void run() {
if (mState != STATE_POSTED) return;
setState(STATE_COMPLETED);
if (mState != State.POSTED) return;
setState(State.COMPLETED);
runActions();
}
public void setState(int state) {
public void setState(@State int state) {
mState = state;
}
......
......@@ -216,9 +216,7 @@ public class TabState {
stream = new DataInputStream(new CipherInputStream(input, cipher));
}
}
if (stream == null) {
stream = new DataInputStream(input);
}
if (stream == null) stream = new DataInputStream(input);
try {
if (encrypted && stream.readLong() != KEY_CHECKER) {
// Got the wrong key, skip the file
......@@ -302,9 +300,7 @@ public class TabState {
* @param encrypted Whether or not the TabState should be encrypted.
*/
public static void saveState(File file, TabState state, boolean encrypted) {
if (state == null || state.contentsState == null) {
return;
}
if (state == null || state.contentsState == null) return;
// Create the byte array from contentsState before opening the FileOutputStream, in case
// contentsState.buffer is an instance of MappedByteBuffer that is mapped to
......@@ -342,9 +338,7 @@ public class TabState {
} else {
dataOutputStream = new DataOutputStream(new BufferedOutputStream(fileOutputStream));
}
if (encrypted) {
dataOutputStream.writeLong(KEY_CHECKER);
}
if (encrypted) dataOutputStream.writeLong(KEY_CHECKER);
dataOutputStream.writeLong(state.timestampMillis);
dataOutputStream.writeInt(contentsStateBytes.length);
dataOutputStream.write(contentsStateBytes);
......
......@@ -69,9 +69,7 @@ public class UsbChooserDialog implements ItemChooserDialog.ItemSelectedCallback
SpannableString statusActive = SpanApplier.applySpans(
activity.getString(R.string.usb_chooser_dialog_footnote_text),
new SpanInfo("<link>", "</link>", new NoUnderlineClickableSpan((view) -> {
if (mNativeUsbChooserDialogPtr == 0) {
return;
}
if (mNativeUsbChooserDialogPtr == 0) return;
nativeLoadUsbHelpPage(mNativeUsbChooserDialogPtr);
......@@ -103,9 +101,7 @@ public class UsbChooserDialog implements ItemChooserDialog.ItemSelectedCallback
private static UsbChooserDialog create(WindowAndroid windowAndroid, String origin,
int securityLevel, long nativeUsbChooserDialogPtr) {
Activity activity = windowAndroid.getActivity().get();
if (activity == null) {
return null;
}
if (activity == null) return null;
UsbChooserDialog dialog = new UsbChooserDialog(nativeUsbChooserDialogPtr);
dialog.show(activity, origin, securityLevel);
......
......@@ -8,6 +8,7 @@ import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.view.ContextThemeWrapper;
import android.view.InflateException;
import android.view.LayoutInflater;
......@@ -32,6 +33,8 @@ import org.chromium.chrome.browser.widget.ControlContainer;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
......@@ -55,15 +58,20 @@ public final class WarmupManager {
static final String WEBCONTENTS_STATUS_HISTOGRAM = "CustomTabs.SpareWebContents.Status";
// See CustomTabs.SpareWebContentsStatus histogram. Append-only.
@VisibleForTesting
static final int WEBCONTENTS_STATUS_CREATED = 0;
@VisibleForTesting
static final int WEBCONTENTS_STATUS_USED = 1;
@VisibleForTesting
static final int WEBCONTENTS_STATUS_KILLED = 2;
@VisibleForTesting
static final int WEBCONTENTS_STATUS_DESTROYED = 3;
private static final int WEBCONTENTS_STATUS_COUNT = 4;
@IntDef({WebContentsStatus.CREATED, WebContentsStatus.USED, WebContentsStatus.KILLED,
WebContentsStatus.DESTROYED})
@Retention(RetentionPolicy.SOURCE)
@interface WebContentsStatus {
@VisibleForTesting
int CREATED = 0;
@VisibleForTesting
int USED = 1;
@VisibleForTesting
int KILLED = 2;
@VisibleForTesting
int DESTROYED = 3;
int NUM_ENTRIES = 4;
}
/**
* Observes spare WebContents deaths. In case of death, records stats, and cleanup the objects.
......@@ -74,7 +82,7 @@ public final class WarmupManager {
long elapsed = SystemClock.elapsedRealtime() - mWebContentsCreationTimeMs;
RecordHistogram.recordLongTimesHistogram(
"CustomTabs.SpareWebContents.TimeBeforeDeath", elapsed, TimeUnit.MILLISECONDS);
recordWebContentsStatus(WEBCONTENTS_STATUS_KILLED);
recordWebContentsStatus(WebContentsStatus.KILLED);
destroySpareWebContentsInternal();
}
};
......@@ -328,14 +336,16 @@ public final class WarmupManager {
*/
public void createSpareWebContents() {
ThreadUtils.assertOnUiThread();
if (!LibraryLoader.getInstance().isInitialized()) return;
if (mSpareWebContents != null || SysUtils.isLowEndDevice()) return;
if (!LibraryLoader.getInstance().isInitialized() || mSpareWebContents != null
|| SysUtils.isLowEndDevice()) {
return;
}
mSpareWebContents = WebContentsFactory.createWebContentsWithWarmRenderer(
false /* incognito */, true /* initiallyHidden */);
mObserver = new RenderProcessGoneObserver();
mSpareWebContents.addObserver(mObserver);
mWebContentsCreationTimeMs = SystemClock.elapsedRealtime();
recordWebContentsStatus(WEBCONTENTS_STATUS_CREATED);
recordWebContentsStatus(WebContentsStatus.CREATED);
}
/**
......@@ -344,7 +354,7 @@ public final class WarmupManager {
public void destroySpareWebContents() {
ThreadUtils.assertOnUiThread();
if (mSpareWebContents == null) return;
recordWebContentsStatus(WEBCONTENTS_STATUS_DESTROYED);
recordWebContentsStatus(WebContentsStatus.DESTROYED);
destroySpareWebContentsInternal();
}
......@@ -364,7 +374,7 @@ public final class WarmupManager {
result.removeObserver(mObserver);
mObserver = null;
if (!initiallyHidden) result.onShow();
recordWebContentsStatus(WEBCONTENTS_STATUS_USED);
recordWebContentsStatus(WebContentsStatus.USED);
return result;
}
......@@ -382,9 +392,9 @@ public final class WarmupManager {
mObserver = null;
}
private static void recordWebContentsStatus(int status) {
private static void recordWebContentsStatus(@WebContentsStatus int status) {
RecordHistogram.recordEnumeratedHistogram(
WEBCONTENTS_STATUS_HISTOGRAM, status, WEBCONTENTS_STATUS_COUNT);
WEBCONTENTS_STATUS_HISTOGRAM, status, WebContentsStatus.NUM_ENTRIES);
}
private static native void nativeStartPreconnectPredictorInitialization(Profile profile);
......
......@@ -202,8 +202,8 @@ public class BluetoothChooserDialogTest {
}
});
Assert.assertEquals(BluetoothChooserDialog.DIALOG_FINISHED_CANCELLED,
mChooserDialog.mFinishedEventType);
Assert.assertEquals(
BluetoothChooserDialog.DialogFinished.CANCELLED, mChooserDialog.mFinishedEventType);
Assert.assertEquals("", mChooserDialog.mFinishedDeviceId);
}
......@@ -261,7 +261,7 @@ public class BluetoothChooserDialogTest {
selectItem(mChooserDialog, 2);
Assert.assertEquals(
BluetoothChooserDialog.DIALOG_FINISHED_SELECTED, mChooserDialog.mFinishedEventType);
BluetoothChooserDialog.DialogFinished.SELECTED, mChooserDialog.mFinishedEventType);
Assert.assertEquals("id-2", mChooserDialog.mFinishedDeviceId);
}
......@@ -284,8 +284,10 @@ public class BluetoothChooserDialogTest {
new TestAndroidPermissionDelegate(dialog);
mWindowAndroid.setAndroidPermissionDelegate(permissionDelegate);
ThreadUtils.runOnUiThreadBlocking(() -> mChooserDialog.notifyDiscoveryState(
BluetoothChooserDialog.DISCOVERY_FAILED_TO_START));
ThreadUtils.runOnUiThreadBlocking(
()
-> mChooserDialog.notifyDiscoveryState(
BluetoothChooserDialog.DiscoveryMode.DISCOVERY_FAILED_TO_START));
Assert.assertEquals(removeLinkTags(mActivityTestRule.getActivity().getString(
R.string.bluetooth_need_location_permission)),
......@@ -342,8 +344,10 @@ public class BluetoothChooserDialogTest {
mLocationUtils.mLocationGranted = true;
mLocationUtils.mSystemLocationSettingsEnabled = false;
ThreadUtils.runOnUiThreadBlocking(() -> mChooserDialog.notifyDiscoveryState(
BluetoothChooserDialog.DISCOVERY_FAILED_TO_START));
ThreadUtils.runOnUiThreadBlocking(
()
-> mChooserDialog.notifyDiscoveryState(
BluetoothChooserDialog.DiscoveryMode.DISCOVERY_FAILED_TO_START));
Assert.assertEquals(removeLinkTags(mActivityTestRule.getActivity().getString(
R.string.bluetooth_need_location_services_on)),
......
......@@ -50,13 +50,13 @@ public class PowerBroadcastReceiverTest {
public CallbackHelper runActionsHelper = new CallbackHelper();
@Override
public void setState(int state) {
public void setState(@State int state) {
super.setState(state);
if (state == STATE_POSTED) {
if (state == State.POSTED) {
postHelper.notifyCalled();
} else if (state == STATE_CANCELED) {
} else if (state == State.CANCELED) {
cancelHelper.notifyCalled();
} else if (state == STATE_COMPLETED) {
} else if (state == State.COMPLETED) {
runHelper.notifyCalled();
}
}
......
......@@ -58,30 +58,31 @@ public class RestoreHistogramTest {
@SmallTest
public void testHistogramWriter() throws ProcessInitException {
LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER);
MetricsUtils.HistogramDelta noRestoreDelta = new MetricsUtils.HistogramDelta(
ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT, ChromeBackupAgent.NO_RESTORE);
MetricsUtils.HistogramDelta noRestoreDelta =
new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT,
ChromeBackupAgent.RestoreStatus.NO_RESTORE);
MetricsUtils.HistogramDelta restoreCompletedDelta =
new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT,
ChromeBackupAgent.RESTORE_COMPLETED);
ChromeBackupAgent.RestoreStatus.RESTORE_COMPLETED);
MetricsUtils.HistogramDelta restoreStatusRecorded =
new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT,
ChromeBackupAgent.RESTORE_STATUS_RECORDED);
ChromeBackupAgent.RestoreStatus.RESTORE_STATUS_RECORDED);
// Check behavior with no preference set
clearPrefs();
ChromeBackupAgent.recordRestoreHistogram();
Assert.assertEquals(1, noRestoreDelta.getDelta());
Assert.assertEquals(0, restoreCompletedDelta.getDelta());
Assert.assertEquals(
ChromeBackupAgent.RESTORE_STATUS_RECORDED, ChromeBackupAgent.getRestoreStatus());
Assert.assertEquals(ChromeBackupAgent.RestoreStatus.RESTORE_STATUS_RECORDED,
ChromeBackupAgent.getRestoreStatus());
// Check behavior with a restore status
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RESTORE_COMPLETED);
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.RESTORE_COMPLETED);
ChromeBackupAgent.recordRestoreHistogram();
Assert.assertEquals(1, noRestoreDelta.getDelta());
Assert.assertEquals(1, restoreCompletedDelta.getDelta());
Assert.assertEquals(
ChromeBackupAgent.RESTORE_STATUS_RECORDED, ChromeBackupAgent.getRestoreStatus());
Assert.assertEquals(ChromeBackupAgent.RestoreStatus.RESTORE_STATUS_RECORDED,
ChromeBackupAgent.getRestoreStatus());
// Second call should record nothing (note this assumes it doesn't record something totally
// random)
......@@ -99,8 +100,9 @@ public class RestoreHistogramTest {
@SmallTest
public void testWritingHistogramAtStartup() throws InterruptedException, ProcessInitException {
LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER);
MetricsUtils.HistogramDelta noRestoreDelta = new MetricsUtils.HistogramDelta(
ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT, ChromeBackupAgent.NO_RESTORE);
MetricsUtils.HistogramDelta noRestoreDelta =
new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT,
ChromeBackupAgent.RestoreStatus.NO_RESTORE);
// Histogram should be written the first time the activity is started.
mActivityTestRule.startMainActivityOnBlankPage();
......
......@@ -157,13 +157,13 @@ public class WarmupManagerTest {
public void testRecordSpareWebContentsStatus() throws Throwable {
String name = WarmupManager.WEBCONTENTS_STATUS_HISTOGRAM;
MetricsUtils.HistogramDelta createdDelta =
new MetricsUtils.HistogramDelta(name, WarmupManager.WEBCONTENTS_STATUS_CREATED);
new MetricsUtils.HistogramDelta(name, WarmupManager.WebContentsStatus.CREATED);
MetricsUtils.HistogramDelta usedDelta =
new MetricsUtils.HistogramDelta(name, WarmupManager.WEBCONTENTS_STATUS_USED);
new MetricsUtils.HistogramDelta(name, WarmupManager.WebContentsStatus.USED);
MetricsUtils.HistogramDelta killedDelta =
new MetricsUtils.HistogramDelta(name, WarmupManager.WEBCONTENTS_STATUS_KILLED);
new MetricsUtils.HistogramDelta(name, WarmupManager.WebContentsStatus.KILLED);
MetricsUtils.HistogramDelta destroyedDelta =
new MetricsUtils.HistogramDelta(name, WarmupManager.WEBCONTENTS_STATUS_DESTROYED);
new MetricsUtils.HistogramDelta(name, WarmupManager.WebContentsStatus.DESTROYED);
// Created, used.
mWarmupManager.createSpareWebContents();
......
......@@ -456,8 +456,8 @@ public class ChromeBackupAgentTest {
false /* allocateChildConnection */, true /* initVariationSeed */);
// Test that the status of the restore has been recorded.
assertThat(
ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.RESTORE_COMPLETED));
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.RESTORE_COMPLETED));
// The test mocks out everything that forces the AsyncTask used by PathUtils setup to
// complete. If it isn't completed before the test exits Robolectric crashes with a null
......@@ -494,7 +494,8 @@ public class ChromeBackupAgentTest {
false /* allocateChildConnection */, true /* initVariationSeed */);
// Test that the status of the restore has been recorded.
assertThat(ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.NOT_SIGNED_IN));
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.NOT_SIGNED_IN));
// The test mocks out everything that forces the AsyncTask used by PathUtils setup to
// complete. If it isn't completed before the test exits Robolectric crashes with a null
......@@ -527,7 +528,7 @@ public class ChromeBackupAgentTest {
// Test that the status of the restore has been recorded.
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.BROWSER_STARTUP_FAILED));
equalTo(ChromeBackupAgent.RestoreStatus.BROWSER_STARTUP_FAILED));
// The test mocks out everything that forces the AsyncTask used by PathUtils setup to
// complete. If it isn't completed before the test exits Robolectric crashes with a null
......@@ -560,7 +561,7 @@ public class ChromeBackupAgentTest {
// Test that the status of the restore has been recorded.
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RESTORE_AFTER_FIRST_RUN));
equalTo(ChromeBackupAgent.RestoreStatus.RESTORE_AFTER_FIRST_RUN));
// The test mocks out everything that forces the AsyncTask used by PathUtils setup to
// complete. If it isn't completed before the test exits Robolectric crashes with a null
......@@ -574,32 +575,35 @@ public class ChromeBackupAgentTest {
@Test
public void testGetRestoreStatus() {
// Test default value
assertThat(ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.NO_RESTORE));
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.NO_RESTORE));
// Test that the value can be changed
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RESTORE_AFTER_FIRST_RUN);
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.RESTORE_AFTER_FIRST_RUN);
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RESTORE_AFTER_FIRST_RUN));
equalTo(ChromeBackupAgent.RestoreStatus.RESTORE_AFTER_FIRST_RUN));
// Prove that the value equalTo held in the app preferences (and not, for example, in a
// static).
clearPrefs();
assertThat(ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.NO_RESTORE));
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.NO_RESTORE));
// Test that ChromeBackupAgent.setRestoreStatus really looks at the argument.
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.BROWSER_STARTUP_FAILED);
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.BROWSER_STARTUP_FAILED);
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.BROWSER_STARTUP_FAILED));
equalTo(ChromeBackupAgent.RestoreStatus.BROWSER_STARTUP_FAILED));
// Test the remaining values are implemented
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.NOT_SIGNED_IN);
assertThat(ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.NOT_SIGNED_IN));
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RESTORE_COMPLETED);
assertThat(
ChromeBackupAgent.getRestoreStatus(), equalTo(ChromeBackupAgent.RESTORE_COMPLETED));
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RESTORE_STATUS_RECORDED);
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.NOT_SIGNED_IN);
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.NOT_SIGNED_IN));
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.RESTORE_COMPLETED);
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RestoreStatus.RESTORE_COMPLETED));
ChromeBackupAgent.setRestoreStatus(ChromeBackupAgent.RestoreStatus.RESTORE_STATUS_RECORDED);
assertThat(ChromeBackupAgent.getRestoreStatus(),
equalTo(ChromeBackupAgent.RESTORE_STATUS_RECORDED));
equalTo(ChromeBackupAgent.RestoreStatus.RESTORE_STATUS_RECORDED));
}
/**
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment