Java Code Examples for org.chromium.chrome.browser.util.UrlUtilities

The following examples show how to use org.chromium.chrome.browser.util.UrlUtilities. These examples are extracted from open source projects. 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 Project: delion   Source File: HelpAndFeedback.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get help context ID from URL.
 *
 * @param url The URL to be checked.
 * @param isIncognito Whether we are in incognito mode or not.
 * @return Help context ID that matches the URL and incognito mode.
 */
public static String getHelpContextIdFromUrl(Context context, String url, boolean isIncognito) {
    if (TextUtils.isEmpty(url)) {
        return context.getString(R.string.help_context_general);
    } else if (url.startsWith(UrlConstants.BOOKMARKS_URL)) {
        return context.getString(R.string.help_context_bookmarks);
    } else if (url.equals(UrlConstants.HISTORY_URL)) {
        return context.getString(R.string.help_context_history);
    // Note: For www.google.com the following function returns false.
    } else if (UrlUtilities.nativeIsGoogleSearchUrl(url)) {
        return context.getString(R.string.help_context_search_results);
    // For incognito NTP, we want to show incognito help.
    } else if (isIncognito) {
        return context.getString(R.string.help_context_incognito);
    } else if (url.equals(UrlConstants.NTP_URL)) {
        return context.getString(R.string.help_context_new_tab);
    }
    return context.getString(R.string.help_context_webpage);
}
 
Example 2
Source Project: delion   Source File: BookmarkEditActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onStop() {
    if (mModel.doesBookmarkExist(mBookmarkId)) {
        final String originalUrl =
                mModel.getBookmarkById(mBookmarkId).getUrl();
        final String title = mTitleEditText.getTrimmedText();
        final String url = mUrlEditText.getTrimmedText();

        if (!mTitleEditText.isEmpty()) {
            mModel.setBookmarkTitle(mBookmarkId, title);
        }

        if (!mUrlEditText.isEmpty()
                && mModel.getBookmarkById(mBookmarkId).isUrlEditable()) {
            String fixedUrl = UrlUtilities.fixupUrl(url);
            if (fixedUrl != null && !fixedUrl.equals(originalUrl)) {
                mModel.setBookmarkUrl(mBookmarkId, fixedUrl);
            }
        }
    }

    super.onStop();
}
 
Example 3
Source Project: delion   Source File: CustomTabActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads the current tab with the given load params while taking client
 * referrer and extra headers into account.
 */
private void loadUrlInTab(final Tab tab, final LoadUrlParams params, long timeStamp) {
    Intent intent = getIntent();
    String url = getUrlToLoad();
    if (mHasPrerendered && UrlUtilities.urlsFragmentsDiffer(mPrerenderedUrl, url)) {
        mHasPrerendered = false;
        LoadUrlParams temporaryParams = new LoadUrlParams(mPrerenderedUrl);
        IntentHandler.addReferrerAndHeaders(temporaryParams, intent, this);
        tab.loadUrl(temporaryParams);
        params.setShouldReplaceCurrentEntry(true);
    }

    IntentHandler.addReferrerAndHeaders(params, intent, this);
    if (params.getReferrer() == null) {
        params.setReferrer(CustomTabsConnection.getInstance(getApplication())
                .getReferrerForSession(mSession));
    }
    // See ChromeTabCreator#getTransitionType(). This marks the navigation chain as starting
    // from an external intent (unless otherwise specified by an extra in the intent).
    params.setTransitionType(IntentHandler.getTransitionTypeFromIntent(this, intent,
            PageTransition.LINK | PageTransition.FROM_API));
    mTabObserver.trackNextPageLoadFromTimestamp(timeStamp);
    tab.loadUrl(params);
}
 
Example 4
Source Project: delion   Source File: GeolocationHeader.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isGeoHeaderEnabledForUrl(Context context, String url,
        boolean isIncognito, boolean recordUma) {
    // Only send X-Geo in normal mode.
    if (isIncognito) return false;

    // Only send X-Geo header to Google domains.
    if (!UrlUtilities.nativeIsGoogleSearchUrl(url)) return false;

    Uri uri = Uri.parse(url);
    if (!HTTPS_SCHEME.equals(uri.getScheme())) return false;

    if (!hasGeolocationPermission(context)) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_CHROME_APP);
        return false;
    }

    // Only send X-Geo header if the user hasn't disabled geolocation for url.
    if (isLocationDisabledForUrl(uri, isIncognito)) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_GOOGLE_DOMAIN);
        return false;
    }

    return true;
}
 
