org.chromium.base.VisibleForTesting Java Examples

The following examples show how to use org.chromium.base.VisibleForTesting. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChromeActivity.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Triggered when the share menu item is selected.
 * This creates and shows a share intent picker dialog or starts a share intent directly.
 * @param shareDirectly Whether it should share directly with the activity that was most
 *                      recently used to share.
 * @param isIncognito Whether currentTab is incognito.
 */
@VisibleForTesting
public void onShareMenuItemSelected(final boolean shareDirectly, final boolean isIncognito) {
    final Tab currentTab = getActivityTab();
    if (currentTab == null) return;

    PrintingController printingController = PrintingControllerImpl.getInstance();
    if (printingController != null && !currentTab.isNativePage() && !printingController.isBusy()
            && PrefServiceBridge.getInstance().isPrintingEnabled()) {
        PrintShareActivity.enablePrintShareOption(this, new Runnable() {
            @Override
            public void run() {
                triggerShare(currentTab, shareDirectly, isIncognito);
            }
        });
        return;
    }

    triggerShare(currentTab, shareDirectly, isIncognito);
}
 
Example #2
Source File: ContextualSearchSelectionController.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
boolean isValidSelection(String selection, ContentViewCore baseContentView) {
    if (selection.length() > MAX_SELECTION_LENGTH) {
        return false;
    }

    if (!doesContainAWord(selection)) {
        return false;
    }

    if (baseContentView != null && baseContentView.isFocusedNodeEditable()) {
        return false;
    }

    return true;
}
 
Example #3
Source File: CastMessageHandler.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Forwards the media message to the page via the media router.
 * The MEDIA_STATUS message needs to be sent to all the clients.
 * @param message The media that's being send by the receiver.
 * @param request The information about the client and the sequence number to respond with.
 */
@VisibleForTesting
void onMediaMessage(String message, RequestRecord request) {
    mSession.onMediaMessage(message);

    if (isMediaStatusMessage(message)) {
        // MEDIA_STATUS needs to be sent to all the clients.
        for (String clientId : mRouteProvider.getClients()) {
            if (request != null && clientId.equals(request.clientId)) continue;

            sendClientMessageTo(
                    clientId, "v2_message", message, INVALID_SEQUENCE_NUMBER);
        }
    }
    if (request != null) {
        sendClientMessageTo(
                request.clientId, "v2_message", message, request.sequenceNumber);
    }
}
 
Example #4
Source File: DocumentModeAssassin.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** Migrates the user from document mode to tabbed mode if necessary. */
@VisibleForTesting
public final void migrateFromDocumentToTabbedMode() {
    ThreadUtils.assertOnUiThread();

    // Migration is already underway.
    if (mStage != STAGE_UNINITIALIZED) return;

    // If migration isn't necessary, don't do anything.
    if (!isMigrationNecessary()) {
        setStage(STAGE_UNINITIALIZED, STAGE_DONE);
        return;
    }

    // If we've crashed or failed too many times, send them to tabbed mode without their data.
    // - Any incorrect or invalid files in the tabbed mode directory will be wiped out by the
    //   TabPersistentStore when the ChromeTabbedActivity starts.
    //
    // - If it crashes in the step after being migrated, then the user will simply be left
    //   with a bunch of inaccessible document mode data instead of being stuck trying to
    //   migrate, which is a lesser evil.  This case will be caught by the check above to see if
    //   migration is even necessary.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    int numMigrationAttempts = prefs.getInt(PREF_NUM_MIGRATION_ATTEMPTS, 0);
    if (numMigrationAttempts >= MAX_MIGRATION_ATTEMPTS_BEFORE_FAILURE) {
        Log.e(TAG, "Too many failures.  Migrating user to tabbed mode without data.");
        setStage(STAGE_UNINITIALIZED, STAGE_WRITE_TABMODEL_METADATA_DONE);
        return;
    }

    // Kick off the migration pipeline.
    // Using apply() instead of commit() seems to save the preference just fine, even if Chrome
    // crashes immediately afterward.
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(PREF_NUM_MIGRATION_ATTEMPTS, numMigrationAttempts + 1);
    editor.apply();
    setStage(STAGE_UNINITIALIZED, STAGE_INITIALIZED);
}
 
Example #5
Source File: DelayedInvalidationsController.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * If there are any pending invalidations, they will be cleared.
 */
@VisibleForTesting
public void clearPendingInvalidations(Context context) {
    SharedPreferences.Editor editor =
            ContextUtils.getAppSharedPreferences().edit();
    editor.putString(DELAYED_ACCOUNT_NAME, null);
    editor.putStringSet(DELAYED_INVALIDATIONS, null);
    editor.apply();
}
 
