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

The following examples show how to use org.chromium.chrome.browser.tab.Tab#getWebContents() . 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: UmaSessionStats.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
private void recordPageLoadStats(Tab tab) {
    WebContents webContents = tab.getWebContents();
    boolean isDesktopUserAgent = webContents != null
            && webContents.getNavigationController().getUseDesktopUserAgent();
    nativeRecordPageLoaded(isDesktopUserAgent);
    if (mKeyboardConnected) {
        nativeRecordPageLoadedWithKeyboard();
    }

    // If the session has ended (i.e. chrome is in the background), escape early. Ideally we
    // could track this number as part of either the previous or next session but this isn't
    // possible since the TabSelector is needed to figure out the current number of open tabs.
    if (mTabModelSelector == null) return;

    TabModel regularModel = mTabModelSelector.getModel(false);
    nativeRecordTabCountPerLoad(getTabCountFromModel(regularModel));
}
 
Example 2
Source File: OfflinePageUtils.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
public static void saveBookmarkOffline(BookmarkId bookmarkId, Tab tab) {
    // If bookmark ID is missing there is nothing to save here.
    if (bookmarkId == null) return;

    // Making sure the feature is enabled.
    if (!OfflinePageBridge.isOfflineBookmarksEnabled()) return;

    // Making sure tab is worth keeping.
    if (shouldSkipSavingTabOffline(tab)) return;

    OfflinePageBridge offlinePageBridge = getInstance().getOfflinePageBridge(tab.getProfile());
    if (offlinePageBridge == null) return;

    WebContents webContents = tab.getWebContents();
    ClientId clientId = ClientId.createClientIdForBookmarkId(bookmarkId);

    // TODO(fgorski): Ensure that request is queued if the model is not loaded.
    offlinePageBridge.savePage(webContents, clientId, new OfflinePageBridge.SavePageCallback() {
        @Override
        public void onSavePageDone(int savePageResult, String url, long offlineId) {
            // TODO(fgorski): Decide if we need to do anything with result.
            // Perhaps some UMA reporting, but that can really happen someplace else.
        }
    });
}
 
Example 3
Source File: UmaSessionStats.java    From delion with Apache License 2.0 6 votes vote down vote up
private void recordPageLoadStats(Tab tab) {
    WebContents webContents = tab.getWebContents();
    boolean isDesktopUserAgent = webContents != null
            && webContents.getNavigationController().getUseDesktopUserAgent();
    nativeRecordPageLoaded(isDesktopUserAgent);
    if (mKeyboardConnected) {
        nativeRecordPageLoadedWithKeyboard();
    }

    // If the session has ended (i.e. chrome is in the background), escape early. Ideally we
    // could track this number as part of either the previous or next session but this isn't
    // possible since the TabSelector is needed to figure out the current number of open tabs.
    if (mTabModelSelector == null) return;

    TabModel regularModel = mTabModelSelector.getModel(false);
    nativeRecordTabCountPerLoad(getTabCountFromModel(regularModel));
}
 
Example 4
Source File: LocationBarLayout.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private void loadUrlFromOmniboxMatch(String url, int transition, int matchPosition, int type) {
    // loadUrl modifies AutocompleteController's state clearing the native
    // AutocompleteResults needed by onSuggestionsSelected. Therefore,
    // loadUrl should should be invoked last.
    Tab currentTab = getCurrentTab();
    String currentPageUrl = getCurrentTabUrl();
    WebContents webContents = currentTab != null ? currentTab.getWebContents() : null;
    long elapsedTimeSinceModified = mNewOmniboxEditSessionTimestamp > 0
            ? (SystemClock.elapsedRealtime() - mNewOmniboxEditSessionTimestamp) : -1;
    boolean shouldSkipNativeLog = mShowCachedZeroSuggestResults
            && (mDeferredOnSelection != null)
            && !mDeferredOnSelection.shouldLog();
    if (!shouldSkipNativeLog) {
        mAutocomplete.onSuggestionSelected(matchPosition, type, currentPageUrl,
                mUrlFocusedFromFakebox, elapsedTimeSinceModified,
                mUrlBar.getAutocompleteLength(),
                webContents);
    }
    loadUrl(url, transition);
}
 
