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

The following examples show how to use org.chromium.chrome.browser.util.UrlUtilities. 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: HelpAndFeedback.java    From delion with 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 File: CustomTabActivity.java    From delion with 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 #3
Source File: BookmarkEditActivity.java    From delion with 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 #4
Source File: GeolocationHeader.java    From delion with 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 File: RoundedIconGenerator.java    From delion with 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 File: HelpAndFeedback.java    From AndroidChromium with 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 File: CustomTabActivity.java    From AndroidChromium with 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 File: GeolocationHeader.java    From AndroidChromium with 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 File: RoundedIconGenerator.java    From AndroidChromium with 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 File: HelpAndFeedback.java    From 365browser with 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 File: UrlBar.java    From 365browser with 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 File: GeolocationHeader.java    From 365browser with 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 File: RoundedIconGenerator.java    From 365browser with 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 File: TabContextMenuItemDelegate.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onAddToContacts(String url) {
    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    if (MailTo.isMailTo(url)) {
        intent.putExtra(
                ContactsContract.Intents.Insert.EMAIL, MailTo.parse(url).getTo().split(",")[0]);
    } else if (UrlUtilities.isTelScheme(url)) {
        intent.putExtra(ContactsContract.Intents.Insert.PHONE, UrlUtilities.getTelNumber(url));
    }
    IntentUtils.safeStartActivity(mTab.getActivity(), intent);
}
 
Example #15
Source File: ExternalNavigationDelegateImpl.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSerpReferrer(String referrerUrl, Tab tab) {
    if (tab == null || tab.getWebContents() == null) {
        return false;
    }

    NavigationController nController = tab.getWebContents().getNavigationController();
    int index = nController.getLastCommittedEntryIndex();
    if (index == -1) return false;

    NavigationEntry entry = nController.getEntryAtIndex(index);
    if (entry == null) return false;

    return UrlUtilities.nativeIsGoogleSearchUrl(entry.getUrl());
}
 
Example #16
Source File: CustomTabsConnection.java    From 365browser with 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.speculationMode == SpeculationParams.PREFETCH) {
        cancelSpeculation(session);
        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 {
        cancelSpeculation(session);
    }
    if (!mClientManager.usesDefaultSessionParameters(session) && webContents != null) {
        RecordHistogram.recordBooleanHistogram(
                "CustomTabs.NonDefaultSessionPrerenderMatched", result != null);
    }

    return result;
}
 
Example #17
Source File: NewTabPageUma.java    From 365browser with 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 #18
Source File: ChromeLauncherActivity.java    From 365browser with 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 open explicitly opted out intents in custom tabs.
    if (CustomTabsIntent.shouldAlwaysUseBrowserUI(intent)) {
        return false;
    }

    // Don't reroute Chrome Intents.
    Context context = ContextUtils.getApplicationContext();
    if (TextUtils.equals(context.getPackageName(),
            IntentUtils.safeGetStringExtra(intent, Browser.EXTRA_APPLICATION_ID))
            || IntentHandler.wasIntentSenderChrome(intent)) {
        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;
    }

    // Don't reroute Home screen shortcuts.
    if (IntentUtils.safeHasExtra(intent, ShortcutHelper.EXTRA_SOURCE)) {
        return false;
    }

    return true;
}
 
Example #19
Source File: ExternalNavigationHandler.java    From 365browser with 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) {
    if (DEBUG) Log.i(TAG, "shouldOverrideUrlLoading called on " + params.getUrl());
    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 #20
Source File: ExternalNavigationDelegateImpl.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSerpReferrer(Tab tab) {
    // TODO (thildebr): Investigate whether or not we can use getLastCommittedUrl() instead of
    // the NavigationController.
    if (tab == null || tab.getWebContents() == null) return false;

    NavigationController nController = tab.getWebContents().getNavigationController();
    int index = nController.getLastCommittedEntryIndex();
    if (index == -1) return false;

    NavigationEntry entry = nController.getEntryAtIndex(index);
    if (entry == null) return false;

    return UrlUtilities.nativeIsGoogleSearchUrl(entry.getUrl());
}
 
Example #21
Source File: PaymentRequestImpl.java    From delion with 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 #22
Source File: TabContextMenuItemDelegate.java    From 365browser with 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);
                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 #23
Source File: ClientManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @return the prediction outcome. NO_PREDICTION if mSessionParams.get(session) returns null.
 */
@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 #24
Source File: ActivityTabTaskDescriptionHelper.java    From 365browser with 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 #25
Source File: ActivityTabTaskDescriptionHelper.java    From delion with 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 #26
Source File: ClientManager.java    From delion with 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 #27
Source File: ExternalNavigationHandler.java    From AndroidChromium with 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 #28
Source File: ChromeLauncherActivity.java    From AndroidChromium with 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 open explicitly opted out intents in custom tabs.
    if (CustomTabsIntent.shouldAlwaysUseBrowserUI(intent)) {
        return false;
    }

    // Don't reroute Chrome Intents.
    Context context = ContextUtils.getApplicationContext();
    if (TextUtils.equals(context.getPackageName(),
            IntentUtils.safeGetStringExtra(intent, Browser.EXTRA_APPLICATION_ID))
            || IntentHandler.wasIntentSenderChrome(intent, context)) {
        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;
    }

    // Don't reroute Home screen shortcuts.
    if (IntentUtils.safeHasExtra(intent, ShortcutHelper.EXTRA_SOURCE)) {
        return false;
    }

    return true;
}
 
Example #29
Source File: WebappDelegateFactory.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the browser 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 browser controls should be shown for {@link url}.
 */
public static boolean shouldShowBrowserControls(
        String webappStartUrl, String url, int securityLevel) {
    // Do not show browser 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.DANGEROUS
            || securityLevel == ConnectionSecurityLevel.SECURITY_WARNING;
    return visible;
}
 
Example #30
Source File: CustomTabDelegateFactory.java    From 365browser with 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(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;
    }
}