Example #6
Source File: NotificationPlatformBridge.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether to use standard notification layouts, using NotificationCompat.Builder,
 * or custom layouts using Chrome's own templates.
 *
 * The --{enable,disable}-web-notification-custom-layouts command line flags take precedence.
 *
 * @return Whether custom layouts should be used.
 */
@VisibleForTesting
static boolean useCustomLayouts() {
    CommandLine commandLine = CommandLine.getInstance();
    if (commandLine.hasSwitch(ChromeSwitches.ENABLE_WEB_NOTIFICATION_CUSTOM_LAYOUTS)) {
        return true;
    }
    if (commandLine.hasSwitch(ChromeSwitches.DISABLE_WEB_NOTIFICATION_CUSTOM_LAYOUTS)) {
        return false;
    }
    if (Build.VERSION.CODENAME.equals("N") || Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        return false;
    }
    return true;
}
 
Example #7
Source File: TabPersistentStore.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes {@code selector} to a byte array, copying out the data pertaining to tab ordering
 * and selected indices.
 * @param selector          The {@link TabModelSelector} to serialize.
 * @param tabsBeingRestored Tabs that are in the process of being restored.
 * @return                  {@code byte[]} containing the serialized state of {@code selector}.
 */
@VisibleForTesting
public static byte[] serializeTabModelSelector(TabModelSelector selector,
        List<TabRestoreDetails> tabsBeingRestored) throws IOException {
    ThreadUtils.assertOnUiThread();

    TabModel incognitoModel = selector.getModel(true);
    TabModelMetadata incognitoInfo = new TabModelMetadata(incognitoModel.index());
    for (int i = 0; i < incognitoModel.getCount(); i++) {
        incognitoInfo.ids.add(incognitoModel.getTabAt(i).getId());
        incognitoInfo.urls.add(incognitoModel.getTabAt(i).getUrl());
    }

    TabModel normalModel = selector.getModel(false);
    TabModelMetadata normalInfo = new TabModelMetadata(normalModel.index());
    for (int i = 0; i < normalModel.getCount(); i++) {
        normalInfo.ids.add(normalModel.getTabAt(i).getId());
        normalInfo.urls.add(normalModel.getTabAt(i).getUrl());
    }

    // Cache the active tab id to be pre-loaded next launch.
    int activeTabId = Tab.INVALID_TAB_ID;
    int activeIndex = normalModel.index();
    if (activeIndex != TabList.INVALID_TAB_INDEX) {
        activeTabId = normalModel.getTabAt(activeIndex).getId();
    }
    // Always override the existing value in case there is no active tab.
    ContextUtils.getAppSharedPreferences().edit().putInt(
            PREF_ACTIVE_TAB_ID, activeTabId).apply();

    return serializeMetadata(normalInfo, incognitoInfo, tabsBeingRestored);
}
 
Example #8
Source File: OmahaClient.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether or not Chrome is currently being used actively.
 */
@VisibleForTesting
protected boolean isChromeBeingUsed() {
    boolean isChromeVisible = ApplicationStatus.hasVisibleActivities();
    boolean isScreenOn = ApiCompatibilityUtils.isInteractive(this);
    return isChromeVisible && isScreenOn;
}
 
Example #9
Source File: RecordHistogram.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Tests may not have native initialized, so they may need to disable metrics. The value should
 * be reset after the test done, to avoid carrying over state to unrelated tests.
 *
 * In JUnit tests this can be done automatically using
 * {@link org.chromium.chrome.browser.DisableHistogramsRule}
 */
@VisibleForTesting
public static void setDisabledForTests(boolean disabled) {
    if (disabled && sDisabledBy != null) {
        throw new IllegalStateException("Histograms are already disabled.", sDisabledBy);
    }
    sDisabledBy = disabled ? new Throwable() : null;
}
 
Example #10
Source File: LayoutManagerChrome.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public void tabSelected(int tabId, int prevId, boolean incognito) {
    // Update the model here so we properly set the right selected TabModel.
    if (getActiveLayout() != null) {
        getActiveLayout().onTabSelected(time(), tabId, prevId, incognito);
    }
}
 
Example #11
Source File: SystemDownloadNotifier.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a successful notification is shown.
 * @param info Pending notification information to be handled.
 * @param notificationId ID of the notification.
 */