Example 5
Source Project: delion   Source File: RoundedIconGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the text which should be used for generating a rounded icon based on |url|.
 *
 * @param url URL to consider when getting the icon's text.
 * @param includePrivateRegistries Should private registries be considered as TLDs?
 * @return The text to use on the rounded icon, or NULL if |url| is empty or the domain cannot
 *         be resolved.
 */
@Nullable
@VisibleForTesting
public static String getIconTextForUrl(String url, boolean includePrivateRegistries) {
    String domain = UrlUtilities.getDomainAndRegistry(url, includePrivateRegistries);
    if (!TextUtils.isEmpty(domain)) return domain;

    // Special-case chrome:// and chrome-native:// URLs.
    if (url.startsWith(UrlConstants.CHROME_SCHEME)
            || url.startsWith(UrlConstants.CHROME_NATIVE_SCHEME)) {
        return "chrome";
    }

    // Use the host component of |url| when it can be parsed as a URI.
    try {
        URI uri = new URI(url);
        if (!TextUtils.isEmpty(uri.getHost())) {
            return uri.getHost();
        }
    } catch (Exception e) {
        Log.w(TAG, "Unable to parse the URL for generating an icon: " + url);
    }

    return url;
}
 
Example 6
Source Project: AndroidChromium   Source File: HelpAndFeedback.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get help context ID from URL.
 *
 * @param url The URL to be checked.
 * @param isIncognito Whether we are in incognito mode or not.
 * @return Help context ID that matches the URL and incognito mode.
 */
public static String getHelpContextIdFromUrl(Context context, String url, boolean isIncognito) {
    if (TextUtils.isEmpty(url)) {
        return context.getString(R.string.help_context_general);
    } else if (url.startsWith(UrlConstants.BOOKMARKS_URL)) {
        return context.getString(R.string.help_context_bookmarks);
    } else if (url.equals(UrlConstants.HISTORY_URL)) {
        return context.getString(R.string.help_context_history);
    // Note: For www.google.com the following function returns false.
    } else if (UrlUtilities.nativeIsGoogleSearchUrl(url)) {
        return context.getString(R.string.help_context_search_results);
    // For incognito NTP, we want to show incognito help.
    } else if (isIncognito) {
        return context.getString(R.string.help_context_incognito);
    } else if (url.equals(UrlConstants.NTP_URL)) {
        return context.getString(R.string.help_context_new_tab);
    }
    return context.getString(R.string.help_context_webpage);
}
 
Example 7
Source Project: AndroidChromium   Source File: CustomTabActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads the current tab with the given load params while taking client
 * referrer and extra headers into account.
 */
private void loadUrlInTab(final Tab tab, final LoadUrlParams params, long timeStamp) {
    Intent intent = getIntent();
    String url = getUrlToLoad();
    if (mHasPrerendered && UrlUtilities.urlsFragmentsDiffer(mPrerenderedUrl, url)) {
        mHasPrerendered = false;
        LoadUrlParams temporaryParams = new LoadUrlParams(mPrerenderedUrl);
        IntentHandler.addReferrerAndHeaders(temporaryParams, intent, this);
        tab.loadUrl(temporaryParams);
        params.setShouldReplaceCurrentEntry(true);
    }

    IntentHandler.addReferrerAndHeaders(params, intent, this);
    if (params.getReferrer() == null) {
        params.setReferrer(CustomTabsConnection.getInstance(getApplication())
                .getReferrerForSession(mSession));
    }
    // See ChromeTabCreator#getTransitionType(). This marks the navigation chain as starting
    // from an external intent (unless otherwise specified by an extra in the intent).
    params.setTransitionType(IntentHandler.getTransitionTypeFromIntent(this, intent,
            PageTransition.LINK | PageTransition.FROM_API));
    mTabObserver.trackNextPageLoadFromTimestamp(timeStamp);
    tab.loadUrl(params);
}
 