Example 5
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 6
Source File: ToolbarTablet.java    From 365browser with Apache License 2.0 5 votes vote down vote up
private void displayNavigationPopup(boolean isForward, View anchorView) {
    Tab tab = getToolbarDataProvider().getTab();
    if (tab == null || tab.getWebContents() == null) return;
    mNavigationPopup = new NavigationPopup(tab.getProfile(), getContext(),
            tab.getWebContents().getNavigationController(), isForward);

    mNavigationPopup.setAnchorView(anchorView);

    int menuWidth = getResources().getDimensionPixelSize(R.dimen.menu_width);
    mNavigationPopup.setWidth(menuWidth);

    if (mNavigationPopup.shouldBeShown()) mNavigationPopup.show();
}
 
Example 7
Source File: OfflinePageUtils.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isOfflinePage(Tab tab) {
    WebContents webContents = tab.getWebContents();
    if (webContents == null) return false;
    OfflinePageBridge offlinePageBridge =
            getInstance().getOfflinePageBridge(tab.getProfile());
    if (offlinePageBridge == null) return false;
    return offlinePageBridge.isOfflinePage(webContents);
}
 
Example 8
Source File: ChromeActivity.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * @see Activity#onContextMenuClosed(Menu)
 */
@Override
public void onContextMenuClosed(Menu menu) {
    final Tab currentTab = getActivityTab();
    if (currentTab == null) return;
    WebContents webContents = currentTab.getWebContents();
    if (webContents == null) return;
    webContents.onContextMenuClosed();
}
 
Example 9
Source File: LocationBarLayout.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(View v) {
    if (v == mDeleteButton) {
        if (!TextUtils.isEmpty(mUrlBar.getQueryText())) {
            setUrlBarText("", null);
            hideSuggestions();
            updateButtonVisibility();
        }

        startZeroSuggest();
        return;
    } else if (!mUrlHasFocus && shouldShowPageInfoForView(v)) {
        Tab currentTab = getCurrentTab();
        if (currentTab != null && currentTab.getWebContents() != null) {
            Activity activity = currentTab.getWindowAndroid().getActivity().get();
            if (activity != null) {
                WebsiteSettingsPopup.show(
                        activity, currentTab, null, WebsiteSettingsPopup.OPENED_FROM_TOOLBAR);
            }
        }
    } else if (v == mMicButton) {
        RecordUserAction.record("MobileOmniboxVoiceSearch");
        startVoiceRecognition();
    } else if (v == mOmniboxResultsContainer) {
        // This will only be triggered when no suggestion items are selected in the container.
        setUrlBarFocus(false);
        updateOmniboxResultsContainerBackground(false);
    }
}
 
Example 10
Source File: LocationBarLayout.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void loadUrlFromOmniboxMatch(String url, int transition, int matchPosition, int type) {
    // loadUrl modifies AutocompleteController's state clearing the native
    // AutocompleteResults needed by onSuggestionsSelected. Therefore,
    // loadUrl should should be invoked last.
    Tab currentTab = getCurrentTab();
    String currentPageUrl = getCurrentTabUrl();
    WebContents webContents = currentTab != null ? currentTab.getWebContents() : null;
    long elapsedTimeSinceModified = mNewOmniboxEditSessionTimestamp > 0
            ? (SystemClock.elapsedRealtime() - mNewOmniboxEditSessionTimestamp) : -1;
    mAutocomplete.onSuggestionSelected(matchPosition, type, currentPageUrl,
            mUrlFocusedFromFakebox, elapsedTimeSinceModified, mUrlBar.getAutocompleteLength(),
            webContents);
    loadUrl(url, transition);
}
 
Example 11
Source File: ReaderModeManager.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public WebContents getBasePageWebContents() {
    Tab tab = mTabModelSelector.getCurrentTab();
    if (tab == null) return null;

    return tab.getWebContents();
}
 