@VisibleForTesting
void onSuccessNotificationShown(
        final PendingNotificationInfo notificationInfo, final int notificationId) {
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            DownloadManagerService.getDownloadManagerService(
                    mApplicationContext).onSuccessNotificationShown(
                            notificationInfo.downloadInfo, notificationInfo.canResolve,
                            notificationId, notificationInfo.systemDownloadId);
        }
    });
}
 
Example #12
Source File: CastMessageHandler.java    From delion with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void handleStopMessage(String clientId, int sequenceNumber) {
    Queue<Integer> sequenceNumbersForClient = mStopRequests.get(clientId);
    if (sequenceNumbersForClient == null) {
        sequenceNumbersForClient = new ArrayDeque<Integer>();
        mStopRequests.put(clientId, sequenceNumbersForClient);
    }
    sequenceNumbersForClient.add(sequenceNumber);

    mSession.stopApplication();
}
 
Example #13
Source File: OmahaClient.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("LI_LAZY_INIT_STATIC")
@VisibleForTesting
static VersionNumberGetter getVersionNumberGetter() {
    if (sVersionNumberGetter == null) {
        sVersionNumberGetter = new VersionNumberGetter();
    }
    return sVersionNumberGetter;
}
 
Example #14
Source File: StripLayoutHelper.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * @param tab The StripLayoutTab to look for.
 * @return The index of the tab in the visual ordering.
 */
@VisibleForTesting
public int visualIndexOfTab(StripLayoutTab tab) {
    for (int i = 0; i < mStripTabsVisuallyOrdered.length; i++) {
        if (mStripTabsVisuallyOrdered[i] == tab) {
            return i;
        }
    }
    return -1;
}
 
Example #15
Source File: OAuth2TokenService.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Triggers a notification to all observers of the native and Java instance of the
 * OAuth2TokenService that a refresh token is now available. This may cause observers to retry
 * operations that require authentication.
 */
@VisibleForTesting
public void fireRefreshTokenAvailable(Account account) {
    ThreadUtils.assertOnUiThread();
    assert account != null;
    nativeFireRefreshTokenAvailableFromJava(
            mNativeOAuth2TokenServiceDelegateAndroid, account.name);
}
 
Example #16
Source File: AbstractMediaRouteController.java    From delion with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void setPlayerStateForMediaItemState(int state) {
    PlayerState playerState = PlayerState.STOPPED;
    switch (state) {
        case MediaItemStatus.PLAYBACK_STATE_BUFFERING:
            playerState = PlayerState.LOADING;
            break;
        case MediaItemStatus.PLAYBACK_STATE_CANCELED:
            playerState = PlayerState.FINISHED;
            break;
        case MediaItemStatus.PLAYBACK_STATE_ERROR:
            playerState = PlayerState.ERROR;
            break;
        case MediaItemStatus.PLAYBACK_STATE_FINISHED:
            playerState = PlayerState.FINISHED;
            break;
        case MediaItemStatus.PLAYBACK_STATE_INVALIDATED:
            playerState = PlayerState.INVALIDATED;
            break;
        case MediaItemStatus.PLAYBACK_STATE_PAUSED:
            if (isAtEndOfVideo(getPosition(), getDuration())) {
                playerState = PlayerState.FINISHED;
            } else {
                playerState = PlayerState.PAUSED;
            }
            break;
        case MediaItemStatus.PLAYBACK_STATE_PENDING:
            playerState = PlayerState.PAUSED;
            break;
        case MediaItemStatus.PLAYBACK_STATE_PLAYING:
            playerState = PlayerState.PLAYING;
            break;
        default:
            break;
    }

    mRemotePlayerState = playerState;
}
 
Example #17
Source File: FeatureUtilities.java    From delion with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static boolean hasGoogleAccountAuthenticator(Context context) {
    if (sHasGoogleAccountAuthenticator == null) {
        AccountManagerHelper accountHelper = AccountManagerHelper.get(context);
        sHasGoogleAccountAuthenticator = accountHelper.hasGoogleAccountAuthenticator();
    }
    return sHasGoogleAccountAuthenticator;
}
 
Example #18
Source File: PwsClientImpl.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Get the language code for the default locales and prepend it to the Accept-Language string
 * if it isn't already present. The logic should match PrependToAcceptLanguagesIfNecessary in
 * chrome/browser/android/preferences/pref_service_bridge.cc
 * @param locales A comma separated string that represents a list of default locales.
 * @param acceptLanguages The default language list for the language of the user's locales.
 * @return An updated language list.
 */