Example 8
Source Project: AndroidChromium   Source File: GeolocationHeader.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isGeoHeaderEnabledForUrl(Context context, String url,
        boolean isIncognito, boolean recordUma) {
    // Only send X-Geo in normal mode.
    if (isIncognito) return false;

    // Only send X-Geo header to Google domains.
    if (!UrlUtilities.nativeIsGoogleSearchUrl(url)) return false;

    Uri uri = Uri.parse(url);
    if (!HTTPS_SCHEME.equals(uri.getScheme())) return false;

    if (!hasGeolocationPermission(context)) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_CHROME_APP);
        return false;
    }

    // Only send X-Geo header if the user hasn't disabled geolocation for url.
    if (isLocationDisabledForUrl(uri, isIncognito)) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_GOOGLE_DOMAIN);
        return false;
    }

    return true;
}
 
Example 9
Source Project: AndroidChromium   Source File: RoundedIconGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the text which should be used for generating a rounded icon based on |url|.
 *
 * @param url URL to consider when getting the icon's text.
 * @param includePrivateRegistries Should private registries be considered as TLDs?
 * @return The text to use on the rounded icon, or NULL if |url| is empty or the domain cannot
 *         be resolved.
 */
@Nullable
@VisibleForTesting
public static String getIconTextForUrl(String url, boolean includePrivateRegistries) {
    String domain = UrlUtilities.getDomainAndRegistry(url, includePrivateRegistries);
    if (!TextUtils.isEmpty(domain)) return domain;

    // Special-case chrome:// and chrome-native:// URLs.
    if (url.startsWith(UrlConstants.CHROME_SCHEME)
            || url.startsWith(UrlConstants.CHROME_NATIVE_SCHEME)) {
        return "chrome";
    }

    // Use the host component of |url| when it can be parsed as a URI.
    try {
        URI uri = new URI(url);
        if (!TextUtils.isEmpty(uri.getHost())) {
            return uri.getHost();
        }
    } catch (Exception e) {
        Log.w(TAG, "Unable to parse the URL for generating an icon: " + url);
    }

    return url;
}
 
Example 10
Source Project: 365browser   Source File: HelpAndFeedback.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get help context ID from URL.
 *
 * @param url The URL to be checked.
 * @param isIncognito Whether we are in incognito mode or not.
 * @return Help context ID that matches the URL and incognito mode.
 */
public static String getHelpContextIdFromUrl(Context context, String url, boolean isIncognito) {
    if (TextUtils.isEmpty(url)) {
        return context.getString(R.string.help_context_general);
    } else if (url.startsWith(UrlConstants.BOOKMARKS_URL)) {
        return context.getString(R.string.help_context_bookmarks);
    } else if (url.equals(UrlConstants.HISTORY_URL)) {
        return context.getString(R.string.help_context_history);
    // Note: For www.google.com the following function returns false.
    } else if (UrlUtilities.nativeIsGoogleSearchUrl(url)) {
        return context.getString(R.string.help_context_search_results);
    // For incognito NTP, we want to show incognito help.
    } else if (isIncognito) {
        return context.getString(R.string.help_context_incognito);
    } else if (url.equals(UrlConstants.NTP_URL)) {
        return context.getString(R.string.help_context_new_tab);
    }
    return context.getString(R.string.help_context_webpage);
}
 
Example 11
Source Project: 365browser   Source File: UrlBar.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Emphasize components of the URL for readability.
 */
public void emphasizeUrl() {
    Editable url = getText();
    if (OmniboxUrlEmphasizer.hasEmphasisSpans(url) || hasFocus()) {
        return;
    }

    if (url.length() < 1) {
        return;
    }

    Tab currentTab = mUrlBarDelegate.getCurrentTab();
    if (currentTab == null || currentTab.getProfile() == null) return;

    boolean isInternalPage = false;
    try {
        String tabUrl = currentTab.getUrl();
        isInternalPage = UrlUtilities.isInternalScheme(new URI(tabUrl));
    } catch (URISyntaxException e) {
        // Ignore as this only is for applying color
    }

    OmniboxUrlEmphasizer.emphasizeUrl(url, getResources(), currentTab.getProfile(),
            currentTab.getSecurityLevel(), isInternalPage,
            mUseDarkColors, mUrlBarDelegate.shouldEmphasizeHttpsScheme());
}
 
