org.chromium.chrome.browser.offlinepages.OfflinePageUtils Java Examples

The following examples show how to use org.chromium.chrome.browser.offlinepages.OfflinePageUtils. 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: DownloadUtils.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Whether the user should be allowed to download the current page.
 * @param tab Tab displaying the page that will be downloaded.
 * @return    Whether the "Download Page" button should be enabled.
 */
public static boolean isAllowedToDownloadPage(Tab tab) {
    if (tab == null) return false;

    // Offline pages isn't supported in Incognito. This should be checked before calling
    // OfflinePageBridge.getForProfile because OfflinePageBridge instance will not be found
    // for incognito profile.
    if (tab.isIncognito()) return false;

    // Check if the page url is supported for saving. Only HTTP and HTTPS pages are allowed.
    if (!OfflinePageBridge.canSavePage(tab.getUrl())) return false;

    // Download will only be allowed for the error page if download button is shown in the page.
    if (tab.isShowingErrorPage()) {
        final OfflinePageBridge bridge = OfflinePageBridge.getForProfile(tab.getProfile());
        return bridge.isShowingDownloadButtonInErrorPage(tab.getWebContents());
    }

    if (tab.isShowingInterstitialPage()) return false;

    // Don't allow re-downloading the currently displayed offline page.
    if (OfflinePageUtils.isOfflinePage(tab)) return false;

    return true;
}
 
Example #2
Source File: LocationBarLayout.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Update visibility of the verbose status based on the button type and focus state of the
 * omnibox.
 */
private void updateVerboseStatusVisibility() {
    // Because is offline page is cleared a bit slower, we also ensure that connection security
    // level is NONE or HTTP_SHOW_WARNING (http://crbug.com/671453).
    boolean verboseStatusVisible = !mUrlHasFocus && getCurrentTab() != null
            && OfflinePageUtils.isOfflinePage(getCurrentTab())
            && (getSecurityLevel() == ConnectionSecurityLevel.NONE
                       || getSecurityLevel() == ConnectionSecurityLevel.HTTP_SHOW_WARNING);

    int verboseStatusVisibility = verboseStatusVisible ? VISIBLE : GONE;

    mVerboseStatusTextView.setTextColor(ApiCompatibilityUtils.getColor(getResources(),
            mUseDarkColors ? R.color.locationbar_status_color
                    : R.color.locationbar_status_color_light));
    mVerboseStatusTextView.setVisibility(verboseStatusVisibility);

    View separator = findViewById(R.id.location_bar_verbose_status_separator);
    separator.setBackgroundColor(ApiCompatibilityUtils.getColor(getResources(), mUseDarkColors
            ? R.color.locationbar_status_separator_color
            : R.color.locationbar_status_separator_color_light));
    separator.setVisibility(verboseStatusVisibility);

    findViewById(R.id.location_bar_verbose_status_extra_space)
            .setVisibility(verboseStatusVisibility);
}
 
Example #3
Source File: OfflinePageDownloadBridge.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * 'Opens' the offline page identified by the GUID.
 * This is done by creating a new tab and navigating it to the saved local snapshot.
 * No automatic redirection is happening based on the connection status.
 * If the item with specified GUID is not found or can't be opened, nothing happens.
 * @param guid          GUID of the item to open.
 * @param componentName If specified, targets a specific Activity to open the offline page in.
 */
@Override
public void openItem(String guid, @Nullable ComponentName componentName) {
    OfflinePageDownloadItem item = getItem(guid);
    if (item == null) return;

    LoadUrlParams params = OfflinePageUtils.getLoadUrlParamsForOpeningOfflineVersion(
            item.getUrl(), nativeGetOfflineIdByGuid(mNativeOfflinePageDownloadBridge, guid));
    AsyncTabCreationParams asyncParams = componentName == null
            ? new AsyncTabCreationParams(params)
            : new AsyncTabCreationParams(params, componentName);
    final TabDelegate tabDelegate = new TabDelegate(false);
    tabDelegate.createNewTab(asyncParams, TabLaunchType.FROM_CHROME_UI, Tab.INVALID_TAB_ID);
}
 
Example #4
Source File: Tab.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Reloads the current page content.
 */
