Java Code Examples for org.chromium.chrome.browser.tab.Tab#getUrl()

The following examples show how to use org.chromium.chrome.browser.tab.Tab#getUrl() . 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: LayoutManagerDocument.java    From delion with Apache License 2.0 6 votes vote down vote up
@Override
public void initLayoutTabFromHost(final int tabId) {
    if (getTabModelSelector() == null || getActiveLayout() == null) return;

    TabModelSelector selector = getTabModelSelector();
    Tab tab = selector.getTabById(tabId);
    if (tab == null) return;

    LayoutTab layoutTab = mTabCache.get(tabId);
    if (layoutTab == null) return;

    String url = tab.getUrl();
    boolean isNativePage = url != null && url.startsWith(UrlConstants.CHROME_NATIVE_SCHEME);
    int themeColor = tab.getThemeColor();
    boolean canUseLiveTexture =
            tab.getContentViewCore() != null && !tab.isShowingSadTab() && !isNativePage;
    layoutTab.initFromHost(tab.getBackgroundColor(), tab.shouldStall(), canUseLiveTexture,
            themeColor, ColorUtils.getTextBoxColorForToolbarBackground(
                                mContext.getResources(), tab, themeColor),
            ColorUtils.getTextBoxAlphaForToolbarBackground(tab));

    mHost.requestRender();
}
 
Example 2
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 3
Source File: CastNotificationControl.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private String getCurrentTabOrigin() {
    Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();

    if (!(activity instanceof ChromeTabbedActivity)) return null;

    Tab tab = ((ChromeTabbedActivity) activity).getActivityTab();
    if (tab == null || !tab.isInitialized()) return null;

    String url = tab.getUrl();
    try {
        return UrlFormatter.formatUrlForSecurityDisplay(new URI(url), true);
    } catch (URISyntaxException | UnsatisfiedLinkError e) {
        // UnstatisfiedLinkError can only happen in tests as the natives are not initialized
        // yet.
        Log.e(TAG, "Unable to parse the origin from the URL. Using the full URL instead.");
        return url;
    }
}
 
Example 4
Source File: TabPrinter.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public String getTitle() {
    Tab tab = mTab.get();
    if (tab == null) return mDefaultTitle;

    String title = tab.getTitle();
    if (!TextUtils.isEmpty(title)) return title;

    String url = tab.getUrl();
    if (!TextUtils.isEmpty(url)) return url;

    return mDefaultTitle;
}
 
Example 5
Source File: ReaderModeManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onContentChanged(Tab tab) {
    // Only listen to events on the currently active tab.
    if (tab.getId() != mTabId) return;
    closeReaderPanel(StateChangeReason.UNKNOWN, false);

    if (mTabStatusMap.containsKey(mTabId)) {
        // If the panel was closed using the "x" icon, don't show it again for this tab.
        if (mTabStatusMap.get(mTabId).isDismissed()) return;
        removeTabState(mTabId);
    }

    ReaderModeTabInfo tabInfo = new ReaderModeTabInfo();
    tabInfo.setStatus(NOT_POSSIBLE);
    tabInfo.setUrl(tab.getUrl());
    mTabStatusMap.put(tab.getId(), tabInfo);

    if (tab.getWebContents() != null) {
        tabInfo.setWebContentsObserver(createWebContentsObserver(tab.getWebContents()));
        if (DomDistillerUrlUtils.isDistilledPage(tab.getUrl())) {
            tabInfo.setStatus(STARTED);
            mReaderModePageUrl = tab.getUrl();
            closeReaderPanel(StateChangeReason.CONTENT_CHANGED, true);
        }
        // Make sure there is a distillability delegate set on the WebContents.
        setDistillabilityCallback(tab.getId());
    }

    if (tab.getInfoBarContainer() != null) tab.getInfoBarContainer().addObserver(this);
}
 