Example 12
Source File: TabModelImpl.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public void cancelTabClosure(int tabId) {
    Tab tab = mRewoundList.getPendingRewindTab(tabId);
    if (tab == null) return;

    tab.setClosing(false);

    // Find a valid previous tab entry so we know what tab to insert after.  With the following
    // example, calling cancelTabClosure(4) would need to know to insert after 2.  So we have to
    // track across mRewoundTabs and mTabs and see what the last valid mTabs entry was (2) when
    // we hit the 4 in the rewound list.  An insertIndex of -1 represents the beginning of the
    // list, as this is the index of tab to insert after.
    // mTabs:       0   2     5
    // mRewoundTabs 0 1 2 3 4 5
    int prevIndex = -1;
    final int stopIndex = mRewoundList.indexOf(tab);
    for (int rewoundIndex = 0; rewoundIndex < stopIndex; rewoundIndex++) {
        Tab rewoundTab = mRewoundList.getTabAt(rewoundIndex);
        if (prevIndex == mTabs.size() - 1) break;
        if (rewoundTab == mTabs.get(prevIndex + 1)) prevIndex++;
    }

    // Figure out where to insert the tab.  Just add one to prevIndex, as -1 represents the
    // beginning of the list, so we'll insert at 0.
    int insertIndex = prevIndex + 1;
    if (mIndex >= insertIndex) mIndex++;
    mTabs.add(insertIndex, tab);

    WebContents webContents = tab.getWebContents();
    if (webContents != null) webContents.setAudioMuted(false);

    boolean activeModel = isCurrentModel();

    if (mIndex == INVALID_TAB_INDEX) {
        // If we're the active model call setIndex to actually select this tab, otherwise just
        // set mIndex but don't kick off everything that happens when calling setIndex().
        if (activeModel) {
            TabModelUtils.setIndex(this, insertIndex);
        } else {
            mIndex = insertIndex;
        }
    }

    // Re-save the tab list now that it is being kept.
    mTabSaver.saveTabListAsynchronously();

    for (TabModelObserver obs : mObservers) obs.tabClosureUndone(tab);
}
 
Example 13
Source File: ToolbarModelImpl.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public WebContents getActiveWebContents() {
    Tab tab = getTab();
    if (tab == null) return null;
    return tab.getWebContents();
}
 
Example 14
Source File: ChromeActivity.java    From 365browser with Apache License 2.0 4 votes vote down vote up
private void triggerShare(
        final Tab currentTab, final boolean shareDirectly, boolean isIncognito) {
    final Activity mainActivity = this;
    WebContents webContents = currentTab.getWebContents();

    RecordHistogram.recordBooleanHistogram(
            "OfflinePages.SharedPageWasOffline", OfflinePageUtils.isOfflinePage(currentTab));
    boolean canShareOfflinePage = OfflinePageBridge.isPageSharingEnabled();

    // Share an empty blockingUri in place of screenshot file. The file ready notification is
    // sent by onScreenshotReady call below when the file is written.
    final Uri blockingUri = (isIncognito || webContents == null)
            ? null
            : ChromeFileProvider.generateUriAndBlockAccess(mainActivity);
    if (canShareOfflinePage) {
        OfflinePageUtils.shareOfflinePage(shareDirectly, true, mainActivity, null,
                blockingUri, null, currentTab);
    } else {
        ShareHelper.share(shareDirectly, true, mainActivity, currentTab.getTitle(), null,
                currentTab.getUrl(), null, blockingUri, null);
        if (shareDirectly) {
            RecordUserAction.record("MobileMenuDirectShare");
        } else {
            RecordUserAction.record("MobileMenuShare");
        }
    }

    if (blockingUri == null) return;

    // Start screenshot capture and notify the provider when it is ready.
    ContentBitmapCallback callback = new ContentBitmapCallback() {
        @Override
        public void onFinishGetBitmap(Bitmap bitmap, int response) {
            ShareHelper.saveScreenshotToDisk(bitmap, mainActivity,
                    new Callback<Uri>() {
                        @Override
                        public void onResult(Uri result) {
                            // Unblock the file once it is saved to disk.
                            ChromeFileProvider.notifyFileReady(blockingUri, result);
                        }
                    });
        }
    };
    if (mScreenshotCaptureSkippedForTesting) {
        callback.onFinishGetBitmap(null, ReadbackResponse.SURFACE_UNAVAILABLE);
    } else {
        webContents.getContentBitmapAsync(0, 0, callback);
    }
}
 
Example 15
Source File: ToolbarModelImpl.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public WebContents getActiveWebContents() {
    Tab tab = getTab();
    if (tab == null) return null;
    return tab.getWebContents();
}
 