public void reload() {
    // TODO(dtrainor): Should we try to rebuild the ContentView if it's frozen?
    if (isBlimpTab()) {
        if (getBlimpContents() != null) {
            getBlimpContents().getNavigationController().reload();
        }
    } else if (isOfflinePage()) {
        // If current page is an offline page, reload it with custom behavior defined in extra
        // header respected.
        OfflinePageUtils.reload(this);
    } else {
        if (getWebContents() != null) getWebContents().getNavigationController().reload(true);
    }
}
 
Example #5
Source File: OfflinePageDownloadBridge.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * 'Opens' the offline page identified by the GUID.
 * This is done by creating a new tab and navigating it to the saved local snapshot.
 * No automatic redirection is happening based on the connection status.
 * If the item with specified GUID is not found or can't be opened, nothing happens.
 * @param guid          GUID of the item to open.
 * @param componentName If specified, targets a specific Activity to open the offline page in.
 */
@Override
public void openItem(String guid, @Nullable ComponentName componentName) {
    OfflinePageDownloadItem item = getItem(guid);
    if (item == null) return;

    LoadUrlParams params = OfflinePageUtils.getLoadUrlParamsForOpeningOfflineVersion(
            item.getUrl(), nativeGetOfflineIdByGuid(mNativeOfflinePageDownloadBridge, guid));
    AsyncTabCreationParams asyncParams = componentName == null
            ? new AsyncTabCreationParams(params)
            : new AsyncTabCreationParams(params, componentName);
    final TabDelegate tabDelegate = new TabDelegate(false);
    tabDelegate.createNewTab(asyncParams, TabLaunchType.FROM_CHROME_UI, Tab.INVALID_TAB_ID);
}
 
Example #6
Source File: LocationBarLayout.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@LocationBarButtonType private int getLocationBarButtonToShow() {
    boolean isOffline =
            getCurrentTab() != null && OfflinePageUtils.isOfflinePage(getCurrentTab());
    boolean isTablet = DeviceFormFactor.isTablet();

    // The navigation icon type is only applicable on tablets.  While smaller form factors do
    // not have an icon visible to the user when the URL is focused, BUTTON_TYPE_NONE is not
    // returned as it will trigger an undesired jump during the animation as it attempts to
    // hide the icon.
    if (mUrlHasFocus && isTablet) return BUTTON_TYPE_NAVIGATION_ICON;

    return getSecurityIconResource(getSecurityLevel(), !isTablet, isOffline) != 0
            ? BUTTON_TYPE_SECURITY_ICON
            : BUTTON_TYPE_NONE;
}
 
Example #7
Source File: LocationBarLayout.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the security icon displayed in the LocationBar.
 */
@Override
public void updateSecurityIcon(int securityLevel) {
    boolean isSmallDevice = !DeviceFormFactor.isTablet();
    boolean isOfflinePage =
            getCurrentTab() != null && OfflinePageUtils.isOfflinePage(getCurrentTab());
    int id = getSecurityIconResource(securityLevel, isSmallDevice, isOfflinePage);
    if (id == 0) {
        mSecurityButton.setImageDrawable(null);
    } else {
        // ImageView#setImageResource is no-op if given resource is the current one.
        mSecurityButton.setImageResource(id);
        mSecurityButton.setTint(getColorStateList(securityLevel, getToolbarDataProvider(),
                getResources(), ColorUtils.shouldUseOpaqueTextboxBackground(
                        getToolbarDataProvider().getPrimaryColor())));
    }

    updateVerboseStatusVisibility();

    boolean shouldEmphasizeHttpsScheme = shouldEmphasizeHttpsScheme();
    if (mSecurityIconResource == id
            && mIsEmphasizingHttpsScheme == shouldEmphasizeHttpsScheme) {
        return;
    }
    mSecurityIconResource = id;

    changeLocationBarIcon();
    updateLocationBarIconContainerVisibility();
    // Since we emphasize the scheme of the URL based on the security type, we need to
    // refresh the emphasis.
    mUrlBar.deEmphasizeUrl();
    emphasizeUrl();
    mIsEmphasizingHttpsScheme = shouldEmphasizeHttpsScheme;
}
 
Example #8
Source File: Tab.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Reloads the current page content.
 */
public void reload() {
    // TODO(dtrainor): Should we try to rebuild the ContentView if it's frozen?
    if (OfflinePageUtils.isOfflinePage(this)) {
        // If current page is an offline page, reload it with custom behavior defined in extra
        // header respected.
        OfflinePageUtils.reload(this);
    } else {
        if (getWebContents() != null) getWebContents().getNavigationController().reload(true);
    }
}
 