@VisibleForTesting
static String prependToAcceptLanguagesIfNecessary(String locales, String acceptLanguages) {
    String localeStrings = locales + "," + acceptLanguages;
    String[] localeList = localeStrings.split(",");

    ArrayList<Locale> uniqueList = new ArrayList<>();
    for (String localeString : localeList) {
        Locale locale = LocaleUtils.forLanguageTag(localeString);
        if (uniqueList.contains(locale) || locale.getLanguage().isEmpty()) {
            continue;
        }
        uniqueList.add(locale);
    }

    // If language is not in the accept languages list, also add language code.
    // A language code should only be inserted after the last languageTag that
    // contains that language.
    // This will work with the IDS_ACCEPT_LANGUAGE localized strings bundled
    // with Chrome but may fail on arbitrary lists of language tags due to
    // differences in case and whitespace.
    HashSet<String> seenLanguages = new HashSet<>();
    ArrayList<String> outputList = new ArrayList<>();
    for (int i = uniqueList.size() - 1; i >= 0; i--) {
        Locale localeAdd = uniqueList.get(i);
        String languageAdd = localeAdd.getLanguage();
        String countryAdd = localeAdd.getCountry();

        if (!seenLanguages.contains(languageAdd)) {
            seenLanguages.add(languageAdd);
            outputList.add(languageAdd);
        }
        if (!countryAdd.isEmpty()) {
            outputList.add(LocaleUtils.toLanguageTag(localeAdd));
        }
    }
    Collections.reverse(outputList);
    return TextUtils.join(",", outputList);
}
 
Example #19
Source File: DocumentTabModelSelector.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Overrides the regular StorageDelegate in the constructor.  MUST be called before the
 * DocumentTabModelSelector instance is created to take effect.
 */
@VisibleForTesting
public static void setStorageDelegateForTests(StorageDelegate delegate) {
    synchronized (STORAGE_DELEGATE_FOR_TESTS_LOCK) {
        sStorageDelegateForTests = delegate;
    }
}
 
Example #20
Source File: PrecacheController.java    From delion with Apache License 2.0 5 votes vote down vote up
/** Releases the precaching {@link WakeLock} if it is held. */
@VisibleForTesting
void releasePrecachingWakeLock() {
    assert mNonThreadSafe.calledOnValidThread();
    Log.v(TAG, "releasing wake lock");
    if (mPrecachingWakeLock != null && mPrecachingWakeLock.isHeld()) {
        mPrecachingWakeLock.release();
    }
}
 
Example #21
Source File: TabIdManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** Returns the Singleton instance of the TabIdManager. */
@VisibleForTesting
static TabIdManager getInstance(Context context) {
    synchronized (INSTANCE_LOCK) {
        if (sInstance == null) sInstance = new TabIdManager(context);
    }
    return sInstance;
}
 
Example #22
Source File: InvalidationServiceFactory.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public static InvalidationService getForTest(Context context) {
    return nativeGetForTest(context);
}
 
Example #23
Source File: CrashFileManager.java    From delion with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
File getCrashDirectory() {
    return new File(mCacheDir, CRASH_DUMP_DIR);
}
 
Example #24
Source File: FeedbackCollector.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * @return the screenshot to use for the feedback report.
 */
@VisibleForTesting
public Bitmap getScreenshot() {
    ThreadUtils.assertOnUiThread();
    return mScreenshot;
}
 
Example #25
Source File: ChromeActivity.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * @return The {@code ReaderModeManager} or {@code null} if none;
 */
@VisibleForTesting
public ReaderModeManager getReaderModeManager() {
    return mReaderModeManager;
}
 
Example #26
Source File: ChromeMediaRouter.java    From delion with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
protected void addMediaRouteProvider(MediaRouteProvider provider) {
    mRouteProviders.add(provider);
}
 
Example #27
Source File: PaymentRequestImpl.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public static void setObserverForTest(PaymentRequestServiceObserverForTest observerForTest) {
    sObserverForTest = observerForTest;
}
 
Example #28
Source File: PowerBroadcastReceiver.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * @return Whether or not this is registered with a context.
 */
@VisibleForTesting
public boolean isRegistered() {
    return mIsRegistered.get();
}
 
Example #29
Source File: ChromeBrowserProvider.java    From delion with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
@SuppressFBWarnings("EI_EXPOSE_REP2")
public void setThumbnail(byte[] thumbnail) {
    mThumbnail = thumbnail;
}
 
Example #30
Source File: TabState.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Overrides the channel name for testing.
 * @param name Channel to use.
 */
@VisibleForTesting
public static void setChannelNameOverrideForTest(String name) {
    sChannelNameOverrideForTest = name;
}