Example 16
Source File: ChromeActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private void triggerShare(
        final Tab currentTab, final boolean shareDirectly, boolean isIncognito) {
    final Activity mainActivity = this;
    WebContents webContents = currentTab.getWebContents();

    RecordHistogram.recordBooleanHistogram(
            "OfflinePages.SharedPageWasOffline", currentTab.isOfflinePage());
    boolean canShareOfflinePage = OfflinePageBridge.isPageSharingEnabled();

    // Share an empty blockingUri in place of screenshot file. The file ready notification is
    // sent by onScreenshotReady call below when the file is written.
    final Uri blockingUri = (isIncognito || webContents == null)
            ? null
            : ChromeFileProvider.generateUriAndBlockAccess(mainActivity);
    if (canShareOfflinePage) {
        OfflinePageUtils.shareOfflinePage(shareDirectly, true, mainActivity, null,
                blockingUri, null, currentTab);
    } else {
        ShareHelper.share(shareDirectly, true, mainActivity, currentTab.getTitle(), null,
                currentTab.getUrl(), null, blockingUri, null);
        if (shareDirectly) {
            RecordUserAction.record("MobileMenuDirectShare");
        } else {
            RecordUserAction.record("MobileMenuShare");
        }
    }

    if (blockingUri == null) return;

    // Start screenshot capture and notify the provider when it is ready.
    ContentBitmapCallback callback = new ContentBitmapCallback() {
        @Override
        public void onFinishGetBitmap(Bitmap bitmap, int response) {
            ShareHelper.saveScreenshotToDisk(bitmap, mainActivity,
                    new Callback<Uri>() {
                        @Override
                        public void onResult(Uri result) {
                            // Unblock the file once it is saved to disk.
                            ChromeFileProvider.notifyFileReady(blockingUri, result);
                        }
                    });
        }
    };
    if (!mScreenshotCaptureSkippedForTesting) {
        webContents.getContentBitmapAsync(Bitmap.Config.ARGB_8888, 1.f, EMPTY_RECT, callback);
    } else {
        callback.onFinishGetBitmap(null, ReadbackResponse.SURFACE_UNAVAILABLE);
    }
}
 
Example 17
Source File: ReaderModeManager.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Set the callback for updating reader mode status based on whether or not the page should
 * be viewed in reader mode.
 * @param tabId The ID of the tab having its callback set.
 */
private void setDistillabilityCallback(final int tabId) {
    if (tabId == Tab.INVALID_TAB_ID || mTabStatusMap.get(tabId).isCallbackSet()) {
        return;
    }

    if (mTabModelSelector == null) return;

    Tab currentTab = mTabModelSelector.getTabById(tabId);
    if (currentTab == null || currentTab.getWebContents() == null
            || currentTab.getContentViewCore() == null) {
        return;
    }

    DistillablePageUtils.setDelegate(currentTab.getWebContents(),
            new DistillablePageUtils.PageDistillableDelegate() {
                @Override
                public void onIsPageDistillableResult(boolean isDistillable, boolean isLast) {
                    if (mTabModelSelector == null) return;

                    ReaderModeTabInfo tabInfo = mTabStatusMap.get(tabId);
                    Tab readerTab = mTabModelSelector.getTabById(tabId);

                    // It is possible that the tab was destroyed before this callback happens.
                    // TODO(wychen/mdjones): Remove the callback when a Tab/WebContents is
                    // destroyed so that this never happens.
                    if (readerTab == null || tabInfo == null) return;

                    // Make sure the page didn't navigate while waiting for a response.
                    if (!readerTab.getUrl().equals(tabInfo.getUrl())) return;

                    if (isDistillable) {
                        tabInfo.setStatus(POSSIBLE);
                        // The user may have changed tabs.
                        if (tabId == mTabModelSelector.getCurrentTabId()) {
                            // TODO(mdjones): Add reason DISTILLER_STATE_CHANGE.
                            requestReaderPanelShow(StateChangeReason.UNKNOWN);
                        }
                    } else {
                        tabInfo.setStatus(NOT_POSSIBLE);
                    }
                    if (!mIsUmaRecorded && (tabInfo.getStatus() == POSSIBLE || isLast)) {
                        mIsUmaRecorded = true;
                        RecordHistogram.recordBooleanHistogram(
                                "DomDistiller.PageDistillable",
                                tabInfo.getStatus() == POSSIBLE);
                    }
                }
            });
    mTabStatusMap.get(tabId).setIsCallbackSet(true);
}
 
Example 18
Source File: OfflinePageUtils.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Indicates whether we should skip saving the given tab as an offline page.
 * A tab shouldn't be saved offline if it shows an error page or a sad tab page.
 */
private static boolean shouldSkipSavingTabOffline(Tab tab) {
    WebContents webContents = tab.getWebContents();
    return tab.isShowingErrorPage() || tab.isShowingSadTab() || webContents == null
            || webContents.isDestroyed() || webContents.isIncognito();
}
 
Example 19
Source File: OfflinePageUtils.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Indicates whether we should skip saving the given tab as an offline page.
 * A tab shouldn't be saved offline if it shows an error page or a sad tab page.
 */
private static boolean shouldSkipSavingTabOffline(Tab tab) {
    WebContents webContents = tab.getWebContents();
    return tab.isShowingErrorPage() || tab.isShowingSadTab() || webContents == null
            || webContents.isDestroyed() || webContents.isIncognito();
}
 