Example #9
Source File: CustomTabToolbar.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void updateSecurityIcon(int securityLevel) {
    if (mState == STATE_TITLE_ONLY) return;

    mSecurityIconType = securityLevel;

    boolean isSmallDevice = !DeviceFormFactor.isTablet();
    boolean isOfflinePage =
            getCurrentTab() != null && OfflinePageUtils.isOfflinePage(getCurrentTab());

    int id = LocationBarLayout.getSecurityIconResource(
            securityLevel, isSmallDevice, isOfflinePage);
    boolean showSecurityButton = true;
    if (id == 0) {
        // Hide the button if we don't have an actual icon to display.
        showSecurityButton = false;
        mSecurityButton.setImageDrawable(null);
    } else {
        // ImageView#setImageResource is no-op if given resource is the current one.
        mSecurityButton.setImageResource(id);
        mSecurityButton.setTint(
                LocationBarLayout.getColorStateList(securityLevel, getToolbarDataProvider(),
                        getResources(), false /* omnibox is not opaque */));
    }

    mShowsOfflinePage = isOfflinePage;

    if (showSecurityButton) {
        mAnimDelegate.showSecurityButton();
    } else {
        mAnimDelegate.hideSecurityButton();
    }

    mUrlBar.emphasizeUrl();
    mUrlBar.invalidate();
}
 
Example #10
Source File: ChromeBackgroundService.java    From delion with Apache License 2.0 4 votes vote down vote up
@Override
@VisibleForTesting
public int onRunTask(final TaskParams params) {
    final String taskTag = params.getTag();
    Log.i(TAG, "[" + taskTag + "] Woken up at " + new java.util.Date().toString());
    final ChromeBackgroundServiceWaiter waiter = getWaiterIfNeeded(params.getExtras());
    final Context context = this;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            switch (taskTag) {
                case BackgroundSyncLauncher.TASK_TAG:
                    handleBackgroundSyncEvent(context, taskTag);
                    break;

                case OfflinePageUtils.TASK_TAG:
                    handleOfflinePageBackgroundLoad(
                            context, params.getExtras(), waiter, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_WIFI_CHARGING:
                case SnippetsLauncher.TASK_TAG_WIFI:
                case SnippetsLauncher.TASK_TAG_FALLBACK:
                    handleFetchSnippets(context, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_RESCHEDULE:
                    handleRescheduleSnippets(context, taskTag);
                    break;

                case PrecacheController.PERIODIC_TASK_TAG:
                case PrecacheController.CONTINUATION_TASK_TAG:
                    handlePrecache(context, taskTag);
                    break;

                case DownloadResumptionScheduler.TASK_TAG:
                    DownloadResumptionScheduler.getDownloadResumptionScheduler(
                            context.getApplicationContext()).handleDownloadResumption();
                    break;

                default:
                    Log.i(TAG, "Unknown task tag " + taskTag);
                    break;
            }
        }
    });
    // If needed, block the GcmNetworkManager thread until the UI thread has finished its work.
    waitForTaskIfNeeded(waiter);

    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example #11
Source File: DeferredStartupHandler.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Handle application level deferred startup tasks that can be lazily done after all
 * the necessary initialization has been completed. Any calls requiring network access should
 * probably go here.
 *
 * Keep these tasks short and break up long tasks into multiple smaller tasks, as they run on
 * the UI thread and are blocking. Remember to follow RAIL guidelines, as much as possible, and
 * that most devices are quite slow, so leave enough buffer.
 */