Example 12
Source Project: 365browser   Source File: GeolocationHeader.java    License: Apache License 2.0 6 votes vote down vote up
@HeaderState
private static int geoHeaderStateForUrl(String url, boolean isIncognito, boolean recordUma) {
    // Only send X-Geo in normal mode.
    if (isIncognito) return INCOGNITO;

    // Only send X-Geo header to Google domains.
    if (!UrlUtilities.nativeIsGoogleSearchUrl(url)) return UNSUITABLE_URL;

    Uri uri = Uri.parse(url);
    if (!UrlConstants.HTTPS_SCHEME.equals(uri.getScheme())) return NOT_HTTPS;

    if (!hasGeolocationPermission()) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_CHROME_APP);
        return LOCATION_PERMISSION_BLOCKED;
    }

    // Only send X-Geo header if the user hasn't disabled geolocation for url.
    if (isLocationDisabledForUrl(uri, isIncognito)) {
        if (recordUma) recordHistogram(UMA_LOCATION_DISABLED_FOR_GOOGLE_DOMAIN);
        return LOCATION_PERMISSION_BLOCKED;
    }

    return HEADER_ENABLED;
}
 
Example 13
Source Project: 365browser   Source File: RoundedIconGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the text which should be used for generating a rounded icon based on |url|.
 *
 * @param url URL to consider when getting the icon's text.
 * @param includePrivateRegistries Should private registries be considered as TLDs?
 * @return The text to use on the rounded icon, or NULL if |url| is empty or the domain cannot
 *         be resolved.
 */
@Nullable
@VisibleForTesting
public static String getIconTextForUrl(String url, boolean includePrivateRegistries) {
    String domain = UrlUtilities.getDomainAndRegistry(url, includePrivateRegistries);
    if (!TextUtils.isEmpty(domain)) return domain;

    // Special-case chrome:// and chrome-native:// URLs.
    if (url.startsWith(UrlConstants.CHROME_URL_PREFIX)
            || url.startsWith(UrlConstants.CHROME_NATIVE_URL_PREFIX)) {
        return UrlConstants.CHROME_SCHEME;
    }

    // Use the host component of |url| when it can be parsed as a URI.
    try {
        URI uri = new URI(url);
        if (!TextUtils.isEmpty(uri.getHost())) {
            return uri.getHost();
        }
    } catch (Exception e) {
        Log.w(TAG, "Unable to parse the URL for generating an icon: " + url);
    }

    return url;
}
 
Example 14
Source Project: delion   Source File: PaymentRequestImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds the PaymentRequest service implementation.
 *
 * @param webContents The web contents that have invoked the PaymentRequest API.
 */
public PaymentRequestImpl(WebContents webContents) {
    if (webContents == null) return;

    ContentViewCore contentViewCore = ContentViewCore.fromWebContents(webContents);
    if (contentViewCore == null) return;

    WindowAndroid window = contentViewCore.getWindowAndroid();
    if (window == null) return;

    mContext = window.getActivity().get();
    if (mContext == null) return;

    mMerchantName = webContents.getTitle();
    // The feature is available only in secure context, so it's OK to not show HTTPS.
    mOrigin = UrlUtilities.formatUrlForSecurityDisplay(webContents.getVisibleUrl(), false);

    final FaviconHelper faviconHelper = new FaviconHelper();
    float scale = mContext.getResources().getDisplayMetrics().density;
    faviconHelper.getLocalFaviconImageForURL(Profile.getLastUsedProfile(),
            webContents.getVisibleUrl(), (int) (FAVICON_SIZE_DP * scale + 0.5f),
            new FaviconHelper.FaviconImageCallback() {
                @Override
                public void onFaviconAvailable(Bitmap bitmap, String iconUrl) {
                    faviconHelper.destroy();
                    if (bitmap == null) return;
                    if (mUI == null) {
                        mFavicon = bitmap;
                        return;
                    }
                    mUI.setTitleBitmap(bitmap);
                }
            });

    mApps = PaymentAppFactory.create(webContents);
}
 
Example 15
Source Project: delion   Source File: ActivityTabTaskDescriptionHelper.java    License: Apache License 2.0 5 votes vote down vote up
private void updateTaskDescription() {
    if (mCurrentTab == null) {
        updateTaskDescription(null, null);
        return;
    }

    if (NewTabPage.isNTPUrl(mCurrentTab.getUrl()) && !mCurrentTab.isIncognito()) {
        // NTP needs a new color in recents, but uses the default application title and icon
        updateTaskDescription(null, null);
        return;
    }

    String label = mCurrentTab.getTitle();
    String domain = UrlUtilities.getDomainAndRegistry(mCurrentTab.getUrl(), false);
    if (TextUtils.isEmpty(label)) {
        label = domain;
    }
    if (mLargestFavicon == null && TextUtils.isEmpty(label)) {
        updateTaskDescription(null, null);
        return;
    }

    Bitmap bitmap = null;
    if (!mCurrentTab.isIncognito()) {
        bitmap = mIconGenerator.getBitmap(mCurrentTab.getUrl(), mLargestFavicon);
    }

    updateTaskDescription(label, bitmap);
}
 
