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