@UiThread
public void initDeferredStartupForApp() {
    if (mDeferredStartupInitializedForApp) return;
    mDeferredStartupInitializedForApp = true;
    ThreadUtils.assertOnUiThread();

    RecordHistogram.recordLongTimesHistogram(
            "UMA.Debug.EnableCrashUpload.DeferredStartUptime2",
            SystemClock.uptimeMillis() - UmaUtils.getForegroundStartTime(),
            TimeUnit.MILLISECONDS);

    mDeferredTasks.add(new Runnable() {
        @Override
        public void run() {
            // Punt all tasks that may block on disk off onto a background thread.
            initAsyncDiskTask();

            AfterStartupTaskUtils.setStartupComplete();

            PartnerBrowserCustomizations.setOnInitializeAsyncFinished(new Runnable() {
                @Override
                public void run() {
                    String homepageUrl = HomepageManager.getHomepageUri(mAppContext);
                    LaunchMetrics.recordHomePageLaunchMetrics(
                            HomepageManager.isHomepageEnabled(mAppContext),
                            NewTabPage.isNTPUrl(homepageUrl), homepageUrl);
                }
            });

            PartnerBookmarksShim.kickOffReading(mAppContext);

            PowerMonitor.create(mAppContext);

            ShareHelper.clearSharedImages();

            OfflinePageUtils.clearSharedOfflineFiles(mAppContext);
        }
    });

    mDeferredTasks.add(new Runnable() {
        @Override
        public void run() {
            // Clear any media notifications that existed when Chrome was last killed.
            MediaCaptureNotificationService.clearMediaNotifications(mAppContext);

            startModerateBindingManagementIfNeeded();

            recordKeyboardLocaleUma();
        }
    });

    mDeferredTasks.add(new Runnable() {
        @Override
        public void run() {
            // Start or stop Physical Web
            PhysicalWeb.onChromeStart();
        }
    });

    final ChromeApplication application = (ChromeApplication) mAppContext;

    mDeferredTasks.add(new Runnable() {
        @Override
        public void run() {
            // Starts syncing with GSA.
            application.createGsaHelper().startSync();
        }
    });

    ProcessInitializationHandler.getInstance().initializeDeferredStartupTasks();
}
 
Example #12
Source File: ChromeBackgroundService.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
@VisibleForTesting
public int onRunTask(final TaskParams params) {
    final String taskTag = params.getTag();
    Log.i(TAG, "[" + taskTag + "] Woken up at " + new java.util.Date().toString());
    final ChromeBackgroundServiceWaiter waiter = getWaiterIfNeeded(params.getExtras());
    final Context context = this;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            switch (taskTag) {
                case BackgroundSyncLauncher.TASK_TAG:
                    handleBackgroundSyncEvent(context, taskTag);
                    break;

                case OfflinePageUtils.TASK_TAG:
                    handleOfflinePageBackgroundLoad(
                            context, params.getExtras(), waiter, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_WIFI:
                case SnippetsLauncher.TASK_TAG_FALLBACK:
                    handleFetchSnippets(context, taskTag);
                    break;

                case PrecacheController.PERIODIC_TASK_TAG:
                case PrecacheController.CONTINUATION_TASK_TAG:
                    handlePrecache(context, taskTag);
                    break;

                case DownloadResumptionScheduler.TASK_TAG:
                    DownloadResumptionScheduler.getDownloadResumptionScheduler(
                            context.getApplicationContext()).handleDownloadResumption();
                    break;

                default:
                    Log.i(TAG, "Unknown task tag " + taskTag);
                    break;
            }
        }
    });
    // If needed, block the GcmNetworkManager thread until the UI thread has finished its work.
    waitForTaskIfNeeded(waiter);

    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example #13
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 #14
Source File: ChromeBackgroundService.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
@VisibleForTesting
public int onRunTask(final TaskParams params) {
    final String taskTag = params.getTag();
    Log.i(TAG, "[" + taskTag + "] Woken up at " + new java.util.Date().toString());
    final ChromeBackgroundServiceWaiter waiter = getWaiterIfNeeded(params.getExtras());
    final Context context = this;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            switch (taskTag) {
                case BackgroundSyncLauncher.TASK_TAG:
                    handleBackgroundSyncEvent(context, taskTag);
                    break;

                case OfflinePageUtils.TASK_TAG:
                    handleOfflinePageBackgroundLoad(
                            context, params.getExtras(), waiter, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_WIFI:
                case SnippetsLauncher.TASK_TAG_FALLBACK:
                    handleFetchSnippets(context, taskTag);
                    break;

                case PrecacheController.PERIODIC_TASK_TAG:
                case PrecacheController.CONTINUATION_TASK_TAG:
                    handlePrecache(context, taskTag);
                    break;

                case DownloadResumptionScheduler.TASK_TAG:
                    DownloadResumptionScheduler.getDownloadResumptionScheduler(
                            context.getApplicationContext()).handleDownloadResumption();
                    break;

                default:
                    Log.i(TAG, "Unknown task tag " + taskTag);
                    break;
            }
        }
    });
    // If needed, block the GcmNetworkManager thread until the UI thread has finished its work.
    waitForTaskIfNeeded(waiter);

    return GcmNetworkManager.RESULT_SUCCESS;
}
 
Example #15
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);
    }
}