Example 16
Source Project: delion   Source File: ClientManager.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
synchronized int getPredictionOutcome(CustomTabsSessionToken session, String url) {
    SessionParams params = mSessionParams.get(session);
    if (params == null) return NO_PREDICTION;

    String predictedUrl = params.getPredictedUrl();
    if (predictedUrl == null) return NO_PREDICTION;

    boolean urlsMatch = TextUtils.equals(predictedUrl, url)
            || (params.mIgnoreFragments
                    && UrlUtilities.urlsMatchIgnoringFragments(predictedUrl, url));
    return urlsMatch ? GOOD_PREDICTION : BAD_PREDICTION;
}
 
Example 17
Source Project: delion   Source File: CustomTabDelegateFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean startActivityIfNeeded(Intent intent) {
    boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(intent.getDataString());
    boolean hasDefaultHandler = hasDefaultHandler(intent);
    try {
        // For a URL chrome can handle and there is no default set, handle it ourselves.
        if (!hasDefaultHandler) {
            if (!TextUtils.isEmpty(mClientPackageName) && isPackageSpecializedHandler(
                    mApplicationContext, mClientPackageName, intent)) {
                intent.setPackage(mClientPackageName);
            } else if (!isExternalProtocol) {
                return false;
            }
        }
        // If android fails to find a handler, handle it ourselves.
        Context context = getAvailableContext();
        if (context instanceof Activity
                && ((Activity) context).startActivityIfNeeded(intent, -1)) {
            mHasActivityStarted = true;
            return true;
        }
        return false;
    } catch (RuntimeException e) {
        logTransactionTooLargeOrRethrow(e, intent);
        return false;
    }
}
 
Example 18
Source Project: delion   Source File: UrlBar.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emphasize the TLD and second domain of the URL.
 */
public void emphasizeUrl() {
    Editable url = getText();
    if (OmniboxUrlEmphasizer.hasEmphasisSpans(url) || hasFocus()) {
        return;
    }

    if (url.length() < 1) {
        return;
    }

    // We retrieve the domain and registry from the full URL (the url bar shows a simplified
    // version of the URL).
    Tab currentTab = mUrlBarDelegate.getCurrentTab();
    if (currentTab == null || currentTab.getProfile() == null) return;

    boolean isInternalPage = false;
    try {
        String tabUrl = currentTab.getUrl();
        isInternalPage = UrlUtilities.isInternalScheme(new URI(tabUrl));
    } catch (URISyntaxException e) {
        // Ignore as this only is for applying color
    }

    OmniboxUrlEmphasizer.emphasizeUrl(url, getResources(), currentTab.getProfile(),
            currentTab.getSecurityLevel(), isInternalPage,
            mUseDarkColors, mUrlBarDelegate.shouldEmphasizeHttpsScheme());
}
 
Example 19
Source Project: delion   Source File: NewTabPageUma.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Record that the user has navigated away from the NTP using the omnibox.
 * @param destinationUrl The URL to which the user navigated.
 * @param transitionType The transition type of the navigation, from PageTransition.java.
 */
public static void recordOmniboxNavigation(String destinationUrl, int transitionType) {
    if ((transitionType & PageTransition.CORE_MASK) == PageTransition.GENERATED) {
        recordAction(ACTION_SEARCHED_USING_OMNIBOX);
    } else {
        if (UrlUtilities.nativeIsGoogleHomePageUrl(destinationUrl)) {
            recordAction(ACTION_NAVIGATED_TO_GOOGLE_HOMEPAGE);
        } else {
            recordAction(ACTION_NAVIGATED_USING_OMNIBOX);
        }
        recordExplicitUserNavigation(destinationUrl, RAPPOR_ACTION_NAVIGATED_USING_OMNIBOX);
    }
}
 