Example 20
Source File: ChromeActivity.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Handles menu item selection and keyboard shortcuts.
 *
 * @param id The ID of the selected menu item (defined in main_menu.xml) or
 *           keyboard shortcut (defined in values.xml).
 * @param fromMenu Whether this was triggered from the menu.
 * @return Whether the action was handled.
 */
public boolean onMenuOrKeyboardAction(int id, boolean fromMenu) {
    if (id == R.id.preferences_id) {
        PreferencesLauncher.launchSettingsPage(this, null);
        RecordUserAction.record("MobileMenuSettings");
    } else if (id == R.id.show_menu) {
        showAppMenuForKeyboardEvent();
    }

    if (id == R.id.update_menu_id) {
        UpdateMenuItemHelper.getInstance().onMenuItemClicked(this);
        return true;
    }

    // All the code below assumes currentTab is not null, so return early if it is null.
    final Tab currentTab = getActivityTab();
    if (currentTab == null) {
        return false;
    } else if (id == R.id.forward_menu_id) {
        if (currentTab.canGoForward()) {
            currentTab.goForward();
            RecordUserAction.record("MobileMenuForward");
            RecordUserAction.record("MobileTabClobbered");
        }
    } else if (id == R.id.bookmark_this_page_id) {
        addOrEditBookmark(currentTab);
        RecordUserAction.record("MobileMenuAddToBookmarks");
    } else if (id == R.id.offline_page_id) {
        DownloadUtils.downloadOfflinePage(this, currentTab);
        RecordUserAction.record("MobileMenuDownloadPage");
    } else if (id == R.id.reload_menu_id) {
        if (currentTab.isLoading()) {
            currentTab.stopLoading();
            RecordUserAction.record("MobileMenuStop");
        } else {
            currentTab.reload();
            RecordUserAction.record("MobileMenuReload");
        }
    } else if (id == R.id.info_menu_id) {
        WebsiteSettingsPopup.show(
                this, currentTab, null, WebsiteSettingsPopup.OPENED_FROM_MENU);
    } else if (id == R.id.open_history_menu_id) {
        currentTab.loadUrl(
                new LoadUrlParams(UrlConstants.HISTORY_URL, PageTransition.AUTO_TOPLEVEL));
        RecordUserAction.record("MobileMenuHistory");
        StartupMetrics.getInstance().recordOpenedHistory();
    } else if (id == R.id.share_menu_id || id == R.id.direct_share_menu_id) {
        onShareMenuItemSelected(id == R.id.direct_share_menu_id,
                getCurrentTabModel().isIncognito());
    } else if (id == R.id.print_id) {
        PrintingController printingController = PrintingControllerImpl.getInstance();
        if (printingController != null && !printingController.isBusy()
                && PrefServiceBridge.getInstance().isPrintingEnabled()) {
            printingController.startPrint(new TabPrinter(currentTab),
                    new PrintManagerDelegateImpl(this));
            RecordUserAction.record("MobileMenuPrint");
        }
    } else if (id == R.id.add_to_homescreen_id) {
        AddToHomescreenManager addToHomescreenManager =
                new AddToHomescreenManager(this, currentTab);
        addToHomescreenManager.start();
        RecordUserAction.record("MobileMenuAddToHomescreen");
    } else if (id == R.id.request_desktop_site_id) {
        final boolean reloadOnChange = !currentTab.isNativePage();
        final boolean usingDesktopUserAgent = currentTab.getUseDesktopUserAgent();
        currentTab.setUseDesktopUserAgent(!usingDesktopUserAgent, reloadOnChange);
        RecordUserAction.record("MobileMenuRequestDesktopSite");
    } else if (id == R.id.reader_mode_prefs_id) {
        if (currentTab.getWebContents() != null) {
            RecordUserAction.record("DomDistiller_DistilledPagePrefsOpened");
            AlertDialog.Builder builder =
                    new AlertDialog.Builder(this, R.style.AlertDialogTheme);
            builder.setView(DistilledPagePrefsView.create(this));
            builder.show();
        }
    } else if (id == R.id.help_id) {
        // Since reading back the compositor is asynchronous, we need to do the readback
        // before starting the GoogleHelp.
        String helpContextId = HelpAndFeedback.getHelpContextIdFromUrl(
                this, currentTab.getUrl(), getCurrentTabModel().isIncognito());
        HelpAndFeedback.getInstance(this)
                .show(this, helpContextId, currentTab.getProfile(), currentTab.getUrl());
        RecordUserAction.record("MobileMenuFeedback");
    } else {
        return false;
    }
    return true;
}