Example 6
Source File: OfflinePageUtils.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Share an offline copy of the current page.
 * @param shareDirectly Whether it should share directly with the activity that was most
 *                      recently used to share.
 * @param saveLastUsed Whether to save the chosen activity for future direct sharing.
 * @param mainActivity Activity that is used to access package manager.
 * @param text Text to be shared. If both |text| and |url| are supplied, they are concatenated
 *             with a space.
 * @param screenshotUri Screenshot of the page to be shared.
 * @param callback Optional callback to be called when user makes a choice. Will not be called
 *                 if receiving a response when the user makes a choice is not supported (see
 *                 TargetChosenReceiver#isSupported()).
 * @param currentTab The current tab for which sharing is being done.
 */
public static void shareOfflinePage(final boolean shareDirectly, final boolean saveLastUsed,
        final Activity mainActivity, final String text, final Uri screenshotUri,
        final ShareHelper.TargetChosenCallback callback, final Tab currentTab) {
    final String url = currentTab.getUrl();
    final String title = currentTab.getTitle();
    final OfflinePageBridge offlinePageBridge =
            OfflinePageBridge.getForProfile(currentTab.getProfile());

    if (offlinePageBridge == null) {
        Log.e(TAG, "Unable to perform sharing on current tab.");
        return;
    }

    OfflinePageItem offlinePage = currentTab.getOfflinePage();
    if (offlinePage != null) {
        // If we're currently on offline page get the saved file directly.
        prepareFileAndShare(shareDirectly, saveLastUsed, mainActivity, title, text,
                            url, screenshotUri, callback, offlinePage.getFilePath());
        return;
    }

    // If this is an online page, share the offline copy of it.
    Callback<OfflinePageItem> prepareForSharing = onGotOfflinePageItemToShare(shareDirectly,
            saveLastUsed, mainActivity, title, text, url, screenshotUri, callback);
    offlinePageBridge.selectPageForOnlineUrl(url, currentTab.getId(),
            selectPageForOnlineUrlCallback(currentTab.getWebContents(), offlinePageBridge,
                    prepareForSharing));
}
 
Example 7
Source File: ReaderModeManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void onContentChanged(Tab tab) {
    // Only listen to events on the currently active tab.
    if (tab.getId() != mTabId) return;
    closeReaderPanel(StateChangeReason.UNKNOWN, false);

    if (mTabStatusMap.containsKey(mTabId)) {
        // If the panel was closed using the "x" icon, don't show it again for this tab.
        if (mTabStatusMap.get(mTabId).isDismissed()) return;
        removeTabState(mTabId);
    }

    ReaderModeTabInfo tabInfo = new ReaderModeTabInfo();
    tabInfo.setStatus(NOT_POSSIBLE);
    tabInfo.setUrl(tab.getUrl());
    mTabStatusMap.put(tab.getId(), tabInfo);

    if (tab.getWebContents() != null) {
        tabInfo.setWebContentsObserver(createWebContentsObserver(tab.getWebContents()));
        if (DomDistillerUrlUtils.isDistilledPage(tab.getUrl())) {
            tabInfo.setStatus(STARTED);
            mReaderModePageUrl = tab.getUrl();
            closeReaderPanel(StateChangeReason.CONTENT_CHANGED, true);
        }
        // Make sure there is a distillability delegate set on the WebContents.
        setDistillabilityCallback(tab.getId());
    }

    if (tab.getInfoBarContainer() != null) tab.getInfoBarContainer().addObserver(this);
}
 
Example 8
Source File: LayerTitleCache.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Comes up with a valid title to return for a tab.
 * @param tab The {@link Tab} to build a title for.
 * @return    The title to use.
 */
private String getTitleForTab(Tab tab, String defaultTitle) {
    String title = tab.getTitle();
    if (TextUtils.isEmpty(title)) {
        title = tab.getUrl();
        if (TextUtils.isEmpty(title)) {
            title = defaultTitle;
            if (TextUtils.isEmpty(title)) {
                title = "";
            }
        }
    }
    return title;
}
 
Example 9
Source File: OfflinePageUtils.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Share an offline copy of the current page.
 * @param shareDirectly Whether it should share directly with the activity that was most
 *                      recently used to share.
 * @param saveLastUsed Whether to save the chosen activity for future direct sharing.
 * @param mainActivity Activity that is used to access package manager.
 * @param text Text to be shared. If both |text| and |url| are supplied, they are concatenated
 *             with a space.
 * @param screenshotUri Screenshot of the page to be shared.
 * @param callback Optional callback to be called when user makes a choice. Will not be called
 *                 if receiving a response when the user makes a choice is not supported (see
 *                 TargetChosenReceiver#isSupported()).
 * @param currentTab The current tab for which sharing is being done.
 */
public static void shareOfflinePage(final boolean shareDirectly, final boolean saveLastUsed,
        final Activity mainActivity, final String text, final Uri screenshotUri,
        final ShareHelper.TargetChosenCallback callback, final Tab currentTab) {
    final String url = currentTab.getUrl();
    final String title = currentTab.getTitle();
    final OfflinePageBridge offlinePageBridge =
            OfflinePageBridge.getForProfile(currentTab.getProfile());

    if (offlinePageBridge == null) {
        Log.e(TAG, "Unable to perform sharing on current tab.");
        return;
    }

    OfflinePageItem offlinePage = offlinePageBridge.getOfflinePage(currentTab.getWebContents());
    if (offlinePage != null) {
        // If we're currently on offline page get the saved file directly.
        prepareFileAndShare(shareDirectly, saveLastUsed, mainActivity, title, text,
                            url, screenshotUri, callback, offlinePage.getFilePath());
        return;
    }

    // If this is an online page, share the offline copy of it.
    Callback<OfflinePageItem> prepareForSharing = onGotOfflinePageItemToShare(shareDirectly,
            saveLastUsed, mainActivity, title, text, url, screenshotUri, callback);
    offlinePageBridge.selectPageForOnlineUrl(url, currentTab.getId(),
            selectPageForOnlineUrlCallback(currentTab.getWebContents(), offlinePageBridge,
                    prepareForSharing));
}
 
Example 10
Source File: ChromeActivity.java    From delion with Apache License 2.0 5 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.
 */
public void onShareMenuItemSelected(final boolean shareDirectly, boolean isIncognito) {
    final Tab currentTab = getActivityTab();
    if (currentTab == null) return;

    final Activity mainActivity = this;
    ContentBitmapCallback callback = new ContentBitmapCallback() {
                @Override
                public void onFinishGetBitmap(Bitmap bitmap, int response) {
                    // Check whether this page is an offline page, and use its online URL if so.
                    String url = currentTab.getOfflinePageOriginalUrl();
                    RecordHistogram.recordBooleanHistogram(
                            "OfflinePages.SharedPageWasOffline", url != null);

                    // If there is no entry in the offline pages DB for this tab, use the tab's
                    // URL directly.
                    if (url == null) url = currentTab.getUrl();

                    ShareHelper.share(
                            shareDirectly, mainActivity, currentTab.getTitle(), url, bitmap);
                    if (shareDirectly) {
                        RecordUserAction.record("MobileMenuDirectShare");
                    } else {
                        RecordUserAction.record("MobileMenuShare");
                    }
                }
            };
    if (isIncognito || currentTab.getWebContents() == null) {
        callback.onFinishGetBitmap(null, ReadbackResponse.SURFACE_UNAVAILABLE);
    } else {
        currentTab.getWebContents().getContentBitmapAsync(
                Bitmap.Config.ARGB_8888, 1.f, EMPTY_RECT, callback);
    }
}
 
Example 11
Source File: AppMenuPropertiesDelegate.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the request desktop site item's visibility
 *
 * @param requstMenuItem {@link MenuItem} for request desktop site.
 * @param currentTab      Current tab being displayed.
 */
protected void updateRequestDesktopSiteMenuItem(
        MenuItem requstMenuItem, Tab currentTab) {
    String url = currentTab.getUrl();
    boolean isChromeScheme = url.startsWith(UrlConstants.CHROME_URL_PREFIX)
            || url.startsWith(UrlConstants.CHROME_NATIVE_URL_PREFIX);
    requstMenuItem.setVisible(!isChromeScheme || currentTab.isNativePage());
    requstMenuItem.setChecked(currentTab.getUseDesktopUserAgent());
    requstMenuItem.setTitleCondensed(requstMenuItem.isChecked()
            ? mActivity.getString(R.string.menu_request_desktop_site_on)
            : mActivity.getString(R.string.menu_request_desktop_site_off));
}
 
Example 12
Source File: LayerTitleCache.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Comes up with a valid title to return for a tab.
 * @param tab The {@link Tab} to build a title for.
 * @return    The title to use.
 */
private String getTitleForTab(Tab tab, String defaultTitle) {
    String title = tab.getTitle();
    if (TextUtils.isEmpty(title)) {
        title = tab.getUrl();
        if (TextUtils.isEmpty(title)) {
            title = defaultTitle;
            if (TextUtils.isEmpty(title)) {
                title = "";
            }
        }
    }
    return title;
}
 
Example 13
Source File: CustomTabAppMenuPropertiesDelegate.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public void prepareMenu(Menu menu) {
    Tab currentTab = mActivity.getActivityTab();
    if (currentTab != null) {
        MenuItem forwardMenuItem = menu.findItem(R.id.forward_menu_id);
        forwardMenuItem.setEnabled(currentTab.canGoForward());

        mReloadMenuItem = menu.findItem(R.id.reload_menu_id);
        mReloadMenuItem.setIcon(R.drawable.btn_reload_stop);
        loadingStateChanged(currentTab.isLoading());

        MenuItem shareItem = menu.findItem(R.id.share_row_menu_id);
        shareItem.setVisible(mShowShare);
        shareItem.setEnabled(mShowShare);
        if (mShowShare) {
            ShareHelper.configureDirectShareMenuItem(
                    mActivity, menu.findItem(R.id.direct_share_menu_id));
        }

        MenuItem iconRow = menu.findItem(R.id.icon_row_menu_id);
        MenuItem openInChromeItem = menu.findItem(R.id.open_in_browser_id);
        MenuItem bookmarkItem = menu.findItem(R.id.bookmark_this_page_id);
        MenuItem downloadItem = menu.findItem(R.id.offline_page_id);

        boolean addToHomeScreenVisible = true;

        // Hide request desktop site on all chrome:// pages except for the NTP. Check request
        // desktop site if it's activated on this page.
        MenuItem requestItem = menu.findItem(R.id.request_desktop_site_id);
        updateRequestDesktopSiteMenuItem(requestItem, currentTab);

        if (mIsMediaViewer) {
            // Most of the menu items don't make sense when viewing media.
            iconRow.setVisible(false);
            openInChromeItem.setVisible(false);
            menu.findItem(R.id.find_in_page_id).setVisible(false);
            menu.findItem(R.id.request_desktop_site_id).setVisible(false);
            addToHomeScreenVisible = false;
        } else {
            openInChromeItem.setTitle(
                    DefaultBrowserInfo.getTitleOpenInDefaultBrowser(mIsOpenedByChrome));
            updateBookmarkMenuItem(bookmarkItem, currentTab);
        }
        bookmarkItem.setVisible(mShowStar);
        downloadItem.setVisible(mShowDownload);
        if (!FirstRunStatus.getFirstRunFlowComplete()) {
            openInChromeItem.setVisible(false);
            bookmarkItem.setVisible(false);
            downloadItem.setVisible(false);
            addToHomeScreenVisible = false;
        }

        downloadItem.setEnabled(DownloadUtils.isAllowedToDownloadPage(currentTab));

        String url = currentTab.getUrl();
        boolean isChromeScheme = url.startsWith(UrlConstants.CHROME_URL_PREFIX)
                || url.startsWith(UrlConstants.CHROME_NATIVE_URL_PREFIX);
        if (isChromeScheme) {
            addToHomeScreenVisible = false;
        }

        // Add custom menu items. Make sure they are only added once.
        if (!mIsCustomEntryAdded) {
            mIsCustomEntryAdded = true;
            for (int i = 0; i < mMenuEntries.size(); i++) {
                MenuItem item = menu.add(0, 0, 1, mMenuEntries.get(i));
                mItemToIndexMap.put(item, i);
            }
        }

        prepareAddToHomescreenMenuItem(menu, currentTab, addToHomeScreenVisible);
    }
}
 
Example 14
Source File: CustomTabActivity.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Opens the URL currently being displayed in the Custom Tab in the regular browser.
 * @param forceReparenting Whether tab reparenting should be forced for testing.
 * @param stayInChrome     Whether the user stays in Chrome after the tab is reparented.
 * @return Whether or not the tab was sent over successfully.
 */
boolean openCurrentUrlInBrowser(boolean forceReparenting, boolean stayInChrome) {
    Tab tab = getActivityTab();
    if (tab == null) return false;

    String url = tab.getUrl();
    if (DomDistillerUrlUtils.isDistilledPage(url)) {
        url = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url);
    }
    if (TextUtils.isEmpty(url)) url = getUrlToLoad();
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, false);
    if (ChromeFeatureList.isEnabled("ReadItLaterInMenu")) {
        // In this trial both "open in chrome" and "read it later" should target Chrome.
        intent.setPackage(getPackageName());
    }

    boolean willChromeHandleIntent = getIntentDataProvider().isOpenedByChrome();
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        willChromeHandleIntent |= ExternalNavigationDelegateImpl
                .willChromeHandleIntent(this, intent, true);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    Bundle startActivityOptions = ActivityOptionsCompat.makeCustomAnimation(
            this, R.anim.abc_fade_in, R.anim.abc_fade_out).toBundle();
    if (willChromeHandleIntent || forceReparenting) {
        Runnable finalizeCallback = new Runnable() {
            @Override
            public void run() {
                finishAndClose();
            }
        };

        mMainTab = null;
        tab.detachAndStartReparenting(intent, startActivityOptions, finalizeCallback,
                stayInChrome);
    } else {
        // Temporarily allowing disk access while fixing. TODO: http://crbug.com/581860
        StrictMode.allowThreadDiskReads();
        StrictMode.allowThreadDiskWrites();
        try {
            startActivity(intent, startActivityOptions);
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
    return true;
}
 
Example 15
Source File: TabPersistentStore.java    From delion with Apache License 2.0 4 votes vote down vote up
private boolean isTabUrlContentScheme(Tab tab) {
    String url = tab.getUrl();
    return url != null && url.startsWith("content");
}
 
Example 16
Source File: CustomTabActivity.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Opens the URL currently being displayed in the Custom Tab in the regular browser.
 * @param forceReparenting Whether tab reparenting should be forced for testing.
 *
 * @return Whether or not the tab was sent over successfully.
 */
boolean openCurrentUrlInBrowser(boolean forceReparenting) {
    Tab tab = getActivityTab();
    if (tab == null) return false;

    String url = tab.getUrl();
    if (DomDistillerUrlUtils.isDistilledPage(url)) {
        url = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url);
    }
    if (TextUtils.isEmpty(url)) url = getUrlToLoad();
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, false);

    boolean willChromeHandleIntent = getIntentDataProvider().isOpenedByChrome();
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        willChromeHandleIntent |= ExternalNavigationDelegateImpl
                .willChromeHandleIntent(intent, true);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    Bundle startActivityOptions = ActivityOptionsCompat.makeCustomAnimation(
            this, R.anim.abc_fade_in, R.anim.abc_fade_out).toBundle();
    if (willChromeHandleIntent || forceReparenting) {
        Runnable finalizeCallback = new Runnable() {
            @Override
            public void run() {
                finishAndClose(true);
            }
        };

        mMainTab = null;
        // mHasCreatedTabEarly == true => mMainTab != null in the rest of the code.
        mHasCreatedTabEarly = false;
        CustomTabsConnection.getInstance(getApplication()).resetPostMessageHandlerForSession(
                mSession, null);
        tab.detachAndStartReparenting(intent, startActivityOptions, finalizeCallback);
    } else {
        // Temporarily allowing disk access while fixing. TODO: http://crbug.com/581860
        StrictMode.allowThreadDiskWrites();
        try {
            if (mIntentDataProvider.isInfoPage()) {
                IntentHandler.startChromeLauncherActivityForTrustedIntent(intent);
            } else {
                startActivity(intent, startActivityOptions);
            }
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
    return true;
}
 
Example 17
Source File: TabPersistentStore.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private boolean isTabUrlContentScheme(Tab tab) {
    String url = tab.getUrl();
    return url != null && url.startsWith("content");
}
 
Example 18
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Opens the URL currently being displayed in the Custom Tab in the regular browser.
 * @param forceReparenting Whether tab reparenting should be forced for testing.
 *
 * @return Whether or not the tab was sent over successfully.
 */
boolean openCurrentUrlInBrowser(boolean forceReparenting) {
    Tab tab = getActivityTab();
    if (tab == null) return false;

    String url = tab.getUrl();
    if (DomDistillerUrlUtils.isDistilledPage(url)) {
        url = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url);
    }
    if (TextUtils.isEmpty(url)) url = getUrlToLoad();
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, false);

    boolean willChromeHandleIntent = getIntentDataProvider().isOpenedByChrome();
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        willChromeHandleIntent |= ExternalNavigationDelegateImpl
                .willChromeHandleIntent(this, intent, true);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    Bundle startActivityOptions = ActivityOptionsCompat.makeCustomAnimation(
            this, R.anim.abc_fade_in, R.anim.abc_fade_out).toBundle();
    if (willChromeHandleIntent || forceReparenting) {
        Runnable finalizeCallback = new Runnable() {
            @Override
            public void run() {
                finishAndClose(true);
            }
        };

        mMainTab = null;
        tab.detachAndStartReparenting(intent, startActivityOptions, finalizeCallback);
    } else {
        // Temporarily allowing disk access while fixing. TODO: http://crbug.com/581860
        StrictMode.allowThreadDiskReads();
        StrictMode.allowThreadDiskWrites();
        try {
            startActivity(intent, startActivityOptions);
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
    return true;
}
 
Example 19
Source File: ContextReporter.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private void reportUsageOfCurrentContextIfPossible(
        Tab tab, boolean isTitleChange, @Nullable GSAContextDisplaySelection displaySelection) {
    Tab currentTab = mActivity.getActivityTab();
    if (currentTab == null || currentTab.isIncognito()) {
        if (currentTab == null) {
            reportStatus(STATUS_NO_TAB);
            Log.d(TAG, "Not reporting, tab is null");
        } else {
            reportStatus(STATUS_INCOGNITO);
            Log.d(TAG, "Not reporting, tab is incognito");
        }
        reportUsageEndedIfNecessary();
        return;
    }

    String currentUrl = currentTab.getUrl();
    if (TextUtils.isEmpty(currentUrl) || !(currentUrl.startsWith(UrlConstants.HTTP_SCHEME)
            || currentUrl.startsWith(UrlConstants.HTTPS_SCHEME))) {
        reportStatus(STATUS_INVALID_SCHEME);
        Log.d(TAG, "Not reporting, URL scheme is invalid");
        reportUsageEndedIfNecessary();
        return;
    }

    // Check whether this is a context change we would like to report.
    if (currentTab.getId() != tab.getId()) {
        reportStatus(STATUS_TAB_ID_MISMATCH);
        Log.d(TAG, "Not reporting, tab ID doesn't match");
        return;
    }
    if (isTitleChange && mLastContextWasTitleChange) {
        reportStatus(STATUS_DUP_TITLE_CHANGE);
        Log.d(TAG, "Not reporting, repeated title update");
        return;
    }

    reportUsageEndedIfNecessary();

    mDelegate.reportContext(currentTab.getUrl(), currentTab.getTitle(), displaySelection);
    mLastContextWasTitleChange = isTitleChange;
    mContextInUse.set(true);
}
 
Example 20
Source File: AppIndexingUtil.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts entities from document metadata and reports it to on-device App Indexing.
 * This call can cache entities from recently parsed webpages, in which case, only the url and
 * title of the page is reported to App Indexing.
 */
public void extractCopylessPasteMetadata(final Tab tab) {
    final String url = tab.getUrl();
    boolean isHttpOrHttps = URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url);
    if (!isEnabledForDevice() || tab.isIncognito() || !isHttpOrHttps) {
        return;
    }

    // There are three conditions that can occur with respect to the cache.
    // 1. Cache hit, and an entity was found previously. Report only the page view to App
    //    Indexing.
    // 2. Cache hit, but no entity was found. Ignore.
    // 3. Cache miss, we need to parse the page.
    if (wasPageVisitedRecently(url)) {
        if (lastPageVisitContainedEntity(url)) {
            // Condition 1
            RecordHistogram.recordEnumeratedHistogram(
                    "CopylessPaste.CacheHit", CACHE_HIT_WITH_ENTITY, CACHE_HISTOGRAM_BOUNDARY);
            getAppIndexingReporter().reportWebPageView(url, tab.getTitle());
            return;
        }
        // Condition 2
        RecordHistogram.recordEnumeratedHistogram(
                "CopylessPaste.CacheHit", CACHE_HIT_WITHOUT_ENTITY, CACHE_HISTOGRAM_BOUNDARY);
    } else {
        // Condition 3
        RecordHistogram.recordEnumeratedHistogram(
                "CopylessPaste.CacheHit", CACHE_MISS, CACHE_HISTOGRAM_BOUNDARY);
        CopylessPaste copylessPaste = getCopylessPasteInterface(tab);
        if (copylessPaste == null) {
            return;
        }
        copylessPaste.getEntities(new CopylessPaste.GetEntitiesResponse() {
            @Override
            public void call(WebPage webpage) {
                putCacheEntry(url, webpage != null);
                if (sCallbackForTesting != null) {
                    sCallbackForTesting.onResult(webpage);
                }
                if (webpage == null) return;
                getAppIndexingReporter().reportWebPage(webpage);
            }
        });
    }
}