Example 20
Source Project: delion   Source File: TabContextMenuItemDelegate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onOpenInChrome(String linkUrl, String pageUrl) {
    Intent chromeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl));
    chromeIntent.setPackage(mTab.getApplicationContext().getPackageName());
    chromeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    boolean activityStarted = false;
    if (pageUrl != null) {
        try {
            URI pageUri = URI.create(pageUrl);
            if (UrlUtilities.isInternalScheme(pageUri)) {
                IntentHandler.startChromeLauncherActivityForTrustedIntent(
                        chromeIntent, mTab.getApplicationContext());
                activityStarted = true;
            }
        } catch (IllegalArgumentException ex) {
            // Ignore the exception for creating the URI and launch the intent
            // without the trusted intent extras.
        }
    }

    if (!activityStarted) {
        Context context = mTab.getActivity();
        if (context == null) context = mTab.getApplicationContext();
        context.startActivity(chromeIntent);
        activityStarted = true;
    }
}
 
Example 21
Source Project: delion   Source File: WebappDelegateFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the top controls should be shown when a webapp is navigated to
 * {@link url}.
 * @param webappStartUrl The webapp's URL when it is opened from the home screen.
 * @param url The webapp's current URL
 * @param securityLevel The security level for the webapp's current URL.
 * @return Whether the top controls should be shown for {@link url}.
 */
public static boolean shouldShowTopControls(
        String webappStartUrl, String url, int securityLevel) {
    // Do not show top controls when URL is not ready yet.
    boolean visible = false;
    if (TextUtils.isEmpty(url)) return false;

    boolean isSameWebsite =
            UrlUtilities.sameDomainOrHost(webappStartUrl, url, true);
    visible = !isSameWebsite || securityLevel == ConnectionSecurityLevel.SECURITY_ERROR
            || securityLevel == ConnectionSecurityLevel.SECURITY_WARNING;
    return visible;
}
 
Example 22
Source Project: delion   Source File: WebappUrlBar.java    License: Apache License 2.0 5 votes vote down vote up
private void updateDisplayedUrl(String originalUrl, URI uri) {
    boolean showScheme = mCurrentIconResource == 0;
    String displayUrl = originalUrl;
    if (uri != null) {
        String shortenedUrl = UrlUtilities.formatUrlForSecurityDisplay(uri, showScheme);
        if (!TextUtils.isEmpty(shortenedUrl)) displayUrl = shortenedUrl;
    }

    mUrlBar.setText(displayUrl);
    if (!TextUtils.equals(mCurrentlyDisplayedUrl, displayUrl)) {
        mCurrentlyDisplayedUrl = displayUrl;
    }
}
 
Example 23
Source Project: delion   Source File: SingleWebsitePreferences.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Bundle with the correct arguments for opening this fragment for
 * the website with the given url.
 *
 * @param url The URL to open the fragment with. This is a complete url including scheme,
 *            domain, port,  path, etc.
 * @return The bundle to attach to the preferences intent.
 */
public static Bundle createFragmentArgsForSite(String url) {
    Bundle fragmentArgs = new Bundle();
    // TODO(mvanouwerkerk): Define a pure getOrigin method in UrlUtilities that is the
    // equivalent of the call below, because this is perfectly fine for non-display purposes.
    String origin =
            UrlUtilities.formatUrlForSecurityDisplay(URI.create(url), true /* showScheme */);
    fragmentArgs.putString(SingleWebsitePreferences.EXTRA_ORIGIN, origin);
    return fragmentArgs;
}
 
Example 24
Source Project: delion   Source File: ChromeLauncherActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return Whether or not an Herb prototype may hijack an Intent.
 */
public static boolean canBeHijackedByHerb(Intent intent) {
    String url = IntentHandler.getUrlFromIntent(intent);

    // Only VIEW Intents with URLs are rerouted to Custom Tabs.
    if (intent == null || !TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())
            || TextUtils.isEmpty(url)) {
        return false;
    }

    // Don't reroute Chrome Intents.
    Context context = ContextUtils.getApplicationContext();
    if (TextUtils.equals(context.getPackageName(),
            IntentUtils.safeGetStringExtra(intent, Browser.EXTRA_APPLICATION_ID))) {
        return false;
    }

    // Don't reroute internal chrome URLs.
    try {
        URI uri = URI.create(url);
        if (UrlUtilities.isInternalScheme(uri)) return false;
    } catch (IllegalArgumentException e) {
        return false;
    }

    return true;
}
 
Example 25
Source Project: delion   Source File: ExternalNavigationHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the URL needs to be sent as an intent to the system,
 * and sends it, if appropriate.
 * @return Whether the URL generated an intent, caused a navigation in
 *         current tab, or wasn't handled at all.
 */
public OverrideUrlLoadingResult shouldOverrideUrlLoading(ExternalNavigationParams params) {
    Intent intent;
    // Perform generic parsing of the URI to turn it into an Intent.
    try {
        intent = Intent.parseUri(params.getUrl(), Intent.URI_INTENT_SCHEME);
    } catch (Exception ex) {
        Log.w(TAG, "Bad URI %s", params.getUrl(), ex);
        return OverrideUrlLoadingResult.NO_OVERRIDE;
    }

    boolean hasBrowserFallbackUrl = false;
    String browserFallbackUrl =
            IntentUtils.safeGetStringExtra(intent, EXTRA_BROWSER_FALLBACK_URL);
    if (browserFallbackUrl != null
            && UrlUtilities.isValidForIntentFallbackNavigation(browserFallbackUrl)) {
        hasBrowserFallbackUrl = true;
    } else {
        browserFallbackUrl = null;
    }

    long time = SystemClock.elapsedRealtime();
    OverrideUrlLoadingResult result = shouldOverrideUrlLoadingInternal(
            params, intent, hasBrowserFallbackUrl, browserFallbackUrl);
    RecordHistogram.recordTimesHistogram("Android.StrictMode.OverrideUrlLoadingTime",
            SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);

    if (result == OverrideUrlLoadingResult.NO_OVERRIDE && hasBrowserFallbackUrl
            && (params.getRedirectHandler() == null
                    // For instance, if this is a chained fallback URL, we ignore it.
                    || !params.getRedirectHandler().shouldNotOverrideUrlLoading())) {
        return clobberCurrentTabWithFallbackUrl(browserFallbackUrl, params);
    }
    return result;
}
 
Example 26
private void updateTaskDescription() {
    if (mCurrentTab == null) {
        updateTaskDescription(null, null);
        return;
    }

    if (NewTabPage.isNTPUrl(mCurrentTab.getUrl()) && !mCurrentTab.isIncognito()) {
        // NTP needs a new color in recents, but uses the default application title and icon
        updateTaskDescription(null, null);
        return;
    }

    String label = mCurrentTab.getTitle();
    String domain = UrlUtilities.getDomainAndRegistry(mCurrentTab.getUrl(), false);
    if (TextUtils.isEmpty(label)) {
        label = domain;
    }
    if (mLargestFavicon == null && TextUtils.isEmpty(label)) {
        updateTaskDescription(null, null);
        return;
    }

    Bitmap bitmap = null;
    if (!mCurrentTab.isIncognito()) {
        bitmap = mIconGenerator.getBitmap(mCurrentTab.getUrl(), mLargestFavicon);
    }

    updateTaskDescription(label, bitmap);
}
 
Example 27
Source Project: AndroidChromium   Source File: ClientManager.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
synchronized int getPredictionOutcome(CustomTabsSessionToken session, String url) {
    SessionParams params = mSessionParams.get(session);
    if (params == null) return NO_PREDICTION;

    String predictedUrl = params.getPredictedUrl();
    if (predictedUrl == null) return NO_PREDICTION;

    boolean urlsMatch = TextUtils.equals(predictedUrl, url)
            || (params.mIgnoreFragments
                    && UrlUtilities.urlsMatchIgnoringFragments(predictedUrl, url));
    return urlsMatch ? GOOD_PREDICTION : BAD_PREDICTION;
}
 
Example 28
Source Project: AndroidChromium   Source File: CustomTabDelegateFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean startActivityIfNeeded(Intent intent, boolean proxy) {
    boolean isExternalProtocol = !UrlUtilities.isAcceptedScheme(intent.toUri(0));
    boolean hasDefaultHandler = hasDefaultHandler(intent);
    try {
        // For a URL chrome can handle and there is no default set, handle it ourselves.
        if (!hasDefaultHandler) {
            if (!TextUtils.isEmpty(mClientPackageName) && isPackageSpecializedHandler(
                    mApplicationContext, mClientPackageName, intent)) {
                intent.setPackage(mClientPackageName);
            } else if (!isExternalProtocol) {
                return false;
            }
        }

        if (proxy) {
            dispatchAuthenticatedIntent(intent);
            mHasActivityStarted = true;
            return true;
        } else {
            // If android fails to find a handler, handle it ourselves.
            Context context = getAvailableContext();
            if (context instanceof Activity
                    && ((Activity) context).startActivityIfNeeded(intent, -1)) {
                mHasActivityStarted = true;
                return true;
            }
        }
        return false;
    } catch (RuntimeException e) {
        IntentUtils.logTransactionTooLargeOrRethrow(e, intent);
        return false;
    }
}
 
Example 29
Source Project: AndroidChromium   Source File: CustomTabsConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Transfers a prerendered WebContents if one exists.
 *
 * This resets the internal WebContents; a subsequent call to this method
 * returns null. Must be called from the UI thread.
 * If a prerender exists for a different URL with the same sessionId or with
 * a different referrer, then this is treated as a mispredict from the
 * client application, and cancels the previous prerender. This is done to
 * avoid keeping resources laying around for too long, but is subject to a
 * race condition, as the following scenario is possible:
 * The application calls:
 * 1. mayLaunchUrl(url1) <- IPC
 * 2. loadUrl(url2) <- Intent
 * 3. mayLaunchUrl(url3) <- IPC
 * If the IPC for url3 arrives before the intent for url2, then this methods
 * cancels the prerender for url3, which is unexpected. On the other
 * hand, not cancelling the previous prerender leads to wasted resources, as
 * a WebContents is lingering. This can be solved by requiring applications
 * to call mayLaunchUrl(null) to cancel a current prerender before 2, that
 * is for a mispredict.
 *
 * Note that this methods accepts URLs that don't exactly match the initially
 * prerendered URL. More precisely, the #fragment is ignored. In this case,
 * the client needs to navigate to the correct URL after the WebContents
 * swap. This can be tested using {@link UrlUtilities#urlsFragmentsDiffer()}.
 *
 * @param session The Binder object identifying a session.
 * @param url The URL the WebContents is for.
 * @param referrer The referrer to use for |url|.
 * @return The prerendered WebContents, or null.
 */
WebContents takePrerenderedUrl(CustomTabsSessionToken session, String url, String referrer) {
    ThreadUtils.assertOnUiThread();
    if (mSpeculation == null || session == null || !session.equals(mSpeculation.session)) {
        return null;
    }

    if (mSpeculation.prefetchOnly) {
        Profile profile = Profile.getLastUsedProfile();
        new ResourcePrefetchPredictor(profile).stopPrefetching(mSpeculation.url);
        mSpeculation = null;
        return null;
    }

    WebContents webContents = mSpeculation.webContents;
    String prerenderedUrl = mSpeculation.url;
    String prerenderReferrer = mSpeculation.referrer;
    if (referrer == null) referrer = "";
    boolean ignoreFragments = mClientManager.getIgnoreFragmentsForSession(session);
    boolean urlsMatch = TextUtils.equals(prerenderedUrl, url)
            || (ignoreFragments
                    && UrlUtilities.urlsMatchIgnoringFragments(prerenderedUrl, url));
    WebContents result = null;
    if (urlsMatch && TextUtils.equals(prerenderReferrer, referrer)) {
        result = webContents;
        mSpeculation = null;
    } else {
        cancelPrerender(session);
    }
    if (!mClientManager.usesDefaultSessionParameters(session) && webContents != null) {
        RecordHistogram.recordBooleanHistogram(
                "CustomTabs.NonDefaultSessionPrerenderMatched", result != null);
    }

    return result;
}
 
Example 30
Source Project: AndroidChromium   Source File: UrlBar.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emphasize the TLD and second domain of the URL.
 */
public void emphasizeUrl() {
    Editable url = getText();
    if (OmniboxUrlEmphasizer.hasEmphasisSpans(url) || hasFocus()) {
        return;
    }

    if (url.length() < 1) {
        return;
    }

    // We retrieve the domain and registry from the full URL (the url bar shows a simplified
    // version of the URL).
    Tab currentTab = mUrlBarDelegate.getCurrentTab();
    if (currentTab == null || currentTab.getProfile() == null) return;

    boolean isInternalPage = false;
    try {
        String tabUrl = currentTab.getUrl();
        isInternalPage = UrlUtilities.isInternalScheme(new URI(tabUrl));
    } catch (URISyntaxException e) {
        // Ignore as this only is for applying color
    }

    OmniboxUrlEmphasizer.emphasizeUrl(url, getResources(), currentTab.getProfile(),
            currentTab.getSecurityLevel(), isInternalPage,
            mUseDarkColors, mUrlBarDelegate.shouldEmphasizeHttpsScheme());
}