diff --git a/DEPS b/DEPS index 1094d701..1901ead 100644 --- a/DEPS +++ b/DEPS
@@ -40,7 +40,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'ce6b4b004b2842e61cd9f86ebb75d1872044b382', + 'skia_revision': 'c352f3b89a28fd06bf9b124bfc960d9581949716', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -52,7 +52,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '165dcf15f8fa8fd1f9aa60096d040a20096fdba3', + 'angle_revision': '12b0b399aaa22d0f5df0784997753f74ecdb8e36', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -64,7 +64,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'ab5939e1ad77f0d4fcdb0abc258da1e6fb7eef1a', + 'pdfium_revision': '54d91ecc4cedd07da6ff599285ac12168c146129', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other.
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 6781d1ac..04e237f3 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -202,13 +202,20 @@ android_assets("assets") { deps = [ + ":license_assets", ":locale_pak_assets", ":monochrome_webview_assets", ":pak_file_assets", ] } -android_assets("stub_assets") { +java_group("stub_assets") { + deps = [ + ":license_assets", + ] +} + +android_assets("license_assets") { sources = [ webview_license_path, ]
diff --git a/android_webview/system_webview_apk_tmpl.gni b/android_webview/system_webview_apk_tmpl.gni index b222511e..29c7374 100644 --- a/android_webview/system_webview_apk_tmpl.gni +++ b/android_webview/system_webview_apk_tmpl.gni
@@ -12,6 +12,8 @@ deps += [ "//android_webview:assets", + "//android_webview/apk:webview_license_activity_java", + "//android_webview/apk:webview_license_provider_java", "//base:base_java", ]
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view.cc b/ash/frame/caption_buttons/frame_caption_button_container_view.cc index 0169b201aa..7f529cd 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view.cc
@@ -338,6 +338,11 @@ } else if (sender == close_button_) { frame_->Close(); action = UMA_WINDOW_CLOSE_BUTTON_CLICK; + if (ash::Shell::Get() + ->maximize_mode_controller() + ->IsMaximizeModeWindowManagerEnabled()) { + action = UMA_TABLET_WINDOW_CLOSE_THROUGH_CAPTION_BUTTON; + } } else { return; }
diff --git a/ash/metrics/user_metrics_action.h b/ash/metrics/user_metrics_action.h index 08cb3fb3..82714330 100644 --- a/ash/metrics/user_metrics_action.h +++ b/ash/metrics/user_metrics_action.h
@@ -117,6 +117,12 @@ UMA_STATUS_AREA_VPN_ADD_THIRD_PARTY_CLICKED, UMA_STATUS_AREA_VPN_DISCONNECT_CLICKED, UMA_STATUS_AREA_VPN_SETTINGS_OPENED, + + // Track different window close actions in tablet mode. + UMA_TABLET_WINDOW_CLOSE_THROUGH_CONTXT_MENU, + UMA_TABLET_WINDOW_CLOSE_THROUGH_CAPTION_BUTTON, + UMA_TABLET_WINDOW_CLOSE_THROUGH_OVERVIEW_CLOSE_BUTTON, + UMA_TOGGLE_MAXIMIZE_CAPTION_CLICK, UMA_TOGGLE_MAXIMIZE_CAPTION_GESTURE, UMA_TOGGLE_SINGLE_AXIS_MAXIMIZE_BORDER_CLICK,
diff --git a/ash/metrics/user_metrics_recorder.cc b/ash/metrics/user_metrics_recorder.cc index f89748b..83c6e9a 100644 --- a/ash/metrics/user_metrics_recorder.cc +++ b/ash/metrics/user_metrics_recorder.cc
@@ -521,6 +521,15 @@ case UMA_STATUS_AREA_VPN_SETTINGS_OPENED: RecordAction(UserMetricsAction("StatusArea_VPN_Settings")); break; + case UMA_TABLET_WINDOW_CLOSE_THROUGH_CONTXT_MENU: + RecordAction(UserMetricsAction("Tablet_WindowCloseFromContextMenu")); + break; + case UMA_TABLET_WINDOW_CLOSE_THROUGH_CAPTION_BUTTON: + RecordAction(UserMetricsAction("Tablet_WindowCloseFromCaptionButton")); + break; + case UMA_TABLET_WINDOW_CLOSE_THROUGH_OVERVIEW_CLOSE_BUTTON: + RecordAction(UserMetricsAction("Tablet_WindowCloseFromOverviewButton")); + break; case UMA_TOGGLE_MAXIMIZE_CAPTION_CLICK: RecordAction(UserMetricsAction("Caption_ClickTogglesMaximize")); break;
diff --git a/ash/wm/overview/window_selector_item.cc b/ash/wm/overview/window_selector_item.cc index 0cf23cc..723e54b 100644 --- a/ash/wm/overview/window_selector_item.cc +++ b/ash/wm/overview/window_selector_item.cc
@@ -11,7 +11,9 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/root_window_controller.h" +#include "ash/shell.h" #include "ash/shell_port.h" +#include "ash/wm/maximize_mode/maximize_mode_controller.h" #include "ash/wm/overview/cleanup_animation_observer.h" #include "ash/wm/overview/overview_animation_type.h" #include "ash/wm/overview/scoped_overview_animation_settings.h" @@ -530,6 +532,12 @@ const ui::Event& event) { if (sender == close_button_) { ShellPort::Get()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW_CLOSE_BUTTON); + if (ash::Shell::Get() + ->maximize_mode_controller() + ->IsMaximizeModeWindowManagerEnabled()) { + ash::ShellPort::Get()->RecordUserMetricsAction( + ash::UMA_TABLET_WINDOW_CLOSE_THROUGH_OVERVIEW_CLOSE_BUTTON); + } CloseWindow(); return; }
diff --git a/build/android/lint/OWNERS b/build/android/lint/OWNERS new file mode 100644 index 0000000..f47bc2f --- /dev/null +++ b/build/android/lint/OWNERS
@@ -0,0 +1,2 @@ +estevenson@chromium.org +wnwen@chromium.org
diff --git a/build/android/lint/suppressions.xml b/build/android/lint/suppressions.xml index c58889a..b7a7dda 100644 --- a/build/android/lint/suppressions.xml +++ b/build/android/lint/suppressions.xml
@@ -103,7 +103,7 @@ </issue> <issue id="IconDensities"> <!-- The large assets below only include a few densities to reduce APK size. --> - <ignore regexp=": data_reduction_illustration.png, physical_web_logo.png, physical_web_logo_anim1.png, physical_web_logo_anim2.png$"/> + <ignore regexp="data_reduction_illustration.png"/> <!-- This is intentional to save on WebAPKs' size. --> <ignore regexp="chrome/android/webapk/shell_apk/res/drawable-*"/> <!-- crbug.com/457918 is tracking missing assets -->
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 7a68819..37bf601 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -646,7 +646,6 @@ jinja_template_resources("chrome_public_apk_template_resources") { resources = [ - "java/res_template/xml/chromebackupscheme.xml", "java/res_template/xml/launchershortcuts.xml", "java/res_template/xml/searchable.xml", "java/res_template/xml/syncadapter.xml", @@ -657,7 +656,6 @@ jinja_template_resources("chrome_sync_shell_apk_template_resources") { resources = [ - "java/res_template/xml/chromebackupscheme.xml", "java/res_template/xml/launchershortcuts.xml", "java/res_template/xml/searchable.xml", "java/res_template/xml/syncadapter.xml",
diff --git a/chrome/android/java/res/drawable-mdpi/physical_web_logo.png b/chrome/android/java/res/drawable-mdpi/physical_web_logo.png deleted file mode 100644 index 4ed62264..0000000 --- a/chrome/android/java/res/drawable-mdpi/physical_web_logo.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim1.png b/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim1.png deleted file mode 100644 index e011946..0000000 --- a/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim1.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim2.png b/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim2.png deleted file mode 100644 index 70c36de..0000000 --- a/chrome/android/java/res/drawable-mdpi/physical_web_logo_anim2.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo.png b/chrome/android/java/res/drawable-xxhdpi/physical_web_logo.png deleted file mode 100644 index ffe49981..0000000 --- a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim1.png b/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim1.png deleted file mode 100644 index ecf30ea..0000000 --- a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim1.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim2.png b/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim2.png deleted file mode 100644 index 9fbfae6..0000000 --- a/chrome/android/java/res/drawable-xxhdpi/physical_web_logo_anim2.png +++ /dev/null Binary files differ
diff --git a/chrome/android/java/res/drawable/payments_ui_logo_bg.xml b/chrome/android/java/res/drawable/payments_ui_logo_bg.xml deleted file mode 100644 index 0df658c..0000000 --- a/chrome/android/java/res/drawable/payments_ui_logo_bg.xml +++ /dev/null
@@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2016 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<!-- Encapsulates the content with a rounded white rectangle. --> -<shape xmlns:android="http://schemas.android.com/apk/res/android"> - <solid android:color="@android:color/white" /> - - <stroke - android:width="1dp" - android:color="#e0e0e0" /> - - <padding - android:left="1dp" - android:top="1dp" - android:right="1dp" - android:bottom="1dp" /> - - <corners android:radius="1dp" /> -</shape>
diff --git a/chrome/android/java/res/values/colors.xml b/chrome/android/java/res/values/colors.xml index 34c3fb4..e3da7df3 100644 --- a/chrome/android/java/res/values/colors.xml +++ b/chrome/android/java/res/values/colors.xml
@@ -15,7 +15,6 @@ <color name="dark_action_bar_color">#263238</color> <color name="descriptive_text_color">#646464</color> <color name="error_text_color">#c53929</color> - <color name="google_blue_200">#90caf9</color> <color name="google_blue_300">#7BAAF7</color> <color name="google_blue_500">#4285f4</color> <color name="google_blue_700">#3367d6</color>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index ccd67a6..8f2718c 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -419,7 +419,6 @@ is doubled. --> <dimen name="pref_autofill_dropdown_bottom_margin">16dp</dimen> <dimen name="pref_autofill_touch_target_padding">15dp</dimen> - <dimen name="pref_child_account_reduced_padding">4dp</dimen> <dimen name="pref_icon_padding">4.6dp</dimen> <dimen name="pref_spinner_padding_end">8dp</dimen>
diff --git a/chrome/android/java/res/xml/single_website_preferences.xml b/chrome/android/java/res/xml/single_website_preferences.xml index d0658cd..a7f3052 100644 --- a/chrome/android/java/res/xml/single_website_preferences.xml +++ b/chrome/android/java/res/xml/single_website_preferences.xml
@@ -11,6 +11,13 @@ <Preference android:key="os_permissions_warning_divider" android:layout="@layout/divider_preference" /> + <org.chromium.chrome.browser.preferences.TextMessagePreference + android:key="intrusive_ads_info" + android:title="@string/intrusive_ads_information" + android:icon="@drawable/btn_info" /> + <Preference + android:key="intrusive_ads_info_divider" + android:layout="@layout/divider_preference" /> <PreferenceCategory android:key="site_heading" android:title="@string/website_settings_site_category" />
diff --git a/chrome/android/java/res_template/xml/chromebackupscheme.xml b/chrome/android/java/res_template/xml/chromebackupscheme.xml deleted file mode 100644 index 3277478..0000000 --- a/chrome/android/java/res_template/xml/chromebackupscheme.xml +++ /dev/null
@@ -1,9 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2015 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> - -<full-backup-content> - <include domain="sharedpref" path="{{manifest_package}}_preferences.xml"/> - <include domain="root" path="app_chrome/Default/Preferences"/> -</full-backup-content> \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ServiceTabLauncher.java b/chrome/android/java/src/org/chromium/chrome/browser/ServiceTabLauncher.java index d15430f..1c18a1e93 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ServiceTabLauncher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ServiceTabLauncher.java
@@ -17,6 +17,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.R; +import org.chromium.chrome.browser.customtabs.CustomTabIntentDataProvider; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.document.AsyncTabCreationParams; @@ -166,6 +167,10 @@ customTabsIntent.intent.putExtra(Browser.EXTRA_APPLICATION_ID, ContextUtils.getApplicationContext().getPackageName()); + // Customize items on menu as payment request UI to show 'Find in page', 'Forward arrow', + // 'Info' and 'Refresh' only. + CustomTabIntentDataProvider.addPaymentRequestUIExtras(customTabsIntent.intent); + customTabsIntent.launchUrl(lastTrackedActivity, Uri.parse(url)); return true;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 01dbb160..17b34f1b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -779,10 +779,10 @@ protected AppMenuPropertiesDelegate createAppMenuPropertiesDelegate() { return new CustomTabAppMenuPropertiesDelegate(this, mIntentDataProvider.getMenuTitles(), mIntentDataProvider.shouldShowShareMenuItem(), - mIntentDataProvider.isOpenedByChrome(), - mIntentDataProvider.isMediaViewer(), + mIntentDataProvider.isOpenedByChrome(), mIntentDataProvider.isMediaViewer(), mIntentDataProvider.shouldShowStarButton(), - mIntentDataProvider.shouldShowDownloadButton()); + mIntentDataProvider.shouldShowDownloadButton(), + mIntentDataProvider.isPaymentRequestUI()); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabAppMenuPropertiesDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabAppMenuPropertiesDelegate.java index 13d326a2..e13619d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabAppMenuPropertiesDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabAppMenuPropertiesDelegate.java
@@ -33,6 +33,7 @@ private final boolean mShowStar; private final boolean mShowDownload; private final boolean mIsOpenedByChrome; + private final boolean mIsPaymentRequestUI; private final List<String> mMenuEntries; private final Map<MenuItem, Integer> mItemToIndexMap = new HashMap<MenuItem, Integer>(); @@ -44,7 +45,8 @@ */ public CustomTabAppMenuPropertiesDelegate(final ChromeActivity activity, List<String> menuEntries, boolean showShare, final boolean isOpenedByChrome, - final boolean isMediaViewer, boolean showStar, boolean showDownload) { + final boolean isMediaViewer, boolean showStar, boolean showDownload, + final boolean isPaymentRequestUI) { super(activity); mMenuEntries = menuEntries; mShowShare = showShare; @@ -52,6 +54,7 @@ mShowStar = showStar; mShowDownload = showDownload; mIsOpenedByChrome = isOpenedByChrome; + mIsPaymentRequestUI = isPaymentRequestUI; } @Override @@ -92,6 +95,12 @@ menu.findItem(R.id.find_in_page_id).setVisible(false); menu.findItem(R.id.request_desktop_site_id).setVisible(false); addToHomeScreenVisible = false; + } else if (mIsPaymentRequestUI) { + // Only the icon row and 'find in page' are shown for openning payment request UI + // from Chrome. + openInChromeItem.setVisible(false); + menu.findItem(R.id.request_desktop_site_id).setVisible(false); + addToHomeScreenVisible = false; } else { openInChromeItem.setTitle( DefaultBrowserInfo.getTitleOpenInDefaultBrowser(mIsOpenedByChrome));
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java index 8201270..aaaf3ec 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java
@@ -67,6 +67,10 @@ public static final String EXTRA_ENABLE_EMBEDDED_MEDIA_EXPERIENCE = "org.chromium.chrome.browser.customtabs.EXTRA_ENABLE_EMBEDDED_MEDIA_EXPERIENCE"; + /** Indicates that the Custom Tab should style itself as payment request UI. */ + public static final String EXTRA_IS_PAYMENT_REQUEST_UI = + "org.chromium.chrome.browser.customtabs.EXTRA_IS_PAYMENT_REQUEST_UI"; + /** Indicates that the Custom Tab should style itself as an info page. */ public static final String EXTRA_IS_INFO_PAGE = "org.chromium.chrome.browser.customtabs.IS_INFO_PAGE"; @@ -104,6 +108,7 @@ private final boolean mIsMediaViewer; private final String mMediaViewerUrl; private final boolean mEnableEmbeddedMediaExperience; + private final boolean mIsPaymentRequestUI; private final boolean mIsInfoPage; private final int mInitialBackgroundColor; private final boolean mDisableStar; @@ -129,6 +134,17 @@ private boolean mIsOpenedByChrome; /** + * Add extras to customize menu items for openning payment request UI custom tab from Chrome. + */ + public static void addPaymentRequestUIExtras(Intent intent) { + intent.putExtra(EXTRA_IS_PAYMENT_REQUEST_UI, true); + intent.putExtra(EXTRA_IS_OPENED_BY_CHROME, true); + intent.putExtra(EXTRA_DISABLE_STAR_BUTTON, true); + intent.putExtra(EXTRA_DISABLE_DOWNLOAD_BUTTON, true); + IntentHandler.addTrustedIntentExtras(intent); + } + + /** * Constructs a {@link CustomTabIntentDataProvider}. */ public CustomTabIntentDataProvider(Intent intent, Context context) { @@ -194,6 +210,8 @@ mEnableEmbeddedMediaExperience = mIsTrustedIntent && IntentUtils.safeGetBooleanExtra( intent, EXTRA_ENABLE_EMBEDDED_MEDIA_EXPERIENCE, false); + mIsPaymentRequestUI = mIsTrustedIntent && mIsOpenedByChrome + && IntentUtils.safeGetBooleanExtra(intent, EXTRA_IS_PAYMENT_REQUEST_UI, false); mIsInfoPage = mIsTrustedIntent && IntentUtils.safeGetBooleanExtra(intent, EXTRA_IS_INFO_PAGE, false); mDisableStar = IntentUtils.safeGetBooleanExtra(intent, EXTRA_DISABLE_STAR_BUTTON, false); @@ -521,6 +539,14 @@ } /** + * @return true If the Custom Tab is opened as payment request UI. + * @See {@link #EXTRA_IS_PAYMENT_REQUEST_UI}. + */ + boolean isPaymentRequestUI() { + return mIsPaymentRequestUI; + } + + /** * @return If the Custom Tab is an info page. * See {@link #EXTRA_IS_INFO_PAGE}. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java index f1a3ac31..06c9d022 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java
@@ -201,8 +201,10 @@ Context context = ContextUtils.getApplicationContext(); try { // Early-out if the intent targets Chrome. - if (intent.getComponent() != null - && context.getPackageName().equals(intent.getComponent().getPackageName())) { + if (context.getPackageName().equals(intent.getPackage()) + || (intent.getComponent() != null + && context.getPackageName().equals( + intent.getComponent().getPackageName()))) { return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SingleWebsitePreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SingleWebsitePreferences.java index 2de9af10..8d61807 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SingleWebsitePreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/website/SingleWebsitePreferences.java
@@ -25,6 +25,7 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ContentSettingsType; import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader; +import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.search_engines.TemplateUrlService; import org.chromium.components.url_formatter.UrlFormatter; import org.chromium.content_public.browser.WebContents; @@ -63,6 +64,8 @@ public static final String PREF_OS_PERMISSIONS_WARNING_EXTRA = "os_permissions_warning_extra"; public static final String PREF_OS_PERMISSIONS_WARNING_DIVIDER = "os_permissions_warning_divider"; + public static final String PREF_INTRUSIVE_ADS_INFO = "intrusive_ads_info"; + public static final String PREF_INTRUSIVE_ADS_INFO_DIVIDER = "intrusive_ads_info_divider"; // Actions at the top (if adding new, see hasUsagePreferences below): public static final String PREF_CLEAR_DATA = "clear_data"; // Buttons: @@ -283,6 +286,8 @@ setUpUsbPreferences(maxPermissionOrder); setUpOsWarningPreferences(); + setUpAdsInformationalBanner(); + // Remove categories if no sub-items. if (!hasUsagePreferences()) { Preference heading = preferenceScreen.findPreference(PREF_USAGE); @@ -389,6 +394,24 @@ } } + private void setUpAdsInformationalBanner() { + // Add the informational banner which shows at the top of the UI if ad blocking is + // activated on this site. + PreferenceScreen preferenceScreen = getPreferenceScreen(); + boolean adBlockingActivated = SiteSettingsCategory.adsCategoryEnabled() + && WebsitePreferenceBridge.getAdBlockingActivated(mSite.getAddress().getOrigin()) + && preferenceScreen.findPreference(PREF_ADS_PERMISSION) != null; + + if (!adBlockingActivated) { + Preference intrusiveAdsInfo = preferenceScreen.findPreference(PREF_INTRUSIVE_ADS_INFO); + Preference intrusiveAdsInfoDivider = + preferenceScreen.findPreference(PREF_INTRUSIVE_ADS_INFO_DIVIDER); + + preferenceScreen.removePreference(intrusiveAdsInfo); + preferenceScreen.removePreference(intrusiveAdsInfoDivider); + } + } + private SiteSettingsCategory getWarningCategory() { // If more than one per-app permission is disabled in Android, we can pick any category to // show the warning, because they will all show the same warning and all take the user to @@ -536,12 +559,22 @@ ContentSetting permission = mSite.getAdsPermission(); // If |permission| is null, there is no explicit (non-default) permission set for this site. - // However, if the blocking is activated, we still want to show the permission as BLOCK. + // If the site is not considered a candidate for blocking, do the standard thing and remove + // the preference. if (permission == null && !activated) { setUpListPreference(preference, null); return; } - setUpListPreference(preference, permission == null ? ContentSetting.BLOCK : permission); + + // However, if the blocking is activated, we still want to show the permission, even if it + // is in the default state. + if (permission == null) { + ContentSetting defaultPermission = PrefServiceBridge.getInstance().adsEnabled() + ? ContentSetting.ALLOW + : ContentSetting.BLOCK; + permission = defaultPermission; + } + setUpListPreference(preference, permission); // The subresource filter permission has a custom BLOCK string. ListPreference listPreference = (ListPreference) preference;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkDisclosureNotificationManager.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkDisclosureNotificationManager.java index b010f1db..02e6454 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkDisclosureNotificationManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkDisclosureNotificationManager.java
@@ -5,14 +5,14 @@ package org.chromium.chrome.browser.webapps; import android.app.Notification; +import android.app.NotificationManager; import android.content.Context; -import android.graphics.BitmapFactory; import org.chromium.base.ContextUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.notifications.ChromeNotificationBuilder; +import org.chromium.chrome.browser.notifications.NotificationBuilderFactory; import org.chromium.chrome.browser.notifications.NotificationUmaTracker; -import org.chromium.chrome.browser.notifications.StandardNotificationBuilder; -import org.chromium.chrome.browser.notifications.WebApkNotificationClient; import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; /** @@ -28,30 +28,30 @@ // Prefix used for generating a unique notification tag. private static final String DISMISSAL_NOTIFICATION_TAG_PREFIX = "dismissal_notification_tag_prefix."; + /** * Shows the privacy disclosure informing the user that Chrome is being used. * @param webappInfo Web App this is currently displayed fullscreen. */ public static void showDisclosure(WebappInfo webappInfo) { Context context = ContextUtils.getApplicationContext(); - String title = webappInfo.shortName(); - // It's okay to not set a valid channelId for web apk notifications because web apks don't - // target O yet. - StandardNotificationBuilder builder = - new StandardNotificationBuilder(context, null /* channelId */); - builder.setTitle(title) + ChromeNotificationBuilder builder = + NotificationBuilderFactory.createChromeNotificationBuilder( + false /* preferCompat */, ChannelDefinitions.CHANNEL_ID_BROWSER); + builder.setContentTitle(webappInfo.name()) .setPriority(Notification.PRIORITY_MIN) - .setLargeIcon(BitmapFactory.decodeResource( - context.getResources(), R.drawable.ic_launcher)) + .setSmallIcon(R.drawable.ic_chrome) + .setLargeIcon(webappInfo.icon()) .setDeleteIntent(WebApkDisclosureNotificationService.getDeleteIntent( context, webappInfo.id())) - .setBody(context.getResources().getString( - R.string.webapk_running_in_chrome_disclosure, title)); + .setContentText(context.getResources().getString( + R.string.webapk_running_in_chrome_disclosure)); - WebApkNotificationClient.notifyNotification(webappInfo.webApkPackageName(), builder, - DISMISSAL_NOTIFICATION_TAG_PREFIX + webappInfo.webApkPackageName(), PLATFORM_ID); - // Even though the Notification is shown via the WebApk, we still want to record UMA. + NotificationManager nm = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(DISMISSAL_NOTIFICATION_TAG_PREFIX + webappInfo.webApkPackageName(), PLATFORM_ID, + builder.build()); NotificationUmaTracker.getInstance().onNotificationShown( NotificationUmaTracker.WEBAPK, ChannelDefinitions.CHANNEL_ID_BROWSER); } @@ -61,9 +61,9 @@ * @param webappInfo Web App this is currently displayed fullscreen. */ public static void dismissNotification(WebappInfo webappInfo) { - WebApkNotificationClient.cancelNotification( - webappInfo.webApkPackageName(), - DISMISSAL_NOTIFICATION_TAG_PREFIX + webappInfo.webApkPackageName(), - PLATFORM_ID); + Context context = ContextUtils.getApplicationContext(); + NotificationManager nm = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + nm.cancel(DISMISSAL_NOTIFICATION_TAG_PREFIX + webappInfo.webApkPackageName(), PLATFORM_ID); } }
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index ac75347c..fef5703 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -743,6 +743,9 @@ <message name="IDS_ALL_SITES" desc='Title of the "All sites" settings screen that allows the user to see permissions for all websites. [CHAR-LIMIT=32]'> All sites </message> + <message name="IDS_INTRUSIVE_ADS_INFORMATION" desc="The extra information at the top of the Site Details page when the site tends to show intrusive ads"> + This site tends to show intrusive ads + </message> <message name="IDS_ADS_PERMISSION_TITLE" desc="Title for the ads permission [CHAR-LIMIT=32]"> Ads </message> @@ -2947,7 +2950,7 @@ <!-- WebAPK related strings --> <message name="IDS_WEBAPK_RUNNING_IN_CHROME_DISCLOSURE" desc="Message on the notification that indicates a WebApk may use Chrome data."> - <ph name="APP_NAME">%1$s<ex>YouTube</ex></ph> is running in Chrome. + This app is running in Chrome. </message> <!-- Keyboard shortcuts in Android N-->
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabFromChromeExternalNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabFromChromeExternalNavigationTest.java index 0849208..4acf84d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabFromChromeExternalNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabFromChromeExternalNavigationTest.java
@@ -11,6 +11,7 @@ import android.support.test.filters.LargeTest; import android.support.test.filters.MediumTest; import android.util.Base64; +import android.view.Menu; import org.junit.After; import org.junit.Assert; @@ -24,7 +25,9 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; +import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; +import org.chromium.chrome.browser.appmenu.AppMenuHandler; import org.chromium.chrome.browser.customtabs.CustomTabDelegateFactory.CustomTabNavigationDelegate; import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.externalnav.ExternalNavigationHandler.OverrideUrlLoadingResult; @@ -93,6 +96,14 @@ getCustomTabFromChromeIntent(url)); } + private void startPaymentRequestUIFromChrome(String url) throws InterruptedException { + Intent intent = getCustomTabFromChromeIntent(url); + CustomTabIntentDataProvider.addPaymentRequestUIExtras(intent); + + mCustomTabActivityTestRule.startCustomTabActivityWithIntent(intent); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + } + @Test @Feature("CustomTabFromChrome") @MediumTest @@ -152,4 +163,47 @@ } }); } + + @Test + @Feature("CustomTabFromChrome") + @MediumTest + public void testIntentToOpenPaymentRequestUI() throws Exception { + startPaymentRequestUIFromChrome("about:blank"); + + Tab tab = mCustomTabActivityTestRule.getActivity().getActivityTab(); + TabDelegateFactory delegateFactory = tab.getDelegateFactory(); + Assert.assertTrue(delegateFactory instanceof CustomTabDelegateFactory); + CustomTabDelegateFactory customTabDelegateFactory = + ((CustomTabDelegateFactory) delegateFactory); + Assert.assertFalse(customTabDelegateFactory.getExternalNavigationDelegate() + instanceof CustomTabNavigationDelegate); + + showAppMenuAndAssertMenuShown(mCustomTabActivityTestRule.getActivity().getAppMenuHandler()); + Menu menu = + mCustomTabActivityTestRule.getActivity().getAppMenuHandler().getAppMenu().getMenu(); + + Assert.assertTrue(menu.findItem(R.id.icon_row_menu_id).isVisible()); + Assert.assertTrue(menu.findItem(R.id.find_in_page_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.open_in_browser_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.bookmark_this_page_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.offline_page_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.request_desktop_site_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.add_to_homescreen_id).isVisible()); + Assert.assertFalse(menu.findItem(R.id.open_webapk_id).isVisible()); + } + + private void showAppMenuAndAssertMenuShown(final AppMenuHandler appMenuHandler) { + ThreadUtils.runOnUiThread(new Runnable() { + @Override + public void run() { + appMenuHandler.showAppMenu(null, false); + } + }); + CriteriaHelper.pollUiThread(new Criteria("AppMenu did not show") { + @Override + public boolean isSatisfied() { + return appMenuHandler.isAppMenuShowing(); + } + }); + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelMergingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelMergingTest.java index 0bef20f4..8f7b151 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelMergingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelMergingTest.java
@@ -91,11 +91,15 @@ // Initialize activities. mActivity1 = mActivityTestRule.getActivity(); + // Start multi-instance mode so that ChromeTabbedActivity's check for whether the activity + // is started up correctly doesn't fail. + ChromeTabbedActivity.onMultiInstanceModeStarted(); mActivity2 = MultiWindowUtilsTest.createSecondChromeTabbedActivity(mActivity1); CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - return mActivity2.getTabModelSelector().isTabStateInitialized(); + return mActivity2.areTabModelsInitialized() + && mActivity2.getTabModelSelector().isTabStateInitialized(); } }); @@ -229,7 +233,8 @@ CriteriaHelper.pollUiThread(new Criteria() { @Override public boolean isSatisfied() { - return newActivity.getTabModelSelector().isTabStateInitialized(); + return newActivity.areTabModelsInitialized() + && newActivity.getTabModelSelector().isTabStateInitialized(); } });
diff --git a/chrome/android/webapk/shell_apk/BUILD.gn b/chrome/android/webapk/shell_apk/BUILD.gn index 446a9cb..b87470ce 100644 --- a/chrome/android/webapk/shell_apk/BUILD.gn +++ b/chrome/android/webapk/shell_apk/BUILD.gn
@@ -14,7 +14,7 @@ webapk_runtime_host_application_name = "Chromium" # The Url of the Web Manifest file. - webapk_web_manifest_url = "https://www.template.com/manifest.json" + webapk_web_manifest_url = "https://pwa.rocks/pwa.webmanifest" # Murmur2 hash of the homescreen icon. The hash should be of the icon as it is # available from the web. The icon bytes should not be transformed (e.g. @@ -22,21 +22,21 @@ webapk_icon_murmur2_hash = "0" # Attributes from Web Manifest. - webapk_start_url = "https://www.template.com/home_page" - webapk_name = "Longer Sample WebAPK Name" - webapk_short_name = "Sample WebAPK" - webapk_scope_url = "https://www.template.com/" + webapk_start_url = "https://pwa.rocks/" + webapk_name = "Progressive Web Apps" + webapk_short_name = "PWA List" + webapk_scope_url = "https://pwa.rocks/" webapk_display_mode = "standalone" webapk_orientation = "portrait" webapk_theme_color = "2147483648L" # HostBrowserLauncher#MANIFEST_COLOR_INVALID_OR_MISSING webapk_background_color = "2147483648L" #HostBrowserLauncher#MANIFEST_COLOR_INVALID_OR_MISSING - webapk_icon_urls_and_icon_murmur2_hashes = "http://www.template.com/icon1.png $webapk_icon_murmur2_hash http://www.template.com/icon2.png $webapk_icon_murmur2_hash" + webapk_icon_urls_and_icon_murmur2_hashes = "http://www.pwa.rocks/icon1.png $webapk_icon_murmur2_hash http://www.pwa.rocks/icon2.png $webapk_icon_murmur2_hash" # Scheme part of |webapk_scope_url|. webapk_scope_url_scheme = "https" # Host part of |webapk_scope_url|. - webapk_scope_url_host = "www.template.com" + webapk_scope_url_host = "pwa.rocks" # Path part of |webapk_scope_url|. webapk_scope_url_path = "/" @@ -118,19 +118,19 @@ "shell_apk_version=$template_shell_apk_version", "manifest_package=org.chromium.webapk.test", "runtime_host=org.chromium.chrome", - "start_url=https://www.template.com/home_page", + "start_url=https://pwa.rocks", "name=Test", "short_name=Test", - "scope_url=https://www.template.com", + "scope_url=https://pwa.rocks", "display_mode=standalone", "orientation=portrait", "theme_color=2147483648L", # HostBrowserLauncher#MANIFEST_COLOR_INVALID_OR_MISSING "background_color=2147483648L", # HostBrowserLauncher#MANIFEST_COLOR_INVALID_OR_MISSING "icon_urls_and_icon_murmur2_hashes=", "scope_url_scheme=https", - "scope_url_host=template.com", + "scope_url_host=pwa.rocks", "scope_url_path=/", - "web_manifest_url=https://www.template.com/manifest.json", + "web_manifest_url=https://pwa.rocks/pwa.webmanifest", "version_code=1", "version_name=1.0", ]
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index e7566f3f..50916ff 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -280,6 +280,8 @@ "conflicts/module_inspector_win.h", "conflicts/msi_util_win.cc", "conflicts/msi_util_win.h", + "conflicts/shell_extension_enumerator_win.cc", + "conflicts/shell_extension_enumerator_win.h", "conflicts/third_party_metrics_recorder_win.cc", "conflicts/third_party_metrics_recorder_win.h", "content_settings/chrome_content_settings_utils.cc",
diff --git a/chrome/browser/android/vr_shell/BUILD.gn b/chrome/browser/android/vr_shell/BUILD.gn index 59855ed..ae59fe80 100644 --- a/chrome/browser/android/vr_shell/BUILD.gn +++ b/chrome/browser/android/vr_shell/BUILD.gn
@@ -65,6 +65,8 @@ "ui_elements/exit_warning.h", "ui_elements/loading_indicator.cc", "ui_elements/loading_indicator.h", + "ui_elements/location_access_indicator.cc", + "ui_elements/location_access_indicator.h", "ui_elements/permanent_security_warning.cc", "ui_elements/permanent_security_warning.h", "ui_elements/screen_capture_indicator.cc",
diff --git a/chrome/browser/android/vr_shell/textures/system_indicator_texture.cc b/chrome/browser/android/vr_shell/textures/system_indicator_texture.cc index 439b3ba..2ee7035 100644 --- a/chrome/browser/android/vr_shell/textures/system_indicator_texture.cc +++ b/chrome/browser/android/vr_shell/textures/system_indicator_texture.cc
@@ -31,7 +31,10 @@ SystemIndicatorTexture::SystemIndicatorTexture(const gfx::VectorIcon& icon, int message_id) - : icon_(icon), message_id_(message_id) {} + : icon_(icon), message_id_(message_id), has_text_(true) {} + +SystemIndicatorTexture::SystemIndicatorTexture(const gfx::VectorIcon& icon) + : icon_(icon), has_text_(false) {} SystemIndicatorTexture::~SystemIndicatorTexture() = default; @@ -46,21 +49,31 @@ SkPaint paint; paint.setColor(color_scheme().system_indicator_background); - base::string16 text = l10n_util::GetStringUTF16(message_id_); + gfx::Rect text_size(0, 0); + std::vector<std::unique_ptr<gfx::RenderText>> lines; - gfx::FontList fonts; - GetFontList(size_.height() * kFontSizeFactor, text, &fonts); - gfx::Rect text_size(0, kTextHeightFactor * size_.height()); + if (has_text_) { + base::string16 text = l10n_util::GetStringUTF16(message_id_); - std::vector<std::unique_ptr<gfx::RenderText>> lines = PrepareDrawStringRect( - text, fonts, color_scheme().system_indicator_foreground, &text_size, - kTextAlignmentNone, kWrappingBehaviorNoWrap); + gfx::FontList fonts; + GetFontList(size_.height() * kFontSizeFactor, text, &fonts); + text_size.set_height(kTextHeightFactor * size_.height()); - DCHECK_LE(text_size.width(), kTextWidthFactor * size_.height()); - // Setting background size giving some extra lateral padding to the text. - size_.set_width((kHeightWidthRatio * kBorderFactor + kIconSizeFactor) * - size_.height() + - text_size.width()); + lines = PrepareDrawStringRect( + text, fonts, color_scheme().system_indicator_foreground, &text_size, + kTextAlignmentNone, kWrappingBehaviorNoWrap); + + DCHECK_LE(text_size.width(), kTextWidthFactor * size_.height()); + + // Setting background size giving some extra lateral padding to the text. + size_.set_width((kHeightWidthRatio * kBorderFactor + kIconSizeFactor) * + size_.height() + + text_size.width()); + } else { + size_.set_width((2 * kBorderFactor + kIconSizeFactor) * size_.height() + + text_size.width()); + } + float radius = size_.height() * kBorderFactor; sk_canvas->drawRoundRect(SkRect::MakeWH(size_.width(), size_.height()), radius, radius, paint);
diff --git a/chrome/browser/android/vr_shell/textures/system_indicator_texture.h b/chrome/browser/android/vr_shell/textures/system_indicator_texture.h index b20ef997..ab03721 100644 --- a/chrome/browser/android/vr_shell/textures/system_indicator_texture.h +++ b/chrome/browser/android/vr_shell/textures/system_indicator_texture.h
@@ -14,6 +14,7 @@ class SystemIndicatorTexture : public UiTexture { public: SystemIndicatorTexture(const gfx::VectorIcon& icon, int message_id); + explicit SystemIndicatorTexture(const gfx::VectorIcon& icon); ~SystemIndicatorTexture() override; gfx::Size GetPreferredTextureSize(int width) const override; gfx::SizeF GetDrawnSize() const override; @@ -24,6 +25,7 @@ gfx::SizeF size_; const gfx::VectorIcon& icon_; int message_id_; + bool has_text_; DISALLOW_COPY_AND_ASSIGN(SystemIndicatorTexture); };
diff --git a/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.cc b/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.cc new file mode 100644 index 0000000..e312a22 --- /dev/null +++ b/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.cc
@@ -0,0 +1,24 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/android/vr_shell/ui_elements/location_access_indicator.h" + +#include "base/memory/ptr_util.h" +#include "chrome/browser/android/vr_shell/textures/system_indicator_texture.h" +#include "chrome/grit/generated_resources.h" +#include "ui/vector_icons/vector_icons.h" + +namespace vr_shell { + +LocationAccessIndicator::LocationAccessIndicator(int preferred_width) + : TexturedElement(preferred_width), + texture_(base::MakeUnique<SystemIndicatorTexture>(ui::kLocationOnIcon)) {} + +LocationAccessIndicator::~LocationAccessIndicator() = default; + +UiTexture* LocationAccessIndicator::GetTexture() const { + return texture_.get(); +} + +} // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.h b/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.h new file mode 100644 index 0000000..9d217e6 --- /dev/null +++ b/chrome/browser/android/vr_shell/ui_elements/location_access_indicator.h
@@ -0,0 +1,31 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_ANDROID_VR_SHELL_UI_ELEMENTS_LOCATION_ACCESS_INDICATOR_H_ +#define CHROME_BROWSER_ANDROID_VR_SHELL_UI_ELEMENTS_LOCATION_ACCESS_INDICATOR_H_ + +#include <memory> + +#include "base/macros.h" +#include "chrome/browser/android/vr_shell/ui_elements/textured_element.h" + +namespace vr_shell { + +class UiTexture; + +class LocationAccessIndicator : public TexturedElement { + public: + explicit LocationAccessIndicator(int preferred_width); + ~LocationAccessIndicator() override; + + private: + UiTexture* GetTexture() const override; + std::unique_ptr<UiTexture> texture_; + + DISALLOW_COPY_AND_ASSIGN(LocationAccessIndicator); +}; + +} // namespace vr_shell + +#endif // CHROME_BROWSER_ANDROID_VR_SHELL_UI_ELEMENTS_LOCATION_ACCESS_INDICATOR_H_
diff --git a/chrome/browser/android/vr_shell/ui_elements/ui_element_debug_id.h b/chrome/browser/android/vr_shell/ui_elements/ui_element_debug_id.h index e8e7878..8d82a4ac 100644 --- a/chrome/browser/android/vr_shell/ui_elements/ui_element_debug_id.h +++ b/chrome/browser/android/vr_shell/ui_elements/ui_element_debug_id.h
@@ -28,6 +28,7 @@ kExitPrompt, kExitPromptBackplane, kTransientUrlBar, + kLocationAccessIndicator, }; } // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/ui_scene_manager.cc b/chrome/browser/android/vr_shell/ui_scene_manager.cc index 9862655..e3af74a 100644 --- a/chrome/browser/android/vr_shell/ui_scene_manager.cc +++ b/chrome/browser/android/vr_shell/ui_scene_manager.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/android/vr_shell/ui_elements/exit_prompt_backplane.h" #include "chrome/browser/android/vr_shell/ui_elements/exit_warning.h" #include "chrome/browser/android/vr_shell/ui_elements/loading_indicator.h" +#include "chrome/browser/android/vr_shell/ui_elements/location_access_indicator.h" #include "chrome/browser/android/vr_shell/ui_elements/permanent_security_warning.h" #include "chrome/browser/android/vr_shell/ui_elements/screen_capture_indicator.h" #include "chrome/browser/android/vr_shell/ui_elements/screen_dimmer.h" @@ -72,11 +73,13 @@ static constexpr float kAudioCaptureIndicatorWidth = 0.5; static constexpr float kVideoCaptureIndicatorWidth = 0.5; static constexpr float kScreenCaptureIndicatorWidth = 0.4; +static constexpr float kLocationIndicatorWidth = 0.088; static constexpr float kCaptureIndicatorsVerticalOffset = 0.1; static constexpr float kAudioCaptureHorizontalOffset = -0.6; static constexpr float kVideoCaptureHorizontalOffset = 0; static constexpr float kScreenCaptureHorizontalOffset = 0.6; +static constexpr float kLocationAccessHorizontalOffset = 1.0; static constexpr float kTransientUrlBarDistance = 1.4; static constexpr float kTransientUrlBarWidth = @@ -222,6 +225,19 @@ audio_capture_indicator_ = element.get(); scene_->AddUiElement(std::move(element)); + element = base::MakeUnique<LocationAccessIndicator>(250); + element->set_debug_id(kLocationAccessIndicator); + element->set_id(AllocateId()); + element->set_translation({kLocationAccessHorizontalOffset, + kCaptureIndicatorsVerticalOffset, + kIndicatorContentDistance}); + element->set_size({kLocationIndicatorWidth, 0, 1}); + element->set_parent_id(main_content_->id()); + element->set_y_anchoring(YAnchoring::YTOP); + element->set_visible(false); + location_access_indicator_ = element.get(); + scene_->AddUiElement(std::move(element)); + element = base::MakeUnique<VideoCaptureIndicator>(512); element->set_debug_id(kVideoCaptureIndicator); element->set_id(AllocateId()); @@ -421,9 +437,7 @@ ConfigureScene(); ConfigureSecurityWarnings(); ConfigureTransientUrlBar(); - audio_capture_indicator_->set_visible(!web_vr && audio_capturing_); - video_capture_indicator_->set_visible(!web_vr && video_capturing_); - screen_capture_indicator_->set_visible(!web_vr && screen_capturing_); + ConfigureIndicators(); } void UiSceneManager::ConfigureScene() { @@ -498,17 +512,22 @@ void UiSceneManager::SetAudioCapturingIndicator(bool enabled) { audio_capturing_ = enabled; - audio_capture_indicator_->set_visible(enabled && !web_vr_mode_); + ConfigureIndicators(); } void UiSceneManager::SetVideoCapturingIndicator(bool enabled) { video_capturing_ = enabled; - video_capture_indicator_->set_visible(enabled && !web_vr_mode_); + ConfigureIndicators(); } void UiSceneManager::SetScreenCapturingIndicator(bool enabled) { screen_capturing_ = enabled; - screen_capture_indicator_->set_visible(enabled && !web_vr_mode_); + ConfigureIndicators(); +} + +void UiSceneManager::SetLocationAccessIndicator(bool enabled) { + location_access_ = enabled; + ConfigureIndicators(); } void UiSceneManager::SetWebVrSecureOrigin(bool secure) { @@ -552,6 +571,13 @@ } } +void UiSceneManager::ConfigureIndicators() { + audio_capture_indicator_->set_visible(!web_vr_mode_ && audio_capturing_); + video_capture_indicator_->set_visible(!web_vr_mode_ && video_capturing_); + screen_capture_indicator_->set_visible(!web_vr_mode_ && screen_capturing_); + location_access_indicator_->set_visible(!web_vr_mode_ && location_access_); +} + void UiSceneManager::OnSecurityWarningTimer() { transient_security_warning_->set_visible(false); }
diff --git a/chrome/browser/android/vr_shell/ui_scene_manager.h b/chrome/browser/android/vr_shell/ui_scene_manager.h index 42d69ec1..6645864 100644 --- a/chrome/browser/android/vr_shell/ui_scene_manager.h +++ b/chrome/browser/android/vr_shell/ui_scene_manager.h
@@ -46,6 +46,7 @@ void SetVideoCapturingIndicator(bool enabled); void SetScreenCapturingIndicator(bool enabled); void SetAudioCapturingIndicator(bool enabled); + void SetLocationAccessIndicator(bool enabled); // These methods are currently stubbed. void SetHistoryButtonsEnabled(bool can_go_back, bool can_go_forward); @@ -70,6 +71,7 @@ void ConfigureScene(); void ConfigureSecurityWarnings(); void ConfigureTransientUrlBar(); + void ConfigureIndicators(); void UpdateBackgroundColor(); void CloseExitPrompt(); void OnSecurityWarningTimer(); @@ -98,6 +100,7 @@ UiElement* audio_capture_indicator_ = nullptr; UiElement* video_capture_indicator_ = nullptr; UiElement* screen_capture_indicator_ = nullptr; + UiElement* location_access_indicator_ = nullptr; UiElement* screen_dimmer_ = nullptr; UiElement* ceiling_ = nullptr; UiElement* floor_ = nullptr; @@ -115,6 +118,7 @@ bool audio_capturing_ = false; bool video_capturing_ = false; bool screen_capturing_ = false; + bool location_access_ = false; int next_available_id_ = 1;
diff --git a/chrome/browser/android/vr_shell/ui_scene_manager_unittest.cc b/chrome/browser/android/vr_shell/ui_scene_manager_unittest.cc index e138633..81f4ca8f 100644 --- a/chrome/browser/android/vr_shell/ui_scene_manager_unittest.cc +++ b/chrome/browser/android/vr_shell/ui_scene_manager_unittest.cc
@@ -311,6 +311,7 @@ manager_->SetAudioCapturingIndicator(true); manager_->SetVideoCapturingIndicator(true); manager_->SetScreenCapturingIndicator(true); + manager_->SetLocationAccessIndicator(true); // All elements should be hidden. VerifyElementsVisible("Elements hidden", std::set<UiElementDebugId>{}); @@ -321,6 +322,7 @@ manager_->SetAudioCapturingIndicator(true); manager_->SetVideoCapturingIndicator(true); manager_->SetScreenCapturingIndicator(true); + manager_->SetLocationAccessIndicator(true); // Transition to WebVR mode manager_->SetWebVrMode(true, false); @@ -335,31 +337,38 @@ EXPECT_FALSE(IsVisible(kAudioCaptureIndicator)); EXPECT_FALSE(IsVisible(kVideoCaptureIndicator)); EXPECT_FALSE(IsVisible(kScreenCaptureIndicator)); + EXPECT_FALSE(IsVisible(kLocationAccessIndicator)); manager_->SetAudioCapturingIndicator(true); manager_->SetVideoCapturingIndicator(true); manager_->SetScreenCapturingIndicator(true); + manager_->SetLocationAccessIndicator(true); EXPECT_TRUE(IsVisible(kAudioCaptureIndicator)); EXPECT_TRUE(IsVisible(kVideoCaptureIndicator)); EXPECT_TRUE(IsVisible(kScreenCaptureIndicator)); + EXPECT_TRUE(IsVisible(kLocationAccessIndicator)); manager_->SetWebVrMode(true, false); EXPECT_FALSE(IsVisible(kAudioCaptureIndicator)); EXPECT_FALSE(IsVisible(kVideoCaptureIndicator)); EXPECT_FALSE(IsVisible(kScreenCaptureIndicator)); + EXPECT_FALSE(IsVisible(kLocationAccessIndicator)); manager_->SetWebVrMode(false, false); EXPECT_TRUE(IsVisible(kAudioCaptureIndicator)); EXPECT_TRUE(IsVisible(kVideoCaptureIndicator)); EXPECT_TRUE(IsVisible(kScreenCaptureIndicator)); + EXPECT_TRUE(IsVisible(kLocationAccessIndicator)); manager_->SetAudioCapturingIndicator(false); manager_->SetVideoCapturingIndicator(false); manager_->SetScreenCapturingIndicator(false); + manager_->SetLocationAccessIndicator(false); EXPECT_FALSE(IsVisible(kAudioCaptureIndicator)); EXPECT_FALSE(IsVisible(kVideoCaptureIndicator)); EXPECT_FALSE(IsVisible(kScreenCaptureIndicator)); + EXPECT_FALSE(IsVisible(kLocationAccessIndicator)); } } // namespace vr_shell
diff --git a/chrome/browser/chrome_browser_main_win.cc b/chrome/browser/chrome_browser_main_win.cc index b682079c..7e747d52 100644 --- a/chrome/browser/chrome_browser_main_win.cc +++ b/chrome/browser/chrome_browser_main_win.cc
@@ -37,6 +37,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/conflicts/module_database_win.h" #include "chrome/browser/conflicts/module_event_sink_impl_win.h" +#include "chrome/browser/conflicts/shell_extension_enumerator_win.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/install_verification/win/install_verification.h" #include "chrome/browser/profiles/profile_manager.h" @@ -207,8 +208,10 @@ } // Helper function for initializing the module database subsystem. Populates -// the provided |module_watcher|. -void SetupModuleDatabase(std::unique_ptr<ModuleWatcher>* module_watcher) { +// the provided |module_watcher| and |shell_extension_enumerator|. +void SetupModuleDatabase( + std::unique_ptr<ModuleWatcher>* module_watcher, + std::unique_ptr<ShellExtensionEnumerator>* shell_extension_enumerator_) { uint64_t creation_time = 0; ModuleEventSinkImpl::GetProcessCreationTime(::GetCurrentProcess(), &creation_time); @@ -226,6 +229,9 @@ content::PROCESS_TYPE_BROWSER); *module_watcher = ModuleWatcher::Create( base::Bind(&OnModuleEvent, process_id, creation_time)); + *shell_extension_enumerator_ = base::MakeUnique<ShellExtensionEnumerator>( + base::Bind(&ModuleDatabase::OnShellExtensionEnumerated, + base::Unretained(module_database))); } } // namespace @@ -357,7 +363,7 @@ // needs to be done before any child processes are initialized as the // ModuleDatabase is an endpoint for IPC from child processes. if (base::FeatureList::IsEnabled(features::kModuleDatabase)) - SetupModuleDatabase(&module_watcher_); + SetupModuleDatabase(&module_watcher_, &shell_extension_enumerator_); } void ChromeBrowserMainPartsWin::PostBrowserStart() {
diff --git a/chrome/browser/chrome_browser_main_win.h b/chrome/browser/chrome_browser_main_win.h index 4060bde..7d0316b 100644 --- a/chrome/browser/chrome_browser_main_win.h +++ b/chrome/browser/chrome_browser_main_win.h
@@ -7,11 +7,14 @@ #ifndef CHROME_BROWSER_CHROME_BROWSER_MAIN_WIN_H_ #define CHROME_BROWSER_CHROME_BROWSER_MAIN_WIN_H_ +#include <memory> + #include "base/files/file_path_watcher.h" #include "base/macros.h" #include "chrome/browser/chrome_browser_main.h" class ModuleWatcher; +class ShellExtensionEnumerator; namespace base { class CommandLine; @@ -69,8 +72,13 @@ static void SetupInstallerUtilStrings(); private: + // Watches module load events and forwards them to the ModuleDatabase. std::unique_ptr<ModuleWatcher> module_watcher_; + // Enumerates registered shell extensions and forwards them to the + // ModuleDatabase. + std::unique_ptr<ShellExtensionEnumerator> shell_extension_enumerator_; + DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainPartsWin); };
diff --git a/chrome/browser/chromeos/login/OWNERS b/chrome/browser/chromeos/login/OWNERS index b280edc9..73d229a 100644 --- a/chrome/browser/chromeos/login/OWNERS +++ b/chrome/browser/chromeos/login/OWNERS
@@ -1,3 +1,4 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org xiyuan@chromium.org
diff --git a/chrome/browser/conflicts/module_database_win.cc b/chrome/browser/conflicts/module_database_win.cc index 263a9e2..f1433b3b 100644 --- a/chrome/browser/conflicts/module_database_win.cc +++ b/chrome/browser/conflicts/module_database_win.cc
@@ -49,7 +49,7 @@ std::unique_ptr<ModuleDatabase> module_database) { DCHECK_EQ(nullptr, g_instance); // This is deliberately leaked. It can be cleaned up by manually deleting the - // ModuleDatabase + // ModuleDatabase. g_instance = module_database.release(); } @@ -60,6 +60,15 @@ CreateProcessInfo(process_id, creation_time, process_type); } +void ModuleDatabase::OnShellExtensionEnumerated(const base::FilePath& path, + uint32_t size_of_image, + uint32_t time_date_stamp) { + DCHECK(task_runner_->RunsTasksInCurrentSequence()); + auto* module_info = + FindOrCreateModuleInfo(path, size_of_image, time_date_stamp); + module_info->second.module_types |= ModuleInfoData::kTypeShellExtension; +} + void ModuleDatabase::OnModuleLoad(uint32_t process_id, uint64_t creation_time, const base::FilePath& module_path, @@ -89,6 +98,8 @@ auto* module_info = FindOrCreateModuleInfo(module_path, module_size, module_time_date_stamp); + module_info->second.module_types |= ModuleInfoData::kTypeLoadedModule; + // Update the list of process types that this module has been seen in. module_info->second.process_types |= ProcessTypeToBit(process_info->first.process_type);
diff --git a/chrome/browser/conflicts/module_database_win.h b/chrome/browser/conflicts/module_database_win.h index 57452a5..6853cb4 100644 --- a/chrome/browser/conflicts/module_database_win.h +++ b/chrome/browser/conflicts/module_database_win.h
@@ -66,6 +66,12 @@ uint64_t creation_time, content::ProcessType process_type); + // Indicates that a new registered shell extension was found. Must be called + // in the same sequence as |task_runner_|. + void OnShellExtensionEnumerated(const base::FilePath& path, + uint32_t size_of_image, + uint32_t time_date_stamp); + // Indicates that a module has been loaded. The data passed to this function // is taken as gospel, so if it originates from a remote process it should be // independently validated first. (In practice, see ModuleEventSinkImpl for
diff --git a/chrome/browser/conflicts/module_info_win.cc b/chrome/browser/conflicts/module_info_win.cc index 91a20448..82c3b6c 100644 --- a/chrome/browser/conflicts/module_info_win.cc +++ b/chrome/browser/conflicts/module_info_win.cc
@@ -75,6 +75,7 @@ } // ModuleInspectionResult ------------------------------------------------------ + ModuleInspectionResult::ModuleInspectionResult() = default; ModuleInspectionResult::~ModuleInspectionResult() = default;
diff --git a/chrome/browser/conflicts/module_info_win.h b/chrome/browser/conflicts/module_info_win.h index 07a80e9d..cb870da5 100644 --- a/chrome/browser/conflicts/module_info_win.h +++ b/chrome/browser/conflicts/module_info_win.h
@@ -77,6 +77,14 @@ // Contains the inspection result of a module and additional information that is // useful to the ModuleDatabase. struct ModuleInfoData { + // The possible types of module we are dealing with. Used as bit set values. + + // These modules are or were loaded into one of chrome's process at some + // point. + static constexpr uint32_t kTypeLoadedModule = 1 << 0; + // These modules are registered as a shell extension. + static constexpr uint32_t kTypeShellExtension = 1 << 1; + ModuleInfoData(); ~ModuleInfoData(); @@ -86,6 +94,9 @@ // "BitIndexToProcessType" for details. uint32_t process_types; + // Set that describes the type of the module. + uint32_t module_types; + // The inspection result obtained via InspectModule(). std::unique_ptr<ModuleInspectionResult> inspection_result; };
diff --git a/chrome/browser/conflicts/shell_extension_enumerator_win.cc b/chrome/browser/conflicts/shell_extension_enumerator_win.cc new file mode 100644 index 0000000..2762919 --- /dev/null +++ b/chrome/browser/conflicts/shell_extension_enumerator_win.cc
@@ -0,0 +1,182 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/conflicts/shell_extension_enumerator_win.h" + +#include "base/files/file.h" +#include "base/memory/ref_counted.h" +#include "base/metrics/histogram_functions.h" +#include "base/strings/string16.h" +#include "base/strings/stringprintf.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/threading/thread_restrictions.h" +#include "base/win/registry.h" +#include "chrome/browser/conflicts/module_info_util_win.h" + +namespace { + +void ReadShellExtensions( + HKEY parent, + const base::Callback<void(const base::FilePath&)>& callback, + int* nb_shell_extensions) { + for (base::win::RegistryValueIterator iter( + parent, ShellExtensionEnumerator::kShellExtensionRegistryKey); + iter.Valid(); ++iter) { + base::string16 key = base::StringPrintf( + ShellExtensionEnumerator::kClassIdRegistryKeyFormat, iter.Name()); + + base::win::RegKey clsid; + if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) + continue; + + base::string16 dll; + if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) + continue; + + nb_shell_extensions++; + callback.Run(base::FilePath(dll)); + } +} + +// Helper function to get a value at a specific offset in a buffer. Also does +// bounds checking. +template <typename T> +bool GetValueAtOffset(const char* buffer, + uint64_t address, + const size_t buffer_size, + T* result) { + // Bounds checking. + if (address + sizeof(T) >= buffer_size) + return false; + + memcpy(result, &buffer[address], sizeof(T)); + return true; +} + +} // namespace + +// static +const wchar_t ShellExtensionEnumerator::kShellExtensionRegistryKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell " + L"Extensions\\Approved"; + +const wchar_t ShellExtensionEnumerator::kClassIdRegistryKeyFormat[] = + L"CLSID\\%ls\\InProcServer32"; + +ShellExtensionEnumerator::ShellExtensionEnumerator( + const OnShellExtensionEnumeratedCallback& + on_shell_extension_enumerated_callback) + : on_shell_extension_enumerated_callback_( + on_shell_extension_enumerated_callback), + weak_ptr_factory_(this) { + base::PostTaskWithTraits( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + base::Bind( + &EnumerateShellExtensionsImpl, base::SequencedTaskRunnerHandle::Get(), + base::Bind(&ShellExtensionEnumerator::OnShellExtensionEnumerated, + weak_ptr_factory_.GetWeakPtr()))); +} + +ShellExtensionEnumerator::~ShellExtensionEnumerator() = default; + +// static +void ShellExtensionEnumerator::EnumerateShellExtensionPaths( + const base::Callback<void(const base::FilePath&)>& callback) { + base::ThreadRestrictions::AssertIOAllowed(); + + int nb_shell_extensions = 0; + ReadShellExtensions(HKEY_LOCAL_MACHINE, callback, &nb_shell_extensions); + ReadShellExtensions(HKEY_CURRENT_USER, callback, &nb_shell_extensions); + + base::UmaHistogramCounts100("ThirdPartyModules.ShellExtensionsCount", + nb_shell_extensions); +} + +// static +bool ShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp( + const base::FilePath& path, + uint32_t* size_of_image, + uint32_t* time_date_stamp) { + base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ); + if (!file.IsValid()) + return false; + + // The values fetched here from the NT header live in the first 4k bytes of + // the file in a well-formed dll. + const size_t kPageSize = 4096; + + char buffer[kPageSize]; + int bytes_read = file.Read(0, buffer, kPageSize); + if (bytes_read == -1) + return false; + + // Get NT header offset. + uint64_t nt_header_offset = offsetof(IMAGE_DOS_HEADER, e_lfanew); + + LONG e_lfanew = 0; + if (!GetValueAtOffset(buffer, nt_header_offset, bytes_read, &e_lfanew)) + return false; + + // Check magic signature. + uint64_t nt_signature_offset = + e_lfanew + offsetof(IMAGE_NT_HEADERS, Signature); + + DWORD nt_signature = 0; + if (!GetValueAtOffset(buffer, nt_signature_offset, bytes_read, &nt_signature)) + return false; + + if (nt_signature != IMAGE_NT_SIGNATURE) + return false; + + // Get SizeOfImage. + uint64_t size_of_image_offset = e_lfanew + + offsetof(IMAGE_NT_HEADERS, OptionalHeader) + + offsetof(IMAGE_OPTIONAL_HEADER, SizeOfImage); + if (!GetValueAtOffset(buffer, size_of_image_offset, bytes_read, + size_of_image)) + return false; + + // Get TimeDateStamp. + uint64_t time_date_stamp_offset = e_lfanew + + offsetof(IMAGE_NT_HEADERS, FileHeader) + + offsetof(IMAGE_FILE_HEADER, TimeDateStamp); + return GetValueAtOffset(buffer, time_date_stamp_offset, bytes_read, + time_date_stamp); +} + +void ShellExtensionEnumerator::OnShellExtensionEnumerated( + const base::FilePath& path, + uint32_t size_of_image, + uint32_t time_date_stamp) { + on_shell_extension_enumerated_callback_.Run(path, size_of_image, + time_date_stamp); +} + +// static +void ShellExtensionEnumerator::EnumerateShellExtensionsImpl( + scoped_refptr<base::SequencedTaskRunner> task_runner, + const OnShellExtensionEnumeratedCallback& callback) { + ShellExtensionEnumerator::EnumerateShellExtensionPaths( + base::Bind(&OnShellExtensionPathEnumerated, task_runner, callback)); +} + +// static +void ShellExtensionEnumerator::OnShellExtensionPathEnumerated( + scoped_refptr<base::SequencedTaskRunner> task_runner, + const OnShellExtensionEnumeratedCallback& callback, + const base::FilePath& path) { + uint32_t size_of_image = 0; + uint32_t time_date_stamp = 0; + if (!ShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp( + path, &size_of_image, &time_date_stamp)) { + return; + } + + task_runner->PostTask( + FROM_HERE, base::Bind(callback, path, size_of_image, time_date_stamp)); +}
diff --git a/chrome/browser/conflicts/shell_extension_enumerator_win.h b/chrome/browser/conflicts/shell_extension_enumerator_win.h new file mode 100644 index 0000000..28b1746c --- /dev/null +++ b/chrome/browser/conflicts/shell_extension_enumerator_win.h
@@ -0,0 +1,68 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CONFLICTS_SHELL_EXTENSION_ENUMERATOR_WIN_H_ +#define CHROME_BROWSER_CONFLICTS_SHELL_EXTENSION_ENUMERATOR_WIN_H_ + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" + +namespace base { +class SequencedTaskRunner; +} + +// Finds shell extensions installed on the computer by enumerating the registry. +class ShellExtensionEnumerator { + public: + // The path to the registry key where shell extensions are registered. + static const wchar_t kShellExtensionRegistryKey[]; + static const wchar_t kClassIdRegistryKeyFormat[]; + + using OnShellExtensionEnumeratedCallback = + base::Callback<void(const base::FilePath&, uint32_t, uint32_t)>; + + explicit ShellExtensionEnumerator(const OnShellExtensionEnumeratedCallback& + on_shell_extension_enumerated_callback); + ~ShellExtensionEnumerator(); + + // Enumerates registered shell extensions, and invokes |callback| once per + // shell extension found. Must be called on a blocking sequence. + // + // TODO(pmonette): Move this function to protected when + // enumerate_modules_model.cc gets deleted. + static void EnumerateShellExtensionPaths( + const base::Callback<void(const base::FilePath&)>& callback); + + protected: + // Reads the file on disk to find out the SizeOfImage and TimeDateStamp + // properties of the module. Returns false on error. + static bool GetModuleImageSizeAndTimeDateStamp(const base::FilePath& path, + uint32_t* size_of_image, + uint32_t* time_date_stamp); + + private: + void OnShellExtensionEnumerated(const base::FilePath& path, + uint32_t size_of_image, + uint32_t time_date_stamp); + + static void EnumerateShellExtensionsImpl( + scoped_refptr<base::SequencedTaskRunner> task_runner, + const OnShellExtensionEnumeratedCallback& callback); + + static void OnShellExtensionPathEnumerated( + scoped_refptr<base::SequencedTaskRunner> task_runner, + const OnShellExtensionEnumeratedCallback& callback, + const base::FilePath& path); + + OnShellExtensionEnumeratedCallback on_shell_extension_enumerated_callback_; + + base::WeakPtrFactory<ShellExtensionEnumerator> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ShellExtensionEnumerator); +}; + +#endif // CHROME_BROWSER_CONFLICTS_SHELL_EXTENSION_ENUMERATOR_WIN_H_
diff --git a/chrome/browser/conflicts/shell_extension_enumerator_win_unittest.cc b/chrome/browser/conflicts/shell_extension_enumerator_win_unittest.cc new file mode 100644 index 0000000..a65bf9f --- /dev/null +++ b/chrome/browser/conflicts/shell_extension_enumerator_win_unittest.cc
@@ -0,0 +1,216 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/conflicts/shell_extension_enumerator_win.h" + +#include <windows.h> + +#include <iostream> +#include <tuple> +#include <vector> + +#include "base/bind.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/path_service.h" +#include "base/scoped_native_library.h" +#include "base/stl_util.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/test/scoped_task_environment.h" +#include "base/test/test_reg_util_win.h" +#include "base/win/pe_image.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +class TestShellExtensionEnumerator : ShellExtensionEnumerator { + public: + using ShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp; +}; + +class ShellExtensionEnumeratorTest : public testing::Test { + public: + ShellExtensionEnumeratorTest() : shell_extension_count_(0) {} + + ~ShellExtensionEnumeratorTest() override = default; + + // Override all registry hives so that real shell extensions don't mess up + // the unit tests. + void OverrideRegistryHives() { + registry_override_manager_.OverrideRegistry(HKEY_CLASSES_ROOT); + registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER); + registry_override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE); + } + + void OnShellExtensionEnumerated(const base::FilePath& path, + uint32_t size_of_image, + uint32_t time_date_stamp) { + shell_extension_count_++; + } + + int shell_extension_count() { return shell_extension_count_; } + + void RunUntilIdle() { scoped_task_environment_.RunUntilIdle(); } + + private: + base::test::ScopedTaskEnvironment scoped_task_environment_; + + registry_util::RegistryOverrideManager registry_override_manager_; + + // Counts the number of shell extensions found via enumeration. + int shell_extension_count_; +}; + +// Adds a fake shell extension entry to the registry that should be found by +// the ShellExtensionEnumerator. +void RegisterFakeShellExtension(HKEY key, + const wchar_t* guid, + const wchar_t* path) { + base::win::RegKey class_id( + HKEY_CLASSES_ROOT, + base::StringPrintf(ShellExtensionEnumerator::kClassIdRegistryKeyFormat, + guid) + .c_str(), + KEY_WRITE); + class_id.WriteValue(nullptr, path); + + base::win::RegKey registration( + key, ShellExtensionEnumerator::kShellExtensionRegistryKey, KEY_WRITE); + registration.WriteValue(guid, L""); +} + +void OnShellExtensionPathEnumerated( + std::vector<base::FilePath>* shell_extension_paths, + const base::FilePath& path) { + shell_extension_paths->push_back(path); +} + +// Creates a truncated copy of the current executable at |location| path to +// mimic a module with an invalid NT header. +bool CreateTruncatedModule(const base::FilePath& location) { + base::FilePath file_exe_path; + if (!base::PathService::Get(base::FILE_EXE, &file_exe_path)) + return false; + + base::File file_exe(file_exe_path, + base::File::FLAG_OPEN | base::File::FLAG_READ); + if (!file_exe.IsValid()) + return false; + + const size_t kSizeOfTruncatedDll = 256; + char buffer[kSizeOfTruncatedDll]; + if (file_exe.Read(0, buffer, kSizeOfTruncatedDll) != kSizeOfTruncatedDll) + return false; + + base::File target_file(location, + base::File::FLAG_CREATE | base::File::FLAG_WRITE); + if (!target_file.IsValid()) + return false; + + return target_file.Write(0, buffer, kSizeOfTruncatedDll) == + kSizeOfTruncatedDll; +} + +} // namespace + +// Registers a few fake shell extensions then see if +// EnumerateShellExtensionPaths() finds them. +TEST_F(ShellExtensionEnumeratorTest, EnumerateShellExtensionPaths) { + const std::tuple<HKEY, const wchar_t*, const wchar_t*> test_cases[] = { + {HKEY_CURRENT_USER, L"{FAKE_GUID_0001}", L"c:\\module.dll"}, + {HKEY_LOCAL_MACHINE, L"{FAKE_GUID_0002}", L"c:\\dir\\shell_ext.dll"}, + {HKEY_LOCAL_MACHINE, L"{FAKE_GUID_0003}", L"c:\\path\\test.dll"}, + }; + + OverrideRegistryHives(); + + // Register all fake shell extensions in test_cases. + for (const auto& test_case : test_cases) { + RegisterFakeShellExtension(std::get<0>(test_case), std::get<1>(test_case), + std::get<2>(test_case)); + } + + std::vector<base::FilePath> shell_extension_paths; + ShellExtensionEnumerator::EnumerateShellExtensionPaths( + base::Bind(&OnShellExtensionPathEnumerated, + base::Unretained(&shell_extension_paths))); + + ASSERT_EQ(3u, shell_extension_paths.size()); + for (size_t i = 0; i < arraysize(test_cases); i++) { + // The inefficiency is fine as long as the number of test cases stay small. + EXPECT_TRUE(base::ContainsValue( + shell_extension_paths, base::FilePath(std::get<2>(test_cases[i])))); + } +} + +// Tests that GetModuleImageSizeAndTimeDateStamp() returns the same information +// from a module that has been loaded in memory. +TEST_F(ShellExtensionEnumeratorTest, GetModuleImageSizeAndTimeDateStamp) { + // Use the current exe file as an arbitrary module that exists. + base::FilePath file_exe; + ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &file_exe)); + + // Read the values from the loaded module. + base::ScopedNativeLibrary scoped_loaded_module(file_exe); + base::win::PEImage pe_image(scoped_loaded_module.get()); + IMAGE_NT_HEADERS* nt_headers = pe_image.GetNTHeaders(); + + // Read the values from the module on disk. + uint32_t size_of_image = 0; + uint32_t time_date_stamp = 0; + EXPECT_TRUE(TestShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp( + file_exe, &size_of_image, &time_date_stamp)); + + EXPECT_EQ(nt_headers->OptionalHeader.SizeOfImage, size_of_image); + EXPECT_EQ(nt_headers->FileHeader.TimeDateStamp, time_date_stamp); +} + +TEST_F(ShellExtensionEnumeratorTest, EnumerateShellExtensions) { + OverrideRegistryHives(); + + // Use the current exe file as an arbitrary module that exists. + base::FilePath file_exe; + ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &file_exe)); + RegisterFakeShellExtension(HKEY_LOCAL_MACHINE, L"{FAKE_GUID}", + file_exe.value().c_str()); + EXPECT_EQ(0, shell_extension_count()); + + ShellExtensionEnumerator shell_extension_enumerator( + base::Bind(&ShellExtensionEnumeratorTest::OnShellExtensionEnumerated, + base::Unretained(this))); + + RunUntilIdle(); + + EXPECT_EQ(1, shell_extension_count()); +} + +TEST_F(ShellExtensionEnumeratorTest, NonexistentDll) { + base::ScopedTempDir scoped_temp_dir; + EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + + base::FilePath nonexistant_dll = + scoped_temp_dir.GetPath().Append(L"nonexistant.dll"); + + uint32_t size_of_image = 0; + uint32_t time_date_stamp = 0; + EXPECT_FALSE(TestShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp( + nonexistant_dll, &size_of_image, &time_date_stamp)); +} + +TEST_F(ShellExtensionEnumeratorTest, InvalidNTHeader) { + base::ScopedTempDir scoped_temp_dir; + EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir()); + + base::FilePath invalid_dll = + scoped_temp_dir.GetPath().Append(L"truncated.dll"); + ASSERT_TRUE(CreateTruncatedModule(invalid_dll)); + + uint32_t size_of_image = 0; + uint32_t time_date_stamp = 0; + EXPECT_FALSE(TestShellExtensionEnumerator::GetModuleImageSizeAndTimeDateStamp( + invalid_dll, &size_of_image, &time_date_stamp)); +}
diff --git a/chrome/browser/download/download_path_reservation_tracker.cc b/chrome/browser/download/download_path_reservation_tracker.cc index c3373d5..9c86144 100644 --- a/chrome/browser/download/download_path_reservation_tracker.cc +++ b/chrome/browser/download/download_path_reservation_tracker.cc
@@ -17,9 +17,12 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" +#include "base/sequenced_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/task_runner_util.h" +#include "base/task_scheduler/post_task.h" #include "base/third_party/icu/icu_utf.h" #include "build/build_config.h" #include "chrome/common/chrome_paths.h" @@ -82,7 +85,6 @@ // Returns true if the given path is in use by a path reservation. bool IsPathReserved(const base::FilePath& path) { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); // No reservation map => no reservations. if (g_reservation_map == NULL) return false; @@ -99,9 +101,9 @@ } // Returns true if the given path is in use by any path reservation or the -// file system. Called on the FILE thread. +// file system. Called on the task runner returned by +// DownloadPathReservationTracker::GetTaskRunner(). bool IsPathInUse(const base::FilePath& path) { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); // If there is a reservation, then the path is in use. if (IsPathReserved(path)) return true; @@ -245,7 +247,9 @@ return PathValidationResult::SUCCESS; } -// Called on the FILE thread to reserve a download path. This method: +// Called on the task runner returned by +// DownloadPathReservationTracker::GetTaskRunner() to reserve a download path. +// This method: // - Creates directory |default_download_path| if it doesn't exist. // - Verifies that the parent directory of |suggested_path| exists and is // writeable. @@ -256,7 +260,6 @@ // - Returns the result of creating the path reservation. PathValidationResult CreateReservation(const CreateReservationInfo& info, base::FilePath* reserved_path) { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); DCHECK(info.suggested_path.IsAbsolute()); // Create a reservation map if one doesn't exist. It will be automatically @@ -295,17 +298,16 @@ return result; } -// Called on the FILE thread to update the path of the reservation associated -// with |key| to |new_path|. +// Called on a background thread to update the path of the reservation +// associated with |key| to |new_path|. void UpdateReservation(ReservationKey key, const base::FilePath& new_path) { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); DCHECK(g_reservation_map != NULL); ReservationMap::iterator iter = g_reservation_map->find(key); if (iter != g_reservation_map->end()) { iter->second = new_path; } else { // This would happen if an UpdateReservation() notification was scheduled on - // the FILE thread before ReserveInternal(), or after a Revoke() + // the SequencedTaskRunner before ReserveInternal(), or after a Revoke() // call. Neither should happen. NOTREACHED(); } @@ -314,7 +316,6 @@ // Called on the FILE thread to remove the path reservation associated with // |key|. void RevokeReservation(ReservationKey key) { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); DCHECK(g_reservation_map != NULL); DCHECK(base::ContainsKey(*g_reservation_map, key)); g_reservation_map->erase(key); @@ -354,8 +355,8 @@ // Update the reservation. base::FilePath new_target_path = download->GetTargetFilePath(); if (new_target_path != last_target_path_) { - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + DownloadPathReservationTracker::GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&UpdateReservation, download, new_target_path)); last_target_path_ = new_target_path; } @@ -374,9 +375,8 @@ // The download filename will need to be re-generated when the download is // restarted. Holding on to the reservation now would prevent the name // from being used for a subsequent retry attempt. - - BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, - base::BindOnce(&RevokeReservation, download)); + DownloadPathReservationTracker::GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&RevokeReservation, download)); download->RemoveUserData(&kUserDataKey); break; @@ -389,8 +389,8 @@ void DownloadItemObserver::OnDownloadDestroyed(DownloadItem* download) { // Items should be COMPLETE/INTERRUPTED/CANCELLED before being destroyed. NOTREACHED(); - BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, - base::BindOnce(&RevokeReservation, download)); + DownloadPathReservationTracker::GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&RevokeReservation, download)); } // static @@ -424,11 +424,11 @@ conflict_action, callback}; - BrowserThread::PostTaskAndReplyWithResult( - BrowserThread::FILE, FROM_HERE, - base::Bind(&CreateReservation, info, reserved_path), - base::Bind(&RunGetReservedPathCallback, callback, - base::Owned(reserved_path))); + base::PostTaskAndReplyWithResult( + GetTaskRunner().get(), FROM_HERE, + base::BindOnce(&CreateReservation, info, reserved_path), + base::BindOnce(&RunGetReservedPathCallback, callback, + base::Owned(reserved_path))); } // static @@ -436,3 +436,17 @@ const base::FilePath& path) { return IsPathInUse(path); } + +// static +scoped_refptr<base::SequencedTaskRunner> +DownloadPathReservationTracker::GetTaskRunner() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + static scoped_refptr<base::SequencedTaskRunner>* task_runner = nullptr; + + if (!task_runner) { + task_runner = new scoped_refptr<base::SequencedTaskRunner>( + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + } + + return *task_runner; +}
diff --git a/chrome/browser/download/download_path_reservation_tracker.h b/chrome/browser/download/download_path_reservation_tracker.h index d13d845..74f2ea4 100644 --- a/chrome/browser/download/download_path_reservation_tracker.h +++ b/chrome/browser/download/download_path_reservation_tracker.h
@@ -6,9 +6,11 @@ #define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PATH_RESERVATION_TRACKER_H_ #include "base/callback_forward.h" +#include "base/memory/ref_counted.h" namespace base { class FilePath; +class SequencedTaskRunner; } namespace content { @@ -59,8 +61,8 @@ // reservation that will live until |download_item| is interrupted, cancelled, // completes or is removed. This method will not modify |download_item|. // - // The process of issuing a reservation happens on the FILE thread, and - // involves: + // The process of issuing a reservation happens on the task runner returned by + // DownloadPathReservationTracker::GetTaskRunner(), and involves: // // - Creating |requested_target_path.DirName()| if it doesn't already exist // and either |create_directory| or |requested_target_path.DirName() == @@ -101,8 +103,12 @@ const ReservedPathCallback& callback); // Returns true if |path| is in use by an existing path reservation. Should - // only be called on the FILE thread. Currently only used by tests. + // only be called on the task runner returned by + // DownloadPathReservationTracker::GetTaskRunner(). Currently only used by + // tests. static bool IsPathInUseForTesting(const base::FilePath& path); + + static scoped_refptr<base::SequencedTaskRunner> GetTaskRunner(); }; #endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_PATH_RESERVATION_TRACKER_H_
diff --git a/chrome/browser/download/download_path_reservation_tracker_unittest.cc b/chrome/browser/download/download_path_reservation_tracker_unittest.cc index e55f9216..6b6fe619 100644 --- a/chrome/browser/download/download_path_reservation_tracker_unittest.cc +++ b/chrome/browser/download/download_path_reservation_tracker_unittest.cc
@@ -20,6 +20,7 @@ #include "chrome/browser/download/download_target_determiner.h" #include "content/public/test/mock_download_item.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" #include "net/base/filename_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -72,7 +73,6 @@ private: void TestReservedPathCallback(base::FilePath* return_path, PathValidationResult* return_result, - const base::Closure& quit_closure, PathValidationResult result, const base::FilePath& path); }; @@ -86,7 +86,7 @@ } void DownloadPathReservationTrackerTest::TearDown() { - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); } MockDownloadItem* DownloadPathReservationTrackerTest::CreateDownloadItem( @@ -109,6 +109,7 @@ bool DownloadPathReservationTrackerTest::IsPathInUse( const base::FilePath& path) { + content::RunAllBlockingPoolTasksUntilIdle(); return DownloadPathReservationTracker::IsPathInUseForTesting(path); } @@ -123,25 +124,21 @@ // function has returned. base::WeakPtrFactory<DownloadPathReservationTrackerTest> weak_ptr_factory( this); - base::RunLoop run_loop; DownloadPathReservationTracker::GetReservedPath( download_item, target_path, default_download_path(), create_directory, conflict_action, base::Bind(&DownloadPathReservationTrackerTest::TestReservedPathCallback, - weak_ptr_factory.GetWeakPtr(), return_path, return_result, - run_loop.QuitClosure())); - run_loop.Run(); + weak_ptr_factory.GetWeakPtr(), return_path, return_result)); + content::RunAllBlockingPoolTasksUntilIdle(); } void DownloadPathReservationTrackerTest::TestReservedPathCallback( base::FilePath* return_path, PathValidationResult* return_result, - const base::Closure& quit_closure, PathValidationResult result, const base::FilePath& path) { *return_path = path; *return_result = result; - quit_closure.Run(); } base::FilePath @@ -182,7 +179,7 @@ // Destroying the item should release the reservation. SetDownloadItemState(item.get(), DownloadItem::COMPLETE); item.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(IsPathInUse(path)); } @@ -206,7 +203,7 @@ // Once the download is interrupted, the path should become available again. SetDownloadItemState(item.get(), DownloadItem::INTERRUPTED); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(IsPathInUse(path)); } @@ -233,7 +230,7 @@ // The path wouldn't be available since it is occupied on disk by the // completed download. SetDownloadItemState(item.get(), DownloadItem::COMPLETE); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(IsPathInUse(path)); } @@ -270,7 +267,7 @@ SetDownloadItemState(item.get(), DownloadItem::COMPLETE); item.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_TRUE(IsPathInUse(path)); EXPECT_FALSE(IsPathInUse(reserved_path)); } @@ -299,7 +296,7 @@ SetDownloadItemState(item.get(), DownloadItem::COMPLETE); item.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); } // If the source is a file:// URL that is in the download directory, then Chrome @@ -324,7 +321,7 @@ SetDownloadItemState(item.get(), DownloadItem::COMPLETE); item.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); } // Multiple reservations for the same path should uniquify around each other. @@ -360,7 +357,7 @@ EXPECT_EQ(uniquified_path.value(), reserved_path2.value()); SetDownloadItemState(item2.get(), DownloadItem::COMPLETE); } - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_TRUE(IsPathInUse(path)); EXPECT_FALSE(IsPathInUse(uniquified_path)); @@ -376,7 +373,7 @@ EXPECT_EQ(uniquified_path.value(), reserved_path2.value()); SetDownloadItemState(item2.get(), DownloadItem::COMPLETE); } - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); // Now acquire an overwriting reservation. We should end up with the same // non-uniquified path for both reservations. @@ -562,7 +559,7 @@ // this state, we shouldn't lose the reservation. ASSERT_EQ(base::FilePath::StringType(), item->GetTargetFilePath().value()); item->NotifyObserversDownloadUpdated(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_TRUE(IsPathInUse(path)); // If the target path changes, we should update the reservation to match. @@ -572,14 +569,14 @@ EXPECT_CALL(*item, GetTargetFilePath()) .WillRepeatedly(ReturnRef(new_target_path)); item->NotifyObserversDownloadUpdated(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(IsPathInUse(path)); EXPECT_TRUE(IsPathInUse(new_target_path)); // Destroying the item should release the reservation. SetDownloadItemState(item.get(), DownloadItem::COMPLETE); item.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(IsPathInUse(new_target_path)); }
diff --git a/chrome/browser/resources/chromeos/chromevox/.eslintrc.js b/chrome/browser/resources/chromeos/chromevox/.eslintrc.js index 06b7bfc..edc99c05 100644 --- a/chrome/browser/resources/chromeos/chromevox/.eslintrc.js +++ b/chrome/browser/resources/chromeos/chromevox/.eslintrc.js
@@ -5,7 +5,7 @@ module.exports = { 'env': { 'browser': true, - 'es6': true + 'es6': true, }, 'rules': { // Override restrictions for document.getElementById usage since,
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_display_manager.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_display_manager.js index f16f9e7..430114a 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_display_manager.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_display_manager.js
@@ -37,8 +37,7 @@ * @type {!cvox.ExpandingBrailleTranslator.ExpansionType} valueExpansion * @private */ - this.expansionType_ = - cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION; + this.expansionType_ = cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION; /** * @type {cvox.PanStrategy} * @private @@ -57,8 +56,7 @@ * @type {!cvox.BrailleDisplayState} * @private */ - this.displayState_ = {available: false, textRowCount: 0, - textColumnCount: 0}; + this.displayState_ = {available: false, textRowCount: 0, textColumnCount: 0}; /** * State reported from the chrome api, reflecting a real hardware * display. @@ -75,8 +73,9 @@ if (area == 'local' && 'brailleWordWrap' in changes) { this.updatePanStrategy_(changes.brailleWordWrap.newValue); } - if (area == 'local' && ('virtualBrailleRows' in changes || - 'virtualBrailleColumns' in changes)) { + if (area == 'local' && + ('virtualBrailleRows' in changes || + 'virtualBrailleColumns' in changes)) { this.onCaptionsStateChanged_(); } }.bind(this)); @@ -84,8 +83,8 @@ this.updatePanStrategy_(items.brailleWordWrap); }.bind(this)); - cvox.BrailleCaptionsBackground.init(goog.bind( - this.onCaptionsStateChanged_, this)); + cvox.BrailleCaptionsBackground.init( + goog.bind(this.onCaptionsStateChanged_, this)); if (goog.isDef(chrome.brailleDisplayPrivate)) { var onDisplayStateChanged = goog.bind(this.refreshDisplayState_, this); chrome.brailleDisplayPrivate.getDisplayState(onDisplayStateChanged); @@ -175,7 +174,7 @@ var imageDataUrl = imageUrl; var imgElement = document.createElement('img'); imgElement.src = imageDataUrl; - imgElement.onload = (function() { + imgElement.onload = function() { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = columns * cellWidth; @@ -192,18 +191,17 @@ var green = data[i + 1]; var blue = data[i + 2]; var alpha = data[i + 3]; - var luminance = - 0.2126 * red + - 0.7152 * green + - 0.0722 * blue; + var luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue; // Show braille pin if the alpha is greater than the threshold and // the luminance is less than the threshold. - var show = (alpha >= cvox.BrailleDisplayManager.ALPHA_THRESHOLD_ && - luminance < cvox.BrailleDisplayManager.LUMINANCE_THRESHOLD_); + var show = + (alpha >= cvox.BrailleDisplayManager.ALPHA_THRESHOLD_ && + luminance < cvox.BrailleDisplayManager.LUMINANCE_THRESHOLD_); outputData.push(show); } - // Convert black-and-white array to the proper encoding for Braille cells. + // Convert black-and-white array to the proper encoding for Braille + // cells. var brailleBuf = new ArrayBuffer(rows * columns); var view = new Uint8Array(brailleBuf); for (var i = 0; i < rows; i++) { @@ -213,12 +211,12 @@ for (var cellColumn = 0; cellColumn < cellWidth; cellColumn++) { for (var cellRow = 0; cellRow < cellHeight; cellRow++) { var bitmapIndex = - (i * columns * cellHeight + j + cellRow * columns) * cellWidth - + cellColumn; + (i * columns * cellHeight + j + cellRow * columns) * cellWidth + + cellColumn; if (outputData[bitmapIndex]) { view[brailleIndex] += - cvox.BrailleDisplayManager.COORDS_TO_BRAILLE_DOT_[ - cellColumn * maxCellHeight + cellRow]; + cvox.BrailleDisplayManager.COORDS_TO_BRAILLE_DOT_ + [cellColumn * maxCellHeight + cellRow]; } } } @@ -227,15 +225,13 @@ if (this.realDisplayState_.available) { chrome.brailleDisplayPrivate.writeDots( - brailleBuf, - this.displayState_.textColumnCount, + brailleBuf, this.displayState_.textColumnCount, this.displayState_.textRowCount); } if (cvox.BrailleCaptionsBackground.isEnabled()) { - cvox.BrailleCaptionsBackground.setImageContent( - brailleBuf, rows, columns); + cvox.BrailleCaptionsBackground.setImageContent(brailleBuf, rows, columns); } - }).bind(this); + }.bind(this); }; @@ -268,8 +264,7 @@ * some fields to be undefined, while cvox.BrailleDisplayState does not. * @private */ -cvox.BrailleDisplayManager.prototype.refreshDisplayState_ = function( - newState) { +cvox.BrailleDisplayManager.prototype.refreshDisplayState_ = function(newState) { var oldColumnCount = this.displayState_.textColumnCount || 0; var oldRowCount = this.displayState_.textRowCount || 0; var processDisplayState = function(displayState) { @@ -321,13 +316,14 @@ var brailleBuf = this.panStrategy_.getCurrentBrailleViewportContents(); var textBuf = this.panStrategy_.getCurrentTextViewportContents(); if (this.realDisplayState_.available) { - chrome.brailleDisplayPrivate.writeDots(brailleBuf, - brailleBuf.byteLength, 1); + chrome.brailleDisplayPrivate.writeDots( + brailleBuf, brailleBuf.byteLength, 1); } if (cvox.BrailleCaptionsBackground.isEnabled()) { - cvox.BrailleCaptionsBackground.setContent(textBuf, brailleBuf, - this.panStrategy_.brailleToText, this.panStrategy_.offsetsForSlices, - this.displayState_.textRowCount, this.displayState_.textColumnCount); + cvox.BrailleCaptionsBackground.setContent( + textBuf, brailleBuf, this.panStrategy_.brailleToText, + this.panStrategy_.offsetsForSlices, this.displayState_.textRowCount, + this.displayState_.textColumnCount); } }; @@ -374,8 +370,8 @@ } else { targetPosition = 0; } - this.panStrategy_.setContent(this.content_.text.toString(), - cells, brailleToText, targetPosition); + this.panStrategy_.setContent( + this.content_.text.toString(), cells, brailleToText, targetPosition); this.refresh_(); }.bind(this); @@ -385,9 +381,7 @@ writeTranslatedContent(new ArrayBuffer(0), [], []); } else { translator.translate( - newContent.text, - newExpansionType, - writeTranslatedContent); + newContent.text, newExpansionType, writeTranslatedContent); } }; @@ -406,9 +400,10 @@ break; case cvox.BrailleKeyCommand.ROUTING: event.displayPosition = this.brailleToTextPosition_( - event.displayPosition + this.panStrategy_.viewPort.firstRow * - this.panStrategy_.displaySize.columns); - // fall through + event.displayPosition + + this.panStrategy_.viewPort.firstRow * + this.panStrategy_.displaySize.columns); + // fall through default: this.commandListener_(event, this.content_); break; @@ -426,9 +421,8 @@ if (this.panStrategy_.previous()) { this.refresh_(); } else { - this.commandListener_({ - command: cvox.BrailleKeyCommand.PAN_LEFT - }, this.content_); + this.commandListener_( + {command: cvox.BrailleKeyCommand.PAN_LEFT}, this.content_); } }; @@ -443,9 +437,8 @@ if (this.panStrategy_.next()) { this.refresh_(); } else { - this.commandListener_({ - command: cvox.BrailleKeyCommand.PAN_RIGHT - }, this.content_); + this.commandListener_( + {command: cvox.BrailleKeyCommand.PAN_RIGHT}, this.content_); } }; @@ -482,8 +475,8 @@ * the translated content. * @return {number} The mapped position in code units. */ -cvox.BrailleDisplayManager.prototype.brailleToTextPosition_ = - function(braillePosition) { +cvox.BrailleDisplayManager.prototype.brailleToTextPosition_ = function( + braillePosition) { var mapping = this.panStrategy_.brailleToText; if (braillePosition < 0) { // This shouldn't happen.
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_input_handler.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_input_handler.js index 2f06fb84..fcfec6f 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_input_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_input_handler.js
@@ -93,8 +93,7 @@ * @const {string} * @private */ -cvox.BrailleInputHandler.IME_EXTENSION_ID_ = - 'jddehjeebkoimngcbdkaahpobgicbffp'; +cvox.BrailleInputHandler.IME_EXTENSION_ID_ = 'jddehjeebkoimngcbdkaahpobgicbffp'; /** * Name of the port to use for communicating with the Braille IME. @@ -175,13 +174,12 @@ */ onBrailleKeyEvent: function(event) { if (event.command === cvox.BrailleKeyCommand.DOTS) - return this.onBrailleDots_(/** @type {number} */(event.brailleDots)); + return this.onBrailleDots_(/** @type {number} */ (event.brailleDots)); // Any other braille command cancels the pending cells. this.pendingCells_.length = 0; if (event.command === cvox.BrailleKeyCommand.STANDARD_KEY) { - if (event.standardKeyCode === 'Backspace' && - !event.altKey && !event.ctrlKey && !event.shiftKey && - this.onBackspace_()) { + if (event.standardKeyCode === 'Backspace' && !event.altKey && + !event.ctrlKey && !event.shiftKey && this.onBackspace_()) { return true; } else { this.commitAndClearEntryState_(); @@ -203,7 +201,7 @@ return cvox.ExpandingBrailleTranslator.ExpansionType.ALL; if (this.entryState_ && this.entryState_.translator === - this.translatorManager_.getDefaultTranslator()) { + this.translatorManager_.getDefaultTranslator()) { return cvox.ExpandingBrailleTranslator.ExpansionType.NONE; } return cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION; @@ -348,8 +346,8 @@ */ onImeMessage_: function(message) { if (!goog.isObject(message)) { - console.error('Unexpected message from Braille IME: ', - JSON.stringify(message)); + console.error( + 'Unexpected message from Braille IME: ', JSON.stringify(message)); } switch (message.type) { case 'activeState': @@ -369,17 +367,19 @@ // Note that we can't send the backspace key through the // virtualKeyboardPrivate API in this case because it would then be // processed by the IME again, leading to an infinite loop. - this.postImeMessage_( - {type: 'keyEventHandled', requestId: message['requestId'], - result: this.onBackspace_()}); + this.postImeMessage_({ + type: 'keyEventHandled', + requestId: message['requestId'], + result: this.onBackspace_() + }); break; case 'reset': this.clearEntryState_(); break; default: - console.error('Unexpected message from Braille IME: ', - JSON.stringify(message)); - break; + console.error( + 'Unexpected message from Braille IME: ', JSON.stringify(message)); + break; } }, @@ -431,8 +431,7 @@ charValue: cvox.BrailleKeyEvent.keyCodeToCharValue(keyName), // See chrome/common/extensions/api/virtual_keyboard_private.json for // these constants. - modifiers: (event.shiftKey ? 2 : 0) | - (event.ctrlKey ? 4 : 0) | + modifiers: (event.shiftKey ? 2 : 0) | (event.ctrlKey ? 4 : 0) | (event.altKey ? 8 : 0) }; chrome.virtualKeyboardPrivate.sendKeyEvent(keyEvent); @@ -544,8 +543,7 @@ * Makes sure the current text is permanently added to the edit field. * After this call, this object should be abandoned. */ - commit: function() { - }, + commit: function() {}, /** * @return {boolean} true if the entry state uses uncommitted cells. @@ -592,8 +590,7 @@ * @param {string} newText Text to send. * @private */ - sendTextChange_: function(newText) { - } + sendTextChange_: function(newText) {} }; /** @@ -605,8 +602,7 @@ * @extends {cvox.BrailleInputHandler.EntryState_} * @private */ -cvox.BrailleInputHandler.EditsEntryState_ = function( - inputHandler, translator) { +cvox.BrailleInputHandler.EditsEntryState_ = function(inputHandler, translator) { cvox.BrailleInputHandler.EntryState_.call(this, inputHandler, translator); }; @@ -617,8 +613,8 @@ sendTextChange_: function(newText) { var oldText = this.text_; // Find the common prefix of the old and new text. - var commonPrefixLength = StringUtil.longestCommonPrefixLength( - oldText, newText); + var commonPrefixLength = + StringUtil.longestCommonPrefixLength(oldText, newText); // How many characters we need to delete from the existing text to replace // them with characters from the new text. var deleteLength = oldText.length - commonPrefixLength; @@ -640,11 +636,12 @@ this.pendingTextsBefore_.push(textBeforeAfterDelete + toInsert); } // Send the replace operation to be performed asynchronously by the IME. - this.inputHandler_.postImeMessage_( - {type: 'replaceText', - contextID: this.inputHandler_.inputContext_.contextID, - deleteBefore: deleteLength, - newText: toInsert}); + this.inputHandler_.postImeMessage_({ + type: 'replaceText', + contextID: this.inputHandler_.inputContext_.contextID, + deleteBefore: deleteLength, + newText: toInsert + }); } } }; @@ -669,9 +666,10 @@ /** @override */ commit: function() { - this.inputHandler_.postImeMessage_( - {type: 'commitUncommitted', - contextID: this.inputHandler_.inputContext_.contextID}); + this.inputHandler_.postImeMessage_({ + type: 'commitUncommitted', + contextID: this.inputHandler_.inputContext_.contextID + }); }, /** @override */ @@ -681,9 +679,10 @@ /** @override */ sendTextChange_: function(newText) { - this.inputHandler_.postImeMessage_( - {type: 'setUncommitted', - contextID: this.inputHandler_.inputContext_.contextID, - text: newText}); + this.inputHandler_.postImeMessage_({ + type: 'setUncommitted', + contextID: this.inputHandler_.inputContext_.contextID, + text: newText + }); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_key_event_rewriter.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_key_event_rewriter.js index 30f148cf..09364d7 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_key_event_rewriter.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_key_event_rewriter.js
@@ -58,8 +58,7 @@ // previous incremental key press. if (evt.command == cvox.BrailleKeyCommand.DOTS && this.incrementalKey_) { // Check if this braille pattern has a standard key mapping. - standardKeyCode = - cvox.BrailleKeyEvent.brailleDotsToStandardKeyCode[dots]; + standardKeyCode = cvox.BrailleKeyEvent.brailleDotsToStandardKeyCode[dots]; } if (standardKeyCode) {
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_key_types.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_key_types.js index 1f5a044..a9ec97dd 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_key_types.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_key_types.js
@@ -84,11 +84,7 @@ */ cvox.BrailleKeyEvent.keyCodeToCharValue = function(keyCode) { /** @const */ - var SPECIAL_CODES = { - 'Backspace': 0x08, - 'Tab': 0x09, - 'Enter': 0x0A - }; + var SPECIAL_CODES = {'Backspace': 0x08, 'Tab': 0x09, 'Enter': 0x0A}; // Note, the Chrome virtual keyboard falls back on the first character of the // key code if the key is not one of the above. Do the same here. return SPECIAL_CODES[keyCode] || keyCode.charCodeAt(0); @@ -201,20 +197,20 @@ }; (function() { - // Add 0-9. - for (var i = '0'.charCodeAt(0); i < '9'.charCodeAt(0); ++i) { - cvox.BrailleKeyEvent.legacyKeyCodeMap_[String.fromCharCode(i)] = i; - } +// Add 0-9. +for (var i = '0'.charCodeAt(0); i < '9'.charCodeAt(0); ++i) { + cvox.BrailleKeyEvent.legacyKeyCodeMap_[String.fromCharCode(i)] = i; +} - // Add A-Z. - for (var i = 'A'.charCodeAt(0); i < 'Z'.charCodeAt(0); ++i) { - cvox.BrailleKeyEvent.legacyKeyCodeMap_[String.fromCharCode(i)] = i; - } +// Add A-Z. +for (var i = 'A'.charCodeAt(0); i < 'Z'.charCodeAt(0); ++i) { + cvox.BrailleKeyEvent.legacyKeyCodeMap_[String.fromCharCode(i)] = i; +} - // Add the F1 to F12 keys. - for (var i = 0; i < 12; ++i) { - cvox.BrailleKeyEvent.legacyKeyCodeMap_['F' + (i + 1)] = 112 + i; - } +// Add the F1 to F12 keys. +for (var i = 0; i < 12; ++i) { + cvox.BrailleKeyEvent.legacyKeyCodeMap_['F' + (i + 1)] = 112 + i; +} })();
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_table.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_table.js index 2098b86d..bf41c2b 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_table.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_table.js
@@ -58,10 +58,9 @@ xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { - callback( - appendCommonFilename( - /** @type {!Array<cvox.BrailleTable.Table>} */ ( - JSON.parse(xhr.responseText)))); + callback(appendCommonFilename( + /** @type {!Array<cvox.BrailleTable.Table>} */ ( + JSON.parse(xhr.responseText)))); } } }; @@ -76,7 +75,10 @@ * @return {cvox.BrailleTable.Table} The found table, or null if not found. */ cvox.BrailleTable.forId = function(tables, id) { - return tables.filter(function(table) { return table.id === id; })[0] || null; + return tables.filter(function(table) { + return table.id === id; + })[0] || + null; }; @@ -93,16 +95,13 @@ function mostUncontractedOf(current, candidate) { // An 8 dot table for the same language is prefered over a 6 dot table // even if the locales differ by region. - if (current.dots === '6' && - candidate.dots === '8' && + if (current.dots === '6' && candidate.dots === '8' && current.locale.lastIndexOf(candidate.locale, 0) == 0) { return candidate; } if (current.locale === candidate.locale && - current.dots === candidate.dots && - goog.isDef(current.grade) && - goog.isDef(candidate.grade) && - candidate.grade < current.grade) { + current.dots === candidate.dots && goog.isDef(current.grade) && + goog.isDef(candidate.grade) && candidate.grade < current.grade) { return candidate; } return current; @@ -120,13 +119,14 @@ if (!table.grade && !table.variant) { return localeName; } else if (table.grade && !table.variant) { - return Msgs.getMsg('braille_table_name_with_grade', - [localeName, table.grade]); + return Msgs.getMsg( + 'braille_table_name_with_grade', [localeName, table.grade]); } else if (!table.grade && table.variant) { - return Msgs.getMsg('braille_table_name_with_variant', - [localeName, table.variant]); + return Msgs.getMsg( + 'braille_table_name_with_variant', [localeName, table.variant]); } else { - return Msgs.getMsg('braille_table_name_with_variant_and_grade', - [localeName, table.variant, table.grade]); + return Msgs.getMsg( + 'braille_table_name_with_variant_and_grade', + [localeName, table.variant, table.grade]); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager.js b/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager.js index 31ad8476..1d50a2c 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager.js
@@ -22,9 +22,10 @@ * @type {!cvox.LibLouis} * @private */ - this.liblouis_ = opt_liblouisForTest || new cvox.LibLouis( - chrome.extension.getURL('braille/liblouis_nacl.nmf'), - chrome.extension.getURL('braille/tables')); + this.liblouis_ = opt_liblouisForTest || + new cvox.LibLouis( + chrome.extension.getURL('braille/liblouis_nacl.nmf'), + chrome.extension.getURL('braille/tables')); /** * @type {!Array<function()>} * @private @@ -62,9 +63,8 @@ this.uncontractedTableId_ = null; if (!opt_liblouisForTest) { - document.addEventListener('DOMContentLoaded', - this.loadLiblouis_.bind(this), - false); + document.addEventListener( + 'DOMContentLoaded', this.loadLiblouis_.bind(this), false); } }; @@ -123,12 +123,13 @@ // for an uncontracted table. Otherwise, use the current table and let // getUncontracted find an appropriate corresponding table. var table8Dot = opt_brailleTable8 ? - cvox.BrailleTable.forId(tables, opt_brailleTable8) : null; - var uncontractedTable = cvox.BrailleTable.getUncontracted( - tables, table8Dot || table); + cvox.BrailleTable.forId(tables, opt_brailleTable8) : + null; + var uncontractedTable = + cvox.BrailleTable.getUncontracted(tables, table8Dot || table); var newDefaultTableId = table.id; - var newUncontractedTableId = table.id === uncontractedTable.id ? - null : uncontractedTable.id; + var newUncontractedTableId = + table.id === uncontractedTable.id ? null : uncontractedTable.id; if (newDefaultTableId === this.defaultTableId_ && newUncontractedTableId === this.uncontractedTableId_) { return; @@ -141,7 +142,9 @@ defaultTranslator, uncontractedTranslator); this.defaultTranslator_ = defaultTranslator; this.uncontractedTranslator_ = uncontractedTranslator; - this.changeListeners_.forEach(function(listener) { listener(); }); + this.changeListeners_.forEach(function(listener) { + listener(); + }); }.bind(this); this.liblouis_.getTranslator(table.fileNames, function(translator) { @@ -149,11 +152,10 @@ finishRefresh(translator, null); } else { this.liblouis_.getTranslator( - uncontractedTable.fileNames, - function(uncontractedTranslator) { + uncontractedTable.fileNames, function(uncontractedTranslator) { finishRefresh(translator, uncontractedTranslator); }); - } + } }.bind(this)); },
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/expanding_braille_translator.js b/chrome/browser/resources/chromeos/chromevox/braille/expanding_braille_translator.js index 563f8e139..bbbe580 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/expanding_braille_translator.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/expanding_braille_translator.js
@@ -33,8 +33,8 @@ * Translator to use for uncontracted braille translation. * @constructor */ -cvox.ExpandingBrailleTranslator = - function(defaultTranslator, opt_uncontractedTranslator) { +cvox.ExpandingBrailleTranslator = function( + defaultTranslator, opt_uncontractedTranslator) { /** * @type {!cvox.LibLouis.Translator} * @private @@ -86,11 +86,13 @@ * callback Called when the translation is done. It takes resulting * braille cells and positional mappings as parameters. */ -cvox.ExpandingBrailleTranslator.prototype.translate = - function(text, expansionType, callback) { +cvox.ExpandingBrailleTranslator.prototype.translate = function( + text, expansionType, callback) { var expandRanges = this.findExpandRanges_(text, expansionType); - var extraCellsSpans = text.getSpansInstanceOf(cvox.ExtraCellsSpan) - .filter(function(span) { return span.cells.byteLength > 0;}); + var extraCellsSpans = + text.getSpansInstanceOf(cvox.ExtraCellsSpan).filter(function(span) { + return span.cells.byteLength > 0; + }); var extraCellsPositions = extraCellsSpans.map(function(span) { return text.getSpanStart(span); }); @@ -108,12 +110,14 @@ chunks.push({translator: translator, start: start, end: end}); } function addExtraCellsChunk(pos, cells) { - var chunk = {translator: null, - start: pos, - end: pos, - cells: cells, - textToBraille: [], - brailleToText: new Array(cells.byteLength)}; + var chunk = { + translator: null, + start: pos, + end: pos, + cells: cells, + textToBraille: [], + brailleToText: new Array(cells.byteLength) + }; for (var i = 0; i < cells.byteLength; ++i) chunk.brailleToText[i] = 0; chunks.push(chunk); @@ -151,16 +155,17 @@ } function finish() { - var totalCells = chunks.reduce( - function(accum, chunk) { return accum + chunk.cells.byteLength;}, 0); + var totalCells = chunks.reduce(function(accum, chunk) { + return accum + chunk.cells.byteLength; + }, 0); var cells = new Uint8Array(totalCells); var cellPos = 0; var textToBraille = []; var brailleToText = []; function appendAdjusted(array, toAppend, adjustment) { - array.push.apply(array, toAppend.map( - function(elem) { return adjustment + elem; } - )); + array.push.apply(array, toAppend.map(function(elem) { + return adjustment + elem; + })); } for (var i = 0, chunk; chunk = chunks[i]; ++i) { cells.set(new Uint8Array(chunk.cells), cellPos); @@ -316,8 +321,8 @@ * An adapted version of the callback. * @private */ -cvox.ExpandingBrailleTranslator.nullParamsToEmptyAdapter_ = - function(inputLength, callback) { +cvox.ExpandingBrailleTranslator.nullParamsToEmptyAdapter_ = function( + inputLength, callback) { return function(cells, textToBraille, brailleToText) { if (!textToBraille) { textToBraille = new Array(inputLength); @@ -325,9 +330,7 @@ textToBraille[i] = 0; } } - callback(cells || new ArrayBuffer(0), - textToBraille, - brailleToText || []); + callback(cells || new ArrayBuffer(0), textToBraille, brailleToText || []); }; };
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js b/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js index 0b8a2ee..ddd3b8bc 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js
@@ -74,11 +74,12 @@ if (!goog.isNull(this.tablesDir_)) { embed.setAttribute('tablesdir', this.tablesDir_); } - embed.addEventListener('load', goog.bind(this.onInstanceLoad_, this), - false /* useCapture */); - embed.addEventListener('error', goog.bind(this.onInstanceError_, this), - false /* useCapture */); - embed.addEventListener('message', goog.bind(this.onInstanceMessage_, this), + embed.addEventListener( + 'load', goog.bind(this.onInstanceLoad_, this), false /* useCapture */); + embed.addEventListener( + 'error', goog.bind(this.onInstanceError_, this), false /* useCapture */); + embed.addEventListener( + 'message', goog.bind(this.onInstanceMessage_, this), false /* useCapture */); elem.appendChild(embed); this.embedElement_ = /** @type {!HTMLEmbedElement} */ (embed); @@ -124,7 +125,7 @@ callback(null /* translator */); return; } - this.rpc_('CheckTable', { 'table_names': tableNames }, function(reply) { + this.rpc_('CheckTable', {'table_names': tableNames}, function(reply) { if (reply['success']) { var translator = new cvox.LibLouis.Translator(this, tableNames); callback(translator); @@ -143,8 +144,7 @@ * @param {function(!Object)} callback Callback to receive the reply. * @private */ -cvox.LibLouis.prototype.rpc_ = - function(command, message, callback) { +cvox.LibLouis.prototype.rpc_ = function(command, message, callback) { if (!this.isAttached()) { throw Error('Cannot send RPC: liblouis instance not loaded'); } @@ -193,8 +193,8 @@ var message = /** @type {!Object} */ (JSON.parse(e.data)); var messageId = message['in_reply_to']; if (!goog.isDef(messageId)) { - window.console.warn('liblouis Native Client module sent message with no ID', - message); + window.console.warn( + 'liblouis Native Client module sent message with no ID', message); return; } if (goog.isDef(message['error'])) { @@ -244,7 +244,7 @@ callback(null /*cells*/, null /*textToBraille*/, null /*brailleToText*/); return; } - var message = { 'table_names': this.tableNames_, 'text': text }; + var message = {'table_names': this.tableNames_, 'text': text}; this.instance_.rpc_('Translate', message, function(reply) { var cells = null; var textToBraille = null; @@ -272,8 +272,7 @@ * @param {!ArrayBuffer} cells Cells to be translated. * @param {function(?string)} callback Callback for result. */ -cvox.LibLouis.Translator.prototype.backTranslate = - function(cells, callback) { +cvox.LibLouis.Translator.prototype.backTranslate = function(cells, callback) { if (!this.instance_.isAttached()) { callback(null /*text*/); return;
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/nav_braille.js b/chrome/browser/resources/chromeos/chromevox/braille/nav_braille.js index 440abec..5ec2769 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/nav_braille.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/nav_braille.js
@@ -30,8 +30,8 @@ * Text, annotated with DOM nodes. * @type {!Spannable} */ - this.text = (kwargs.text instanceof Spannable) ? - kwargs.text : new Spannable(kwargs.text); + this.text = (kwargs.text instanceof Spannable) ? kwargs.text : + new Spannable(kwargs.text); /** * Selection start index. @@ -43,8 +43,8 @@ * Selection end index. * @type {number} */ - this.endIndex = goog.isDef(kwargs.endIndex) ? - kwargs.endIndex : this.startIndex; + this.endIndex = + goog.isDef(kwargs.endIndex) ? kwargs.endIndex : this.startIndex; }; /** @@ -89,8 +89,8 @@ */ cvox.NavBraille.prototype.toString = function() { return 'NavBraille(text="' + this.text.toString() + '" ' + - ' startIndex="' + this.startIndex + '" ' + - ' endIndex="' + this.endIndex + '")'; + ' startIndex="' + this.startIndex + '" ' + + ' endIndex="' + this.endIndex + '")'; };
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/pan_strategy.js b/chrome/browser/resources/chromeos/chromevox/braille/pan_strategy.js index 5338b43..730145a 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/pan_strategy.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/pan_strategy.js
@@ -108,9 +108,11 @@ * braille and text indices of the current slice. */ get offsetsForSlices() { - return {brailleOffset: this.viewPort_.firstRow * this.displaySize_.columns, - textOffset: this.brailleToText[this.viewPort_.firstRow * - this.displaySize_.columns]}; + return { + brailleOffset: this.viewPort_.firstRow * this.displaySize_.columns, + textOffset: this.brailleToText + [this.viewPort_.firstRow * this.displaySize_.columns] + }; }, /** @@ -124,8 +126,8 @@ * @return {number} The number of lines in the wrappedBuffer. */ get wrappedLineCount() { - return Math.ceil(this.wrappedBuffer_.byteLength / - this.displaySize_.columns); + return Math.ceil( + this.wrappedBuffer_.byteLength / this.displaySize_.columns); }, /** @@ -144,9 +146,10 @@ * bounds of the viewport. */ getCurrentBrailleViewportContents: function() { - var buf = this.panStrategyWrapped_ ? - this.wrappedBuffer_ : this.fixedBuffer_; - return buf.slice(this.viewPort_.firstRow * this.displaySize_.columns, + var buf = + this.panStrategyWrapped_ ? this.wrappedBuffer_ : this.fixedBuffer_; + return buf.slice( + this.viewPort_.firstRow * this.displaySize_.columns, (this.viewPort_.lastRow + 1) * this.displaySize_.columns); }, @@ -188,8 +191,8 @@ */ setDisplaySize: function(rowCount, columnCount) { this.displaySize_ = {rows: rowCount, columns: columnCount}; - this.setContent(this.textBuffer_, this.fixedBuffer_, - this.fixedBrailleToText_, 0); + this.setContent( + this.textBuffer_, this.fixedBuffer_, this.fixedBrailleToText_, 0); }, /** @@ -202,8 +205,8 @@ * @param {number} targetPosition Target position. The viewport is changed * to overlap this position. */ - setContent: function(textBuffer, translatedContent, fixedBrailleToText, - targetPosition) { + setContent: function( + textBuffer, translatedContent, fixedBrailleToText, targetPosition) { this.viewPort_.firstRow = 0; this.viewPort_.lastRow = this.displaySize_.rows - 1; this.fixedBrailleToText_ = fixedBrailleToText; @@ -219,18 +222,19 @@ var cellsPadded = 0; var index; for (index = 0; index < translatedContent.byteLength + cellsPadded; - index++) { + index++) { // Is index at the beginning of a new line? if (index != 0 && index % this.displaySize_.columns == 0) { if (view[index - cellsPadded] == 0) { // Delete all empty cells at the beginning of this line. while (index - cellsPadded < view.length && - view[index - cellsPadded] == 0) { + view[index - cellsPadded] == 0) { cellsPadded--; } index--; lastBreak = index; - } else if (view[index - cellsPadded - 1] != 0 && + } else if ( + view[index - cellsPadded - 1] != 0 && lastBreak % this.displaySize_.columns != 0) { // If first cell is not empty, we need to move the whole word down to // this line and padd to previous line with 0's, from |lastBreak| to @@ -275,8 +279,8 @@ * @return {boolean} {@code true} if the viewport was changed. */ next: function() { - var contentLength = this.panStrategyWrapped_ ? - this.wrappedLineCount : this.fixedLineCount; + var contentLength = + this.panStrategyWrapped_ ? this.wrappedLineCount : this.fixedLineCount; var newStart = this.viewPort_.lastRow + 1; var newEnd; if (newStart + this.displaySize_.rows - 1 < contentLength) { @@ -297,8 +301,8 @@ * @return {boolean} {@code true} if the viewport was changed. */ previous: function() { - var contentLength = this.panStrategyWrapped_ ? - this.wrappedLineCount : this.fixedLineCount; + var contentLength = + this.panStrategyWrapped_ ? this.wrappedLineCount : this.fixedLineCount; if (this.viewPort_.firstRow > 0) { var newStart, newEnd; if (this.viewPort_.firstRow < this.displaySize_.rows) { @@ -324,8 +328,9 @@ panToPosition_: function(position) { if (this.displaySize_.rows * this.displaySize_.columns > 0) { this.viewPort_ = {firstRow: -1, lastRow: -1}; - while (this.next() && (this.viewPort_.lastRow + 1) * - this.displaySize_.columns <= position) { + while (this.next() && + (this.viewPort_.lastRow + 1) * this.displaySize_.columns <= + position) { // Nothing to do. } } else {
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/spans.js b/chrome/browser/resources/chromeos/chromevox/braille/spans.js index 103da9c..525b107 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/spans.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/spans.js
@@ -47,9 +47,7 @@ Spannable.registerSerializableSpan( - cvox.ValueSpan, - 'cvox.ValueSpan', - cvox.ValueSpan.fromJson, + cvox.ValueSpan, 'cvox.ValueSpan', cvox.ValueSpan.fromJson, cvox.ValueSpan.prototype.toJson); @@ -57,8 +55,7 @@ * Attached to the selected text within a value. * @constructor */ -cvox.ValueSelectionSpan = function() { -}; +cvox.ValueSelectionSpan = function() {}; Spannable.registerStatelessSerializableSpan(
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js index 6fdbcb9..234b5b7 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/background.js
@@ -35,8 +35,7 @@ * interprets them. * @constructor */ -cvox.ChromeVoxBackground = function() { -}; +cvox.ChromeVoxBackground = function() {}; /** @@ -47,8 +46,8 @@ cvox.ChromeVoxBackground.setPref = function(pref, value, announce) { if (pref == 'active' && value != cvox.ChromeVox.isActive) { if (cvox.ChromeVox.isActive) { - cvox.ChromeVox.tts.speak(Msgs.getMsg('chromevox_inactive'), - cvox.QueueMode.FLUSH); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('chromevox_inactive'), cvox.QueueMode.FLUSH); chrome.accessibilityPrivate.setNativeAccessibilityEnabled(true); } else { chrome.accessibilityPrivate.setNativeAccessibilityEnabled(false); @@ -57,12 +56,11 @@ cvox.AbstractEarcons.enabled = !!value; } else if (pref == 'sticky' && announce) { if (value) { - cvox.ChromeVox.tts.speak(Msgs.getMsg('sticky_mode_enabled'), - cvox.QueueMode.FLUSH); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('sticky_mode_enabled'), cvox.QueueMode.FLUSH); } else { cvox.ChromeVox.tts.speak( - Msgs.getMsg('sticky_mode_disabled'), - cvox.QueueMode.FLUSH); + Msgs.getMsg('sticky_mode_disabled'), cvox.QueueMode.FLUSH); } } else if (pref == 'typingEcho' && announce) { var announceStr = ''; @@ -89,8 +87,8 @@ cvox.BrailleCaptionsBackground.setActive(!!value); } else if (pref == 'position') { cvox.ChromeVox.position = - /** @type {Object<string, cvox.Point>} */(JSON.parse( - /** @type {string} */(value))); + /** @type {Object<string, cvox.Point>} */ (JSON.parse( + /** @type {string} */ (value))); } window['prefs'].setPref(pref, value); cvox.ChromeVoxBackground.readPrefs(); @@ -143,9 +141,7 @@ /** * @type {cvox.TtsInterface} */ - this.tts = new cvox.CompositeTts() - .add(this.backgroundTts_) - .add(consoleTts); + this.tts = new cvox.CompositeTts().add(this.backgroundTts_).add(consoleTts); this.addBridgeListener(); @@ -172,18 +168,15 @@ // Set up a message passing system for goog.provide() calls from // within the content scripts. - chrome.extension.onMessage.addListener( - function(request, sender, callback) { - if (request['srcFile']) { - var srcFile = request['srcFile']; - cvox.InjectedScriptLoader.fetchCode( - [srcFile], - function(code) { - callback({'code': code[srcFile]}); - }); - } - return true; + chrome.extension.onMessage.addListener(function(request, sender, callback) { + if (request['srcFile']) { + var srcFile = request['srcFile']; + cvox.InjectedScriptLoader.fetchCode([srcFile], function(code) { + callback({'code': code[srcFile]}); }); + } + return true; + }); var self = this; @@ -197,14 +190,12 @@ if (localStorage['active'] == 'false') { // Warn the user when the browser first starts if ChromeVox is inactive. - this.tts.speak(Msgs.getMsg('chromevox_inactive'), - cvox.QueueMode.QUEUE); + this.tts.speak(Msgs.getMsg('chromevox_inactive'), cvox.QueueMode.QUEUE); } else if (cvox.PlatformUtil.matchesPlatform(cvox.PlatformFilter.WML)) { // Introductory message. - this.tts.speak(Msgs.getMsg('chromevox_intro'), - cvox.QueueMode.QUEUE); - cvox.ChromeVox.braille.write(cvox.NavBraille.fromText( - Msgs.getMsg('intro_brl'))); + this.tts.speak(Msgs.getMsg('chromevox_intro'), cvox.QueueMode.QUEUE); + cvox.ChromeVox.braille.write( + cvox.NavBraille.fromText(Msgs.getMsg('intro_brl'))); } }; @@ -222,10 +213,9 @@ listOfFiles = ['chromeVoxChromePageScript.js']; } else { listOfFiles = [ - 'closure/closure_preinit.js', - 'closure/base.js', - 'deps.js', - 'chromevox/injected/loader.js']; + 'closure/closure_preinit.js', 'closure/base.js', 'deps.js', + 'chromevox/injected/loader.js' + ]; } var stageTwo = function(code) { @@ -239,10 +229,7 @@ */ var executeScript = goog.bind(function(code) { chrome.tabs.executeScript( - tab.id, - {'code': code, - 'allFrames': true}, - goog.bind(function() { + tab.id, {'code': code, 'allFrames': true}, goog.bind(function() { if (!chrome.extension.lastError) { return; } @@ -251,8 +238,9 @@ } sawError = true; console.error('Could not inject into tab', tab); - this.tts.speak('Error starting ChromeVox for ' + - tab.title + ', ' + tab.url, cvox.QueueMode.QUEUE); + this.tts.speak( + 'Error starting ChromeVox for ' + tab.title + ', ' + tab.url, + cvox.QueueMode.QUEUE); }, this)); }, this); @@ -268,12 +256,15 @@ // // Also, set some variables so that Closure deps work correctly and so // that ChromeVox knows not to announce feedback as if a page just loaded. - executeScript('try { window.disableChromeVox(); } catch(e) { }\n' + + executeScript( + 'try { window.disableChromeVox(); } catch(e) { }\n' + 'window.INJECTED_AFTER_LOAD = true;\n' + 'window.CLOSURE_NO_DEPS = true\n'); // Now inject the ChromeVox content script code into the tab. - listOfFiles.forEach(function(file) { executeScript(code[file]); }); + listOfFiles.forEach(function(file) { + executeScript(code[file]); + }); } }; @@ -290,41 +281,38 @@ */ cvox.ChromeVoxBackground.prototype.onTtsMessage = function(msg) { if (msg['action'] == 'speak') { - this.tts.speak(msg['text'], - /** cvox.QueueMode */msg['queueMode'], - msg['properties']); + this.tts.speak( + msg['text'], + /** cvox.QueueMode */ msg['queueMode'], msg['properties']); } else if (msg['action'] == 'stop') { this.tts.stop(); } else if (msg['action'] == 'increaseOrDecrease') { this.tts.increaseOrDecreaseProperty(msg['property'], msg['increase']); var property = msg['property']; var engine = this.backgroundTts_; - var valueAsPercent = Math.round( - this.backgroundTts_.propertyToPercentage(property) * 100); + var valueAsPercent = + Math.round(this.backgroundTts_.propertyToPercentage(property) * 100); var announcement; switch (msg['property']) { - case cvox.AbstractTts.RATE: - announcement = Msgs.getMsg('announce_rate', - [valueAsPercent]); - break; - case cvox.AbstractTts.PITCH: - announcement = Msgs.getMsg('announce_pitch', - [valueAsPercent]); - break; - case cvox.AbstractTts.VOLUME: - announcement = Msgs.getMsg('announce_volume', - [valueAsPercent]); - break; + case cvox.AbstractTts.RATE: + announcement = Msgs.getMsg('announce_rate', [valueAsPercent]); + break; + case cvox.AbstractTts.PITCH: + announcement = Msgs.getMsg('announce_pitch', [valueAsPercent]); + break; + case cvox.AbstractTts.VOLUME: + announcement = Msgs.getMsg('announce_volume', [valueAsPercent]); + break; } if (announcement) { - this.tts.speak(announcement, - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + this.tts.speak( + announcement, cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOTATION); } } else if (msg['action'] == 'cyclePunctuationEcho') { - this.tts.speak(Msgs.getMsg( - this.backgroundTts_.cyclePunctuationEcho()), - cvox.QueueMode.FLUSH); + this.tts.speak( + Msgs.getMsg(this.backgroundTts_.cyclePunctuationEcho()), + cvox.QueueMode.FLUSH); } }; @@ -350,88 +338,91 @@ var action = msg['action']; switch (target) { - case 'OpenTab': - var destination = {url: msg['url']}; - chrome.tabs.create(destination); - break; - case 'KbExplorer': - var explorerPage = {url: 'chromevox/background/kbexplorer.html'}; - chrome.tabs.create(explorerPage); - break; - case 'HelpDocs': - var helpPage = {url: 'http://chromevox.com/tutorial/index.html'}; - chrome.tabs.create(helpPage); - break; - case 'Options': - if (action == 'open') { - var optionsPage = {url: 'chromevox/background/options.html'}; - chrome.tabs.create(optionsPage); - } - break; - case 'Data': - if (action == 'getHistory') { - var results = {}; - chrome.history.search({text: '', maxResults: 25}, function(items) { - items.forEach(function(item) { - if (item.url) { - results[item.url] = true; - } + case 'OpenTab': + var destination = {url: msg['url']}; + chrome.tabs.create(destination); + break; + case 'KbExplorer': + var explorerPage = {url: 'chromevox/background/kbexplorer.html'}; + chrome.tabs.create(explorerPage); + break; + case 'HelpDocs': + var helpPage = {url: 'http://chromevox.com/tutorial/index.html'}; + chrome.tabs.create(helpPage); + break; + case 'Options': + if (action == 'open') { + var optionsPage = {url: 'chromevox/background/options.html'}; + chrome.tabs.create(optionsPage); + } + break; + case 'Data': + if (action == 'getHistory') { + var results = {}; + chrome.history.search({text: '', maxResults: 25}, function(items) { + items.forEach(function(item) { + if (item.url) { + results[item.url] = true; + } + }); + port.postMessage({'history': results}); }); + } + break; + case 'Prefs': + if (action == 'getPrefs') { + this.prefs.sendPrefsToPort(port); + } else if (action == 'setPref') { + var pref = /** @type {string} */ (msg['pref']); + var announce = !!msg['announce']; + cvox.ChromeVoxBackground.setPref(pref, msg['value'], announce); + } + break; + case 'Math': + // TODO (sorge): Put the change of styles etc. here! + if (msg['action'] == 'getDomains') { port.postMessage({ - 'history': results + 'message': 'DOMAINS_STYLES', + 'domains': this.backgroundTts_.mathmap.allDomains, + 'styles': this.backgroundTts_.mathmap.allStyles }); - }); - } - break; - case 'Prefs': - if (action == 'getPrefs') { - this.prefs.sendPrefsToPort(port); - } else if (action == 'setPref') { - var pref = /** @type {string} */(msg['pref']); - var announce = !!msg['announce']; - cvox.ChromeVoxBackground.setPref( - pref, msg['value'], announce); - } - break; - case 'Math': - // TODO (sorge): Put the change of styles etc. here! - if (msg['action'] == 'getDomains') { - port.postMessage({'message': 'DOMAINS_STYLES', - 'domains': this.backgroundTts_.mathmap.allDomains, - 'styles': this.backgroundTts_.mathmap.allStyles}); - } - break; - case 'TTS': - if (msg['startCallbackId'] != undefined) { - msg['properties']['startCallback'] = function(opt_cleanupOnly) { - port.postMessage({'message': 'TTS_CALLBACK', - 'cleanupOnly': opt_cleanupOnly, - 'id': msg['startCallbackId']}); - }; - } - if (msg['endCallbackId'] != undefined) { - msg['properties']['endCallback'] = function(opt_cleanupOnly) { - port.postMessage({'message': 'TTS_CALLBACK', - 'cleanupOnly': opt_cleanupOnly, - 'id': msg['endCallbackId']}); - }; - } - try { - this.onTtsMessage(msg); - } catch (err) { - console.log(err); - } - break; - case 'EARCON': - this.onEarconMessage(msg); - break; - case 'BRAILLE': - try { - this.backgroundBraille_.onBrailleMessage(msg); - } catch (err) { - console.log(err); - } - break; + } + break; + case 'TTS': + if (msg['startCallbackId'] != undefined) { + msg['properties']['startCallback'] = function(opt_cleanupOnly) { + port.postMessage({ + 'message': 'TTS_CALLBACK', + 'cleanupOnly': opt_cleanupOnly, + 'id': msg['startCallbackId'] + }); + }; + } + if (msg['endCallbackId'] != undefined) { + msg['properties']['endCallback'] = function(opt_cleanupOnly) { + port.postMessage({ + 'message': 'TTS_CALLBACK', + 'cleanupOnly': opt_cleanupOnly, + 'id': msg['endCallbackId'] + }); + }; + } + try { + this.onTtsMessage(msg); + } catch (err) { + console.log(err); + } + break; + case 'EARCON': + this.onEarconMessage(msg); + break; + case 'BRAILLE': + try { + this.backgroundBraille_.onBrailleMessage(msg); + } catch (err) { + console.log(err); + } + break; } }, this)); }; @@ -458,11 +449,11 @@ * Handles the onIntroduceChromeVox event. */ cvox.ChromeVoxBackground.prototype.onIntroduceChromeVox = function() { - cvox.ChromeVox.tts.speak(Msgs.getMsg('chromevox_intro'), - cvox.QueueMode.QUEUE, - {doNotInterrupt: true}); - cvox.ChromeVox.braille.write(cvox.NavBraille.fromText( - Msgs.getMsg('intro_brl'))); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('chromevox_intro'), cvox.QueueMode.QUEUE, + {doNotInterrupt: true}); + cvox.ChromeVox.braille.write( + cvox.NavBraille.fromText(Msgs.getMsg('intro_brl'))); }; @@ -479,22 +470,21 @@ // so that other background pages can access it. Also export the prefs object // for access by the options page. (function() { - var background = new cvox.ChromeVoxBackground(); - background.init(); - window['speak'] = goog.bind(background.tts.speak, background.tts); - ChromeVoxState.backgroundTts = background.backgroundTts_; +var background = new cvox.ChromeVoxBackground(); +background.init(); +window['speak'] = goog.bind(background.tts.speak, background.tts); +ChromeVoxState.backgroundTts = background.backgroundTts_; - // Export the prefs object for access by the options page. - window['prefs'] = background.prefs; +// Export the prefs object for access by the options page. +window['prefs'] = background.prefs; - // Export the braille translator manager for access by the options page. - window['braille_translator_manager'] = - background.backgroundBraille_.getTranslatorManager(); +// Export the braille translator manager for access by the options page. +window['braille_translator_manager'] = + background.backgroundBraille_.getTranslatorManager(); - window['getCurrentVoice'] = - background.getCurrentVoice.bind(background); +window['getCurrentVoice'] = background.getCurrentVoice.bind(background); - // Export injection for ChromeVox Next. - cvox.ChromeVox.injectChromeVoxIntoTabs = - background.injectChromeVoxIntoTabs.bind(background); +// Export injection for ChromeVox Next. +cvox.ChromeVox.injectChromeVoxIntoTabs = + background.injectChromeVoxIntoTabs.bind(background); })();
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/braille_captions_background.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/braille_captions_background.js index 796122d8..6e46c83 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/braille_captions_background.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/braille_captions_background.js
@@ -64,28 +64,25 @@ * @param {number} rows Number of rows to display. * @param {number} columns Number of columns to display. */ -cvox.BrailleCaptionsBackground.setContent = function(text, cells, - brailleToText, offsetsForSlices, rows, columns) { +cvox.BrailleCaptionsBackground.setContent = function( + text, cells, brailleToText, offsetsForSlices, rows, columns) { var self = cvox.BrailleCaptionsBackground; // Convert the cells to Unicode braille pattern characters. var byteBuf = new Uint8Array(cells); var brailleChars = ''; for (var i = 0; i < byteBuf.length; ++i) { - brailleChars += String.fromCharCode( - self.BRAILLE_UNICODE_BLOCK_START | byteBuf[i]); + brailleChars += + String.fromCharCode(self.BRAILLE_UNICODE_BLOCK_START | byteBuf[i]); } - var groups = this.groupBrailleAndText(brailleChars, text, brailleToText, - offsetsForSlices); + var groups = this.groupBrailleAndText( + brailleChars, text, brailleToText, offsetsForSlices); if (cvox.ChromeVox.isChromeOS) { var data = {groups: groups, rows: rows, cols: columns}; (new PanelCommand(PanelCommandType.UPDATE_BRAILLE, data)).send(); } else { - cvox.ExtensionBridge.send({ - message: 'BRAILLE_CAPTION', - text: text, - brailleChars: brailleChars - }); + cvox.ExtensionBridge.send( + {message: 'BRAILLE_CAPTION', text: text, brailleChars: brailleChars}); } }; @@ -94,16 +91,16 @@ * @param {number} rows Number of rows to display. * @param {number} columns Number of columns to display. */ -cvox.BrailleCaptionsBackground.setImageContent = function(cells, rows, - columns) { +cvox.BrailleCaptionsBackground.setImageContent = function( + cells, rows, columns) { var self = cvox.BrailleCaptionsBackground; // Convert the cells to Unicode braille pattern characters. var byteBuf = new Uint8Array(cells); var brailleChars = ''; for (var i = 0; i < byteBuf.length; ++i) { - brailleChars += String.fromCharCode( - self.BRAILLE_UNICODE_BLOCK_START | byteBuf[i]); + brailleChars += + String.fromCharCode(self.BRAILLE_UNICODE_BLOCK_START | byteBuf[i]); } var groups = [['Image', brailleChars]]; @@ -121,8 +118,8 @@ * the second is the text offset. * @return {Array} The groups of braille and texts to be displayed. */ -cvox.BrailleCaptionsBackground.groupBrailleAndText = function(brailleChars, - text, brailleToText, offsets) { +cvox.BrailleCaptionsBackground.groupBrailleAndText = function( + brailleChars, text, brailleToText, offsets) { var brailleBuf = ''; var groups = []; var textIndex = 0; @@ -135,9 +132,8 @@ for (var i = 0; i < brailleChars.length; ++i) { var textSliceIndex = calculateTextIndex(i); if (i != 0 && textSliceIndex != textIndex) { - groups.push([text.substr(textIndex, - textSliceIndex - textIndex), - brailleBuf]); + groups.push( + [text.substr(textIndex, textSliceIndex - textIndex), brailleBuf]); brailleBuf = ''; textIndex = textSliceIndex; } @@ -163,9 +159,8 @@ if (self.stateCallback_) { self.stateCallback_(); } - var msg = newValue ? - Msgs.getMsg('braille_captions_enabled') : - Msgs.getMsg('braille_captions_disabled'); + var msg = newValue ? Msgs.getMsg('braille_captions_enabled') : + Msgs.getMsg('braille_captions_disabled'); cvox.ChromeVox.tts.speak(msg, cvox.QueueMode.QUEUE); cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(msg)); } @@ -184,8 +179,8 @@ var rows = items['virtualBrailleRows']; chrome.storage.local.get({'virtualBrailleColumns': 40}, function(items) { var columns = items['virtualBrailleColumns']; - callback({available: true, textRowCount: rows, - textColumnCount: columns}); + callback( + {available: true, textRowCount: rows, textColumnCount: columns}); }); }); } else {
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/injected_script_loader.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/injected_script_loader.js index 1cb54c87..15d21b8 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/injected_script_loader.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/injected_script_loader.js
@@ -10,9 +10,8 @@ - /** @constructor */ -cvox.InjectedScriptLoader = function() { }; +cvox.InjectedScriptLoader = function() {}; /** @@ -41,8 +40,8 @@ var debugSrc = src.replace('closure/../', ''); // The 'chromevox' id is only used in the DevTools instead of a long // extension id. - scriptText += '\n//# sourceURL= chrome-extension://chromevox/' + - debugSrc + '\n'; + scriptText += + '\n//# sourceURL= chrome-extension://chromevox/' + debugSrc + '\n'; code[src] = scriptText; waiting--; if (waiting == 0) { @@ -54,5 +53,7 @@ xhr.send(null); }; - files.forEach(function(f) { loadScriptAsCode(f); }); + files.forEach(function(f) { + loadScriptAsCode(f); + }); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/kbexplorer.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/kbexplorer.js index 98d6ad7..017d5e32 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/kbexplorer.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/kbexplorer.js
@@ -22,7 +22,7 @@ * Class to manage the keyboard explorer. * @constructor */ -cvox.KbExplorer = function() { }; +cvox.KbExplorer = function() {}; /** @@ -30,8 +30,7 @@ */ cvox.KbExplorer.init = function() { var backgroundWindow = chrome.extension.getBackgroundPage(); - backgroundWindow.addEventListener( - 'keydown', cvox.KbExplorer.onKeyDown, true); + backgroundWindow.addEventListener('keydown', cvox.KbExplorer.onKeyDown, true); backgroundWindow.addEventListener('keyup', cvox.KbExplorer.onKeyUp, true); backgroundWindow.addEventListener( 'keypress', cvox.KbExplorer.onKeyPress, true); @@ -61,8 +60,9 @@ } /** @type {cvox.LibLouis} */ - this.currentBrailleTranslator_ = backgroundWindow['cvox']['BrailleBackground'] - ['getInstance']()['getTranslatorManager']()['getDefaultTranslator'](); + this.currentBrailleTranslator_ = + backgroundWindow['cvox']['BrailleBackground']['getInstance']() + ['getTranslatorManager']()['getDefaultTranslator'](); cvox.ChromeVoxKbHandler.commandHandler = cvox.KbExplorer.onCommand; $('instruction').focus(); @@ -172,8 +172,7 @@ break; } - var command = - BrailleCommandHandler.getCommand(dots); + var command = BrailleCommandHandler.getCommand(dots); if (command && cvox.KbExplorer.onCommand(command)) return; text = BrailleCommandHandler.makeShortcutText(dots, true); @@ -184,9 +183,9 @@ return; var cells = new ArrayBuffer(1); var view = new Uint8Array(cells); - view[0]= dots; - cvox.KbExplorer.currentBrailleTranslator_.backTranslate(cells, - function(res) { + view[0] = dots; + cvox.KbExplorer.currentBrailleTranslator_.backTranslate( + cells, function(res) { cvox.KbExplorer.output(res); }.bind(this)); return; @@ -235,6 +234,6 @@ /** Clears ChromeVox range. */ cvox.KbExplorer.clearRange = function() { - chrome.extension.getBackgroundPage()[ - 'ChromeVoxState']['instance']['setCurrentRange'](null); + chrome.extension.getBackgroundPage()['ChromeVoxState']['instance'] + ['setCurrentRange'](null); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/key_map.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/key_map.js index 7b769ce..3e2bf37 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/key_map.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/key_map.js
@@ -68,18 +68,10 @@ * @const */ cvox.KeyMap.AVAILABLE_MAP_INFO = { -'keymap_classic': { - 'file': 'classic_keymap.json' - }, -'keymap_flat': { - 'file': 'flat_keymap.json' - }, -'keymap_next': { - 'file': 'next_keymap.json' - }, -'keymap_experimental': { - 'file': 'experimental.json' - } + 'keymap_classic': {'file': 'classic_keymap.json'}, + 'keymap_flat': {'file': 'flat_keymap.json'}, + 'keymap_next': {'file': 'next_keymap.json'}, + 'keymap_experimental': {'file': 'experimental.json'} }; @@ -228,12 +220,12 @@ return [this.commandToKey_[command]]; } else { var keySequenceArray = []; - for (var i = 0; i < this.bindings_.length; i++) { + for (var i = 0; i < this.bindings_.length; i++) { var binding = this.bindings_[i]; - if (binding.command == command) { - keySequenceArray.push(binding.sequence); - } - } + if (binding.command == command) { + keySequenceArray.push(binding.sequence); + } + } } return (keySequenceArray.length > 0) ? keySequenceArray : []; }; @@ -256,8 +248,8 @@ if (command == 'toggleStickyMode') { // TODO(dtseng): More uglyness because of sticky key. continue; - } else if (key && command && - !this.hasKey(key) && !this.hasCommand(command)) { + } else if ( + key && command && !this.hasKey(key) && !this.hasCommand(command)) { this.bind_(command, key); } else { cleanMerge = false; @@ -307,10 +299,7 @@ } } if (!bound) { - var binding = { - 'command': command, - 'sequence': newKey - }; + var binding = {'command': command, 'sequence': newKey}; this.bindings_.push(binding); this.commandToKey_[binding.command] = binding.sequence; } @@ -323,9 +312,9 @@ * @return {!cvox.KeyMap} The default key map. */ cvox.KeyMap.fromDefaults = function() { - return /** @type {!cvox.KeyMap} */ ( - cvox.KeyMap.fromPath(cvox.KeyMap.KEYMAP_PATH + - cvox.KeyMap.AVAILABLE_MAP_INFO['keymap_classic'].file)); + return /** @type {!cvox.KeyMap} */ (cvox.KeyMap.fromPath( + cvox.KeyMap.KEYMAP_PATH + + cvox.KeyMap.AVAILABLE_MAP_INFO['keymap_classic'].file)); }; @@ -334,7 +323,8 @@ * @return {cvox.KeyMap} The Next key map. */ cvox.KeyMap.fromNext = function() { - return cvox.KeyMap.fromPath(cvox.KeyMap.KEYMAP_PATH + + return cvox.KeyMap.fromPath( + cvox.KeyMap.KEYMAP_PATH + cvox.KeyMap.AVAILABLE_MAP_INFO['keymap_next'].file); }; @@ -350,7 +340,7 @@ var commandsAndKeySequences = /** @type {Array<Object<{command: string, * sequence: cvox.KeySequence}>>} */ - (JSON.parse(json).bindings); + (JSON.parse(json).bindings); commandsAndKeySequences = commandsAndKeySequences.filter(function(value) { return value.sequence.platformFilter === undefined || cvox.PlatformUtil.matchesPlatform(value.sequence.platformFilter); @@ -371,7 +361,7 @@ return null; } else { commandsAndKeySequences[i].sequence = /** @type {cvox.KeySequence} */ - (cvox.KeySequence.deserialize(commandsAndKeySequences[i].sequence)); + (cvox.KeySequence.deserialize(commandsAndKeySequences[i].sequence)); } } return new cvox.KeyMap(commandsAndKeySequences);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/mathmaps/math_map.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/mathmaps/math_map.js index 0fd53066..b94705c 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/mathmaps/math_map.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/mathmaps/math_map.js
@@ -26,18 +26,16 @@ * @type {cvox.MathCompoundStore} */ this.store = cvox.MathCompoundStore.getInstance(); - cvox.MathMap.parseFiles( - cvox.MathMap.FUNCTIONS_FILES_.map( - function(file) { - return cvox.MathMap.FUNCTIONS_PATH_ + file; - })) - .forEach(goog.bind(this.store.addFunctionRules, this.store)); - cvox.MathMap.parseFiles( - cvox.MathMap.SYMBOLS_FILES_.map( - function(file) { - return cvox.MathMap.SYMBOLS_PATH_ + file; - })) - .forEach(goog.bind(this.store.addSymbolRules, this.store)); + cvox.MathMap + .parseFiles(cvox.MathMap.FUNCTIONS_FILES_.map(function(file) { + return cvox.MathMap.FUNCTIONS_PATH_ + file; + })) + .forEach(goog.bind(this.store.addFunctionRules, this.store)); + cvox.MathMap + .parseFiles(cvox.MathMap.SYMBOLS_FILES_.map(function(file) { + return cvox.MathMap.SYMBOLS_PATH_ + file; + })) + .forEach(goog.bind(this.store.addSymbolRules, this.store)); var cstrValues = this.store.getDynamicConstraintValues(); /** @@ -125,9 +123,8 @@ * @const * @private */ -cvox.MathMap.FUNCTIONS_FILES_ = [ - 'algebra.json', 'elementary.json', 'hyperbolic.json', 'trigonometry.json' -]; +cvox.MathMap.FUNCTIONS_FILES_ = + ['algebra.json', 'elementary.json', 'hyperbolic.json', 'trigonometry.json']; /** @@ -162,10 +159,14 @@ cvox.MathMap.parseFiles = function(files) { var strs = cvox.MathMap.loadFiles(files); - return [].concat.apply([], strs.map( - // Note: As JSON.parse does not expect the value index as the second - // parameter, we wrap it. - function(value) { return JSON.parse(value); })); + return [].concat.apply( + [], + strs.map( + // Note: As JSON.parse does not expect the value index as the second + // parameter, we wrap it. + function(value) { + return JSON.parse(value); + })); }; @@ -179,7 +180,7 @@ var url = chrome.extension.getURL(path); if (!url) { throw 'Invalid path: ' + path; - } + } var xhr = new XMLHttpRequest(); xhr.open('GET', url, false);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/options.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/options.js index 9e154d20..93270ba 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/options.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/options.js
@@ -26,8 +26,7 @@ * Class to manage the options page. * @constructor */ -cvox.OptionsPage = function() { -}; +cvox.OptionsPage = function() {}; /** * The ChromeVoxPrefs object. @@ -52,10 +51,10 @@ $('brailleWordWrap').checked = items.brailleWordWrap; }); - chrome.storage.local.get({'virtualBrailleRows' : 1}, function(items) { + chrome.storage.local.get({'virtualBrailleRows': 1}, function(items) { $('virtual_braille_display_rows_input').value = items['virtualBrailleRows']; }); - chrome.storage.local.get({'virtualBrailleColumns' : 40}, function(items) { + chrome.storage.local.get({'virtualBrailleColumns': 40}, function(items) { $('virtual_braille_display_columns_input').value = items['virtualBrailleColumns']; }); @@ -68,26 +67,26 @@ var currentlyDisplayingSideBySide = Msgs.getMsg('options_current_display_style_side_by_side'); $('changeDisplayStyle').textContent = - localStorage['brailleSideBySide'] === 'true' ? - changeToInterleave : changeToSideBySide; + localStorage['brailleSideBySide'] === 'true' ? changeToInterleave : + changeToSideBySide; $('currentDisplayStyle').textContent = localStorage['brailleSideBySide'] === 'true' ? - currentlyDisplayingSideBySide : currentlyDisplayingInterleave; + currentlyDisplayingSideBySide : + currentlyDisplayingInterleave; - chrome.commandLinePrivate.hasSwitch('enable-audio-focus', - function(result) { - if (!result) { - $('audioStrategy').hidden = true; - $('audioDescription').hidden = true; + chrome.commandLinePrivate.hasSwitch('enable-audio-focus', function(result) { + if (!result) { + $('audioStrategy').hidden = true; + $('audioDescription').hidden = true; + } + if (localStorage['audioStrategy']) { + for (var i = 0, opt; opt = $('audioStrategy').options[i]; i++) { + if (opt.id == localStorage['audioStrategy']) { + opt.setAttribute('selected', ''); } - if (localStorage['audioStrategy']) { - for (var i = 0, opt; opt = $('audioStrategy').options[i]; i++) { - if (opt.id == localStorage['audioStrategy']) { - opt.setAttribute('selected', ''); - } - } - } - }); + } + } + }); Msgs.addTranslatedMessagesToDom(document); cvox.OptionsPage.hidePlatformSpecifics(); @@ -105,8 +104,7 @@ }); if (cvox.PlatformUtil.matchesPlatform(cvox.PlatformFilter.WML)) { - $('version').textContent = - chrome.app.getDetails().version; + $('version').textContent = chrome.app.getDetails().version; } var clearVirtualDisplay = function() { @@ -115,10 +113,11 @@ parseInt($('virtual_braille_display_rows_input').innerHTML, 10) * parseInt($('virtual_braille_display_columns_input').innerHTML, 10); for (var i = 0; i < sizeOfDisplay; i++) { - groups.push(['X', 'X']); + groups.push(['X', 'X']); } - (new PanelCommand(PanelCommandType.UPDATE_BRAILLE, - {groups: groups})).send(); + (new PanelCommand(PanelCommandType.UPDATE_BRAILLE, { + groups: groups + })).send(); }; $('changeDisplayStyle').addEventListener('click', function(evt) { @@ -126,16 +125,16 @@ localStorage['brailleSideBySide'] = sideBySide; $('changeDisplayStyle').textContent = sideBySide ? changeToInterleave : changeToSideBySide; - $('currentDisplayStyle').textContent = - sideBySide ? currentlyDisplayingSideBySide : + $('currentDisplayStyle').textContent = sideBySide ? + currentlyDisplayingSideBySide : currentlyDisplayingInterleave; clearVirtualDisplay(); }, true); - handleNumericalInputPref('virtual_braille_display_rows_input', - 'virtualBrailleRows'); - handleNumericalInputPref('virtual_braille_display_columns_input', - 'virtualBrailleColumns'); + handleNumericalInputPref( + 'virtual_braille_display_rows_input', 'virtualBrailleRows'); + handleNumericalInputPref( + 'virtual_braille_display_columns_input', 'virtualBrailleColumns'); }; /** @@ -164,12 +163,12 @@ $(id).addEventListener('input', function(evt) { if ($(id).value === '') { return; - } - else if (parseInt($(id).value, 10) < 1 || parseInt($(id).value, 10) > 99) { + } else if ( + parseInt($(id).value, 10) < 1 || parseInt($(id).value, 10) > 99) { chrome.storage.local.get(pref, function(items) { $(id).value = items[pref]; }); - }else { + } else { var items = {}; items[pref] = $(id).value; chrome.storage.local.set(items); @@ -241,10 +240,11 @@ if (table.dots !== dots) { continue; } - items.push({id: table.id, - name: cvox.BrailleTable.getDisplayName(table)}); + items.push({id: table.id, name: cvox.BrailleTable.getDisplayName(table)}); } - items.sort(function(a, b) { return a.name.localeCompare(b.name);}); + items.sort(function(a, b) { + return a.name.localeCompare(b.name); + }); for (var i = 0, item; item = items[i]; ++i) { var elem = document.createElement('option'); elem.id = item.id; @@ -285,8 +285,7 @@ } localStorage['brailleTable'] = localStorage['brailleTable6']; localStorage['brailleTableType'] = 'brailleTable6'; - tableTypeButton.textContent = - Msgs.getMsg('options_braille_table_type_6'); + tableTypeButton.textContent = Msgs.getMsg('options_braille_table_type_6'); } else { select6.parentElement.style.display = 'none'; select8.parentElement.style.display = 'block'; @@ -295,8 +294,7 @@ } localStorage['brailleTable'] = localStorage['brailleTable8']; localStorage['brailleTableType'] = 'brailleTable8'; - tableTypeButton.textContent = - Msgs.getMsg('options_braille_table_type_8'); + tableTypeButton.textContent = Msgs.getMsg('options_braille_table_type_8'); } cvox.OptionsPage.getBrailleTranslatorManager().refresh( localStorage['brailleTable']);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/prefs.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/prefs.js index 9073bcd..842e74d7 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/prefs.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/prefs.js
@@ -70,7 +70,7 @@ // TODO(dtseng): Leaking state about multiple key maps here until we have a // class to manage multiple key maps. Also, this doesn't belong as a pref; // should just store in local storage. - 'currentKeyMap' : cvox.KeyMap.DEFAULT_KEYMAP, + 'currentKeyMap': cvox.KeyMap.DEFAULT_KEYMAP, 'cvoxKey': '', 'earcons': true, 'focusFollowsMouse': false, @@ -111,7 +111,7 @@ * Switches to another key map. * @param {string} selectedKeyMap The id of the keymap in * cvox.KeyMap.AVAIABLE_KEYMAP_INFO. -*/ + */ cvox.ChromeVoxPrefs.prototype.switchToKeyMap = function(selectedKeyMap) { // Switching key maps potentially affects the key codes that involve // sequencing. Without resetting this list, potentially stale key @@ -184,8 +184,8 @@ * @param {boolean} sendPrefs Whether to send the prefs. * @param {boolean} sendKeyBindings Whether to send the key bindings. */ -cvox.ChromeVoxPrefs.prototype.sendPrefsToAllTabs = - function(sendPrefs, sendKeyBindings) { +cvox.ChromeVoxPrefs.prototype.sendPrefsToAllTabs = function( + sendPrefs, sendKeyBindings) { var context = this; var message = {}; if (sendPrefs) { @@ -211,9 +211,8 @@ * @param {Port} port The port representing the connection to a content script. */ cvox.ChromeVoxPrefs.prototype.sendPrefsToPort = function(port) { - port.postMessage({ - 'keyBindings': this.keyMap_.toJSON(), - 'prefs': this.getPrefs()}); + port.postMessage( + {'keyBindings': this.keyMap_.toJSON(), 'prefs': this.getPrefs()}); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/tabs_api_handler.js b/chrome/browser/resources/chromeos/chromevox/chromevox/background/tabs_api_handler.js index e957f4c..c46fce6 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/tabs_api_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/tabs_api_handler.js
@@ -66,9 +66,9 @@ return; } if (cvox.TabsApiHandler.shouldOutputSpeechAndBraille) { - cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_created'), - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); + cvox.ChromeVox.tts.speak( + this.msg_('chrome_tab_created'), cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); cvox.ChromeVox.braille.write( cvox.NavBraille.fromText(this.msg_('chrome_tab_created'))); } @@ -108,13 +108,11 @@ chrome.tabs.get(activeInfo.tabId, function(tab) { if (cvox.TabsApiHandler.shouldOutputSpeechAndBraille) { var title = tab.title ? tab.title : tab.url; - cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_selected', - [title]), - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); - cvox.ChromeVox.braille.write( - cvox.NavBraille.fromText( - this.msg_('chrome_tab_selected', [title]))); + cvox.ChromeVox.tts.speak( + this.msg_('chrome_tab_selected', [title]), cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); + cvox.ChromeVox.braille.write(cvox.NavBraille.fromText( + this.msg_('chrome_tab_selected', [title]))); } cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_SELECT); this.refreshAutomationHandler_(tab.id); @@ -186,11 +184,11 @@ var tab = tabs[0] || {}; if (cvox.TabsApiHandler.shouldOutputSpeechAndBraille) { var msgId = window.incognito ? 'chrome_incognito_window_selected' : - 'chrome_normal_window_selected'; + 'chrome_normal_window_selected'; var title = tab.title ? tab.title : tab.url; - cvox.ChromeVox.tts.speak(this.msg_(msgId, [title]), - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); + cvox.ChromeVox.tts.speak( + this.msg_(msgId, [title]), cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); cvox.ChromeVox.braille.write( cvox.NavBraille.fromText(this.msg_(msgId, [title]))); }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/active_indicator.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/active_indicator.js index c5df3d0..0d9d25b0 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/active_indicator.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/active_indicator.js
@@ -135,8 +135,7 @@ * @type {string} * @const */ -cvox.ActiveIndicator.STYLE = - '.cvox_indicator_container {' + +cvox.ActiveIndicator.STYLE = '.cvox_indicator_container {' + ' position: absolute !important;' + ' left: 0 !important;' + ' top: 0 !important;' + @@ -346,10 +345,8 @@ for (var i = 0; i < this.lastClientRects_.length; ++i) { var last = this.lastClientRects_[i]; var current = newClientRects[i]; - if (last.top != current.top || - last.right != current.right || - last.bottom != current.bottom || - last.left != last.left) { + if (last.top != current.top || last.right != current.right || + last.bottom != current.bottom || last.left != last.left) { needsUpdate = true; break; } @@ -434,8 +431,9 @@ if (window.getComputedStyle(document.body, null).position != 'static') { offsetX = -document.body.getBoundingClientRect().left; offsetY = -document.body.getBoundingClientRect().top; - } else if (window.getComputedStyle(document.documentElement, null).position != - 'static') { + } else if ( + window.getComputedStyle(document.documentElement, null).position != + 'static') { offsetX = -document.documentElement.getBoundingClientRect().left; offsetY = -document.documentElement.getBoundingClientRect().top; } else { @@ -556,8 +554,7 @@ // existing elements (which results in animating the transition). for (i = 0; i < regions.length; i++) { var parent = null; - if (i == 0 && - this.container_.childElementCount == 1 && + if (i == 0 && this.container_.childElementCount == 1 && this.container_.children[0].childElementCount == 6) { parent = this.container_.children[0]; } @@ -660,18 +657,18 @@ var q1 = Math.floor((3 * r.top + 1 * r.bottom) / 4); var q2 = Math.floor((2 * r.top + 2 * r.bottom) / 4); var q3 = Math.floor((1 * r.top + 3 * r.bottom) / 4); - this.setElementCoords_(regionTop, r.left, r.top, r.right, q1, - true, true, true, false); - this.setElementCoords_(regionMiddleNW, r.left, q1, r.left, q2, - true, true, false, false); - this.setElementCoords_(regionMiddleSW, r.left, q2, r.left, q3, - true, false, false, true); - this.setElementCoords_(regionMiddleNE, r.right, q1, r.right, q2, - false, true, true, false); - this.setElementCoords_(regionMiddleSE, r.right, q2, r.right, q3, - false, false, true, true); - this.setElementCoords_(regionBottom, r.left, q3, r.right, r.bottom, - true, false, true, true); + this.setElementCoords_( + regionTop, r.left, r.top, r.right, q1, true, true, true, false); + this.setElementCoords_( + regionMiddleNW, r.left, q1, r.left, q2, true, true, false, false); + this.setElementCoords_( + regionMiddleSW, r.left, q2, r.left, q3, true, false, false, true); + this.setElementCoords_( + regionMiddleNE, r.right, q1, r.right, q2, false, true, true, false); + this.setElementCoords_( + regionMiddleSE, r.right, q2, r.right, q3, false, false, true, true); + this.setElementCoords_( + regionBottom, r.left, q3, r.right, r.bottom, true, false, true, true); return; } @@ -704,10 +701,9 @@ middleIndex++; } middleRect = this.inset_(middleRect, -margin, -margin, -margin, -margin); - middleRect.left = Math.min( - middleRect.left, topRect.left, bottomRect.left); - middleRect.right = Math.max( - middleRect.right, topRect.right, bottomRect.right); + middleRect.left = Math.min(middleRect.left, topRect.left, bottomRect.left); + middleRect.right = + Math.max(middleRect.right, topRect.right, bottomRect.right); middleRect.width = middleRect.right - middleRect.left; } @@ -736,23 +732,17 @@ this.setElementRect_(regionBottom, bottomRect, true, false, true, true); this.setElementCoords_( - regionMiddleNW, - middleRect.left, topRect.bottom, topRect.left, midline, + regionMiddleNW, middleRect.left, topRect.bottom, topRect.left, midline, true, true, false, false); this.setElementCoords_( - regionMiddleNE, - topRect.right, topRect.bottom, - middleRect.right, midline, + regionMiddleNE, topRect.right, topRect.bottom, middleRect.right, midline, false, true, true, false); this.setElementCoords_( - regionMiddleSW, - middleRect.left, midline, bottomRect.left, bottomRect.top, + regionMiddleSW, middleRect.left, midline, bottomRect.left, bottomRect.top, true, false, false, true); this.setElementCoords_( - regionMiddleSE, - bottomRect.right, midline, - middleRect.right, bottomRect.top, - false, false, true, true); + regionMiddleSE, bottomRect.right, midline, middleRect.right, + bottomRect.top, false, false, true, true); }; /** @@ -766,10 +756,9 @@ */ cvox.ActiveIndicator.prototype.intersects_ = function(r1, r2) { var slop = 2 * cvox.ActiveIndicator.MARGIN; - return (r2.left <= r1.right + slop && - r2.right >= r1.left - slop && - r2.top <= r1.bottom + slop && - r2.bottom >= r1.top - slop); + return ( + r2.left <= r1.right + slop && r2.right >= r1.left - slop && + r2.top <= r1.bottom + slop && r2.bottom >= r1.top - slop); }; /** @@ -791,7 +780,7 @@ }; result.width = result.right - result.left; result.height = result.bottom - result.top; - return /** @type {ClientRect} */(result); + return /** @type {ClientRect} */ (result); }; /** @@ -817,7 +806,7 @@ }; result.width = result.right - result.left; result.height = result.bottom - result.top; - return /** @type {ClientRect} */(result); + return /** @type {ClientRect} */ (result); }; /** @@ -830,7 +819,7 @@ * @private */ cvox.ActiveIndicator.prototype.createDiv_ = function( - parent, className, opt_before) { + parent, className, opt_before) { var elem = document.createElement('div'); elem.setAttribute('aria-hidden', 'true'); @@ -901,9 +890,8 @@ * @private */ cvox.ActiveIndicator.prototype.setElementCoords_ = function( - element, - left, top, right, bottom, - showLeft, showTop, showRight, showBottom) { + element, left, top, right, bottom, showLeft, showTop, showRight, + showBottom) { var origWidth = right - left; var origHeight = bottom - top; @@ -960,9 +948,10 @@ * @private */ cvox.ActiveIndicator.prototype.setElementRect_ = function( - element, r, showLeft, showTop, showRight, showBottom) { - this.setElementCoords_(element, r.left, r.top, r.right, r.bottom, - showLeft, showTop, showRight, showBottom); + element, r, showLeft, showTop, showRight, showBottom) { + this.setElementCoords_( + element, r.left, r.top, r.right, r.bottom, showLeft, showTop, showRight, + showBottom); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js index 4804bd6..632d3f8 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api.js
@@ -16,248 +16,243 @@ } (function() { - /* - * Private data and methods. - */ +/* + * Private data and methods. + */ - /** - * The name of the port between the content script and background page. - * @type {string} - * @const - */ - var PORT_NAME = 'cvox.Port'; +/** + * The name of the port between the content script and background page. + * @type {string} + * @const + */ +var PORT_NAME = 'cvox.Port'; - /** - * The name of the message between the page and content script that sets - * up the bidirectional port between them. - * @type {string} - * @const - */ - var PORT_SETUP_MSG = 'cvox.PortSetup'; +/** + * The name of the message between the page and content script that sets + * up the bidirectional port between them. + * @type {string} + * @const + */ +var PORT_SETUP_MSG = 'cvox.PortSetup'; - /** - * The message between content script and the page that indicates the - * connection to the background page has been lost. - * @type {string} - * @const - */ - var DISCONNECT_MSG = 'cvox.Disconnect'; +/** + * The message between content script and the page that indicates the + * connection to the background page has been lost. + * @type {string} + * @const + */ +var DISCONNECT_MSG = 'cvox.Disconnect'; - /** - * The channel between the page and content script. - * @type {MessageChannel} - */ - var channel; +/** + * The channel between the page and content script. + * @type {MessageChannel} + */ +var channel; - /** - * Tracks whether or not the ChromeVox API should be considered active. - * @type {boolean} - */ - var isActive = false; +/** + * Tracks whether or not the ChromeVox API should be considered active. + * @type {boolean} + */ +var isActive = false; - /** - * The next id to use for async callbacks. - * @type {number} - */ - var nextCallbackId = 1; +/** + * The next id to use for async callbacks. + * @type {number} + */ +var nextCallbackId = 1; - /** - * Map from callback ID to callback function. - * @type {Object<number, function(*)>} - */ - var callbackMap = {}; +/** + * Map from callback ID to callback function. + * @type {Object<number, function(*)>} + */ +var callbackMap = {}; - /** - * Internal function to connect to the content script. - */ - function connect_() { - if (channel) { - // If there is already an existing channel, close the existing ports. - channel.port1.close(); - channel.port2.close(); - channel = null; - } +/** + * Internal function to connect to the content script. + */ +function connect_() { + if (channel) { + // If there is already an existing channel, close the existing ports. + channel.port1.close(); + channel.port2.close(); + channel = null; + } - channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - if (event.data == DISCONNECT_MSG) { - channel = null; - } - try { - var message = JSON.parse(event.data); - if (message['id'] && callbackMap[message['id']]) { - callbackMap[message['id']](message); - delete callbackMap[message['id']]; - } - } catch (e) { - } - }; - window.postMessage(PORT_SETUP_MSG, '*', [channel.port2]); - } + channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + if (event.data == DISCONNECT_MSG) { + channel = null; + } + try { + var message = JSON.parse(event.data); + if (message['id'] && callbackMap[message['id']]) { + callbackMap[message['id']](message); + delete callbackMap[message['id']]; + } + } catch (e) { + } + }; + window.postMessage(PORT_SETUP_MSG, '*', [channel.port2]); +} - /** - * Internal function to send a message to the content script and - * call a callback with the response. - * @param {Object} message A serializable message. - * @param {function(*)} callback A callback that will be called - * with the response message. - */ - function callAsync_(message, callback) { - var id = nextCallbackId; - nextCallbackId++; - if (message['args'] === undefined) { - message['args'] = []; - } - message['args'] = [id].concat(message['args']); - callbackMap[id] = callback; - channel.port1.postMessage(JSON.stringify(message)); - } +/** + * Internal function to send a message to the content script and + * call a callback with the response. + * @param {Object} message A serializable message. + * @param {function(*)} callback A callback that will be called + * with the response message. + */ +function callAsync_(message, callback) { + var id = nextCallbackId; + nextCallbackId++; + if (message['args'] === undefined) { + message['args'] = []; + } + message['args'] = [id].concat(message['args']); + callbackMap[id] = callback; + channel.port1.postMessage(JSON.stringify(message)); +} - /** - * Wraps callAsync_ for sending speak requests. - * @param {Object} message A serializable message. - * @param {Object=} properties Speech properties to use for this utterance. - * @private - */ - function callSpeakAsync_(message, properties) { - var callback = null; - /* Use the user supplied callback as callAsync_'s callback. */ - if (properties && properties['endCallback']) { - callback = properties['endCallback']; - } - callAsync_(message, callback); - } +/** + * Wraps callAsync_ for sending speak requests. + * @param {Object} message A serializable message. + * @param {Object=} properties Speech properties to use for this utterance. + * @private + */ +function callSpeakAsync_(message, properties) { + var callback = null; + /* Use the user supplied callback as callAsync_'s callback. */ + if (properties && properties['endCallback']) { + callback = properties['endCallback']; + } + callAsync_(message, callback); +} - /** - * Gets an object given a dotted namespace object path. - * @param {string} path - * @return {*} - */ - function getObjectByName(path) { - var pieces = path.split('.'); - var resolved = window; - for (var i = 0; i < pieces.length; i++) { - resolved = resolved[pieces[i]]; - if (!resolved) { - return null; - } - } - return resolved; - } +/** + * Gets an object given a dotted namespace object path. + * @param {string} path + * @return {*} + */ +function getObjectByName(path) { + var pieces = path.split('.'); + var resolved = window; + for (var i = 0; i < pieces.length; i++) { + resolved = resolved[pieces[i]]; + if (!resolved) { + return null; + } + } + return resolved; +} - /** - * Maybe enable MathJaX support. - */ - function maybeEnableMathJaX() { - if (!getObjectByName('MathJax.Hub.Register.LoadHook') || - !getObjectByName('MathJax.Ajax.Require')) { - return; - } +/** + * Maybe enable MathJaX support. + */ +function maybeEnableMathJaX() { + if (!getObjectByName('MathJax.Hub.Register.LoadHook') || + !getObjectByName('MathJax.Ajax.Require')) { + return; + } - MathJax.Hub.Register.LoadHook('[a11y]/explorer.js', function() { - // |explorer| is an object instance, so we get it to call an instance - // |method. - var explorer = getObjectByName('MathJax.Extension.explorer'); - if (explorer.Enable) { - explorer.Enable(true, true); - } - }); - MathJax.Ajax.Require('[a11y]/explorer.js'); - } + MathJax.Hub.Register.LoadHook('[a11y]/explorer.js', function() { + // |explorer| is an object instance, so we get it to call an instance + // |method. + var explorer = getObjectByName('MathJax.Extension.explorer'); + if (explorer.Enable) { + explorer.Enable(true, true); + } + }); + MathJax.Ajax.Require('[a11y]/explorer.js'); +} - /* - * Public API. - */ +/* + * Public API. + */ - if (!window['cvox']) { - window['cvox'] = {}; - } - var cvox = window.cvox; +if (!window['cvox']) { + window['cvox'] = {}; +} +var cvox = window.cvox; - /** - * ApiImplementation - this is only visible if all the scripts are compiled - * together like in the Android case. Otherwise, implementation will remain - * null which means communication must happen over the bridge. - * - * @type {*} - */ - var implementation = null; - if (typeof(cvox.ApiImplementation) != 'undefined') { - implementation = cvox.ApiImplementation; - } +/** + * ApiImplementation - this is only visible if all the scripts are compiled + * together like in the Android case. Otherwise, implementation will remain + * null which means communication must happen over the bridge. + * + * @type {*} + */ +var implementation = null; +if (typeof(cvox.ApiImplementation) != 'undefined') { + implementation = cvox.ApiImplementation; +} - /** - * @constructor - */ - cvox.Api = function() { - }; +/** + * @constructor + */ +cvox.Api = function() {}; - /** - * Internal-only function, only to be called by the content script. - * Enables the API and connects to the content script. - */ - cvox.Api.internalEnable = function() { - isActive = true; - maybeEnableMathJaX(); - if (!implementation) { - connect_(); - } - var event = document.createEvent('UIEvents'); - event.initEvent('chromeVoxLoaded', true, false); - document.dispatchEvent(event); - }; +/** + * Internal-only function, only to be called by the content script. + * Enables the API and connects to the content script. + */ +cvox.Api.internalEnable = function() { + isActive = true; + maybeEnableMathJaX(); + if (!implementation) { + connect_(); + } + var event = document.createEvent('UIEvents'); + event.initEvent('chromeVoxLoaded', true, false); + document.dispatchEvent(event); +}; - /** - * Returns true if ChromeVox is currently running. If the API is available - * in the JavaScript namespace but this method returns false, it means that - * the user has (temporarily) disabled ChromeVox. - * - * You can listen for the 'chromeVoxLoaded' event to be notified when - * ChromeVox is loaded. - * - * @return {boolean} True if ChromeVox is currently active. - */ - cvox.Api.isChromeVoxActive = function() { - if (implementation) { - return isActive; - } - return !!channel; - }; +/** + * Returns true if ChromeVox is currently running. If the API is available + * in the JavaScript namespace but this method returns false, it means that + * the user has (temporarily) disabled ChromeVox. + * + * You can listen for the 'chromeVoxLoaded' event to be notified when + * ChromeVox is loaded. + * + * @return {boolean} True if ChromeVox is currently active. + */ +cvox.Api.isChromeVoxActive = function() { + if (implementation) { + return isActive; + } + return !!channel; +}; - /** - * Speaks the given string using the specified queueMode and properties. - * - * @param {string} textString The string of text to be spoken. - * @param {number=} queueMode Valid modes are 0 for flush; 1 for queue. - * @param {Object=} properties Speech properties to use for this utterance. - */ - cvox.Api.speak = function(textString, queueMode, properties) { - if (!cvox.Api.isChromeVoxActive()) { - return; - } +/** + * Speaks the given string using the specified queueMode and properties. + * + * @param {string} textString The string of text to be spoken. + * @param {number=} queueMode Valid modes are 0 for flush; 1 for queue. + * @param {Object=} properties Speech properties to use for this utterance. + */ +cvox.Api.speak = function(textString, queueMode, properties) { + if (!cvox.Api.isChromeVoxActive()) { + return; + } - if (implementation) { - implementation.speak(textString, queueMode, properties); - } else { - var message = { - 'cmd': 'speak', - 'args': [textString, queueMode, properties] - }; - callSpeakAsync_(message, properties); - } - }; + if (implementation) { + implementation.speak(textString, queueMode, properties); + } else { + var message = {'cmd': 'speak', 'args': [textString, queueMode, properties]}; + callSpeakAsync_(message, properties); + } +}; - /** - * This method is kept to keep Docs from throwing an error. - * - */ - cvox.Api.stop = function() { - }; +/** + * This method is kept to keep Docs from throwing an error. + * + */ +cvox.Api.stop = function() {}; - cvox.Api.internalEnable(); +cvox.Api.internalEnable(); })();
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api_implementation.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api_implementation.js index 6f11e35..26b7fb4 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api_implementation.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/api_implementation.js
@@ -15,8 +15,7 @@ /** * @constructor */ -cvox.ApiImplementation = function() { -}; +cvox.ApiImplementation = function() {}; /** * Inject the API into the page and set up communication with it. @@ -26,8 +25,8 @@ window.addEventListener('message', cvox.ApiImplementation.portSetup, true); var scripts = [window.chrome.extension.getURL('chromevox/injected/api.js')]; - var didInstall = cvox.ScriptInstaller.installScript(scripts, - 'cvoxapi', opt_onload); + var didInstall = + cvox.ScriptInstaller.installScript(scripts, 'cvoxapi', opt_onload); if (!didInstall) { // If the API script is already installed, just re-enable it. window.location.href = 'javascript:cvox.Api.internalEnable();'; @@ -44,8 +43,7 @@ if (event.data == 'cvox.PortSetup') { cvox.ApiImplementation.port = event.ports[0]; cvox.ApiImplementation.port.onmessage = function(event) { - cvox.ApiImplementation.dispatchApiMessage( - JSON.parse(event.data)); + cvox.ApiImplementation.dispatchApiMessage(JSON.parse(event.data)); }; // Stop propagation since it was our message. @@ -62,8 +60,10 @@ cvox.ApiImplementation.dispatchApiMessage = function(message) { var method; switch (message['cmd']) { - case 'speak': method = cvox.ApiImplementation.speak; break; - break; + case 'speak': + method = cvox.ApiImplementation.speak; + break; + break; } if (!method) { throw 'Unknown API call: ' + message['cmd']; @@ -80,10 +80,7 @@ */ function setupEndCallback_(properties, callbackId) { var endCallback = function() { - cvox.ApiImplementation.port.postMessage(JSON.stringify( - { - 'id': callbackId - })); + cvox.ApiImplementation.port.postMessage(JSON.stringify({'id': callbackId})); }; if (properties) { properties['endCallback'] = endCallback; @@ -104,11 +101,13 @@ properties = {}; } setupEndCallback_(properties, callbackId); - var message = {'target': 'TTS', - 'action': 'speak', - 'text': textString, - 'queueMode': queueMode, - 'properties': properties}; + var message = { + 'target': 'TTS', + 'action': 'speak', + 'text': textString, + 'queueMode': queueMode, + 'properties': properties + }; cvox.ExtensionBridge.send(message); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/console_tts.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/console_tts.js index d828a22..72656b3 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/console_tts.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/console_tts.js
@@ -47,7 +47,9 @@ }; /** @override */ -cvox.ConsoleTts.prototype.isSpeaking = function() { return false; }; +cvox.ConsoleTts.prototype.isSpeaking = function() { + return false; +}; /** @override */ cvox.ConsoleTts.prototype.stop = function() { @@ -57,13 +59,13 @@ }; /** @override */ -cvox.ConsoleTts.prototype.addCapturingEventListener = function(listener) { }; +cvox.ConsoleTts.prototype.addCapturingEventListener = function(listener) {}; /** @override */ -cvox.ConsoleTts.prototype.increaseOrDecreaseProperty = function() { }; +cvox.ConsoleTts.prototype.increaseOrDecreaseProperty = function() {}; /** @override */ -cvox.ConsoleTts.prototype.propertyToPercentage = function() { }; +cvox.ConsoleTts.prototype.propertyToPercentage = function() {}; /** * Sets the enabled bit. @@ -74,7 +76,7 @@ }; /** @override */ -cvox.ConsoleTts.prototype.getDefaultProperty = function(property) { }; +cvox.ConsoleTts.prototype.getDefaultProperty = function(property) {}; /** @override */ -cvox.ConsoleTts.prototype.toggleSpeechOnOrOff = function() { }; +cvox.ConsoleTts.prototype.toggleSpeechOnOrOff = function() {};
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher.js index f628c09..982bada9 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher.js
@@ -35,8 +35,7 @@ /** * @constructor */ -cvox.ChromeVoxEventWatcher = function() { -}; +cvox.ChromeVoxEventWatcher = function() {}; /** * The maximum amount of time to wait before processing events. @@ -194,13 +193,13 @@ cvox.ChromeVoxEventWatcher.readyCallbacks_ = new Array(); -/** - * tracks whether we've received two or more key up's while pass through mode - * is active. - * @type {boolean} - * @private - */ -cvox.ChromeVoxEventWatcher.secondPassThroughKeyUp_ = false; + /** + * tracks whether we've received two or more key up's while pass through mode + * is active. + * @type {boolean} + * @private + */ + cvox.ChromeVoxEventWatcher.secondPassThroughKeyUp_ = false; /** * Whether or not the ChromeOS Search key (keyCode == 91) is being held. @@ -271,7 +270,8 @@ } if (!cvox.ChromeVoxEventWatcher.queueProcessingScheduled_) { cvox.ChromeVoxEventWatcher.queueProcessingScheduled_ = true; - window.setTimeout(cvox.ChromeVoxEventWatcher.processQueue_, + window.setTimeout( + cvox.ChromeVoxEventWatcher.processQueue_, cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_); } }; @@ -314,8 +314,8 @@ window.setTimeout(function() { cvox.ChromeVoxEventWatcher.readyCallbackRunning_ = false; if (!cvox.ChromeVoxEventWatcher.hasPendingEvents_() && - !cvox.ChromeVoxEventWatcher.queueProcessingScheduled_ && - cvox.ChromeVoxEventWatcher.readyCallbacks_.length > 0) { + !cvox.ChromeVoxEventWatcher.queueProcessingScheduled_ && + cvox.ChromeVoxEventWatcher.readyCallbacks_.length > 0) { cvox.ChromeVoxEventWatcher.readyCallbacks_.shift()(); cvox.ChromeVoxEventWatcher.maybeCallReadyCallbacks_(); } @@ -331,55 +331,55 @@ */ cvox.ChromeVoxEventWatcher.addEventListeners_ = function(doc) { // We always need key down listeners to intercept activate/deactivate. - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'keydown', cvox.ChromeVoxEventWatcher.keyDownEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'keydown', cvox.ChromeVoxEventWatcher.keyDownEventWatcher, true); // If ChromeVox isn't active, skip all other event listeners. if (!cvox.ChromeVox.isActive || cvox.ChromeVox.entireDocumentIsHidden) { return; } - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'keypress', cvox.ChromeVoxEventWatcher.keyPressEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'keyup', cvox.ChromeVoxEventWatcher.keyUpEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'keypress', cvox.ChromeVoxEventWatcher.keyPressEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'keyup', cvox.ChromeVoxEventWatcher.keyUpEventWatcher, true); // Listen for our own events to handle public user commands if the web app // doesn't do it for us. - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - cvox.UserEventDetail.Category.JUMP, - cvox.ChromeVoxUserCommands.handleChromeVoxUserEvent, - false); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, cvox.UserEventDetail.Category.JUMP, + cvox.ChromeVoxUserCommands.handleChromeVoxUserEvent, false); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'focus', cvox.ChromeVoxEventWatcher.focusEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'blur', cvox.ChromeVoxEventWatcher.blurEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'change', cvox.ChromeVoxEventWatcher.changeEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'copy', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'cut', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'paste', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'select', cvox.ChromeVoxEventWatcher.selectEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'focus', cvox.ChromeVoxEventWatcher.focusEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'blur', cvox.ChromeVoxEventWatcher.blurEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'change', cvox.ChromeVoxEventWatcher.changeEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'copy', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'cut', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'paste', cvox.ChromeVoxEventWatcher.clipboardEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'select', cvox.ChromeVoxEventWatcher.selectEventWatcher, true); // TODO(dtseng): Experimental, see: // https://developers.google.com/chrome/whitepapers/pagevisibility - cvox.ChromeVoxEventWatcher.addEventListener_(doc, 'webkitvisibilitychange', + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'webkitvisibilitychange', cvox.ChromeVoxEventWatcher.visibilityChangeWatcher, true); cvox.ChromeVoxEventWatcher.events_ = new Array(); cvox.ChromeVoxEventWatcher.queueProcessingScheduled_ = false; // Handle mouse events directly without going into the events queue. - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'mouseover', cvox.ChromeVoxEventWatcher.mouseOverEventWatcher, true); - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'mouseout', cvox.ChromeVoxEventWatcher.mouseOutEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'mouseover', cvox.ChromeVoxEventWatcher.mouseOverEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'mouseout', cvox.ChromeVoxEventWatcher.mouseOutEventWatcher, true); // With the exception of non-Android, click events go through the event queue. - cvox.ChromeVoxEventWatcher.addEventListener_(doc, - 'click', cvox.ChromeVoxEventWatcher.mouseClickEventWatcher, true); + cvox.ChromeVoxEventWatcher.addEventListener_( + doc, 'click', cvox.ChromeVoxEventWatcher.mouseClickEventWatcher, true); cvox.ChromeVoxEventWatcher.mutationObserver_ = new window.WebKitMutationObserver( @@ -441,8 +441,8 @@ * before they're sent to targets beneath it in the DOM tree. * @private */ -cvox.ChromeVoxEventWatcher.addEventListener_ = function(doc, type, - listener, useCapture) { +cvox.ChromeVoxEventWatcher.addEventListener_ = function( + doc, type, listener, useCapture) { cvox.ChromeVoxEventWatcher.listeners_.push( {'type': type, 'listener': listener, 'useCapture': useCapture}); doc.addEventListener(type, listener, useCapture); @@ -464,8 +464,8 @@ */ cvox.ChromeVoxEventWatcher.setLastFocusedNode_ = function(element) { cvox.ChromeVoxEventWatcher.lastFocusedNode = element; - cvox.ChromeVoxEventWatcher.lastFocusedNodeValue = !element ? null : - cvox.DomUtil.getControlValueAndStateString(element); + cvox.ChromeVoxEventWatcher.lastFocusedNodeValue = + !element ? null : cvox.DomUtil.getControlValueAndStateString(element); }; /** @@ -482,8 +482,7 @@ cvox.ChromeVox.navigationManager.updateIndicatorIfChanged(); cvox.LiveRegions.processMutations( - mutations, - function(assertive, navDescriptions) { + mutations, function(assertive, navDescriptions) { var evt = new window.Event('LiveRegion'); evt.navDescriptions = navDescriptions; evt.assertive = assertive; @@ -519,8 +518,7 @@ // happens in a focused text field). cvox.Focuser.setFocus(cvox.ChromeVox.navigationManager.getCurrentNode()); cvox.ChromeVox.tts.speak( - Msgs.getMsg('element_clicked'), - cvox.ChromeVoxEventWatcher.queueMode_(), + Msgs.getMsg('element_clicked'), cvox.ChromeVoxEventWatcher.queueMode_(), cvox.AbstractTts.PERSONALITY_ANNOTATION); var targetNode = cvox.ChromeVox.navigationManager.getCurrentNode(); // If the targetNode has a defined onclick function, just call it directly @@ -558,7 +556,7 @@ } if (cvox.DomUtil.isDescendantOfNode( - cvox.ChromeVoxEventWatcher.announcedMouseOverNode, evt.target)) { + cvox.ChromeVoxEventWatcher.announcedMouseOverNode, evt.target)) { return true; } @@ -580,24 +578,23 @@ // Only focus and announce if the mouse stays over the same target // for longer than the given delay. - cvox.ChromeVoxEventWatcher.mouseOverTimeoutId = window.setTimeout( - function() { - cvox.ChromeVoxEventWatcher.mouseOverTimeoutId = null; - if (evt.target != cvox.ChromeVoxEventWatcher.pendingMouseOverNode) { - return; - } + cvox.ChromeVoxEventWatcher.mouseOverTimeoutId = window.setTimeout(function() { + cvox.ChromeVoxEventWatcher.mouseOverTimeoutId = null; + if (evt.target != cvox.ChromeVoxEventWatcher.pendingMouseOverNode) { + return; + } - cvox.Memoize.scope(function() { - cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance = true; - cvox.ChromeVox.navigationManager.stopReading(true); - var target = /** @type {Node} */(evt.target); - cvox.Focuser.setFocus(target); - cvox.ChromeVox.navigationManager.syncToNode( - target, true, cvox.ChromeVoxEventWatcher.queueMode_()); + cvox.Memoize.scope(function() { + cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance = true; + cvox.ChromeVox.navigationManager.stopReading(true); + var target = /** @type {Node} */ (evt.target); + cvox.Focuser.setFocus(target); + cvox.ChromeVox.navigationManager.syncToNode( + target, true, cvox.ChromeVoxEventWatcher.queueMode_()); - cvox.ChromeVoxEventWatcher.announcedMouseOverNode = target; - }); - }, mouseoverDelayMs); + cvox.ChromeVoxEventWatcher.announcedMouseOverNode = target; + }); + }, mouseoverDelayMs); return true; }; @@ -637,7 +634,7 @@ cvox.ChromeVoxEventWatcher.addEvent(evt); } else if (evt.target && evt.target.nodeType == Node.ELEMENT_NODE) { cvox.ChromeVoxEventWatcher.setLastFocusedNode_( - /** @type {Element} */(evt.target)); + /** @type {Element} */ (evt.target)); } return true; }; @@ -651,8 +648,7 @@ if (!cvox.ChromeVox.documentHasFocus()) { return; } - if (evt.target && - evt.target.hasAttribute && + if (evt.target && evt.target.hasAttribute && evt.target.getAttribute('aria-hidden') == 'true' && evt.target.getAttribute('chromevoxignoreariahidden') != 'true') { cvox.ChromeVoxEventWatcher.setLastFocusedNode_(null); @@ -660,7 +656,7 @@ return; } if (evt.target && evt.target != window) { - var target = /** @type {Element} */(evt.target); + var target = /** @type {Element} */ (evt.target); var parentControl = cvox.DomUtil.getSurroundingControl(target); if (parentControl && parentControl == cvox.ChromeVoxEventWatcher.lastFocusedNode) { @@ -670,7 +666,7 @@ if (parentControl) { cvox.ChromeVoxEventWatcher.setLastFocusedNode_( - /** @type {Element} */(parentControl)); + /** @type {Element} */ (parentControl)); } else { cvox.ChromeVoxEventWatcher.setLastFocusedNode_(target); } @@ -762,8 +758,7 @@ } // Store some extra ChromeVox-specific properties in the event. - evt.searchKeyHeld = - cvox.ChromeVox.searchKeyHeld && cvox.ChromeVox.isActive; + evt.searchKeyHeld = cvox.ChromeVox.searchKeyHeld && cvox.ChromeVox.isActive; evt.stickyMode = cvox.ChromeVox.isStickyModeOn() && cvox.ChromeVox.isActive; evt.keyPrefix = cvox.ChromeVox.keyPrefixOn && cvox.ChromeVox.isActive; @@ -843,11 +838,12 @@ // skips potentially costly computations (especially for content editable). // This is done deliberately for the sake of responsiveness and in some cases // (e.g. content editable), to have characters echoed properly. - if (cvox.ChromeVoxEditableTextBase.eventTypingEcho && (speakChar && - cvox.DomPredicates.editTextPredicate([document.activeElement])) && + if (cvox.ChromeVoxEditableTextBase.eventTypingEcho && + (speakChar && + cvox.DomPredicates.editTextPredicate([document.activeElement])) && document.activeElement.type !== 'password') { - cvox.ChromeVox.tts.speak(String.fromCharCode(evt.charCode), - cvox.QueueMode.FLUSH); + cvox.ChromeVox.tts.speak( + String.fromCharCode(evt.charCode), cvox.QueueMode.FLUSH); } cvox.ChromeVoxEventWatcher.addEvent(evt); if (cvox.ChromeVoxEventWatcher.eventToEat && @@ -880,9 +876,8 @@ cvox.ChromeVoxEventWatcher.clipboardEventWatcher = function(evt) { // Don't announce anything unless this document has focus and the // editable element that's the target of the clipboard event is visible. - var targetNode = /** @type {Node} */(evt.target); - if (!cvox.ChromeVox.documentHasFocus() || - !targetNode || + var targetNode = /** @type {Node} */ (evt.target); + if (!cvox.ChromeVox.documentHasFocus() || !targetNode || !cvox.DomUtil.isVisible(targetNode) || cvox.AriaUtil.isHidden(targetNode)) { return true; @@ -890,16 +885,15 @@ var text = ''; switch (evt.type) { - case 'paste': - text = evt.clipboardData.getData('text'); - break; - case 'copy': - case 'cut': - text = window.getSelection().toString(); - break; + case 'paste': + text = evt.clipboardData.getData('text'); + break; + case 'copy': + case 'cut': + text = window.getSelection().toString(); + break; } - cvox.ChromeVox.tts.speak( - Msgs.getMsg(evt.type, [text]), cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak(Msgs.getMsg(evt.type, [text]), cvox.QueueMode.QUEUE); cvox.ChromeVox.navigationManager.clearPageSel(); return true; }; @@ -957,8 +951,7 @@ * representing the description of the live region changes. * @private */ -cvox.ChromeVoxEventWatcher.speakLiveRegion_ = function( - assertive, messages) { +cvox.ChromeVoxEventWatcher.speakLiveRegion_ = function(assertive, messages) { var queueMode = cvox.ChromeVoxEventWatcher.queueMode_(); var descSpeaker = new cvox.NavigationSpeaker(); descSpeaker.speakDescriptionArray(messages, queueMode, null); @@ -970,8 +963,7 @@ */ cvox.ChromeVoxEventWatcher.setUpTextHandler = function() { var currentFocus = document.activeElement; - if (currentFocus && - currentFocus.hasAttribute && + if (currentFocus && currentFocus.hasAttribute && currentFocus.getAttribute('aria-hidden') == 'true' && currentFocus.getAttribute('chromevoxignoreariahidden') != 'true') { currentFocus = null; @@ -1002,17 +994,19 @@ cvox.ChromeVoxEventWatcher.currentTextControl = currentFocus; cvox.ChromeVoxEventWatcher.currentTextHandler = new cvox.ChromeVoxEditableHTMLInput(currentFocus, cvox.ChromeVox.tts); - } else if ((currentFocus.constructor == HTMLTextAreaElement) && + } else if ( + (currentFocus.constructor == HTMLTextAreaElement) && cvox.ChromeVoxEventWatcher.shouldEchoKeys) { cvox.ChromeVoxEventWatcher.currentTextControl = currentFocus; cvox.ChromeVoxEventWatcher.currentTextHandler = new cvox.ChromeVoxEditableTextArea(currentFocus, cvox.ChromeVox.tts); - } else if (currentFocus.isContentEditable || - currentFocus.getAttribute('role') == 'textbox') { + } else if ( + currentFocus.isContentEditable || + currentFocus.getAttribute('role') == 'textbox') { cvox.ChromeVoxEventWatcher.currentTextControl = currentFocus; cvox.ChromeVoxEventWatcher.currentTextHandler = - new cvox.ChromeVoxEditableContentEditable(currentFocus, - cvox.ChromeVox.tts); + new cvox.ChromeVoxEditableContentEditable( + currentFocus, cvox.ChromeVox.tts); } if (cvox.ChromeVoxEventWatcher.currentTextControl) { @@ -1134,9 +1128,8 @@ } var activeDescendant = cvox.AriaUtil.getActiveDescendant(control); - if ((parentControl && - parentControl != control && - document.activeElement == control)) { + if ((parentControl && parentControl != control && + document.activeElement == control)) { // Sync ChromeVox to the newly selected control. cvox.ChromeVox.navigationManager.syncToNode( activeDescendant || control, true, @@ -1145,17 +1138,15 @@ announceChange = false; } else if (activeDescendant) { cvox.ChromeVox.navigationManager.updateSelToArbitraryNode( - activeDescendant, - true); + activeDescendant, true); announceChange = true; } if (newValue && announceChange && !cvox.ChromeVoxEventSuspender.areEventsSuspended()) { - cvox.ChromeVox.tts.speak(newValue, - cvox.ChromeVoxEventWatcher.queueMode_(), - null); + cvox.ChromeVox.tts.speak( + newValue, cvox.ChromeVoxEventWatcher.queueMode_(), null); cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(newValue)); } }; @@ -1173,7 +1164,7 @@ var control = evt.target; if (control.tagName == 'SELECT' && (control.size <= 1) && - (evt.keyCode == 13 || evt.keyCode == 32)) { // Enter or Space + (evt.keyCode == 13 || evt.keyCode == 32)) { // Enter or Space // TODO (dmazzoni, clchen): Remove this workaround once accessibility // APIs make browser based popups accessible. // @@ -1246,29 +1237,26 @@ if (cvox.ChromeVox.navigationManager.currentDialog && !dialog) { if (!cvox.DomUtil.isDescendantOfNode( - document.activeElement, - cvox.ChromeVox.navigationManager.currentDialog)) { + document.activeElement, + cvox.ChromeVox.navigationManager.currentDialog)) { cvox.ChromeVox.navigationManager.currentDialog = null; cvox.ChromeVoxEventWatcher.speakAnnotationWithCategory_( - Msgs.getMsg('exiting_dialog'), - cvox.TtsCategory.NAV); + Msgs.getMsg('exiting_dialog'), cvox.TtsCategory.NAV); return true; } } else { if (dialog) { cvox.ChromeVox.navigationManager.currentDialog = dialog; cvox.ChromeVoxEventWatcher.speakAnnotationWithCategory_( - Msgs.getMsg('entering_dialog'), - cvox.TtsCategory.NAV); + Msgs.getMsg('entering_dialog'), cvox.TtsCategory.NAV); if (role == 'alertdialog') { var dialogDescArray = cvox.DescriptionUtil.getFullDescriptionsFromChildren(null, dialog); var descSpeaker = new cvox.NavigationSpeaker(); - descSpeaker.speakDescriptionArray(dialogDescArray, - cvox.QueueMode.QUEUE, - null); + descSpeaker.speakDescriptionArray( + dialogDescArray, cvox.QueueMode.QUEUE, null); } return true; } @@ -1294,9 +1282,7 @@ } properties['category'] = category; cvox.ChromeVox.tts.speak( - text, - cvox.ChromeVoxEventWatcher.queueMode_(), - properties); + text, cvox.ChromeVoxEventWatcher.queueMode_(), properties); }; /** @@ -1388,10 +1374,10 @@ if (lastFocusIndex >= 0 && cvox.ChromeVoxEventWatcherUtil.shouldWaitToProcess( lastFocusTimestamp, - cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime, - currentTime)) { - window.setTimeout(cvox.ChromeVoxEventWatcher.processQueue_, - cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_); + cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime, currentTime)) { + window.setTimeout( + cvox.ChromeVoxEventWatcher.processQueue_, + cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_); return; } @@ -1438,7 +1424,7 @@ break; case 'click': cvox.ChromeVox.navigationManager.syncToNode( - /** @type {Node} */(evt.target), true); + /** @type {Node} */ (evt.target), true); break; case 'focus': cvox.ChromeVoxEventWatcher.focusHandler(evt); @@ -1467,19 +1453,18 @@ */ cvox.ChromeVoxEventWatcher.setUpTimeHandler_ = function() { var currentFocus = document.activeElement; - if (currentFocus && - currentFocus.hasAttribute && + if (currentFocus && currentFocus.hasAttribute && currentFocus.getAttribute('aria-hidden') == 'true' && currentFocus.getAttribute('chromevoxignoreariahidden') != 'true') { currentFocus = null; } - if (currentFocus.constructor == HTMLInputElement && - currentFocus.type && (currentFocus.type == 'time')) { + if (currentFocus.constructor == HTMLInputElement && currentFocus.type && + (currentFocus.type == 'time')) { cvox.ChromeVoxEventWatcher.currentTimeHandler = new cvox.ChromeVoxHTMLTimeWidget(currentFocus, cvox.ChromeVox.tts); - } else { - cvox.ChromeVoxEventWatcher.currentTimeHandler = null; - } + } else { + cvox.ChromeVoxEventWatcher.currentTimeHandler = null; + } return (null != cvox.ChromeVoxEventWatcher.currentTimeHandler); }; @@ -1491,8 +1476,7 @@ */ cvox.ChromeVoxEventWatcher.setUpMediaHandler_ = function() { var currentFocus = document.activeElement; - if (currentFocus && - currentFocus.hasAttribute && + if (currentFocus && currentFocus.hasAttribute && currentFocus.getAttribute('aria-hidden') == 'true' && currentFocus.getAttribute('chromevoxignoreariahidden') != 'true') { currentFocus = null; @@ -1501,9 +1485,9 @@ (currentFocus.constructor == HTMLAudioElement)) { cvox.ChromeVoxEventWatcher.currentMediaHandler = new cvox.ChromeVoxHTMLMediaWidget(currentFocus, cvox.ChromeVox.tts); - } else { - cvox.ChromeVoxEventWatcher.currentMediaHandler = null; - } + } else { + cvox.ChromeVoxEventWatcher.currentMediaHandler = null; + } return (null != cvox.ChromeVoxEventWatcher.currentMediaHandler); }; @@ -1514,21 +1498,18 @@ */ cvox.ChromeVoxEventWatcher.setUpDateHandler_ = function() { var currentFocus = document.activeElement; - if (currentFocus && - currentFocus.hasAttribute && + if (currentFocus && currentFocus.hasAttribute && currentFocus.getAttribute('aria-hidden') == 'true' && currentFocus.getAttribute('chromevoxignoreariahidden') != 'true') { currentFocus = null; } - if (currentFocus.constructor == HTMLInputElement && - currentFocus.type && - ((currentFocus.type == 'date') || - (currentFocus.type == 'month') || - (currentFocus.type == 'week'))) { + if (currentFocus.constructor == HTMLInputElement && currentFocus.type && + ((currentFocus.type == 'date') || (currentFocus.type == 'month') || + (currentFocus.type == 'week'))) { cvox.ChromeVoxEventWatcher.currentDateHandler = new cvox.ChromeVoxHTMLDateWidget(currentFocus, cvox.ChromeVox.tts); - } else { - cvox.ChromeVoxEventWatcher.currentDateHandler = null; - } + } else { + cvox.ChromeVoxEventWatcher.currentDateHandler = null; + } return (null != cvox.ChromeVoxEventWatcher.currentDateHandler); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/externs.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/externs.js index bf3e55c..10d55eee 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/externs.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/externs.js
@@ -17,7 +17,7 @@ * @param {Array<*>} args * @param {string} err */ -MathJax.Callback.After = function(args, err) { }; +MathJax.Callback.After = function(args, err) {}; /** @@ -40,11 +40,11 @@ /** * @param {string} name */ -MathJax.RootElement.prototype.toMathML = function(name) { }; +MathJax.RootElement.prototype.toMathML = function(name) {}; /** */ -MathJax.RootElement.prototype.toMathMLattributes = function() { }; +MathJax.RootElement.prototype.toMathMLattributes = function() {}; /** @@ -55,11 +55,11 @@ /** * @param {string} id */ -MathJax.Hub.getJaxFor = function(id) { }; +MathJax.Hub.getJaxFor = function(id) {}; /** */ -MathJax.Hub.getAllJax = function() { }; +MathJax.Hub.getAllJax = function() {}; /** * @type {{PreProcessor: Function, @@ -88,7 +88,7 @@ /** * @param {?string} mml MathML expression. */ -MathJax.ElementJax.mml = function(mml) { }; +MathJax.ElementJax.mml = function(mml) {}; /** @@ -108,7 +108,7 @@ /** * @param {string} err */ -MathJax.ElementJax.mml.merror = function(err) { }; +MathJax.ElementJax.mml.merror = function(err) {}; /** @@ -143,7 +143,7 @@ * @param {Object<string>} attribs * @param {Array<string>} text */ -MathJax.HTML.Element = function(tag, attribs, text) { }; +MathJax.HTML.Element = function(tag, attribs, text) {}; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/history.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/history.js index e2b73a6..5ed3a94 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/history.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/history.js
@@ -300,8 +300,7 @@ 'User command ' + functionName + ' overlaps current event', this.currentEvent_); } - this.currentEvent_ = new cvox.HistoryEvent() - .withUserCommand(functionName); + this.currentEvent_ = new cvox.HistoryEvent().withUserCommand(functionName); this.events_.push(this.currentEvent_); }; @@ -335,20 +334,22 @@ /** @override */ -cvox.History.prototype.isSpeaking = function() { return false; }; +cvox.History.prototype.isSpeaking = function() { + return false; +}; /** @override */ -cvox.History.prototype.stop = function() { }; +cvox.History.prototype.stop = function() {}; /** @override */ -cvox.History.prototype.addCapturingEventListener = function(listener) { }; +cvox.History.prototype.addCapturingEventListener = function(listener) {}; /** @override */ -cvox.History.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { }; +cvox.History.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) {}; /** @override */ -cvox.History.prototype.propertyToPercentage = function(property) { }; +cvox.History.prototype.propertyToPercentage = function(property) {}; /** @override */ -cvox.History.prototype.getDefaultProperty = function(property) { }; +cvox.History.prototype.getDefaultProperty = function(property) {}; /** @override */ -cvox.History.prototype.toggleSpeechOnOrOff = function() { }; +cvox.History.prototype.toggleSpeechOnOrOff = function() {}; /** TODO: add doc comment. */ @@ -367,14 +368,20 @@ cvox.History.prototype.dumpJsOutput_ = function(opt_skipCommands) { var skipMap = {}; if (opt_skipCommands) { - opt_skipCommands.forEach(function(e) { skipMap[e] = 1; }); + opt_skipCommands.forEach(function(e) { + skipMap[e] = 1; + }); } // TODO: pretty print - return ['/*DOC: += ', - this.nodeBreadcrumb_.dumpWalkedDom().innerHTML, '*/\n'] + return ['/*DOC: += ', this.nodeBreadcrumb_.dumpWalkedDom().innerHTML, '*/\n'] .concat(this.events_ - .filter(function(e) { return ! (e.userCommand_ in skipMap); }) - .map(function(e) { return e.outputJs(); })).join(''); + .filter(function(e) { + return !(e.userCommand_ in skipMap); + }) + .map(function(e) { + return e.outputJs(); + })) + .join(''); }; @@ -393,11 +400,11 @@ var runFeedbackScript = document.createElement('script'); runFeedbackScript.type = 'text/javascript'; - runFeedbackScript.innerHTML = - 'userfeedback.api.startFeedback(' + - '{ productId: \'76092\' }, ' + - '{ cvoxHistory: ' + cvox.ChromeVoxJSON.stringify( - cvox.ChromeVoxJSON.stringify(output)) + ' });'; + runFeedbackScript.innerHTML = 'userfeedback.api.startFeedback(' + + '{ productId: \'76092\' }, ' + + '{ cvoxHistory: ' + + cvox.ChromeVoxJSON.stringify(cvox.ChromeVoxJSON.stringify(output)) + + ' });'; feedbackScript.onload = function() { document.body.appendChild(runFeedbackScript);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_document.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_document.js index 79c0168..9784e63 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_document.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_document.js
@@ -60,16 +60,13 @@ */ cvox.ChromeVox.recallInit_ = function(reason) { if (cvox.ChromeVox.initTimeout_ > cvox.ChromeVox.MAX_INIT_TIMEOUT_) { - window.console.log(reason + - ' Taking too long - giving up.'); + window.console.log(reason + ' Taking too long - giving up.'); return; } - window.console.log(reason + - ' Will try again in ' + - cvox.ChromeVox.initTimeout_ + 'ms'); + window.console.log( + reason + ' Will try again in ' + cvox.ChromeVox.initTimeout_ + 'ms'); cvox.ChromeVox.initTimer_ = window.setTimeout( - cvox.ChromeVox.initDocument, - cvox.ChromeVox.initTimeout_); + cvox.ChromeVox.initDocument, cvox.ChromeVox.initTimeout_); cvox.ChromeVox.initTimeout_ *= 2; }; @@ -97,19 +94,13 @@ if (disableContentScript) { var url = location.href; url = url.substring(0, url.indexOf('#')) || url; - cvox.ExtensionBridge.send({ - target: 'next', - action: 'enableClassicCompatForUrl', - url: url - }); + cvox.ExtensionBridge.send( + {target: 'next', action: 'enableClassicCompatForUrl', url: url}); return; } - cvox.ExtensionBridge.send({ - target: 'next', - action: 'getIsClassicEnabled', - url: location.href - }); + cvox.ExtensionBridge.send( + {target: 'next', action: 'getIsClassicEnabled', url: location.href}); cvox.ChromeVox.initTimer_ = 0; var reinitReason; @@ -120,8 +111,8 @@ reinitReason = 'ChromeVox waiting for background page'; } if (reinitReason) { - cvox.ChromeVox.recallInit_(reinitReason + ': ' + - document.location.href + '.'); + cvox.ChromeVox.recallInit_( + reinitReason + ': ' + document.location.href + '.'); return; } @@ -133,8 +124,9 @@ cvox.ChromeVox.host = cvox.HostFactory.getHost(); if (!cvox.ChromeVox.host.ttsLoaded()) { - cvox.ChromeVox.recallInit_('ChromeVox not starting; waiting for TTS. ' + - document.location.href + '.'); + cvox.ChromeVox.recallInit_( + 'ChromeVox not starting; waiting for TTS. ' + document.location.href + + '.'); return; }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_globals.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_globals.js index 73df385..31330e9b 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_globals.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/init_globals.js
@@ -22,7 +22,7 @@ /** * @constructor */ -cvox.InitGlobals = function() { }; +cvox.InitGlobals = function() {}; /** @@ -34,9 +34,9 @@ } cvox.ChromeVox.tts = new cvox.CompositeTts() - .add(cvox.HostFactory.getTts()) - .add(cvox.History.getInstance()) - .add(cvox.ConsoleTts.getInstance()); + .add(cvox.HostFactory.getTts()) + .add(cvox.History.getInstance()) + .add(cvox.ConsoleTts.getInstance()); if (!cvox.ChromeVox.braille) { cvox.ChromeVox.braille = cvox.HostFactory.getBraille();
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/initial_speech.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/initial_speech.js index fa1fcf6..6bfac70b 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/initial_speech.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/initial_speech.js
@@ -48,15 +48,13 @@ } if (title && !disableSpeak) { - cvox.ChromeVox.tts.speak( - title, cvox.QueueMode.FLUSH); + cvox.ChromeVox.tts.speak(title, cvox.QueueMode.FLUSH); } cvox.BrailleOverlayWidget.getInstance().init(); } // Initialize live regions and speak alerts. - cvox.LiveRegions.init( - new Date(), cvox.QueueMode.QUEUE, disableSpeak); + cvox.LiveRegions.init(new Date(), cvox.QueueMode.QUEUE, disableSpeak); // If our activeElement is on body, try to sync to the first element. This // actually happens inside of NavigationManager.reset, which doesn't get
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions.js index 3eedf086..4100d80 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions.js
@@ -21,8 +21,7 @@ /** * @constructor */ -cvox.LiveRegions = function() { -}; +cvox.LiveRegions = function() {}; /** * @type {Date} @@ -62,7 +61,7 @@ /** * @type {Date} -*/ + */ cvox.LiveRegions.lastAnnouncedTime = null; /** @@ -92,10 +91,7 @@ var regions = cvox.AriaUtil.getLiveRegions(document.body); for (var i = 0; i < regions.length; i++) { cvox.LiveRegions.handleOneChangedNode( - regions[i], - regions[i], - false, - false, + regions[i], regions[i], false, false, function(assertive, navDescriptions) { if (!assertive && queueMode == cvox.QueueMode.FLUSH) { queueMode = cvox.QueueMode.QUEUE; @@ -121,8 +117,8 @@ for (var j = 0, description; description = structs[j]; j++) { descriptions.push(new cvox.NavDescription(description)); } - new cvox.NavigationSpeaker() - .speakDescriptionArray(descriptions, message['queueMode'], null); + new cvox.NavigationSpeaker().speakDescriptionArray( + descriptions, message['queueMode'], null); } } }); @@ -310,8 +306,7 @@ * @param {function(boolean, Array<cvox.NavDescription>)} handler * Callback function to be called for each live region found. */ -cvox.LiveRegions.announceChange = function( - node, liveRoot, isRemoval, handler) { +cvox.LiveRegions.announceChange = function(node, liveRoot, isRemoval, handler) { // If this node is in an atomic container, announce the whole container. // This includes aria-atomic, but also ARIA controls and other nodes // whose ARIA roles make them leaves. @@ -335,9 +330,10 @@ if (isRemoval) { navDescriptions = [cvox.DescriptionUtil.getDescriptionFromAncestors( [node], true, cvox.ChromeVox.verbosity)]; - navDescriptions = [new cvox.NavDescription({ - context: Msgs.getMsg('live_regions_removed'), text: '' - })].concat(navDescriptions); + navDescriptions = [ + new cvox.NavDescription( + {context: Msgs.getMsg('live_regions_removed'), text: ''}) + ].concat(navDescriptions); } if (navDescriptions.length == 0) { @@ -380,12 +376,12 @@ var assertive = cvox.AriaUtil.getAriaLive(liveRoot) == 'assertive'; if (cvox.Interframe.isIframe() && !cvox.ChromeVox.documentHasFocus()) { - cvox.Interframe.sendMessageToParentWindow( - {'command': 'speakLiveRegion', - 'content': JSON.stringify(navDescriptions), - 'queueMode': assertive ? 0 : 1, - 'src': window.location.href } - ); + cvox.Interframe.sendMessageToParentWindow({ + 'command': 'speakLiveRegion', + 'content': JSON.stringify(navDescriptions), + 'queueMode': assertive ? 0 : 1, + 'src': window.location.href + }); return; } @@ -415,10 +411,8 @@ allStrings.push(desc.userValue); } }); - navDescriptions = [new cvox.NavDescription({ - text: allStrings.join(', '), - category: cvox.TtsCategory.LIVE - })]; + navDescriptions = [new cvox.NavDescription( + {text: allStrings.join(', '), category: cvox.TtsCategory.LIVE})]; } handler(assertive, navDescriptions); @@ -435,8 +429,7 @@ * at this node. */ cvox.LiveRegions.getNavDescriptionsRecursive = function(node) { - if (cvox.AriaUtil.getAriaAtomic(node) || - cvox.DomUtil.isLeafNode(node)) { + if (cvox.AriaUtil.getAriaAtomic(node) || cvox.DomUtil.isLeafNode(node)) { var description = cvox.DescriptionUtil.getDescriptionFromAncestors( [node], true, cvox.ChromeVox.verbosity); if (!description.isEmpty()) { @@ -445,6 +438,7 @@ return []; } } - return cvox.DescriptionUtil.getFullDescriptionsFromChildren(null, + return cvox.DescriptionUtil.getFullDescriptionsFromChildren( + null, /** @type {!Element} */ (node)); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_history.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_history.js index 968564c..b092904 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_history.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_history.js
@@ -74,8 +74,7 @@ } // If list is too long, pop the last (oldest) item. - if (this.history_.length > - cvox.NavigationHistory.MAX_HISTORY_LEN_) { + if (this.history_.length > cvox.NavigationHistory.MAX_HISTORY_LEN_) { this.history_.pop(); } @@ -100,7 +99,7 @@ // changing very quickly. Be defensive here and allow the default // navigation action by returning true. if (!this.arrivedValid_) { - this.arrivedValid_ = true; // Reset flag. + this.arrivedValid_ = true; // Reset flag. return false; }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager.js index 6346841..5cdf52a 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager.js
@@ -85,20 +85,19 @@ * @type {!Array<Object>} * @private */ - this.shifterTypes_ = [cvox.NavigationShifter, - cvox.TableShifter, - cvox.MathShifter]; + this.shifterTypes_ = + [cvox.NavigationShifter, cvox.TableShifter, cvox.MathShifter]; /** * @type {!Array<!cvox.AbstractShifter>} - */ + */ this.shifterStack_ = []; /** * The active shifter. * @type {!cvox.AbstractShifter} * @private - */ + */ this.shifter_ = new cvox.NavigationShifter(); // NOTE(deboer): document.activeElement can not be null (c.f. @@ -416,11 +415,10 @@ } if (opt_speakNode) { - this.speakDescriptionArray(this.getDescription(), - /** @type {cvox.QueueMode} */ (opt_queueMode), - null, - null, - cvox.TtsCategory.NAV); + this.speakDescriptionArray( + this.getDescription(), + /** @type {cvox.QueueMode} */ (opt_queueMode), null, null, + cvox.TtsCategory.NAV); } cvox.ChromeVox.braille.write(this.getBraille()); @@ -438,8 +436,9 @@ var hasSel = !!this.pageSel_; if (hasSel && opt_announce) { var announcement = Msgs.getMsg('clear_page_selection'); - cvox.ChromeVox.tts.speak(announcement, cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + announcement, cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOTATION); } this.pageSel_ = null; return hasSel; @@ -452,7 +451,8 @@ * @return {boolean} Whether selection is on or off after this call. */ cvox.NavigationManager.prototype.togglePageSel = function() { - this.pageSel_ = this.pageSel_ ? null : + this.pageSel_ = this.pageSel_ ? + null : new cvox.PageSelection(this.curSel_.setReversed(false)); return !!this.pageSel_; }; @@ -489,8 +489,8 @@ } // Selected content. - var desc = this.pageSel_ ? this.pageSel_.getDescription( - this.shifter_, this.prevSel_, this.curSel_) : + var desc = this.pageSel_ ? + this.pageSel_.getDescription(this.shifter_, this.prevSel_, this.curSel_) : this.shifter_.getDescription(this.prevSel_, this.curSel_); var earcons = []; @@ -517,7 +517,7 @@ } if (earcons.length > 0 && desc.length > 0) { earcons.forEach(function(earcon) { - desc[0].pushEarcon(earcon); + desc[0].pushEarcon(earcon); }); } return desc; @@ -543,8 +543,7 @@ case 'enterShifter': case 'enterShifterSilently': for (var i = this.shifterTypes_.length - 1, shifterType; - shifterType = this.shifterTypes_[i]; - i--) { + shifterType = this.shifterTypes_[i]; i--) { var shifter = shifterType.create(this.curSel_); if (shifter && shifter.getName() != this.shifter_.getName()) { this.shifterStack_.push(this.shifter_); @@ -574,14 +573,13 @@ this.sync(); this.exitedShifter_ = true; break; - default: - if (this.shifter_.hasAction(name)) { - return this.updateSel( - this.shifter_.performAction(name, this.curSel_)); - } else { - return false; - } - } + default: + if (this.shifter_.hasAction(name)) { + return this.updateSel(this.shifter_.performAction(name, this.curSel_)); + } else { + return false; + } + } return true; }; @@ -688,10 +686,7 @@ * @param {string=} opt_category Optional category for all descriptions. */ cvox.NavigationManager.prototype.speakDescriptionArray = function( - descriptionArray, - initialQueueMode, - completionFunction, - opt_personality, + descriptionArray, initialQueueMode, completionFunction, opt_personality, opt_category) { if (opt_personality) { descriptionArray.forEach(function(desc) { @@ -718,8 +713,7 @@ */ cvox.NavigationManager.prototype.updatePosition = function(node) { var msg = cvox.ChromeVox.position; - msg[document.location.href] = - cvox.DomUtil.elementToPoint(node); + msg[document.location.href] = cvox.DomUtil.elementToPoint(node); cvox.ChromeVox.host.sendToBackgroundPage({ 'target': 'Prefs', @@ -754,8 +748,8 @@ if (this.isReversed()) { msg = Msgs.getMsg('wrapped_to_bottom'); } - cvox.ChromeVox.tts.speak(msg, cvox.QueueMode.QUEUE, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + msg, cvox.QueueMode.QUEUE, cvox.AbstractTts.PERSONALITY_ANNOTATION); } return; } @@ -780,11 +774,9 @@ opt_prefix, queueMode, cvox.AbstractTts.PERSONALITY_ANNOTATION); queueMode = cvox.QueueMode.QUEUE; } - this.speakDescriptionArray(descriptionArray, - queueMode, - opt_callback || null, - null, - cvox.TtsCategory.NAV); + this.speakDescriptionArray( + descriptionArray, queueMode, opt_callback || null, null, + cvox.TtsCategory.NAV); cvox.ChromeVox.braille.write(this.getBraille()); @@ -814,7 +806,7 @@ this.ensureNotSubnavigating(); if (opt_granularity !== undefined && (opt_granularity !== this.getGranularity() || - this.shifterStack_.length > 0)) { + this.shifterStack_.length > 0)) { this.setGranularity(opt_granularity, true); this.sync(); } @@ -899,17 +891,17 @@ */ cvox.NavigationManager.prototype.startCallbackReading_ = cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode) { - this.finishNavCommand('', true, queueMode, goog.bind(function() { - if (this.prevReadingSel_ == this.curSel_) { - this.stopReading(); - return; - } - this.prevReadingSel_ = this.curSel_; - if (this.next_(true) && this.keepReading_) { - this.startCallbackReading_(cvox.QueueMode.QUEUE); - } - }, this)); -}); + this.finishNavCommand('', true, queueMode, goog.bind(function() { + if (this.prevReadingSel_ == this.curSel_) { + this.stopReading(); + return; + } + this.prevReadingSel_ = this.curSel_; + if (this.next_(true) && this.keepReading_) { + this.startCallbackReading_(cvox.QueueMode.QUEUE); + } + }, this)); + }); /** @@ -920,18 +912,18 @@ */ cvox.NavigationManager.prototype.startNonCallbackReading_ = cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode) { - if (!this.keepReading_) { - return; - } + if (!this.keepReading_) { + return; + } - if (!cvox.ChromeVox.tts.isSpeaking()) { - this.finishNavCommand('', true, queueMode, null); - if (!this.next_(true)) { - this.keepReading_ = false; - } - } - window.setTimeout(goog.bind(this.startNonCallbackReading_, this), 1000); -}); + if (!cvox.ChromeVox.tts.isSpeaking()) { + this.finishNavCommand('', true, queueMode, null); + if (!this.next_(true)) { + this.keepReading_ = false; + } + } + window.setTimeout(goog.bind(this.startNonCallbackReading_, this), 1000); + }); /** @@ -947,8 +939,7 @@ return this.pageSel_.getFullDescription(); } return [cvox.DescriptionUtil.getDescriptionFromAncestors( - cvox.DomUtil.getAncestors(this.curSel_.start.node), - true, + cvox.DomUtil.getAncestors(this.curSel_.start.node), true, cvox.ChromeVox.verbosity)]; }; @@ -1200,7 +1191,7 @@ if (node == null || node.tagName != 'IFRAME' || !node.src) { return false; } - var iframeElement = /** @type {HTMLIFrameElement} */(node); + var iframeElement = /** @type {HTMLIFrameElement} */ (node); var iframeId = undefined; for (var id in this.iframeIdMap) { @@ -1228,10 +1219,7 @@ } } - var message = { - 'command': 'enterIframe', - 'id': iframeId - }; + var message = {'command': 'enterIframe', 'id': iframeId}; cvox.ChromeVox.serializer.storeOn(message); cvox.Interframe.sendMessageToIFrame(message, iframeElement); return true; @@ -1244,9 +1232,8 @@ * @param {boolean=} opt_skipIframe True to skip iframes. */ cvox.NavigationManager.prototype.syncToBeginning = function(opt_skipIframe) { - var ret = this.shifter_.begin(this.curSel_, { - reversed: this.curSel_.isReversed() - }); + var ret = + this.shifter_.begin(this.curSel_, {reversed: this.curSel_.isReversed()}); if (!opt_skipIframe && this.tryIframe_(ret && ret.start.node)) { return; }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_shifter.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_shifter.js index 61e11ca4..bbc59dc 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_shifter.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_shifter.js
@@ -165,8 +165,9 @@ cvox.NavigationShifter.prototype.makeMoreGranular = function() { goog.base(this, 'makeMoreGranular'); this.currentWalkerIndex_ = Math.max(this.currentWalkerIndex_ - 1, 0); - if (!cvox.NavigationShifter.allowSentence && this.currentWalkerIndex_ == - cvox.NavigationShifter.GRANULARITIES.SENTENCE) { + if (!cvox.NavigationShifter.allowSentence && + this.currentWalkerIndex_ == + cvox.NavigationShifter.GRANULARITIES.SENTENCE) { this.currentWalkerIndex_--; } this.currentWalker_ = this.walkers_[this.currentWalkerIndex_]; @@ -179,8 +180,9 @@ goog.base(this, 'makeLessGranular'); this.currentWalkerIndex_ = Math.min(this.currentWalkerIndex_ + 1, this.walkers_.length - 1); - if (!cvox.NavigationShifter.allowSentence && this.currentWalkerIndex_ == - cvox.NavigationShifter.GRANULARITIES.SENTENCE) { + if (!cvox.NavigationShifter.allowSentence && + this.currentWalkerIndex_ == + cvox.NavigationShifter.GRANULARITIES.SENTENCE) { this.currentWalkerIndex_++; } this.currentWalker_ = this.walkers_[this.currentWalkerIndex_]; @@ -246,12 +248,8 @@ this.characterWalker_ = new cvox.CharacterWalker(); this.walkers_ = [ - this.characterWalker_, - this.wordWalker_, - this.lineWalker_, - this.sentenceWalker_, - this.objectWalker_, - this.groupWalker_ + this.characterWalker_, this.wordWalker_, this.lineWalker_, + this.sentenceWalker_, this.objectWalker_, this.groupWalker_ ]; this.currentWalkerIndex_ = this.walkers_.indexOf(this.groupWalker_);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_speaker.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_speaker.js index 6de2b855..89d1f97 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_speaker.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_speaker.js
@@ -110,7 +110,7 @@ switch (annon) { case 'table': case 'Math': - return true; + return true; } return false; }; @@ -128,10 +128,8 @@ for (var i = 0; i < descriptionArray.length; i++) { var descr = descriptionArray[i]; if (cvox.NavigationSpeaker.structuredElement(descr.annotation)) { - descs.push(new cvox.NavDescription({ - text: '', - annotation: descr.annotation - })); + descs.push( + new cvox.NavDescription({text: '', annotation: descr.annotation})); descr.annotation = ''; } descs.push(descr);
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/node_breadcrumb.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/node_breadcrumb.js index e61b11a..4b79660 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/node_breadcrumb.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/node_breadcrumb.js
@@ -51,7 +51,7 @@ var cvTag; var currentNode = cvox.ChromeVox.navigationManager.getCurrentNode(); while (currentNode && !currentNode.hasAttribute) { - currentNode = currentNode.parentNode; + currentNode = currentNode.parentNode; } if (!currentNode) { cvTag = -1; @@ -157,9 +157,10 @@ cvox.NodeBreadcrumb.getCurrentNodeTag = function() { var currentNode = cvox.ChromeVox.navigationManager.getCurrentNode(); while (currentNode && !currentNode.hasAttribute) { - currentNode = currentNode.parentNode; + currentNode = currentNode.parentNode; } - if (currentNode && currentNode.hasAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG)) { + if (currentNode && + currentNode.hasAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG)) { return currentNode.getAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG); } else { return -1;
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/script_installer.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/script_installer.js index 471039b..cf7b2f8 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/script_installer.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/script_installer.js
@@ -29,8 +29,8 @@ * @return {boolean} False if the script already existed and this function * didn't do anything. */ -cvox.ScriptInstaller.installScript = function(srcs, uid, opt_onload, - opt_chromevoxScriptBase) { +cvox.ScriptInstaller.installScript = function( + srcs, uid, opt_onload, opt_chromevoxScriptBase) { if (cvox.ScriptInstaller.blacklistPattern.test(document.URL)) { return false; } @@ -41,8 +41,8 @@ return false; } - cvox.ScriptInstaller.installScriptHelper_(srcs, uid, opt_onload, - opt_chromevoxScriptBase); + cvox.ScriptInstaller.installScriptHelper_( + srcs, uid, opt_onload, opt_chromevoxScriptBase); return true; }; @@ -58,12 +58,12 @@ * attribute to add. * @private */ -cvox.ScriptInstaller.installScriptHelper_ = function(srcs, uid, opt_onload, - opt_chromevoxScriptBase) { +cvox.ScriptInstaller.installScriptHelper_ = function( + srcs, uid, opt_onload, opt_chromevoxScriptBase) { function next() { if (srcs.length > 0) { - cvox.ScriptInstaller.installScriptHelper_(srcs, uid, opt_onload, - opt_chromevoxScriptBase); + cvox.ScriptInstaller.installScriptHelper_( + srcs, uid, opt_onload, opt_chromevoxScriptBase); } else if (opt_onload) { opt_onload(); } @@ -89,8 +89,7 @@ apiScript.setAttribute(uid, '1'); apiScript.textContent = scriptText; if (opt_chromevoxScriptBase) { - apiScript.setAttribute('chromevoxScriptBase', - opt_chromevoxScriptBase); + apiScript.setAttribute('chromevoxScriptBase', opt_chromevoxScriptBase); } var scriptOwner = document.head || document.body; scriptOwner.appendChild(apiScript); @@ -102,8 +101,9 @@ xhr.open('GET', url, true); xhr.send(null); } catch (exception) { - console.log('Warning: ChromeVox external script loading for ' + - document.location + ' stopped after failing to install ' + scriptSrc); + console.log( + 'Warning: ChromeVox external script loading for ' + document.location + + ' stopped after failing to install ' + scriptSrc); next(); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/serializer.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/serializer.js index 6195336..9725a20f 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/serializer.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/serializer.js
@@ -15,7 +15,7 @@ /** * @constructor */ -cvox.Serializer = function() { }; +cvox.Serializer = function() {}; /** * Stores state variables in a provided object.
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/braille_overlay_widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/braille_overlay_widget.js index 844628f..e440c31 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/braille_overlay_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/braille_overlay_widget.js
@@ -45,8 +45,7 @@ * listener for braille content messages from the background page. */ cvox.BrailleOverlayWidget.prototype.init = function() { - cvox.ExtensionBridge.addMessageListener(goog.bind( - this.onMessage_, this)); + cvox.ExtensionBridge.addMessageListener(goog.bind(this.onMessage_, this)); };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/keyboard_help_widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/keyboard_help_widget.js index bde0aab..34fc0e1 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/keyboard_help_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/keyboard_help_widget.js
@@ -70,7 +70,7 @@ * @override */ cvox.KeyboardHelpWidget.prototype.onKeyDown = function(evt) { - if (evt.keyCode == 13) { // Enter + if (evt.keyCode == 13) { // Enter var currentCommand = cvox.ChromeVox.navigationManager.getCurrentNode().parentNode.id; this.hide();
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/overlay_widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/overlay_widget.js index 4831ac7..a0c48c4 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/overlay_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/overlay_widget.js
@@ -62,14 +62,14 @@ goog.base(this, 'onKeyDown', evt); // Do not interfere with any key that exits the widget. - if (evt.keyCode == 13 || evt.keyCode == 27) { // Enter or escape. + if (evt.keyCode == 13 || evt.keyCode == 27) { // Enter or escape. return true; } // Bound navigation within the snippet for any other key. var r = cvox.ChromeVox.navigationManager.isReversed(); if (!cvox.DomUtil.isDescendantOfNode( - cvox.ChromeVox.navigationManager.getCurrentNode(), this.host_)) { + cvox.ChromeVox.navigationManager.getCurrentNode(), this.host_)) { if (r) { cvox.ChromeVox.navigationManager.syncToBeginning(); } else { @@ -77,8 +77,8 @@ } this.onNavigate(); cvox.ChromeVox.navigationManager.speakDescriptionArray( - cvox.ChromeVox.navigationManager.getDescription(), - cvox.QueueMode.FLUSH, null); + cvox.ChromeVox.navigationManager.getDescription(), cvox.QueueMode.FLUSH, + null); } return false; };
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/search_widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/search_widget.js index dfab9b2..fda79a99e 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/search_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/search_widget.js
@@ -52,7 +52,7 @@ /** * @type {boolean} * @private - */ + */ this.hasMatch_ = false; goog.base(this); }; @@ -118,33 +118,27 @@ this.active = false; } - cvox.$m('choice_widget_exited'). - andPause(). - andMessage(this.getNameMsg()). - speakFlush(); + cvox.$m('choice_widget_exited') + .andPause() + .andMessage(this.getNameMsg()) + .speakFlush(); if (!this.hasMatch_ || !opt_noSync) { - cvox.ChromeVox.navigationManager.updateSelToArbitraryNode( - this.initialNode); + cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(this.initialNode); } cvox.ChromeVoxEventSuspender.withSuspendedEvents(goog.bind( cvox.ChromeVox.navigationManager.syncAll, cvox.ChromeVox.navigationManager))(true); cvox.ChromeVox.navigationManager.speakDescriptionArray( - cvox.ChromeVox.navigationManager.getDescription(), - cvox.QueueMode.QUEUE, - null, - cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); + cvox.ChromeVox.navigationManager.getDescription(), cvox.QueueMode.QUEUE, + null, cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); // Update on Braille too. // TODO: Use line granularity in search so we can simply call // cvox.ChromeVox.navigationManager.getBraille().write() instead. var text = this.textFromCurrentDescription_(); - cvox.ChromeVox.braille.write(new cvox.NavBraille({ - text: text, - startIndex: 0, - endIndex: 0 - })); + cvox.ChromeVox.braille.write( + new cvox.NavBraille({text: text, startIndex: 0, endIndex: 0})); goog.base(this, 'hide', true); }; @@ -174,7 +168,7 @@ return false; } var searchStr = this.txtNode_.value; - if (evt.keyCode == 8) { // Backspace + if (evt.keyCode == 8) { // Backspace if (searchStr.length > 0) { searchStr = searchStr.substring(0, searchStr.length - 1); this.txtNode_.value = searchStr; @@ -184,15 +178,15 @@ this.initialNode); cvox.ChromeVox.navigationManager.syncAll(); } - } else if (evt.keyCode == 40) { // Down arrow + } else if (evt.keyCode == 40) { // Down arrow this.next_(searchStr, false); - } else if (evt.keyCode == 38) { // Up arrow + } else if (evt.keyCode == 38) { // Up arrow this.next_(searchStr, true); - } else if (evt.keyCode == 13) { // Enter + } else if (evt.keyCode == 13) { // Enter this.hide(true); - } else if (evt.keyCode == 27) { // Escape + } else if (evt.keyCode == 27) { // Escape this.hide(false); - } else if (evt.ctrlKey && evt.keyCode == 67) { // ctrl + c + } else if (evt.ctrlKey && evt.keyCode == 67) { // ctrl + c this.toggleCaseSensitivity_(); } else { return goog.base(this, 'onKeyDown', evt); @@ -225,8 +219,7 @@ * Called when navigation occurs. * Override this method to react to navigation caused by user input. */ -cvox.SearchWidget.prototype.onNavigate = function() { -}; +cvox.SearchWidget.prototype.onNavigate = function() {}; /** @@ -309,8 +302,7 @@ textNode.style['color'] = '#fff'; textNode.style['background-color'] = 'rgba(0, 0, 0, 0.7)'; textNode.style['vertical-align'] = 'middle'; - textNode.addEventListener('textInput', - this.handleSearchChanged_, false); + textNode.addEventListener('textInput', this.handleSearchChanged_, false); return textNode; }; @@ -323,13 +315,11 @@ if (this.caseSensitive_) { cvox.SearchWidget.caseSensitive_ = false; cvox.ChromeVox.tts.speak( - Msgs.getMsg('ignoring_case'), - cvox.QueueMode.FLUSH, null); + Msgs.getMsg('ignoring_case'), cvox.QueueMode.FLUSH, null); } else { this.caseSensitive_ = true; cvox.ChromeVox.tts.speak( - Msgs.getMsg('case_sensitive'), - cvox.QueueMode.FLUSH, null); + Msgs.getMsg('case_sensitive'), cvox.QueueMode.FLUSH, null); } }; @@ -363,14 +353,13 @@ var descriptions = cvox.ChromeVox.navigationManager.getDescription(); for (var i = 0; i < descriptions.length; i++) { var targetStr = this.caseSensitive_ ? descriptions[i].text : - descriptions[i].text.toLowerCase(); + descriptions[i].text.toLowerCase(); var targetIndex = targetStr.indexOf(searchStr); // Surround search hit with pauses. if (targetIndex != -1 && targetStr.length > searchStr.length) { - descriptions[i].text = - cvox.DomUtil.collapseWhitespace( - targetStr.substring(0, targetIndex)) + + descriptions[i].text = cvox.DomUtil.collapseWhitespace( + targetStr.substring(0, targetIndex)) + ', ' + searchStr + ', ' + targetStr.substring(targetIndex + searchStr.length); descriptions[i].text = @@ -381,8 +370,8 @@ } } cvox.ChromeVox.navigationManager.setReversed(r); - } while (cvox.ChromeVox.navigationManager.navigate(true, - cvox.NavigationShifter.GRANULARITIES.OBJECT)); + } while (cvox.ChromeVox.navigationManager.navigate( + true, cvox.NavigationShifter.GRANULARITIES.OBJECT)); return null; }; @@ -458,14 +447,12 @@ cvox.ChromeVox.navigationManager))(true); cvox.ChromeVox.navigationManager.speakDescriptionArray( - result, - cvox.QueueMode.FLUSH, - null, + result, cvox.QueueMode.FLUSH, null, cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); - cvox.ChromeVox.tts.speak(Msgs.getMsg('search_help_item'), - cvox.QueueMode.QUEUE, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('search_help_item'), cvox.QueueMode.QUEUE, + cvox.AbstractTts.PERSONALITY_ANNOTATION); // Output to Braille. // TODO: Use line granularity in search so we can simply call @@ -488,8 +475,7 @@ // position to be at the end of search query string // (consistent with editing text in a field). var text = this.textFromCurrentDescription_(); - var targetStr = this.caseSensitive_ ? text : - text.toLowerCase(); + var targetStr = this.caseSensitive_ ? text : text.toLowerCase(); searchStr = this.caseSensitive_ ? searchStr : searchStr.toLowerCase(); var targetIndex = targetStr.indexOf(searchStr); if (targetIndex == -1) {
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/spoken_messages.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/spoken_messages.js index dc72579..9364fa6 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/spoken_messages.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/spoken_messages.js
@@ -52,8 +52,8 @@ throw 'Invalid message received.'; var finalText = Msgs.getMsg.apply(Msgs, message.id); - cvox.ChromeVox.tts.speak(finalText, mode, - cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); + cvox.ChromeVox.tts.speak( + finalText, mode, cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT); // Always queue after the first message. mode = cvox.QueueMode.QUEUE;
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/widget.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/widget.js index dcd02a86..40e3fea 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/widget.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/ui/widget.js
@@ -80,18 +80,17 @@ window.addEventListener('keydown', this.onKeyDown, true); window.addEventListener('keypress', this.onKeyPress, true); - this.initialNode = - cvox.ChromeVox.navigationManager.getCurrentNode(); + this.initialNode = cvox.ChromeVox.navigationManager.getCurrentNode(); this.initialFocus = document.activeElement; // Widgets do not respond to sticky key. cvox.ChromeVox.stickyOverride = false; if (this.getNameMsg() && this.getHelpMsg()) { - cvox.$m(this.getNameMsg()). - andPause(). - andMessage(this.getHelpMsg()). - speakFlush(); + cvox.$m(this.getNameMsg()) + .andPause() + .andMessage(this.getHelpMsg()) + .speakFlush(); } cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_OPEN); @@ -113,10 +112,10 @@ cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_CLOSE); if (!opt_noSync) { this.initialNode = this.initialNode.nodeType == 1 ? - this.initialNode : this.initialNode.parentNode; - cvox.ChromeVox.navigationManager.syncToNode(this.initialNode, - true, - cvox.QueueMode.QUEUE); + this.initialNode : + this.initialNode.parentNode; + cvox.ChromeVox.navigationManager.syncToNode( + this.initialNode, true, cvox.QueueMode.QUEUE); } this.active = false; @@ -160,11 +159,11 @@ * @protected */ cvox.Widget.prototype.onKeyDown = function(evt) { - if (evt.keyCode == 27) { // Escape + if (evt.keyCode == 27) { // Escape this.hide(); evt.preventDefault(); return true; - } else if (evt.keyCode == 9) { // Tab + } else if (evt.keyCode == 9) { // Tab this.hide(); return true; } else if (evt.keyCode == 17) {
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands.js index 1a44975..2ceb44f 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands.js
@@ -180,8 +180,7 @@ cvox.ChromeVoxUserCommands.removeTabDummySpan = function() { // Break the following line to get around a Chromium js linter warning. // TODO(plundblad): Find a better solution. - var previousDummySpan = document. - getElementById('ChromeVoxTabDummySpan'); + var previousDummySpan = document.getElementById('ChromeVoxTabDummySpan'); if (previousDummySpan && document.activeElement != previousDummySpan) { previousDummySpan.parentNode.removeChild(previousDummySpan); } @@ -305,8 +304,7 @@ if (!cmdStruct.findNext) { throw 'Invalid find command.'; } - var NodeInfoStruct = - cvox.CommandStore.NODE_INFO_MAP[cmdStruct.findNext]; + var NodeInfoStruct = cvox.CommandStore.NODE_INFO_MAP[cmdStruct.findNext]; var predicateName = NodeInfoStruct.predicate; var predicate = cvox.DomPredicates[predicateName]; var error = ''; @@ -364,57 +362,57 @@ break; case 'previousCharacter': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.CHARACTER); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.CHARACTER); break; case 'nextCharacter': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.CHARACTER); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.CHARACTER); break; case 'previousWord': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.WORD); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.WORD); break; case 'nextWord': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.WORD); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.WORD); break; case 'previousSentence': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.SENTENCE); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.SENTENCE); break; case 'nextSentence': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.SENTENCE); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.SENTENCE); break; case 'previousLine': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.LINE); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.LINE); break; case 'nextLine': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.LINE); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.LINE); break; case 'previousObject': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.OBJECT); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.OBJECT); break; case 'nextObject': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.OBJECT); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.OBJECT); break; case 'previousGroup': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.GROUP); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.GROUP); break; case 'nextGroup': - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.GROUP); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.GROUP); break; case 'previousRow': @@ -439,8 +437,7 @@ case 'readFromHere': cvox.ChromeVox.navigationManager.setGranularity( cvox.NavigationShifter.GRANULARITIES.OBJECT, true, true); - cvox.ChromeVox.navigationManager.startReading( - cvox.QueueMode.FLUSH); + cvox.ChromeVox.navigationManager.startReading(cvox.QueueMode.FLUSH); break; case 'cycleTypingEcho': cvox.ChromeVox.host.sendToBackgroundPage({ @@ -467,10 +464,8 @@ break; case 'help': cvox.ChromeVox.tts.stop(); - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'HelpDocs', - 'action': 'open' - }); + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'HelpDocs', 'action': 'open'}); break; case 'contextMenu': // Move this logic to a central dispatching class if it grows any bigger. @@ -484,24 +479,18 @@ break; case 'showBookmarkManager': // TODO(stoarca): Should this have tts.stop()?? - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'BookmarkManager', - 'action': 'open' - }); + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'BookmarkManager', 'action': 'open'}); break; case 'showOptionsPage': cvox.ChromeVox.tts.stop(); - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'Options', - 'action': 'open' - }); + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'Options', 'action': 'open'}); break; case 'showKbExplorerPage': cvox.ChromeVox.tts.stop(); - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'KbExplorer', - 'action': 'open' - }); + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'KbExplorer', 'action': 'open'}); break; case 'readLinkURL': var activeElement = document.activeElement; @@ -517,8 +506,8 @@ if (url != '') { cvox.ChromeVox.tts.speak(url, cvox.QueueMode.QUEUE); } else { - cvox.ChromeVox.tts.speak(Msgs.getMsg('no_url_found'), - cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('no_url_found'), cvox.QueueMode.QUEUE); } break; case 'readCurrentTitle': @@ -559,18 +548,13 @@ break; case 'toggleChromeVoxVersion': case 'showNextUpdatePage': - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'next', - 'action': 'onCommand', - 'command': cmd - }); + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'next', 'action': 'onCommand', 'command': cmd}); break; case 'fullyDescribe': var descs = cvox.ChromeVox.navigationManager.getFullDescription(); cvox.ChromeVox.navigationManager.speakDescriptionArray( - descs, - cvox.QueueMode.FLUSH, - null); + descs, cvox.QueueMode.FLUSH, null); break; case 'speakTimeAndDate': var dateTime = new Date(); @@ -580,9 +564,8 @@ break; case 'toggleSelection': var selState = cvox.ChromeVox.navigationManager.togglePageSel(); - prefixMsg = Msgs.getMsg( - selState ? 'begin_selection' : 'end_selection'); - break; + prefixMsg = Msgs.getMsg(selState ? 'begin_selection' : 'end_selection'); + break; case 'startHistoryRecording': cvox.History.getInstance().startRecording(); break; @@ -612,7 +595,7 @@ case 'speakTableLocation': case 'exitShifterContent': if (!cvox.DomPredicates.tablePredicate(cvox.DomUtil.getAncestors( - cvox.ChromeVox.navigationManager.getCurrentNode()))) { + cvox.ChromeVox.navigationManager.getCurrentNode()))) { errorMsg = 'not_inside_table'; } else if (!cvox.ChromeVox.navigationManager.performAction(cmd)) { errorMsg = 'not_in_table_mode'; @@ -650,12 +633,10 @@ cvox.ChromeVox.tts.increaseOrDecreaseProperty( cvox.AbstractTts.VOLUME, true); break; - case 'cyclePunctuationEcho': - cvox.ChromeVox.host.sendToBackgroundPage({ - 'target': 'TTS', - 'action': 'cyclePunctuationEcho' - }); - break; + case 'cyclePunctuationEcho': + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'TTS', 'action': 'cyclePunctuationEcho'}); + break; case 'toggleStickyMode': cvox.ChromeVox.host.sendToBackgroundPage({ @@ -679,9 +660,8 @@ break; case 'toggleEarcons': - prefixMsg = cvox.ChromeVox.earcons.toggle() ? - Msgs.getMsg('earcons_on') : - Msgs.getMsg('earcons_off'); + prefixMsg = cvox.ChromeVox.earcons.toggle() ? Msgs.getMsg('earcons_on') : + Msgs.getMsg('earcons_off'); break; case 'showHeadingsList': @@ -692,11 +672,13 @@ if (!cmdStruct.nodeList) { break; } - var nodeListStruct = - cvox.CommandStore.NODE_INFO_MAP[cmdStruct.nodeList]; + var nodeListStruct = cvox.CommandStore.NODE_INFO_MAP[cmdStruct.nodeList]; - cvox.NodeSearchWidget.create(nodeListStruct.typeMsg, - cvox.DomPredicates[nodeListStruct.predicate]).show(); + cvox.NodeSearchWidget + .create( + nodeListStruct.typeMsg, + cvox.DomPredicates[nodeListStruct.predicate]) + .show(); break; case 'openLongDesc': @@ -704,15 +686,14 @@ if (cvox.DomUtil.hasLongDesc(currentNode)) { cvox.ChromeVox.host.sendToBackgroundPage({ 'target': 'OpenTab', - 'url': currentNode.longDesc // Use .longDesc instead of getAttribute - // since we want Chrome to convert the - // longDesc to an absolute URL. + 'url': currentNode.longDesc // Use .longDesc instead of getAttribute + // since we want Chrome to convert the + // longDesc to an absolute URL. }); } else { cvox.ChromeVox.tts.speak( - Msgs.getMsg('no_long_desc'), - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + Msgs.getMsg('no_long_desc'), cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOTATION); } break; @@ -730,11 +711,11 @@ // Math specific commands. case 'toggleSemantics': if (cvox.TraverseMath.toggleSemantic()) { - cvox.ChromeVox.tts.speak(Msgs.getMsg('semantics_on'), - cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('semantics_on'), cvox.QueueMode.QUEUE); } else { - cvox.ChromeVox.tts.speak(Msgs.getMsg('semantics_off'), - cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak( + Msgs.getMsg('semantics_off'), cvox.QueueMode.QUEUE); } break; @@ -753,8 +734,8 @@ // after line up/pan left and move the display to the far right on the // line in case the synced to node is longer than one display line. // Should also work with all widgets. - cvox.ChromeVox.navigationManager.navigate(false, - cvox.NavigationShifter.GRANULARITIES.LINE); + cvox.ChromeVox.navigationManager.navigate( + false, cvox.NavigationShifter.GRANULARITIES.LINE); break; case 'debug': @@ -769,8 +750,7 @@ if (errorMsg != '') { cvox.ChromeVox.tts.speak( - Msgs.getMsg(errorMsg), - cvox.QueueMode.FLUSH, + Msgs.getMsg(errorMsg), cvox.QueueMode.FLUSH, cvox.AbstractTts.PERSONALITY_ANNOTATION); } else if (cvox.ChromeVox.navigationManager.isReading()) { if (cmdStruct.disallowContinuation) {
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_event_detail.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_event_detail.js index b527699..b8d759d 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_event_detail.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_event_detail.js
@@ -143,18 +143,18 @@ */ // TODO (clchen): Integrate this with command_store.js. cvox.UserEventDetail.JUMP_COMMANDS = [ - 'nextCheckbox', 'previousCheckbox', 'nextRadio', 'previousRadio', - 'nextSlider', 'previousSlider', 'nextGraphic', 'previousGraphic', - 'nextButton', 'previousButton', 'nextComboBox', 'previousComboBox', - 'nextEditText', 'previousEditText', 'nextHeading', 'previousHeading', - 'nextHeading1', 'previousHeading1', 'nextHeading2', 'previousHeading2', - 'nextHeading3', 'previousHeading3', 'nextHeading4', 'previousHeading4', - 'nextHeading5', 'previousHeading5', 'nextHeading6', 'previousHeading6', - 'nextLink', 'previousLink', 'nextMath', 'previousMath', 'nextTable', - 'previousTable', 'nextList', 'previousList', 'nextListItem', - 'previousListItem', 'nextFormField', 'previousFormField', 'nextLandmark', - 'previousLandmark', 'nextSection', 'previousSection', 'nextControl', - 'previousControl' + 'nextCheckbox', 'previousCheckbox', 'nextRadio', 'previousRadio', + 'nextSlider', 'previousSlider', 'nextGraphic', 'previousGraphic', + 'nextButton', 'previousButton', 'nextComboBox', 'previousComboBox', + 'nextEditText', 'previousEditText', 'nextHeading', 'previousHeading', + 'nextHeading1', 'previousHeading1', 'nextHeading2', 'previousHeading2', + 'nextHeading3', 'previousHeading3', 'nextHeading4', 'previousHeading4', + 'nextHeading5', 'previousHeading5', 'nextHeading6', 'previousHeading6', + 'nextLink', 'previousLink', 'nextMath', 'previousMath', + 'nextTable', 'previousTable', 'nextList', 'previousList', + 'nextListItem', 'previousListItem', 'nextFormField', 'previousFormField', + 'nextLandmark', 'previousLandmark', 'nextSection', 'previousSection', + 'nextControl', 'previousControl' ]; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/closure/closure_preinit.js b/chrome/browser/resources/chromeos/chromevox/closure/closure_preinit.js index ef8fa27..e6102ac 100644 --- a/chrome/browser/resources/chromeos/chromevox/closure/closure_preinit.js +++ b/chrome/browser/resources/chromeos/chromevox/closure/closure_preinit.js
@@ -36,8 +36,7 @@ // when trying to inject ChromeVox scripts. // TODO(lazyboy): Use URL instead. if (src.startsWith('chrome-extension://')) { - if (!goog.inHtmlDocument_() || - goog.dependencies_.written[src]) { + if (!goog.inHtmlDocument_() || goog.dependencies_.written[src]) { return false; } goog.dependencies_.written[src] = true; @@ -50,8 +49,7 @@ if (window.CLOSURE_USE_EXT_MESSAGES) { var relativeSrc = src.substr(src.indexOf('closure/..') + 11); chrome.extension.sendMessage( - {'srcFile': relativeSrc}, - function(response) { + {'srcFile': relativeSrc}, function(response) { try { eval(response['code']); } catch (e) {
diff --git a/chrome/browser/resources/chromeos/chromevox/common/aria_util.js b/chrome/browser/resources/chromeos/chromevox/common/aria_util.js index 435c968..06b7389 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/aria_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/aria_util.js
@@ -19,8 +19,7 @@ * Create the namespace * @constructor */ -cvox.AriaUtil = function() { -}; +cvox.AriaUtil = function() {}; /** @@ -31,41 +30,41 @@ * @type {Object<string>} */ cvox.AriaUtil.WIDGET_ROLE_TO_NAME = { - 'alert' : 'role_alert', - 'alertdialog' : 'role_alertdialog', - 'button' : 'role_button', - 'checkbox' : 'role_checkbox', - 'columnheader' : 'role_columnheader', - 'combobox' : 'role_combobox', - 'dialog' : 'role_dialog', - 'grid' : 'role_grid', - 'gridcell' : 'role_gridcell', - 'link' : 'role_link', - 'listbox' : 'role_listbox', - 'log' : 'role_log', - 'marquee' : 'role_marquee', - 'menu' : 'role_menu', - 'menubar' : 'role_menubar', - 'menuitem' : 'role_menuitem', - 'menuitemcheckbox' : 'role_menuitemcheckbox', - 'menuitemradio' : 'role_menuitemradio', - 'option' : 'role_option', - 'progressbar' : 'role_progressbar', - 'radio' : 'role_radio', - 'radiogroup' : 'role_radiogroup', - 'rowheader' : 'role_rowheader', - 'scrollbar' : 'role_scrollbar', - 'slider' : 'role_slider', - 'spinbutton' : 'role_spinbutton', - 'status' : 'role_status', - 'tab' : 'role_tab', - 'tablist' : 'role_tablist', - 'tabpanel' : 'role_tabpanel', - 'textbox' : 'role_textbox', - 'timer' : 'role_timer', - 'toolbar' : 'role_toolbar', - 'tooltip' : 'role_tooltip', - 'treeitem' : 'role_treeitem' + 'alert': 'role_alert', + 'alertdialog': 'role_alertdialog', + 'button': 'role_button', + 'checkbox': 'role_checkbox', + 'columnheader': 'role_columnheader', + 'combobox': 'role_combobox', + 'dialog': 'role_dialog', + 'grid': 'role_grid', + 'gridcell': 'role_gridcell', + 'link': 'role_link', + 'listbox': 'role_listbox', + 'log': 'role_log', + 'marquee': 'role_marquee', + 'menu': 'role_menu', + 'menubar': 'role_menubar', + 'menuitem': 'role_menuitem', + 'menuitemcheckbox': 'role_menuitemcheckbox', + 'menuitemradio': 'role_menuitemradio', + 'option': 'role_option', + 'progressbar': 'role_progressbar', + 'radio': 'role_radio', + 'radiogroup': 'role_radiogroup', + 'rowheader': 'role_rowheader', + 'scrollbar': 'role_scrollbar', + 'slider': 'role_slider', + 'spinbutton': 'role_spinbutton', + 'status': 'role_status', + 'tab': 'role_tab', + 'tablist': 'role_tablist', + 'tabpanel': 'role_tabpanel', + 'textbox': 'role_textbox', + 'timer': 'role_timer', + 'toolbar': 'role_toolbar', + 'tooltip': 'role_tooltip', + 'treeitem': 'role_treeitem' }; @@ -76,29 +75,29 @@ * @type {Object<string>} */ cvox.AriaUtil.STRUCTURE_ROLE_TO_NAME = { - 'article' : 'role_article', - 'application' : 'role_application', - 'banner' : 'role_banner', - 'columnheader' : 'role_columnheader', - 'complementary' : 'role_complementary', - 'contentinfo' : 'role_contentinfo', - 'definition' : 'role_definition', - 'directory' : 'role_directory', - 'document' : 'role_document', - 'form' : 'role_form', - 'group' : 'role_group', - 'heading' : 'role_heading', - 'img' : 'role_img', - 'list' : 'role_list', - 'listitem' : 'role_listitem', - 'main' : 'role_main', - 'math' : 'role_math', - 'navigation' : 'role_navigation', - 'note' : 'role_note', - 'region' : 'role_region', - 'rowheader' : 'role_rowheader', - 'search' : 'role_search', - 'separator' : 'role_separator' + 'article': 'role_article', + 'application': 'role_application', + 'banner': 'role_banner', + 'columnheader': 'role_columnheader', + 'complementary': 'role_complementary', + 'contentinfo': 'role_contentinfo', + 'definition': 'role_definition', + 'directory': 'role_directory', + 'document': 'role_document', + 'form': 'role_form', + 'group': 'role_group', + 'heading': 'role_heading', + 'img': 'role_img', + 'list': 'role_list', + 'listitem': 'role_listitem', + 'main': 'role_main', + 'math': 'role_math', + 'navigation': 'role_navigation', + 'note': 'role_note', + 'region': 'role_region', + 'rowheader': 'role_rowheader', + 'search': 'role_search', + 'separator': 'role_separator' }; @@ -106,38 +105,49 @@ * @type {Array<Object>} */ cvox.AriaUtil.ATTRIBUTE_VALUE_TO_STATUS = [ - { name: 'aria-autocomplete', values: - {'inline' : 'aria_autocomplete_inline', - 'list' : 'aria_autocomplete_list', - 'both' : 'aria_autocomplete_both'} }, - { name: 'aria-checked', values: - {'true' : 'checked_true', - 'false' : 'checked_false', - 'mixed' : 'checked_mixed'} }, - { name: 'aria-disabled', values: - {'true' : 'aria_disabled_true'} }, - { name: 'aria-expanded', values: - {'true' : 'aria_expanded_true', - 'false' : 'aria_expanded_false'} }, - { name: 'aria-invalid', values: - {'true' : 'aria_invalid_true', - 'grammar' : 'aria_invalid_grammar', - 'spelling' : 'aria_invalid_spelling'} }, - { name: 'aria-multiline', values: - {'true' : 'aria_multiline_true'} }, - { name: 'aria-multiselectable', values: - {'true' : 'aria_multiselectable_true'} }, - { name: 'aria-pressed', values: - {'true' : 'aria_pressed_true', - 'false' : 'aria_pressed_false', - 'mixed' : 'aria_pressed_mixed'} }, - { name: 'aria-readonly', values: - {'true' : 'aria_readonly_true'} }, - { name: 'aria-required', values: - {'true' : 'aria_required_true'} }, - { name: 'aria-selected', values: - {'true' : 'aria_selected_true', - 'false' : 'aria_selected_false'} } + { + name: 'aria-autocomplete', + values: { + 'inline': 'aria_autocomplete_inline', + 'list': 'aria_autocomplete_list', + 'both': 'aria_autocomplete_both' + } + }, + { + name: 'aria-checked', + values: { + 'true': 'checked_true', + 'false': 'checked_false', + 'mixed': 'checked_mixed' + } + }, + {name: 'aria-disabled', values: {'true': 'aria_disabled_true'}}, { + name: 'aria-expanded', + values: {'true': 'aria_expanded_true', 'false': 'aria_expanded_false'} + }, + { + name: 'aria-invalid', + values: { + 'true': 'aria_invalid_true', + 'grammar': 'aria_invalid_grammar', + 'spelling': 'aria_invalid_spelling' + } + }, + {name: 'aria-multiline', values: {'true': 'aria_multiline_true'}}, + {name: 'aria-multiselectable', values: {'true': 'aria_multiselectable_true'}}, + { + name: 'aria-pressed', + values: { + 'true': 'aria_pressed_true', + 'false': 'aria_pressed_false', + 'mixed': 'aria_pressed_mixed' + } + }, + {name: 'aria-readonly', values: {'true': 'aria_readonly_true'}}, + {name: 'aria-required', values: {'true': 'aria_required_true'}}, { + name: 'aria-selected', + values: {'true': 'aria_selected_true', 'false': 'aria_selected_false'} + } ]; @@ -274,9 +284,8 @@ return true; } if (node.tagName == 'INPUT') { - return (node.type == 'submit' || - node.type == 'reset' || - node.type == 'button'); + return ( + node.type == 'submit' || node.type == 'reset' || node.type == 'button'); } return false; }; @@ -365,7 +374,7 @@ } for (var i = 0, attr; attr = cvox.AriaUtil.ATTRIBUTE_VALUE_TO_STATUS[i]; - i++) { + i++) { var value = targetNode.getAttribute(attr.name); var msgId = attr.values[value]; if (msgId) { @@ -373,7 +382,7 @@ } } if (targetNode.getAttribute('role') == 'grid') { - return cvox.AriaUtil.getGridState_(targetNode, targetNode); + return cvox.AriaUtil.getGridState_(targetNode, targetNode); } var role = cvox.AriaUtil.getRoleAttribute(targetNode); @@ -430,12 +439,8 @@ currentDescendant = cvox.AriaUtil.getActiveDescendant(parentControl); } else { role = cvox.AriaUtil.getRoleAttribute(targetNode); - if (role == 'option' || - role == 'menuitem' || - role == 'menuitemcheckbox' || - role == 'menuitemradio' || - role == 'radio' || - role == 'tab' || + if (role == 'option' || role == 'menuitem' || role == 'menuitemcheckbox' || + role == 'menuitemradio' || role == 'radio' || role == 'tab' || role == 'treeitem') { currentDescendant = targetNode; parentControl = targetNode.parentElement; @@ -452,7 +457,7 @@ if (parentControl && (cvox.AriaUtil.isCompositeControl(parentControl) || - cvox.AriaUtil.getRoleAttribute(parentControl) == 'treeitem') && + cvox.AriaUtil.getRoleAttribute(parentControl) == 'treeitem') && currentDescendant) { var parentRole = cvox.AriaUtil.getRoleAttribute(parentControl); var descendantRoleList; @@ -462,9 +467,7 @@ descendantRoleList = ['option']; break; case 'menu': - descendantRoleList = ['menuitem', - 'menuitemcheckbox', - 'menuitemradio']; + descendantRoleList = ['menuitem', 'menuitemcheckbox', 'menuitemradio']; break; case 'radiogroup': descendantRoleList = ['radio']; @@ -495,8 +498,8 @@ } if (listLength == undefined || currentIndex == undefined) { - var descendants = cvox.AriaUtil.getNextLevel(parentControl, - descendantRoleList); + var descendants = + cvox.AriaUtil.getNextLevel(parentControl, descendantRoleList); if (listLength == undefined) { listLength = descendants.length; } @@ -537,7 +540,7 @@ for (var k = 0; k < gridcells.length; k++) { if (gridcells[k] == activeDescendant) { return /** @type {cvox.NodeState} */ ( - [['role_gridcell_pos', j + 1, k + 1]]); + [['role_gridcell_pos', j + 1, k + 1]]); } } } @@ -598,7 +601,7 @@ * @return {Array<Element>} The array of matching nodes. */ cvox.AriaUtil.getNextLevelItems = function(current, role) { - if (current.nodeType != 1) { // If reached a node that is not an element. + if (current.nodeType != 1) { // If reached a node that is not an element. return []; } if (role.indexOf(cvox.AriaUtil.getRoleAttribute(current)) != -1) { @@ -810,9 +813,9 @@ var tokens = value.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').split(' '); if (change == 'all') { - return (tokens.indexOf('additions') >= 0 && - tokens.indexOf('text') >= 0 && - tokens.indexOf('removals') >= 0); + return ( + tokens.indexOf('additions') >= 0 && tokens.indexOf('text') >= 0 && + tokens.indexOf('removals') >= 0); } else { return (tokens.indexOf(change) >= 0); } @@ -858,22 +861,22 @@ * @return {boolean} Whether or not the node is an ARIA landmark. */ cvox.AriaUtil.isLandmark = function(node) { - if (!node || !node.getAttribute) { - return false; - } - var role = cvox.AriaUtil.getRoleAttribute(node); - switch (role) { - case 'application': - case 'banner': - case 'complementary': - case 'contentinfo': - case 'form': - case 'main': - case 'navigation': - case 'search': - return true; - } + if (!node || !node.getAttribute) { return false; + } + var role = cvox.AriaUtil.getRoleAttribute(node); + switch (role) { + case 'application': + case 'banner': + case 'complementary': + case 'contentinfo': + case 'form': + case 'main': + case 'navigation': + case 'search': + return true; + } + return false; }; @@ -884,16 +887,16 @@ * @return {boolean} Whether or not the node is an ARIA grid. */ cvox.AriaUtil.isGrid = function(node) { - if (!node || !node.getAttribute) { - return false; - } - var role = cvox.AriaUtil.getRoleAttribute(node); - switch (role) { - case 'grid': - case 'treegrid': - return true; - } + if (!node || !node.getAttribute) { return false; + } + var role = cvox.AriaUtil.getRoleAttribute(node); + switch (role) { + case 'grid': + case 'treegrid': + return true; + } + return false; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/aural_style_util.js b/chrome/browser/resources/chromeos/chromevox/common/aural_style_util.js index 0e8c3b5..cfdce46 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/aural_style_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/aural_style_util.js
@@ -147,7 +147,7 @@ * Gets the aural style for a node. * @param {Node} node The node. * @return {Object} The aural style, converted to tts properties. -*/ + */ cvox.AuralStyleUtil.getStyleForNode = function(node) { var style = cvox.AuralStyleUtil.defaultStyles[node.tagName]; if (!style) { @@ -161,49 +161,19 @@ * A list of default aural styles. */ cvox.AuralStyleUtil.defaultStyles = { - 'ARTICLE': { - PITCH: -0.1 - }, - 'ASIDE': { - PITCH: -0.1 - }, - 'FOOTER': { - PITCH: -0.1 - }, - 'H1': { - PITCH: -0.3 - }, - 'H2': { - PITCH: -0.25 - }, - 'H3': { - PITCH: -0.2 - }, - 'H4': { - PITCH: -0.15 - }, - 'H5': { - PITCH: -0.1 - }, - 'H6': { - PITCH: -0.05 - }, - 'HEADER': { - PITCH: -0.1 - }, - 'HGROUP': { - PITCH: -0.1 - }, - 'MARK': { - PITCH: -0.1 - }, - 'NAV': { - PITCH: -0.1 - }, - 'SECTION': { - PITCH: -0.1 - }, - 'TIME': { - PITCH: -0.1 - } + 'ARTICLE': {PITCH: -0.1}, + 'ASIDE': {PITCH: -0.1}, + 'FOOTER': {PITCH: -0.1}, + 'H1': {PITCH: -0.3}, + 'H2': {PITCH: -0.25}, + 'H3': {PITCH: -0.2}, + 'H4': {PITCH: -0.15}, + 'H5': {PITCH: -0.1}, + 'H6': {PITCH: -0.05}, + 'HEADER': {PITCH: -0.1}, + 'HGROUP': {PITCH: -0.1}, + 'MARK': {PITCH: -0.1}, + 'NAV': {PITCH: -0.1}, + 'SECTION': {PITCH: -0.1}, + 'TIME': {PITCH: -0.1} };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/braille_text_handler.js b/chrome/browser/resources/chromeos/chromevox/common/braille_text_handler.js index 36d3e04c..dc2c3354 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/braille_text_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/common/braille_text_handler.js
@@ -49,9 +49,8 @@ if (element) { spannable.setSpan(element, 0, line.length); } - content = new cvox.NavBraille({text: spannable, - startIndex: start, - endIndex: end}); + content = new cvox.NavBraille( + {text: spannable, startIndex: start, endIndex: end}); } else { if (cvox.ChromeVox.navigationManager) { content = cvox.ChromeVox.navigationManager.getBraille();
diff --git a/chrome/browser/resources/chromeos/chromevox/common/braille_util.js b/chrome/browser/resources/chromeos/chromevox/common/braille_util.js index 6ab38da..a720580 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/braille_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/braille_util.js
@@ -36,11 +36,7 @@ * @type {!Array<string>} */ cvox.BrailleUtil.CONTAINER = [ - 'tag_h1_brl', - 'tag_h2_brl', - 'tag_h3_brl', - 'tag_h4_brl', - 'tag_h5_brl', + 'tag_h1_brl', 'tag_h2_brl', 'tag_h3_brl', 'tag_h4_brl', 'tag_h5_brl', 'tag_h6_brl' ]; @@ -180,13 +176,13 @@ var spannable = new Spannable(value, valueSpan); if (node === document.activeElement && cvox.DomUtil.doesInputSupportSelection(node)) { - var selectionStart = cvox.BrailleUtil.clamp_( - node.selectionStart, 0, spannable.length); - var selectionEnd = cvox.BrailleUtil.clamp_( - node.selectionEnd, 0, spannable.length); - spannable.setSpan(new cvox.ValueSelectionSpan(), - Math.min(selectionStart, selectionEnd), - Math.max(selectionStart, selectionEnd)); + var selectionStart = + cvox.BrailleUtil.clamp_(node.selectionStart, 0, spannable.length); + var selectionEnd = + cvox.BrailleUtil.clamp_(node.selectionEnd, 0, spannable.length); + spannable.setSpan( + new cvox.ValueSelectionSpan(), Math.min(selectionStart, selectionEnd), + Math.max(selectionStart, selectionEnd)); } return spannable; } else if (node instanceof HTMLTextAreaElement) { @@ -203,9 +199,9 @@ node.selectionStart - lineStart, 0, spannable.length); var selectionEnd = cvox.BrailleUtil.clamp_( node.selectionEnd - lineStart, 0, spannable.length); - spannable.setSpan(new cvox.ValueSelectionSpan(), - Math.min(selectionStart, selectionEnd), - Math.max(selectionStart, selectionEnd)); + spannable.setSpan( + new cvox.ValueSelectionSpan(), Math.min(selectionStart, selectionEnd), + Math.max(selectionStart, selectionEnd)); } return spannable; } else { @@ -231,8 +227,8 @@ opt_override = opt_override ? opt_override : {}; var roleMsg = opt_override.roleMsg || (node ? cvox.DomUtil.getRoleMsg(node, cvox.VERBOSITY_VERBOSE) : ''); - var template = cvox.BrailleUtil.TEMPLATE[roleMsg] || - cvox.BrailleUtil.TEMPLATE['base']; + var template = + cvox.BrailleUtil.TEMPLATE[roleMsg] || cvox.BrailleUtil.TEMPLATE['base']; var state = opt_override.state; if (!state) { if (node) { @@ -244,8 +240,7 @@ } var role = opt_override.role || ''; if (!role && roleMsg) { - role = Msgs.getMsg(roleMsg + '_brl') || - Msgs.getMsg(roleMsg); + role = Msgs.getMsg(roleMsg + '_brl') || Msgs.getMsg(roleMsg); } var templated = new Spannable(); @@ -274,8 +269,8 @@ // should be placed on the empty space after the empty value. if (!component.toString() && template[i + 1] == ' ' && (!(component instanceof Spannable) || - !/**@type {Spannable}*/(component).getSpanInstanceOf( - cvox.ValueSelectionSpan))) { + !/**@type {Spannable}*/ (component).getSpanInstanceOf( + cvox.ValueSelectionSpan))) { i++; } } @@ -293,8 +288,8 @@ * @param {number=} opt_textOffset Start offset of text. * @return {!Spannable} The value spannable. */ -cvox.BrailleUtil.createValue = function(text, opt_selStart, opt_selEnd, - opt_textOffset) { +cvox.BrailleUtil.createValue = function( + text, opt_selStart, opt_selEnd, opt_textOffset) { var spannable = new Spannable(text, new cvox.ValueSpan(opt_textOffset || 0)); if (goog.isDef(opt_selStart)) { opt_selEnd = goog.isDef(opt_selEnd) ? opt_selEnd : opt_selStart; @@ -328,22 +323,22 @@ cvox.BrailleUtil.click = function(braille, opt_displayPosition) { var handled = false; var spans = braille.text.getSpans(opt_displayPosition || 0); - var node = spans.filter(function(n) { return n instanceof Node; })[0]; + var node = spans.filter(function(n) { + return n instanceof Node; + })[0]; if (node) { if (goog.isDef(opt_displayPosition) && (cvox.DomUtil.isInputTypeText(node) || - node instanceof HTMLTextAreaElement)) { - var valueSpan = spans.filter( - function(s) { - return s instanceof cvox.ValueSpan; - })[0]; + node instanceof HTMLTextAreaElement)) { + var valueSpan = spans.filter(function(s) { + return s instanceof cvox.ValueSpan; + })[0]; if (valueSpan) { if (document.activeElement !== node) { cvox.Focuser.setFocus(node); } var cursorPosition = opt_displayPosition - - braille.text.getSpanStart(valueSpan) + - valueSpan.offset; + braille.text.getSpanStart(valueSpan) + valueSpan.offset; cvox.ChromeVoxEventWatcher.setUpTextHandler(); node.selectionStart = node.selectionEnd = cursorPosition; cvox.ChromeVoxEventWatcher.handleTextChanged(true); @@ -353,8 +348,8 @@ } if (!handled) { cvox.DomUtil.clickElem( - node || cvox.ChromeVox.navigationManager.getCurrentNode(), - false, false, false, true); + node || cvox.ChromeVox.navigationManager.getCurrentNode(), false, false, + false, true); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/chromevox.js b/chrome/browser/resources/chromeos/chromevox/common/chromevox.js index aabaf00..1dcb41b 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/chromevox.js +++ b/chrome/browser/resources/chromeos/chromevox/common/chromevox.js
@@ -16,49 +16,31 @@ // us to group all of the forward declarations for each file without // having them overwrite the mapping in deps.js goog.addDependency( - '../host/interface/abstract_host.js', - ['cvox.AbstractHost'], + '../host/interface/abstract_host.js', ['cvox.AbstractHost'], []); + +goog.addDependency( + '../host/interface/tts_interface.js', ['cvox.TtsInterface'], []); + +goog.addDependency( + '../host/interface/braille_interface.js', ['cvox.BrailleInterface'], []); + +goog.addDependency( + '../host/interface/mathjax_interface.js', ['cvox.MathJaxInterface'], []); + +goog.addDependency('../chromevox/messages/msgs.js', ['Msgs'], []); + +goog.addDependency( + '../host/interface/abstract_earcons.js', ['cvox.AbstractEarcons'], []); + +goog.addDependency( + '../chromevox/common/key_sequence.js', ['cvox.KeySequence'], []); + +goog.addDependency( + '../chromevox/injected/navigation_manager.js', ['cvox.NavigationManager'], []); goog.addDependency( - '../host/interface/tts_interface.js', - ['cvox.TtsInterface'], - []); - -goog.addDependency( - '../host/interface/braille_interface.js', - ['cvox.BrailleInterface'], - []); - -goog.addDependency( - '../host/interface/mathjax_interface.js', - ['cvox.MathJaxInterface'], - []); - -goog.addDependency( - '../chromevox/messages/msgs.js', - ['Msgs'], - []); - -goog.addDependency( - '../host/interface/abstract_earcons.js', - ['cvox.AbstractEarcons'], - []); - -goog.addDependency( - '../chromevox/common/key_sequence.js', - ['cvox.KeySequence'], - []); - -goog.addDependency( - '../chromevox/injected/navigation_manager.js', - ['cvox.NavigationManager'], - []); - -goog.addDependency( - '../chromevox/injected/serializer.js', - ['cvox.Serializer'], - []); + '../chromevox/injected/serializer.js', ['cvox.Serializer'], []); // Constants /** @@ -202,8 +184,7 @@ * @param {boolean=} speakNode If true, speaks out the node. * @param {number=} opt_queueMode The queue mode to use for speaking. */ -cvox.ChromeVox.syncToNode = function( - targetNode, speakNode, opt_queueMode) {}; +cvox.ChromeVox.syncToNode = function(targetNode, speakNode, opt_queueMode) {}; /** * Provide a way for modules that can't depend on cvox.ChromeVoxUserCommands
diff --git a/chrome/browser/resources/chromeos/chromevox/common/chromevox_json.js b/chrome/browser/resources/chromeos/chromevox/common/chromevox_json.js index 6f65d54..2757908 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/chromevox_json.js +++ b/chrome/browser/resources/chromeos/chromevox/common/chromevox_json.js
@@ -43,23 +43,19 @@ } if (typeof Date.prototype.toJSON !== 'function') { - Date.prototype.toJSON = function(key) { return isFinite(this.valueOf()) ? - this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' : 'null'; + this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : + 'null'; }; - Boolean.prototype.toJSON = - Number.prototype.toJSON = - String.prototype.toJSON = function(key) { - return /** @type {string} */ (this.valueOf()); - }; + Boolean.prototype.toJSON = Number.prototype.toJSON = + String.prototype.toJSON = function(key) { + return /** @type {string} */ (this.valueOf()); + }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, @@ -79,40 +75,39 @@ function quote(string) { - // If the string contains no control characters, no quote characters, and // no backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe // escape sequences. escapable.lastIndex = 0; - return escapable.test(string) ? - '"' + string.replace(escapable, function(a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : - '"' + string + '"'; + return escapable.test(string) ? '"' + + string.replace( + escapable, + function(a) { + var c = meta[a]; + return typeof c === 'string' ? c : + '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + + '"' : + '"' + string + '"'; } function str(key, holder) { - // Produce a string from holder[key]. - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement // value. if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { + typeof value.toJSON === 'function') { value = value.toJSON(key); } @@ -140,8 +135,8 @@ // the remote chance that this gets fixed someday. return String(value); - // If the type is 'object', we might be dealing with an object or an - // array or null. + // If the type is 'object', we might be dealing with an object or an + // array or null. case 'object': @@ -161,7 +156,6 @@ // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { - // The value is an array. Stringify every element. Use null as a // placeholder for non-JSON values. @@ -173,11 +167,11 @@ // Join all of the elements together, separated with commas, and // wrap them in brackets. - v = partial.length === 0 ? '[]' : - gap ? '[\n' + gap + - partial.join(',\n' + gap) + '\n' + - mind + ']' : - '[' + partial.join(',') + ']'; + v = partial.length === 0 ? + '[]' : + gap ? + '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : + '[' + partial.join(',') + ']'; gap = mind; return v; } @@ -197,7 +191,6 @@ } } } else { - // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { @@ -212,9 +205,11 @@ // Join all of the member texts together, separated with commas, // and wrap them in braces. - v = partial.length === 0 ? '{}' : - gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + - mind + '}' : '{' + partial.join(',') + '}'; + v = partial.length === 0 ? + '{}' : + gap ? + '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : + '{' + partial.join(',') + '}'; gap = mind; return v; } @@ -263,7 +258,7 @@ rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { + typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } @@ -291,7 +286,6 @@ var j; function walk(holder, key) { - // The walk method is used to recursively walk the resulting structure // so that modifications can be made. @@ -321,8 +315,7 @@ cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function(a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } @@ -340,11 +333,12 @@ // remaining characters are only whitespace or ']' or ',' or ':' or '{' // or '}'. If that is so, then the text is safe for eval. - if (/^[\],:{}\s]*$/. - test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). - replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). - replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - + if (/^[\],:{}\s]*$/.test( + text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace( + /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text // into a JavaScript structure. The '{' operator is subject to a // syntactic ambiguity in JavaScript: it can begin a block or an
diff --git a/chrome/browser/resources/chromeos/chromevox/common/command_store.js b/chrome/browser/resources/chromeos/chromevox/common/command_store.js index 6a54a38..d6d1ce1 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/command_store.js +++ b/chrome/browser/resources/chromeos/chromevox/common/command_store.js
@@ -132,505 +132,647 @@ * false. */ cvox.CommandStore.CMD_WHITELIST = { - 'toggleStickyMode': {announce: false, - msgId: 'toggle_sticky_mode', - 'disallowOOBE': true, - category: 'modifier_keys'}, - 'toggleKeyPrefix': {announce: false, - skipInput: true, - msgId: 'prefix_key', - 'disallowOOBE': true, - category: 'modifier_keys'}, - 'passThroughMode': {announce: false, - msgId: 'pass_through_key_description', - category: 'modifier_keys'}, + 'toggleStickyMode': { + announce: false, + msgId: 'toggle_sticky_mode', + 'disallowOOBE': true, + category: 'modifier_keys' + }, + 'toggleKeyPrefix': { + announce: false, + skipInput: true, + msgId: 'prefix_key', + 'disallowOOBE': true, + category: 'modifier_keys' + }, + 'passThroughMode': { + announce: false, + msgId: 'pass_through_key_description', + category: 'modifier_keys' + }, - 'stopSpeech': {announce: false, - disallowContinuation: true, - doDefault: true, - msgId: 'stop_speech_key', - category: 'controlling_speech'}, - 'toggleChromeVox': {announce: false, - platformFilter: cvox.PlatformFilter.WML, - msgId: 'toggle_chromevox_active', - category: 'modifier_keys'}, + 'stopSpeech': { + announce: false, + disallowContinuation: true, + doDefault: true, + msgId: 'stop_speech_key', + category: 'controlling_speech' + }, + 'toggleChromeVox': { + announce: false, + platformFilter: cvox.PlatformFilter.WML, + msgId: 'toggle_chromevox_active', + category: 'modifier_keys' + }, 'toggleChromeVoxVersion': {announce: false}, 'showNextUpdatePage': { msgId: 'show_next_update_description', - announce: false, 'category': 'help_commands'}, - 'openChromeVoxMenus': {announce: false, - msgId: 'menus_title'}, - 'decreaseTtsRate': {announce: false, - msgId: 'decrease_tts_rate', - category: 'controlling_speech'}, - 'increaseTtsRate': {announce: false, - msgId: 'increase_tts_rate', - category: 'controlling_speech'}, - 'decreaseTtsPitch': {announce: false, - msgId: 'decrease_tts_pitch', - category: 'controlling_speech'}, - 'increaseTtsPitch': {announce: false, - msgId: 'increase_tts_pitch', - category: 'controlling_speech'}, - 'decreaseTtsVolume': {announce: false, - msgId: 'decrease_tts_volume', - category: 'controlling_speech'}, - 'increaseTtsVolume': {announce: false, - msgId: 'increase_tts_volume', - category: 'controlling_speech'}, - 'cyclePunctuationEcho': {announce: false, - msgId: 'cycle_punctuation_echo', - category: 'controlling_speech'}, - 'cycleTypingEcho': {announce: false, - msgId: 'cycle_typing_echo', - category: 'controlling_speech'}, - - - 'toggleEarcons': {announce: true, - msgId: 'toggle_earcons', - category: 'controlling_speech'}, - - 'toggleSpeechOnOrOff': { - msgId: 'speech_on_off_description', + announce: false, + 'category': 'help_commands' + }, + 'openChromeVoxMenus': {announce: false, msgId: 'menus_title'}, + 'decreaseTtsRate': { + announce: false, + msgId: 'decrease_tts_rate', category: 'controlling_speech' }, + 'increaseTtsRate': { + announce: false, + msgId: 'increase_tts_rate', + category: 'controlling_speech' + }, + 'decreaseTtsPitch': { + announce: false, + msgId: 'decrease_tts_pitch', + category: 'controlling_speech' + }, + 'increaseTtsPitch': { + announce: false, + msgId: 'increase_tts_pitch', + category: 'controlling_speech' + }, + 'decreaseTtsVolume': { + announce: false, + msgId: 'decrease_tts_volume', + category: 'controlling_speech' + }, + 'increaseTtsVolume': { + announce: false, + msgId: 'increase_tts_volume', + category: 'controlling_speech' + }, + 'cyclePunctuationEcho': { + announce: false, + msgId: 'cycle_punctuation_echo', + category: 'controlling_speech' + }, + 'cycleTypingEcho': { + announce: false, + msgId: 'cycle_typing_echo', + category: 'controlling_speech' + }, + + + 'toggleEarcons': + {announce: true, msgId: 'toggle_earcons', category: 'controlling_speech'}, + + 'toggleSpeechOnOrOff': + {msgId: 'speech_on_off_description', category: 'controlling_speech'}, 'handleTab': { allowEvents: true, msgId: 'handle_tab_next', disallowContinuation: true, - category: 'navigation'}, + category: 'navigation' + }, 'handleTabPrev': { allowEvents: true, msgId: 'handle_tab_prev', disallowContinuation: true, - category: 'navigation'}, - 'forward': {forward: true, - announce: true, - msgId: 'forward', - category: 'navigation'}, - 'backward': {backward: true, - announce: true, - msgId: 'backward', - category: 'navigation'}, - 'right': {forward: true, - announce: true, - msgId: 'right', - category: 'navigation'}, - 'left': {backward: true, - announce: true, - msgId: 'left', - category: 'navigation'}, - 'previousGranularity': {announce: true, - msgId: 'previous_granularity', - category: 'navigation'}, - 'nextGranularity': {announce: true, - msgId: 'next_granularity', - category: 'navigation'}, + category: 'navigation' + }, + 'forward': + {forward: true, announce: true, msgId: 'forward', category: 'navigation'}, + 'backward': { + backward: true, + announce: true, + msgId: 'backward', + category: 'navigation' + }, + 'right': + {forward: true, announce: true, msgId: 'right', category: 'navigation'}, + 'left': + {backward: true, announce: true, msgId: 'left', category: 'navigation'}, + 'previousGranularity': + {announce: true, msgId: 'previous_granularity', category: 'navigation'}, + 'nextGranularity': + {announce: true, msgId: 'next_granularity', category: 'navigation'}, - 'previousCharacter': {backward: true, - announce: true, - msgId: 'previous_character', - skipInput: true, - category: 'navigation'}, - 'nextCharacter': {forward: true, - announce: true, - msgId: 'next_character', - skipInput: true, - category: 'navigation'}, - 'previousWord': {backward: true, - announce: true, - msgId: 'previous_word', - skipInput: true, - category: 'navigation'}, - 'nextWord': {forward: true, - announce: true, - msgId: 'next_word', - skipInput: true, - category: 'navigation'}, - 'previousLine': {backward: true, - announce: true, - msgId: 'previous_line', - category: 'navigation'}, - 'nextLine': {forward: true, - announce: true, - msgId: 'next_line', - category: 'navigation'}, - 'previousSentence': {backward: true, - announce: true, - msgId: 'previous_sentence', - skipInput: true, - category: 'navigation'}, - 'nextSentence': {forward: true, - announce: true, - msgId: 'next_sentence', - skipInput: true, - category: 'navigation'}, - 'previousObject': {backward: true, - announce: true, - msgId: 'previous_object', - skipInput: true, - category: 'navigation'}, - 'nextObject': {forward: true, - announce: true, - msgId: 'next_object', - skipInput: true, - category: 'navigation'}, - 'previousGroup': {backward: true, - announce: true, - msgId: 'previous_group', - skipInput: true, - category: 'navigation'}, - 'nextGroup': {forward: true, - announce: true, - msgId: 'next_group', - skipInput: true, - category: 'navigation'}, + 'previousCharacter': { + backward: true, + announce: true, + msgId: 'previous_character', + skipInput: true, + category: 'navigation' + }, + 'nextCharacter': { + forward: true, + announce: true, + msgId: 'next_character', + skipInput: true, + category: 'navigation' + }, + 'previousWord': { + backward: true, + announce: true, + msgId: 'previous_word', + skipInput: true, + category: 'navigation' + }, + 'nextWord': { + forward: true, + announce: true, + msgId: 'next_word', + skipInput: true, + category: 'navigation' + }, + 'previousLine': { + backward: true, + announce: true, + msgId: 'previous_line', + category: 'navigation' + }, + 'nextLine': { + forward: true, + announce: true, + msgId: 'next_line', + category: 'navigation' + }, + 'previousSentence': { + backward: true, + announce: true, + msgId: 'previous_sentence', + skipInput: true, + category: 'navigation' + }, + 'nextSentence': { + forward: true, + announce: true, + msgId: 'next_sentence', + skipInput: true, + category: 'navigation' + }, + 'previousObject': { + backward: true, + announce: true, + msgId: 'previous_object', + skipInput: true, + category: 'navigation' + }, + 'nextObject': { + forward: true, + announce: true, + msgId: 'next_object', + skipInput: true, + category: 'navigation' + }, + 'previousGroup': { + backward: true, + announce: true, + msgId: 'previous_group', + skipInput: true, + category: 'navigation' + }, + 'nextGroup': { + forward: true, + announce: true, + msgId: 'next_group', + skipInput: true, + category: 'navigation' + }, - 'jumpToTop': {forward: true, - announce: true, - msgId: 'jump_to_top', - category: 'navigation' -}, - 'jumpToBottom': {backward: true, - announce: true, - msgId: 'jump_to_bottom', - category: 'navigation'}, + 'jumpToTop': { + forward: true, + announce: true, + msgId: 'jump_to_top', + category: 'navigation' + }, + 'jumpToBottom': { + backward: true, + announce: true, + msgId: 'jump_to_bottom', + category: 'navigation' + }, // Intentionally uncategorized. 'moveToStartOfLine': {forward: true, announce: true}, 'moveToEndOfLine': {backward: true, announce: true}, - 'readFromHere': {forward: true, - announce: false, - msgId: 'read_from_here', - category: 'navigation'}, + 'readFromHere': { + forward: true, + announce: false, + msgId: 'read_from_here', + category: 'navigation' + }, - 'performDefaultAction': {disallowContinuation: true, - msgId: 'perform_default_action', - doDefault: true, - skipInput: true, - category: 'navigation'}, - 'forceClickOnCurrentItem': {announce: true, - disallowContinuation: true, - allowEvents: true, - msgId: 'force_click_on_current_item', - category: 'navigation'}, - 'forceDoubleClickOnCurrentItem': {announce: true, - allowEvents: true, - disallowContinuation: true}, + 'performDefaultAction': { + disallowContinuation: true, + msgId: 'perform_default_action', + doDefault: true, + skipInput: true, + category: 'navigation' + }, + 'forceClickOnCurrentItem': { + announce: true, + disallowContinuation: true, + allowEvents: true, + msgId: 'force_click_on_current_item', + category: 'navigation' + }, + 'forceDoubleClickOnCurrentItem': + {announce: true, allowEvents: true, disallowContinuation: true}, - 'readLinkURL': {announce: false, - msgId: 'read_link_url', - category: 'information'}, - 'readCurrentTitle': {announce: false, - msgId: 'read_current_title', - category: 'information'}, - 'readCurrentURL': {announce: false, - msgId: 'read_current_url', - category: 'information'}, + 'readLinkURL': + {announce: false, msgId: 'read_link_url', category: 'information'}, + 'readCurrentTitle': + {announce: false, msgId: 'read_current_title', category: 'information'}, + 'readCurrentURL': + {announce: false, msgId: 'read_current_url', category: 'information'}, - 'fullyDescribe': {announce: false, - msgId: 'fully_describe', - category: 'information'}, - 'speakTimeAndDate': {announce: false, - msgId: 'speak_time_and_date', - category: 'information'}, - 'toggleSelection': {announce: true, - msgId: 'toggle_selection', - category: 'information'}, + 'fullyDescribe': + {announce: false, msgId: 'fully_describe', category: 'information'}, + 'speakTimeAndDate': + {announce: false, msgId: 'speak_time_and_date', category: 'information'}, + 'toggleSelection': + {announce: true, msgId: 'toggle_selection', category: 'information'}, - 'toggleSearchWidget': {announce: false, - disallowContinuation: true, - msgId: 'toggle_search_widget', - category: 'information'}, + 'toggleSearchWidget': { + announce: false, + disallowContinuation: true, + msgId: 'toggle_search_widget', + category: 'information' + }, - 'undarkenScreen': { - msgId: 'undarken_screen', + 'undarkenScreen': {msgId: 'undarken_screen', category: 'help_commands'}, + + 'darkenScreen': {msgId: 'darken_screen', category: 'help_commands'}, + + 'toggleBrailleTable': + {msgId: 'toggle_braille_table', category: 'help_commands'}, + + 'toggleKeyboardHelp': { + announce: false, + disallowContinuation: true, + msgId: 'show_power_key', + category: 'help_commands' + }, + 'help': { + announce: false, + msgId: 'help', + 'disallowOOBE': true, + disallowContinuation: true, + category: 'help_commands' + }, + 'contextMenu': { + announce: false, + msgId: 'show_context_menu', + disallowContinuation: true, + category: 'information' + }, + + 'showOptionsPage': { + announce: false, + disallowContinuation: true, + msgId: 'show_options_page', + 'disallowOOBE': true, + category: 'help_commands' + }, + 'showKbExplorerPage': { + announce: false, + disallowContinuation: true, + msgId: 'show_kb_explorer_page', + 'disallowOOBE': true, + category: 'help_commands' + }, + 'toggleBrailleCaptions': + {announce: false, msgId: 'braille_captions', category: 'help_commands'}, + 'reportIssue': { + announce: false, + msgId: 'panel_menu_item_report_issue', category: 'help_commands' }, - 'darkenScreen': { - msgId: 'darken_screen', - category: 'help_commands' + 'showFormsList': { + announce: false, + disallowContinuation: true, + nodeList: 'formField', + msgId: 'show_forms_list', + category: 'overview' + }, + 'showHeadingsList': { + announce: false, + nodeList: 'heading', + disallowContinuation: true, + msgId: 'show_headings_list', + category: 'overview' + }, + 'showLandmarksList': { + announce: false, + nodeList: 'landmark', + disallowContinuation: true, + msgId: 'show_landmarks_list', + category: 'overview' + }, + 'showLinksList': { + announce: false, + nodeList: 'link', + disallowContinuation: true, + msgId: 'show_links_list', + category: 'overview' + }, + 'showTablesList': { + announce: false, + nodeList: 'table', + disallowContinuation: true, + msgId: 'show_tables_list', + category: 'overview' }, - 'toggleBrailleTable': { - msgId: 'toggle_braille_table', - category: 'help_commands' + 'nextArticle': {forward: true, findNext: 'article'}, + + 'nextButton': { + forward: true, + findNext: 'button', + msgId: 'next_button', + category: 'jump_commands' }, - - 'toggleKeyboardHelp': {announce: false, - disallowContinuation: true, - msgId: 'show_power_key', - category: 'help_commands'}, - 'help': {announce: false, - msgId: 'help', - 'disallowOOBE': true, - disallowContinuation: true, - category: 'help_commands'}, - 'contextMenu': {announce: false, - msgId: 'show_context_menu', - disallowContinuation: true, - category: 'information'}, - - 'showOptionsPage': {announce: false, - disallowContinuation: true, - msgId: 'show_options_page', - 'disallowOOBE': true, - category: 'help_commands'}, - 'showKbExplorerPage': {announce: false, - disallowContinuation: true, - msgId: 'show_kb_explorer_page', - 'disallowOOBE': true, - category: 'help_commands'}, - 'toggleBrailleCaptions': {announce: false, - msgId: 'braille_captions', - category: 'help_commands'}, - 'reportIssue': {announce: false, - msgId: 'panel_menu_item_report_issue', - category: 'help_commands'}, - - 'showFormsList': {announce: false, - disallowContinuation: true, - nodeList: 'formField', - msgId: 'show_forms_list', - category: 'overview'}, - 'showHeadingsList': {announce: false, nodeList: 'heading', - disallowContinuation: true, - msgId: 'show_headings_list', - category: 'overview'}, - 'showLandmarksList': {announce: false, nodeList: 'landmark', - disallowContinuation: true, - msgId: 'show_landmarks_list', - category: 'overview'}, - 'showLinksList': {announce: false, nodeList: 'link', - disallowContinuation: true, - msgId: 'show_links_list', - category: 'overview'}, - 'showTablesList': {announce: false, nodeList: 'table', - disallowContinuation: true, - msgId: 'show_tables_list', - category: 'overview'}, - - 'nextArticle': {forward: true, - findNext: 'article'}, - - 'nextButton': {forward: true, - findNext: 'button', - msgId: 'next_button', - category: 'jump_commands'}, - 'nextCheckbox': {forward: true, - findNext: 'checkbox', - msgId: 'next_checkbox', - category: 'jump_commands'}, - 'nextComboBox': {forward: true, - findNext: 'combobox', - msgId: 'next_combo_box', - category: 'jump_commands'}, + 'nextCheckbox': { + forward: true, + findNext: 'checkbox', + msgId: 'next_checkbox', + category: 'jump_commands' + }, + 'nextComboBox': { + forward: true, + findNext: 'combobox', + msgId: 'next_combo_box', + category: 'jump_commands' + }, 'nextControl': {forward: true, findNext: 'control'}, - 'nextEditText': {forward: true, - findNext: 'editText', - msgId: 'next_edit_text', - category: 'jump_commands'}, - 'nextFormField': {forward: true, - findNext: 'formField', - msgId: 'next_form_field', - category: 'jump_commands'}, - 'nextGraphic': {forward: true, - findNext: 'graphic', - msgId: 'next_graphic', - category: 'jump_commands'}, - 'nextHeading': {forward: true, - findNext: 'heading', - msgId: 'next_heading', - category: 'jump_commands'}, - 'nextHeading1': {forward: true, - findNext: 'heading1', - msgId: 'next_heading1', - category: 'jump_commands'}, - 'nextHeading2': {forward: true, - findNext: 'heading2', - msgId: 'next_heading2', - category: 'jump_commands'}, - 'nextHeading3': {forward: true, - findNext: 'heading3', - msgId: 'next_heading3', - category: 'jump_commands'}, - 'nextHeading4': {forward: true, - findNext: 'heading4', - msgId: 'next_heading4', - category: 'jump_commands'}, - 'nextHeading5': {forward: true, - findNext: 'heading5', - msgId: 'next_heading5', - category: 'jump_commands'}, - 'nextHeading6': {forward: true, - findNext: 'heading6', - msgId: 'next_heading6', - category: 'jump_commands'}, + 'nextEditText': { + forward: true, + findNext: 'editText', + msgId: 'next_edit_text', + category: 'jump_commands' + }, + 'nextFormField': { + forward: true, + findNext: 'formField', + msgId: 'next_form_field', + category: 'jump_commands' + }, + 'nextGraphic': { + forward: true, + findNext: 'graphic', + msgId: 'next_graphic', + category: 'jump_commands' + }, + 'nextHeading': { + forward: true, + findNext: 'heading', + msgId: 'next_heading', + category: 'jump_commands' + }, + 'nextHeading1': { + forward: true, + findNext: 'heading1', + msgId: 'next_heading1', + category: 'jump_commands' + }, + 'nextHeading2': { + forward: true, + findNext: 'heading2', + msgId: 'next_heading2', + category: 'jump_commands' + }, + 'nextHeading3': { + forward: true, + findNext: 'heading3', + msgId: 'next_heading3', + category: 'jump_commands' + }, + 'nextHeading4': { + forward: true, + findNext: 'heading4', + msgId: 'next_heading4', + category: 'jump_commands' + }, + 'nextHeading5': { + forward: true, + findNext: 'heading5', + msgId: 'next_heading5', + category: 'jump_commands' + }, + 'nextHeading6': { + forward: true, + findNext: 'heading6', + msgId: 'next_heading6', + category: 'jump_commands' + }, - 'nextLandmark': {forward: true, - findNext: 'landmark', - msgId: 'next_landmark', - category: 'jump_commands'}, - 'nextLink': {forward: true, - findNext: 'link', - msgId: 'next_link', - category: 'jump_commands'}, - 'nextList': {forward: true, - findNext: 'list', - msgId: 'next_list', - category: 'jump_commands'}, - 'nextListItem': {forward: true, - findNext: 'listItem', - msgId: 'next_list_item', - category: 'jump_commands'}, - 'nextMath': {forward: true, - findNext: 'math', - msgId: 'next_math', - category: 'jump_commands'}, - 'nextMedia': {forward: true, - findNext: 'media', - msgId: 'next_media', - category: 'jump_commands'}, - 'nextRadio': {forward: true, - findNext: 'radio', - msgId: 'next_radio', - category: 'jump_commands'}, + 'nextLandmark': { + forward: true, + findNext: 'landmark', + msgId: 'next_landmark', + category: 'jump_commands' + }, + 'nextLink': { + forward: true, + findNext: 'link', + msgId: 'next_link', + category: 'jump_commands' + }, + 'nextList': { + forward: true, + findNext: 'list', + msgId: 'next_list', + category: 'jump_commands' + }, + 'nextListItem': { + forward: true, + findNext: 'listItem', + msgId: 'next_list_item', + category: 'jump_commands' + }, + 'nextMath': { + forward: true, + findNext: 'math', + msgId: 'next_math', + category: 'jump_commands' + }, + 'nextMedia': { + forward: true, + findNext: 'media', + msgId: 'next_media', + category: 'jump_commands' + }, + 'nextRadio': { + forward: true, + findNext: 'radio', + msgId: 'next_radio', + category: 'jump_commands' + }, 'nextSection': {forward: true, findNext: 'section'}, 'nextSlider': {forward: true, findNext: 'slider'}, - 'nextTable': {forward: true, - findNext: 'table', - msgId: 'next_table', - category: 'jump_commands'}, - 'nextVisitedLink': {forward: true, - findNext: 'visitedLink', - msgId: 'next_visited_link', - category: 'jump_commands'}, + 'nextTable': { + forward: true, + findNext: 'table', + msgId: 'next_table', + category: 'jump_commands' + }, + 'nextVisitedLink': { + forward: true, + findNext: 'visitedLink', + msgId: 'next_visited_link', + category: 'jump_commands' + }, - 'previousArticle': {backward: true, - findNext: 'article'}, + 'previousArticle': {backward: true, findNext: 'article'}, - 'previousButton': {backward: true, - findNext: 'button', - msgId: 'previous_button', - category: 'jump_commands'}, - 'previousCheckbox': {backward: true, - findNext: 'checkbox', - msgId: 'previous_checkbox', - category: 'jump_commands'}, - 'previousComboBox': {backward: true, - findNext: 'combobox', - msgId: 'previous_combo_box', - category: 'jump_commands'}, + 'previousButton': { + backward: true, + findNext: 'button', + msgId: 'previous_button', + category: 'jump_commands' + }, + 'previousCheckbox': { + backward: true, + findNext: 'checkbox', + msgId: 'previous_checkbox', + category: 'jump_commands' + }, + 'previousComboBox': { + backward: true, + findNext: 'combobox', + msgId: 'previous_combo_box', + category: 'jump_commands' + }, 'previousControl': {backward: true, findNext: 'control'}, - 'previousEditText': {backward: true, - findNext: 'editText', - msgId: 'previous_edit_text', - category: 'jump_commands'}, - 'previousFormField': {backward: true, - findNext: 'formField', - msgId: 'previous_form_field', - category: 'jump_commands'}, - 'previousGraphic': {backward: true, - findNext: 'graphic', - msgId: 'previous_graphic', - category: 'jump_commands'}, - 'previousHeading': {backward: true, - findNext: 'heading', - msgId: 'previous_heading', - category: 'jump_commands'}, - 'previousHeading1': {backward: true, - findNext: 'heading1', - msgId: 'previous_heading1', - category: 'jump_commands'}, - 'previousHeading2': {backward: true, - findNext: 'heading2', - msgId: 'previous_heading2', - category: 'jump_commands'}, - 'previousHeading3': {backward: true, - findNext: 'heading3', - msgId: 'previous_heading3', - category: 'jump_commands'}, - 'previousHeading4': {backward: true, - findNext: 'heading4', - msgId: 'previous_heading4', - category: 'jump_commands'}, - 'previousHeading5': {backward: true, - findNext: 'heading5', - msgId: 'previous_heading5', - category: 'jump_commands'}, - 'previousHeading6': {backward: true, - findNext: 'heading6', - msgId: 'previous_heading6', - category: 'jump_commands'}, + 'previousEditText': { + backward: true, + findNext: 'editText', + msgId: 'previous_edit_text', + category: 'jump_commands' + }, + 'previousFormField': { + backward: true, + findNext: 'formField', + msgId: 'previous_form_field', + category: 'jump_commands' + }, + 'previousGraphic': { + backward: true, + findNext: 'graphic', + msgId: 'previous_graphic', + category: 'jump_commands' + }, + 'previousHeading': { + backward: true, + findNext: 'heading', + msgId: 'previous_heading', + category: 'jump_commands' + }, + 'previousHeading1': { + backward: true, + findNext: 'heading1', + msgId: 'previous_heading1', + category: 'jump_commands' + }, + 'previousHeading2': { + backward: true, + findNext: 'heading2', + msgId: 'previous_heading2', + category: 'jump_commands' + }, + 'previousHeading3': { + backward: true, + findNext: 'heading3', + msgId: 'previous_heading3', + category: 'jump_commands' + }, + 'previousHeading4': { + backward: true, + findNext: 'heading4', + msgId: 'previous_heading4', + category: 'jump_commands' + }, + 'previousHeading5': { + backward: true, + findNext: 'heading5', + msgId: 'previous_heading5', + category: 'jump_commands' + }, + 'previousHeading6': { + backward: true, + findNext: 'heading6', + msgId: 'previous_heading6', + category: 'jump_commands' + }, - 'previousLandmark': {backward: true, - findNext: 'landmark', - msgId: 'previous_landmark', - category: 'jump_commands'}, - 'previousLink': {backward: true, - findNext: 'link', - msgId: 'previous_link', - category: 'jump_commands'}, - 'previousList': {backward: true, - findNext: 'list', - msgId: 'previous_list', - category: 'jump_commands'}, - 'previousListItem': {backward: true, - findNext: 'listItem', - msgId: 'previous_list_item', - category: 'jump_commands'}, - 'previousMath': {backward: true, - findNext: 'math', - msgId: 'previous_math', - category: 'jump_commands'}, - 'previousMedia': {backward: true, - findNext: 'media', - msgId: 'previous_media', - category: 'jump_commands'}, - 'previousRadio': {backward: true, - findNext: 'radio', - msgId: 'previous_radio', - category: 'jump_commands'}, + 'previousLandmark': { + backward: true, + findNext: 'landmark', + msgId: 'previous_landmark', + category: 'jump_commands' + }, + 'previousLink': { + backward: true, + findNext: 'link', + msgId: 'previous_link', + category: 'jump_commands' + }, + 'previousList': { + backward: true, + findNext: 'list', + msgId: 'previous_list', + category: 'jump_commands' + }, + 'previousListItem': { + backward: true, + findNext: 'listItem', + msgId: 'previous_list_item', + category: 'jump_commands' + }, + 'previousMath': { + backward: true, + findNext: 'math', + msgId: 'previous_math', + category: 'jump_commands' + }, + 'previousMedia': { + backward: true, + findNext: 'media', + msgId: 'previous_media', + category: 'jump_commands' + }, + 'previousRadio': { + backward: true, + findNext: 'radio', + msgId: 'previous_radio', + category: 'jump_commands' + }, 'previousSection': {backward: true, findNext: 'section'}, 'previousSlider': {backward: true, findNext: 'slider'}, - 'previousTable': {backward: true, - findNext: 'table', - msgId: 'previous_table', - category: 'jump_commands'}, - 'previousVisitedLink': {backward: true, - findNext: 'visitedLink', - msgId: 'previous_visited_link', - category: 'jump_commands'}, + 'previousTable': { + backward: true, + findNext: 'table', + msgId: 'previous_table', + category: 'jump_commands' + }, + 'previousVisitedLink': { + backward: true, + findNext: 'visitedLink', + msgId: 'previous_visited_link', + category: 'jump_commands' + }, // Table Actions. - 'announceHeaders': {announce: false, - msgId: 'announce_headers', - category: 'tables'}, - 'speakTableLocation': {announce: false, - msgId: 'speak_table_location', - category: 'tables'}, - 'goToFirstCell': {announce: true, - msgId: 'skip_to_beginning', - category: 'tables'}, - 'goToLastCell': {announce: true, - msgId: 'skip_to_end', - category: 'tables'}, - 'goToRowFirstCell': {announce: true, - msgId: 'skip_to_row_beginning', - category: 'tables'}, - 'goToRowLastCell': {announce: true, - msgId: 'skip_to_row_end', - category: 'tables'}, - 'goToColFirstCell': {announce: true, - msgId: 'skip_to_col_beginning', - category: 'tables'}, - 'goToColLastCell': {announce: true, - msgId: 'skip_to_col_end', - category: 'tables'}, + 'announceHeaders': + {announce: false, msgId: 'announce_headers', category: 'tables'}, + 'speakTableLocation': + {announce: false, msgId: 'speak_table_location', category: 'tables'}, + 'goToFirstCell': + {announce: true, msgId: 'skip_to_beginning', category: 'tables'}, + 'goToLastCell': {announce: true, msgId: 'skip_to_end', category: 'tables'}, + 'goToRowFirstCell': + {announce: true, msgId: 'skip_to_row_beginning', category: 'tables'}, + 'goToRowLastCell': + {announce: true, msgId: 'skip_to_row_end', category: 'tables'}, + 'goToColFirstCell': + {announce: true, msgId: 'skip_to_col_beginning', category: 'tables'}, + 'goToColLastCell': + {announce: true, msgId: 'skip_to_col_end', category: 'tables'}, // These commands are left out of the options page because they involve // multiple, non-user configurable modifiers. 'previousRow': {backward: true, announce: true, skipInput: true}, @@ -639,64 +781,71 @@ 'nextCol': {forward: true, announce: true, skipInput: true}, // Generic Actions. - 'enterShifter': {announce: true, - msgId: 'enter_content', - category: 'navigation'}, - 'exitShifter': {announce: true, - msgId: 'exit_content', - category: 'navigation'}, + 'enterShifter': + {announce: true, msgId: 'enter_content', category: 'navigation'}, + 'exitShifter': + {announce: true, msgId: 'exit_content', category: 'navigation'}, 'exitShifterContent': {announce: true}, - 'openLongDesc': {announce: false, - msgId: 'open_long_desc', - category: 'information'}, + 'openLongDesc': + {announce: false, msgId: 'open_long_desc', category: 'information'}, - 'pauseAllMedia': {announce: false, - msgId: 'pause_all_media', - category: 'information'}, + 'pauseAllMedia': + {announce: false, msgId: 'pause_all_media', category: 'information'}, // Math specific commands. - 'toggleSemantics': {announce: false, - msgId: 'toggle_semantics', - category: 'information'}, + 'toggleSemantics': + {announce: false, msgId: 'toggle_semantics', category: 'information'}, // Braille specific commands. - 'routing': {announce: false, - allowEvents: true, - msgId: 'braille_routing', - category: 'braille'}, - 'pan_left': {backward: true, - announce: true, - msgId: 'braille_pan_left', - category: 'braille'}, - 'pan_right': {forward: true, - announce: true, - msgId: 'braille_pan_right', - category: 'braille'}, - 'line_up': {backward: true, - announce: true, - msgId: 'braille_line_up', - category: 'braille'}, - 'line_down': {forward: true, - announce: true, - msgId: 'braille_line_down', - category: 'braille'}, - 'top': {forward: true, - announce: true, - msgId: 'braille_top', - category: 'braille'}, - 'bottom': {backward: true, - announce: true, - msgId: 'braille_bottom', - category: 'braille'}, - 'viewGraphicAsBraille': {announce: true, - msgId: 'view_graphic_as_braille', - category: 'braille'}, + 'routing': { + announce: false, + allowEvents: true, + msgId: 'braille_routing', + category: 'braille' + }, + 'pan_left': { + backward: true, + announce: true, + msgId: 'braille_pan_left', + category: 'braille' + }, + 'pan_right': { + forward: true, + announce: true, + msgId: 'braille_pan_right', + category: 'braille' + }, + 'line_up': { + backward: true, + announce: true, + msgId: 'braille_line_up', + category: 'braille' + }, + 'line_down': { + forward: true, + announce: true, + msgId: 'braille_line_down', + category: 'braille' + }, + 'top': { + forward: true, + announce: true, + msgId: 'braille_top', + category: 'braille' + }, + 'bottom': { + backward: true, + announce: true, + msgId: 'braille_bottom', + category: 'braille' + }, + 'viewGraphicAsBraille': + {announce: true, msgId: 'view_graphic_as_braille', category: 'braille'}, // Developer commands. - 'enableConsoleTts': {announce: false, - msgId: 'enable_tts_log', - category: 'developer'}, + 'enableConsoleTts': + {announce: false, msgId: 'enable_tts_log', category: 'developer'}, 'startHistoryRecording': {announce: false}, 'stopHistoryRecording': {announce: false}, @@ -718,100 +867,152 @@ * backwardError: The message id of the error string when moving backward. */ cvox.CommandStore.NODE_INFO_MAP = { - 'checkbox': {predicate: 'checkboxPredicate', - forwardError: 'no_next_checkbox', - backwardError: 'no_previous_checkbox', - typeMsg: 'role_checkbox'}, - 'radio': {predicate: 'radioPredicate', - forwardError: 'no_next_radio_button', - backwardError: 'no_previous_radio_button', - typeMsg: 'role_radio'}, - 'slider': {predicate: 'sliderPredicate', - forwardError: 'no_next_slider', - backwardError: 'no_previous_slider', - typeMsg: 'role_slider'}, - 'graphic': {predicate: 'graphicPredicate', - forwardError: 'no_next_graphic', - backwardError: 'no_previous_graphic', - typeMsg: 'UNUSED'}, - 'article': {predicate: 'articlePredicate', - forwardError: 'no_next_ARTICLE', - backwardError: 'no_previous_ARTICLE', - typeMsg: 'TAG_ARTICLE'}, - 'button': {predicate: 'buttonPredicate', - forwardError: 'no_next_button', - backwardError: 'no_previous_button', - typeMsg: 'role_button'}, - 'combobox': {predicate: 'comboBoxPredicate', - forwardError: 'no_next_combo_box', - backwardError: 'no_previous_combo_box', - typeMsg: 'role_combobox'}, - 'editText': {predicate: 'editTextPredicate', - forwardError: 'no_next_edit_text', - backwardError: 'no_previous_edit_text', - typeMsg: 'input_type_text'}, - 'heading': {predicate: 'headingPredicate', - forwardError: 'no_next_heading', - backwardError: 'no_previous_heading', - typeMsg: 'role_heading'}, - 'heading1': {predicate: 'heading1Predicate', - forwardError: 'no_next_heading_1', - backwardError: 'no_previous_heading_1'}, - 'heading2': {predicate: 'heading2Predicate', - forwardError: 'no_next_heading_2', - backwardError: 'no_previous_heading_2'}, - 'heading3': {predicate: 'heading3Predicate', - forwardError: 'no_next_heading_3', - backwardError: 'no_previous_heading_3'}, - 'heading4': {predicate: 'heading4Predicate', - forwardError: 'no_next_heading_4', - backwardError: 'no_previous_heading_4'}, - 'heading5': {predicate: 'heading5Predicate', - forwardError: 'no_next_heading_5', - backwardError: 'no_previous_heading_5'}, - 'heading6': {predicate: 'heading6Predicate', - forwardError: 'no_next_heading_6', - backwardError: 'no_previous_heading_6'}, + 'checkbox': { + predicate: 'checkboxPredicate', + forwardError: 'no_next_checkbox', + backwardError: 'no_previous_checkbox', + typeMsg: 'role_checkbox' + }, + 'radio': { + predicate: 'radioPredicate', + forwardError: 'no_next_radio_button', + backwardError: 'no_previous_radio_button', + typeMsg: 'role_radio' + }, + 'slider': { + predicate: 'sliderPredicate', + forwardError: 'no_next_slider', + backwardError: 'no_previous_slider', + typeMsg: 'role_slider' + }, + 'graphic': { + predicate: 'graphicPredicate', + forwardError: 'no_next_graphic', + backwardError: 'no_previous_graphic', + typeMsg: 'UNUSED' + }, + 'article': { + predicate: 'articlePredicate', + forwardError: 'no_next_ARTICLE', + backwardError: 'no_previous_ARTICLE', + typeMsg: 'TAG_ARTICLE' + }, + 'button': { + predicate: 'buttonPredicate', + forwardError: 'no_next_button', + backwardError: 'no_previous_button', + typeMsg: 'role_button' + }, + 'combobox': { + predicate: 'comboBoxPredicate', + forwardError: 'no_next_combo_box', + backwardError: 'no_previous_combo_box', + typeMsg: 'role_combobox' + }, + 'editText': { + predicate: 'editTextPredicate', + forwardError: 'no_next_edit_text', + backwardError: 'no_previous_edit_text', + typeMsg: 'input_type_text' + }, + 'heading': { + predicate: 'headingPredicate', + forwardError: 'no_next_heading', + backwardError: 'no_previous_heading', + typeMsg: 'role_heading' + }, + 'heading1': { + predicate: 'heading1Predicate', + forwardError: 'no_next_heading_1', + backwardError: 'no_previous_heading_1' + }, + 'heading2': { + predicate: 'heading2Predicate', + forwardError: 'no_next_heading_2', + backwardError: 'no_previous_heading_2' + }, + 'heading3': { + predicate: 'heading3Predicate', + forwardError: 'no_next_heading_3', + backwardError: 'no_previous_heading_3' + }, + 'heading4': { + predicate: 'heading4Predicate', + forwardError: 'no_next_heading_4', + backwardError: 'no_previous_heading_4' + }, + 'heading5': { + predicate: 'heading5Predicate', + forwardError: 'no_next_heading_5', + backwardError: 'no_previous_heading_5' + }, + 'heading6': { + predicate: 'heading6Predicate', + forwardError: 'no_next_heading_6', + backwardError: 'no_previous_heading_6' + }, - 'link': {predicate: 'linkPredicate', - forwardError: 'no_next_link', - backwardError: 'no_previous_link', - typeMsg: 'role_link'}, - 'table': {predicate: 'tablePredicate', - forwardError: 'no_next_table', - backwardError: 'no_previous_table', - typeMsg: 'table_strategy'}, - 'visitedLink': {predicate: 'visitedLinkPredicate', - forwardError: 'no_next_visited_link', - backwardError: 'no_previous_visited_link', - typeMsg: 'role_link'}, - 'list': {predicate: 'listPredicate', - forwardError: 'no_next_list', - backwardError: 'no_previous_list', - typeMsg: 'role_list'}, - 'listItem': {predicate: 'listItemPredicate', - forwardError: 'no_next_list_item', - backwardError: 'no_previous_list_item', - typeMsg: 'role_listitem'}, - 'formField': {predicate: 'formFieldPredicate', - forwardError: 'no_next_form_field', - backwardError: 'no_previous_form_field', - typeMsg: 'role_form'}, - 'landmark': {predicate: 'landmarkPredicate', - forwardError: 'no_next_landmark', - backwardError: 'no_previous_landmark', - typeMsg: 'role_landmark'}, - 'math': {predicate: 'mathPredicate', - forwardError: 'no_next_math', - backwardError: 'no_previous_math', - typeMsg: 'math_expr'}, - 'media': {predicate: 'mediaPredicate', - forwardError: 'no_next_media_widget', - backwardError: 'no_previous_media_widget'}, - 'section': {predicate: 'sectionPredicate', - forwardError: 'no_next_section', - backwardError: 'no_previous_section'}, - 'control': {predicate: 'controlPredicate', - forwardError: 'no_next_control', - backwardError: 'no_previous_control'} + 'link': { + predicate: 'linkPredicate', + forwardError: 'no_next_link', + backwardError: 'no_previous_link', + typeMsg: 'role_link' + }, + 'table': { + predicate: 'tablePredicate', + forwardError: 'no_next_table', + backwardError: 'no_previous_table', + typeMsg: 'table_strategy' + }, + 'visitedLink': { + predicate: 'visitedLinkPredicate', + forwardError: 'no_next_visited_link', + backwardError: 'no_previous_visited_link', + typeMsg: 'role_link' + }, + 'list': { + predicate: 'listPredicate', + forwardError: 'no_next_list', + backwardError: 'no_previous_list', + typeMsg: 'role_list' + }, + 'listItem': { + predicate: 'listItemPredicate', + forwardError: 'no_next_list_item', + backwardError: 'no_previous_list_item', + typeMsg: 'role_listitem' + }, + 'formField': { + predicate: 'formFieldPredicate', + forwardError: 'no_next_form_field', + backwardError: 'no_previous_form_field', + typeMsg: 'role_form' + }, + 'landmark': { + predicate: 'landmarkPredicate', + forwardError: 'no_next_landmark', + backwardError: 'no_previous_landmark', + typeMsg: 'role_landmark' + }, + 'math': { + predicate: 'mathPredicate', + forwardError: 'no_next_math', + backwardError: 'no_previous_math', + typeMsg: 'math_expr' + }, + 'media': { + predicate: 'mediaPredicate', + forwardError: 'no_next_media_widget', + backwardError: 'no_previous_media_widget' + }, + 'section': { + predicate: 'sectionPredicate', + forwardError: 'no_next_section', + backwardError: 'no_previous_section' + }, + 'control': { + predicate: 'controlPredicate', + forwardError: 'no_next_control', + backwardError: 'no_previous_control' + } };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/composite_tts.js b/chrome/browser/resources/chromeos/chromevox/common/composite_tts.js index e7d19e5..67037d6 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/composite_tts.js +++ b/chrome/browser/resources/chromeos/chromevox/common/composite_tts.js
@@ -40,8 +40,8 @@ /** * @override */ -cvox.CompositeTts.prototype.speak = - function(textString, queueMode, properties) { +cvox.CompositeTts.prototype.speak = function( + textString, queueMode, properties) { this.ttsEngines_.forEach(function(engine) { engine.speak(textString, queueMode, properties); }); @@ -83,8 +83,8 @@ /** * @override */ -cvox.CompositeTts.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { +cvox.CompositeTts.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) { this.ttsEngines_.forEach(function(engine) { engine.increaseOrDecreaseProperty(propertyName, increase); });
diff --git a/chrome/browser/resources/chromeos/chromevox/common/content_editable_extractor.js b/chrome/browser/resources/chromeos/chromevox/common/content_editable_extractor.js index ce0d941..f0f8dfff 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/content_editable_extractor.js +++ b/chrome/browser/resources/chromeos/chromevox/common/content_editable_extractor.js
@@ -103,11 +103,8 @@ continue; } - if (lastBottom !== null && - rect.bottom != lastBottom && - textSize > 0 && - text.substr(-1).match(/\S/) && - c.match(/\S/)) { + if (lastBottom !== null && rect.bottom != lastBottom && textSize > 0 && + text.substr(-1).match(/\S/) && c.match(/\S/)) { text += '\n'; textSize++; } @@ -120,8 +117,7 @@ } } - if (!setStart && - selectionStartIndex == -1 && + if (!setStart && selectionStartIndex == -1 && endCursor.node == selectionStart.node && endCursor.index >= selectionStart.index) { if (endCursor.index > selectionStart.index) { @@ -130,8 +126,7 @@ setStart = true; } } - if (!setEnd && - selectionEndIndex == -1 && + if (!setEnd && selectionEndIndex == -1 && endCursor.node == selectionEnd.node && endCursor.index >= selectionEnd.index) { if (endCursor.index > selectionEnd.index) {
diff --git a/chrome/browser/resources/chromeos/chromevox/common/cursor.js b/chrome/browser/resources/chromeos/chromevox/common/cursor.js index 1cf5963..223c10f 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/cursor.js +++ b/chrome/browser/resources/chromeos/chromevox/common/cursor.js
@@ -53,7 +53,6 @@ * @return {boolean} True if equal. */ cvox.Cursor.prototype.equals = function(rhs) { - return this.node == rhs.node && - this.index == rhs.index && + return this.node == rhs.node && this.index == rhs.index && this.text == rhs.text; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/cursor_selection.js b/chrome/browser/resources/chromeos/chromevox/common/cursor_selection.js index f043516..cb8bea8 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/cursor_selection.js +++ b/chrome/browser/resources/chromeos/chromevox/common/cursor_selection.js
@@ -40,10 +40,10 @@ if ((this.isReversed_ && this.start.node.compareDocumentPosition(this.end.node) == - cvox.CursorSelection.BEFORE) || + cvox.CursorSelection.BEFORE) || (!this.isReversed_ && this.end.node.compareDocumentPosition(this.start.node) == - cvox.CursorSelection.BEFORE)) { + cvox.CursorSelection.BEFORE)) { var oldStart = this.start; this.start = this.end; this.end = oldStart; @@ -134,8 +134,7 @@ var text = cvox.TraverseUtil.getNodeText(node); return new cvox.CursorSelection( - new cvox.Cursor(node, 0, text), - new cvox.Cursor(node, 0, text)); + new cvox.Cursor(node, 0, text), new cvox.Cursor(node, 0, text)); }; @@ -144,8 +143,8 @@ * @return {!cvox.CursorSelection} The selection. */ cvox.CursorSelection.fromBody = function() { - return /** @type {!cvox.CursorSelection} */ ( - cvox.CursorSelection.fromNode(document.body)); + return /** @type {!cvox.CursorSelection} */ ( + cvox.CursorSelection.fromNode(document.body)); }; /** @@ -190,7 +189,8 @@ * @return {boolean} True if equal. */ cvox.CursorSelection.prototype.absEquals = function(rhs) { - return ((this.start.equals(rhs.start) && this.end.equals(rhs.end)) || + return ( + (this.start.equals(rhs.start) && this.end.equals(rhs.end)) || (this.end.equals(rhs.start) && this.start.equals(rhs.end))); }; @@ -221,7 +221,7 @@ // DOM ranges use different conventions when surrounding a node. For // instance, input nodes endOffset is always 0 while h1's endOffset is 1 - //with both having no children. Use a range to compute the endOffset. + // with both having no children. Use a range to compute the endOffset. var testRange = document.createRange(); testRange.selectNodeContents(node); this.absEnd().index = testRange.endOffset;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/date_widget.js b/chrome/browser/resources/chromeos/chromevox/common/date_widget.js index b494db92..0b4860f 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/date_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/common/date_widget.js
@@ -93,11 +93,11 @@ for (var i = 0; i < this.maxPos_; i++) { var evt = document.createEvent('KeyboardEvent'); evt.initKeyboardEvent( - 'keydown', true, true, window, 'Left', 0, false, false, false, false); + 'keydown', true, true, window, 'Left', 0, false, false, false, false); this.dateElem_.dispatchEvent(evt); evt = document.createEvent('KeyboardEvent'); evt.initKeyboardEvent( - 'keyup', true, true, window, 'Left', 0, false, false, false, false); + 'keyup', true, true, window, 'Left', 0, false, false, false, false); this.dateElem_.dispatchEvent(evt); } @@ -130,7 +130,7 @@ // start at 1. var monthString = currentDate.getMonth() + 1 + ''; if (monthString.length < 2) { - monthString = '0' + monthString; // Month format is MM. + monthString = '0' + monthString; // Month format is MM. } var dayString = currentDate.getDate() + ''; @@ -151,7 +151,7 @@ var weekString = Math.ceil((((currentDate - yearStart) / 86400000) + 1) / 7) + ''; if (weekString.length < 2) { - weekString = '0' + weekString; // Week format is WXX. + weekString = '0' + weekString; // Week format is WXX. } weekString = 'W' + weekString; valueString = yearString + '-' + weekString; @@ -231,8 +231,8 @@ } if (week != this.pWeek_) { - changeMessage = changeMessage + - Msgs.getMsg('datewidget_week') + week + '\n'; + changeMessage = + changeMessage + Msgs.getMsg('datewidget_week') + week + '\n'; this.pWeek_ = week; }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/description_util.js b/chrome/browser/resources/chromeos/chromevox/common/description_util.js index c6145fc..16b142e7 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/description_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/description_util.js
@@ -44,8 +44,8 @@ * itself and its surrounding control if it has one. * @return {cvox.NavDescription} The description of the control. */ -cvox.DescriptionUtil.getControlDescription = - function(control, opt_changedAncestors) { +cvox.DescriptionUtil.getControlDescription = function( + control, opt_changedAncestors) { var ancestors = [control]; if (opt_changedAncestors && (opt_changedAncestors.length > 0)) { ancestors = opt_changedAncestors; @@ -145,8 +145,8 @@ // it for larger ancestry changes. if (context.length > 0 || (annotation.length > 0 && node.childElementCount > 1)) { - context = roleText + ' ' + cvox.DomUtil.getState(node, false) + - ' ' + context; + context = + roleText + ' ' + cvox.DomUtil.getState(node, false) + ' ' + context; } else { if (annotation.length > 0) { annotation += @@ -185,25 +185,24 @@ * @return {!Array<cvox.NavDescription>} The description of the navigation * action. */ -cvox.DescriptionUtil.getDescriptionFromNavigation = - function(prevNode, node, recursive, verbosity) { +cvox.DescriptionUtil.getDescriptionFromNavigation = function( + prevNode, node, recursive, verbosity) { if (!prevNode || !node) { return []; } // Specialized math descriptions. - if (cvox.DomUtil.isMath(node) && - !cvox.AriaUtil.isMath(node)) { + if (cvox.DomUtil.isMath(node) && !cvox.AriaUtil.isMath(node)) { return cvox.DescriptionUtil.getMathDescription(node); } // Next, check to see if the current node is a collection type. if (cvox.DescriptionUtil.COLLECTION_NODE_TYPE[node.tagName]) { return cvox.DescriptionUtil.getCollectionDescription( - /** @type {!cvox.CursorSelection} */( + /** @type {!cvox.CursorSelection} */ ( cvox.CursorSelection.fromNode(prevNode)), - /** @type {!cvox.CursorSelection} */( - cvox.CursorSelection.fromNode(node))); + /** @type {!cvox.CursorSelection} */ + (cvox.CursorSelection.fromNode(node))); } // Now, generate a description for all other elements. @@ -215,8 +214,7 @@ var prevDesc = cvox.DescriptionUtil.getDescriptionFromAncestors( prevAncestors, recursive, verbosity); if (prevDesc.context && !desc.context) { - desc.context = - Msgs.getMsg('exited_container', [prevDesc.context]); + desc.context = Msgs.getMsg('exited_container', [prevDesc.context]); } } return [desc]; @@ -276,8 +274,7 @@ while (cvox.DomUtil.isDescendantOfNode(node, sel.start.node)) { var ancestors = cvox.DomUtil.getUniqueAncestors(prevNode, node); // Specialized math descriptions. - if (cvox.DomUtil.isMath(node) && - !cvox.AriaUtil.isMath(node)) { + if (cvox.DomUtil.isMath(node) && !cvox.AriaUtil.isMath(node)) { descriptions = descriptions.concat(cvox.DescriptionUtil.getMathDescription(node)); } else { @@ -305,8 +302,8 @@ * @param {!Node} node The target element. * @return {!Array<!cvox.NavDescription>} The descriptions. */ -cvox.DescriptionUtil.getFullDescriptionsFromChildren = - function(prevnode, node) { +cvox.DescriptionUtil.getFullDescriptionsFromChildren = function( + prevnode, node) { var descriptions = []; if (!node) { return descriptions; @@ -362,10 +359,8 @@ // <annotation> collection with <n> items. Currently only enabled // for links, but support should be added for any other type that // makes sense. - if (descriptions.length >= 3 && - descriptions[0].context.length == 0 && - annotations.length == 1 && - annotations[0].length > 0 && + if (descriptions.length >= 3 && descriptions[0].context.length == 0 && + annotations.length == 1 && annotations[0].length > 0 && cvox.DescriptionUtil.isAnnotationCollection_(annotations[0])) { var commonAnnotation = annotations[0]; var firstContext = descriptions[0].context; @@ -379,8 +374,7 @@ text: '', annotation: Msgs.getMsg( 'collection', - [commonAnnotation, - Msgs.getNumber(descriptions.length)]) + [commonAnnotation, Msgs.getNumber(descriptions.length)]) })); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/dom_predicates.js b/chrome/browser/resources/chromeos/chromevox/common/dom_predicates.js index d43ed79..3674383 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/dom_predicates.js +++ b/chrome/browser/resources/chromeos/chromevox/common/dom_predicates.js
@@ -121,10 +121,9 @@ cvox.DomPredicates.editTextPredicate = function(nodes) { for (var i = 0; i < nodes.length; i++) { if ((nodes[i].getAttribute && nodes[i].getAttribute('role') == 'textbox') || - nodes[i].tagName == 'TEXTAREA' || - nodes[i].isContentEditable || + nodes[i].tagName == 'TEXTAREA' || nodes[i].isContentEditable || (nodes[i].tagName == 'INPUT' && - cvox.DomUtil.isInputTypeText(nodes[i]))) { + cvox.DomUtil.isInputTypeText(nodes[i]))) { return nodes[i]; } } @@ -139,8 +138,7 @@ */ cvox.DomPredicates.headingPredicate = function(nodes) { for (var i = 0; i < nodes.length; i++) { - if (nodes[i].getAttribute && - nodes[i].getAttribute('role') == 'heading') { + if (nodes[i].getAttribute && nodes[i].getAttribute('role') == 'heading') { return nodes[i]; } switch (nodes[i].tagName) { @@ -257,8 +255,7 @@ cvox.DomPredicates.cellPredicate = function(nodes) { for (var i = nodes.length - 1; i >= 0; --i) { var node = nodes[i]; - if (node.tagName == 'TD' || - node.tagName == 'TH' || + if (node.tagName == 'TD' || node.tagName == 'TH' || (node.getAttribute && node.getAttribute('role') == 'gridcell')) { return node; } @@ -291,8 +288,7 @@ cvox.DomPredicates.listPredicate = function(nodes) { for (var i = 0; i < nodes.length; i++) { if ((nodes[i].getAttribute && nodes[i].getAttribute('role') == 'list') || - nodes[i].tagName == 'UL' || - nodes[i].tagName == 'OL') { + nodes[i].tagName == 'UL' || nodes[i].tagName == 'OL') { return nodes[i]; } } @@ -397,8 +393,7 @@ if (cvox.AriaUtil.isLandmark(nodes[i])) { return nodes[i]; } - if (nodes[i].getAttribute && - nodes[i].getAttribute('role') == 'heading') { + if (nodes[i].getAttribute && nodes[i].getAttribute('role') == 'heading') { return nodes[i]; } switch (nodes[i].tagName) { @@ -454,8 +449,7 @@ */ cvox.DomPredicates.articlePredicate = function(nodes) { for (var i = 0; i < nodes.length; i++) { - if ((nodes[i].getAttribute && - nodes[i].getAttribute('role') == 'article') || + if ((nodes[i].getAttribute && nodes[i].getAttribute('role') == 'article') || nodes[i].tagName == 'ARTICLE') { return nodes[i]; } @@ -470,8 +464,7 @@ */ cvox.DomPredicates.mediaPredicate = function(nodes) { for (var i = 0; i < nodes.length; i++) { - if (nodes[i].tagName == 'AUDIO' || - nodes[i].tagName == 'VIDEO') { + if (nodes[i].tagName == 'AUDIO' || nodes[i].tagName == 'VIDEO') { return nodes[i]; } }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/dom_util.js b/chrome/browser/resources/chromeos/chromevox/common/dom_util.js index 15e43ec6..47a4aa7b 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/dom_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/dom_util.js
@@ -24,8 +24,7 @@ * Create the namespace * @constructor */ -cvox.DomUtil = function() { -}; +cvox.DomUtil = function() {}; /** @@ -35,27 +34,27 @@ * @type {Object} */ cvox.DomUtil.INPUT_TYPE_TO_INFORMATION_TABLE_MSG = { - 'button' : 'role_button', - 'checkbox' : 'role_checkbox', - 'color' : 'input_type_color', - 'datetime' : 'input_type_datetime', - 'datetime-local' : 'input_type_datetime_local', - 'date' : 'input_type_date', - 'email' : 'input_type_email', - 'file' : 'input_type_file', - 'image' : 'role_button', - 'month' : 'input_type_month', - 'number' : 'input_type_number', - 'password' : 'input_type_password', - 'radio' : 'role_radio', - 'range' : 'role_slider', - 'reset' : 'input_type_reset', - 'search' : 'input_type_search', - 'submit' : 'role_button', - 'tel' : 'input_type_number', - 'text' : 'input_type_text', - 'url' : 'input_type_url', - 'week' : 'input_type_week' + 'button': 'role_button', + 'checkbox': 'role_checkbox', + 'color': 'input_type_color', + 'datetime': 'input_type_datetime', + 'datetime-local': 'input_type_datetime_local', + 'date': 'input_type_date', + 'email': 'input_type_email', + 'file': 'input_type_file', + 'image': 'role_button', + 'month': 'input_type_month', + 'number': 'input_type_number', + 'password': 'input_type_password', + 'radio': 'role_radio', + 'range': 'role_slider', + 'reset': 'input_type_reset', + 'search': 'input_type_search', + 'submit': 'role_button', + 'tel': 'input_type_number', + 'text': 'input_type_text', + 'url': 'input_type_url', + 'week': 'input_type_week' }; @@ -66,31 +65,31 @@ * @type {Object} */ cvox.DomUtil.TAG_TO_INFORMATION_TABLE_VERBOSE_MSG = { - 'A' : 'role_link', - 'ARTICLE' : 'tag_article', - 'ASIDE' : 'tag_aside', - 'AUDIO' : 'tag_audio', - 'BUTTON' : 'role_button', - 'FOOTER' : 'tag_footer', - 'H1' : 'tag_h1', - 'H2' : 'tag_h2', - 'H3' : 'tag_h3', - 'H4' : 'tag_h4', - 'H5' : 'tag_h5', - 'H6' : 'tag_h6', - 'HEADER' : 'tag_header', - 'HGROUP' : 'tag_hgroup', - 'LI' : 'tag_li', - 'MARK' : 'tag_mark', - 'NAV' : 'tag_nav', - 'OL' : 'tag_ol', - 'SECTION' : 'tag_section', - 'SELECT' : 'tag_select', - 'TABLE' : 'tag_table', - 'TEXTAREA' : 'tag_textarea', - 'TIME' : 'tag_time', - 'UL' : 'tag_ul', - 'VIDEO' : 'tag_video' + 'A': 'role_link', + 'ARTICLE': 'tag_article', + 'ASIDE': 'tag_aside', + 'AUDIO': 'tag_audio', + 'BUTTON': 'role_button', + 'FOOTER': 'tag_footer', + 'H1': 'tag_h1', + 'H2': 'tag_h2', + 'H3': 'tag_h3', + 'H4': 'tag_h4', + 'H5': 'tag_h5', + 'H6': 'tag_h6', + 'HEADER': 'tag_header', + 'HGROUP': 'tag_hgroup', + 'LI': 'tag_li', + 'MARK': 'tag_mark', + 'NAV': 'tag_nav', + 'OL': 'tag_ol', + 'SECTION': 'tag_section', + 'SELECT': 'tag_select', + 'TABLE': 'tag_table', + 'TEXTAREA': 'tag_textarea', + 'TIME': 'tag_time', + 'UL': 'tag_ul', + 'VIDEO': 'tag_video' }; /** @@ -98,21 +97,22 @@ * @type {Object} */ cvox.DomUtil.TAG_TO_INFORMATION_TABLE_BRIEF_MSG = { - 'AUDIO' : 'tag_audio', - 'BUTTON' : 'role_button', - 'SELECT' : 'tag_select', - 'TABLE' : 'tag_table', - 'TEXTAREA' : 'tag_textarea', - 'VIDEO' : 'tag_video' + 'AUDIO': 'tag_audio', + 'BUTTON': 'role_button', + 'SELECT': 'tag_select', + 'TABLE': 'tag_table', + 'TEXTAREA': 'tag_textarea', + 'VIDEO': 'tag_video' }; /** * These tags are treated as text formatters. * @type {Array<string>} */ -cvox.DomUtil.FORMATTING_TAGS = - ['B', 'BIG', 'CITE', 'CODE', 'DFN', 'EM', 'I', 'KBD', 'SAMP', 'SMALL', - 'SPAN', 'STRIKE', 'STRONG', 'SUB', 'SUP', 'U', 'VAR']; +cvox.DomUtil.FORMATTING_TAGS = [ + 'B', 'BIG', 'CITE', 'CODE', 'DFN', 'EM', 'I', 'KBD', 'SAMP', 'SMALL', 'SPAN', + 'STRIKE', 'STRONG', 'SUB', 'SUP', 'U', 'VAR' +]; /** * Determine if the given node is visible on the page. This does not check if @@ -150,7 +150,8 @@ var fname = 'isVisible-' + checkAncestors + '-' + checkDescendants; return /** @type {boolean} */ (cvox.Memoize.memoize( cvox.DomUtil.computeIsVisible_.bind( - this, node, checkAncestors, checkDescendants), fname, node)); + this, node, checkAncestors, checkDescendants), + fname, node)); }; /** @@ -176,8 +177,7 @@ } // Confirm that no subtree containing node is invisible. - if (checkAncestors && - cvox.DomUtil.hasInvisibleAncestor_(node)) { + if (checkAncestors && cvox.DomUtil.hasInvisibleAncestor_(node)) { return false; } @@ -233,8 +233,8 @@ if (!root.parentElement) { return false; } - var parentStyle = document.defaultView - .getComputedStyle(root.parentElement, null); + var parentStyle = + document.defaultView.getComputedStyle(root.parentElement, null); var isVisibleParent = !cvox.DomUtil.isInvisibleStyle(parentStyle); return isVisibleParent; } @@ -350,7 +350,7 @@ } // Now we know for sure it's an element. - var element = /** @type {Element} */(node); + var element = /** @type {Element} */ (node); if (!opt_allowHidden && !cvox.DomUtil.isVisible(element, {checkAncestors: false})) { return true; @@ -408,16 +408,15 @@ */ cvox.DomUtil.isDescendantOf = function(node, tagName, className) { while (node) { - - if (tagName && className && - (node.tagName && (node.tagName == tagName)) && + if (tagName && className && (node.tagName && (node.tagName == tagName)) && (node.className && (node.className == className))) { return true; - } else if (tagName && !className && - (node.tagName && (node.tagName == tagName))) { + } else if ( + tagName && !className && (node.tagName && (node.tagName == tagName))) { return true; - } else if (!tagName && className && - (node.className && (node.className == className))) { + } else if ( + !tagName && className && + (node.className && (node.className == className))) { return true; } node = node.parentNode; @@ -473,8 +472,8 @@ for (var labelNodeId, i = 0; labelNodeId = labelNodeIds[i]; i++) { var labelNode = document.getElementById(labelNodeId); if (labelNode) { - label += ' ' + cvox.DomUtil.getName( - labelNode, true, includeControls, true); + label += ' ' + + cvox.DomUtil.getName(labelNode, true, includeControls, true); } } } else if (node.hasAttribute('aria-label')) { @@ -587,8 +586,7 @@ cvox.DomUtil.hasChildrenBasedName_ = function(node, opt_allowHidden) { if (!!cvox.DomPredicates.linkPredicate([node]) || !!cvox.DomPredicates.headingPredicate([node]) || - node.tagName == 'BUTTON' || - cvox.AriaUtil.isControlWidget(node) || + node.tagName == 'BUTTON' || cvox.AriaUtil.isControlWidget(node) || !cvox.DomUtil.isLeafNode(node, opt_allowHidden)) { return true; } else { @@ -665,8 +663,7 @@ // Fall back to naming via title only if there is no text content. if (cvox.DomUtil.collapseWhitespace(node.textContent).length == 0 && - node.hasAttribute && - node.hasAttribute('title')) { + node.hasAttribute && node.hasAttribute('title')) { return node.getAttribute('title'); } @@ -709,10 +706,10 @@ } var isVisible = cvox.DomUtil.isVisible(child, {checkAncestors: false}); if (opt_allowHidden || (isVisible && !cvox.AriaUtil.isHidden(child))) { - delimiter = (prevChild.tagName == 'SPAN' || - child.tagName == 'SPAN' || + delimiter = (prevChild.tagName == 'SPAN' || child.tagName == 'SPAN' || child.parentNode.tagName == 'SPAN') ? - '' : ' '; + '' : + ' '; name += delimiter + cvox.DomUtil.getName(child, true, includeControls); } } @@ -741,19 +738,18 @@ } // Do nothing if we're not at the leftmost leaf. - if (firstListitem && - firstListitem.parentNode && - opt_index == 0 && - firstListitem.parentNode.tagName == 'OL' && - node == leftmost && + if (firstListitem && firstListitem.parentNode && opt_index == 0 && + firstListitem.parentNode.tagName == 'OL' && node == leftmost && document.defaultView.getComputedStyle(firstListitem.parentElement) - .listStyleType != 'none') { - var items = cvox.DomUtil.toArray(firstListitem.parentNode.children).filter( - function(li) { return li.tagName == 'LI'; }); + .listStyleType != 'none') { + var items = cvox.DomUtil.toArray(firstListitem.parentNode.children) + .filter(function(li) { + return li.tagName == 'LI'; + }); var position = items.indexOf(firstListitem) + 1; // TODO(dtseng): Support all list style types. - if (document.defaultView.getComputedStyle( - firstListitem.parentElement).listStyleType.indexOf('latin') != -1) { + if (document.defaultView.getComputedStyle(firstListitem.parentElement) + .listStyleType.indexOf('latin') != -1) { position--; prefix = String.fromCharCode('A'.charCodeAt(0) + position % 26); } else { @@ -780,9 +776,9 @@ // no title/label for that control. if (node.hasAttribute && ((node.hasAttribute('aria-label') && - (node.getAttribute('aria-label') == '')) || - (node.hasAttribute('aria-title') && - (node.getAttribute('aria-title') == '')))) { + (node.getAttribute('aria-label') == '')) || + (node.hasAttribute('aria-title') && + (node.getAttribute('aria-title') == '')))) { return ''; } @@ -794,15 +790,17 @@ // then try getting the content from the closest node. var prevNode = cvox.DomUtil.previousLeafNode(node); var prevTraversalCount = 0; - while (prevNode && (!cvox.DomUtil.hasContent(prevNode) || - cvox.DomUtil.isControl(prevNode))) { + while (prevNode && + (!cvox.DomUtil.hasContent(prevNode) || + cvox.DomUtil.isControl(prevNode))) { prevNode = cvox.DomUtil.previousLeafNode(prevNode); prevTraversalCount++; } var nextNode = cvox.DomUtil.directedNextLeafNode(node); var nextTraversalCount = 0; - while (nextNode && (!cvox.DomUtil.hasContent(nextNode) || - cvox.DomUtil.isControl(nextNode))) { + while (nextNode && + (!cvox.DomUtil.hasContent(nextNode) || + cvox.DomUtil.isControl(nextNode))) { nextNode = cvox.DomUtil.directedNextLeafNode(nextNode); nextTraversalCount++; } @@ -863,17 +861,17 @@ } if (node.constructor == HTMLSelectElement) { - node = /** @type {HTMLSelectElement} */(node); + node = /** @type {HTMLSelectElement} */ (node); var value = ''; var start = node.selectedOptions ? node.selectedOptions[0] : null; var end = node.selectedOptions ? - node.selectedOptions[node.selectedOptions.length - 1] : null; + node.selectedOptions[node.selectedOptions.length - 1] : + null; // TODO(dtseng): Keeping this stateless means we describe the start and end // of the selection only since we don't know which was added or // removed. Once we keep the previous selection, we can read the diff. if (start && end && start != end) { - value = Msgs.getMsg( - 'selected_options_value', [start.text, end.text]); + value = Msgs.getMsg('selected_options_value', [start.text, end.text]); } else if (start) { value = start.text + ''; } @@ -927,8 +925,8 @@ } else { var url = node.src; if (url.substring(0, 4) != 'data') { - var filename = url.substring( - url.lastIndexOf('/') + 1, url.lastIndexOf('.')); + var filename = + url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.')); // Hack to not speak the filename if it's ridiculously long. if (filename.length >= 1 && filename.length <= 16) { @@ -1086,8 +1084,7 @@ if (enclosingLabel.hasAttribute('for')) { var targetId = enclosingLabel.getAttribute('for'); var targetNode = document.getElementById(targetId); - if (targetNode && - cvox.DomUtil.isControl(targetNode) && + if (targetNode && cvox.DomUtil.isControl(targetNode) && !embeddedControl) { return false; } @@ -1146,8 +1143,7 @@ var labelledByTargets = cvox.DomUtil.getLabelledByTargets(); var enclosingNodeWithId = node; while (enclosingNodeWithId) { - if (enclosingNodeWithId.id && - labelledByTargets[enclosingNodeWithId.id]) { + if (enclosingNodeWithId.id && labelledByTargets[enclosingNodeWithId.id]) { // If we got here, some element on this page has an aria-labelledby // attribute listing this node as its id. As long as that "some" element // is not this element, we should return false, indicating this element @@ -1240,8 +1236,8 @@ previousNode, currentNode, opt_fallback) { var prevAncestors = cvox.DomUtil.getAncestors(previousNode); var currentAncestors = cvox.DomUtil.getAncestors(currentNode); - var divergence = cvox.DomUtil.compareAncestors(prevAncestors, - currentAncestors); + var divergence = + cvox.DomUtil.compareAncestors(prevAncestors, currentAncestors); var diff = currentAncestors.slice(divergence); return (diff.length == 0 && opt_fallback) ? currentAncestors : diff; }; @@ -1260,21 +1256,21 @@ if (!info) { if (targetNode.tagName == 'INPUT') { info = cvox.DomUtil.INPUT_TYPE_TO_INFORMATION_TABLE_MSG[targetNode.type]; - } else if (targetNode.tagName == 'A' && - cvox.DomUtil.isInternalLink(targetNode)) { + } else if ( + targetNode.tagName == 'A' && cvox.DomUtil.isInternalLink(targetNode)) { info = 'internal_link'; - } else if (targetNode.tagName == 'A' && - targetNode.getAttribute('href') && + } else if ( + targetNode.tagName == 'A' && targetNode.getAttribute('href') && cvox.ChromeVox.visitedUrls[targetNode.href]) { info = 'visited_link'; - } else if (targetNode.tagName == 'A' && - targetNode.getAttribute('name')) { - info = ''; // Don't want to add any role to anchors. + } else if (targetNode.tagName == 'A' && targetNode.getAttribute('name')) { + info = ''; // Don't want to add any role to anchors. } else if (targetNode.isContentEditable) { info = 'input_type_text'; } else if (cvox.DomUtil.isMath(targetNode)) { info = 'math_expr'; - } else if (targetNode.tagName == 'TABLE' && + } else if ( + targetNode.tagName == 'TABLE' && cvox.DomUtil.isLayoutTable(targetNode)) { info = ''; } else { @@ -1282,8 +1278,8 @@ info = cvox.DomUtil.TAG_TO_INFORMATION_TABLE_BRIEF_MSG[targetNode.tagName]; } else { - info = cvox.DomUtil.TAG_TO_INFORMATION_TABLE_VERBOSE_MSG[ - targetNode.tagName]; + info = cvox.DomUtil + .TAG_TO_INFORMATION_TABLE_VERBOSE_MSG[targetNode.tagName]; if (cvox.DomUtil.hasLongDesc(targetNode)) { info = 'image_with_long_desc'; @@ -1312,8 +1308,7 @@ */ cvox.DomUtil.getRole = function(targetNode, verbosity) { var roleMsg = cvox.DomUtil.getRoleMsg(targetNode, verbosity) || ''; - var role = roleMsg && roleMsg != ' ' ? - Msgs.getMsg(roleMsg) : ''; + var role = roleMsg && roleMsg != ' ' ? Msgs.getMsg(roleMsg) : ''; return role ? role : roleMsg; }; @@ -1326,12 +1321,10 @@ */ cvox.DomUtil.getListLength = function(targetNode) { var count = 0; - for (var node = targetNode.firstChild; - node; - node = node.nextSibling) { + for (var node = targetNode.firstChild; node; node = node.nextSibling) { if (cvox.DomUtil.isVisible(node) && (node.tagName == 'LI' || - (node.getAttribute && node.getAttribute('role') == 'listitem'))) { + (node.getAttribute && node.getAttribute('role') == 'listitem'))) { if (node.hasAttribute('aria-setsize')) { var ariaLength = parseInt(node.getAttribute('aria-setsize'), 10); if (!isNaN(ariaLength)) { @@ -1372,7 +1365,8 @@ 'checkbox-true': 'checkbox_checked_state', 'checkbox-false': 'checkbox_unchecked_state', 'radio-true': 'radio_selected_state', - 'radio-false': 'radio_unselected_state' }; + 'radio-false': 'radio_unselected_state' + }; var msgId = INPUT_MSGS[targetNode.type + '-' + !!targetNode.checked]; if (msgId) { info.push([msgId]); @@ -1380,19 +1374,23 @@ } } else if (targetNode.tagName == 'SELECT') { if (targetNode.selectedOptions && targetNode.selectedOptions.length <= 1) { - info.push(['list_position', - Msgs.getNumber(targetNode.selectedIndex + 1), - Msgs.getNumber(targetNode.options.length)]); + info.push([ + 'list_position', Msgs.getNumber(targetNode.selectedIndex + 1), + Msgs.getNumber(targetNode.options.length) + ]); } else { - info.push(['selected_options_state', - Msgs.getNumber(targetNode.selectedOptions.length)]); + info.push([ + 'selected_options_state', + Msgs.getNumber(targetNode.selectedOptions.length) + ]); } - } else if (targetNode.tagName == 'UL' || - targetNode.tagName == 'OL' || - role == 'list') { - info.push(['list_with_items_not_pluralized', - Msgs.getNumber( - cvox.DomUtil.getListLength(targetNode))]); + } else if ( + targetNode.tagName == 'UL' || targetNode.tagName == 'OL' || + role == 'list') { + info.push([ + 'list_with_items_not_pluralized', + Msgs.getNumber(cvox.DomUtil.getListLength(targetNode)) + ]); } if (cvox.DomUtil.isDisabled(targetNode)) { @@ -1450,8 +1448,7 @@ return true; } - if (targetNode.hasAttribute && - targetNode.hasAttribute('tabindex') && + if (targetNode.hasAttribute && targetNode.hasAttribute('tabindex') && targetNode.getAttribute('tabindex') == '-1') { return true; } @@ -1492,7 +1489,8 @@ */ cvox.DomUtil.countFocusableDescendants = function(targetNode) { return targetNode ? - cvox.DomUtil.countNodes(targetNode, cvox.DomUtil.isFocusable) : 0; + cvox.DomUtil.countNodes(targetNode, cvox.DomUtil.isFocusable) : + 0; }; @@ -1562,30 +1560,36 @@ // Send a mousedown (or simply a double click if requested). var evt = document.createEvent('MouseEvents'); var evtType = opt_double ? 'dblclick' : 'mousedown'; - evt.initMouseEvent(evtType, true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + evtType, true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); // Unless asked not to, Mark any events we generate so we don't try to // process our own events. evt.fromCvox = !opt_handleOwnEvents; try { targetNode.dispatchEvent(evt); - } catch (e) {} - //Send a mouse up + } catch (e) { + } + // Send a mouse up evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('mouseup', true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + 'mouseup', true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); evt.fromCvox = !opt_handleOwnEvents; try { targetNode.dispatchEvent(evt); - } catch (e) {} - //Send a click + } catch (e) { + } + // Send a click evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('click', true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + 'click', true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); evt.fromCvox = !opt_handleOwnEvents; try { targetNode.dispatchEvent(evt); - } catch (e) {} + } catch (e) { + } if (cvox.DomUtil.isInternalLink(targetNode)) { cvox.DomUtil.syncInternalLink(targetNode); @@ -1659,8 +1663,7 @@ * @return {boolean} True if the node is a control. */ cvox.DomUtil.isControl = function(node) { - if (cvox.AriaUtil.isControlWidget(node) && - cvox.DomUtil.isFocusable(node)) { + if (cvox.AriaUtil.isControlWidget(node) && cvox.DomUtil.isFocusable(node)) { return true; } if (node.tagName) { @@ -1691,8 +1694,9 @@ */ cvox.DomUtil.isLeafLevelControl = function(node) { if (cvox.DomUtil.isControl(node)) { - return !(cvox.AriaUtil.isCompositeControl(node) && - cvox.DomUtil.findFocusableDescendant(node)); + return !( + cvox.AriaUtil.isCompositeControl(node) && + cvox.DomUtil.findFocusableDescendant(node)); } return false; }; @@ -1710,7 +1714,7 @@ node.hasAttribute('role')) { surroundingControl = node.parentElement; while (surroundingControl && - !cvox.AriaUtil.isCompositeControl(surroundingControl)) { + !cvox.AriaUtil.isCompositeControl(surroundingControl)) { surroundingControl = surroundingControl.parentElement; } } @@ -1742,7 +1746,7 @@ } // since node is never above document.body, it always has a parent. // so node.parentNode will never be null. - node = /** @type {!Node} */(node.parentNode); + node = /** @type {!Node} */ (node.parentNode); if (node == document.body) { // we've readed the end of the document. return null; @@ -1750,13 +1754,13 @@ } if (cvox.DomUtil.directedNextSibling(node, r)) { // we just checked that next sibling is non-null. - node = /** @type {!Node} */(cvox.DomUtil.directedNextSibling(node, r)); + node = /** @type {!Node} */ (cvox.DomUtil.directedNextSibling(node, r)); } } // once we're at our next sibling, we want to descend down into it as // far as the child class will allow while (cvox.DomUtil.directedFirstChild(node, r) && !isLeaf(node)) { - node = /** @type {!Node} */(cvox.DomUtil.directedFirstChild(node, r)); + node = /** @type {!Node} */ (cvox.DomUtil.directedFirstChild(node, r)); } // after we've done all that, if we are still at document.body, this must @@ -1870,8 +1874,8 @@ if (!deep && pred(next)) { return next; } - var leaf = (deep ? - cvox.DomUtil.directedFindDeepestNode : + var leaf = + (deep ? cvox.DomUtil.directedFindDeepestNode : cvox.DomUtil.directedFindFirstNode)(next, r, pred); if (leaf) { return leaf; @@ -1881,7 +1885,7 @@ } next = cvox.DomUtil.directedNextSibling(next, r); } - var parent = /** @type {!Node} */(node.parentNode); + var parent = /** @type {!Node} */ (node.parentNode); if (above && pred(parent)) { return parent; } @@ -1900,9 +1904,8 @@ var parentControl = cvox.DomUtil.getSurroundingControl(control); if (parentControl) { return cvox.DomUtil.collapseWhitespace( - cvox.DomUtil.getValue(control) + ' ' + - cvox.DomUtil.getName(control) + ' ' + - cvox.DomUtil.getState(control, true)); + cvox.DomUtil.getValue(control) + ' ' + cvox.DomUtil.getName(control) + + ' ' + cvox.DomUtil.getState(control, true)); } else { return cvox.DomUtil.collapseWhitespace( cvox.DomUtil.getValue(control) + ' ' + @@ -1917,7 +1920,7 @@ * @return {boolean} True if the node is an internal link, false otherwise. */ cvox.DomUtil.isInternalLink = function(node) { - if (node.nodeType == 1) { // Element nodes only. + if (node.nodeType == 1) { // Element nodes only. var href = node.getAttribute('href'); if (href && href.indexOf('#') != -1) { var path = href.split('#')[0]; @@ -1944,8 +1947,7 @@ } else { return ''; } - } else if (cvox.AriaUtil.getRoleName(node) == - Msgs.getMsg('role_link')) { + } else if (cvox.AriaUtil.getRoleName(node) == Msgs.getMsg('role_link')) { return Msgs.getMsg('unknown_link'); } @@ -2004,8 +2006,9 @@ cvox.DomUtil.isLayoutTable = function(tableNode) { // TODO(stoarca): Why are we returning based on this inaccurate heuristic // instead of first trying the better heuristics below? - if (tableNode.rows && (tableNode.rows.length <= 1 || - (tableNode.rows[0].childElementCount == 1))) { + if (tableNode.rows && + (tableNode.rows.length <= 1 || + (tableNode.rows[0].childElementCount == 1))) { // This table has either 0 or one rows, or only "one" column. // This is a quick check for column count and may not be accurate. See // TraverseTable.getW3CColCount_ for a more accurate @@ -2065,7 +2068,7 @@ // this is probably a layout table. var points = 0; - if (! cvox.DomUtil.hasBorder(tableNode)) { + if (!cvox.DomUtil.hasBorder(tableNode)) { // This table has no border. points++; } @@ -2080,10 +2083,10 @@ points++; } - if (cvox.XpathUtil.evalXPath('tbody/tr/td/table', tableNode).length > 0) { - // This table has nested tables. - points++; - } + if (cvox.XpathUtil.evalXPath('tbody/tr/td/table', tableNode).length > 0) { + // This table has nested tables. + points++; + } return (points >= 3); }; @@ -2344,7 +2347,9 @@ */ cvox.DomUtil.createSimpleClickFunction = function(targetNode) { var target = targetNode.cloneNode(true); - return function() { cvox.DomUtil.clickElem(target, false, false); }; + return function() { + cvox.DomUtil.clickElem(target, false, false); + }; }; /** @@ -2356,7 +2361,7 @@ */ cvox.DomUtil.addNodeToHead = function(node, opt_id) { if (opt_id && document.getElementById(opt_id)) { - return; + return; } var p = document.head || document.body; p.appendChild(node); @@ -2398,10 +2403,8 @@ * @return {boolean} Whether or not a node is a math node. */ cvox.DomUtil.isMath = function(node) { - return cvox.DomUtil.isMathml(node) || - cvox.DomUtil.isMathJax(node) || - cvox.DomUtil.isMathImg(node) || - cvox.AriaUtil.isMath(node); + return cvox.DomUtil.isMathml(node) || cvox.DomUtil.isMathJax(node) || + cvox.DomUtil.isMathImg(node) || cvox.AriaUtil.isMath(node); }; @@ -2430,7 +2433,11 @@ cvox.DomUtil.altMathQuerySelector = function(contentType) { var classes = cvox.DomUtil.ALT_MATH_CLASSES[contentType]; if (classes) { - return classes.map(function(x) {return 'img.' + x;}).join(', '); + return classes + .map(function(x) { + return 'img.' + x; + }) + .join(', '); } return ''; }; @@ -2485,13 +2492,15 @@ } function isSpanWithClass(n, cl) { - return (n.tagName == 'SPAN' && - n.className.split(' ').some(function(x) { - return x.toLowerCase() == cl;})); + return (n.tagName == 'SPAN' && n.className.split(' ').some(function(x) { + return x.toLowerCase() == cl; + })); } if (isSpanWithClass(node, 'math')) { var ancestors = cvox.DomUtil.getAncestors(node); - return ancestors.some(function(x) {return isSpanWithClass(x, 'mathjax');}); + return ancestors.some(function(x) { + return isSpanWithClass(x, 'mathjax'); + }); } return false; }; @@ -2546,10 +2555,9 @@ * @return {!Array<Node|string|null>} The cleaned up list of nodes. */ cvox.DomUtil.purgeNodes = function(nodes) { - return cvox.DomUtil.toArray(nodes). - filter(function(node) { - return node.nodeType != Node.TEXT_NODE || - !node.textContent.match(/^\s+$/);}); + return cvox.DomUtil.toArray(nodes).filter(function(node) { + return node.nodeType != Node.TEXT_NODE || !node.textContent.match(/^\s+$/); + }); }; @@ -2566,10 +2574,7 @@ node = node.parentNode; } var r = node.getBoundingClientRect(); - return { - x: r.left + (r.width / 2), - y: r.top + (r.height / 2) - }; + return {x: r.left + (r.width / 2), y: r.top + (r.height / 2)}; }; @@ -2580,9 +2585,7 @@ * @return {boolean} True if HTML5 selection supported. */ cvox.DomUtil.doesInputSupportSelection = function(node) { - return goog.isDef(node) && - node.tagName == 'INPUT' && - node.type != 'email' && + return goog.isDef(node) && node.tagName == 'INPUT' && node.type != 'email' && node.type != 'number'; }; @@ -2600,8 +2603,7 @@ for (var describedById, i = 0; describedById = describedByIds[i]; i++) { var describedNode = document.getElementById(describedById); if (describedNode) { - desc += ' ' + cvox.DomUtil.getName( - describedNode, true, true, true); + desc += ' ' + cvox.DomUtil.getName(describedNode, true, true, true); } } }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/editable_text.js b/chrome/browser/resources/chromeos/chromevox/common/editable_text.js index 3e9a214d..a18a44cf 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/editable_text.js +++ b/chrome/browser/resources/chromeos/chromevox/common/editable_text.js
@@ -60,8 +60,8 @@ * @extends {cvox.ChromeVoxEditableTextBase} * @constructor */ -cvox.ChromeVoxEditableElement = function(node, value, start, end, isPassword, - tts) { +cvox.ChromeVoxEditableElement = function( + node, value, start, end, isPassword, tts) { goog.base(this, value, start, end, isPassword, tts); /** @@ -70,7 +70,8 @@ * @private */ this.brailleHandler_ = cvox.ChromeVox.braille ? - new cvox.BrailleTextHandler(cvox.ChromeVox.braille) : undefined; + new cvox.BrailleTextHandler(cvox.ChromeVox.braille) : + undefined; /** * The DOM node which allows text input. @@ -86,8 +87,7 @@ */ this.justSpokeDescription_ = false; }; -goog.inherits(cvox.ChromeVoxEditableElement, - cvox.ChromeVoxEditableTextBase); +goog.inherits(cvox.ChromeVoxEditableElement, cvox.ChromeVoxEditableTextBase); /** @override */ @@ -181,11 +181,11 @@ /** @override */ -cvox.ChromeVoxEditableElement.prototype.moveCursorToNextParagraph = - function() { +cvox.ChromeVoxEditableElement.prototype.moveCursorToNextParagraph = function() { var node = this.node; var length = node.value.length; - var index = node.selectionEnd >= length ? length : + var index = node.selectionEnd >= length ? + length : node.value.indexOf('\n', node.selectionEnd); if (index < 0) { index = length; @@ -200,7 +200,8 @@ cvox.ChromeVoxEditableElement.prototype.moveCursorToPreviousParagraph = function() { var node = this.node; - var index = node.selectionStart <= 0 ? 0 : + var index = node.selectionStart <= 0 ? + 0 : node.value.lastIndexOf('\n', node.selectionStart - 2) + 1; if (index < 0) { index = 0; @@ -229,8 +230,8 @@ var lineStart = this.getLineStart(lineIndex); var start = this.start - lineStart; var end = Math.min(this.end - lineStart, line.length); - this.brailleHandler_.changed(line, start, end, this.multiline, this.node, - lineStart); + this.brailleHandler_.changed( + line, start, end, this.multiline, this.node, lineStart); } }; @@ -248,16 +249,11 @@ cvox.ChromeVoxEditableHTMLInput = function(node, tts) { this.node = node; this.setup(); - goog.base(this, - node, - node.value, - node.selectionStart, - node.selectionEnd, - node.type === 'password', - tts); + goog.base( + this, node, node.value, node.selectionStart, node.selectionEnd, + node.type === 'password', tts); }; -goog.inherits(cvox.ChromeVoxEditableHTMLInput, - cvox.ChromeVoxEditableElement); +goog.inherits(cvox.ChromeVoxEditableHTMLInput, cvox.ChromeVoxEditableElement); /** @@ -296,10 +292,9 @@ */ cvox.ChromeVoxEditableHTMLInput.prototype.update = function(triggeredByUser) { var newValue = this.node.value; - var textChangeEvent = new cvox.TextChangeEvent(newValue, - this.node.selectionStart, - this.node.selectionEnd, - triggeredByUser); + var textChangeEvent = new cvox.TextChangeEvent( + newValue, this.node.selectionStart, this.node.selectionEnd, + triggeredByUser); this.changed(textChangeEvent); }; @@ -316,7 +311,8 @@ * @constructor */ cvox.ChromeVoxEditableTextArea = function(node, tts) { - goog.base(this, node, node.value, node.selectionStart, node.selectionEnd, + goog.base( + this, node, node.value, node.selectionStart, node.selectionEnd, false /* isPassword */, tts); this.multiline = true; @@ -327,8 +323,7 @@ */ this.shadowIsCurrent_ = false; }; -goog.inherits(cvox.ChromeVoxEditableTextArea, - cvox.ChromeVoxEditableElement); +goog.inherits(cvox.ChromeVoxEditableTextArea, cvox.ChromeVoxEditableElement); /** @@ -350,8 +345,9 @@ if (this.node.value != this.value) { this.shadowIsCurrent_ = false; } - var textChangeEvent = new cvox.TextChangeEvent(this.node.value, - this.node.selectionStart, this.node.selectionEnd, triggeredByUser); + var textChangeEvent = new cvox.TextChangeEvent( + this.node.value, this.node.selectionStart, this.node.selectionEnd, + triggeredByUser); this.changed(textChangeEvent); }; @@ -416,8 +412,10 @@ var lineStart = shadow.getLineStart(lineIndex); var offset = node.selectionEnd - lineStart; var lastLine = (length == 0) ? 0 : shadow.getLineIndex(length - 1); - var newCursorPosition = (lineIndex >= lastLine) ? length : - Math.min(shadow.getLineStart(lineIndex + 1) + offset, + var newCursorPosition = (lineIndex >= lastLine) ? + length : + Math.min( + shadow.getLineStart(lineIndex + 1) + offset, shadow.getLineEnd(lineIndex + 1)); node.selectionStart = node.selectionEnd = newCursorPosition; cvox.ChromeVoxEventWatcher.handleTextChanged(true); @@ -435,8 +433,10 @@ var lineIndex = shadow.getLineIndex(node.selectionStart); var lineStart = shadow.getLineStart(lineIndex); var offset = node.selectionStart - lineStart; - var newCursorPosition = (lineIndex <= 0) ? 0 : - Math.min(shadow.getLineStart(lineIndex - 1) + offset, + var newCursorPosition = (lineIndex <= 0) ? + 0 : + Math.min( + shadow.getLineStart(lineIndex - 1) + offset, shadow.getLineEnd(lineIndex - 1)); node.selectionStart = node.selectionEnd = newCursorPosition; cvox.ChromeVoxEventWatcher.handleTextChanged(true); @@ -476,8 +476,8 @@ this.end = extractor.getEndIndex(); this.multiline = true; }; -goog.inherits(cvox.ChromeVoxEditableContentEditable, - cvox.ChromeVoxEditableElement); +goog.inherits( + cvox.ChromeVoxEditableContentEditable, cvox.ChromeVoxEditableElement); /** * A helper used to compute the line numbers. A single object is @@ -494,14 +494,12 @@ * * @param {boolean} triggeredByUser True if this was triggered by a user action. */ -cvox.ChromeVoxEditableContentEditable.prototype.update = - function(triggeredByUser) { +cvox.ChromeVoxEditableContentEditable.prototype.update = function( + triggeredByUser) { this.extractorIsCurrent_ = false; var textChangeEvent = new cvox.TextChangeEvent( - this.getExtractor().getText(), - this.getExtractor().getStartIndex(), - this.getExtractor().getEndIndex(), - triggeredByUser); + this.getExtractor().getText(), this.getExtractor().getStartIndex(), + this.getExtractor().getEndIndex(), triggeredByUser); this.changed(textChangeEvent); }; @@ -555,8 +553,7 @@ /** @override */ -cvox.ChromeVoxEditableContentEditable.prototype.changed = - function(evt) { +cvox.ChromeVoxEditableContentEditable.prototype.changed = function(evt) { if (!evt.triggeredByUser) { return; } @@ -564,9 +561,9 @@ if (!this.shouldDescribeChange(evt)) { this.speak(Msgs.getMsg('text_box_blank'), true); if (this.brailleHandler_) { - this.brailleHandler_.changed('' /*line*/, 0 /*start*/, 0 /*end*/, - true /*multiline*/, null /*element*/, - evt.start /*lineStart*/); + this.brailleHandler_.changed( + '' /*line*/, 0 /*start*/, 0 /*end*/, true /*multiline*/, + null /*element*/, evt.start /*lineStart*/); } } else { goog.base(this, 'changed', evt); @@ -612,8 +609,8 @@ /** * @override */ -cvox.ChromeVoxEditableContentEditable.prototype.shouldDescribeChange = - function(evt) { +cvox.ChromeVoxEditableContentEditable.prototype.shouldDescribeChange = function( + evt) { var sel = window.getSelection(); var cursor = new cvox.Cursor(sel.baseNode, sel.baseOffset, ''); @@ -630,10 +627,8 @@ // The new lines after Title are not traversed to by TraverseUtil. A root fix // would make changes there. However, considering the fickle nature of that // code, we specifically detect for new lines here. - if (Math.abs(this.start - evt.start) != 1 && - this.start == this.end && - evt.start == evt.end && - sel.baseNode == sel.extentNode && + if (Math.abs(this.start - evt.start) != 1 && this.start == this.end && + evt.start == evt.end && sel.baseNode == sel.extentNode && sel.baseOffset == sel.extentOffset && sel.baseNode.nodeType == Node.ELEMENT_NODE && sel.baseNode.querySelector('BR') &&
diff --git a/chrome/browser/resources/chromeos/chromevox/common/editable_text_base.js b/chrome/browser/resources/chromeos/chromevox/common/editable_text_base.js index e240f529..d4e79a7 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/editable_text_base.js +++ b/chrome/browser/resources/chromeos/chromevox/common/editable_text_base.js
@@ -275,8 +275,7 @@ * should trigger description. */ cvox.ChromeVoxEditableTextBase.prototype.shouldDescribeChange = function(evt) { - if (evt.value == this.value && - evt.start == this.start && + if (evt.value == this.value && evt.start == this.start && evt.end == this.end) { return false; } @@ -291,8 +290,8 @@ * user action. * @param {Object=} opt_personality Personality used to speak text. */ -cvox.ChromeVoxEditableTextBase.prototype.speak = - function(str, opt_triggeredByUser, opt_personality) { +cvox.ChromeVoxEditableTextBase.prototype.speak = function( + str, opt_triggeredByUser, opt_personality) { if (!str) { return; } @@ -336,15 +335,18 @@ * stays the same. * @param {cvox.TextChangeEvent} evt The text change event. */ -cvox.ChromeVoxEditableTextBase.prototype.describeSelectionChanged = - function(evt) { +cvox.ChromeVoxEditableTextBase.prototype.describeSelectionChanged = function( + evt) { // TODO(deboer): Factor this into two function: // - one to determine the selection event // - one to speak if (this.isPassword) { - this.speak((new goog.i18n.MessageFormat(Msgs.getMsg('bullet')) - .format({'COUNT': 1})), evt.triggeredByUser); + this.speak( + (new goog.i18n.MessageFormat(Msgs.getMsg('bullet')).format({ + 'COUNT': 1 + })), + evt.triggeredByUser); return; } if (evt.start == evt.end) { @@ -352,8 +354,7 @@ if (this.start != this.end) { // It was previously a selection, so just announce 'unselected'. this.speak(Msgs.getMsg('Unselected'), evt.triggeredByUser); - } else if (this.getLineIndex(this.start) != - this.getLineIndex(evt.start)) { + } else if (this.getLineIndex(this.start) != this.getLineIndex(evt.start)) { // Moved to a different line; read it. var lineValue = this.getLine(this.getLineIndex(evt.start)); if (lineValue == '') { @@ -364,67 +365,70 @@ lineValue = Msgs.getMsg('text_box_whitespace'); } this.speak(lineValue, evt.triggeredByUser); - } else if (this.start == evt.start + 1 || - this.start == evt.start - 1) { + } else if (this.start == evt.start + 1 || this.start == evt.start - 1) { // Moved by one character; read it. if (!cvox.ChromeVoxEditableTextBase.useIBeamCursor) { if (evt.start == this.value.length) { if (cvox.ChromeVox.verbosity == cvox.VERBOSITY_VERBOSE) { - this.speak(Msgs.getMsg('end_of_text_verbose'), - evt.triggeredByUser); + this.speak(Msgs.getMsg('end_of_text_verbose'), evt.triggeredByUser); } else { - this.speak(Msgs.getMsg('end_of_text_brief'), - evt.triggeredByUser); + this.speak(Msgs.getMsg('end_of_text_brief'), evt.triggeredByUser); } } else { - this.speak(this.value.substr(evt.start, 1), - evt.triggeredByUser, - {'phoneticCharacters': evt.triggeredByUser}); + this.speak( + this.value.substr(evt.start, 1), evt.triggeredByUser, + {'phoneticCharacters': evt.triggeredByUser}); } } else { - this.speak(this.value.substr(Math.min(this.start, evt.start), 1), - evt.triggeredByUser, - {'phoneticCharacters': evt.triggeredByUser}); + this.speak( + this.value.substr(Math.min(this.start, evt.start), 1), + evt.triggeredByUser, {'phoneticCharacters': evt.triggeredByUser}); } } else { // Moved by more than one character. Read all characters crossed. - this.speak(this.value.substr(Math.min(this.start, evt.start), - Math.abs(this.start - evt.start)), evt.triggeredByUser); + this.speak( + this.value.substr( + Math.min(this.start, evt.start), + Math.abs(this.start - evt.start)), + evt.triggeredByUser); } } else { // It's currently a selection. - if (this.start + 1 == evt.start && - this.end == this.value.length && + if (this.start + 1 == evt.start && this.end == this.value.length && evt.end == this.value.length) { // Autocomplete: the user typed one character of autocompleted text. this.speak(this.value.substr(this.start, 1), evt.triggeredByUser); this.speak(this.value.substr(evt.start)); } else if (this.start == this.end) { // It was previously a cursor. - this.speak(this.value.substr(evt.start, evt.end - evt.start), - evt.triggeredByUser); + this.speak( + this.value.substr(evt.start, evt.end - evt.start), + evt.triggeredByUser); this.speak(Msgs.getMsg('selected')); } else if (this.start == evt.start && this.end < evt.end) { - this.speak(this.value.substr(this.end, evt.end - this.end), - evt.triggeredByUser); + this.speak( + this.value.substr(this.end, evt.end - this.end), evt.triggeredByUser); this.speak(Msgs.getMsg('added_to_selection')); } else if (this.start == evt.start && this.end > evt.end) { - this.speak(this.value.substr(evt.end, this.end - evt.end), - evt.triggeredByUser); + this.speak( + this.value.substr(evt.end, this.end - evt.end), evt.triggeredByUser); this.speak(Msgs.getMsg('removed_from_selection')); } else if (this.end == evt.end && this.start > evt.start) { - this.speak(this.value.substr(evt.start, this.start - evt.start), - evt.triggeredByUser); + this.speak( + this.value.substr(evt.start, this.start - evt.start), + evt.triggeredByUser); this.speak(Msgs.getMsg('added_to_selection')); } else if (this.end == evt.end && this.start < evt.start) { - this.speak(this.value.substr(this.start, evt.start - this.start), - evt.triggeredByUser); + this.speak( + this.value.substr(this.start, evt.start - this.start), + evt.triggeredByUser); this.speak(Msgs.getMsg('removed_from_selection')); } else { // The selection changed but it wasn't an obvious extension of // a previous selection. Just read the new selection. - this.speak(this.value.substr(evt.start, evt.end - evt.start), - evt.triggeredByUser); + this.speak( + this.value.substr(evt.start, evt.end - evt.start), + evt.triggeredByUser); this.speak(Msgs.getMsg('selected')); } } @@ -441,8 +445,11 @@ personality = cvox.AbstractTts.PERSONALITY_DELETED; } if (this.isPassword) { - this.speak((new goog.i18n.MessageFormat(Msgs.getMsg('bullet')) - .format({'COUNT': 1})), evt.triggeredByUser, personality); + this.speak( + (new goog.i18n.MessageFormat(Msgs.getMsg('bullet')).format({ + 'COUNT': 1 + })), + evt.triggeredByUser, personality); return; } @@ -478,9 +485,8 @@ // breakers). // TODO(dtseng): Think about a more reliable way to do this. if (!(cvox.ChromeVoxEditableContentEditable && - this instanceof cvox.ChromeVoxEditableContentEditable) || - newLen < len || - this.isWordBreakChar(evt.value[newLen - 1] || '')) { + this instanceof cvox.ChromeVoxEditableContentEditable) || + newLen < len || this.isWordBreakChar(evt.value[newLen - 1] || '')) { this.describeTextChangedHelper( evt, prefixLen, suffixLen, autocompleteSuffix, personality); } @@ -493,16 +499,13 @@ // a word or line. prefixLen = evt.start; suffixLen = newLen - evtEnd; - if (this.start == this.end && - evt.start == evtEnd && + if (this.start == this.end && evt.start == evtEnd && evtValue.substr(0, prefixLen) == value.substr(0, prefixLen) && - evtValue.substr(newLen - suffixLen) == - value.substr(len - suffixLen)) { + evtValue.substr(newLen - suffixLen) == value.substr(len - suffixLen)) { // Forward deletions causes reading of the character immediately to the // right of the caret or the deleted text depending on the iBeam cursor // setting. - if (this.start == evt.start && - this.end == evt.end && + if (this.start == evt.start && this.end == evt.end && !cvox.ChromeVoxEditableTextBase.useIBeamCursor) { this.speak(evt.value[evt.start], evt.triggeredByUser); } else { @@ -525,8 +528,8 @@ // The user added text either to the beginning or the end. if (evtValue.length > value.length) { if (evtValue.startsWith(value)) { - this.speak(evtValue[evtValue.length - 1], evt.triggeredByUser, - personality); + this.speak( + evtValue[evtValue.length - 1], evt.triggeredByUser, personality); return; } else if (evtValue.indexOf(value) == 1) { this.speak(evtValue[0], evt.triggeredByUser, personality); @@ -548,8 +551,7 @@ if (this.multiline) { // Fall back to announce deleted but omit the text that was deleted. if (evt.value.length < this.value.length) { - this.speak(Msgs.getMsg('text_deleted'), - evt.triggeredByUser, personality); + this.speak(Msgs.getMsg('text_deleted'), evt.triggeredByUser, personality); } // The below is a somewhat loose way to deal with non-standard // insertions/deletions. Intentionally skip for multiline since deletion @@ -570,8 +572,7 @@ // Otherwise, look for the common prefix and suffix, but back up so // that we can speak complete words, to be minimally confusing. prefixLen = 0; - while (prefixLen < len && - prefixLen < newLen && + while (prefixLen < len && prefixLen < newLen && value[prefixLen] == evtValue[prefixLen]) { prefixLen++; } @@ -580,8 +581,7 @@ } suffixLen = 0; - while (suffixLen < (len - prefixLen) && - suffixLen < (newLen - prefixLen) && + while (suffixLen < (len - prefixLen) && suffixLen < (newLen - prefixLen) && value[len - suffixLen - 1] == evtValue[newLen - suffixLen - 1]) { suffixLen++; } @@ -622,9 +622,8 @@ utterance = inserted; } else if (insertedLen == 1) { if ((cvox.ChromeVox.typingEcho == cvox.TypingEcho.WORD || - cvox.ChromeVox.typingEcho == cvox.TypingEcho.CHARACTER_AND_WORD) && - this.isWordBreakChar(inserted) && - prefixLen > 0 && + cvox.ChromeVox.typingEcho == cvox.TypingEcho.CHARACTER_AND_WORD) && + this.isWordBreakChar(inserted) && prefixLen > 0 && !this.isWordBreakChar(evt.value.substr(prefixLen - 1, 1))) { // Speak previous word. var index = prefixLen; @@ -635,14 +634,15 @@ utterance = evt.value.substr(index, prefixLen + 1 - index); } else { utterance = inserted; - triggeredByUser = false; // Implies QUEUE_MODE_QUEUE. + triggeredByUser = false; // Implies QUEUE_MODE_QUEUE. } - } else if (cvox.ChromeVox.typingEcho == cvox.TypingEcho.CHARACTER || + } else if ( + cvox.ChromeVox.typingEcho == cvox.TypingEcho.CHARACTER || cvox.ChromeVox.typingEcho == cvox.TypingEcho.CHARACTER_AND_WORD) { // This particular case is handled in event watcher. See the key press // handler for more details. - utterance = cvox.ChromeVoxEditableTextBase.eventTypingEcho ? '' : - inserted; + utterance = + cvox.ChromeVoxEditableTextBase.eventTypingEcho ? '' : inserted; } } else if (deletedLen > 1 && !autocompleteSuffix) { utterance = deleted + ', deleted'; @@ -667,7 +667,9 @@ * @return {boolean} True if the action was handled. */ cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextCharacter = - function() { return false; }; + function() { + return false; +}; /** @@ -675,39 +677,45 @@ * @return {boolean} True if the action was handled. */ cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousCharacter = - function() { return false; }; + function() { + return false; +}; /** * Moves the cursor forward by one word. * @return {boolean} True if the action was handled. */ -cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextWord = - function() { return false; }; +cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextWord = function() { + return false; +}; /** * Moves the cursor backward by one word. * @return {boolean} True if the action was handled. */ -cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousWord = - function() { return false; }; +cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousWord = function() { + return false; +}; /** * Moves the cursor forward by one line. * @return {boolean} True if the action was handled. */ -cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextLine = - function() { return false; }; +cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextLine = function() { + return false; +}; /** * Moves the cursor backward by one line. * @return {boolean} True if the action was handled. */ -cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousLine = - function() { return false; }; +cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousLine = function() { + return false; +}; /** @@ -715,7 +723,9 @@ * @return {boolean} True if the action was handled. */ cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextParagraph = - function() { return false; }; + function() { + return false; +}; /** @@ -723,7 +733,9 @@ * @return {boolean} True if the action was handled. */ cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousParagraph = - function() { return false; }; + function() { + return false; +}; /******************************************/
diff --git a/chrome/browser/resources/chromeos/chromevox/common/find_util.js b/chrome/browser/resources/chromeos/chromevox/common/find_util.js index a5ac8a6..4599c027 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/find_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/find_util.js
@@ -34,8 +34,8 @@ */ cvox.FindUtil.findNext = function(sel, predicate, opt_initialNode) { var r = sel.isReversed(); - var cur = new cvox.CursorSelection(sel.absStart(), sel.absStart()) - .setReversed(r); + var cur = + new cvox.CursorSelection(sel.absStart(), sel.absStart()).setReversed(r); // We may have been sync'ed into a subtree of the current predicate match. // Find our ancestor that matches the predicate.
diff --git a/chrome/browser/resources/chromeos/chromevox/common/focus_util.js b/chrome/browser/resources/chromeos/chromevox/common/focus_util.js index 4c00595a..f543834 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/focus_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/focus_util.js
@@ -15,8 +15,7 @@ * Utilities for managing focus. * @constructor */ -cvox.FocusUtil = function() { -}; +cvox.FocusUtil = function() {}; /** * Maps whether an input element of specified type accepts text selection or @@ -31,29 +30,29 @@ * @type {Object} */ cvox.FocusUtil.INPUT_TYPE_ACCEPTS_SELECTION_TABLE = { - 'hidden' : false, - 'text' : true, - 'search' : true, - 'tel' : true, - 'url' : true, - 'email' : true, - 'password' : true, - 'datetime' : false, - 'date' : false, - 'month' : false, - 'week' : false, - 'time' : false, - 'datetime-local' : false, - 'number' : false, - 'range' : false, - 'color' : false, - 'checkbox' : false, - 'radio' : false, - 'file' : false, - 'submit' : false, - 'image' : false, - 'reset' : false, - 'button' : false + 'hidden': false, + 'text': true, + 'search': true, + 'tel': true, + 'url': true, + 'email': true, + 'password': true, + 'datetime': false, + 'date': false, + 'month': false, + 'week': false, + 'time': false, + 'datetime-local': false, + 'number': false, + 'range': false, + 'color': false, + 'checkbox': false, + 'radio': false, + 'file': false, + 'submit': false, + 'image': false, + 'reset': false, + 'button': false }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/common/focuser.js b/chrome/browser/resources/chromeos/chromevox/common/focuser.js index f0a29d87..dede442 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/focuser.js +++ b/chrome/browser/resources/chromeos/chromevox/common/focuser.js
@@ -73,15 +73,14 @@ targetNode.focus(); cvox.ChromeVoxEventSuspender.exitSuspendEvents(); }, 0); - } - else { + } else { window.setTimeout(function() { - targetNode.focus(); + targetNode.focus(); }, 0); } } - } else if (document.activeElement && - document.activeElement.tagName != 'BODY') { + } else if ( + document.activeElement && document.activeElement.tagName != 'BODY') { document.activeElement.blur(); } @@ -103,7 +102,7 @@ * @param {Node} targetNode The node that is being focused. * @return {boolean} True if enterSuspendEvents should be called. */ -cvox.Focuser.shouldEnterSuspendEvents_ = function(targetNode){ +cvox.Focuser.shouldEnterSuspendEvents_ = function(targetNode) { if (targetNode.constructor && targetNode.constructor == HTMLVideoElement) { return false; }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/group_util.js b/chrome/browser/resources/chromeos/chromevox/common/group_util.js index d2a8ff1..d487cfc 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/group_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/group_util.js
@@ -60,10 +60,10 @@ 'tr,' + 'ul,' + 'math,' + - // This takes care of MathJax expressions. + // This takes care of MathJax expressions. 'span.math,' + -// TODO (sorge) Do we want to group all math or only display math? -// '[mode="display"],' + + // TODO (sorge) Do we want to group all math or only display math? + // '[mode="display"],' + // Aria widget roles '[role~="alert ' + 'alertdialog ' + @@ -119,8 +119,8 @@ } if (!cvox.DomUtil.isSemanticElt(node)) { - var breakingNodes = node.querySelectorAll( - cvox.GroupUtil.BREAKOUT_SELECTOR_); + var breakingNodes = + node.querySelectorAll(cvox.GroupUtil.BREAKOUT_SELECTOR_); for (var i = 0; i < breakingNodes.length; ++i) { if (cvox.DomUtil.hasContent(breakingNodes[i])) { @@ -135,8 +135,7 @@ } var content = cvox.DomUtil.collapseWhitespace( - cvox.DomUtil.getValue(node) + ' ' + - cvox.DomUtil.getName(node)); + cvox.DomUtil.getValue(node) + ' ' + cvox.DomUtil.getName(node)); if (content.length > cvox.GroupUtil.MAX_CHARCOUNT_) { return false; }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/interframe.js b/chrome/browser/resources/chromeos/chromevox/common/interframe.js index 319ce7d..bae17e9 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/interframe.js +++ b/chrome/browser/resources/chromeos/chromevox/common/interframe.js
@@ -22,8 +22,7 @@ /** * @constructor */ -cvox.Interframe = function() { -}; +cvox.Interframe = function() {}; /** * The prefix of all interframe messages. @@ -86,8 +85,7 @@ if (typeof event.data === 'string' && event.data.startsWith(cvox.Interframe.IF_MSG_PREFIX)) { var suffix = event.data.substr(cvox.Interframe.IF_MSG_PREFIX.length); - var message = /** @type {Object} */ ( - cvox.ChromeVoxJSON.parse(suffix)); + var message = /** @type {Object} */ (cvox.ChromeVoxJSON.parse(suffix)); if (message['command'] == cvox.Interframe.SET_ID) { cvox.Interframe.id = message['id']; message['command'] = cvox.Interframe.ACK_SET_ID; @@ -160,8 +158,7 @@ if (iframe.hasAttribute('id') && document.getElementById(iframe.id) == iframe) { // Ideally, try to send it based on the iframe's existing id. - script.innerHTML = - 'document.getElementById(decodeURI(\'' + + script.innerHTML = 'document.getElementById(decodeURI(\'' + encodeURI(iframe.id) + '\')).contentWindow.postMessage(decodeURI(\'' + encodeURI(encodedMessage) + '\'), \'*\');'; } else { @@ -173,8 +170,7 @@ iframe.className += ' ' + styleName; } - script.innerHTML = - 'document.getElementsByClassName(decodeURI(\'' + + script.innerHTML = 'document.getElementsByClassName(decodeURI(\'' + encodeURI(styleName) + '\'))[0].contentWindow.postMessage(decodeURI(\'' + encodeURI(encodedMessage) + '\'), \'*\');'; @@ -208,8 +204,7 @@ // the page context. var encodedMessage = cvox.Interframe.IF_MSG_PREFIX + cvox.ChromeVoxJSON.stringify(message, null, null); - window.location.href = - 'javascript:window.parent.postMessage(\'' + + window.location.href = 'javascript:window.parent.postMessage(\'' + encodeURI(encodedMessage) + '\', \'*\');'; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/key_sequence.js b/chrome/browser/resources/chromeos/chromevox/common/key_sequence.js index e4f1a82..a96c7a71 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/key_sequence.js +++ b/chrome/browser/resources/chromeos/chromevox/common/key_sequence.js
@@ -44,8 +44,9 @@ * @param {boolean=} opt_requireStickyMode Whether to require sticky mode. * @constructor */ -cvox.KeySequence = function(originalEvent, opt_cvoxModifier, opt_doubleTap, - opt_skipStripping, opt_requireStickyMode) { +cvox.KeySequence = function( + originalEvent, opt_cvoxModifier, opt_doubleTap, opt_skipStripping, + opt_requireStickyMode) { /** @type {boolean} */ this.doubleTap = !!opt_doubleTap; @@ -174,8 +175,8 @@ // If one key sequence requires sticky mode, return early the strict // sticky mode state. if (this.requireStickyMode || rhs.requireStickyMode) { - return (this.stickyMode || rhs.stickyMode) && - !this.cvoxModifier && !rhs.cvoxModifier; + return (this.stickyMode || rhs.stickyMode) && !this.cvoxModifier && + !rhs.cvoxModifier; } // If they both have the ChromeVox modifier, or they both don't have the @@ -355,25 +356,25 @@ // If the combo string becomes empty, then the user has activated the combo. if (this.isKeyModifierActive(keyEvent, 'ctrlKey')) { modifierKeyCombo = modifierKeyCombo.filter(function(modifier) { - return modifier != 'Ctrl'; - }); + return modifier != 'Ctrl'; + }); } if (this.isKeyModifierActive(keyEvent, 'altKey')) { modifierKeyCombo = modifierKeyCombo.filter(function(modifier) { - return modifier != 'Alt'; - }); + return modifier != 'Alt'; + }); } if (this.isKeyModifierActive(keyEvent, 'shiftKey')) { modifierKeyCombo = modifierKeyCombo.filter(function(modifier) { - return modifier != 'Shift'; - }); + return modifier != 'Shift'; + }); } if (this.isKeyModifierActive(keyEvent, 'metaKey') || this.isKeyModifierActive(keyEvent, 'searchKeyHeld')) { var metaKeyName = this.getMetaKeyName_(); modifierKeyCombo = modifierKeyCombo.filter(function(modifier) { - return modifier != metaKeyName; - }); + return modifier != metaKeyName; + }); } return (modifierKeyCombo.length == 0); }; @@ -405,7 +406,8 @@ return (keyEvent.metaKey || (keyEvent.keyCode == 91)); break; case 'searchKeyHeld': - return ((cvox.ChromeVox.isChromeOS && keyEvent.keyCode == 91) || + return ( + (cvox.ChromeVox.isChromeOS && keyEvent.keyCode == 91) || keyEvent['searchKeyHeld']); break; } @@ -437,9 +439,11 @@ var firstSequenceEvent = {}; firstSequenceEvent['stickyMode'] = (sequenceObject.stickyMode == undefined) ? - false : sequenceObject.stickyMode; + false : + sequenceObject.stickyMode; firstSequenceEvent['prefixKey'] = (sequenceObject.prefixKey == undefined) ? - false : sequenceObject.prefixKey; + false : + sequenceObject.prefixKey; var secondKeyPressed = sequenceObject.keys.keyCode.length > 1; var secondSequenceEvent = {}; @@ -451,12 +455,11 @@ } } var skipStripping = sequenceObject.skipStripping !== undefined ? - sequenceObject.skipStripping : true; - var keySeq = new cvox.KeySequence(firstSequenceEvent, - sequenceObject.cvoxModifier, - sequenceObject.doubleTap, - skipStripping, - sequenceObject.requireStickyMode); + sequenceObject.skipStripping : + true; + var keySeq = new cvox.KeySequence( + firstSequenceEvent, sequenceObject.cvoxModifier, sequenceObject.doubleTap, + skipStripping, sequenceObject.requireStickyMode); if (secondKeyPressed) { cvox.ChromeVox.sequenceSwitchKeyCodes.push( new cvox.KeySequence(firstSequenceEvent, sequenceObject.cvoxModifier));
diff --git a/chrome/browser/resources/chromeos/chromevox/common/key_util.js b/chrome/browser/resources/chromeos/chromevox/common/key_util.js index 1f64d1c..067af93 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/key_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/key_util.js
@@ -27,8 +27,7 @@ * Create the namespace * @constructor */ -cvox.KeyUtil = function() { -}; +cvox.KeyUtil = function() {}; /** * The time in ms at which the ChromeVox Sticky Mode key was pressed. @@ -81,8 +80,8 @@ } // Either we are in the middle of a key sequence (N > H), or the key prefix // was pressed before (Ctrl+Z), or sticky mode is enabled - var keyIsPrefixed = util.sequencing || keyEvent['keyPrefix'] || - keyEvent['stickyMode']; + var keyIsPrefixed = + util.sequencing || keyEvent['keyPrefix'] || keyEvent['stickyMode']; // Create key sequence. var keySequence = new cvox.KeySequence(keyEvent); @@ -114,8 +113,7 @@ // Repeated keys pressed. var currTime = new Date().getTime(); - if (cvox.KeyUtil.isDoubleTapKey(keySequence) && - util.prevKeySequence && + if (cvox.KeyUtil.isDoubleTapKey(keySequence) && util.prevKeySequence && keySequence.equals(util.prevKeySequence)) { var prevTime = util.modeKeyPressTime; var delta = currTime - prevTime; @@ -193,15 +191,15 @@ */ cvox.KeyUtil.modStringToKeyCode = function(keyString) { switch (keyString) { - case 'Ctrl': - return 17; - case 'Alt': - return 18; - case 'Shift': - return 16; - case 'Cmd': - case 'Win': - return 91; + case 'Ctrl': + return 17; + case 'Alt': + return 18; + case 'Shift': + return 16; + case 'Cmd': + case 'Win': + return 91; } return -1; }; @@ -270,7 +268,7 @@ } else if (keyCode == 32) { return 'Space'; } else if (keyCode == 35) { - return'end'; + return 'end'; } else if (keyCode == 36) { return 'home'; } else if (keyCode == 37) { @@ -348,9 +346,9 @@ */ cvox.KeyUtil.getStickyKeyCode = function() { // TODO (rshearer): This should not be hard-coded here. - var stickyKeyCode = 45; // Insert for Linux and Windows + var stickyKeyCode = 45; // Insert for Linux and Windows if (cvox.ChromeVox.isChromeOS || cvox.ChromeVox.isMac) { - stickyKeyCode = 91; // GUI key (Search/Cmd) for ChromeOs and Mac + stickyKeyCode = 91; // GUI key (Search/Cmd) for ChromeOs and Mac } return stickyKeyCode; }; @@ -424,42 +422,42 @@ var modifier = ''; switch (keyPressed) { case 'ctrlKey': - // TODO(rshearer): This is a hack to work around the special casing - // of the Ctrl key that used to happen in keyEventToString. We won't - // need it once we move away from strings completely. - modifier = 'Ctrl'; - break; - case 'searchKeyHeld': - var searchKey = cvox.KeyUtil.getReadableNameForKeyCode(91); - modifier = searchKey; - break; - case 'altKey': - modifier = 'Alt'; - break; - case 'altGraphKey': - modifier = 'AltGraph'; - break; - case 'shiftKey': - modifier = 'Shift'; - break; - case 'metaKey': - var metaKey = cvox.KeyUtil.getReadableNameForKeyCode(91); - modifier = metaKey; - break; - case 'keyCode': - var keyCode = keySequence.keys[keyPressed][index]; - // We make sure the keyCode isn't for a modifier key. If it is, then - // we've already added that into the string above. - if (!keySequence.isModifierKey(keyCode) && !opt_modifiers) { - if (opt_readableKeyCode) { - tempStr += cvox.KeyUtil.getReadableNameForKeyCode(keyCode); - } else { - tempStr += cvox.KeyUtil.keyCodeToString(keyCode); + // TODO(rshearer): This is a hack to work around the special casing + // of the Ctrl key that used to happen in keyEventToString. We won't + // need it once we move away from strings completely. + modifier = 'Ctrl'; + break; + case 'searchKeyHeld': + var searchKey = cvox.KeyUtil.getReadableNameForKeyCode(91); + modifier = searchKey; + break; + case 'altKey': + modifier = 'Alt'; + break; + case 'altGraphKey': + modifier = 'AltGraph'; + break; + case 'shiftKey': + modifier = 'Shift'; + break; + case 'metaKey': + var metaKey = cvox.KeyUtil.getReadableNameForKeyCode(91); + modifier = metaKey; + break; + case 'keyCode': + var keyCode = keySequence.keys[keyPressed][index]; + // We make sure the keyCode isn't for a modifier key. If it is, then + // we've already added that into the string above. + if (!keySequence.isModifierKey(keyCode) && !opt_modifiers) { + if (opt_readableKeyCode) { + tempStr += cvox.KeyUtil.getReadableNameForKeyCode(keyCode); + } else { + tempStr += cvox.KeyUtil.keyCodeToString(keyCode); + } } - } } if (str.indexOf(modifier) == -1) { - tempStr += modifier + '+'; + tempStr += modifier + '+'; } } str += tempStr;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_attr.js b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_attr.js index 940121d..edda145 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_attr.js +++ b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_attr.js
@@ -57,17 +57,16 @@ /** * @type {Array<string>} */ - this.generalPunctuations = - [ - '!', '"', '#', '%', '&', '\'', '*', ',', ':', ';', '?', '@', '\\', - '¡', '§', '¶', '·', '¿', '‗', '†', '‡', '•', '‣', '․', '‥', '‧', - '‰', '‱', '‸', '※', '‼', '‽', '‾', '⁁', '⁂', '⁃', '⁇', '⁈', '⁉', - '⁋', '⁌', '⁍', '⁎', '⁏', '⁐', '⁑', '⁓', '⁕', '⁖', '⁘', '⁙', '⁚', - '⁛', '⁜', '⁝', '⁞', '︐', '︓', '︔', '︕', '︖', '︰', '﹅', '﹆', - '﹉', '﹊', '﹋', '﹌', '﹐', '﹔', '﹕', '﹖', '﹗', '﹟', '﹠', '﹡', '﹨', - '﹪', '﹫', '!', '"', '#', '%', '&', ''', '*', ',', '/', ':', - ';', '?', '@', '\' - ]; + this.generalPunctuations = [ + '!', '"', '#', '%', '&', '\'', '*', ',', ':', ';', '?', '@', + '\\', '¡', '§', '¶', '·', '¿', '‗', '†', '‡', '•', '‣', '․', + '‥', '‧', '‰', '‱', '‸', '※', '‼', '‽', '‾', '⁁', '⁂', '⁃', + '⁇', '⁈', '⁉', '⁋', '⁌', '⁍', '⁎', '⁏', '⁐', '⁑', '⁓', '⁕', + '⁖', '⁘', '⁙', '⁚', '⁛', '⁜', '⁝', '⁞', '︐', '︓', '︔', '︕', + '︖', '︰', '﹅', '﹆', '﹉', '﹊', '﹋', '﹌', '﹐', '﹔', '﹕', '﹖', + '﹗', '﹟', '﹠', '﹡', '﹨', '﹪', '﹫', '!', '"', '#', '%', '&', + ''', '*', ',', '/', ':', ';', '?', '@', '\' + ]; /** * @type {string} * @private @@ -77,31 +76,19 @@ /** * @type {Array<string>} */ - this.ellipses = - [ - '…', '⋮', '⋯', '⋰', '⋱', '︙' - ]; + this.ellipses = ['…', '⋮', '⋯', '⋰', '⋱', '︙']; /** * @type {Array<string>} */ - this.fullStops = - [ - '.', '﹒', '.' - ]; + this.fullStops = ['.', '﹒', '.']; /** * @type {Array<string>} */ - this.dashes = - [ - '‒', '–', '—', '―', '〜', '︱', '︲', '﹘' - ]; + this.dashes = ['‒', '–', '—', '―', '〜', '︱', '︲', '﹘']; /** * @type {Array<string>} */ - this.primes = - [ - '′', '″', '‴', '‵', '‶', '‷', '⁗' - ]; + this.primes = ['′', '″', '‴', '‵', '‶', '‷', '⁗']; // Fences. // Fences are treated slightly differently from other symbols as we want to @@ -110,41 +97,108 @@ * Mapping opening to closing fences. * @type {Object<string>} */ - this.openClosePairs = - { - // Unicode categories Ps and Pe. - // Observe that left quotation 301D could also be matched to 301F, - // but is currently matched to 301E. - '(': ')', '[': ']', '{': '}', '⁅': '⁆', '〈': '〉', '❨': '❩', - '❪': '❫', '❬': '❭', '❮': '❯', '❰': '❱', '❲': '❳', '❴': '❵', - '⟅': '⟆', '⟦': '⟧', '⟨': '⟩', '⟪': '⟫', '⟬': '⟭', '⟮': '⟯', - '⦃': '⦄', '⦅': '⦆', '⦇': '⦈', '⦉': '⦊', '⦋': '⦌', '⦍': '⦎', - '⦏': '⦐', '⦑': '⦒', '⦓': '⦔', '⦕': '⦖', '⦗': '⦘', '⧘': '⧙', - '⧚': '⧛', '⧼': '⧽', '⸢': '⸣', '⸤': '⸥', '⸦': '⸧', '⸨': '⸩', - '〈': '〉', '《': '》', '「': '」', '『': '』', '【': '】', - '〔': '〕', '〖': '〗', '〘': '〙', '〚': '〛', '〝': '〞', - '﴾': '﴿', '︗': '︘', '﹙': '﹚', '﹛': '﹜', '﹝': '﹞', '(': ')', - '[': ']', '{': '}', '⦅': '⦆', '「': '」', - // Unicode categories Sm and So. - '⌈': '⌉', '⌊': '⌋', '⌌': '⌍', '⌎': '⌏', '⌜': '⌝', '⌞': '⌟', - // Extender fences. - // Parenthesis. - '⎛': '⎞', '⎜': '⎟', '⎝': '⎠', - // Square bracket. - '⎡': '⎤', '⎢': '⎥', '⎣': '⎦', - // Curly bracket. - '⎧': '⎫', '⎨': '⎬', '⎩': '⎭', '⎰': '⎱', '⎸': '⎹' - }; + this.openClosePairs = { + // Unicode categories Ps and Pe. + // Observe that left quotation 301D could also be matched to 301F, + // but is currently matched to 301E. + '(': ')', + '[': ']', + '{': '}', + '⁅': '⁆', + '〈': '〉', + '❨': '❩', + '❪': '❫', + '❬': '❭', + '❮': '❯', + '❰': '❱', + '❲': '❳', + '❴': '❵', + '⟅': '⟆', + '⟦': '⟧', + '⟨': '⟩', + '⟪': '⟫', + '⟬': '⟭', + '⟮': '⟯', + '⦃': '⦄', + '⦅': '⦆', + '⦇': '⦈', + '⦉': '⦊', + '⦋': '⦌', + '⦍': '⦎', + '⦏': '⦐', + '⦑': '⦒', + '⦓': '⦔', + '⦕': '⦖', + '⦗': '⦘', + '⧘': '⧙', + '⧚': '⧛', + '⧼': '⧽', + '⸢': '⸣', + '⸤': '⸥', + '⸦': '⸧', + '⸨': '⸩', + '〈': '〉', + '《': '》', + '「': '」', + '『': '』', + '【': '】', + '〔': '〕', + '〖': '〗', + '〘': '〙', + '〚': '〛', + '〝': '〞', + '﴾': '﴿', + '︗': '︘', + '﹙': '﹚', + '﹛': '﹜', + '﹝': '﹞', + '(': ')', + '[': ']', + '{': '}', + '⦅': '⦆', + '「': '」', + // Unicode categories Sm and So. + '⌈': '⌉', + '⌊': '⌋', + '⌌': '⌍', + '⌎': '⌏', + '⌜': '⌝', + '⌞': '⌟', + // Extender fences. + // Parenthesis. + '⎛': '⎞', + '⎜': '⎟', + '⎝': '⎠', + // Square bracket. + '⎡': '⎤', + '⎢': '⎥', + '⎣': '⎦', + // Curly bracket. + '⎧': '⎫', + '⎨': '⎬', + '⎩': '⎭', + '⎰': '⎱', + '⎸': '⎹' + }; /** * Mapping top to bottom fences. * @type {Object<string>} */ - this.topBottomPairs = - { - '⎴': '⎵', '⏜': '⏝', '⏞': '⏟', '⏠': '⏡', '︵': '︶', '︷': '︸', - '︹': '︺', '︻': '︼', '︽': '︾', '︿': '﹀', '﹁': '﹂', - '﹃': '﹄', '﹇': '﹈' - }; + this.topBottomPairs = { + '⎴': '⎵', + '⏜': '⏝', + '⏞': '⏟', + '⏠': '⏡', + '︵': '︶', + '︷': '︸', + '︹': '︺', + '︻': '︼', + '︽': '︾', + '︿': '﹀', + '﹁': '﹂', + '﹃': '﹄', + '﹇': '﹈' + }; /** * @type {Array<string>} */ @@ -165,10 +219,7 @@ /** * @type {Array<string>} */ - this.neutralFences = - [ - '|', '¦', '‖', '❘', '⦀', '⫴', '¦', '|' - ]; + this.neutralFences = ['|', '¦', '‖', '❘', '⦀', '⫴', '¦', '|']; /** Array of all fences. * @type {Array<string>} */ @@ -180,322 +231,279 @@ /** * @type {Array<string>} */ - this.capitalLatin = - [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' - ]; + this.capitalLatin = [ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' + ]; /** * @type {Array<string>} */ - this.smallLatin = - [ - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - // dotless i and j. - 'ı', 'ȷ' - ]; + this.smallLatin = [ + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + // dotless i and j. + 'ı', 'ȷ' + ]; /** * @type {Array<string>} */ - this.capitalLatinFullWidth = - [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' - ]; + this.capitalLatinFullWidth = [ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', + 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' + ]; /** * @type {Array<string>} */ - this.smallLatinFullWidth = - [ - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' - ]; + this.smallLatinFullWidth = [ + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' + ]; /** * @type {Array<string>} */ - this.capitalLatinBold = - [ - '𝐀', '𝐁', '𝐂', '𝐃', '𝐄', '𝐅', '𝐆', '𝐇', '𝐈', '𝐉', '𝐊', '𝐋', '𝐌', - '𝐍', '𝐎', '𝐏', '𝐐', '𝐑', '𝐒', '𝐓', '𝐔', '𝐕', '𝐖', '𝐗', '𝐘', '𝐙' - ]; + this.capitalLatinBold = [ + '𝐀', '𝐁', '𝐂', '𝐃', '𝐄', '𝐅', '𝐆', '𝐇', '𝐈', '𝐉', '𝐊', '𝐋', '𝐌', + '𝐍', '𝐎', '𝐏', '𝐐', '𝐑', '𝐒', '𝐓', '𝐔', '𝐕', '𝐖', '𝐗', '𝐘', '𝐙' + ]; /** * @type {Array<string>} */ - this.smallLatinBold = - [ - '𝐚', '𝐛', '𝐜', '𝐝', '𝐞', '𝐟', '𝐠', '𝐡', '𝐢', '𝐣', '𝐤', '𝐥', '𝐦', - '𝐧', '𝐨', '𝐩', '𝐪', '𝐫', '𝐬', '𝐭', '𝐮', '𝐯', '𝐰', '𝐱', '𝐲', '𝐳' - ]; + this.smallLatinBold = [ + '𝐚', '𝐛', '𝐜', '𝐝', '𝐞', '𝐟', '𝐠', '𝐡', '𝐢', '𝐣', '𝐤', '𝐥', '𝐦', + '𝐧', '𝐨', '𝐩', '𝐪', '𝐫', '𝐬', '𝐭', '𝐮', '𝐯', '𝐰', '𝐱', '𝐲', '𝐳' + ]; /** * @type {Array<string>} */ - this.capitalLatinItalic = - [ - '𝐴', '𝐵', '𝐶', '𝐷', '𝐸', '𝐹', '𝐺', '𝐻', '𝐼', '𝐽', '𝐾', '𝐿', '𝑀', - '𝑁', '𝑂', '𝑃', '𝑄', '𝑅', '𝑆', '𝑇', '𝑈', '𝑉', '𝑊', '𝑋', '𝑌', '𝑍' - ]; + this.capitalLatinItalic = [ + '𝐴', '𝐵', '𝐶', '𝐷', '𝐸', '𝐹', '𝐺', '𝐻', '𝐼', '𝐽', '𝐾', '𝐿', '𝑀', + '𝑁', '𝑂', '𝑃', '𝑄', '𝑅', '𝑆', '𝑇', '𝑈', '𝑉', '𝑊', '𝑋', '𝑌', '𝑍' + ]; /** * @type {Array<string>} */ - this.smallLatinItalic = - [ - '𝑎', '𝑏', '𝑐', '𝑑', '𝑒', '𝑓', '𝑔', 'ℎ', '𝑖', '𝑗', '𝑘', '𝑙', '𝑚', - '𝑛', '𝑜', '𝑝', '𝑞', '𝑟', '𝑠', '𝑡', '𝑢', '𝑣', '𝑤', '𝑥', '𝑦', '𝑧', - // dotless i and j. - '𝚤', '𝚥' - ]; + this.smallLatinItalic = [ + '𝑎', '𝑏', '𝑐', '𝑑', '𝑒', '𝑓', '𝑔', 'ℎ', '𝑖', '𝑗', '𝑘', '𝑙', '𝑚', '𝑛', '𝑜', + '𝑝', '𝑞', '𝑟', '𝑠', '𝑡', '𝑢', '𝑣', '𝑤', '𝑥', '𝑦', '𝑧', + // dotless i and j. + '𝚤', '𝚥' + ]; /** * @type {Array<string>} */ - this.capitalLatinScript = - [ - '𝒜', 'ℬ', '𝒞', '𝒟', 'ℰ', 'ℱ', '𝒢', 'ℋ', 'ℐ', '𝒥', '𝒦', 'ℒ', 'ℳ', - '𝒩', '𝒪', '𝒫', '𝒬', 'ℛ', '𝒮', '𝒯', '𝒰', '𝒱', '𝒲', '𝒳', '𝒴', '𝒵', - // Powerset Cap P. - '℘' - ]; + this.capitalLatinScript = [ + '𝒜', 'ℬ', '𝒞', '𝒟', 'ℰ', 'ℱ', '𝒢', 'ℋ', 'ℐ', '𝒥', '𝒦', 'ℒ', 'ℳ', '𝒩', '𝒪', + '𝒫', '𝒬', 'ℛ', '𝒮', '𝒯', '𝒰', '𝒱', '𝒲', '𝒳', '𝒴', '𝒵', + // Powerset Cap P. + '℘' + ]; /** * @type {Array<string>} */ - this.smallLatinScript = - [ - '𝒶', '𝒷', '𝒸', '𝒹', 'ℯ', '𝒻', 'ℊ', '𝒽', '𝒾', '𝒿', '𝓀', '𝓁', '𝓂', - '𝓃', 'ℴ', '𝓅', '𝓆', '𝓇', '𝓈', '𝓉', '𝓊', '𝓋', '𝓌', '𝓍', '𝓎', '𝓏', - // script small l - 'ℓ' - ]; + this.smallLatinScript = [ + '𝒶', '𝒷', '𝒸', '𝒹', 'ℯ', '𝒻', 'ℊ', '𝒽', '𝒾', '𝒿', '𝓀', '𝓁', '𝓂', '𝓃', 'ℴ', + '𝓅', '𝓆', '𝓇', '𝓈', '𝓉', '𝓊', '𝓋', '𝓌', '𝓍', '𝓎', '𝓏', + // script small l + 'ℓ' + ]; /** * @type {Array<string>} */ - this.capitalLatinBoldScript = - [ - '𝓐', '𝓑', '𝓒', '𝓓', '𝓔', '𝓕', '𝓖', '𝓗', '𝓘', '𝓙', '𝓚', '𝓛', '𝓜', - '𝓝', '𝓞', '𝓟', '𝓠', '𝓡', '𝓢', '𝓣', '𝓤', '𝓥', '𝓦', '𝓧', '𝓨', '𝓩' - ]; + this.capitalLatinBoldScript = [ + '𝓐', '𝓑', '𝓒', '𝓓', '𝓔', '𝓕', '𝓖', '𝓗', '𝓘', '𝓙', '𝓚', '𝓛', '𝓜', + '𝓝', '𝓞', '𝓟', '𝓠', '𝓡', '𝓢', '𝓣', '𝓤', '𝓥', '𝓦', '𝓧', '𝓨', '𝓩' + ]; /** * @type {Array<string>} */ - this.smallLatinBoldScript = - [ - '𝓪', '𝓫', '𝓬', '𝓭', '𝓮', '𝓯', '𝓰', '𝓱', '𝓲', '𝓳', '𝓴', '𝓵', '𝓶', - '𝓷', '𝓸', '𝓹', '𝓺', '𝓻', '𝓼', '𝓽', '𝓾', '𝓿', '𝔀', '𝔁', '𝔂', '𝔃' - ]; + this.smallLatinBoldScript = [ + '𝓪', '𝓫', '𝓬', '𝓭', '𝓮', '𝓯', '𝓰', '𝓱', '𝓲', '𝓳', '𝓴', '𝓵', '𝓶', + '𝓷', '𝓸', '𝓹', '𝓺', '𝓻', '𝓼', '𝓽', '𝓾', '𝓿', '𝔀', '𝔁', '𝔂', '𝔃' + ]; /** * @type {Array<string>} */ - this.capitalLatinFraktur = - [ - '𝔄', '𝔅', 'ℭ', '𝔇', '𝔈', '𝔉', '𝔊', 'ℌ', 'ℑ', '𝔍', '𝔎', '𝔏', '𝔐', - '𝔑', '𝔒', '𝔓', '𝔔', 'ℜ', '𝔖', '𝔗', '𝔘', '𝔙', '𝔚', '𝔛', '𝔜', 'ℨ' - ]; + this.capitalLatinFraktur = [ + '𝔄', '𝔅', 'ℭ', '𝔇', '𝔈', '𝔉', '𝔊', 'ℌ', 'ℑ', '𝔍', '𝔎', '𝔏', '𝔐', + '𝔑', '𝔒', '𝔓', '𝔔', 'ℜ', '𝔖', '𝔗', '𝔘', '𝔙', '𝔚', '𝔛', '𝔜', 'ℨ' + ]; /** * @type {Array<string>} */ - this.smallLatinFraktur = - [ - '𝔞', '𝔟', '𝔠', '𝔡', '𝔢', '𝔣', '𝔤', '𝔥', '𝔦', '𝔧', '𝔨', '𝔩', '𝔪', - '𝔫', '𝔬', '𝔭', '𝔮', '𝔯', '𝔰', '𝔱', '𝔲', '𝔳', '𝔴', '𝔵', '𝔶', '𝔷' - ]; + this.smallLatinFraktur = [ + '𝔞', '𝔟', '𝔠', '𝔡', '𝔢', '𝔣', '𝔤', '𝔥', '𝔦', '𝔧', '𝔨', '𝔩', '𝔪', + '𝔫', '𝔬', '𝔭', '𝔮', '𝔯', '𝔰', '𝔱', '𝔲', '𝔳', '𝔴', '𝔵', '𝔶', '𝔷' + ]; /** * @type {Array<string>} */ - this.capitalLatinDoubleStruck = - [ - '𝔸', '𝔹', 'ℂ', '𝔻', '𝔼', '𝔽', '𝔾', 'ℍ', '𝕀', '𝕁', '𝕂', '𝕃', '𝕄', - 'ℕ', '𝕆', 'ℙ', 'ℚ', 'ℝ', '𝕊', '𝕋', '𝕌', '𝕍', '𝕎', '𝕏', '𝕐', 'ℤ' - ]; + this.capitalLatinDoubleStruck = [ + '𝔸', '𝔹', 'ℂ', '𝔻', '𝔼', '𝔽', '𝔾', 'ℍ', '𝕀', '𝕁', '𝕂', '𝕃', '𝕄', + 'ℕ', '𝕆', 'ℙ', 'ℚ', 'ℝ', '𝕊', '𝕋', '𝕌', '𝕍', '𝕎', '𝕏', '𝕐', 'ℤ' + ]; /** * @type {Array<string>} */ - this.smallLatinDoubleStruck = - [ - '𝕒', '𝕓', '𝕔', '𝕕', '𝕖', '𝕗', '𝕘', '𝕙', '𝕚', '𝕛', '𝕜', '𝕝', '𝕞', - '𝕟', '𝕠', '𝕡', '𝕢', '𝕣', '𝕤', '𝕥', '𝕦', '𝕧', '𝕨', '𝕩', '𝕪', '𝕫' - ]; + this.smallLatinDoubleStruck = [ + '𝕒', '𝕓', '𝕔', '𝕕', '𝕖', '𝕗', '𝕘', '𝕙', '𝕚', '𝕛', '𝕜', '𝕝', '𝕞', + '𝕟', '𝕠', '𝕡', '𝕢', '𝕣', '𝕤', '𝕥', '𝕦', '𝕧', '𝕨', '𝕩', '𝕪', '𝕫' + ]; /** * @type {Array<string>} */ - this.capitalLatinBoldFraktur = - [ - '𝕬', '𝕭', '𝕮', '𝕯', '𝕰', '𝕱', '𝕲', '𝕳', '𝕴', '𝕵', '𝕶', '𝕷', '𝕸', - '𝕹', '𝕺', '𝕻', '𝕼', '𝕽', '𝕾', '𝕿', '𝖀', '𝖁', '𝖂', '𝖃', '𝖄', '𝖅' - ]; + this.capitalLatinBoldFraktur = [ + '𝕬', '𝕭', '𝕮', '𝕯', '𝕰', '𝕱', '𝕲', '𝕳', '𝕴', '𝕵', '𝕶', '𝕷', '𝕸', + '𝕹', '𝕺', '𝕻', '𝕼', '𝕽', '𝕾', '𝕿', '𝖀', '𝖁', '𝖂', '𝖃', '𝖄', '𝖅' + ]; /** * @type {Array<string>} */ - this.smallLatinBoldFraktur = - [ - '𝖆', '𝖇', '𝖈', '𝖉', '𝖊', '𝖋', '𝖌', '𝖍', '𝖎', '𝖏', '𝖐', '𝖑', '𝖒', - '𝖓', '𝖔', '𝖕', '𝖖', '𝖗', '𝖘', '𝖙', '𝖚', '𝖛', '𝖜', '𝖝', '𝖞', '𝖟' - ]; + this.smallLatinBoldFraktur = [ + '𝖆', '𝖇', '𝖈', '𝖉', '𝖊', '𝖋', '𝖌', '𝖍', '𝖎', '𝖏', '𝖐', '𝖑', '𝖒', + '𝖓', '𝖔', '𝖕', '𝖖', '𝖗', '𝖘', '𝖙', '𝖚', '𝖛', '𝖜', '𝖝', '𝖞', '𝖟' + ]; /** * @type {Array<string>} */ - this.capitalLatinSansSerif = - [ - '𝖠', '𝖡', '𝖢', '𝖣', '𝖤', '𝖥', '𝖦', '𝖧', '𝖨', '𝖩', '𝖪', '𝖫', '𝖬', - '𝖭', '𝖮', '𝖯', '𝖰', '𝖱', '𝖲', '𝖳', '𝖴', '𝖵', '𝖶', '𝖷', '𝖸', '𝖹' - ]; + this.capitalLatinSansSerif = [ + '𝖠', '𝖡', '𝖢', '𝖣', '𝖤', '𝖥', '𝖦', '𝖧', '𝖨', '𝖩', '𝖪', '𝖫', '𝖬', + '𝖭', '𝖮', '𝖯', '𝖰', '𝖱', '𝖲', '𝖳', '𝖴', '𝖵', '𝖶', '𝖷', '𝖸', '𝖹' + ]; /** * @type {Array<string>} */ - this.smallLatinSansSerif = - [ - '𝖺', '𝖻', '𝖼', '𝖽', '𝖾', '𝖿', '𝗀', '𝗁', '𝗂', '𝗃', '𝗄', '𝗅', '𝗆', - '𝗇', '𝗈', '𝗉', '𝗊', '𝗋', '𝗌', '𝗍', '𝗎', '𝗏', '𝗐', '𝗑', '𝗒', '𝗓' - ]; + this.smallLatinSansSerif = [ + '𝖺', '𝖻', '𝖼', '𝖽', '𝖾', '𝖿', '𝗀', '𝗁', '𝗂', '𝗃', '𝗄', '𝗅', '𝗆', + '𝗇', '𝗈', '𝗉', '𝗊', '𝗋', '𝗌', '𝗍', '𝗎', '𝗏', '𝗐', '𝗑', '𝗒', '𝗓' + ]; /** * @type {Array<string>} */ - this.capitalLatinSansSerifBold = - [ - '𝗔', '𝗕', '𝗖', '𝗗', '𝗘', '𝗙', '𝗚', '𝗛', '𝗜', '𝗝', '𝗞', '𝗟', '𝗠', - '𝗡', '𝗢', '𝗣', '𝗤', '𝗥', '𝗦', '𝗧', '𝗨', '𝗩', '𝗪', '𝗫', '𝗬', '𝗭' - ]; + this.capitalLatinSansSerifBold = [ + '𝗔', '𝗕', '𝗖', '𝗗', '𝗘', '𝗙', '𝗚', '𝗛', '𝗜', '𝗝', '𝗞', '𝗟', '𝗠', + '𝗡', '𝗢', '𝗣', '𝗤', '𝗥', '𝗦', '𝗧', '𝗨', '𝗩', '𝗪', '𝗫', '𝗬', '𝗭' + ]; /** * @type {Array<string>} */ - this.smallLatinSansSerifBold = - [ - '𝗮', '𝗯', '𝗰', '𝗱', '𝗲', '𝗳', '𝗴', '𝗵', '𝗶', '𝗷', '𝗸', '𝗹', '𝗺', - '𝗻', '𝗼', '𝗽', '𝗾', '𝗿', '𝘀', '𝘁', '𝘂', '𝘃', '𝘄', '𝘅', '𝘆', '𝘇' - ]; + this.smallLatinSansSerifBold = [ + '𝗮', '𝗯', '𝗰', '𝗱', '𝗲', '𝗳', '𝗴', '𝗵', '𝗶', '𝗷', '𝗸', '𝗹', '𝗺', + '𝗻', '𝗼', '𝗽', '𝗾', '𝗿', '𝘀', '𝘁', '𝘂', '𝘃', '𝘄', '𝘅', '𝘆', '𝘇' + ]; /** * @type {Array<string>} */ - this.capitalLatinSansSerifItalic = - [ - '𝘈', '𝘉', '𝘊', '𝘋', '𝘌', '𝘍', '𝘎', '𝘏', '𝘐', '𝘑', '𝘒', '𝘓', '𝘔', - '𝘕', '𝘖', '𝘗', '𝘘', '𝘙', '𝘚', '𝘛', '𝘜', '𝘝', '𝘞', '𝘟', '𝘠', '𝘡' - ]; + this.capitalLatinSansSerifItalic = [ + '𝘈', '𝘉', '𝘊', '𝘋', '𝘌', '𝘍', '𝘎', '𝘏', '𝘐', '𝘑', '𝘒', '𝘓', '𝘔', + '𝘕', '𝘖', '𝘗', '𝘘', '𝘙', '𝘚', '𝘛', '𝘜', '𝘝', '𝘞', '𝘟', '𝘠', '𝘡' + ]; /** * @type {Array<string>} */ - this.smallLatinSansSerifItalic = - [ - '𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮', - '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻' - ]; + this.smallLatinSansSerifItalic = [ + '𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮', + '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻' + ]; /** * @type {Array<string>} */ - this.capitalLatinMonospace = - [ - '𝙰', '𝙱', '𝙲', '𝙳', '𝙴', '𝙵', '𝙶', '𝙷', '𝙸', '𝙹', '𝙺', '𝙻', '𝙼', - '𝙽', '𝙾', '𝙿', '𝚀', '𝚁', '𝚂', '𝚃', '𝚄', '𝚅', '𝚆', '𝚇', '𝚈', '𝚉' - ]; + this.capitalLatinMonospace = [ + '𝙰', '𝙱', '𝙲', '𝙳', '𝙴', '𝙵', '𝙶', '𝙷', '𝙸', '𝙹', '𝙺', '𝙻', '𝙼', + '𝙽', '𝙾', '𝙿', '𝚀', '𝚁', '𝚂', '𝚃', '𝚄', '𝚅', '𝚆', '𝚇', '𝚈', '𝚉' + ]; /** * @type {Array<string>} */ - this.smallLatinMonospace = - [ - '𝚊', '𝚋', '𝚌', '𝚍', '𝚎', '𝚏', '𝚐', '𝚑', '𝚒', '𝚓', '𝚔', '𝚕', '𝚖', - '𝚗', '𝚘', '𝚙', '𝚚', '𝚛', '𝚜', '𝚝', '𝚞', '𝚟', '𝚠', '𝚡', '𝚢', '𝚣' - ]; + this.smallLatinMonospace = [ + '𝚊', '𝚋', '𝚌', '𝚍', '𝚎', '𝚏', '𝚐', '𝚑', '𝚒', '𝚓', '𝚔', '𝚕', '𝚖', + '𝚗', '𝚘', '𝚙', '𝚚', '𝚛', '𝚜', '𝚝', '𝚞', '𝚟', '𝚠', '𝚡', '𝚢', '𝚣' + ]; /** * @type {Array<string>} */ - this.latinDoubleStruckItalic = - [ - 'ⅅ', 'ⅆ', 'ⅇ', 'ⅈ', 'ⅉ' - ]; + this.latinDoubleStruckItalic = ['ⅅ', 'ⅆ', 'ⅇ', 'ⅈ', 'ⅉ']; // Greek Alphabets /** * @type {Array<string>} */ - this.capitalGreek = - [ - 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', - 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω' - ]; + this.capitalGreek = [ + 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', + 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω' + ]; /** * @type {Array<string>} */ - this.smallGreek = - [ - 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', - 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω' - ]; + this.smallGreek = [ + 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', + 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω' + ]; /** * @type {Array<string>} */ - this.capitalGreekBold = - [ - '𝚨', '𝚩', '𝚪', '𝚫', '𝚬', '𝚭', '𝚮', '𝚯', '𝚰', '𝚱', '𝚲', '𝚳', '𝚴', - '𝚵', '𝚶', '𝚷', '𝚸', '𝚺', '𝚻', '𝚼', '𝚽', '𝚾', '𝚿', '𝛀' - ]; + this.capitalGreekBold = [ + '𝚨', '𝚩', '𝚪', '𝚫', '𝚬', '𝚭', '𝚮', '𝚯', '𝚰', '𝚱', '𝚲', '𝚳', + '𝚴', '𝚵', '𝚶', '𝚷', '𝚸', '𝚺', '𝚻', '𝚼', '𝚽', '𝚾', '𝚿', '𝛀' + ]; /** * @type {Array<string>} */ - this.smallGreekBold = - [ - '𝛂', '𝛃', '𝛄', '𝛅', '𝛆', '𝛇', '𝛈', '𝛉', '𝛊', '𝛋', '𝛌', '𝛍', '𝛎', - '𝛏', '𝛐', '𝛑', '𝛒', '𝛓', '𝛔', '𝛕', '𝛖', '𝛗', '𝛘', '𝛙', '𝛚' - ]; + this.smallGreekBold = [ + '𝛂', '𝛃', '𝛄', '𝛅', '𝛆', '𝛇', '𝛈', '𝛉', '𝛊', '𝛋', '𝛌', '𝛍', '𝛎', + '𝛏', '𝛐', '𝛑', '𝛒', '𝛓', '𝛔', '𝛕', '𝛖', '𝛗', '𝛘', '𝛙', '𝛚' + ]; /** * @type {Array<string>} */ - this.capitalGreekItalic = - [ - '𝛢', '𝛣', '𝛤', '𝛥', '𝛦', '𝛧', '𝛨', '𝛩', '𝛪', '𝛫', '𝛬', '𝛭', '𝛮', - '𝛯', '𝛰', '𝛱', '𝛲', '𝛴', '𝛵', '𝛶', '𝛷', '𝛸', '𝛹', '𝛺' - ]; + this.capitalGreekItalic = [ + '𝛢', '𝛣', '𝛤', '𝛥', '𝛦', '𝛧', '𝛨', '𝛩', '𝛪', '𝛫', '𝛬', '𝛭', + '𝛮', '𝛯', '𝛰', '𝛱', '𝛲', '𝛴', '𝛵', '𝛶', '𝛷', '𝛸', '𝛹', '𝛺' + ]; /** * @type {Array<string>} */ - this.smallGreekItalic = - [ - '𝛼', '𝛽', '𝛾', '𝛿', '𝜀', '𝜁', '𝜂', '𝜃', '𝜄', '𝜅', '𝜆', '𝜇', '𝜈', - '𝜉', '𝜊', '𝜋', '𝜌', '𝜍', '𝜎', '𝜏', '𝜐', '𝜑', '𝜒', '𝜓', '𝜔' - ]; + this.smallGreekItalic = [ + '𝛼', '𝛽', '𝛾', '𝛿', '𝜀', '𝜁', '𝜂', '𝜃', '𝜄', '𝜅', '𝜆', '𝜇', '𝜈', + '𝜉', '𝜊', '𝜋', '𝜌', '𝜍', '𝜎', '𝜏', '𝜐', '𝜑', '𝜒', '𝜓', '𝜔' + ]; /** * @type {Array<string>} */ - this.capitalGreekSansSerifBold = - [ - '𝝖', '𝝗', '𝝘', '𝝙', '𝝚', '𝝛', '𝝜', '𝝝', '𝝞', '𝝟', '𝝠', '𝝡', '𝝢', - '𝝣', '𝝤', '𝝥', '𝝦', '𝝨', '𝝩', '𝝪', '𝝫', '𝝬', '𝝭', '𝝮' - ]; + this.capitalGreekSansSerifBold = [ + '𝝖', '𝝗', '𝝘', '𝝙', '𝝚', '𝝛', '𝝜', '𝝝', '𝝞', '𝝟', '𝝠', '𝝡', + '𝝢', '𝝣', '𝝤', '𝝥', '𝝦', '𝝨', '𝝩', '𝝪', '𝝫', '𝝬', '𝝭', '𝝮' + ]; /** * @type {Array<string>} */ - this.smallGreekSansSerifBold = - [ - '𝝰', '𝝱', '𝝲', '𝝳', '𝝴', '𝝵', '𝝶', '𝝷', '𝝸', '𝝹', '𝝺', '𝝻', '𝝼', - '𝝽', '𝝾', '𝝿', '𝞀', '𝞁', '𝞂', '𝞃', '𝞄', '𝞅', '𝞆', '𝞇', '𝞈' - ]; + this.smallGreekSansSerifBold = [ + '𝝰', '𝝱', '𝝲', '𝝳', '𝝴', '𝝵', '𝝶', '𝝷', '𝝸', '𝝹', '𝝺', '𝝻', '𝝼', + '𝝽', '𝝾', '𝝿', '𝞀', '𝞁', '𝞂', '𝞃', '𝞄', '𝞅', '𝞆', '𝞇', '𝞈' + ]; /** * @type {Array<string>} */ - this.greekDoubleStruck = - [ - 'ℼ', 'ℽ', 'ℾ', 'ℿ' - ]; + this.greekDoubleStruck = ['ℼ', 'ℽ', 'ℾ', 'ℿ']; // Other alphabets. /** * @type {Array<string>} */ - this.hebrewLetters = - [ - 'ℵ', 'ℶ', 'ℷ', 'ℸ' - ]; + this.hebrewLetters = ['ℵ', 'ℶ', 'ℷ', 'ℸ']; - //Operator symbols + // Operator symbols /** * @type {Array<string>} */ - this.additions = - [ - '+', '±', '∓', '∔', '∧', '∨', '∩', '∪', '⊌', '⊓', '⊔', '⊝', '⊞', - '⊤', '⊥', '⊺', '⊻', '⊼', '⋄', '⋎', '⋏', '⋒', '⋓', '△', '▷', '▽', - '◁', '⩞', '⊕' - ]; - /** - * @type {Array<string>} - */ + this.additions = [ + '+', '±', '∓', '∔', '∧', '∨', '∩', '∪', '⊌', '⊓', '⊔', '⊝', '⊞', '⊤', '⊥', + '⊺', '⊻', '⊼', '⋄', '⋎', '⋏', '⋒', '⋓', '△', '▷', '▽', '◁', '⩞', '⊕' + ]; + /** + * @type {Array<string>} + */ /** * Invisible operator for plus. * @type {string} @@ -506,11 +514,10 @@ /** * @type {Array<string>} */ - this.multiplications = - [ - '†', '‡', '∐', '∗', '∘', '∙', '≀', '⊚', '⊛', '⊠', '⊡', '⋅', '⋆', '⋇', - '⋉', '⋊', '⋋', '⋌', '○' - ]; + this.multiplications = [ + '†', '‡', '∐', '∗', '∘', '∙', '≀', '⊚', '⊛', '⊠', '⊡', '⋅', '⋆', '⋇', '⋉', + '⋊', '⋋', '⋌', '○' + ]; /** * Invisible operator for multiplication. * @type {string} @@ -521,18 +528,14 @@ /** * @type {Array<string>} */ - this.subtractions = - [ - '-', '⁒', '⁻', '₋', '−', '∖', '∸', '≂', '⊖', '⊟', '➖', '⨩', '⨪', - '⨫', '⨬', '⨺', '⩁', '⩬', '﹣', '-', '‐', '‑' - ]; + this.subtractions = [ + '-', '⁒', '⁻', '₋', '−', '∖', '∸', '≂', '⊖', '⊟', '➖', + '⨩', '⨪', '⨫', '⨬', '⨺', '⩁', '⩬', '﹣', '-', '‐', '‑' + ]; /** * @type {Array<string>} */ - this.divisions = - [ - '/', '÷', '⁄', '∕', '⊘', '⟌', '⦼', '⨸' - ]; + this.divisions = ['/', '÷', '⁄', '∕', '⊘', '⟌', '⦼', '⨸']; /** * Invisible operator for function application. * @type {string} @@ -540,111 +543,97 @@ */ this.functionApplication_ = cvox.SemanticUtil.numberToUnicode(0x2061); - //Relation symbols + // Relation symbols /** * @type {Array<string>} */ - this.equalities = - [ - '=', '~', '⁼', '₌', '∼', '∽', '≃', '≅', '≈', '≊', '≋', '≌', '≍', - '≎', '≑', '≒', '≓', '≔', '≕', '≖', '≗', '≘', '≙', '≚', '≛', '≜', - '≝', '≞', '≟', '≡', '≣', '⧤', '⩦', '⩮', '⩯', '⩰', '⩱', '⩲', '⩳', - '⩴', '⩵', '⩶', '⩷', '⩸', '⋕', '⩭', '⩪', '⩫', '⩬', '﹦', '=' - ]; + this.equalities = [ + '=', '~', '⁼', '₌', '∼', '∽', '≃', '≅', '≈', '≊', '≋', '≌', '≍', + '≎', '≑', '≒', '≓', '≔', '≕', '≖', '≗', '≘', '≙', '≚', '≛', '≜', + '≝', '≞', '≟', '≡', '≣', '⧤', '⩦', '⩮', '⩯', '⩰', '⩱', '⩲', '⩳', + '⩴', '⩵', '⩶', '⩷', '⩸', '⋕', '⩭', '⩪', '⩫', '⩬', '﹦', '=' + ]; /** * @type {Array<string>} */ - this.inequalities = - [ - '<', '>', '≁', '≂', '≄', '≆', '≇', '≉', '≏', '≐', '≠', '≢', '≤', - '≥', '≦', '≧', '≨', '≩', '≪', '≫', '≬', '≭', '≮', '≯', '≰', '≱', - '≲', '≳', '≴', '≵', '≶', '≷', '≸', '≹', '≺', '≻', '≼', '≽', '≾', - '≿', '⊀', '⊁', '⋖', '⋗', '⋘', '⋙', '⋚', '⋛', '⋜', '⋝', '⋞', '⋟', - '⋠', '⋡', '⋢', '⋣', '⋤', '⋥', '⋦', '⋧', '⋨', '⋩', '⩹', '⩺', '⩻', - '⩼', '⩽', '⩾', '⩿', '⪀', '⪁', '⪂', '⪃', '⪄', '⪅', '⪆', '⪇', '⪈', - '⪉', '⪊', '⪋', '⪌', '⪍', '⪎', '⪏', '⪐', '⪑', '⪒', '⪓', '⪔', '⪕', - '⪖', '⪗', '⪘', '⪙', '⪚', '⪛', '⪜', '⪝', '⪞', '⪟', '⪠', '⪡', '⪢', - '⪣', '⪤', '⪥', '⪦', '⪧', '⪨', '⪩', '⪪', '⪫', '⪬', '⪭', '⪮', '⪯', - '⪰', '⪱', '⪲', '⪳', '⪴', '⪵', '⪶', '⪷', '⪸', '⪹', '⪺', '⪻', '⪼', - '⫷', '⫸', '⫹', '⫺', '⧀', '⧁', '﹤', '﹥', '<', '>' - ]; + this.inequalities = [ + '<', '>', '≁', '≂', '≄', '≆', '≇', '≉', '≏', '≐', '≠', '≢', '≤', '≥', + '≦', '≧', '≨', '≩', '≪', '≫', '≬', '≭', '≮', '≯', '≰', '≱', '≲', '≳', + '≴', '≵', '≶', '≷', '≸', '≹', '≺', '≻', '≼', '≽', '≾', '≿', '⊀', '⊁', + '⋖', '⋗', '⋘', '⋙', '⋚', '⋛', '⋜', '⋝', '⋞', '⋟', '⋠', '⋡', '⋢', '⋣', + '⋤', '⋥', '⋦', '⋧', '⋨', '⋩', '⩹', '⩺', '⩻', '⩼', '⩽', '⩾', '⩿', '⪀', + '⪁', '⪂', '⪃', '⪄', '⪅', '⪆', '⪇', '⪈', '⪉', '⪊', '⪋', '⪌', '⪍', '⪎', + '⪏', '⪐', '⪑', '⪒', '⪓', '⪔', '⪕', '⪖', '⪗', '⪘', '⪙', '⪚', '⪛', '⪜', + '⪝', '⪞', '⪟', '⪠', '⪡', '⪢', '⪣', '⪤', '⪥', '⪦', '⪧', '⪨', '⪩', '⪪', + '⪫', '⪬', '⪭', '⪮', '⪯', '⪰', '⪱', '⪲', '⪳', '⪴', '⪵', '⪶', '⪷', '⪸', + '⪹', '⪺', '⪻', '⪼', '⫷', '⫸', '⫹', '⫺', '⧀', '⧁', '﹤', '﹥', '<', '>' + ]; /** * @type {Array<string>} */ - this.relations = - [ - // TODO (sorge): Add all the other relations. - ]; + this.relations = [ + // TODO (sorge): Add all the other relations. + ]; /** * @type {Array<string>} */ - this.arrows = - [ - '←', '↑', '→', '↓', '↔', '↕', '↖', '↗', '↘', '↙', '↚', '↛', '↜', - '↝', '↞', '↟', '↠', '↡', '↢', '↣', '↤', '↥', '↦', '↧', '↨', '↩', - '↪', '↫', '↬', '↭', '↮', '↯', '↰', '↱', '↲', '↳', '↴', '↵', '↶', - '↷', '↸', '↹', '↺', '↻', '⇄', '⇅', '⇆', '⇇', '⇈', '⇉', '⇊', '⇍', - '⇎', '⇏', '⇐', '⇑', '⇒', '⇓', '⇔', '⇕', '⇖', '⇗', '⇘', '⇙', '⇚', - '⇛', '⇜', '⇝', '⇞', '⇟', '⇠', '⇡', '⇢', '⇣', '⇤', '⇥', '⇦', '⇧', - '⇨', '⇩', '⇪', '⇫', '⇬', '⇭', '⇮', '⇯', '⇰', '⇱', '⇲', '⇳', '⇴', - '⇵', '⇶', '⇷', '⇸', '⇹', '⇺', '⇻', '⇼', '⇽', '⇾', '⇿', '⌁', '⌃', - '⌄', '⌤', '⎋', '➔', '➘', '➙', '➚', '➛', '➜', '➝', '➞', '➟', '➠', - '➡', '➢', '➣', '➤', '➥', '➦', '➧', '➨', '➩', '➪', '➫', '➬', '➭', - '➮', '➯', '➱', '➲', '➳', '➴', '➵', '➶', '➷', '➸', '➹', '➺', '➻', - '➼', '➽', '➾', '⟰', '⟱', '⟲', '⟳', '⟴', '⟵', '⟶', '⟷', '⟸', '⟹', - '⟺', '⟻', '⟼', '⟽', '⟾', '⟿', '⤀', '⤁', '⤂', '⤃', '⤄', '⤅', '⤆', - '⤇', '⤈', '⤉', '⤊', '⤋', '⤌', '⤍', '⤎', '⤏', '⤐', '⤑', '⤒', '⤓', - '⤔', '⤕', '⤖', '⤗', '⤘', '⤙', '⤚', '⤛', '⤜', '⤝', '⤞', '⤟', '⤠', - '⤡', '⤢', '⤣', '⤤', '⤥', '⤦', '⤧', '⤨', '⤩', '⤪', '⤭', '⤮', '⤯', - '⤰', '⤱', '⤲', '⤳', '⤴', '⤵', '⤶', '⤷', '⤸', '⤹', '⤺', '⤻', '⤼', - '⤽', '⤾', '⤿', '⥀', '⥁', '⥂', '⥃', '⥄', '⥅', '⥆', '⥇', '⥈', '⥉', - '⥰', '⥱', '⥲', '⥳', '⥴', '⥵', '⥶', '⥷', '⥸', '⥹', '⥺', '⥻', '⦳', - '⦴', '⦽', '⧪', '⧬', '⧭', '⨗', '⬀', '⬁', '⬂', '⬃', '⬄', '⬅', '⬆', - '⬇', '⬈', '⬉', '⬊', '⬋', '⬌', '⬍', '⬎', '⬏', '⬐', '⬑', '⬰', '⬱', - '⬲', '⬳', '⬴', '⬵', '⬶', '⬷', '⬸', '⬹', '⬺', '⬻', '⬼', '⬽', '⬾', - '⬿', '⭀', '⭁', '⭂', '⭃', '⭄', '⭅', '⭆', '⭇', '⭈', '⭉', '⭊', '⭋', - '⭌', '←', '↑', '→', '↓', - // Harpoons - '↼', '↽', '↾', '↿', '⇀', '⇁', '⇂', '⇃', '⇋', '⇌', '⥊', '⥋', '⥌', - '⥍', '⥎', '⥏', '⥐', '⥑', '⥒', '⥓', '⥔', '⥕', '⥖', '⥗', '⥘', '⥙', - '⥚', '⥛', '⥜', '⥝', '⥞', '⥟', '⥠', '⥡', '⥢', '⥣', '⥤', '⥥', '⥦', - '⥧', '⥨', '⥩', '⥪', '⥫', '⥬', '⥭', '⥮', '⥯', '⥼', '⥽', '⥾', '⥿' - ]; + this.arrows = [ + '←', '↑', '→', '↓', '↔', '↕', '↖', '↗', '↘', '↙', '↚', '↛', '↜', '↝', '↞', + '↟', '↠', '↡', '↢', '↣', '↤', '↥', '↦', '↧', '↨', '↩', '↪', '↫', '↬', '↭', + '↮', '↯', '↰', '↱', '↲', '↳', '↴', '↵', '↶', '↷', '↸', '↹', '↺', '↻', '⇄', + '⇅', '⇆', '⇇', '⇈', '⇉', '⇊', '⇍', '⇎', '⇏', '⇐', '⇑', '⇒', '⇓', '⇔', '⇕', + '⇖', '⇗', '⇘', '⇙', '⇚', '⇛', '⇜', '⇝', '⇞', '⇟', '⇠', '⇡', '⇢', '⇣', '⇤', + '⇥', '⇦', '⇧', '⇨', '⇩', '⇪', '⇫', '⇬', '⇭', '⇮', '⇯', '⇰', '⇱', '⇲', '⇳', + '⇴', '⇵', '⇶', '⇷', '⇸', '⇹', '⇺', '⇻', '⇼', '⇽', '⇾', '⇿', '⌁', '⌃', '⌄', + '⌤', '⎋', '➔', '➘', '➙', '➚', '➛', '➜', '➝', '➞', '➟', '➠', '➡', '➢', '➣', + '➤', '➥', '➦', '➧', '➨', '➩', '➪', '➫', '➬', '➭', '➮', '➯', '➱', '➲', '➳', + '➴', '➵', '➶', '➷', '➸', '➹', '➺', '➻', '➼', '➽', '➾', '⟰', '⟱', '⟲', '⟳', + '⟴', '⟵', '⟶', '⟷', '⟸', '⟹', '⟺', '⟻', '⟼', '⟽', '⟾', '⟿', '⤀', '⤁', '⤂', + '⤃', '⤄', '⤅', '⤆', '⤇', '⤈', '⤉', '⤊', '⤋', '⤌', '⤍', '⤎', '⤏', '⤐', '⤑', + '⤒', '⤓', '⤔', '⤕', '⤖', '⤗', '⤘', '⤙', '⤚', '⤛', '⤜', '⤝', '⤞', '⤟', '⤠', + '⤡', '⤢', '⤣', '⤤', '⤥', '⤦', '⤧', '⤨', '⤩', '⤪', '⤭', '⤮', '⤯', '⤰', '⤱', + '⤲', '⤳', '⤴', '⤵', '⤶', '⤷', '⤸', '⤹', '⤺', '⤻', '⤼', '⤽', '⤾', '⤿', '⥀', + '⥁', '⥂', '⥃', '⥄', '⥅', '⥆', '⥇', '⥈', '⥉', '⥰', '⥱', '⥲', '⥳', '⥴', '⥵', + '⥶', '⥷', '⥸', '⥹', '⥺', '⥻', '⦳', '⦴', '⦽', '⧪', '⧬', '⧭', '⨗', '⬀', '⬁', + '⬂', '⬃', '⬄', '⬅', '⬆', '⬇', '⬈', '⬉', '⬊', '⬋', '⬌', '⬍', '⬎', '⬏', '⬐', + '⬑', '⬰', '⬱', '⬲', '⬳', '⬴', '⬵', '⬶', '⬷', '⬸', '⬹', '⬺', '⬻', '⬼', '⬽', + '⬾', '⬿', '⭀', '⭁', '⭂', '⭃', '⭄', '⭅', '⭆', '⭇', '⭈', '⭉', '⭊', '⭋', '⭌', + '←', '↑', '→', '↓', + // Harpoons + '↼', '↽', '↾', '↿', '⇀', '⇁', '⇂', '⇃', '⇋', '⇌', '⥊', '⥋', '⥌', '⥍', '⥎', + '⥏', '⥐', '⥑', '⥒', '⥓', '⥔', '⥕', '⥖', '⥗', '⥘', '⥙', '⥚', '⥛', '⥜', '⥝', + '⥞', '⥟', '⥠', '⥡', '⥢', '⥣', '⥤', '⥥', '⥦', '⥧', '⥨', '⥩', '⥪', '⥫', '⥬', + '⥭', '⥮', '⥯', '⥼', '⥽', '⥾', '⥿' + ]; - //Big operation symbols + // Big operation symbols /** * @type {Array<string>} */ - this.sumOps = - [ - '⅀', // double struck - '∏', '∐', '∑', '⋀', '⋁', '⋂', '⋃', '⨀', '⨁', '⨂', '⨃', '⨄', '⨅', - '⨆', '⨇', '⨈', '⨉', '⨊', '⨋', '⫼', '⫿' - ]; + this.sumOps = [ + '⅀', // double struck + '∏', '∐', '∑', '⋀', '⋁', '⋂', '⋃', '⨀', '⨁', '⨂', '⨃', + '⨄', '⨅', '⨆', '⨇', '⨈', '⨉', '⨊', '⨋', '⫼', '⫿' + ]; /** * @type {Array<string>} */ - this.intOps = - [ - '∫', '∬', '∭', '∮', '∯', '∰', '∱', '∲', '∳', '⨌', '⨍', '⨎', '⨏', - '⨐', '⨑', '⨒', '⨓', '⨔', '⨕', '⨖', '⨗', '⨘', '⨙', '⨚', '⨛', '⨜' - ]; + this.intOps = [ + '∫', '∬', '∭', '∮', '∯', '∰', '∱', '∲', '∳', '⨌', '⨍', '⨎', '⨏', + '⨐', '⨑', '⨒', '⨓', '⨔', '⨕', '⨖', '⨗', '⨘', '⨙', '⨚', '⨛', '⨜' + ]; /** * @type {Array<string>} */ this.prefixOps = // TODO (sorge) Insert nabla, differential operators etc. - [ - '∀', '∃' - ]; + ['∀', '∃']; /** * @type {Array<string>} */ this.operatorBits = // TODO (sorge) What to do if single glyphs of big ops occur on their own. - [ - '⌠', '⌡', '⎶', '⎪', '⎮', '⎯', '⎲', '⎳', '⎷' - ]; + ['⌠', '⌡', '⎶', '⎪', '⎮', '⎯', '⎲', '⎳', '⎷']; // Accents. // TODO (sorge) Add accented characters. @@ -654,106 +643,82 @@ /** * @type {Array<string>} */ - this.digitsNormal = - [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' - ]; + this.digitsNormal = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; /** * @type {Array<string>} */ this.digitsFullWidth = - [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' - ]; + ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; /** * @type {Array<string>} */ - this.digitsBold = - [ - '𝟎', '𝟏', '𝟐', '𝟑', '𝟒', '𝟓', '𝟔', '𝟕', '𝟖', '𝟗' - ]; + this.digitsBold = ['𝟎', '𝟏', '𝟐', '𝟑', '𝟒', '𝟓', '𝟔', '𝟕', '𝟖', '𝟗']; /** * @type {Array<string>} */ - this.digitsDoubleStruck = - [ - '𝟘', '𝟙', '𝟚', '𝟛', '𝟜', '𝟝', '𝟞', '𝟟', '𝟠', '𝟡' - ]; + this.digitsDoubleStruck = ['𝟘', '𝟙', '𝟚', '𝟛', '𝟜', '𝟝', '𝟞', '𝟟', '𝟠', '𝟡']; /** * @type {Array<string>} */ - this.digitsSansSerif = - [ - '𝟢', '𝟣', '𝟤', '𝟥', '𝟦', '𝟧', '𝟨', '𝟩', '𝟪', '𝟫' - ]; + this.digitsSansSerif = ['𝟢', '𝟣', '𝟤', '𝟥', '𝟦', '𝟧', '𝟨', '𝟩', '𝟪', '𝟫']; /** * @type {Array<string>} */ - this.digitsSansSerifBold = - [ - '𝟬', '𝟭', '𝟮', '𝟯', '𝟰', '𝟱', '𝟲', '𝟳', '𝟴', '𝟵' - ]; + this.digitsSansSerifBold = ['𝟬', '𝟭', '𝟮', '𝟯', '𝟰', '𝟱', '𝟲', '𝟳', '𝟴', '𝟵']; /** * @type {Array<string>} */ - this.digitsMonospace = - [ - '𝟶', '𝟷', '𝟸', '𝟹', '𝟺', '𝟻', '𝟼', '𝟽', '𝟾', '𝟿' - ]; + this.digitsMonospace = ['𝟶', '𝟷', '𝟸', '𝟹', '𝟺', '𝟻', '𝟼', '𝟽', '𝟾', '𝟿']; /** * @type {Array<string>} */ - this.digitsSuperscript = - [ - '²', '³', '¹', '⁰', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹' - ]; + this.digitsSuperscript = ['²', '³', '¹', '⁰', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']; /** * @type {Array<string>} */ - this.digitsSubscript = - [ - '₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉' - ]; + this.digitsSubscript = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉']; /** * @type {Array<string>} */ - this.fractions = - [ - '¼', '½', '¾', '⅐', '⅑', '⅒', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', - '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '↉' - ]; + this.fractions = [ + '¼', '½', '¾', '⅐', '⅑', '⅒', '⅓', '⅔', '⅕', '⅖', + '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '↉' + ]; /** * @type {Array<string>} */ this.enclosedNumbers = // Encircled numbers. [ - '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', - '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳', '⓪', '⓫', '⓬', '⓭', '⓮', '⓯', - '⓰', '⓱', '⓲', '⓳', '⓴', '⓵', '⓶', '⓷', '⓸', '⓹', '⓺', '⓻', '⓼', - '⓽', '⓾', '⓿', '❶', '❷', '❸', '❹', '❺', '❻', '❼', '❽', '❾', '❿', - '➀', '➁', '➂', '➃', '➄', '➅', '➆', '➇', '➈', '➉', '➊', '➋', '➌', - '➍', '➎', '➏', '➐', '➑', '➒', '➓', '㉈', '㉉', '㉊', '㉋', '㉌', + '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', + '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳', '⓪', '⓫', + '⓬', '⓭', '⓮', '⓯', '⓰', '⓱', '⓲', '⓳', '⓴', '⓵', '⓶', + '⓷', '⓸', '⓹', '⓺', '⓻', '⓼', '⓽', '⓾', '⓿', '❶', '❷', + '❸', '❹', '❺', '❻', '❼', '❽', '❾', '❿', '➀', '➁', '➂', + '➃', '➄', '➅', '➆', '➇', '➈', '➉', '➊', '➋', '➌', '➍', + '➎', '➏', '➐', '➑', '➒', '➓', '㉈', '㉉', '㉊', '㉋', '㉌', '㉍', '㉎', '㉏', '㉑', '㉒', '㉓', '㉔', '㉕', '㉖', '㉗', '㉘', '㉙', '㉚', '㉛', '㉜', '㉝', '㉞', '㉟', '㊱', '㊲', '㊳', '㊴', - '㊵', '㊶', '㊷', '㊸', '㊹', '㊺', '㊻', '㊼', '㊽', '㊾', '㊿']; + '㊵', '㊶', '㊷', '㊸', '㊹', '㊺', '㊻', '㊼', '㊽', '㊾', '㊿' + ]; /** * @type {Array<string>} */ this.fencedNumbers = // Numbers in Parenthesis. [ - '⑴', '⑵', '⑶', '⑷', '⑸', '⑹', '⑺', '⑻', '⑼', '⑽', '⑾', '⑿', '⒀', - '⒁', '⒂', '⒃', '⒄', '⒅', '⒆', '⒇' + '⑴', '⑵', '⑶', '⑷', '⑸', '⑹', '⑺', '⑻', '⑼', '⑽', + '⑾', '⑿', '⒀', '⒁', '⒂', '⒃', '⒄', '⒅', '⒆', '⒇' ]; /** * @type {Array<string>} */ this.punctuatedNumbers = // Numbers with other punctuation. - ['⒈', '⒉', '⒊', '⒋', '⒌', '⒍', '⒎', '⒏', '⒐', '⒑', '⒒', '⒓', '⒔', - '⒕', '⒖', '⒗', '⒘', '⒙', '⒚', '⒛', // full stop. - '🄀', '🄁', '🄂', '🄃', '🄄', '🄅', '🄆', '🄇', '🄈', '🄉', '🄊' // comma. + [ + '⒈', '⒉', '⒊', '⒋', '⒌', '⒍', '⒎', '⒏', '⒐', '⒑', '⒒', + '⒓', '⒔', '⒕', '⒖', '⒗', '⒘', '⒙', '⒚', '⒛', // full stop. + '🄀', '🄁', '🄂', '🄃', '🄄', '🄅', '🄆', '🄇', '🄈', '🄉', '🄊' // comma. ]; /** Array of all single digits. * @type {Array<string>} @@ -765,8 +730,8 @@ * @type {Array<string>} */ this.numbers = this.fractions.concat( - this.digitsSuperscript, this.digitsSubscript, - this.enclosedNumbers, this.fencedNumbers, this.punctuatedNumbers); + this.digitsSuperscript, this.digitsSubscript, this.enclosedNumbers, + this.fencedNumbers, this.punctuatedNumbers); /** Array of all number symbols. * @type {Array<string>} */ @@ -776,58 +741,44 @@ /** * @type {Array<string>} */ - this.trigonometricFunctions = - [ - 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'arccos', 'arccot', - 'arccsc', 'arcsec', 'arcsin', 'arctan' - ]; + this.trigonometricFunctions = [ + 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'arccos', 'arccot', 'arccsc', + 'arcsec', 'arcsin', 'arctan' + ]; /** * @type {Array<string>} */ - this.hyperbolicFunctions = - [ - 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', - 'arcosh', 'arcoth', 'arcsch', 'arsech', 'arsinh', 'artanh', - 'arccosh', 'arccoth', 'arccsch', 'arcsech', 'arcsinh', 'arctanh' - ]; + this.hyperbolicFunctions = [ + 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', 'arcosh', 'arcoth', + 'arcsch', 'arsech', 'arsinh', 'artanh', 'arccosh', 'arccoth', 'arccsch', + 'arcsech', 'arcsinh', 'arctanh' + ]; /** * @type {Array<string>} */ - this.algebraicFunctions = - [ - 'deg', 'det', 'dim', 'hom', 'ker', 'Tr', 'tr' - ]; + this.algebraicFunctions = ['deg', 'det', 'dim', 'hom', 'ker', 'Tr', 'tr']; /** * @type {Array<string>} */ this.elementaryFunctions = - [ - 'log', 'ln', 'lg', 'exp', 'expt', 'gcd', 'gcd', 'arg', 'im', 're', 'Pr' - ]; + ['log', 'ln', 'lg', 'exp', 'expt', 'gcd', 'gcd', 'arg', 'im', 're', 'Pr']; /** All predefined prefix functions. * @type {Array<string>} */ this.prefixFunctions = this.trigonometricFunctions.concat( - this.hyperbolicFunctions, - this.algebraicFunctions, - this.elementaryFunctions - ); + this.hyperbolicFunctions, this.algebraicFunctions, + this.elementaryFunctions); /** Limit functions are handled separately as they can have lower (and upper) * limiting expressions. * @type {Array<string>} */ - this.limitFunctions = - [ - 'inf', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'injlim', - 'projlim' - ]; + this.limitFunctions = [ + 'inf', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'injlim', 'projlim' + ]; /** * @type {Array<string>} */ - this.infixFunctions = - [ - 'mod', 'rem' - ]; + this.infixFunctions = ['mod', 'rem']; /** * Default assignments of semantic attributes. * @type {Array<{set: Array<string>, @@ -838,333 +789,405 @@ */ this.symbolSetToSemantic_ = [ // Punctuation - {set: this.generalPunctuations, - type: cvox.SemanticAttr.Type.PUNCTUATION, - role: cvox.SemanticAttr.Role.UNKNOWN + { + set: this.generalPunctuations, + type: cvox.SemanticAttr.Type.PUNCTUATION, + role: cvox.SemanticAttr.Role.UNKNOWN }, - {set: this.ellipses, - type: cvox.SemanticAttr.Type.PUNCTUATION, - role: cvox.SemanticAttr.Role.ELLIPSIS + { + set: this.ellipses, + type: cvox.SemanticAttr.Type.PUNCTUATION, + role: cvox.SemanticAttr.Role.ELLIPSIS }, - {set: this.fullStops, - type: cvox.SemanticAttr.Type.PUNCTUATION, - role: cvox.SemanticAttr.Role.FULLSTOP + { + set: this.fullStops, + type: cvox.SemanticAttr.Type.PUNCTUATION, + role: cvox.SemanticAttr.Role.FULLSTOP }, - {set: this.dashes, - type: cvox.SemanticAttr.Type.PUNCTUATION, - role: cvox.SemanticAttr.Role.DASH + { + set: this.dashes, + type: cvox.SemanticAttr.Type.PUNCTUATION, + role: cvox.SemanticAttr.Role.DASH }, - {set: this.primes, - type: cvox.SemanticAttr.Type.PUNCTUATION, - role: cvox.SemanticAttr.Role.PRIME + { + set: this.primes, + type: cvox.SemanticAttr.Type.PUNCTUATION, + role: cvox.SemanticAttr.Role.PRIME }, // Fences - {set: this.leftFences, - type: cvox.SemanticAttr.Type.FENCE, - role: cvox.SemanticAttr.Role.OPEN + { + set: this.leftFences, + type: cvox.SemanticAttr.Type.FENCE, + role: cvox.SemanticAttr.Role.OPEN }, - {set: this.rightFences, - type: cvox.SemanticAttr.Type.FENCE, - role: cvox.SemanticAttr.Role.CLOSE + { + set: this.rightFences, + type: cvox.SemanticAttr.Type.FENCE, + role: cvox.SemanticAttr.Role.CLOSE }, - {set: this.topFences, - type: cvox.SemanticAttr.Type.FENCE, - role: cvox.SemanticAttr.Role.TOP + { + set: this.topFences, + type: cvox.SemanticAttr.Type.FENCE, + role: cvox.SemanticAttr.Role.TOP }, - {set: this.bottomFences, - type: cvox.SemanticAttr.Type.FENCE, - role: cvox.SemanticAttr.Role.BOTTOM + { + set: this.bottomFences, + type: cvox.SemanticAttr.Type.FENCE, + role: cvox.SemanticAttr.Role.BOTTOM }, - {set: this.neutralFences, - type: cvox.SemanticAttr.Type.FENCE, - role: cvox.SemanticAttr.Role.NEUTRAL + { + set: this.neutralFences, + type: cvox.SemanticAttr.Type.FENCE, + role: cvox.SemanticAttr.Role.NEUTRAL }, // Single characters. // Latin alphabets. - {set: this.smallLatin, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.smallLatin, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.capitalLatin, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.capitalLatin, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.smallLatinFullWidth, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.smallLatinFullWidth, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.capitalLatinFullWidth, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.capitalLatinFullWidth, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.smallLatinBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLD + { + set: this.smallLatinBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLD }, - {set: this.capitalLatinBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLD + { + set: this.capitalLatinBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLD }, - {set: this.smallLatinItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.ITALIC + { + set: this.smallLatinItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.ITALIC }, - {set: this.capitalLatinItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.ITALIC + { + set: this.capitalLatinItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.ITALIC }, - {set: this.smallLatinScript, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SCRIPT + { + set: this.smallLatinScript, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SCRIPT }, - {set: this.capitalLatinScript, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SCRIPT + { + set: this.capitalLatinScript, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SCRIPT }, - {set: this.smallLatinBoldScript, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLDSCRIPT + { + set: this.smallLatinBoldScript, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLDSCRIPT }, - {set: this.capitalLatinBoldScript, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLDSCRIPT + { + set: this.capitalLatinBoldScript, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLDSCRIPT }, - {set: this.smallLatinFraktur, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.FRAKTUR + { + set: this.smallLatinFraktur, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.FRAKTUR }, - {set: this.capitalLatinFraktur, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.FRAKTUR + { + set: this.capitalLatinFraktur, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.FRAKTUR }, - {set: this.smallLatinDoubleStruck, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.DOUBLESTRUCK + { + set: this.smallLatinDoubleStruck, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.DOUBLESTRUCK }, - {set: this.capitalLatinDoubleStruck, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.DOUBLESTRUCK + { + set: this.capitalLatinDoubleStruck, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.DOUBLESTRUCK }, - {set: this.smallLatinBoldFraktur, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLDFRAKTUR + { + set: this.smallLatinBoldFraktur, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLDFRAKTUR }, - {set: this.capitalLatinBoldFraktur, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.BOLDFRAKTUR + { + set: this.capitalLatinBoldFraktur, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.BOLDFRAKTUR }, - {set: this.smallLatinSansSerif, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIF + { + set: this.smallLatinSansSerif, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIF }, - {set: this.capitalLatinSansSerif, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIF + { + set: this.capitalLatinSansSerif, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIF }, - {set: this.smallLatinSansSerifBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFBOLD + { + set: this.smallLatinSansSerifBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFBOLD }, - {set: this.capitalLatinSansSerifBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFBOLD + { + set: this.capitalLatinSansSerifBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFBOLD }, - {set: this.smallLatinSansSerifItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFITALIC + { + set: this.smallLatinSansSerifItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFITALIC }, - {set: this.capitalLatinSansSerifItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFITALIC + { + set: this.capitalLatinSansSerifItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFITALIC }, - {set: this.smallLatinMonospace, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.MONOSPACE + { + set: this.smallLatinMonospace, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.MONOSPACE }, - {set: this.capitalLatinMonospace, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.MONOSPACE + { + set: this.capitalLatinMonospace, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.MONOSPACE }, - {set: this.latinDoubleStruckItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.LATINLETTER, - font: cvox.SemanticAttr.Font.DOUBLESTRUCKITALIC + { + set: this.latinDoubleStruckItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.LATINLETTER, + font: cvox.SemanticAttr.Font.DOUBLESTRUCKITALIC }, // Greek alphabets. - {set: this.smallGreek, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.smallGreek, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.capitalGreek, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.capitalGreek, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.smallGreekBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.BOLD + { + set: this.smallGreekBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.BOLD }, - {set: this.capitalGreekBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.BOLD + { + set: this.capitalGreekBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.BOLD }, - {set: this.smallGreekItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.ITALIC + { + set: this.smallGreekItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.ITALIC }, - {set: this.capitalGreekItalic, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.ITALIC + { + set: this.capitalGreekItalic, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.ITALIC }, - {set: this.smallGreekSansSerifBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFBOLD + { + set: this.smallGreekSansSerifBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFBOLD }, - {set: this.capitalGreekSansSerifBold, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.SANSSERIFBOLD + { + set: this.capitalGreekSansSerifBold, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.SANSSERIFBOLD }, - {set: this.greekDoubleStruck, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.GREEKLETTER, - font: cvox.SemanticAttr.Font.DOUBLESTRUCK + { + set: this.greekDoubleStruck, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.GREEKLETTER, + font: cvox.SemanticAttr.Font.DOUBLESTRUCK }, // Other alphabets. - {set: this.hebrewLetters, - type: cvox.SemanticAttr.Type.IDENTIFIER, - role: cvox.SemanticAttr.Role.OTHERLETTER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.hebrewLetters, + type: cvox.SemanticAttr.Type.IDENTIFIER, + role: cvox.SemanticAttr.Role.OTHERLETTER, + font: cvox.SemanticAttr.Font.NORMAL }, // Numbers. - {set: this.digitsNormal, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.digitsNormal, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.digitsFullWidth, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.NORMAL + { + set: this.digitsFullWidth, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.NORMAL }, - {set: this.digitsBold, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.BOLD + { + set: this.digitsBold, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.BOLD }, - {set: this.digitsDoubleStruck, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.DOUBLESTRUCK + { + set: this.digitsDoubleStruck, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.DOUBLESTRUCK }, - {set: this.digitsSansSerif, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.SANSSERIF + { + set: this.digitsSansSerif, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.SANSSERIF }, - {set: this.digitsSansSerifBold, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.SANSSERIFBOLD + { + set: this.digitsSansSerifBold, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.SANSSERIFBOLD }, - {set: this.digitsMonospace, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER, - font: cvox.SemanticAttr.Font.MONOSPACE + { + set: this.digitsMonospace, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER, + font: cvox.SemanticAttr.Font.MONOSPACE }, - {set: this.numbers, - type: cvox.SemanticAttr.Type.NUMBER, - role: cvox.SemanticAttr.Role.INTEGER + { + set: this.numbers, + type: cvox.SemanticAttr.Type.NUMBER, + role: cvox.SemanticAttr.Role.INTEGER }, // Operators. - {set: this.additions, - type: cvox.SemanticAttr.Type.OPERATOR, - role: cvox.SemanticAttr.Role.ADDITION + { + set: this.additions, + type: cvox.SemanticAttr.Type.OPERATOR, + role: cvox.SemanticAttr.Role.ADDITION }, - {set: this.multiplications, - type: cvox.SemanticAttr.Type.OPERATOR, - role: cvox.SemanticAttr.Role.MULTIPLICATION + { + set: this.multiplications, + type: cvox.SemanticAttr.Type.OPERATOR, + role: cvox.SemanticAttr.Role.MULTIPLICATION }, - {set: this.subtractions, - type: cvox.SemanticAttr.Type.OPERATOR, - role: cvox.SemanticAttr.Role.SUBTRACTION + { + set: this.subtractions, + type: cvox.SemanticAttr.Type.OPERATOR, + role: cvox.SemanticAttr.Role.SUBTRACTION }, - {set: this.divisions, - type: cvox.SemanticAttr.Type.OPERATOR, - role: cvox.SemanticAttr.Role.DIVISION + { + set: this.divisions, + type: cvox.SemanticAttr.Type.OPERATOR, + role: cvox.SemanticAttr.Role.DIVISION }, - {set: this.prefixOps, - type: cvox.SemanticAttr.Type.PREFIXOP, - role: cvox.SemanticAttr.Role.PREFIXFUNC + { + set: this.prefixOps, + type: cvox.SemanticAttr.Type.PREFIXOP, + role: cvox.SemanticAttr.Role.PREFIXFUNC }, // Relations - {set: this.equalities, - type: cvox.SemanticAttr.Type.RELATION, - role: cvox.SemanticAttr.Role.EQUALITY + { + set: this.equalities, + type: cvox.SemanticAttr.Type.RELATION, + role: cvox.SemanticAttr.Role.EQUALITY }, - {set: this.inequalities, - type: cvox.SemanticAttr.Type.RELATION, - role: cvox.SemanticAttr.Role.INEQUALITY + { + set: this.inequalities, + type: cvox.SemanticAttr.Type.RELATION, + role: cvox.SemanticAttr.Role.INEQUALITY }, - {set: this.relations, - type: cvox.SemanticAttr.Type.RELATION, - role: cvox.SemanticAttr.Role.UNKNOWN + { + set: this.relations, + type: cvox.SemanticAttr.Type.RELATION, + role: cvox.SemanticAttr.Role.UNKNOWN }, - {set: this.arrows, - type: cvox.SemanticAttr.Type.RELATION, - role: cvox.SemanticAttr.Role.ARROW + { + set: this.arrows, + type: cvox.SemanticAttr.Type.RELATION, + role: cvox.SemanticAttr.Role.ARROW }, // Large operators - {set: this.sumOps, - type: cvox.SemanticAttr.Type.LARGEOP, - role: cvox.SemanticAttr.Role.SUM}, - {set: this.intOps, - type: cvox.SemanticAttr.Type.LARGEOP, - role: cvox.SemanticAttr.Role.INTEGRAL}, + { + set: this.sumOps, + type: cvox.SemanticAttr.Type.LARGEOP, + role: cvox.SemanticAttr.Role.SUM + }, + { + set: this.intOps, + type: cvox.SemanticAttr.Type.LARGEOP, + role: cvox.SemanticAttr.Role.INTEGRAL + }, // Functions - {set: this.limitFunctions, - type: cvox.SemanticAttr.Type.FUNCTION, - role: cvox.SemanticAttr.Role.LIMFUNC}, - {set: this.prefixFunctions, - type: cvox.SemanticAttr.Type.FUNCTION, - role: cvox.SemanticAttr.Role.PREFIXFUNC}, - {set: this.infixFunctions, - type: cvox.SemanticAttr.Type.OPERATOR, - role: cvox.SemanticAttr.Role.MULTIPLICATION - } - // TODO (sorge) Add some of the remaining elements. + { + set: this.limitFunctions, + type: cvox.SemanticAttr.Type.FUNCTION, + role: cvox.SemanticAttr.Role.LIMFUNC + }, + { + set: this.prefixFunctions, + type: cvox.SemanticAttr.Type.FUNCTION, + role: cvox.SemanticAttr.Role.PREFIXFUNC + }, + { + set: this.infixFunctions, + type: cvox.SemanticAttr.Type.OPERATOR, + role: cvox.SemanticAttr.Role.MULTIPLICATION + } // TODO (sorge) Add some of the remaining elements. ]; }; goog.addSingletonGetter(cvox.SemanticAttr); @@ -1262,11 +1285,11 @@ ELLIPSIS: 'ellipsis', FULLSTOP: 'fullstop', DASH: 'dash', - PRIME: 'prime', // Superscript. - VBAR: 'vbar', // A vertical bar. + PRIME: 'prime', // Superscript. + VBAR: 'vbar', // A vertical bar. OPENFENCE: 'openfence', CLOSEFENCE: 'closefence', - APPLICATION: 'application', // Function Application. + APPLICATION: 'application', // Function Application. // Fences. OPEN: 'open', @@ -1433,11 +1456,11 @@ */ cvox.SemanticAttr.isMatchingFenceRole = function(open, close) { return (open == cvox.SemanticAttr.Role.OPEN && - close == cvox.SemanticAttr.Role.CLOSE) || - (open == cvox.SemanticAttr.Role.NEUTRAL && - close == cvox.SemanticAttr.Role.NEUTRAL) || - (open == cvox.SemanticAttr.Role.TOP && - close == cvox.SemanticAttr.Role.BOTTOM); + close == cvox.SemanticAttr.Role.CLOSE) || + (open == cvox.SemanticAttr.Role.NEUTRAL && + close == cvox.SemanticAttr.Role.NEUTRAL) || + (open == cvox.SemanticAttr.Role.TOP && + close == cvox.SemanticAttr.Role.BOTTOM); }; @@ -1459,8 +1482,9 @@ * @return {boolean} True if the fence is open or neutral. */ cvox.SemanticAttr.isOpeningFence = function(fence) { - return (fence == cvox.SemanticAttr.Role.OPEN || - fence == cvox.SemanticAttr.Role.NEUTRAL); + return ( + fence == cvox.SemanticAttr.Role.OPEN || + fence == cvox.SemanticAttr.Role.NEUTRAL); }; @@ -1470,8 +1494,9 @@ * @return {boolean} True if the fence is close or neutral. */ cvox.SemanticAttr.isClosingFence = function(fence) { - return (fence == cvox.SemanticAttr.Role.CLOSE || - fence == cvox.SemanticAttr.Role.NEUTRAL); + return ( + fence == cvox.SemanticAttr.Role.CLOSE || + fence == cvox.SemanticAttr.Role.NEUTRAL); }; @@ -1482,8 +1507,8 @@ * @return {boolean} True if the character is indeed a single small d. */ cvox.SemanticAttr.isCharacterD = function(chr) { - var Ds = ['d', 'ⅆ', 'd', '𝐝', '𝑑', '𝒹', '𝓭', '𝔡', - '𝕕', '𝖉', '𝖽', '𝗱', '𝘥', '𝚍']; + var Ds = + ['d', 'ⅆ', 'd', '𝐝', '𝑑', '𝒹', '𝓭', '𝔡', '𝕕', '𝖉', '𝖽', '𝗱', '𝘥', '𝚍']; return Ds.indexOf(chr) != -1; }; @@ -1516,14 +1541,16 @@ cvox.SemanticAttr.prototype.lookupMeaning_ = function(symbol) { for (var i = 0, set; set = this.symbolSetToSemantic_[i]; i++) { if (set.set.indexOf(symbol) != -1) { - return {role: set.role || cvox.SemanticAttr.Role.UNKNOWN, - type: set.type || cvox.SemanticAttr.Type.UNKNOWN, - font: set.font || cvox.SemanticAttr.Font.UNKNOWN - }; + return { + role: set.role || cvox.SemanticAttr.Role.UNKNOWN, + type: set.type || cvox.SemanticAttr.Type.UNKNOWN, + font: set.font || cvox.SemanticAttr.Font.UNKNOWN + }; } } - return {role: cvox.SemanticAttr.Role.UNKNOWN, - type: cvox.SemanticAttr.Type.UNKNOWN, - font: cvox.SemanticAttr.Font.UNKNOWN - }; + return { + role: cvox.SemanticAttr.Role.UNKNOWN, + type: cvox.SemanticAttr.Type.UNKNOWN, + font: cvox.SemanticAttr.Font.UNKNOWN + }; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_tree.js b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_tree.js index daf76719..bcddbde 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_tree.js +++ b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_tree.js
@@ -98,61 +98,63 @@ }; - /** - * Returns an XML representation of the tree. - * @param {boolean=} brief If set attributes are omitted. - * @return {Node} The XML representation of the tree. - */ - cvox.SemanticTree.prototype.xml = function(brief) { - var dp = new DOMParser(); - var xml = dp.parseFromString('<stree></stree>', 'text/xml'); +/** + * Returns an XML representation of the tree. + * @param {boolean=} brief If set attributes are omitted. + * @return {Node} The XML representation of the tree. + */ +cvox.SemanticTree.prototype.xml = function(brief) { + var dp = new DOMParser(); + var xml = dp.parseFromString('<stree></stree>', 'text/xml'); - var xmlRoot = this.root.xml(xml, brief); - xml.childNodes[0].appendChild(xmlRoot); + var xmlRoot = this.root.xml(xml, brief); + xml.childNodes[0].appendChild(xmlRoot); - return xml.childNodes[0]; - }; - - - /** - * An XML tree representation of the current node. - * @param {Document} xml The XML document. - * @param {boolean=} brief If set attributes are omitted. - * @return {Node} The XML representation of the node. - */ - cvox.SemanticTree.Node.prototype.xml = function(xml, brief) { - /** - * Translates a list of nodes into XML representation. - * @param {string} tag Name of the enclosing tag. - * @param {!Array<!cvox.SemanticTree.Node>} nodes A list of nodes. - * @return {Node} An XML representation of the node list. - */ - var xmlNodeList = function(tag, nodes) { - var xmlNodes = nodes.map(function(x) {return x.xml(xml, brief);}); - var tagNode = xml.createElement(tag); - for (var i = 0, child; child = xmlNodes[i]; i++) { - tagNode.appendChild(child); - } - return tagNode; - }; - var node = xml.createElement(this.type); - if (!brief) { - this.xmlAttributes_(node); - } - node.textContent = this.textContent; - if (this.contentNodes.length > 0) { - node.appendChild(xmlNodeList('content', this.contentNodes)); - } - if (this.childNodes.length > 0) { - node.appendChild(xmlNodeList('children', this.childNodes)); - } - return node; - }; + return xml.childNodes[0]; +}; /** - * Serializes the XML representation of the tree. - * @param {boolean=} brief If set attributes are omitted. + * An XML tree representation of the current node. + * @param {Document} xml The XML document. + * @param {boolean=} brief If set attributes are omitted. + * @return {Node} The XML representation of the node. + */ +cvox.SemanticTree.Node.prototype.xml = function(xml, brief) { + /** + * Translates a list of nodes into XML representation. + * @param {string} tag Name of the enclosing tag. + * @param {!Array<!cvox.SemanticTree.Node>} nodes A list of nodes. + * @return {Node} An XML representation of the node list. + */ + var xmlNodeList = function(tag, nodes) { + var xmlNodes = nodes.map(function(x) { + return x.xml(xml, brief); + }); + var tagNode = xml.createElement(tag); + for (var i = 0, child; child = xmlNodes[i]; i++) { + tagNode.appendChild(child); + } + return tagNode; + }; + var node = xml.createElement(this.type); + if (!brief) { + this.xmlAttributes_(node); + } + node.textContent = this.textContent; + if (this.contentNodes.length > 0) { + node.appendChild(xmlNodeList('content', this.contentNodes)); + } + if (this.childNodes.length > 0) { + node.appendChild(xmlNodeList('children', this.childNodes)); + } + return node; +}; + + +/** + * Serializes the XML representation of the tree. + * @param {boolean=} brief If set attributes are omitted. * @return {string} Serialized string. */ cvox.SemanticTree.prototype.toString = function(brief) { @@ -184,26 +186,25 @@ xml = xml.replace(reg, '$1\r\n$2\r\n$3'); var formatted = ''; var padding = ''; - xml.split('\r\n') - .forEach(function(node) { - if (node.match(/.+<\/\w[^>]*>$/)) { - // Node with content. - formatted += padding + node + '\r\n'; - } else if (node.match(/^<\/\w/)) { - if (padding) { - // Closing tag - padding = padding.slice(2); - formatted += padding + node + '\r\n'; - } - } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) { - // Opening tag - formatted += padding + node + '\r\n'; - padding += ' '; - } else { - // Empty tag - formatted += padding + node + '\r\n'; - } - }); + xml.split('\r\n').forEach(function(node) { + if (node.match(/.+<\/\w[^>]*>$/)) { + // Node with content. + formatted += padding + node + '\r\n'; + } else if (node.match(/^<\/\w/)) { + if (padding) { + // Closing tag + padding = padding.slice(2); + formatted += padding + node + '\r\n'; + } + } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) { + // Opening tag + formatted += padding + node + '\r\n'; + padding += ' '; + } else { + // Empty tag + formatted += padding + node + '\r\n'; + } + }); return formatted; }; @@ -341,10 +342,12 @@ // To not mess up the order of MathML elements more than necessary, we only // remove and add difference lists. The hope is that we might end up with // little change. - var removeMathml = oldNode.mathml.filter( - function(x) {return newNode.mathml.indexOf(x) == -1;}); - var addMathml = newNode.mathml.filter( - function(x) {return oldNode.mathml.indexOf(x) == -1;}); + var removeMathml = oldNode.mathml.filter(function(x) { + return newNode.mathml.indexOf(x) == -1; + }); + var addMathml = newNode.mathml.filter(function(x) { + return oldNode.mathml.indexOf(x) == -1; + }); this.removeMathmlNodes_(removeMathml); this.addMathmlNodes_(addMathml); }; @@ -396,16 +399,15 @@ children = cvox.SemanticUtil.purgeNodes(children); // Single child node, i.e. the row is meaningless. if (children.length == 1) { - return this.parseMathml_(/** @type {!Element} */(children[0])); + return this.parseMathml_(/** @type {!Element} */ (children[0])); } // Case of a 'meaningful' row, even if they are empty. return this.processRow_(this.parseMathmlChildren_(children)); - break; + break; case 'MFRAC': var newNode = this.makeBranchNode_( cvox.SemanticAttr.Type.FRACTION, - [this.parseMathml_(children[0]), this.parseMathml_(children[1])], - []); + [this.parseMathml_(children[0]), this.parseMathml_(children[1])], []); newNode.role = cvox.SemanticAttr.Role.DIVISION; return newNode; break; @@ -415,40 +417,38 @@ case 'MOVER': case 'MUNDER': case 'MUNDEROVER': - return this.makeLimitNode_(cvox.SemanticUtil.tagName(mml), - this.parseMathmlChildren_(children)); + return this.makeLimitNode_( + cvox.SemanticUtil.tagName(mml), this.parseMathmlChildren_(children)); break; case 'MROOT': return this.makeBranchNode_( cvox.SemanticAttr.Type.ROOT, - [this.parseMathml_(children[0]), this.parseMathml_(children[1])], - []); + [this.parseMathml_(children[0]), this.parseMathml_(children[1])], []); break; case 'MSQRT': - children = this.parseMathmlChildren_( - cvox.SemanticUtil.purgeNodes(children)); + children = + this.parseMathmlChildren_(cvox.SemanticUtil.purgeNodes(children)); return this.makeBranchNode_( cvox.SemanticAttr.Type.SQRT, [this.processRow_(children)], []); break; case 'MTABLE': newNode = this.makeBranchNode_( - cvox.SemanticAttr.Type.TABLE, - this.parseMathmlChildren_(children), []); + cvox.SemanticAttr.Type.TABLE, this.parseMathmlChildren_(children), + []); if (cvox.SemanticTree.tableIsMultiline_(newNode)) { this.tableToMultiline_(newNode); - } + } return newNode; break; case 'MTR': newNode = this.makeBranchNode_( - cvox.SemanticAttr.Type.ROW, - this.parseMathmlChildren_(children), []); + cvox.SemanticAttr.Type.ROW, this.parseMathmlChildren_(children), []); newNode.role = cvox.SemanticAttr.Role.TABLE; return newNode; break; case 'MTD': - children = this.parseMathmlChildren_( - cvox.SemanticUtil.purgeNodes(children)); + children = + this.parseMathmlChildren_(cvox.SemanticUtil.purgeNodes(children)); newNode = this.makeBranchNode_( cvox.SemanticAttr.Type.CELL, [this.processRow_(children)], []); newNode.role = cvox.SemanticAttr.Role.TABLE; @@ -485,7 +485,7 @@ break; // TODO (sorge) Do something useful with error and phantom symbols. default: - // Ordinarilly at this point we should not get any other tag. + // Ordinarilly at this point we should not get any other tag. return this.makeUnprocessed_(mml); } }; @@ -564,12 +564,10 @@ node.type = type; node.childNodes = children; node.contentNodes = contentNodes; - children.concat(contentNodes) - .forEach( - function(x) { - x.parent = node; - node.addMathmlNodes_(x.mathml); - }); + children.concat(contentNodes).forEach(function(x) { + x.parent = node; + node.addMathmlNodes_(x.mathml); + }); return node; }; @@ -584,7 +582,7 @@ cvox.SemanticTree.prototype.makeImplicitNode_ = function(nodes) { if (nodes.length == 1) { return nodes[0]; - } + } var operator = this.createNode_(); // For now we assume this is a multiplication using invisible times. operator.updateContent_(cvox.SemanticAttr.invisibleTimes()); @@ -621,7 +619,11 @@ if (nodeList.length == 0) { return inner; } - var content = nodeList.map(function(x) {return x.textContent;}).join(' '); + var content = nodeList + .map(function(x) { + return x.textContent; + }) + .join(' '); var newNode = this.makeBranchNode_(type, [inner], nodeList, content); if (nodeList.length > 0) { newNode.role = cvox.SemanticAttr.Role.MULTIOP; @@ -717,10 +719,11 @@ if (nodes.length == 1) { return nodes[0]; } - var children = partition.comp.map( - goog.bind(this.processOperationsInRow_, this)); - if (partition.rel.every( - function(x) {return x.textContent == firstRel.textContent;})) { + var children = + partition.comp.map(goog.bind(this.processOperationsInRow_, this)); + if (partition.rel.every(function(x) { + return x.textContent == firstRel.textContent; + })) { return this.makeBranchNode_( cvox.SemanticAttr.Type.RELSEQ, children, partition.rel, firstRel.textContent); @@ -745,8 +748,7 @@ } var prefix = []; - while (nodes.length > 0 && - nodes[0].type == cvox.SemanticAttr.Type.OPERATOR) { + while (nodes.length > 0 && nodes[0].type == cvox.SemanticAttr.Type.OPERATOR) { prefix.push(nodes.shift()); } // Pathological case: only operators in row. @@ -810,8 +812,7 @@ return this.makeOperationsTree_(split.tail, root, lastop, prefixes); } - var node = this.makePrefixNode_( - this.makeImplicitNode_(split.head), prefixes); + var node = this.makePrefixNode_(this.makeImplicitNode_(split.head), prefixes); var newNode = this.appendOperand_(root, lastop, node); if (!split.div) { return newNode; @@ -841,7 +842,7 @@ } return op.role == cvox.SemanticAttr.Role.MULTIPLICATION ? this.appendMultiplicativeOp_(root, op, node) : - this.appendAdditiveOp_(root, op, node); + this.appendAdditiveOp_(root, op, node); }; @@ -900,8 +901,7 @@ this.appendExistingOperator_( // Again, if this is an INFIXOP node, we know it has a child! /** @type {!cvox.SemanticTree.Node} */ - (root.childNodes[root.childNodes.length - 1]), - op, node); + (root.childNodes[root.childNodes.length - 1]), op, node); return false; }; @@ -946,11 +946,11 @@ * @private */ cvox.SemanticTree.prototype.processFences_ = function( - fences, content, openStack, contentStack) { + fences, content, openStack, contentStack) { // Base case 1: Everything is used up. if (fences.length == 0 && openStack.length == 0) { return contentStack[0]; - } + } var openPred = cvox.SemanticTree.attrPred_('role', 'OPEN'); // Base case 2: Only open and neutral fences are left on the stack. if (fences.length == 0) { @@ -979,9 +979,9 @@ var innerNodes = this.processNeutralFences_( split.head, contentStack.slice(0, cutLength)); contentStack = contentStack.slice(cutLength); - //var rightContent = contentStack.shift(); + // var rightContent = contentStack.shift(); result.push.apply(result, innerNodes); - //result.push.apply(result, rightContent); + // result.push.apply(result, rightContent); if (split.div) { split.tail.unshift(split.div); } @@ -997,21 +997,21 @@ // Either we have an open fence. if (firstRole == cvox.SemanticAttr.Role.OPEN || // Or we have a neutral fence that does not have a counter part. - (firstRole == cvox.SemanticAttr.Role.NEUTRAL && - (!lastOpen || - fences[0].textContent != lastOpen.textContent))) { + (firstRole == cvox.SemanticAttr.Role.NEUTRAL && + (!lastOpen || fences[0].textContent != lastOpen.textContent))) { openStack.push(fences.shift()); contentStack.push(content.shift()); return this.processFences_(fences, content, openStack, contentStack); } // General closing case. - if (lastOpen && ( - // Closing fence for some opening fence. - (firstRole == cvox.SemanticAttr.Role.CLOSE && - lastOpen.role == cvox.SemanticAttr.Role.OPEN) || - // Netural fence with exact counter part. - (firstRole == cvox.SemanticAttr.Role.NEUTRAL && - fences[0].textContent == lastOpen.textContent))) { + if (lastOpen && + ( + // Closing fence for some opening fence. + (firstRole == cvox.SemanticAttr.Role.CLOSE && + lastOpen.role == cvox.SemanticAttr.Role.OPEN) || + // Netural fence with exact counter part. + (firstRole == cvox.SemanticAttr.Role.NEUTRAL && + fences[0].textContent == lastOpen.textContent))) { var fenced = this.makeHorizontalFencedNode_( openStack.pop(), fences.shift(), contentStack.pop()); contentStack.push(contentStack.pop().concat([fenced], content.shift())); @@ -1020,7 +1020,7 @@ // Closing with a neutral fence on the stack. if (lastOpen && firstRole == cvox.SemanticAttr.Role.CLOSE && lastOpen.role == cvox.SemanticAttr.Role.NEUTRAL && - openStack.some(openPred)) { + openStack.some(openPred)) { // Steps of the algorithm: // 1. Split list at right most opening bracket. // 2. Cut content list at corresponding length. @@ -1037,8 +1037,8 @@ // shift of content. var rightContent = contentStack.pop(); var cutLength = contentStack.length - split.tail.length + 1; - var innerNodes = this.processNeutralFences_( - split.tail, contentStack.slice(cutLength)); + var innerNodes = + this.processNeutralFences_(split.tail, contentStack.slice(cutLength)); contentStack = contentStack.slice(0, cutLength); var fenced = this.makeHorizontalFencedNode_( split.div, fences.shift(), @@ -1072,18 +1072,19 @@ if (fences.length == 1) { cvox.SemanticTree.fenceToPunct_(fences[0]); return fences; - } + } var firstFence = fences.shift(); - var split = cvox.SemanticTree.sliceNodes_( - fences, function(x) {return x.textContent == firstFence.textContent;}); + var split = cvox.SemanticTree.sliceNodes_(fences, function(x) { + return x.textContent == firstFence.textContent; + }); if (!split.div) { cvox.SemanticTree.fenceToPunct_(firstFence); var restContent = content.shift(); restContent.unshift(firstFence); return restContent.concat(this.processNeutralFences_(fences, content)); } - var newContent = this.combineFencedContent_( - firstFence, split.div, split.head, content); + var newContent = + this.combineFencedContent_(firstFence, split.div, split.head, content); if (split.tail.length > 0) { var leftContent = newContent.shift(); var result = this.processNeutralFences_(split.tail, newContent); @@ -1114,8 +1115,8 @@ leftFence, rightFence, midFences, content) { if (midFences.length == 0) { - var fenced = this.makeHorizontalFencedNode_( - leftFence, rightFence, content.shift()); + var fenced = + this.makeHorizontalFencedNode_(leftFence, rightFence, content.shift()); content.unshift(fenced); return content; } @@ -1128,15 +1129,15 @@ var innerNodes = this.processNeutralFences_(midFences, midContent); leftContent.push.apply(leftContent, innerNodes); leftContent.push.apply(leftContent, rightContent); - var fenced = this.makeHorizontalFencedNode_( - leftFence, rightFence, leftContent); + var fenced = + this.makeHorizontalFencedNode_(leftFence, rightFence, leftContent); if (content.length > 0) { content[0].unshift(fenced); } else { content = [[fenced]]; } return content; - }; +}; /** @@ -1148,14 +1149,14 @@ fence.type = cvox.SemanticAttr.Type.PUNCTUATION; switch (fence.role) { case cvox.SemanticAttr.Role.NEUTRAL: - fence.role = cvox.SemanticAttr.Role.VBAR; - break; + fence.role = cvox.SemanticAttr.Role.VBAR; + break; case cvox.SemanticAttr.Role.OPEN: - fence.role = cvox.SemanticAttr.Role.OPENFENCE; - break; + fence.role = cvox.SemanticAttr.Role.OPENFENCE; + break; case cvox.SemanticAttr.Role.CLOSE: - fence.role = cvox.SemanticAttr.Role.CLOSEFENCE; - break; + fence.role = cvox.SemanticAttr.Role.CLOSEFENCE; + break; } }; @@ -1194,10 +1195,10 @@ // similar to an mrow. The only exception are ellipses, which we assume to be // in lieu of identifiers. // In addition we keep the single punctuation nodes as content. - var partition = cvox.SemanticTree.partitionNodes_( - nodes, function(x) { - return cvox.SemanticTree.attrPred_('type', 'PUNCTUATION')(x) && - !cvox.SemanticTree.attrPred_('role', 'ELLIPSIS')(x);}); + var partition = cvox.SemanticTree.partitionNodes_(nodes, function(x) { + return cvox.SemanticTree.attrPred_('type', 'PUNCTUATION')(x) && + !cvox.SemanticTree.attrPred_('role', 'ELLIPSIS')(x); + }); if (partition.rel.length == 0) { return nodes; } @@ -1235,7 +1236,8 @@ if (punctuations.length == 1 && nodes[0].type == cvox.SemanticAttr.Type.PUNCTUATION) { newNode.role = cvox.SemanticAttr.Role.STARTPUNCT; - } else if (punctuations.length == 1 && + } else if ( + punctuations.length == 1 && nodes[nodes.length - 1].type == cvox.SemanticAttr.Type.PUNCTUATION) { newNode.role = cvox.SemanticAttr.Role.ENDPUNCT; } else { @@ -1269,46 +1271,46 @@ switch (mmlTag) { case 'MSUB': case 'MUNDER': - type = cvox.SemanticAttr.Type.LIMLOWER; - break; + type = cvox.SemanticAttr.Type.LIMLOWER; + break; case 'MSUP': case 'MOVER': - type = cvox.SemanticAttr.Type.LIMUPPER; - break; + type = cvox.SemanticAttr.Type.LIMUPPER; + break; case 'MSUBSUP': case 'MUNDEROVER': - type = cvox.SemanticAttr.Type.LIMBOTH; - break; + type = cvox.SemanticAttr.Type.LIMBOTH; + break; } } else { switch (mmlTag) { case 'MSUB': - type = cvox.SemanticAttr.Type.SUBSCRIPT; - break; + type = cvox.SemanticAttr.Type.SUBSCRIPT; + break; case 'MSUP': - type = cvox.SemanticAttr.Type.SUPERSCRIPT; - break; + type = cvox.SemanticAttr.Type.SUPERSCRIPT; + break; case 'MSUBSUP': - var innerNode = this.makeBranchNode_(cvox.SemanticAttr.Type.SUBSCRIPT, - [center, children[1]], []); - innerNode.role = center.role; - children = [innerNode, children[2]]; - type = cvox.SemanticAttr.Type.SUPERSCRIPT; - break; + var innerNode = this.makeBranchNode_( + cvox.SemanticAttr.Type.SUBSCRIPT, [center, children[1]], []); + innerNode.role = center.role; + children = [innerNode, children[2]]; + type = cvox.SemanticAttr.Type.SUPERSCRIPT; + break; case 'MOVER': - type = cvox.SemanticAttr.Type.OVERSCORE; - break; + type = cvox.SemanticAttr.Type.OVERSCORE; + break; case 'MUNDER': - type = cvox.SemanticAttr.Type.UNDERSCORE; - break; + type = cvox.SemanticAttr.Type.UNDERSCORE; + break; case 'MUNDEROVER': default: - var innerNode = this.makeBranchNode_(cvox.SemanticAttr.Type.UNDERSCORE, - [center, children[1]], []); - innerNode.role = center.role; - children = [innerNode, children[2]]; - type = cvox.SemanticAttr.Type.OVERSCORE; - break; + var innerNode = this.makeBranchNode_( + cvox.SemanticAttr.Type.UNDERSCORE, [center, children[1]], []); + innerNode.role = center.role; + children = [innerNode, children[2]]; + type = cvox.SemanticAttr.Type.OVERSCORE; + break; } } var newNode = this.makeBranchNode_(type, children, []); @@ -1371,7 +1373,7 @@ // We do not allow double function application. This is not lambda calculus! if (funcNode.type == cvox.SemanticAttr.Type.APPL || funcNode.type == cvox.SemanticAttr.Type.BIGOP || - funcNode.type == cvox.SemanticAttr.Type.INTEGRAL) { + funcNode.type == cvox.SemanticAttr.Type.INTEGRAL) { return ''; } // Find and remove explicit function applications. @@ -1387,19 +1389,19 @@ } switch (funcNode.role) { case cvox.SemanticAttr.Role.INTEGRAL: - return 'integral'; - break; + return 'integral'; + break; case cvox.SemanticAttr.Role.SUM: - return 'bigop'; - break; + return 'bigop'; + break; case cvox.SemanticAttr.Role.PREFIXFUNC: case cvox.SemanticAttr.Role.LIMFUNC: - return 'prefix'; - break; + return 'prefix'; + break; default: - if (funcNode.type == cvox.SemanticAttr.Type.IDENTIFIER) { - return 'simple'; - } + if (funcNode.type == cvox.SemanticAttr.Type.IDENTIFIER) { + return 'simple'; + } } return ''; }; @@ -1433,50 +1435,50 @@ cvox.SemanticTree.prototype.getFunctionArgs_ = function(func, rest, heuristic) { switch (heuristic) { case 'integral': - var components = this.getIntegralArgs_(rest); - var integrand = this.processRow_(components.integrand); - var funcNode = this.makeIntegralNode_(func, integrand, components.intvar); - components.rest.unshift(funcNode); - return components.rest; - break; + var components = this.getIntegralArgs_(rest); + var integrand = this.processRow_(components.integrand); + var funcNode = this.makeIntegralNode_(func, integrand, components.intvar); + components.rest.unshift(funcNode); + return components.rest; + break; case 'prefix': - if (rest[0] && rest[0].type == cvox.SemanticAttr.Type.FENCED) { - funcNode = this.makeFunctionNode_( - func, /** @type {!cvox.SemanticTree.Node} */ (rest.shift())); - rest.unshift(funcNode); - return rest; - } + if (rest[0] && rest[0].type == cvox.SemanticAttr.Type.FENCED) { + funcNode = this.makeFunctionNode_( + func, /** @type {!cvox.SemanticTree.Node} */ (rest.shift())); + rest.unshift(funcNode); + return rest; + } case 'bigop': - var partition = cvox.SemanticTree.sliceNodes_( - rest, cvox.SemanticTree.prefixFunctionBoundary_); - var arg = this.processRow_(partition.head); - if (heuristic == 'prefix') { - funcNode = this.makeFunctionNode_(func, arg); - } else { - funcNode = this.makeBigOpNode_(func, arg); - } - if (partition.div) { - partition.tail.unshift(partition.div); - } - partition.tail.unshift(funcNode); - return partition.tail; - break; + var partition = cvox.SemanticTree.sliceNodes_( + rest, cvox.SemanticTree.prefixFunctionBoundary_); + var arg = this.processRow_(partition.head); + if (heuristic == 'prefix') { + funcNode = this.makeFunctionNode_(func, arg); + } else { + funcNode = this.makeBigOpNode_(func, arg); + } + if (partition.div) { + partition.tail.unshift(partition.div); + } + partition.tail.unshift(funcNode); + return partition.tail; + break; case 'simple': - if (rest.length == 0) { - return [func]; - } - var firstArg = rest[0]; - if (firstArg.type == cvox.SemanticAttr.Type.FENCED && - firstArg.role != cvox.SemanticAttr.Role.NEUTRAL && - this.simpleFunctionHeuristic_(firstArg)) { - funcNode = this.makeFunctionNode_( - func, /** @type {!cvox.SemanticTree.Node} */ (rest.shift())); - rest.unshift(funcNode); + if (rest.length == 0) { + return [func]; + } + var firstArg = rest[0]; + if (firstArg.type == cvox.SemanticAttr.Type.FENCED && + firstArg.role != cvox.SemanticAttr.Role.NEUTRAL && + this.simpleFunctionHeuristic_(firstArg)) { + funcNode = this.makeFunctionNode_( + func, /** @type {!cvox.SemanticTree.Node} */ (rest.shift())); + rest.unshift(funcNode); + return rest; + } + rest.unshift(func); return rest; - } - rest.unshift(func); - return rest; - break; + break; } return []; }; @@ -1509,8 +1511,8 @@ if (nodes[1] && cvox.SemanticTree.integralDxBoundary_(firstNode, nodes[1])) { var comma = this.createNode_(); comma.updateContent_(cvox.SemanticAttr.invisibleComma()); - var intvar = this.makePunctuatedNode_( - [firstNode, comma, nodes[1]], [comma]); + var intvar = + this.makePunctuatedNode_([firstNode, comma, nodes[1]], [comma]); intvar.role = cvox.SemanticAttr.Role.INTEGRAL; return {integrand: args, intvar: intvar, rest: nodes.slice(2)}; } @@ -1531,8 +1533,8 @@ applNode.updateContent_(cvox.SemanticAttr.functionApplication()); applNode.type = cvox.SemanticAttr.Type.PUNCTUATION; applNode.role = cvox.SemanticAttr.Role.APPLICATION; - var newNode = this.makeBranchNode_(cvox.SemanticAttr.Type.APPL, [func, arg], - [applNode]); + var newNode = this.makeBranchNode_( + cvox.SemanticAttr.Type.APPL, [func, arg], [applNode]); newNode.role = func.role; return newNode; }; @@ -1546,8 +1548,8 @@ * @private */ cvox.SemanticTree.prototype.makeBigOpNode_ = function(bigOp, arg) { - var newNode = this.makeBranchNode_( - cvox.SemanticAttr.Type.BIGOP, [bigOp, arg], []); + var newNode = + this.makeBranchNode_(cvox.SemanticAttr.Type.BIGOP, [bigOp, arg], []); newNode.role = bigOp.role; return newNode; }; @@ -1566,8 +1568,8 @@ integral, integrand, intvar) { integrand = integrand || this.makeEmptyNode_(); intvar = intvar || this.makeEmptyNode_(); - var newNode = this.makeBranchNode_(cvox.SemanticAttr.Type.INTEGRAL, - [integral, integrand, intvar], []); + var newNode = this.makeBranchNode_( + cvox.SemanticAttr.Type.INTEGRAL, [integral, integrand, intvar], []); newNode.role = integral.role; return newNode; }; @@ -1625,11 +1627,10 @@ * @return {boolean} True if the second node exists and the first node is a 'd'. * @private */ -cvox.SemanticTree.integralDxBoundary_ = function( - firstNode, secondNode) { +cvox.SemanticTree.integralDxBoundary_ = function(firstNode, secondNode) { return !!secondNode && cvox.SemanticTree.attrPred_('type', 'IDENTIFIER')(secondNode) && - cvox.SemanticAttr.isCharacterD(firstNode.textContent); + cvox.SemanticAttr.isCharacterD(firstNode.textContent); }; @@ -1704,8 +1705,9 @@ * @private */ cvox.SemanticTree.isTableOrMultiline_ = function(node) { - return !!node && (cvox.SemanticTree.attrPred_('type', 'TABLE')(node) || - cvox.SemanticTree.attrPred_('type', 'MULTILINE')(node)); + return !!node && + (cvox.SemanticTree.attrPred_('type', 'TABLE')(node) || + cvox.SemanticTree.attrPred_('type', 'MULTILINE')(node)); }; @@ -1719,8 +1721,8 @@ cvox.SemanticTree.tableIsMatrixOrVector_ = function(node) { return !!node && cvox.SemanticTree.attrPred_('type', 'FENCED')(node) && cvox.SemanticTree.attrPred_('role', 'LEFTRIGHT')(node) && - node.childNodes.length == 1 && - cvox.SemanticTree.isTableOrMultiline_(node.childNodes[0]); + node.childNodes.length == 1 && + cvox.SemanticTree.isTableOrMultiline_(node.childNodes[0]); }; @@ -1733,7 +1735,8 @@ cvox.SemanticTree.prototype.tableToMatrixOrVector_ = function(node) { var matrix = node.childNodes[0]; var type = cvox.SemanticTree.attrPred_('type', 'MULTILINE')(matrix) ? - 'VECTOR' : 'MATRIX'; + 'VECTOR' : + 'MATRIX'; matrix.type = cvox.SemanticAttr.Type[type]; node.contentNodes.forEach(goog.bind(matrix.appendContentNode_, matrix)); for (var i = 0, row; row = matrix.childNodes[i]; i++) { @@ -1753,8 +1756,8 @@ */ cvox.SemanticTree.tableIsCases_ = function(table, prevNodes) { return prevNodes.length > 0 && - cvox.SemanticTree.attrPred_('role', 'OPENFENCE')( - prevNodes[prevNodes.length - 1]); + cvox.SemanticTree.attrPred_( + 'role', 'OPENFENCE')(prevNodes[prevNodes.length - 1]); }; @@ -1790,10 +1793,10 @@ * @private */ cvox.SemanticTree.tableIsMultiline_ = function(table) { - return table.childNodes.every( - function(row) { - var length = row.childNodes.length; - return length <= 1;}); + return table.childNodes.every(function(row) { + var length = row.childNodes.length; + return length <= 1; + }); }; @@ -1821,7 +1824,7 @@ role = role || cvox.SemanticAttr.Role.UNKNOWN; if (cvox.SemanticTree.attrPred_('type', 'ROW')(row) && row.childNodes.length == 1 && - cvox.SemanticTree.attrPred_('type', 'CELL')(row.childNodes[0])) { + cvox.SemanticTree.attrPred_('type', 'CELL')(row.childNodes[0])) { row.type = cvox.SemanticAttr.Type.LINE; row.role = role; row.childNodes = row.childNodes[0].childNodes; @@ -1871,13 +1874,13 @@ for (var i = 0, node; node = nodes[i]; i++) { if (pred(node)) { if (reverse) { - return {head: nodes.slice(i + 1).reverse(), - div: node, - tail: head.reverse()}; + return { + head: nodes.slice(i + 1).reverse(), + div: node, + tail: head.reverse() + }; } - return {head: head, - div: node, - tail: nodes.slice(i + 1)}; + return {head: head, div: node, tail: nodes.slice(i + 1)}; } head.push(node); } @@ -1931,11 +1934,16 @@ cvox.SemanticTree.attrPred_ = function(prop, attr) { var getAttr = function(prop) { switch (prop) { - case 'type': return cvox.SemanticAttr.Type[attr]; - case 'role': return cvox.SemanticAttr.Role[attr]; - case 'font': return cvox.SemanticAttr.Font[attr]; + case 'type': + return cvox.SemanticAttr.Type[attr]; + case 'role': + return cvox.SemanticAttr.Role[attr]; + case 'font': + return cvox.SemanticAttr.Font[attr]; } }; - return function(node) {return node[prop] == getAttr(prop);}; + return function(node) { + return node[prop] == getAttr(prop); + }; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_util.js b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_util.js index 8d996874..227efdf23 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/math_semantic_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/math_semantic_util.js
@@ -12,7 +12,7 @@ /** * @constructor */ -cvox.SemanticUtil = function() { }; +cvox.SemanticUtil = function() {}; /** @@ -125,10 +125,11 @@ var nodeArray = []; for (var i = 0, node; node = nodes[i]; i++) { var tagName = cvox.SemanticUtil.tagName(node); - if (cvox.SemanticUtil.IGNORETAGS.indexOf(tagName) != -1) continue; + if (cvox.SemanticUtil.IGNORETAGS.indexOf(tagName) != -1) + continue; if (cvox.SemanticUtil.EMPTYTAGS.indexOf(tagName) != -1 && node.childNodes.length == 0) - continue; + continue; nodeArray.push(node); } return nodeArray;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/math_util.js b/chrome/browser/resources/chromeos/chromevox/common/math_util.js index 4de27ae..1a56479 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/math_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/math_util.js
@@ -34,8 +34,9 @@ cvox.MathUtil.isMathjaxNodeOfClass_ = function(node, tags) { if (node.tagName == 'SPAN') { var classes = node.className.split(' '); - return classes.some(function(x) - {return tags.indexOf(x.toUpperCase()) != -1;}); + return classes.some(function(x) { + return tags.indexOf(x.toUpperCase()) != -1; + }); } return false; }; @@ -50,9 +51,10 @@ * @return {boolean} True if node has a tag name included in tags. */ cvox.MathUtil.isMathNodeOfClass_ = function(node, tags) { - return (node.nodeType == Node.ELEMENT_NODE && - (cvox.MathUtil.isMathmlNodeOfClass_(node, tags) || - cvox.MathUtil.isMathjaxNodeOfClass_(node, tags))); + return ( + node.nodeType == Node.ELEMENT_NODE && + (cvox.MathUtil.isMathmlNodeOfClass_(node, tags) || + cvox.MathUtil.isMathjaxNodeOfClass_(node, tags))); }; @@ -84,9 +86,10 @@ * Array of MathML Layout Schemata. * @type {!Array<string>} */ -cvox.MathUtil.LAYOUT_LIST = ['MROW', 'MFRAC', 'MSQRT', 'MROOT', 'MSTYLE', - 'MERROR', 'MPADDED', 'MPHANTOM', 'MFENCED', - 'MENCLOSE']; +cvox.MathUtil.LAYOUT_LIST = [ + 'MROW', 'MFRAC', 'MSQRT', 'MROOT', 'MSTYLE', 'MERROR', 'MPADDED', 'MPHANTOM', + 'MFENCED', 'MENCLOSE' +]; /** @@ -115,8 +118,10 @@ * Array of MathML Script Schemata. * @type {!Array<string>} */ -cvox.MathUtil.SCRIPT_LIST = ['MSUB', 'MSUP', 'MSUBSUP', 'MUNDER', 'MOVER', - 'MUNDEROVER', 'MMULTISCRIPTS', 'MPRESCRIPTS']; +cvox.MathUtil.SCRIPT_LIST = [ + 'MSUB', 'MSUP', 'MSUBSUP', 'MUNDER', 'MOVER', 'MUNDEROVER', 'MMULTISCRIPTS', + 'MPRESCRIPTS' +]; /** @@ -145,8 +150,8 @@ * Array of MathML Table and Matrix tokens. * @type {!Array<string>} */ -cvox.MathUtil.TABLES_LIST = ['MTABLE', 'MLABELEDTR', 'MTR', 'MTD', - 'MALIGNGROUP', 'MALIGNMARK']; +cvox.MathUtil.TABLES_LIST = + ['MTABLE', 'MLABELEDTR', 'MTR', 'MTD', 'MALIGNGROUP', 'MALIGNMARK']; /** @@ -170,8 +175,9 @@ * Array of MathML Elementary Layout Schemata. * @type {!Array<string>} */ -cvox.MathUtil.ELEMENTARY_LIST = ['MSTACK', 'MLONGDIV', 'MSGROUP', 'MSROW', - 'MSCARRIES', 'MSCARRY', 'MSLINE']; +cvox.MathUtil.ELEMENTARY_LIST = [ + 'MSTACK', 'MLONGDIV', 'MSGROUP', 'MSROW', 'MSCARRIES', 'MSCARRY', 'MSLINE' +]; /** @@ -189,8 +195,8 @@ * @return {boolean} True if element is a elementary schema. */ cvox.MathUtil.isElementary = function(element) { - return cvox.MathUtil.isMathNodeOfClass_(element, - cvox.MathUtil.ELEMENTARY_LIST); + return cvox.MathUtil.isMathNodeOfClass_( + element, cvox.MathUtil.ELEMENTARY_LIST); }; @@ -199,12 +205,13 @@ * This is a union of all other token lists. * @type {!Array<string>} */ -cvox.MathUtil.MATHML_TAG_LIST = [cvox.MathUtil.TOKEN_LIST, - cvox.MathUtil.LAYOUT_LIST, - cvox.MathUtil.SCRIPT_LIST, - cvox.MathUtil.TABLES_LIST, - cvox.MathUtil.ELEMENTARY_LIST].reduce( - function(x, y) { return x.concat(y); }); +cvox.MathUtil.MATHML_TAG_LIST = [ + cvox.MathUtil.TOKEN_LIST, cvox.MathUtil.LAYOUT_LIST, + cvox.MathUtil.SCRIPT_LIST, cvox.MathUtil.TABLES_LIST, + cvox.MathUtil.ELEMENTARY_LIST +].reduce(function(x, y) { + return x.concat(y); +}); /** @@ -213,8 +220,8 @@ * @return {boolean} True if element has a valid MathML tag. */ cvox.MathUtil.isMathmlTag = function(element) { - return cvox.MathUtil.isMathNodeOfClass_(element, - cvox.MathUtil.MATHML_TAG_LIST); + return cvox.MathUtil.isMathNodeOfClass_( + element, cvox.MathUtil.MATHML_TAG_LIST); }; @@ -223,8 +230,8 @@ * These are elements that can occur in the other token lists. * @type {!Array<string>} */ -cvox.MathUtil.WHITESPACE_LIST = ['MSROW', 'MROW', 'MSPACE', - 'MPHANTOM', 'MPADDED']; +cvox.MathUtil.WHITESPACE_LIST = + ['MSROW', 'MROW', 'MSPACE', 'MPHANTOM', 'MPADDED']; /** @@ -234,8 +241,8 @@ * @return {boolean} True if element is a whitespace node. */ cvox.MathUtil.isWhitespace = function(element) { - return cvox.MathUtil.isMathNodeOfClass_(element, - cvox.MathUtil.WHITESPACE_LIST); + return cvox.MathUtil.isMathNodeOfClass_( + element, cvox.MathUtil.WHITESPACE_LIST); }; @@ -246,8 +253,9 @@ * @return {boolean} True if element is a non-whitespace node. */ cvox.MathUtil.isNotWhitespace = function(element) { - return (cvox.MathUtil.isMathmlTag(element) && - !cvox.MathUtil.isWhitespace(element)); + return ( + cvox.MathUtil.isMathmlTag(element) && + !cvox.MathUtil.isWhitespace(element)); }; @@ -259,5 +267,7 @@ * @return {Array} Union of a and b. */ cvox.MathUtil.union = function(a, b) { - return a.concat(b.filter(function(x) {return a.indexOf(x) < 0;})); + return a.concat(b.filter(function(x) { + return a.indexOf(x) < 0; + })); };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/media_widget.js b/chrome/browser/resources/chromeos/chromevox/common/media_widget.js index 0c2444cb..9ea4a695 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/media_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/common/media_widget.js
@@ -18,7 +18,7 @@ * @param {Element} mediaElem The media widget element. * @param {cvox.TtsInterface} tts The TTS object from ChromeVox. */ -cvox.ChromeVoxHTMLMediaWidget = function(mediaElem, tts){ +cvox.ChromeVoxHTMLMediaWidget = function(mediaElem, tts) { var self = this; this.mediaElem_ = mediaElem; this.mediaTts_ = tts; @@ -71,20 +71,20 @@ if (evt.type == 'keydown') { // Space/Enter for play/pause toggle. if ((evt.keyCode == 13) || (evt.keyCode == 32)) { - if (this.mediaElem_.paused){ + if (this.mediaElem_.paused) { this.mediaElem_.play(); } else { this.mediaElem_.pause(); } - } else if (evt.keyCode == 39) { // Right - FF + } else if (evt.keyCode == 39) { // Right - FF this.jumpToTime_( - this.mediaElem_.currentTime + (this.mediaElem_.duration/10)); - } else if (evt.keyCode == 37) { // Left - REW + this.mediaElem_.currentTime + (this.mediaElem_.duration / 10)); + } else if (evt.keyCode == 37) { // Left - REW this.jumpToTime_( - this.mediaElem_.currentTime - (this.mediaElem_.duration/10)); - } else if (evt.keyCode == 38) { // Up - Vol. Up + this.mediaElem_.currentTime - (this.mediaElem_.duration / 10)); + } else if (evt.keyCode == 38) { // Up - Vol. Up this.setVolume_(this.mediaElem_.volume + .1); - } else if (evt.keyCode == 40) { // Down - Vol. Down + } else if (evt.keyCode == 40) { // Down - Vol. Down this.setVolume_(this.mediaElem_.volume - .1); } }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/memoize.js b/chrome/browser/resources/chromeos/chromevox/common/memoize.js index 0ac3f638..d17970f 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/memoize.js +++ b/chrome/browser/resources/chromeos/chromevox/common/memoize.js
@@ -43,8 +43,7 @@ * Create the namespace. * @constructor */ -cvox.Memoize = function() { -}; +cvox.Memoize = function() {}; /** * The cache: a map from string function name to a WeakMap from DOM node
diff --git a/chrome/browser/resources/chromeos/chromevox/common/msgs.js b/chrome/browser/resources/chromeos/chromevox/common/msgs.js index afb7720a..dd01c766 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/msgs.js +++ b/chrome/browser/resources/chromeos/chromevox/common/msgs.js
@@ -51,8 +51,7 @@ var message = Msgs.Untranslated[messageId.toUpperCase()]; if (message !== undefined) return Msgs.applySubstitutions_(message, opt_subs); - message = chrome.i18n.getMessage( - Msgs.NAMESPACE_ + messageId, opt_subs); + message = chrome.i18n.getMessage(Msgs.NAMESPACE_ + messageId, opt_subs); if (message == undefined || message == '') { throw new Error('Invalid ChromeVox message id: ' + messageId); } @@ -105,8 +104,8 @@ */ Msgs.getLocaleDisplayName = function(locale) { if (!Msgs.localeNameDict_) { - Msgs.localeNameDict_ = /** @type {!Object<string>} */( - JSON.parse(this.getMsg('locale_dict'))); + Msgs.localeNameDict_ = + /** @type {!Object<string>} */ (JSON.parse(this.getMsg('locale_dict'))); } var name = Msgs.localeNameDict_[locale]; if (!name) {
diff --git a/chrome/browser/resources/chromeos/chromevox/common/nav_description.js b/chrome/browser/resources/chromeos/chromevox/common/nav_description.js index a158b574..15b957da 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/nav_description.js +++ b/chrome/browser/resources/chromeos/chromevox/common/nav_description.js
@@ -58,11 +58,10 @@ * @return {boolean} true if this description is empty. */ cvox.NavDescription.prototype.isEmpty = function() { - return (this.context.length == 0 && - this.earcons.length == 0 && - this.text.length == 0 && - this.userValue.length == 0 && - this.annotation.length == 0); + return ( + this.context.length == 0 && this.earcons.length == 0 && + this.text.length == 0 && this.userValue.length == 0 && + this.annotation.length == 0); }; @@ -71,11 +70,10 @@ */ cvox.NavDescription.prototype.toString = function() { return 'NavDescription(context="' + this.context + '" ' + - ' text="' + this.text + '" ' + - ' userValue="' + this.userValue + '" ' + - ' annotation="' + this.annotation + - (this.category ? '" category="' + this.category + '")' : '') + - '")'; + ' text="' + this.text + '" ' + + ' userValue="' + this.userValue + '" ' + + ' annotation="' + this.annotation + + (this.category ? '" category="' + this.category + '")' : '') + '")'; }; @@ -117,9 +115,8 @@ queueMode = cvox.QueueMode.QUEUE; } - speakArgs.push([this.text, - queueMode, - this.personality ? this.personality : {}]); + speakArgs.push( + [this.text, queueMode, this.personality ? this.personality : {}]); queueMode = cvox.QueueMode.QUEUE; if (this.userValue) { @@ -156,8 +153,6 @@ * @return {boolean} True if equal. */ cvox.NavDescription.prototype.equals = function(that) { - return this.context == that.context && - this.text == that.text && - this.userValue == that.userValue && - this.annotation == that.annotation; + return this.context == that.context && this.text == that.text && + this.userValue == that.userValue && this.annotation == that.annotation; };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/node_state.js b/chrome/browser/resources/chromeos/chromevox/common/node_state.js index d7f97fec..ce082ac1 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/node_state.js +++ b/chrome/browser/resources/chromeos/chromevox/common/node_state.js
@@ -34,18 +34,20 @@ */ cvox.NodeStateUtil.expand = function(state) { try { - return state.map(function(s) { - if (s.length < 1) { - throw new Error('cvox.NodeState must have at least one entry'); - } - var args = s.slice(1).map(function(a) { - if (typeof a == 'number') { - return Msgs.getNumber(a); - } - return a; - }); - return Msgs.getMsg(/** @type {string} */ (s[0]), args); - }).join(' '); + return state + .map(function(s) { + if (s.length < 1) { + throw new Error('cvox.NodeState must have at least one entry'); + } + var args = s.slice(1).map(function(a) { + if (typeof a == 'number') { + return Msgs.getNumber(a); + } + return a; + }); + return Msgs.getMsg(/** @type {string} */ (s[0]), args); + }) + .join(' '); } catch (e) { throw new Error('error: ' + e + ' state: ' + state); }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/page_selection.js b/chrome/browser/resources/chromeos/chromevox/common/page_selection.js index 7a46db20..1f866772 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/page_selection.js +++ b/chrome/browser/resources/chromeos/chromevox/common/page_selection.js
@@ -39,8 +39,8 @@ * @param {!cvox.CursorSelection} curSel Current CursorSelection in navigation. * @return {Array<cvox.NavDescription>} The new description. */ -cvox.PageSelection.prototype.getDescription = - function(navShifter, prevSel, curSel) { +cvox.PageSelection.prototype.getDescription = function( + navShifter, prevSel, curSel) { var desc = []; if (this.sel_.isReversed() != curSel.isReversed()) { // A shrinking selection. @@ -55,8 +55,7 @@ if (!this.wasBegin_ && this.sel_.absEquals(curSel.clone().normalize())) { // A selection has inverted across the start cursor. Describe it. var prevDesc = navShifter.getDescription(curSel, prevSel); - prevDesc[0].annotation = - Msgs.getMsg('describe_unselected'); + prevDesc[0].annotation = Msgs.getMsg('describe_unselected'); prevDesc[0].pushEarcon(cvox.Earcon.SELECTION_REVERSE); prevDesc[0].pushEarcon(cvox.Earcon.WRAP); desc = prevDesc.concat(desc); @@ -74,9 +73,10 @@ * @return {Array<cvox.NavDescription>} The new description. */ cvox.PageSelection.prototype.getFullDescription = function() { - return [new cvox.NavDescription( - {text: window.getSelection().toString(), - context: Msgs.getMsg('selection_is')})]; + return [new cvox.NavDescription({ + text: window.getSelection().toString(), + context: Msgs.getMsg('selection_is') + })]; }; @@ -99,7 +99,8 @@ // PageSelection to the end of "sel". In the second case, shrink/extend this // PageSelection to the start of "sel". this.sel_.end = this.sel_.isReversed() == sel.isReversed() ? - sel.end.clone() : sel.start.clone(); + sel.end.clone() : + sel.start.clone(); } this.sel_.select(); this.wasBegin_ = false;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/selection_util.js b/chrome/browser/resources/chromeos/chromevox/common/selection_util.js index 3057d2e..41fd78c7 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/selection_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/selection_util.js
@@ -93,7 +93,6 @@ var lastSelectionOffset; while (expand) { - // nodeType:3 == TEXT_NODE if (sel.focusNode.nodeType == 3) { // The focus node is of type text, check end for period @@ -105,8 +104,8 @@ if (fnode.substringData(sel.getRangeAt(0).endOffset - 1, 1) == '.') { // Text node ends with period. return true; - } else if (fnode.substringData(sel.getRangeAt(0).endOffset - 1, 1) == - ' ') { + } else if ( + fnode.substringData(sel.getRangeAt(0).endOffset - 1, 1) == ' ') { // Text node ends with space. return true; } else { @@ -186,8 +185,7 @@ */ cvox.SelectionUtil.isSelectionValid = function(sel) { var regExpWhiteSpace = new RegExp(/^\s+$/); - return (! ((regExpWhiteSpace.test(sel.toString())) || - (sel.toString() == ''))); + return (!((regExpWhiteSpace.test(sel.toString())) || (sel.toString() == ''))); }; /** @@ -199,8 +197,7 @@ cvox.SelectionUtil.isRangeValid = function(range) { var text = range.cloneContents().textContent; var regExpWhiteSpace = new RegExp(/^\s+$/); - return (! ((regExpWhiteSpace.test(text)) || - (text == ''))); + return (!((regExpWhiteSpace.test(text)) || (text == ''))); }; /** @@ -247,8 +244,8 @@ // Center the active element on the page once we know it's visible. var pos = cvox.SelectionUtil.findPos_(focusNode); - window.scrollTo(pos[0] - window.innerWidth / 2, - pos[1] - window.innerHeight / 2); + window.scrollTo( + pos[0] - window.innerWidth / 2, pos[1] - window.innerHeight / 2); }; /** @@ -273,12 +270,11 @@ var left = pos[1]; var scrolledVertically = window.pageYOffset || - document.documentElement.scrollTop || - document.body.scrollTop; + document.documentElement.scrollTop || document.body.scrollTop; var pageHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; - var pageWidth = window.innerWidth || - document.documentElement.innerWidth || document.body.clientWidth; + var pageWidth = window.innerWidth || document.documentElement.innerWidth || + document.body.clientWidth; if (left < pageWidth) { left = 0; @@ -331,9 +327,9 @@ */ cvox.SelectionUtil.isIgnorable = function(node) { - return (node.nodeType == 8) || // A comment node - ((node.nodeType == 3) && - cvox.SelectionUtil.isAllWs(node)); // a text node, all ws + return (node.nodeType == 8) || // A comment node + ((node.nodeType == 3) && + cvox.SelectionUtil.isAllWs(node)); // a text node, all ws }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/common/spannable.js b/chrome/browser/resources/chromeos/chromevox/common/spannable.js index a275621..e288b9c 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/spannable.js +++ b/chrome/browser/resources/chromeos/chromevox/common/spannable.js
@@ -37,7 +37,7 @@ // Optionally annotate the entire string. if (goog.isDef(opt_annotation)) { var len = this.string_.length; - this.spans_.push({ value: opt_annotation, start: 0, end: len }); + this.spans_.push({value: opt_annotation, start: 0, end: len}); } }; @@ -63,7 +63,7 @@ if (0 <= start && start <= end && end <= this.string_.length) { // Zero-length spans are explicitly allowed, because it is possible to // query for position by annotation as well as the reverse. - this.spans_.push({ value: value, start: start, end: end }); + this.spans_.push({value: value, start: start, end: end}); this.spans_.sort(function(a, b) { var ret = a.start - b.start; if (ret == 0) @@ -71,8 +71,9 @@ return ret; }); } else { - throw new RangeError('span out of range (start=' + start + - ', end=' + end + ', len=' + this.string_.length + ')'); + throw new RangeError( + 'span out of range (start=' + start + ', end=' + end + + ', len=' + this.string_.length + ')'); } }, @@ -99,9 +100,7 @@ this.string_ += otherSpannable.string_; other.spans_.forEach(function(span) { this.setSpan( - span.value, - span.start + originalLength, - span.end + originalLength); + span.value, span.start + originalLength, span.end + originalLength); }.bind(this)); } else if (typeof other === 'string') { this.string_ += /** @type {string} */ (other); @@ -134,8 +133,7 @@ * @return {!Array<Object>} Array of object. */ getSpansInstanceOf: function(constructor) { - return (this.spans_.filter(spanInstanceOf(constructor)) - .map(valueOfSpan)); + return (this.spans_.filter(spanInstanceOf(constructor)).map(valueOfSpan)); }, /** @@ -144,9 +142,7 @@ * @return {!Array} Values annotating that position. */ getSpans: function(position) { - return (this.spans_ - .filter(spanCoversPosition(position)) - .map(valueOfSpan)); + return (this.spans_.filter(spanCoversPosition(position)).map(valueOfSpan)); }, /** @@ -225,7 +221,7 @@ if (span.start <= end && span.end >= start) { var newStart = Math.max(0, span.start - start); var newEnd = Math.min(end - start, span.end - start); - result.spans_.push({ value: span.value, start: newStart, end: newEnd }); + result.spans_.push({value: span.value, start: newStart, end: newEnd}); } }); return result; @@ -278,8 +274,8 @@ // Otherwise, we have at least one non-whitespace character to use as an // anchor when trimming. var trimmedStart = trimStart ? this.string_.match(/^\s*/)[0].length : 0; - var trimmedEnd = trimEnd ? - this.string_.match(/\s*$/).index : this.string_.length; + var trimmedEnd = + trimEnd ? this.string_.match(/\s*$/).index : this.string_.length; return this.substring(trimmedStart, trimmedEnd); }, @@ -294,12 +290,14 @@ result.string = this.string_; result.spans = []; this.spans_.forEach(function(span) { - var serializeInfo = serializableSpansByConstructor.get( - span.value.constructor); + var serializeInfo = + serializableSpansByConstructor.get(span.value.constructor); if (serializeInfo) { - var spanObj = {type: serializeInfo.name, - start: span.start, - end: span.end}; + var spanObj = { + type: serializeInfo.name, + start: span.start, + end: span.end + }; if (serializeInfo.toJson) { spanObj.value = serializeInfo.toJson.apply(span.value); } @@ -318,8 +316,7 @@ */ Spannable.fromJson = function(obj) { if (typeof obj.string !== 'string') { - throw new Error( - 'Invalid spannable json object: string field not a string'); + throw new Error('Invalid spannable json object: string field not a string'); } if (!(obj.spans instanceof Array)) { throw new Error('Invalid spannable json object: no spans array'); @@ -374,7 +371,7 @@ * @return {!Object} */ obj.fromJson = function(obj) { - return new constructor(); + return new constructor(); }; serializableSpansByName.set(name, obj); serializableSpansByConstructor.set(constructor, obj);
diff --git a/chrome/browser/resources/chromeos/chromevox/common/table_util.js b/chrome/browser/resources/chromeos/chromevox/common/table_util.js index ec22512..a5b1df6 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/table_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/table_util.js
@@ -37,10 +37,11 @@ * interest of providing meaningful header information for all tables, here * we take the position that <TD> elements can act as headers. */ - return ((cell.tagName == 'TH') || - cell.hasAttribute('scope') || (cell.hasAttribute('role') && - ((cell.getAttribute('role') == 'rowheader') || - (cell.getAttribute('role') == 'columnheader')))); + return ( + (cell.tagName == 'TH') || cell.hasAttribute('scope') || + (cell.hasAttribute('role') && + ((cell.getAttribute('role') == 'rowheader') || + (cell.getAttribute('role') == 'columnheader')))); }; @@ -60,15 +61,12 @@ } // A colgroup has either a series of col element children or a span // attribute. If it has col children, ignore the span attribute - for (var colGroupCtr = 0; colGroupCtr < colGroups.length; - colGroupCtr++) { - + for (var colGroupCtr = 0; colGroupCtr < colGroups.length; colGroupCtr++) { var currentColGroup = colGroups[colGroupCtr]; var childCols = cvox.TableUtil.getColNodes(currentColGroup); if (childCols.length > 0) { - for (var colNodeCtr = 0; colNodeCtr < childCols.length; - colNodeCtr++) { + for (var colNodeCtr = 0; colNodeCtr < childCols.length; colNodeCtr++) { var colElement = childCols[colNodeCtr]; if (colElement.hasAttribute('span')) { @@ -120,8 +118,10 @@ * @return {Array} An array of all the child rows of the active table. */ cvox.TableUtil.getChildRows = function(table) { - return cvox.XpathUtil.evalXPath('child::tbody/tr | child::thead/tr | ' + - 'child::*[attribute::role="row"]', table); + return cvox.XpathUtil.evalXPath( + 'child::tbody/tr | child::thead/tr | ' + + 'child::*[attribute::role="row"]', + table); }; @@ -133,10 +133,12 @@ * @return {Array} An array of all the child cells of the given row node. */ cvox.TableUtil.getChildCells = function(rowNode) { - return cvox.XpathUtil.evalXPath('child::td | child::th | ' + - 'child::*[attribute::role="gridcell"] |' + - 'child::*[attribute::role="rowheader"] |' + - 'child::*[attribute::role="columnheader"]', rowNode); + return cvox.XpathUtil.evalXPath( + 'child::td | child::th | ' + + 'child::*[attribute::role="gridcell"] |' + + 'child::*[attribute::role="rowheader"] |' + + 'child::*[attribute::role="columnheader"]', + rowNode); }; @@ -176,4 +178,3 @@ cvox.TableUtil.getColNodes = function(colGroupNode) { return cvox.XpathUtil.evalXPath('child::col', colGroupNode); }; -
diff --git a/chrome/browser/resources/chromeos/chromevox/common/time_widget.js b/chrome/browser/resources/chromeos/chromevox/common/time_widget.js index 8691d63f..bfb17a62f 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/time_widget.js +++ b/chrome/browser/resources/chromeos/chromevox/common/time_widget.js
@@ -37,11 +37,11 @@ }; if (this.timeElem_.hasAttribute('step')) { var step = this.timeElem_.getAttribute('step'); - if (step > 0) { // 0 or invalid values show hh:mm AM/PM + if (step > 0) { // 0 or invalid values show hh:mm AM/PM if (step >= 1) { - this.maxPos_ = 3; // Anything larger than 1 shows hh:mm:ss AM/PM + this.maxPos_ = 3; // Anything larger than 1 shows hh:mm:ss AM/PM } else { - this.maxPos_ = 4; // Anything less than 1 shows hh:mm:ss.ms AM/PM + this.maxPos_ = 4; // Anything less than 1 shows hh:mm:ss.ms AM/PM } } } @@ -56,11 +56,11 @@ for (var i = 0; i < this.maxPos_; i++) { var evt = document.createEvent('KeyboardEvent'); evt.initKeyboardEvent( - 'keydown', true, true, window, 'Left', 0, false, false, false, false); + 'keydown', true, true, window, 'Left', 0, false, false, false, false); this.timeElem_.dispatchEvent(evt); evt = document.createEvent('KeyboardEvent'); evt.initKeyboardEvent( - 'keyup', true, true, window, 'Left', 0, false, false, false, false); + 'keyup', true, true, window, 'Left', 0, false, false, false, false); this.timeElem_.dispatchEvent(evt); } @@ -166,8 +166,8 @@ } if (hours != this.pHours_) { - changeMessage = changeMessage + hours + ' ' + - Msgs.getMsg('timewidget_hours') + '\n'; + changeMessage = + changeMessage + hours + ' ' + Msgs.getMsg('timewidget_hours') + '\n'; this.pHours_ = hours; }
diff --git a/chrome/browser/resources/chromeos/chromevox/common/traverse_content.js b/chrome/browser/resources/chromeos/chromevox/common/traverse_content.js index 4ca1ec4..a473d31 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/traverse_content.js +++ b/chrome/browser/resources/chromeos/chromevox/common/traverse_content.js
@@ -118,12 +118,11 @@ * @type {Array<string>} * @const */ -cvox.TraverseContent.kAllGrains = - [cvox.TraverseContent.kParagraph, - cvox.TraverseContent.kSentence, - cvox.TraverseContent.kLine, - cvox.TraverseContent.kWord, - cvox.TraverseContent.kCharacter]; +cvox.TraverseContent.kAllGrains = [ + cvox.TraverseContent.kParagraph, cvox.TraverseContent.kSentence, + cvox.TraverseContent.kLine, cvox.TraverseContent.kWord, + cvox.TraverseContent.kCharacter +]; /** * Set the current position to match the current WebKit selection. @@ -383,11 +382,7 @@ * it should break a sentence or line. */ cvox.TraverseContent.prototype.getBreakTags = function() { - return { - 'A': this.breakAtLinks, - 'BR': true, - 'HR': true - }; + return {'A': this.breakAtLinks, 'BR': true, 'HR': true}; }; /** @@ -409,7 +404,7 @@ var result = this.moveNext(grain); if (result != null && (!cvox.DomUtil.isDescendantOfNode( - this.startCursor_.node, this.currentDomObj) || + this.startCursor_.node, this.currentDomObj) || !cvox.DomUtil.isDescendantOfNode( this.endCursor_.node, this.currentDomObj))) { return null; @@ -438,7 +433,7 @@ var result = this.movePrev(grain); if (result != null && (!cvox.DomUtil.isDescendantOfNode( - this.startCursor_.node, this.currentDomObj) || + this.startCursor_.node, this.currentDomObj) || !cvox.DomUtil.isDescendantOfNode( this.endCursor_.node, this.currentDomObj))) { return null;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/traverse_math.js b/chrome/browser/resources/chromeos/chromevox/common/traverse_math.js index f14d8c29..a0f6a31 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/traverse_math.js +++ b/chrome/browser/resources/chromeos/chromevox/common/traverse_math.js
@@ -131,14 +131,15 @@ node = this.allTexs_[cvoxid]; } if (cvox.DomUtil.isMathJax(node)) { - this.activeMathmlHost = this.allMathjaxs_[node.getAttribute('id')]; + this.activeMathmlHost = this.allMathjaxs_[node.getAttribute('id')]; } this.activeMath = this.activeMathmlHost || node; this.activeNode = this.activeMathmlHost || node; if (this.activeNode && cvox.TraverseMath.setSemantic_ && this.activeNode.nodeType == Node.ELEMENT_NODE) { this.activeNode = - (new cvox.SemanticTree(/** @type {!Element} */ (this.activeNode))).xml(); + (new cvox.SemanticTree(/** @type {!Element} */ (this.activeNode))) + .xml(); } }; @@ -166,7 +167,9 @@ * @param {string} id The MathJax node id. */ cvox.TraverseMath.prototype.redoMathjaxs = function(mml, id) { - var fetch = goog.bind(function() {this.addMathjax(mml, id);}, this); + var fetch = goog.bind(function() { + this.addMathjax(mml, id); + }, this); setTimeout(fetch, 500); }; @@ -178,17 +181,15 @@ * rendered or re-rendered later. */ cvox.TraverseMath.prototype.initializeMathjaxs = function() { - var callback = - goog.bind(function(mml, id) { - this.addMathjax(mml, id); - }, this); - cvox.ChromeVox.mathJax.isMathjaxActive( - function(bool) { - if (bool) { - cvox.ChromeVox.mathJax.getAllJax(callback); - cvox.ChromeVox.mathJax.registerSignal(callback, 'New Math'); - } - }); + var callback = goog.bind(function(mml, id) { + this.addMathjax(mml, id); + }, this); + cvox.ChromeVox.mathJax.isMathjaxActive(function(bool) { + if (bool) { + cvox.ChromeVox.mathJax.getAllJax(callback); + cvox.ChromeVox.mathJax.registerSignal(callback, 'New Math'); + } + }); }; @@ -198,26 +199,24 @@ */ cvox.TraverseMath.prototype.initializeAltMaths = function() { if (!document.querySelector( - cvox.DomUtil.altMathQuerySelector('tex') + ', ' + + cvox.DomUtil.altMathQuerySelector('tex') + ', ' + cvox.DomUtil.altMathQuerySelector('asciimath'))) { return; } - var callback = goog.bind( - function(mml, id) { - this.allTexs_[id] = mml; - }, this); + var callback = goog.bind(function(mml, id) { + this.allTexs_[id] = mml; + }, this); // Inject a minimalistic version of MathJax into the page. cvox.ChromeVox.mathJax.injectScripts(); // Once MathJax is injected we harvest all Latex and AsciiMath in alt // attributes and translate them to MathML expression. - cvox.ChromeVox.mathJax.isMathjaxActive( - function(active) { - if (active) { - cvox.ChromeVox.mathJax.configMediaWiki(); - cvox.ChromeVox.mathJax.getAllTexs(callback); - cvox.ChromeVox.mathJax.getAllAsciiMaths(callback); - } - }); + cvox.ChromeVox.mathJax.isMathjaxActive(function(active) { + if (active) { + cvox.ChromeVox.mathJax.configMediaWiki(); + cvox.ChromeVox.mathJax.getAllTexs(callback); + cvox.ChromeVox.mathJax.getAllAsciiMaths(callback); + } + }); }; @@ -230,9 +229,9 @@ cvox.TraverseMath.prototype.nextLeaf = function(reverse, pred) { if (this.activeNode && this.activeMath) { var next = pred(this.activeNode) ? - cvox.DomUtil.directedFindNextNode( - this.activeNode, this.activeMath, reverse, pred) : - cvox.DomUtil.directedFindFirstNode(this.activeNode, reverse, pred); + cvox.DomUtil.directedFindNextNode( + this.activeNode, this.activeMath, reverse, pred) : + cvox.DomUtil.directedFindFirstNode(this.activeNode, reverse, pred); if (next) { this.activeNode = next; } @@ -262,28 +261,28 @@ return null; } if (!reverse) { - var child = cvox.DomUtil.directedFindFirstNode( - this.activeNode, reverse, pred); + var child = + cvox.DomUtil.directedFindFirstNode(this.activeNode, reverse, pred); if (child) { this.activeNode = child; } else { var next = cvox.DomUtil.directedFindNextNode( this.activeNode, this.activeMath, reverse, pred); if (next) { - this.activeNode = next; + this.activeNode = next; } } } else { if (this.activeNode == this.activeMath) { - var child = cvox.DomUtil.directedFindDeepestNode( - this.activeNode, reverse, pred); + var child = + cvox.DomUtil.directedFindDeepestNode(this.activeNode, reverse, pred); if (child != this.activeNode) { this.activeNode = child; return this.activeNode; } } var prev = cvox.DomUtil.directedFindNextNode( - this.activeNode, this.activeMath, reverse, pred, true, true); + this.activeNode, this.activeMath, reverse, pred, true, true); if (prev) { this.activeNode = prev; } @@ -303,7 +302,7 @@ return null; } var node = this.activeNode; - node = r ? node.previousSibling : node.nextSibling; + node = r ? node.previousSibling : node.nextSibling; if (!node) { return null; } @@ -342,15 +341,13 @@ */ cvox.TraverseMath.prototype.addDomainsAndStyles = function(domains, styles) { this.allDomains.push.apply( - this.allDomains, - domains.filter( - goog.bind(function(x) {return this.allDomains.indexOf(x) < 0;}, - this))); + this.allDomains, domains.filter(goog.bind(function(x) { + return this.allDomains.indexOf(x) < 0; + }, this))); this.allStyles.push.apply( - this.allStyles, - styles.filter( - goog.bind(function(x) {return this.allStyles.indexOf(x) < 0;}, - this))); + this.allStyles, styles.filter(goog.bind(function(x) { + return this.allStyles.indexOf(x) < 0; + }, this))); }; @@ -364,11 +361,10 @@ this.addDomainsAndStyles( cvox.ChromeVox.host['mathMap'].allDomains, cvox.ChromeVox.host['mathMap'].allStyles); - } else { - cvox.ChromeVox.host.sendToBackgroundPage( - {'target': 'Math', - 'action': 'getDomains'}); - } + } else { + cvox.ChromeVox.host.sendToBackgroundPage( + {'target': 'Math', 'action': 'getDomains'}); + } };
diff --git a/chrome/browser/resources/chromeos/chromevox/common/traverse_table.js b/chrome/browser/resources/chromeos/chromevox/common/traverse_table.js index 7b6c0a4e..925af5f 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/traverse_table.js +++ b/chrome/browser/resources/chromeos/chromevox/common/traverse_table.js
@@ -237,8 +237,8 @@ // TODO (stoarca): Is this safe? When this object goes away, doesn't the // eventListener stay on the node? Someone with better knowledge of js // please confirm. If so, this is a leak. - this.activeTable_.addEventListener('DOMSubtreeModified', - goog.bind(function() { + this.activeTable_.addEventListener( + 'DOMSubtreeModified', goog.bind(function() { this.buildShadowTable_(); this.colCount = this.shadowColCount_(); this.rowCount = this.countRows_(); @@ -295,7 +295,7 @@ for (var j = 0; j < this.colCount; ++j) { if (this.shadowTable_[i][j]) { if (cvox.DomUtil.isDescendantOfNode( - n, this.shadowTable_[i][j].activeCell)) { + n, this.shadowTable_[i][j].activeCell)) { return [i, j]; } } @@ -334,8 +334,7 @@ this.currentCellCursor = null; return; } - var aboveCell = - this.shadowTable_[numRows - 1][currentCursor[1]]; + var aboveCell = this.shadowTable_[numRows - 1][currentCursor[1]]; if (aboveCell) { this.currentCellCursor = [(numRows - 1), currentCursor[1]]; } else { @@ -379,10 +378,8 @@ var shadowTableCol = 0; while (activeTableCol < childCells.length) { - // Check to make sure we haven't already filled this cell. if (this.shadowTable_[i][shadowTableCol] == null) { - var activeTableCell = childCells[activeTableCol]; // Default value for colspan and rowspan is 1 @@ -390,9 +387,7 @@ var rowsSpanned = 1; if (activeTableCell.hasAttribute('colspan')) { - - colsSpanned = - parseInt(activeTableCell.getAttribute('colspan'), 10); + colsSpanned = parseInt(activeTableCell.getAttribute('colspan'), 10); if ((isNaN(colsSpanned)) || (colsSpanned <= 0)) { // The HTML5 spec defines colspan MUST be greater than 0: @@ -408,8 +403,7 @@ } } if (activeTableCell.hasAttribute('rowspan')) { - rowsSpanned = - parseInt(activeTableCell.getAttribute('rowspan'), 10); + rowsSpanned = parseInt(activeTableCell.getAttribute('rowspan'), 10); if ((isNaN(rowsSpanned)) || (rowsSpanned <= 0)) { // The HTML5 spec defines that rowspan can be any non-negative @@ -488,7 +482,7 @@ shadowNode.colGroup = 0; } - if (! shadowNode.spanned) { + if (!shadowNode.spanned) { if (activeTableCell.id != null) { this.idToShadowNode_[activeTableCell.id] = shadowNode; } @@ -526,7 +520,6 @@ // #header-and-data-cell-semantics for (var i = 0; i < this.candidateHeaders_.length; i++) { - var currentShadowNode = this.candidateHeaders_[i]; var currentCell = currentShadowNode.activeCell; @@ -537,20 +530,20 @@ continue; } - if ((currentCell.tagName == 'TH') && - !(currentCell.hasAttribute('scope'))) { + if ((currentCell.tagName == 'TH') && !(currentCell.hasAttribute('scope'))) { // No scope specified - compute scope ourselves. // Go left/right - if there's a header node, then this is a column // header if (currentShadowNode.j > 0) { - if (this.shadowTable_[currentShadowNode.i][currentShadowNode.j - 1]. - activeCell.tagName == 'TH') { + if (this.shadowTable_[currentShadowNode.i][currentShadowNode.j - 1] + .activeCell.tagName == 'TH') { assumedScope = 'col'; } - } else if (currentShadowNode.j < this.shadowTable_[currentShadowNode.i]. - length - 1) { - if (this.shadowTable_[currentShadowNode.i][currentShadowNode.j + 1]. - activeCell.tagName == 'TH') { + } else if ( + currentShadowNode.j < + this.shadowTable_[currentShadowNode.i].length - 1) { + if (this.shadowTable_[currentShadowNode.i][currentShadowNode.j + 1] + .activeCell.tagName == 'TH') { assumedScope = 'col'; } } else { @@ -561,13 +554,13 @@ if (assumedScope == null) { // Go up/down - if there's a header node, then this is a row header if (currentShadowNode.i > 0) { - if (this.shadowTable_[currentShadowNode.i - 1][currentShadowNode.j]. - activeCell.tagName == 'TH') { + if (this.shadowTable_[currentShadowNode.i - 1][currentShadowNode.j] + .activeCell.tagName == 'TH') { assumedScope = 'row'; } } else if (currentShadowNode.i < this.shadowTable_.length - 1) { - if (this.shadowTable_[currentShadowNode.i + 1][currentShadowNode.j]. - activeCell.tagName == 'TH') { + if (this.shadowTable_[currentShadowNode.i + 1][currentShadowNode.j] + .activeCell.tagName == 'TH') { assumedScope = 'row'; } } else { @@ -578,12 +571,14 @@ } } else if (currentCell.hasAttribute('scope')) { specifiedScope = currentCell.getAttribute('scope'); - } else if (currentCell.hasAttribute('role') && + } else if ( + currentCell.hasAttribute('role') && (currentCell.getAttribute('role') == 'rowheader')) { specifiedScope = 'row'; - } else if (currentCell.hasAttribute('role') && + } else if ( + currentCell.hasAttribute('role') && (currentCell.getAttribute('role') == 'columnheader')) { - specifiedScope = 'col'; + specifiedScope = 'col'; } if ((specifiedScope == 'row') || (assumedScope == 'row')) { @@ -595,13 +590,10 @@ for (var rightCtr = currentShadowNode.j; rightCtr < this.shadowTable_[currentShadowNode.i].length; rightCtr++) { - var rightShadowNode = this.shadowTable_[currentShadowNode.i][rightCtr]; var rightCell = rightShadowNode.activeCell; - if ((rightCell.tagName == 'TH') || - (rightCell.hasAttribute('scope'))) { - + if ((rightCell.tagName == 'TH') || (rightCell.hasAttribute('scope'))) { if (rightCtr < this.shadowTable_[currentShadowNode.i].length - 1) { var checkDataCell = this.shadowTable_[currentShadowNode.i][rightCtr + 1]; @@ -618,18 +610,14 @@ // Add this cell to each shadowNode.colHeaders attribute as you go. for (var downCtr = currentShadowNode.i; - downCtr < this.shadowTable_.length; - downCtr++) { - + downCtr < this.shadowTable_.length; downCtr++) { var downShadowNode = this.shadowTable_[downCtr][currentShadowNode.j]; if (downShadowNode == null) { break; } var downCell = downShadowNode.activeCell; - if ((downCell.tagName == 'TH') || - (downCell.hasAttribute('scope'))) { - + if ((downCell.tagName == 'TH') || (downCell.hasAttribute('scope'))) { if (downCtr < this.shadowTable_.length - 1) { var checkDataCell = this.shadowTable_[downCtr + 1][currentShadowNode.j]; @@ -639,7 +627,7 @@ } this.tableColHeaders.push(currentCell); } else if (specifiedScope == 'rowgroup') { - currentShadowNode.isRowHeader = true; + currentShadowNode.isRowHeader = true; // This cell is a row header for the rest of the cells in this row group. var currentRowGroup = currentShadowNode.rowGroup; @@ -648,25 +636,20 @@ for (var cellsInRow = currentShadowNode.j + 1; cellsInRow < this.shadowTable_[currentShadowNode.i].length; cellsInRow++) { - this.shadowTable_[currentShadowNode.i][cellsInRow]. - rowHeaderCells.push(currentCell); + this.shadowTable_[currentShadowNode.i][cellsInRow].rowHeaderCells.push( + currentCell); } // Now propagate to rest of row group for (var downCtr = currentShadowNode.i + 1; - downCtr < this.shadowTable_.length; - downCtr++) { - + downCtr < this.shadowTable_.length; downCtr++) { if (this.shadowTable_[downCtr][0].rowGroup != currentRowGroup) { break; } - for (var rightCtr = 0; - rightCtr < this.shadowTable_[downCtr].length; + for (var rightCtr = 0; rightCtr < this.shadowTable_[downCtr].length; rightCtr++) { - - this.shadowTable_[downCtr][rightCtr]. - rowHeaderCells.push(currentCell); + this.shadowTable_[downCtr][rightCtr].rowHeaderCells.push(currentCell); } } this.tableRowHeaders.push(currentCell); @@ -683,24 +666,20 @@ cellsInCol++) { if (this.shadowTable_[currentShadowNode.i][cellsInCol].colGroup == currentColGroup) { - this.shadowTable_[currentShadowNode.i][cellsInCol]. - colHeaderCells.push(currentCell); + this.shadowTable_[currentShadowNode.i][cellsInCol] + .colHeaderCells.push(currentCell); } } // Now propagate to rest of col group for (var downCtr = currentShadowNode.i + 1; - downCtr < this.shadowTable_.length; - downCtr++) { - - for (var rightCtr = 0; - rightCtr < this.shadowTable_[downCtr].length; + downCtr < this.shadowTable_.length; downCtr++) { + for (var rightCtr = 0; rightCtr < this.shadowTable_[downCtr].length; rightCtr++) { - if (this.shadowTable_[downCtr][rightCtr].colGroup == currentColGroup) { - this.shadowTable_[downCtr][rightCtr]. - colHeaderCells.push(currentCell); + this.shadowTable_[downCtr][rightCtr].colHeaderCells.push( + currentCell); } } } @@ -739,8 +718,8 @@ var idList = activeTableCell.getAttribute('headers').split(' '); for (var idToken = 0; idToken < idList.length; idToken++) { // Find cell(s) with this ID, add to header list - var idCellArray = cvox.TableUtil.getCellWithID(this.activeTable_, - idList[idToken]); + var idCellArray = + cvox.TableUtil.getCellWithID(this.activeTable_, idList[idToken]); for (var idCtr = 0; idCtr < idCellArray.length; idCtr++) { if (idCellArray[idCtr].id == activeTableCell.id) { @@ -749,9 +728,8 @@ } // Check if this list of candidate headers contains a // shadowNode with an active cell with this ID already - var possibleHeaderNode = - this.idToShadowNode_[idCellArray[idCtr].id]; - if (! cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)) { + var possibleHeaderNode = this.idToShadowNode_[idCellArray[idCtr].id]; + if (!cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)) { // This listed header cell will not be handled later. // Determine whether this is a row or col header for // the active table cell @@ -759,16 +737,16 @@ var iDiff = Math.abs(possibleHeaderNode.i - currentShadowNode.i); var jDiff = Math.abs(possibleHeaderNode.j - currentShadowNode.j); if ((iDiff == 0) || (iDiff < jDiff)) { - cvox.TableUtil.pushIfNotContained(currentShadowNode.rowHeaderCells, - possibleHeaderNode.activeCell); - cvox.TableUtil.pushIfNotContained(this.tableRowHeaders, - possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + currentShadowNode.rowHeaderCells, possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + this.tableRowHeaders, possibleHeaderNode.activeCell); } else { // This is a column header - cvox.TableUtil.pushIfNotContained(currentShadowNode.colHeaderCells, - possibleHeaderNode.activeCell); - cvox.TableUtil.pushIfNotContained(this.tableColHeaders, - possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + currentShadowNode.colHeaderCells, possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + this.tableColHeaders, possibleHeaderNode.activeCell); } } } @@ -793,15 +771,15 @@ * * @private */ -cvox.TraverseTable.prototype.findAttrbDescribedBy_ = - function(currentShadowNode) { +cvox.TraverseTable.prototype.findAttrbDescribedBy_ = function( + currentShadowNode) { var activeTableCell = currentShadowNode.activeCell; var idList = activeTableCell.getAttribute('aria-describedby').split(' '); for (var idToken = 0; idToken < idList.length; idToken++) { // Find cell(s) with this ID, add to header list - var idCellArray = cvox.TableUtil.getCellWithID(this.activeTable_, - idList[idToken]); + var idCellArray = + cvox.TableUtil.getCellWithID(this.activeTable_, idList[idToken]); for (var idCtr = 0; idCtr < idCellArray.length; idCtr++) { if (idCellArray[idCtr].id == activeTableCell.id) { @@ -810,27 +788,27 @@ } // Check if this list of candidate headers contains a // shadowNode with an active cell with this ID already - var possibleHeaderNode = - this.idToShadowNode_[idCellArray[idCtr].id]; - if (! cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)) { + var possibleHeaderNode = this.idToShadowNode_[idCellArray[idCtr].id]; + if (!cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)) { // This listed header cell will not be handled later. // Determine whether this is a row or col header for // the active table cell if (possibleHeaderNode.activeCell.hasAttribute('role') && (possibleHeaderNode.activeCell.getAttribute('role') == - 'rowheader')) { - cvox.TableUtil.pushIfNotContained(currentShadowNode.rowHeaderCells, - possibleHeaderNode.activeCell); - cvox.TableUtil.pushIfNotContained(this.tableRowHeaders, - possibleHeaderNode.activeCell); - } else if (possibleHeaderNode.activeCell.hasAttribute('role') && + 'rowheader')) { + cvox.TableUtil.pushIfNotContained( + currentShadowNode.rowHeaderCells, possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + this.tableRowHeaders, possibleHeaderNode.activeCell); + } else if ( + possibleHeaderNode.activeCell.hasAttribute('role') && (possibleHeaderNode.activeCell.getAttribute('role') == - 'columnheader')) { - cvox.TableUtil.pushIfNotContained(currentShadowNode.colHeaderCells, - possibleHeaderNode.activeCell); - cvox.TableUtil.pushIfNotContained(this.tableColHeaders, - possibleHeaderNode.activeCell); + 'columnheader')) { + cvox.TableUtil.pushIfNotContained( + currentShadowNode.colHeaderCells, possibleHeaderNode.activeCell); + cvox.TableUtil.pushIfNotContained( + this.tableColHeaders, possibleHeaderNode.activeCell); } } } @@ -943,24 +921,20 @@ cvox.TraverseTable.prototype.getCol = function() { var colArray = []; for (var i = 0; i < this.shadowTable_.length; i++) { - if (this.shadowTable_[i][this.currentCellCursor[1]]) { var shadowEntry = this.shadowTable_[i][this.currentCellCursor[1]]; if (shadowEntry.colSpan && shadowEntry.rowSpan) { // Look at the last element in the column cell aray. var prev = colArray[colArray.length - 1]; - if (prev != - shadowEntry.activeCell) { + if (prev != shadowEntry.activeCell) { // Watch out for positions spanned by a cell with rowspan and // colspan. We don't want the same cell showing up multiple times // in per-column cell lists. - colArray.push( - shadowEntry.activeCell); + colArray.push(shadowEntry.activeCell); } } else if ((shadowEntry.colSpan) || (!shadowEntry.rowSpan)) { - colArray.push( - shadowEntry.activeCell); + colArray.push(shadowEntry.activeCell); } } } @@ -1005,8 +979,7 @@ */ cvox.TraverseTable.prototype.captionText = function() { // If there's more than one outer <caption> element, choose the first one. - var captionNodes = cvox.XpathUtil.evalXPath('caption\[1]', - this.activeTable_); + var captionNodes = cvox.XpathUtil.evalXPath('caption\[1]', this.activeTable_); if (captionNodes.length > 0) { return captionNodes[0].innerHTML; } else { @@ -1058,8 +1031,8 @@ cvox.TraverseTable.prototype.getW3CColCount_ = function() { // See http://www.w3.org/TR/html401/struct/tables.html#h-11.2.4.3 - var colgroupNodes = cvox.XpathUtil.evalXPath('child::colgroup', - this.activeTable_); + var colgroupNodes = + cvox.XpathUtil.evalXPath('child::colgroup', this.activeTable_); var colNodes = cvox.XpathUtil.evalXPath('child::col', this.activeTable_); if ((colgroupNodes.length == 0) && (colNodes.length == 0)) { @@ -1082,8 +1055,8 @@ } } for (i = 0; i < colgroupNodes.length; i++) { - var colChildren = cvox.XpathUtil.evalXPath('child::col', - colgroupNodes[i]); + var colChildren = + cvox.XpathUtil.evalXPath('child::col', colgroupNodes[i]); if (colChildren.length == 0) { if (colgroupNodes[i].hasAttribute('span')) { sum += colgroupNodes[i].getAttribute('span'); @@ -1104,7 +1077,7 @@ * 1) True if the update has been made. * 2) False if the end of the table has been reached and the update has not * happened. - */ + */ cvox.TraverseTable.prototype.nextRow = function() { if (!this.currentCellCursor) { // We have not started moving through the table yet @@ -1253,8 +1226,7 @@ } var lastRow = this.shadowTable_[numRows - 1]; var lastIndex = [(numRows - 1), (lastRow.length - 1)]; - var cell = - this.shadowTable_[lastIndex[0]][lastIndex[1]]; + var cell = this.shadowTable_[lastIndex[0]][lastIndex[1]]; if (cell != null) { this.currentCellCursor = lastIndex; return true; @@ -1273,8 +1245,7 @@ cvox.TraverseTable.prototype.goToRowLastCell = function() { var currentRow = this.currentCellCursor[0]; var lastIndex = [currentRow, (this.shadowTable_[currentRow].length - 1)]; - var cell = - this.shadowTable_[lastIndex[0]][lastIndex[1]]; + var cell = this.shadowTable_[lastIndex[0]][lastIndex[1]]; if (cell != null) { this.currentCellCursor = lastIndex; return true; @@ -1293,8 +1264,7 @@ cvox.TraverseTable.prototype.goToColLastCell = function() { var currentCol = this.getCol(); var lastIndex = [(currentCol.length - 1), this.currentCellCursor[1]]; - var cell = - this.shadowTable_[lastIndex[0]][lastIndex[1]]; + var cell = this.shadowTable_[lastIndex[0]][lastIndex[1]]; if (cell != null) { this.currentCellCursor = lastIndex; return true;
diff --git a/chrome/browser/resources/chromeos/chromevox/common/traverse_util.js b/chrome/browser/resources/chromeos/chromevox/common/traverse_util.js index a77ac3e..717fc8af 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/traverse_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/traverse_util.js
@@ -47,10 +47,8 @@ * @return {boolean} True if the node should be treated as a leaf node. */ cvox.TraverseUtil.treatAsLeafNode = function(node) { - return node.childNodes.length == 0 || - node.nodeName == 'SELECT' || - node.getAttribute('role') == 'listbox' || - node.nodeName == 'OBJECT'; + return node.childNodes.length == 0 || node.nodeName == 'SELECT' || + node.getAttribute('role') == 'listbox' || node.nodeName == 'OBJECT'; }; /** @@ -154,8 +152,7 @@ while (cursor.node != null) { // Try to move to the next sibling. var siblingNode = null; - for (var node = cursor.node.nextSibling; - node != null; + for (var node = cursor.node.nextSibling; node != null; node = node.nextSibling) { if (cvox.TraverseUtil.isHidden(node)) { if (node instanceof HTMLElement) { @@ -252,8 +249,7 @@ while (true) { // Try to move to the previous sibling. var siblingNode = null; - for (var node = cursor.node.previousSibling; - node != null; + for (var node = cursor.node.previousSibling; node != null; node = node.previousSibling) { if (cvox.TraverseUtil.isHidden(node)) { if (node instanceof HTMLElement) { @@ -323,8 +319,8 @@ // Save the starting position and get the first character. startCursor.copyFrom(endCursor); - var c = cvox.TraverseUtil.forwardsChar( - endCursor, elementsEntered, elementsLeft); + var c = + cvox.TraverseUtil.forwardsChar(endCursor, elementsEntered, elementsLeft); if (c == null) return null; @@ -333,7 +329,7 @@ // Keep scanning until we find a non-whitespace or non-skipped character. while ((cvox.TraverseUtil.isWhitespace(c)) || - (cvox.TraverseUtil.isHidden(endCursor.node))) { + (cvox.TraverseUtil.isHidden(endCursor.node))) { c = cvox.TraverseUtil.forwardsChar( endCursor, elementsEntered, elementsLeft); if (c == null) @@ -345,8 +341,7 @@ startCursor.copyFrom(endCursor); startCursor.index--; return c; - } - else { + } else { for (var i = 0; i < elementsEntered.length; i++) { if (cvox.TraverseUtil.isHidden(elementsEntered[i])) { // We need to make sure that startCursor and endCursor aren't @@ -396,7 +391,7 @@ // Keep scanning until we find a non-whitespace or non-skipped character. while ((cvox.TraverseUtil.isWhitespace(c)) || - (cvox.TraverseUtil.isHidden(startCursor.node))) { + (cvox.TraverseUtil.isHidden(startCursor.node))) { c = cvox.TraverseUtil.backwardsChar( startCursor, elementsEntered, elementsLeft); if (c == null) @@ -436,8 +431,8 @@ * @return {?string} The next word, or null if the bottom of the * document has been reached. */ -cvox.TraverseUtil.getNextWord = function(startCursor, endCursor, - elementsEntered, elementsLeft) { +cvox.TraverseUtil.getNextWord = function( + startCursor, endCursor, elementsEntered, elementsLeft) { // Find the first non-whitespace or non-skipped character. var cursor = endCursor.clone(); @@ -445,7 +440,7 @@ if (c == null) return null; while ((cvox.TraverseUtil.isWhitespace(c)) || - (cvox.TraverseUtil.isHidden(cursor.node))) { + (cvox.TraverseUtil.isHidden(cursor.node))) { c = cvox.TraverseUtil.forwardsChar(cursor, elementsEntered, elementsLeft); if (c == null) return null; @@ -469,8 +464,7 @@ if (c == null) { return word; } - while (!cvox.TraverseUtil.isWhitespace(c) && - newEntered.length == 0 && + while (!cvox.TraverseUtil.isWhitespace(c) && newEntered.length == 0 && newLeft == 0) { word += c; endCursor.copyFrom(cursor); @@ -497,16 +491,17 @@ * @return {?string} The previous word, or null if the bottom of the * document has been reached. */ -cvox.TraverseUtil.getPreviousWord = function(startCursor, endCursor, - elementsEntered, elementsLeft) { +cvox.TraverseUtil.getPreviousWord = function( + startCursor, endCursor, elementsEntered, elementsLeft) { // Find the first non-whitespace or non-skipped character. var cursor = startCursor.clone(); - var c = cvox.TraverseUtil.backwardsChar( - cursor, elementsEntered, elementsLeft); + var c = + cvox.TraverseUtil.backwardsChar(cursor, elementsEntered, elementsLeft); if (c == null) return null; - while ((cvox.TraverseUtil.isWhitespace(c) || - (cvox.TraverseUtil.isHidden(cursor.node)))) { + while ( + (cvox.TraverseUtil.isWhitespace(c) || + (cvox.TraverseUtil.isHidden(cursor.node)))) { c = cvox.TraverseUtil.backwardsChar(cursor, elementsEntered, elementsLeft); if (c == null) return null; @@ -528,8 +523,7 @@ c = cvox.TraverseUtil.backwardsChar(cursor, newEntered, newLeft); if (c == null) return word; - while (!cvox.TraverseUtil.isWhitespace(c) && - newEntered.length == 0 && + while (!cvox.TraverseUtil.isWhitespace(c) && newEntered.length == 0 && newLeft.length == 0) { word = c + word; startCursor.copyFrom(cursor); @@ -649,7 +643,7 @@ var currentRect = null; var rightMostRect = null; var prevCursor = endCursor.clone(); - return cvox.TraverseUtil.getNextString( + return cvox.TraverseUtil.getNextString( startCursor, endCursor, elementsEntered, elementsLeft, function(str, word, elementsEntered, elementsLeft) { range.setStart(startCursor.node, startCursor.index); @@ -661,8 +655,8 @@ // Break at new lines except when within a link. if (currentRect.bottom != rightMostRect.bottom && - !cvox.DomPredicates.linkPredicate(cvox.DomUtil.getAncestors( - endCursor.node))) { + !cvox.DomPredicates.linkPredicate( + cvox.DomUtil.getAncestors(endCursor.node))) { endCursor.copyFrom(prevCursor); return true; } @@ -707,8 +701,8 @@ // Break at new lines except when within a link. if (currentRect.top != leftMostRect.top && - !cvox.DomPredicates.linkPredicate(cvox.DomUtil.getAncestors( - startCursor.node))) { + !cvox.DomPredicates.linkPredicate( + cvox.DomUtil.getAncestors(startCursor.node))) { startCursor.copyFrom(prevCursor); return true; } @@ -734,8 +728,8 @@ * @return {?string} The next paragraph, or null if the bottom of the * document has been reached. */ -cvox.TraverseUtil.getNextParagraph = function(startCursor, endCursor, - elementsEntered, elementsLeft) { +cvox.TraverseUtil.getNextParagraph = function( + startCursor, endCursor, elementsEntered, elementsLeft) { return cvox.TraverseUtil.getNextString( startCursor, endCursor, elementsEntered, elementsLeft, function(str, word, elementsEntered, elementsLeft) {
diff --git a/chrome/browser/resources/chromeos/chromevox/common/xpath_util.js b/chrome/browser/resources/chromeos/chromevox/common/xpath_util.js index cad6346..96efc6e 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/xpath_util.js +++ b/chrome/browser/resources/chromeos/chromevox/common/xpath_util.js
@@ -15,8 +15,7 @@ * Utilities for simplifying working with xpaths * @constructor */ -cvox.XpathUtil = function() { - }; +cvox.XpathUtil = function() {}; /** @@ -25,7 +24,7 @@ * @private */ cvox.XpathUtil.nameSpaces_ = { - 'xhtml' : 'http://www.w3.org/1999/xhtml', + 'xhtml': 'http://www.w3.org/1999/xhtml', 'mathml': 'http://www.w3.org/1998/Math/MathML' }; @@ -52,18 +51,15 @@ cvox.XpathUtil.evalXPath = function(expression, rootNode) { try { var xpathIterator = rootNode.ownerDocument.evaluate( - expression, - rootNode, - cvox.XpathUtil.resolveNameSpace, - XPathResult.ORDERED_NODE_ITERATOR_TYPE, - null); // no existing results + expression, rootNode, cvox.XpathUtil.resolveNameSpace, + XPathResult.ORDERED_NODE_ITERATOR_TYPE, + null); // no existing results } catch (err) { return []; } var results = []; // Convert result to JS array - for (var xpathNode = xpathIterator.iterateNext(); - xpathNode; + for (var xpathNode = xpathIterator.iterateNext(); xpathNode; xpathNode = xpathIterator.iterateNext()) { results.push(xpathNode); } @@ -78,18 +74,16 @@ cvox.XpathUtil.getLeafNodes = function(rootNode) { try { var xpathIterator = rootNode.ownerDocument.evaluate( - './/*[count(*)=0]', - rootNode, - null, // no namespace resolver - XPathResult.ORDERED_NODE_ITERATOR_TYPE, - null); // no existing results + './/*[count(*)=0]', rootNode, + null, // no namespace resolver + XPathResult.ORDERED_NODE_ITERATOR_TYPE, + null); // no existing results } catch (err) { return []; } var results = []; // Convert result to JS array - for (var xpathNode = xpathIterator.iterateNext(); - xpathNode; + for (var xpathNode = xpathIterator.iterateNext(); xpathNode; xpathNode = xpathIterator.iterateNext()) { results.push(xpathNode); } @@ -118,11 +112,9 @@ cvox.XpathUtil.evaluateBoolean = function(expression, rootNode) { try { var xpathResult = rootNode.ownerDocument.evaluate( - expression, - rootNode, - cvox.XpathUtil.resolveNameSpace, + expression, rootNode, cvox.XpathUtil.resolveNameSpace, XPathResult.BOOLEAN_TYPE, - null); // no existing results + null); // no existing results } catch (err) { return false; } @@ -140,11 +132,9 @@ cvox.XpathUtil.evaluateString = function(expression, rootNode) { try { var xpathResult = rootNode.ownerDocument.evaluate( - expression, - rootNode, - cvox.XpathUtil.resolveNameSpace, + expression, rootNode, cvox.XpathUtil.resolveNameSpace, XPathResult.STRING_TYPE, - null); // no existing results + null); // no existing results } catch (err) { return ''; }
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_object_constructor_installer.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_object_constructor_installer.js index de18ba9..f79cf30 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_object_constructor_installer.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_object_constructor_installer.js
@@ -20,17 +20,17 @@ */ AutomationObjectConstructorInstaller.init = function(node, callback) { chrome.automation.AutomationNode = - /** @type {function (new:chrome.automation.AutomationNode)} */( + /** @type {function (new:chrome.automation.AutomationNode)} */ ( node.constructor); - node.addEventListener(chrome.automation.EventType.CHILDREN_CHANGED, + node.addEventListener( + chrome.automation.EventType.CHILDREN_CHANGED, function installAutomationEvent(e) { chrome.automation.AutomationEvent = - /** @type {function (new:chrome.automation.AutomationEvent)} */( + /** @type {function (new:chrome.automation.AutomationEvent)} */ ( e.constructor); node.removeEventListener( chrome.automation.EventType.CHILDREN_CHANGED, - installAutomationEvent, - true); + installAutomationEvent, true); callback(); }, true);
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js index 866cd0e..4c0dba3 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js
@@ -39,7 +39,7 @@ * @return {AutomationPredicate.Unary} */ AutomationPredicate.roles = function(roles) { - return AutomationPredicate.match({anyRole: roles }); + return AutomationPredicate.match({anyRole: roles}); }; /** @@ -52,8 +52,12 @@ var anyRole = params.anyRole || []; var anyPredicate = params.anyPredicate || []; return function(node) { - return anyRole.some(function(role) { return role == node.role; }) || - anyPredicate.some(function(p) { return p(node); }); + return anyRole.some(function(role) { + return role == node.role; + }) || + anyPredicate.some(function(p) { + return p(node); + }); }; }; @@ -88,26 +92,18 @@ * @return {boolean} */ AutomationPredicate.editText = function(node) { - return node.state.editable && - node.parent && - !node.parent.state.editable; + return node.state.editable && node.parent && !node.parent.state.editable; }; /** @type {AutomationPredicate.Unary} */ AutomationPredicate.formField = AutomationPredicate.match({ anyPredicate: [ - AutomationPredicate.button, - AutomationPredicate.comboBox, + AutomationPredicate.button, AutomationPredicate.comboBox, AutomationPredicate.editText ], anyRole: [ - Role.CHECK_BOX, - Role.COLOR_WELL, - Role.LIST_BOX, - Role.SLIDER, - Role.SWITCH, - Role.TAB, - Role.TREE + Role.CHECK_BOX, Role.COLOR_WELL, Role.LIST_BOX, Role.SLIDER, Role.SWITCH, + Role.TAB, Role.TREE ] }); @@ -117,12 +113,8 @@ AutomationPredicate.formField, ], anyRole: [ - Role.DISCLOSURE_TRIANGLE, - Role.MENU_ITEM, - Role.MENU_ITEM_CHECK_BOX, - Role.MENU_ITEM_RADIO, - Role.MENU_LIST_OPTION, - Role.SCROLL_BAR + Role.DISCLOSURE_TRIANGLE, Role.MENU_ITEM, Role.MENU_ITEM_CHECK_BOX, + Role.MENU_ITEM_RADIO, Role.MENU_LIST_OPTION, Role.SCROLL_BAR ] }); @@ -135,26 +127,14 @@ }; /** @type {AutomationPredicate.Unary} */ -AutomationPredicate.linkOrControl = AutomationPredicate.match({ - anyPredicate: [ - AutomationPredicate.control - ], - anyRole: [ - Role.LINK - ] -}); +AutomationPredicate.linkOrControl = AutomationPredicate.match( + {anyPredicate: [AutomationPredicate.control], anyRole: [Role.LINK]}); /** @type {AutomationPredicate.Unary} */ AutomationPredicate.landmark = AutomationPredicate.roles([ - Role.APPLICATION, - Role.BANNER, - Role.COMPLEMENTARY, - Role.CONTENT_INFO, - Role.FORM, - Role.MAIN, - Role.NAVIGATION, - Role.REGION, - Role.SEARCH]); + Role.APPLICATION, Role.BANNER, Role.COMPLEMENTARY, Role.CONTENT_INFO, + Role.FORM, Role.MAIN, Role.NAVIGATION, Role.REGION, Role.SEARCH +]); /** * @param {!AutomationNode} node @@ -177,14 +157,10 @@ * @return {boolean} */ AutomationPredicate.leaf = function(node) { - return !node.firstChild || - node.role == Role.BUTTON || - node.role == Role.BUTTON_DROP_DOWN || - node.role == Role.POP_UP_BUTTON || - node.role == Role.SLIDER || - node.role == Role.TEXT_FIELD || - node.state[State.INVISIBLE] || - node.children.every(function(n) { + return !node.firstChild || node.role == Role.BUTTON || + node.role == Role.BUTTON_DROP_DOWN || node.role == Role.POP_UP_BUTTON || + node.role == Role.SLIDER || node.role == Role.TEXT_FIELD || + node.state[State.INVISIBLE] || node.children.every(function(n) { return n.state[State.INVISIBLE]; }); }; @@ -194,8 +170,7 @@ * @return {boolean} */ AutomationPredicate.leafWithText = function(node) { - return AutomationPredicate.leaf(node) && - !!(node.name || node.value); + return AutomationPredicate.leaf(node) && !!(node.name || node.value); }; /** @@ -206,8 +181,7 @@ * @return {boolean} */ AutomationPredicate.leafOrStaticText = function(node) { - return AutomationPredicate.leaf(node) || - node.role == Role.STATIC_TEXT; + return AutomationPredicate.leaf(node) || node.role == Role.STATIC_TEXT; }; /** @@ -232,8 +206,7 @@ return node.state.focusable || (AutomationPredicate.leafOrStaticText(node) && (/\S+/.test(node.name) || - (node.role != Role.LINE_BREAK && - node.role != Role.STATIC_TEXT && + (node.role != Role.LINE_BREAK && node.role != Role.STATIC_TEXT && node.role != Role.INLINE_TEXT_BOX))); }; @@ -243,16 +216,10 @@ * @return {boolean} */ AutomationPredicate.group = AutomationPredicate.match({ - anyRole: [ - Role.HEADING, - Role.LIST, - Role.PARAGRAPH - ], + anyRole: [Role.HEADING, Role.LIST, Role.PARAGRAPH], anyPredicate: [ - AutomationPredicate.editText, - AutomationPredicate.formField, - AutomationPredicate.object, - AutomationPredicate.table + AutomationPredicate.editText, AutomationPredicate.formField, + AutomationPredicate.object, AutomationPredicate.table ] }); @@ -265,8 +232,7 @@ // TODO(dtseng): Use next/previousOnLin once available. var fl = first.location; var sl = second.location; - return fl.top != sl.top || - (fl.top + fl.height != sl.top + sl.height); + return fl.top != sl.top || (fl.top + fl.height != sl.top + sl.height); }; /** @@ -278,24 +244,20 @@ AutomationPredicate.container = function(node) { return AutomationPredicate.match({ anyRole: [ - Role.GENERIC_CONTAINER, - Role.DOCUMENT, - Role.GROUP, - Role.LIST_ITEM, - Role.TOOLBAR, - Role.WINDOW], + Role.GENERIC_CONTAINER, Role.DOCUMENT, Role.GROUP, Role.LIST_ITEM, + Role.TOOLBAR, Role.WINDOW + ], anyPredicate: [ - AutomationPredicate.landmark, - AutomationPredicate.structuralContainer, + AutomationPredicate.landmark, AutomationPredicate.structuralContainer, function(node) { // For example, crosh. return (node.role == Role.TEXT_FIELD && node.state.readOnly); }, function(node) { - return (node.state.editable && - node.parent && - !node.parent.state.editable); - }] + return ( + node.state.editable && node.parent && !node.parent.state.editable); + } + ] })(node); }; @@ -306,15 +268,10 @@ * @return {boolean} */ AutomationPredicate.structuralContainer = AutomationPredicate.roles([ - Role.ALERT_DIALOG, - Role.DIALOG, - Role.ROOT_WEB_AREA, - Role.WEB_VIEW, - Role.WINDOW, - Role.EMBEDDED_OBJECT, - Role.IFRAME, - Role.IFRAME_PRESENTATIONAL, - Role.UNKNOWN]); + Role.ALERT_DIALOG, Role.DIALOG, Role.ROOT_WEB_AREA, Role.WEB_VIEW, + Role.WINDOW, Role.EMBEDDED_OBJECT, Role.IFRAME, Role.IFRAME_PRESENTATIONAL, + Role.UNKNOWN +]); /** * Returns whether the given node should not be crossed when performing @@ -330,8 +287,7 @@ // The below logic handles nested dialogs properly in the desktop tree // like that found in a bubble view. return node.root.role != Role.DESKTOP || - (!!node.parent && - node.parent.role == Role.WINDOW && + (!!node.parent && node.parent.role == Role.WINDOW && node.parent.children.every(function(child) { return node.role == Role.WINDOW || node.role == Role.DIALOG; })); @@ -369,17 +325,11 @@ return false; // Ignore some roles. - return AutomationPredicate.leaf(node) && - (AutomationPredicate.roles([Role.CLIENT, - Role.COLUMN, - Role.GENERIC_CONTAINER, - Role.GROUP, - Role.IMAGE, - Role.STATIC_TEXT, - Role.SVG_ROOT, - Role.TABLE_HEADER_CONTAINER, - Role.UNKNOWN - ])(node)); + return AutomationPredicate.leaf(node) && (AutomationPredicate.roles([ + Role.CLIENT, Role.COLUMN, Role.GENERIC_CONTAINER, Role.GROUP, + Role.IMAGE, Role.STATIC_TEXT, Role.SVG_ROOT, + Role.TABLE_HEADER_CONTAINER, Role.UNKNOWN + ])(node)); }; /** @@ -388,11 +338,9 @@ * @return {boolean} */ AutomationPredicate.checkable = AutomationPredicate.roles([ - Role.CHECK_BOX, - Role.RADIO_BUTTON, - Role.MENU_ITEM_CHECK_BOX, - Role.MENU_ITEM_RADIO, - Role.TREE_ITEM]); + Role.CHECK_BOX, Role.RADIO_BUTTON, Role.MENU_ITEM_CHECK_BOX, + Role.MENU_ITEM_RADIO, Role.TREE_ITEM +]); // Table related predicates. /** @@ -400,17 +348,15 @@ * @param {!AutomationNode} node * @return {boolean} */ -AutomationPredicate.cellLike = AutomationPredicate.roles([ - Role.CELL, - Role.ROW_HEADER, - Role.COLUMN_HEADER]); +AutomationPredicate.cellLike = + AutomationPredicate.roles([Role.CELL, Role.ROW_HEADER, Role.COLUMN_HEADER]); /** * Returns a predicate that will match against the directed next cell taking * into account the current ancestor cell's position in the table. * @param {AutomationNode} start * @param {{dir: (Dir|undefined), -* row: (boolean|undefined), + * row: (boolean|undefined), * col: (boolean|undefined)}} opts * |dir|, specifies direction for |row or/and |col| movement by one cell. * |dir| defaults to forward. @@ -492,9 +438,7 @@ * @param {!AutomationNode} node * @return {boolean} */ -AutomationPredicate.supportsImageData = AutomationPredicate.roles([ - Role.CANVAS, - Role.IMAGE, - Role.VIDEO]); +AutomationPredicate.supportsImageData = + AutomationPredicate.roles([Role.CANVAS, Role.IMAGE, Role.VIDEO]); }); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util.js index 77e323a..6d60261 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util.js
@@ -42,8 +42,7 @@ var ret = AutomationUtil.findNodePre(child, dir, pred); if (ret) return ret; - child = dir == Dir.BACKWARD ? - child.previousSibling : child.nextSibling; + child = dir == Dir.BACKWARD ? child.previousSibling : child.nextSibling; } return null; }; @@ -65,8 +64,7 @@ var ret = AutomationUtil.findNodePost(child, dir, pred); if (ret) return ret; - child = dir == Dir.BACKWARD ? - child.previousSibling : child.nextSibling; + child = dir == Dir.BACKWARD ? child.previousSibling : child.nextSibling; } if (pred(cur) && !AutomationPredicate.shouldIgnoreNode(cur)) @@ -101,10 +99,12 @@ */ AutomationUtil.findNextNode = function(cur, dir, pred, opt_restrictions) { var restrictions = {}; - opt_restrictions = opt_restrictions || {leaf: undefined, - root: undefined, - visit: undefined, - skipInitialSubtree: !AutomationPredicate.container(cur) && pred(cur)}; + opt_restrictions = opt_restrictions || { + leaf: undefined, + root: undefined, + visit: undefined, + skipInitialSubtree: !AutomationPredicate.container(cur) && pred(cur) + }; restrictions.root = opt_restrictions.root || AutomationPredicate.root; restrictions.leaf = opt_restrictions.leaf || function(node) { @@ -288,10 +288,8 @@ if (!root || root.role == RoleType.DESKTOP) return null; - while (root && - root.parent && - root.parent.root && - root.parent.root.role != RoleType.DESKTOP) { + while (root && root.parent && root.parent.root && + root.parent.root.role != RoleType.DESKTOP) { root = root.parent.root; } return root;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js index 8c85cb7..0c9805a 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js
@@ -93,21 +93,22 @@ // Next earcons or the Classic earcons depending on the current mode. Object.defineProperty(cvox.ChromeVox, 'earcons', { get: (function() { - if (this.mode === ChromeVoxMode.FORCE_NEXT || - this.mode === ChromeVoxMode.NEXT) { - return this.nextEarcons_; - } else { - return this.classicEarcons_; - } - }).bind(this) + if (this.mode === ChromeVoxMode.FORCE_NEXT || + this.mode === ChromeVoxMode.NEXT) { + return this.nextEarcons_; + } else { + return this.classicEarcons_; + } + }).bind(this) }); if (cvox.ChromeVox.isChromeOS) { Object.defineProperty(cvox.ChromeVox, 'modKeyStr', { get: function() { return (this.mode == ChromeVoxMode.CLASSIC || - this.mode == ChromeVoxMode.CLASSIC_COMPAT) ? - 'Search+Shift' : 'Search'; + this.mode == ChromeVoxMode.CLASSIC_COMPAT) ? + 'Search+Shift' : + 'Search'; }.bind(this) }); @@ -174,11 +175,13 @@ // Record a metric with the mode we're in on startup. var useNext = localStorage['useClassic'] != 'true'; chrome.metricsPrivate.recordValue( - { metricName: 'Accessibility.CrosChromeVoxNext', + { + metricName: 'Accessibility.CrosChromeVoxNext', type: chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LINEAR, min: 1, // According to histogram.h, this should be 1 for enums. max: 2, // Maximum should be exclusive. - buckets: 3 }, // Number of buckets: 0, 1 and overflowing 2. + buckets: 3 + }, // Number of buckets: 0, 1 and overflowing 2. useNext ? 1 : 0); }; @@ -245,15 +248,13 @@ // Closure complains, but clearly, |target| is not null. var topLevelRoot = - AutomationUtil.getTopLevelRoot(/** @type {!AutomationNode} */(target)); + AutomationUtil.getTopLevelRoot(/** @type {!AutomationNode} */ (target)); if (!topLevelRoot) - return useNext ? ChromeVoxMode.FORCE_NEXT : - ChromeVoxMode.CLASSIC_COMPAT; + return useNext ? ChromeVoxMode.FORCE_NEXT : ChromeVoxMode.CLASSIC_COMPAT; var docUrl = topLevelRoot.docUrl || ''; var nextSite = this.isWhitelistedForNext_(docUrl); - var classicCompat = - this.isWhitelistedForClassicCompat_(docUrl); + var classicCompat = this.isWhitelistedForClassicCompat_(docUrl); if (classicCompat && !useNext) return ChromeVoxMode.CLASSIC_COMPAT; else if (nextSite) @@ -290,8 +291,7 @@ // async. Save it to ensure we're looking at the currentRange at this moment // in time. var cur = this.currentRange_; - chrome.tabs.query({active: true, - lastFocusedWindow: true}, function(tabs) { + chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) { if (newMode == ChromeVoxMode.CLASSIC) { // Generally, we don't want to inject classic content scripts as it is // done by the extension system at document load. The exception is when @@ -362,8 +362,8 @@ else this.setCurrentRange(null); - var announce = Msgs.getMsg(useNext ? - 'switch_to_next' : 'switch_to_classic'); + var announce = + Msgs.getMsg(useNext ? 'switch_to_next' : 'switch_to_classic'); cvox.ChromeVox.tts.speak( announce, cvox.QueueMode.FLUSH, {doNotInterrupt: true}); @@ -439,19 +439,17 @@ var o = new Output(); var selectedRange; - if (this.pageSel_ && - this.pageSel_.isValid() && - range.isValid()) { + if (this.pageSel_ && this.pageSel_.isValid() && range.isValid()) { // Compute the direction of the endpoints of each range. // Casts are ok because isValid checks node start and end nodes are // non-null; Closure just doesn't eval enough to see it. - var startDir = - AutomationUtil.getDirection(this.pageSel_.start.node, - /** @type {!AutomationNode} */ (range.start.node)); - var endDir = - AutomationUtil.getDirection(this.pageSel_.end.node, - /** @type {!AutomationNode} */ (range.end.node)); + var startDir = AutomationUtil.getDirection( + this.pageSel_.start.node, + /** @type {!AutomationNode} */ (range.start.node)); + var endDir = AutomationUtil.getDirection( + this.pageSel_.end.node, + /** @type {!AutomationNode} */ (range.end.node)); // Selection across roots isn't supported. var pageRootStart = this.pageSel_.start.node.root; @@ -460,10 +458,8 @@ var curRootEnd = range.end.node.root; // Disallow crossing over the start of the page selection and roots. - if (startDir == Dir.BACKWARD || - pageRootStart != pageRootEnd || - pageRootStart != curRootStart || - pageRootEnd != curRootEnd) { + if (startDir == Dir.BACKWARD || pageRootStart != pageRootEnd || + pageRootStart != curRootStart || pageRootEnd != curRootEnd) { o.format('@end_selection'); this.pageSel_ = null; } else { @@ -471,16 +467,13 @@ var msg; if (endDir == Dir.FORWARD && (this.pageSel_.end.node != range.end.node || - this.pageSel_.end.index <= range.end.index)) { + this.pageSel_.end.index <= range.end.index)) { msg = '@selected'; } else { msg = '@unselected'; selectedRange = prevRange; } - this.pageSel_ = new cursors.Range( - this.pageSel_.start, - range.end - ); + this.pageSel_ = new cursors.Range(this.pageSel_.start, range.end); if (this.pageSel_) this.pageSel_.select(); } @@ -488,8 +481,8 @@ // Ensure we don't select the editable when we first encounter it. var lca = null; if (range.start.node && prevRange.start.node) { - lca = AutomationUtil.getLeastCommonAncestor(prevRange.start.node, - range.start.node); + lca = AutomationUtil.getLeastCommonAncestor( + prevRange.start.node, range.start.node); } if (!lca || lca.state[StateType.EDITABLE] || !range.start.node.state[StateType.EDITABLE]) @@ -497,8 +490,8 @@ } o.withRichSpeechAndBraille( - selectedRange || range, prevRange, Output.EventType.NAVIGATE) - .withQueueMode(cvox.QueueMode.FLUSH); + selectedRange || range, prevRange, Output.EventType.NAVIGATE) + .withQueueMode(cvox.QueueMode.FLUSH); if (msg) o.format(msg); @@ -573,8 +566,7 @@ */ shouldEnableClassicForUrl_: function(url) { return this.mode != ChromeVoxMode.FORCE_NEXT && - !this.isBlacklistedForClassic_(url) && - !this.isWhitelistedForNext_(url); + !this.isBlacklistedForClassic_(url) && !this.isWhitelistedForNext_(url); }, /** @@ -585,9 +577,10 @@ * @return {boolean} */ isWhitelistedForClassicCompat_: function(url) { - return (this.isBlacklistedForClassic_(url) || (this.getCurrentRange() && - !this.getCurrentRange().isWebRange() && - this.getCurrentRange().start.node.state[StateType.FOCUSED])) || false; + return (this.isBlacklistedForClassic_(url) || + (this.getCurrentRange() && !this.getCurrentRange().isWebRange() && + this.getCurrentRange().start.node.state[StateType.FOCUSED])) || + false; }, /** @@ -666,11 +659,12 @@ var targetPosition = position - start + offset; if (actionNode.state.richlyEditable) { - chrome.automation.setDocumentSelection( - { anchorObject: actionNode, - anchorOffset: targetPosition, - focusObject: actionNode, - focusOffset: targetPosition }); + chrome.automation.setDocumentSelection({ + anchorObject: actionNode, + anchorOffset: targetPosition, + focusObject: actionNode, + focusOffset: targetPosition + }); } else { actionNode.setSelection(targetPosition, targetPosition); } @@ -690,10 +684,8 @@ if (action == 'getIsClassicEnabled') { var url = msg['url']; var isClassicEnabled = this.shouldEnableClassicForUrl_(url); - port.postMessage({ - target: 'next', - isClassicEnabled: isClassicEnabled - }); + port.postMessage( + {target: 'next', isClassicEnabled: isClassicEnabled}); } else if (action == 'enableClassicCompatForUrl') { var url = msg['url']; this.classicBlacklist_.add(url); @@ -753,10 +745,7 @@ if (!command) return false; - var msg = { - 'message': 'USER_COMMAND', - 'command': command - }; + var msg = {'message': 'USER_COMMAND', 'command': command}; cvox.ExtensionBridge.send(msg); return true; }, @@ -783,10 +772,11 @@ // First, see if we've crossed a root. Remove once webview handles focus // correctly. if (prevRange && prevRange.start.node && start) { - var entered = AutomationUtil.getUniqueAncestors( - prevRange.start.node, start); + var entered = + AutomationUtil.getUniqueAncestors(prevRange.start.node, start); var embeddedObject = entered.find(function(f) { - return f.role == RoleType.EMBEDDED_OBJECT; }); + return f.role == RoleType.EMBEDDED_OBJECT; + }); if (embeddedObject && !embeddedObject.state[StateType.FOCUSED]) embeddedObject.focus(); } @@ -805,7 +795,8 @@ if (!start.state[StateType.FOCUSED]) start.focus(); return; - } else if (!AutomationPredicate.structuralContainer(end) && + } else if ( + !AutomationPredicate.structuralContainer(end) && end.state[StateType.FOCUSABLE]) { if (!end.state[StateType.FOCUSED]) end.focus(); @@ -839,11 +830,16 @@ * @private */ Background.globsToRegExp_ = function(globs) { - return new RegExp('^(' + globs.map(function(glob) { - return glob.replace(/[.+^$(){}|[\]\\]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/\?/g, '.'); - }).join('|') + ')$'); + return new RegExp( + '^(' + + globs + .map(function(glob) { + return glob.replace(/[.+^$(){}|[\]\\]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/\?/g, '.'); + }) + .join('|') + + ')$'); }; new Background();
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/base_automation_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/base_automation_handler.js index 7aaa8015..a74264f 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/base_automation_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/base_automation_handler.js
@@ -77,11 +77,10 @@ }, /** - * Called after the event |evt| is handled. + * Called after the event |evt| is handled. * @protected */ - didHandleEvent_: function(evt) { - } + didHandleEvent_: function(evt) {} }; }); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js index 9469ee7..9cc7d0c 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/braille_command_handler.js
@@ -13,8 +13,7 @@ * Maps a dot pattern to a command. * @type {!Object<number, string>} */ -BrailleCommandHandler.DOT_PATTERN_TO_COMMAND = { -}; +BrailleCommandHandler.DOT_PATTERN_TO_COMMAND = {}; /** * Makes a dot pattern given a list of dots numbered from 1 to 8 arranged in a @@ -93,8 +92,9 @@ */ BrailleCommandHandler.init_ = function() { var map = function(dots, command) { - BrailleCommandHandler.DOT_PATTERN_TO_COMMAND[ - BrailleCommandHandler.makeDotPattern(dots)] = command; + BrailleCommandHandler + .DOT_PATTERN_TO_COMMAND[BrailleCommandHandler.makeDotPattern(dots)] = + command; }; map([2, 3], 'previousGroup'); @@ -148,4 +148,4 @@ BrailleCommandHandler.init_(); -}); // goog.scope +}); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/chromevox_state.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/chromevox_state.js index 3373797..9304206 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/chromevox_state.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/chromevox_state.js
@@ -63,8 +63,8 @@ /** * @type {boolean} - */ - ChromeVoxState.isReadingContinuously; + */ +ChromeVoxState.isReadingContinuously; ChromeVoxState.prototype = { /** @type {ChromeVoxMode} */
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js index ad04393..57c3451 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js
@@ -45,11 +45,14 @@ chrome.automation.getDesktop(function(d) { // First, try speaking the on-screen time. var allTime = d.findAll({role: RoleType.TIME}); - allTime.filter(function(t) { return t.root.role == RoleType.DESKTOP; }); + allTime.filter(function(t) { + return t.root.role == RoleType.DESKTOP; + }); var timeString = ''; allTime.forEach(function(t) { - if (t.name) timeString = t.name; + if (t.name) + timeString = t.name; }); if (timeString) { cvox.ChromeVox.tts.speak(timeString, cvox.QueueMode.FLUSH); @@ -467,8 +470,8 @@ case 'jumpToTop': var node = AutomationUtil.findNodePost( current.start.node.root, Dir.FORWARD, AutomationPredicate.leaf); - if (node) - current = cursors.Range.fromNode(node); + if (node) + current = cursors.Range.fromNode(node); break; case 'jumpToBottom': var node = AutomationUtil.findNodePost( @@ -480,7 +483,7 @@ if (ChromeVoxState.instance.currentRange) { var actionNode = ChromeVoxState.instance.currentRange.start.node; while (actionNode.role == RoleType.INLINE_TEXT_BOX || - actionNode.role == RoleType.STATIC_TEXT) + actionNode.role == RoleType.STATIC_TEXT) actionNode = actionNode.parent; if (actionNode.inPageLinkTarget) { ChromeVoxState.instance.navigateToRange( @@ -500,9 +503,8 @@ return; var prevRange = ChromeVoxState.instance.currentRange_; - var newRange = - ChromeVoxState.instance.currentRange_.move( - cursors.Unit.NODE, Dir.FORWARD); + var newRange = ChromeVoxState.instance.currentRange_.move( + cursors.Unit.NODE, Dir.FORWARD); // Stop if we've wrapped back to the document. var maybeDoc = newRange.start.node; @@ -515,17 +517,17 @@ ChromeVoxState.instance.setCurrentRange(newRange); new Output() - .withRichSpeechAndBraille(ChromeVoxState.instance.currentRange_, - prevRange, - Output.EventType.NAVIGATE) + .withRichSpeechAndBraille( + ChromeVoxState.instance.currentRange_, prevRange, + Output.EventType.NAVIGATE) .onSpeechEnd(continueReading) .go(); }.bind(this); new Output() - .withRichSpeechAndBraille(ChromeVoxState.instance.currentRange_, - null, - Output.EventType.NAVIGATE) + .withRichSpeechAndBraille( + ChromeVoxState.instance.currentRange_, null, + Output.EventType.NAVIGATE) .onSpeechEnd(continueReading) .go(); @@ -570,7 +572,8 @@ output.withString(target.name || target.docUrl); } else { // Views. - while (target.role != RoleType.WINDOW) target = target.parent; + while (target.role != RoleType.WINDOW) + target = target.parent; if (target) output.withString(target.name || ''); } @@ -661,8 +664,8 @@ node = node.parent; if (!node) break; - var end = AutomationUtil.findNodePost(node, - command == 'goToRowLastCell' ? Dir.BACKWARD : Dir.FORWARD, + var end = AutomationUtil.findNodePost( + node, command == 'goToRowLastCell' ? Dir.BACKWARD : Dir.FORWARD, AutomationPredicate.leaf); if (end) current = cursors.Range.fromNode(end); @@ -704,8 +707,8 @@ node = node.parent; if (!node) break; - var end = AutomationUtil.findNodePost(node, - command == 'goToLastCell' ? Dir.BACKWARD : Dir.FORWARD, + var end = AutomationUtil.findNodePost( + node, command == 'goToLastCell' ? Dir.BACKWARD : Dir.FORWARD, AutomationPredicate.leaf); if (end) current = cursors.Range.fromNode(end); @@ -740,22 +743,24 @@ bound = root; } else { bound = AutomationUtil.findNodePost( - root, dir, AutomationPredicate.leaf) || bound; + root, dir, AutomationPredicate.leaf) || + bound; } node = AutomationUtil.findNextNode( bound, dir, pred, {skipInitialAncestry: true}); - if (node && !skipSync) { - node = AutomationUtil.findNodePre( - node, Dir.FORWARD, AutomationPredicate.object) || node; - } + if (node && !skipSync) { + node = AutomationUtil.findNodePre( + node, Dir.FORWARD, AutomationPredicate.object) || + node; + } - if (node) { - current = cursors.Range.fromNode(node); - } else if (predErrorMsg) { + if (node) { + current = cursors.Range.fromNode(node); + } else if (predErrorMsg) { cvox.ChromeVox.tts.speak( Msgs.getMsg(predErrorMsg), cvox.QueueMode.FLUSH); - return false; + return false; } } } @@ -792,12 +797,12 @@ * step size, otherwise decreases. * @private */ -CommandHandler.increaseOrDecreaseSpeechProperty_ = - function(propertyName, increase) { +CommandHandler.increaseOrDecreaseSpeechProperty_ = function( + propertyName, increase) { cvox.ChromeVox.tts.increaseOrDecreaseProperty(propertyName, increase); var announcement; - var valueAsPercent = Math.round( - cvox.ChromeVox.tts.propertyToPercentage(propertyName) * 100); + var valueAsPercent = + Math.round(cvox.ChromeVox.tts.propertyToPercentage(propertyName) * 100); switch (propertyName) { case cvox.AbstractTts.RATE: announcement = Msgs.getMsg('announce_rate', [valueAsPercent]); @@ -833,11 +838,11 @@ return; if (!AutomationUtil.isDescendantOf( - ChromeVoxState.instance.currentRange.start.node, - CommandHandler.imageNode_)) { + ChromeVoxState.instance.currentRange.start.node, + CommandHandler.imageNode_)) { CommandHandler.imageNode_.removeEventListener( - EventType.IMAGE_FRAME_UPDATED, - CommandHandler.onImageFrameUpdated_, false); + EventType.IMAGE_FRAME_UPDATED, CommandHandler.onImageFrameUpdated_, + false); CommandHandler.imageNode_ = null; return; } @@ -857,20 +862,19 @@ CommandHandler.viewGraphicAsBraille_ = function(current) { if (CommandHandler.imageNode_) { CommandHandler.imageNode_.removeEventListener( - EventType.IMAGE_FRAME_UPDATED, - CommandHandler.onImageFrameUpdated_, false); + EventType.IMAGE_FRAME_UPDATED, CommandHandler.onImageFrameUpdated_, + false); CommandHandler.imageNode_ = null; } // Find the first node within the current range that supports image data. var imageNode = AutomationUtil.findNodePost( - current.start.node, Dir.FORWARD, - AutomationPredicate.supportsImageData); + current.start.node, Dir.FORWARD, AutomationPredicate.supportsImageData); if (!imageNode) return; - imageNode.addEventListener(EventType.IMAGE_FRAME_UPDATED, - this.onImageFrameUpdated_, false); + imageNode.addEventListener( + EventType.IMAGE_FRAME_UPDATED, this.onImageFrameUpdated_, false); CommandHandler.imageNode_ = imageNode; if (imageNode.imageDataUrl) { var event = new CustomAutomationEvent( @@ -887,30 +891,30 @@ */ CommandHandler.init_ = function() { var firstRunId = 'jdgcneonijmofocbhmijhacgchbihela'; - chrome.runtime.onMessageExternal.addListener( - function(request, sender, sendResponse) { - if (sender.id != firstRunId) - return; + chrome.runtime.onMessageExternal.addListener(function( + request, sender, sendResponse) { + if (sender.id != firstRunId) + return; - if (request.openTutorial) { - var launchTutorial = function(desktop, evt) { - desktop.removeEventListener( - chrome.automation.EventType.FOCUS, launchTutorial, true); - CommandHandler.onCommand('help'); - }; + if (request.openTutorial) { + var launchTutorial = function(desktop, evt) { + desktop.removeEventListener( + chrome.automation.EventType.FOCUS, launchTutorial, true); + CommandHandler.onCommand('help'); + }; - // Since we get this command early on ChromeVox launch, the first run - // UI is not yet shown. Monitor for when first run gets focused, and - // show our tutorial. - chrome.automation.getDesktop(function(desktop) { - launchTutorial = launchTutorial.bind(this, desktop); - desktop.addEventListener( - chrome.automation.EventType.FOCUS, launchTutorial, true); - }); - } + // Since we get this command early on ChromeVox launch, the first run + // UI is not yet shown. Monitor for when first run gets focused, and + // show our tutorial. + chrome.automation.getDesktop(function(desktop) { + launchTutorial = launchTutorial.bind(this, desktop); + desktop.addEventListener( + chrome.automation.EventType.FOCUS, launchTutorial, true); }); + } + }); }; CommandHandler.init_(); -}); // goog.scope +}); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js index b3e9555..7142a0e7 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js
@@ -88,12 +88,13 @@ node = nextNode; index = 0; } - } else if (node.role == RoleType.GENERIC_CONTAINER && - node.state.richlyEditable && - (node.firstChild && (node.firstChild.role == RoleType.LINE_BREAK || - node.firstChild.role == RoleType.STATIC_TEXT))) { + } else if ( + node.role == RoleType.GENERIC_CONTAINER && node.state.richlyEditable && + (node.firstChild && + (node.firstChild.role == RoleType.LINE_BREAK || + node.firstChild.role == RoleType.STATIC_TEXT))) { // Re-interpret this case as pointing to the text under the div. - node = node.find({ role: RoleType.INLINE_TEXT_BOX }) || node; + node = node.find({role: RoleType.INLINE_TEXT_BOX}) || node; } /** @type {number} @private */ @@ -126,8 +127,7 @@ * @return {boolean} */ equals: function(rhs) { - return this.node === rhs.node && - this.index === rhs.index; + return this.node === rhs.node && this.index === rhs.index; }, /** @@ -142,11 +142,13 @@ // node. var lNode = this.node; var rNode = rhs.node; - while (lNode && (lNode.role == RoleType.INLINE_TEXT_BOX || - lNode.role == RoleType.STATIC_TEXT)) + while (lNode && + (lNode.role == RoleType.INLINE_TEXT_BOX || + lNode.role == RoleType.STATIC_TEXT)) lNode = lNode.parent; - while (rNode && (rNode.role == RoleType.INLINE_TEXT_BOX || - rNode.role == RoleType.STATIC_TEXT)) + while (rNode && + (rNode.role == RoleType.INLINE_TEXT_BOX || + rNode.role == RoleType.STATIC_TEXT)) rNode = rNode.parent; // Ignore indicies for now. @@ -216,7 +218,8 @@ adjustedNode = grandparent; } else if (grandparent && grandparent.role == RoleType.LINE_BREAK) { adjustedNode = grandparent.parent; - } else if (this.index_ == cursors.NODE_INDEX || + } else if ( + this.index_ == cursors.NODE_INDEX || adjustedNode.role == RoleType.INLINE_TEXT_BOX || adjustedNode.nameFrom != chrome.automation.NameFromType.CONTENTS) { // A node offset or unselectable character offset. @@ -245,8 +248,9 @@ if (this.node.state.editable) { return this.index_ == cursors.NODE_INDEX ? 0 : this.index_; - } else if (this.node.role == RoleType.INLINE_TEXT_BOX && - // Selections under a line break are broken. + } else if ( + this.node.role == RoleType.INLINE_TEXT_BOX && + // Selections under a line break are broken. this.node.parent && this.node.parent.role != RoleType.LINE_BREAK) { if (adjustedIndex == cursors.NODE_INDEX) adjustedIndex = 0; @@ -256,7 +260,8 @@ adjustedIndex += sibling.name.length; sibling = sibling.previousSibling; } - } else if (this.index_ == cursors.NODE_INDEX || + } else if ( + this.index_ == cursors.NODE_INDEX || this.node.nameFrom != chrome.automation.NameFromType.CONTENTS) { // A node offset or unselectable character offset. @@ -312,8 +317,8 @@ newNode, dir, AutomationPredicate.leafWithText); if (newNode) { var newText = AutomationUtil.getText(newNode); - newIndex = - dir == Dir.FORWARD ? 0 : + newIndex = dir == Dir.FORWARD ? + 0 : StringUtil.previousCodePointOffset(newText, newText.length); newIndex = Math.max(newIndex, 0); } else { @@ -323,10 +328,10 @@ break; case Unit.WORD: if (newNode.role != RoleType.INLINE_TEXT_BOX) { - newNode = AutomationUtil.findNextNode(newNode, - Dir.FORWARD, - AutomationPredicate.inlineTextBox, - {skipInitialSubtree: false}) || newNode; + newNode = AutomationUtil.findNextNode( + newNode, Dir.FORWARD, AutomationPredicate.inlineTextBox, + {skipInitialSubtree: false}) || + newNode; } switch (movement) { case Movement.BOUND: @@ -365,8 +370,8 @@ if (dir == Dir.BACKWARD && newIndex != 0) { newIndex = 0; } else { - newNode = AutomationUtil.findNextNode(newNode, dir, - AutomationPredicate.leaf); + newNode = AutomationUtil.findNextNode( + newNode, dir, AutomationPredicate.leaf); if (newNode) { newIndex = 0; if (dir == Dir.BACKWARD && @@ -391,10 +396,10 @@ newIndex = dir == Dir.FORWARD ? this.getText().length - 1 : 0; break; case Movement.DIRECTIONAL: - var pred = unit == Unit.TEXT ? - AutomationPredicate.leaf : AutomationPredicate.object; - newNode = AutomationUtil.findNextNode(newNode, dir, pred) || - originalNode; + var pred = unit == Unit.TEXT ? AutomationPredicate.leaf : + AutomationPredicate.object; + newNode = + AutomationUtil.findNextNode(newNode, dir, pred) || originalNode; newIndex = cursors.NODE_INDEX; break; } @@ -406,8 +411,8 @@ switch (movement) { case Movement.BOUND: - newNode = AutomationUtil.findNodeUntil(newNode, dir, - AutomationPredicate.linebreak, true); + newNode = AutomationUtil.findNodeUntil( + newNode, dir, AutomationPredicate.linebreak, true); newNode = newNode || originalNode; newIndex = dir == Dir.FORWARD ? AutomationUtil.getText(newNode).length : 0; @@ -416,8 +421,8 @@ newNode = AutomationUtil.findNodeUntil( newNode, dir, AutomationPredicate.linebreak); break; - } - break; + } + break; default: throw Error('Unrecognized unit: ' + unit); } @@ -450,7 +455,8 @@ newIndex = newIndex - length; } break; - } else if (newNode.role != RoleType.INLINE_TEXT_BOX && + } else if ( + newNode.role != RoleType.INLINE_TEXT_BOX && newNode.children[newIndex]) { // Valid node offset. newNode = newNode.children[newIndex]; @@ -506,8 +512,7 @@ return this; // Regular movement. - if (!AutomationPredicate.root(this.node) || - dir == Dir.FORWARD || + if (!AutomationPredicate.root(this.node) || dir == Dir.FORWARD || movement == Movement.BOUND) result = cursors.Cursor.prototype.move.call(this, unit, movement, dir); @@ -523,8 +528,8 @@ // For 2, place range on the root (if not already there). If at root, // try to descend to the first leaf-like object. if (movement == Movement.DIRECTIONAL && result.equals(this)) { - var pred = unit == Unit.NODE ? - AutomationPredicate.object : AutomationPredicate.leaf; + var pred = unit == Unit.NODE ? AutomationPredicate.object : + AutomationPredicate.leaf; var endpoint = this.node; if (!endpoint) return this; @@ -539,11 +544,9 @@ // Case 2: backward (sync downwards to a leaf), if already on the root. if (dir == Dir.BACKWARD && endpoint == this.node) { playEarcon = true; - endpoint = AutomationUtil.findNodePre(endpoint, - dir, - function(n) { - return pred(n) && !AutomationPredicate.shouldIgnoreNode(n); - }) || endpoint; + endpoint = AutomationUtil.findNodePre(endpoint, dir, function(n) { + return pred(n) && !AutomationPredicate.shouldIgnoreNode(n); + }) || endpoint; } if (playEarcon) @@ -580,7 +583,7 @@ return new cursors.Range(cursor, cursor); }; - /** +/** * Given |rangeA| and |rangeB| in order, determine which |Dir| * relates them. * @param {!cursors.Range} rangeA @@ -591,8 +594,8 @@ if (!rangeA || !rangeB) return Dir.FORWARD; - if (!rangeA.start.node || !rangeA.end.node || - !rangeB.start.node || !rangeB.end.node) + if (!rangeA.start.node || !rangeA.end.node || !rangeB.start.node || + !rangeB.end.node) return Dir.FORWARD; // They are the same range. @@ -601,11 +604,9 @@ return Dir.FORWARD; var testDirA = - AutomationUtil.getDirection( - rangeA.start.node, rangeB.end.node); + AutomationUtil.getDirection(rangeA.start.node, rangeB.end.node); var testDirB = - AutomationUtil.getDirection( - rangeB.start.node, rangeA.end.node); + AutomationUtil.getDirection(rangeB.start.node, rangeA.end.node); // The two ranges are either partly overlapping or non overlapping. if (testDirA == Dir.FORWARD && testDirB == Dir.BACKWARD) @@ -624,8 +625,7 @@ * @return {boolean} */ equals: function(rhs) { - return this.start_.equals(rhs.start) && - this.end_.equals(rhs.end); + return this.start_.equals(rhs.start) && this.end_.equals(rhs.end); }, /** @@ -668,8 +668,7 @@ * @return {boolean} */ isSubNode: function() { - return this.start.node === this.end.node && - this.start.index > -1 && + return this.start.node === this.end.node && this.start.index > -1 && this.end.index > -1; }, @@ -679,8 +678,7 @@ * @return {boolean?} */ isInlineText: function() { - return this.start.node && - this.end.node && + return this.start.node && this.end.node && this.start.node.role == this.end.node.role && this.start.node.role == RoleType.INLINE_TEXT_BOX; }, @@ -733,32 +731,32 @@ return; // Only allow selections within the same web tree. - if (startNode.root && - startNode.root.role == RoleType.ROOT_WEB_AREA && + if (startNode.root && startNode.root.role == RoleType.ROOT_WEB_AREA && startNode.root == endNode.root) { // We want to adjust to select the entire node for node offsets; // otherwise, use the plain character offset. var startIndex = this.start.selectionIndex_; var endIndex = this.end.index_ == cursors.NODE_INDEX ? - this.end.selectionIndex_ + 1 : this.end.selectionIndex_; + this.end.selectionIndex_ + 1 : + this.end.selectionIndex_; - chrome.automation.setDocumentSelection( - { anchorObject: startNode, - anchorOffset: startIndex, - focusObject: endNode, - focusOffset: endIndex } - ); + chrome.automation.setDocumentSelection({ + anchorObject: startNode, + anchorOffset: startIndex, + focusObject: endNode, + focusOffset: endIndex + }); } }, /** * Returns true if this range has either cursor end on web content. * @return {boolean} - */ + */ isWebRange: function() { return this.isValid() && (this.start.node.root.role != RoleType.DESKTOP || - this.end.node.root.role != RoleType.DESKTOP); + this.end.node.root.role != RoleType.DESKTOP); }, /**
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/desktop_automation_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/desktop_automation_handler.js index 584adc37..ae5450bd 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/desktop_automation_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/desktop_automation_handler.js
@@ -43,61 +43,46 @@ */ this.lastValueChanged_ = new Date(0); - this.addListener_(EventType.ACTIVEDESCENDANTCHANGED, - this.onActiveDescendantChanged); - this.addListener_(EventType.ALERT, - this.onAlert); - this.addListener_(EventType.ARIA_ATTRIBUTE_CHANGED, - this.onAriaAttributeChanged); - this.addListener_(EventType.AUTOCORRECTION_OCCURED, - this.onEventIfInRange); - this.addListener_(EventType.BLUR, - this.onBlur); - this.addListener_(EventType.CHECKED_STATE_CHANGED, - this.onCheckedStateChanged); - this.addListener_(EventType.CHILDREN_CHANGED, - this.onChildrenChanged); - this.addListener_(EventType.EXPANDED_CHANGED, - this.onEventIfInRange); - this.addListener_(EventType.FOCUS, - this.onFocus); - this.addListener_(EventType.HOVER, - this.onHover); - this.addListener_(EventType.INVALID_STATUS_CHANGED, - this.onEventIfInRange); - this.addListener_(EventType.LOAD_COMPLETE, - this.onLoadComplete); - this.addListener_(EventType.MENU_END, - this.onMenuEnd); - this.addListener_(EventType.MENU_LIST_ITEM_SELECTED, - this.onEventIfSelected); - this.addListener_(EventType.MENU_START, - this.onMenuStart); - this.addListener_(EventType.ROW_COLLAPSED, - this.onEventIfInRange); - this.addListener_(EventType.ROW_EXPANDED, - this.onEventIfInRange); - this.addListener_(EventType.SCROLL_POSITION_CHANGED, - this.onScrollPositionChanged); - this.addListener_(EventType.SELECTION, - this.onSelection); - this.addListener_(EventType.TEXT_CHANGED, - this.onTextChanged); - this.addListener_(EventType.TEXT_SELECTION_CHANGED, - this.onTextSelectionChanged); - this.addListener_(EventType.VALUE_CHANGED, - this.onValueChanged); + this.addListener_( + EventType.ACTIVEDESCENDANTCHANGED, this.onActiveDescendantChanged); + this.addListener_(EventType.ALERT, this.onAlert); + this.addListener_( + EventType.ARIA_ATTRIBUTE_CHANGED, this.onAriaAttributeChanged); + this.addListener_(EventType.AUTOCORRECTION_OCCURED, this.onEventIfInRange); + this.addListener_(EventType.BLUR, this.onBlur); + this.addListener_( + EventType.CHECKED_STATE_CHANGED, this.onCheckedStateChanged); + this.addListener_(EventType.CHILDREN_CHANGED, this.onChildrenChanged); + this.addListener_(EventType.EXPANDED_CHANGED, this.onEventIfInRange); + this.addListener_(EventType.FOCUS, this.onFocus); + this.addListener_(EventType.HOVER, this.onHover); + this.addListener_(EventType.INVALID_STATUS_CHANGED, this.onEventIfInRange); + this.addListener_(EventType.LOAD_COMPLETE, this.onLoadComplete); + this.addListener_(EventType.MENU_END, this.onMenuEnd); + this.addListener_(EventType.MENU_LIST_ITEM_SELECTED, this.onEventIfSelected); + this.addListener_(EventType.MENU_START, this.onMenuStart); + this.addListener_(EventType.ROW_COLLAPSED, this.onEventIfInRange); + this.addListener_(EventType.ROW_EXPANDED, this.onEventIfInRange); + this.addListener_( + EventType.SCROLL_POSITION_CHANGED, this.onScrollPositionChanged); + this.addListener_(EventType.SELECTION, this.onSelection); + this.addListener_(EventType.TEXT_CHANGED, this.onTextChanged); + this.addListener_( + EventType.TEXT_SELECTION_CHANGED, this.onTextSelectionChanged); + this.addListener_(EventType.VALUE_CHANGED, this.onValueChanged); AutomationObjectConstructorInstaller.init(node, function() { - chrome.automation.getFocus((function(focus) { - if (ChromeVoxState.instance.mode != ChromeVoxMode.FORCE_NEXT) - return; + chrome.automation.getFocus( + (function(focus) { + if (ChromeVoxState.instance.mode != ChromeVoxMode.FORCE_NEXT) + return; - if (focus) { - var event = new CustomAutomationEvent(EventType.FOCUS, focus, 'page'); - this.onFocus(event); - } - }).bind(this)); + if (focus) { + var event = + new CustomAutomationEvent(EventType.FOCUS, focus, 'page'); + this.onFocus(event); + } + }).bind(this)); }.bind(this)); }; @@ -142,8 +127,7 @@ return; // Don't output if focused node hasn't changed. - if (prevRange && - evt.type == 'focus' && + if (prevRange && evt.type == 'focus' && ChromeVoxState.instance.currentRange.equals(prevRange)) return; @@ -176,9 +160,9 @@ // Intentionally skip setting range. new Output() - .withRichSpeechAndBraille(cursors.Range.fromNode(evt.target), - prev, - Output.EventType.NAVIGATE) + .withRichSpeechAndBraille( + cursors.Range.fromNode(evt.target), prev, + Output.EventType.NAVIGATE) .go(); } }, @@ -290,7 +274,8 @@ // Always refresh the braille contents. if (curRange && curRange.equals(cursors.Range.fromNode(evt.target))) { - new Output().withBraille(curRange, curRange, Output.EventType.NAVIGATE) + new Output() + .withBraille(curRange, curRange, Output.EventType.NAVIGATE) .go(); } @@ -325,9 +310,9 @@ var prevRange = ChromeVoxState.instance.currentRange; var prevNode = prevRange ? prevRange.start.node : null; if (prevNode) { - var prevRoot = AutomationUtil.getTopLevelRoot(prevNode); + var prevRoot = AutomationUtil.getTopLevelRoot(prevNode); if (prevRoot && prevRoot !== root) - ChromeVoxState.instance.focusRecoveryMap.set(prevRoot, prevRange); + ChromeVoxState.instance.focusRecoveryMap.set(prevRoot, prevRange); } // If a previous node was saved for this focus, restore it. var savedRange = ChromeVoxState.instance.focusRecoveryMap.get(root); @@ -354,10 +339,12 @@ // ChromeVox. this.createTextEditHandlerIfNeeded_(focus); - // If auto read is set, skip focus recovery and start reading from the top. + // If auto read is set, skip focus recovery and start reading from the + // top. if (localStorage['autoRead'] == 'true' && AutomationUtil.getTopLevelRoot(evt.target) == evt.target) { - ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(evt.target)); + ChromeVoxState.instance.setCurrentRange( + cursors.Range.fromNode(evt.target)); cvox.ChromeVox.tts.stop(); CommandHandler.onCommand('readFromHere'); return; @@ -388,7 +375,8 @@ Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH); o.withRichSpeechAndBraille( - ChromeVoxState.instance.currentRange, null, evt.type).go(); + ChromeVoxState.instance.currentRange, null, evt.type) + .go(); }.bind(this)); }, @@ -418,9 +406,7 @@ onEditableChanged_: function(evt) { var topRoot = AutomationUtil.getTopLevelRoot(evt.target); if (!evt.target.state.focused || - (topRoot && - topRoot.parent && - !topRoot.parent.state.focused)) + (topRoot && topRoot.parent && !topRoot.parent.state.focused)) return; if (!ChromeVoxState.instance.currentRange) { @@ -466,8 +452,7 @@ return; var t = evt.target; - if (t.state.focused || - t.root.role == RoleType.DESKTOP || + if (t.state.focused || t.root.role == RoleType.DESKTOP || AutomationUtil.isDescendantOf( ChromeVoxState.instance.currentRange.start.node, t)) { if (new Date() - this.lastValueChanged_ <= @@ -517,7 +502,7 @@ // that focus is an ancestor of a selection target. var override = evt.target.role == RoleType.MENU_ITEM || (evt.target.root == focus.root && - focus.root.role == RoleType.DESKTOP); + focus.root.role == RoleType.DESKTOP); Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH); if (override || AutomationUtil.isDescendantOf(evt.target, focus)) this.onEventDefault(evt); @@ -555,8 +540,7 @@ * @param {!AutomationNode} node */ createTextEditHandlerIfNeeded_: function(node) { - if (!this.textEditHandler_ || - this.textEditHandler_.node !== node) { + if (!this.textEditHandler_ || this.textEditHandler_.node !== node) { this.textEditHandler_ = editing.TextEditHandler.createForNode(node); } }, @@ -570,8 +554,7 @@ var mode = ChromeVoxState.instance.mode; // Only output desktop rooted nodes or web nodes for next engine modes. return evt.target.root.role == RoleType.DESKTOP || - (mode == ChromeVoxMode.NEXT || - mode == ChromeVoxMode.FORCE_NEXT || + (mode == ChromeVoxMode.NEXT || mode == ChromeVoxMode.FORCE_NEXT || mode == ChromeVoxMode.CLASSIC_COMPAT); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/earcon_engine.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/earcon_engine.js index 07c3581..9a4da0e 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/earcon_engine.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/earcon_engine.js
@@ -91,10 +91,10 @@ this.reverbConvolver_ = null; /** - * @type {Object<string, AudioBuffer>} A map between the name of an - * audio data file and its loaded AudioBuffer. - * @private - */ + * @type {Object<string, AudioBuffer>} A map between the name of an + * audio data file and its loaded AudioBuffer. + * @private + */ this.buffers_ = {}; /** @@ -121,28 +121,24 @@ // Initialization: load the base sound data files asynchronously. var allSoundFilesToLoad = EarconEngine.SOUNDS.concat(EarconEngine.REVERBS); allSoundFilesToLoad.forEach((function(sound) { - var url = EarconEngine.BASE_URL + sound + '.wav'; - this.loadSound(sound, url); - }).bind(this)); + var url = + EarconEngine.BASE_URL + sound + '.wav'; + this.loadSound(sound, url); + }).bind(this)); }; /** * @type {Array<string>} The list of sound data files to load. * @const */ -EarconEngine.SOUNDS = [ - 'control', - 'selection', - 'selection_reverse', - 'skim', - 'static']; +EarconEngine.SOUNDS = + ['control', 'selection', 'selection_reverse', 'skim', 'static']; /** * @type {Array<string>} The list of reverb data files to load. * @const */ -EarconEngine.REVERBS = [ - 'small_room_2']; +EarconEngine.REVERBS = ['small_room_2']; /** * @type {number} The scale factor for one half-step. @@ -174,12 +170,12 @@ // Decode asynchronously. request.onload = (function() { - this.context_.decodeAudioData( - /** @type {!ArrayBuffer} */ (request.response), - (function(buffer) { - this.buffers_[name] = buffer; - }).bind(this)); - }).bind(this); + this.context_.decodeAudioData( + /** @type {!ArrayBuffer} */ (request.response), + (function(buffer) { + this.buffers_[name] = buffer; + }).bind(this)); + }).bind(this); request.send(); }; @@ -276,7 +272,7 @@ if (!opt_properties) { // This typecast looks silly, but the Closure compiler doesn't support // optional fields in record types very well so this is the shortest hack. - opt_properties = /** @type {undefined} */({}); + opt_properties = /** @type {undefined} */ ({}); } var pitch = this.masterPitch; @@ -327,13 +323,11 @@ */ EarconEngine.prototype.onTextField = function() { this.play('static', {gain: this.clickVolume}); - this.play('static', {time: this.baseDelay * 1.5, - gain: this.clickVolume * 0.5}); + this.play( + 'static', {time: this.baseDelay * 1.5, gain: this.clickVolume * 0.5}); this.play(this.controlSound, {pitch: 4}); - this.play(this.controlSound, - {pitch: 4, - time: this.baseDelay * 1.5, - gain: 0.5}); + this.play( + this.controlSound, {pitch: 4, time: this.baseDelay * 1.5, gain: 0.5}); }; /** @@ -343,14 +337,10 @@ this.play('static', {gain: this.clickVolume}); this.play(this.controlSound); - this.play(this.controlSound, - {time: this.baseDelay * 3, - gain: 0.2, - pitch: 12}); - this.play(this.controlSound, - {time: this.baseDelay * 4.5, - gain: 0.2, - pitch: 12}); + this.play( + this.controlSound, {time: this.baseDelay * 3, gain: 0.2, pitch: 12}); + this.play( + this.controlSound, {time: this.baseDelay * 4.5, gain: 0.2, pitch: 12}); }; /** @@ -387,22 +377,13 @@ EarconEngine.prototype.onSlider = function() { this.play('static', {gain: this.clickVolume}); this.play(this.controlSound); - this.play(this.controlSound, - {time: this.baseDelay, - gain: 0.5, - pitch: 2}); - this.play(this.controlSound, - {time: this.baseDelay * 2, - gain: 0.25, - pitch: 4}); - this.play(this.controlSound, - {time: this.baseDelay * 3, - gain: 0.125, - pitch: 6}); - this.play(this.controlSound, - {time: this.baseDelay * 4, - gain: 0.0625, - pitch: 8}); + this.play(this.controlSound, {time: this.baseDelay, gain: 0.5, pitch: 2}); + this.play( + this.controlSound, {time: this.baseDelay * 2, gain: 0.25, pitch: 4}); + this.play( + this.controlSound, {time: this.baseDelay * 3, gain: 0.125, pitch: 6}); + this.play( + this.controlSound, {time: this.baseDelay * 4, gain: 0.0625, pitch: 8}); }; /** @@ -480,8 +461,7 @@ if (properties.endFreq) { osc.frequency.setValueAtTime( - properties.freq * (i + 1), - this.context_.currentTime + time); + properties.freq * (i + 1), this.context_.currentTime + time); osc.frequency.exponentialRampToValueAtTime( properties.endFreq * (i + 1), this.context_.currentTime + properties.dur); @@ -504,8 +484,7 @@ envelopeNode.gain.linearRampToValueAtTime( 1, this.context_.currentTime + time + properties.attack); envelopeNode.gain.setValueAtTime( - 1, this.context_.currentTime + time + - properties.dur - properties.decay); + 1, this.context_.currentTime + time + properties.dur - properties.decay); envelopeNode.gain.linearRampToValueAtTime( 0, this.context_.currentTime + time + properties.dur); @@ -600,20 +579,24 @@ EarconEngine.prototype.onAlert = function() { var freq1 = 220 * Math.pow(EarconEngine.HALF_STEP, this.alertPitch - 2); var freq2 = 220 * Math.pow(EarconEngine.HALF_STEP, this.alertPitch - 3); - this.generateSinusoidal({attack: 0.02, - decay: 0.07, - dur: 0.15, - gain: 0.3, - freq: freq1, - overtones: 3, - overtoneFactor: 0.1}); - this.generateSinusoidal({attack: 0.02, - decay: 0.07, - dur: 0.15, - gain: 0.3, - freq: freq2, - overtones: 3, - overtoneFactor: 0.1}); + this.generateSinusoidal({ + attack: 0.02, + decay: 0.07, + dur: 0.15, + gain: 0.3, + freq: freq1, + overtones: 3, + overtoneFactor: 0.1 + }); + this.generateSinusoidal({ + attack: 0.02, + decay: 0.07, + dur: 0.15, + gain: 0.3, + freq: freq2, + overtones: 3, + overtoneFactor: 0.1 + }); }; /** @@ -623,14 +606,16 @@ this.play('static', {gain: this.clickVolume * 0.3}); var freq1 = 220 * Math.pow(EarconEngine.HALF_STEP, this.wrapPitch - 8); var freq2 = 220 * Math.pow(EarconEngine.HALF_STEP, this.wrapPitch + 8); - this.generateSinusoidal({attack: 0.01, - decay: 0.1, - dur: 0.15, - gain: 0.3, - freq: freq1, - endFreq: freq2, - overtones: 1, - overtoneFactor: 0.1}); + this.generateSinusoidal({ + attack: 0.01, + decay: 0.1, + dur: 0.15, + gain: 0.3, + freq: freq1, + endFreq: freq2, + overtones: 1, + overtoneFactor: 0.1 + }); }; /** @@ -641,34 +626,30 @@ EarconEngine.prototype.generateProgressTickTocks_ = function() { while (this.progressTime_ < this.context_.currentTime + 3.0) { var t = this.progressTime_ - this.context_.currentTime; - this.progressSources_.push( - [this.progressTime_, - this.play('static', - {gain: 0.5 * this.progressGain_, - time: t})]); - this.progressSources_.push( - [this.progressTime_, - this.play(this.controlSound, - {pitch: 20, - time: t, - gain: this.progressGain_})]); + this.progressSources_.push([ + this.progressTime_, + this.play('static', {gain: 0.5 * this.progressGain_, time: t}) + ]); + this.progressSources_.push([ + this.progressTime_, + this.play( + this.controlSound, {pitch: 20, time: t, gain: this.progressGain_}) + ]); if (this.progressGain_ > this.progressFinalGain) { this.progressGain_ *= this.progressGain_Decay; } t += 0.5; - this.progressSources_.push( - [this.progressTime_, - this.play('static', - {gain: 0.5 * this.progressGain_, - time: t})]); - this.progressSources_.push( - [this.progressTime_, - this.play(this.controlSound, - {pitch: 8, - time: t, - gain: this.progressGain_})]); + this.progressSources_.push([ + this.progressTime_, + this.play('static', {gain: 0.5 * this.progressGain_, time: t}) + ]); + this.progressSources_.push([ + this.progressTime_, + this.play( + this.controlSound, {pitch: 8, time: t, gain: this.progressGain_}) + ]); if (this.progressGain_ > this.progressFinalGain) { this.progressGain_ *= this.progressGain_Decay; @@ -679,7 +660,8 @@ var removeCount = 0; while (removeCount < this.progressSources_.length && - this.progressSources_[removeCount][0] < this.context_.currentTime - 0.2) { + this.progressSources_[removeCount][0] < + this.context_.currentTime - 0.2) { removeCount++; } this.progressSources_.splice(0, removeCount); @@ -698,8 +680,8 @@ this.progressGain_ = 0.5; this.progressTime_ = this.context_.currentTime; this.generateProgressTickTocks_(); - this.progressIntervalID_ = window.setInterval( - this.generateProgressTickTocks_.bind(this), 1000); + this.progressIntervalID_ = + window.setInterval(this.generateProgressTickTocks_.bind(this), 1000); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/editing.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/editing.js index a07c904..c18ebb4 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/editing.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/editing.js
@@ -74,12 +74,11 @@ editing.TextEditHandler.call(this, node); chrome.automation.getDesktop(function(desktop) { - var useRichText = editing.useRichText && - node.state.richlyEditable; + var useRichText = editing.useRichText && node.state.richlyEditable; /** @private {!AutomationEditableText} */ - this.editableText_ = useRichText ? - new AutomationRichEditableText(node) : new AutomationEditableText(node); + this.editableText_ = useRichText ? new AutomationRichEditableText(node) : + new AutomationEditableText(node); }.bind(this)); } @@ -90,11 +89,9 @@ onEvent: function(evt) { if (evt.type !== EventType.TEXT_CHANGED && evt.type !== EventType.TEXT_SELECTION_CHANGED && - evt.type !== EventType.VALUE_CHANGED && - evt.type !== EventType.FOCUS) + evt.type !== EventType.VALUE_CHANGED && evt.type !== EventType.FOCUS) return; - if (!evt.target.state.focused || - !evt.target.state.editable || + if (!evt.target.state.focused || !evt.target.state.editable || evt.target != this.node_) return; @@ -115,12 +112,8 @@ var start = node.textSelStart; var end = node.textSelEnd; cvox.ChromeVoxEditableTextBase.call( - this, - node.value || '', - Math.min(start, end), - Math.max(start, end), - node.state[StateType.PROTECTED] /**password*/, - cvox.ChromeVox.tts); + this, node.value || '', Math.min(start, end), Math.max(start, end), + node.state[StateType.PROTECTED] /**password*/, cvox.ChromeVox.tts); /** @override */ this.multiline = node.state[StateType.MULTILINE] || false; /** @type {!AutomationNode} @private */ @@ -142,9 +135,7 @@ this.lineBreaks_ = []; var textChangeEvent = new cvox.TextChangeEvent( - newValue, - this.node_.textSelStart || 0, - this.node_.textSelEnd || 0, + newValue, this.node_.textSelStart || 0, this.node_.textSelEnd || 0, true /* triggered by user */); this.changed(textChangeEvent); this.outputBraille_(); @@ -241,18 +232,15 @@ return; var cur = new editing.EditableLine( - root.anchorObject, root.anchorOffset || 0, - root.focusObject, root.focusOffset || 0); + root.anchorObject, root.anchorOffset || 0, root.focusObject, + root.focusOffset || 0); var prev = this.line_; this.line_ = cur; if (prev.equals(cur)) { // Collapsed cursor. this.changed(new cvox.TextChangeEvent( - cur.text || '', - cur.startOffset || 0, - cur.endOffset || 0, - true)); + cur.text || '', cur.startOffset || 0, cur.endOffset || 0, true)); this.brailleCurrentRichLine_(); // Finally, queue up any text markers/styles at bounds. @@ -324,9 +312,9 @@ if (msgs.length) { msgs.forEach(function(msg) { - cvox.ChromeVox.tts.speak(Msgs.getMsg(msg), - cvox.QueueMode.QUEUE, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + Msgs.getMsg(msg), cvox.QueueMode.QUEUE, + cvox.AbstractTts.PERSONALITY_ANNOTATION); }); } }, @@ -349,9 +337,9 @@ if (msgs.length) { msgs.forEach(function(msg) { - cvox.ChromeVox.tts.speak(Msgs.getMsg(msg), - cvox.QueueMode.QUEUE, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + Msgs.getMsg(msg), cvox.QueueMode.QUEUE, + cvox.AbstractTts.PERSONALITY_ANNOTATION); }); } }, @@ -364,9 +352,7 @@ value.setSpan( new cvox.ValueSelectionSpan(), cur.startOffset, cur.endOffset); cvox.ChromeVox.braille.write(new cvox.NavBraille( - {text: value, - startIndex: cur.startOffset, - endIndex: cur.endOffset})); + {text: value, startIndex: cur.startOffset, endIndex: cur.endOffset})); }, /** @override */ @@ -456,7 +442,7 @@ * An EditableLine encapsulates all data concerning a line in the automation * tree necessary to provide output. * @constructor - */ + */ editing.EditableLine = function(startNode, startIndex, endNode, endIndex) { /** @private {!Cursor} */ this.start_ = new Cursor(startNode, startIndex); @@ -596,7 +582,8 @@ // Also, annotate this span if it is associated with line containre. if (parent == this.startContainer_) this.value_.setSpan(parent, prevLen, len); - } catch (e) {} + } catch (e) { + } } }, @@ -671,7 +658,7 @@ // staying the same. return otherLine.lineStartContainer_ == this.lineStartContainer_ && otherLine.localLineStartContainerOffset_ == - this.localLineStartContainerOffset_; + this.localLineStartContainerOffset_; } };
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/find_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/find_handler.js index af0aa2a9..80ee94d 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/find_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/find_handler.js
@@ -47,7 +47,7 @@ */ FindHandler.onTextMatch_ = function(evt) { if (!evt.target.markerTypes.some(function(markerType) { - return markerType & 4 /* Text match */; + return markerType & 4 /* Text match */; })) return;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js index 070ba0d6..c47ac58 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js
@@ -53,7 +53,8 @@ throw 'Incremental search started from invalid range.'; var leaf = AutomationUtil.findNodePre( - cursor.node, Dir.FORWARD, AutomationPredicate.leaf) || cursor.node; + cursor.node, Dir.FORWARD, AutomationPredicate.leaf) || + cursor.node; /** @type {!cursors.Cursor} */ this.cursor = cursors.Cursor.fromNode(leaf); @@ -90,8 +91,7 @@ var move = function(curNode) { var cur = cursors.Cursor.fromNode(curNode); var prev = cur; - cur = - cur.move(cursors.Unit.NODE, cursors.Movement.DIRECTIONAL, dir); + cur = cur.move(cursors.Unit.NODE, cursors.Movement.DIRECTIONAL, dir); if (prev.equals(cur)) { this.handler_.onSearchReachedBoundary(this.cursor.node); return; @@ -171,9 +171,9 @@ var node = this.iSearch_.cursor.node; if (!node) return; - chrome.extension.getBackgroundPage().ChromeVoxState.instance[ - 'navigateToRange']( - cursors.Range.fromNode(node)); + chrome.extension.getBackgroundPage() + .ChromeVoxState.instance['navigateToRange']( + cursors.Range.fromNode(node)); }.bind(this)); Panel.closeMenusAndRestoreFocus(); return false; @@ -218,8 +218,11 @@ */ output_: function(node) { Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH); - var o = new Output().withRichSpeechAndBraille( - cursors.Range.fromNode(node), null, Output.EventType.NAVIGATE).go(); + var o = + new Output() + .withRichSpeechAndBraille( + cursors.Range.fromNode(node), null, Output.EventType.NAVIGATE) + .go(); this.background_.setCurrentRange(cursors.Range.fromNode(node)); },
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js index 7690467..993fc81 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/keyboard_handler.js
@@ -92,8 +92,8 @@ // Switching out of classic, classic compat, or uninitialized // (on startup). window['prefs'].switchToKeyMap('keymap_next'); - } else if (oldMode && - oldMode != ChromeVoxMode.CLASSIC && + } else if ( + oldMode && oldMode != ChromeVoxMode.CLASSIC && oldMode != ChromeVoxMode.CLASSIC_COMPAT) { // Switching out of next. Intentionally do nothing when switching out of // an uninitialized |oldMode|.
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js index 57197e2d..46784e4 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/live_regions.js
@@ -105,8 +105,8 @@ var removals = relevant.indexOf('removals') >= 0; var all = relevant.indexOf('all') >= 0; - if (all || (additions && - (type == 'nodeCreated' || type == 'subtreeCreated'))) { + if (all || + (additions && (type == 'nodeCreated' || type == 'subtreeCreated'))) { this.outputLiveRegionChange_(node, null); }
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/media_automation_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/media_automation_handler.js index ff6f1fa..3d597d81 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/media_automation_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/media_automation_handler.js
@@ -36,10 +36,10 @@ chrome.automation.getDesktop(function(node) { BaseAutomationHandler.call(this, node); - this.addListener_(EventType.MEDIA_STARTED_PLAYING, - this.onMediaStartedPlaying); - this.addListener_(EventType.MEDIA_STOPPED_PLAYING, - this.onMediaStoppedPlaying); + this.addListener_( + EventType.MEDIA_STARTED_PLAYING, this.onMediaStartedPlaying); + this.addListener_( + EventType.MEDIA_STOPPED_PLAYING, this.onMediaStoppedPlaying); }.bind(this)); };
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/notifications.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/notifications.js index 791e411..780c36c 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/notifications.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/notifications.js
@@ -30,7 +30,7 @@ cvox.ChromeVox.isChromeOS; }, -/** Shows the notification. */ + /** Shows the notification. */ show: function() { if (!this.shouldShow()) return;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index fb5d99d..8a13ff0a2 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -115,244 +115,88 @@ * @private */ Output.ROLE_INFO_ = { - alert: { - msgId: 'role_alert' - }, - alertDialog: { - msgId: 'role_alertdialog', - outputContextFirst: true - }, - article: { - msgId: 'role_article', - inherits: 'abstractContainer' - }, - application: { - msgId: 'role_application', - inherits: 'abstractContainer' - }, - banner: { - msgId: 'role_banner', - inherits: 'abstractContainer' - }, - button: { - msgId: 'role_button', - earconId: 'BUTTON' - }, - buttonDropDown: { - msgId: 'role_button', - earconId: 'BUTTON' - }, - checkBox: { - msgId: 'role_checkbox' - }, - columnHeader: { - msgId: 'role_columnheader', - inherits: 'cell' - }, - comboBox: { - msgId: 'role_combobox', - earconId: 'LISTBOX' - }, - complementary: { - msgId: 'role_complementary', - inherits: 'abstractContainer' - }, - contentInfo: { - msgId: 'role_contentinfo', - inherits: 'abstractContainer' - }, - date: { - msgId: 'input_type_date', - inherits: 'abstractContainer' - }, - definition: { - msgId: 'role_definition', - inherits: 'abstractContainer' - }, - dialog: { - msgId: 'role_dialog', - outputContextFirst: true - }, - directory: { - msgId: 'role_directory', - inherits: 'abstractContainer' - }, - document: { - msgId: 'role_document', - inherits: 'abstractContainer' - }, - form: { - msgId: 'role_form', - inherits: 'abstractContainer' - }, - grid: { - msgId: 'role_grid' - }, - group: { - msgId: 'role_group', - inherits: 'abstractContainer' - }, + alert: {msgId: 'role_alert'}, + alertDialog: {msgId: 'role_alertdialog', outputContextFirst: true}, + article: {msgId: 'role_article', inherits: 'abstractContainer'}, + application: {msgId: 'role_application', inherits: 'abstractContainer'}, + banner: {msgId: 'role_banner', inherits: 'abstractContainer'}, + button: {msgId: 'role_button', earconId: 'BUTTON'}, + buttonDropDown: {msgId: 'role_button', earconId: 'BUTTON'}, + checkBox: {msgId: 'role_checkbox'}, + columnHeader: {msgId: 'role_columnheader', inherits: 'cell'}, + comboBox: {msgId: 'role_combobox', earconId: 'LISTBOX'}, + complementary: {msgId: 'role_complementary', inherits: 'abstractContainer'}, + contentInfo: {msgId: 'role_contentinfo', inherits: 'abstractContainer'}, + date: {msgId: 'input_type_date', inherits: 'abstractContainer'}, + definition: {msgId: 'role_definition', inherits: 'abstractContainer'}, + dialog: {msgId: 'role_dialog', outputContextFirst: true}, + directory: {msgId: 'role_directory', inherits: 'abstractContainer'}, + document: {msgId: 'role_document', inherits: 'abstractContainer'}, + form: {msgId: 'role_form', inherits: 'abstractContainer'}, + grid: {msgId: 'role_grid'}, + group: {msgId: 'role_group', inherits: 'abstractContainer'}, heading: { msgId: 'role_heading', }, image: { msgId: 'role_img', }, - inputTime: { - msgId: 'input_type_time', - inherits: 'abstractContainer' - }, - link: { - msgId: 'role_link', - earconId: 'LINK' - }, - listBox: { - msgId: 'role_listbox', - earconId: 'LISTBOX' - }, - listBoxOption: { - msgId: 'role_listitem', - earconId: 'LIST_ITEM' - }, - listItem: { - msgId: 'role_listitem', - earconId: 'LIST_ITEM' - }, + inputTime: {msgId: 'input_type_time', inherits: 'abstractContainer'}, + link: {msgId: 'role_link', earconId: 'LINK'}, + listBox: {msgId: 'role_listbox', earconId: 'LISTBOX'}, + listBoxOption: {msgId: 'role_listitem', earconId: 'LIST_ITEM'}, + listItem: {msgId: 'role_listitem', earconId: 'LIST_ITEM'}, log: { msgId: 'role_log', }, - main: { - msgId: 'role_main', - inherits: 'abstractContainer' - }, + main: {msgId: 'role_main', inherits: 'abstractContainer'}, marquee: { msgId: 'role_marquee', }, - math: { - msgId: 'role_math', - inherits: 'abstractContainer' - }, - menu: { - msgId: 'role_menu', - outputContextFirst: true - }, + math: {msgId: 'role_math', inherits: 'abstractContainer'}, + menu: {msgId: 'role_menu', outputContextFirst: true}, menuBar: { msgId: 'role_menubar', }, - menuItem: { - msgId: 'role_menuitem' - }, - menuItemCheckBox: { - msgId: 'role_menuitemcheckbox' - }, - menuItemRadio: { - msgId: 'role_menuitemradio' - }, - menuListOption: { - msgId: 'role_menuitem' - }, - menuListPopup: { - msgId: 'role_menu' - }, - meter: { - msgId: 'role_meter', - inherits: 'abstractRange' - }, - navigation: { - msgId: 'role_navigation', - inherits: 'abstractContainer' - }, - note: { - msgId: 'role_note', - inherits: 'abstractContainer' - }, - progressIndicator: { - msgId: 'role_progress_indicator', - inherits: 'abstractRange' - }, - popUpButton: { - msgId: 'role_button', - earconId: 'POP_UP_BUTTON' - }, - radioButton: { - msgId: 'role_radio' - }, + menuItem: {msgId: 'role_menuitem'}, + menuItemCheckBox: {msgId: 'role_menuitemcheckbox'}, + menuItemRadio: {msgId: 'role_menuitemradio'}, + menuListOption: {msgId: 'role_menuitem'}, + menuListPopup: {msgId: 'role_menu'}, + meter: {msgId: 'role_meter', inherits: 'abstractRange'}, + navigation: {msgId: 'role_navigation', inherits: 'abstractContainer'}, + note: {msgId: 'role_note', inherits: 'abstractContainer'}, + progressIndicator: + {msgId: 'role_progress_indicator', inherits: 'abstractRange'}, + popUpButton: {msgId: 'role_button', earconId: 'POP_UP_BUTTON'}, + radioButton: {msgId: 'role_radio'}, radioGroup: { msgId: 'role_radiogroup', }, - rootWebArea: { - outputContextFirst: true - }, - row: { - msgId: 'role_row', - inherits: 'abstractContainer' - }, - rowHeader: { - msgId: 'role_rowheader', - inherits: 'cell' - }, - scrollBar: { - msgId: 'role_scrollbar', - inherits: 'abstractRange' - }, - search: { - msgId: 'role_search', - inherits: 'abstractContainer' - }, - separator: { - msgId: 'role_separator', - inherits: 'abstractContainer' - }, - slider: { - msgId: 'role_slider', - inherits: 'abstractRange', - earconId: 'SLIDER' - }, + rootWebArea: {outputContextFirst: true}, + row: {msgId: 'role_row', inherits: 'abstractContainer'}, + rowHeader: {msgId: 'role_rowheader', inherits: 'cell'}, + scrollBar: {msgId: 'role_scrollbar', inherits: 'abstractRange'}, + search: {msgId: 'role_search', inherits: 'abstractContainer'}, + separator: {msgId: 'role_separator', inherits: 'abstractContainer'}, + slider: {msgId: 'role_slider', inherits: 'abstractRange', earconId: 'SLIDER'}, spinButton: { msgId: 'role_spinbutton', inherits: 'abstractRange', earconId: 'LISTBOX' }, - status: { - msgId: 'role_status' - }, - tab: { - msgId: 'role_tab' - }, - tabList: { - msgId: 'role_tablist' - }, - tabPanel: { - msgId: 'role_tabpanel' - }, - textBox: { - msgId: 'input_type_text', - earconId: 'EDITABLE_TEXT' - }, - textField: { - msgId: 'input_type_text', - earconId: 'EDITABLE_TEXT' - }, - time: { - msgId: 'tag_time', - inherits: 'abstractContainer' - }, - timer: { - msgId: 'role_timer' - }, - toolbar: { - msgId: 'role_toolbar' - }, - toggleButton: { - msgId: 'role_button', - inherits: 'checkBox' - }, - tree: { - msgId: 'role_tree' - }, - treeItem: { - msgId: 'role_treeitem' - } + status: {msgId: 'role_status'}, + tab: {msgId: 'role_tab'}, + tabList: {msgId: 'role_tablist'}, + tabPanel: {msgId: 'role_tabpanel'}, + textBox: {msgId: 'input_type_text', earconId: 'EDITABLE_TEXT'}, + textField: {msgId: 'input_type_text', earconId: 'EDITABLE_TEXT'}, + time: {msgId: 'tag_time', inherits: 'abstractContainer'}, + timer: {msgId: 'role_timer'}, + toolbar: {msgId: 'role_toolbar'}, + toggleButton: {msgId: 'role_button', inherits: 'checkBox'}, + tree: {msgId: 'role_tree'}, + treeItem: {msgId: 'role_treeitem'} }; /** @@ -420,17 +264,13 @@ */ Output.RULES = { navigate: { - 'default': { - speak: '$name $value $state $role $description', - braille: '' - }, + 'default': {speak: '$name $value $state $role $description', braille: ''}, abstractContainer: { enter: '$nameFromNode $role $state $description', leave: '@exited_container($role)' }, abstractRange: { - speak: - '$if($valueForRange, $valueForRange, $value) ' + + speak: '$if($valueForRange, $valueForRange, $value) ' + '$if($minValueForRange, @aria_value_min($minValueForRange)) ' + '$if($maxValueForRange, @aria_value_max($maxValueForRange)) ' + '$name $role $description $state' @@ -445,37 +285,25 @@ }, cell: { enter: '@cell_summary($if($ariaCellRowIndex, $ariaCellRowIndex, ' + - '$tableCellRowIndex), ' + - '$if($ariaCellColumnIndex, $ariaCellColumnIndex, ' + - '$tableCellColumnIndex)) $node(tableColumnHeader)', + '$tableCellRowIndex), ' + + '$if($ariaCellColumnIndex, $ariaCellColumnIndex, ' + + '$tableCellColumnIndex)) $node(tableColumnHeader)', speak: '$name @cell_summary($if($ariaCellRowIndex, $ariaCellRowIndex, ' + - '$tableCellRowIndex), ' + - '$if($ariaCellColumnIndex, $ariaCellColumnIndex, ' + - '$tableCellColumnIndex)) $node(tableColumnHeader) $state' + '$tableCellRowIndex), ' + + '$if($ariaCellColumnIndex, $ariaCellColumnIndex, ' + + '$tableCellColumnIndex)) $node(tableColumnHeader) $state' }, checkBox: { speak: '$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) ' + - '$name $role $checked $description $state' + '$name $role $checked $description $state' }, - client: { - speak: '$name' - }, - date: { - enter: '$nameFromNode $role $description' - }, - dialog: { - enter: '$nameFromNode $role $description' - }, - genericContainer: { - enter: '$nameFromNode', - speak: '$nameOrTextContent $description' - }, - embeddedObject: { - speak: '$name' - }, - grid: { - enter: '$nameFromNode $role $description' - }, + client: {speak: '$name'}, + date: {enter: '$nameFromNode $role $description'}, + dialog: {enter: '$nameFromNode $role $description'}, + genericContainer: + {enter: '$nameFromNode', speak: '$nameOrTextContent $description'}, + embeddedObject: {speak: '$name'}, + grid: {enter: '$nameFromNode $role $description'}, group: { enter: '$nameFromNode $state $description', speak: '$nameOrDescendants $value $state $description', @@ -493,12 +321,8 @@ speak: '$if($name, $name, $urlFilename) ' + '$value $state $role $description', }, - inlineTextBox: { - speak: '$name=' - }, - inputTime: { - enter: '$nameFromNode $role $description' - }, + inlineTextBox: {speak: '$name='}, + inputTime: {enter: '$nameFromNode $role $description'}, link: { enter: '$nameFromNode= $role $state', speak: '$name $value $state ' + @@ -545,9 +369,7 @@ speak: '$name @role_menuitem ' + '@describe_index($indexInParent, $parentChildCount) $description' }, - paragraph: { - speak: '$descendants' - }, + paragraph: {speak: '$descendants'}, popUpButton: { speak: '$value $name $role @aria_has_popup ' + '$state $description' @@ -557,25 +379,12 @@ '$if($checked, @describe_radio_selected($name), ' + '@describe_radio_unselected($name)) $description' }, - radioGroup: { - enter: '$name $role $description' - }, - rootWebArea: { - enter: '$name', - speak: '$if($name, $name, $docUrl)' - }, - region: { - speak: '$nameOrTextContent' - }, - row: { - enter: '$node(tableRowHeader)' - }, - rowHeader: { - speak: '$nameOrTextContent $state' - }, - staticText: { - speak: '$name=' - }, + radioGroup: {enter: '$name $role $description'}, + rootWebArea: {enter: '$name', speak: '$if($name, $name, $docUrl)'}, + region: {speak: '$nameOrTextContent'}, + row: {enter: '$node(tableRowHeader)'}, + rowHeader: {speak: '$nameOrTextContent $state'}, + staticText: {speak: '$name='}, switch: { speak: '$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) ' + '$if($checked, @describe_switch_on($name), ' + @@ -591,27 +400,19 @@ '$if($ariaColumnCount, $ariaColumnCount, $tableColumnCount)) ' + '$node(tableHeader)' }, - tableHeaderContainer: { - speak: '$nameOrTextContent $state $description' - }, + tableHeaderContainer: {speak: '$nameOrTextContent $state $description'}, textField: { speak: '$name $value $if($multiline, @tag_textarea, $if(' + '$inputType, $inputType, $role)) $description $state', braille: '' }, - timer: { - speak: '$nameFromNode $descendants $value $state $description' - }, + timer: {speak: '$nameFromNode $descendants $value $state $description'}, toggleButton: { speak: '$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) ' + '$name $role $pressed $description $state' }, - toolbar: { - enter: '$name $role $description' - }, - tree: { - enter: '$name $role @@list_with_items($countChildren(treeItem))' - }, + toolbar: {enter: '$name $role $description'}, + tree: {enter: '$name $role @@list_with_items($countChildren(treeItem))'}, treeItem: { enter: '$role $expanded $collapsed ' + '@describe_index($indexInParent, $parentChildCount) ' + @@ -626,21 +427,14 @@ speak: '@describe_window($name) $earcon(OBJECT_OPEN)' } }, - menuStart: { - 'default': { - speak: '@chrome_menu_opened($name) $earcon(OBJECT_OPEN)' - } - }, - menuEnd: { - 'default': { - speak: '@chrome_menu_closed $earcon(OBJECT_CLOSE)' - } - }, + menuStart: + {'default': {speak: '@chrome_menu_opened($name) $earcon(OBJECT_OPEN)'}}, + menuEnd: {'default': {speak: '@chrome_menu_closed $earcon(OBJECT_CLOSE)'}}, menuListValueChanged: { 'default': { speak: '$value $name ' + '$find({"state": {"selected": true, "invisible": false}}, ' + - '@describe_index($indexInParent, $parentChildCount)) ' + '@describe_index($indexInParent, $parentChildCount)) ' } }, alert: { @@ -661,12 +455,10 @@ * Custom actions performed while rendering an output string. * @constructor */ -Output.Action = function() { -}; +Output.Action = function() {}; Output.Action.prototype = { - run: function() { - } + run: function() {} }; /** @@ -744,7 +536,7 @@ * Calling this will make the next speech utterance use |mode| even if it would * normally queue or do a category flush. This differs from the |withQueueMode| * instance method as it can apply to future output. - * @param {cvox.QueueMode} mode + * @param {cvox.QueueMode} mode */ Output.forceModeForNextSpeechUtterance = function(mode) { Output.forceModeForNextSpeechUtterance_ = mode; @@ -757,7 +549,7 @@ * 'false'|undefined -> false */ Output.isTruthy = function(node, attrib) { - switch(attrib) { + switch (attrib) { case 'checked': return node.checked && node.checked !== 'false'; default: @@ -790,7 +582,7 @@ return this; }, - /** + /** * Specify ranges for aurally styled speech. * @param {!cursors.Range} range * @param {cursors.Range} prevRange @@ -842,7 +634,7 @@ return this; }, - /** + /** * Specify the same ranges for aurally styled speech and braille. * @param {!cursors.Range} range * @param {cursors.Range} prevRange @@ -905,8 +697,7 @@ * @return {!Output} |this| for chaining */ format: function(formatStr, opt_node) { - return this - .formatForSpeech(formatStr, opt_node) + return this.formatForSpeech(formatStr, opt_node) .formatForBraille(formatStr, opt_node); }, @@ -972,8 +763,9 @@ for (var i = 0; i < this.speechBuffer_.length; i++) { var buff = this.speechBuffer_[i]; - var speechProps = /** @type {Object} */( - buff.getSpanInstanceOf(Output.SpeechProperties)) || {}; + var speechProps = /** @type {Object} */ ( + buff.getSpanInstanceOf(Output.SpeechProperties)) || + {}; speechProps.category = this.speechCategory_; @@ -992,16 +784,14 @@ if (i == this.speechBuffer_.length - 1) speechProps['endCallback'] = this.speechEndCallback_; - cvox.ChromeVox.tts.speak( - buff.toString(), queueMode, speechProps); + cvox.ChromeVox.tts.speak(buff.toString(), queueMode, speechProps); queueMode = cvox.QueueMode.QUEUE; } // Braille. if (this.brailleBuffer_.length) { var buff = this.mergeBraille_(this.brailleBuffer_); - var selSpan = - buff.getSpanInstanceOf(Output.SelectionSpan); + var selSpan = buff.getSpanInstanceOf(Output.SelectionSpan); var startIndex = -1, endIndex = -1; if (selSpan) { var valueStart = buff.getSpanStart(selSpan); @@ -1012,11 +802,8 @@ buff.setSpan(new cvox.ValueSelectionSpan(), startIndex, endIndex); } - var output = new cvox.NavBraille({ - text: buff, - startIndex: startIndex, - endIndex: endIndex - }); + var output = new cvox.NavBraille( + {text: buff, startIndex: startIndex, endIndex: endIndex}); cvox.ChromeVox.braille.write(output); } @@ -1119,12 +906,10 @@ var selectedText = ''; if (node.textSelStart !== undefined) { options.annotation.push(new Output.SelectionSpan( - node.textSelStart || 0, - node.textSelEnd || 0)); + node.textSelStart || 0, node.textSelEnd || 0)); - selectedText = - node.value.substring(node.textSelStart || 0, - node.textSelEnd || 0); + selectedText = node.value.substring( + node.textSelStart || 0, node.textSelEnd || 0); } options.annotation.push(token); if (selectedText && !this.formatOptions_.braille) { @@ -1155,7 +940,7 @@ // Hack to not speak the filename if it's ridiculously long. if (filename.length >= 30) - filename = filename.substring(0, 16) + '...'; + filename = filename.substring(0, 16) + '...'; } this.append_(buff, filename, options); } else if (token == 'nameFromNode') { @@ -1190,9 +975,11 @@ } else if (token == 'parentChildCount') { if (node.parent) { options.annotation.push(token); - var count = node.parent.children.filter(function(child) { - return node.role == child.role; - }).length; + var count = node.parent.children + .filter(function(child) { + return node.role == child.role; + }) + .length; this.append_(buff, String(count)); } } else if (token == 'checked') { @@ -1210,7 +997,7 @@ Object.getOwnPropertyNames(node.state).forEach(function(s) { var stateInfo = Output.STATE_INFO_[s]; if (stateInfo && !stateInfo.isRoleSpecific && stateInfo.on) - this.format_(node, '@' + stateInfo.on.msgId, buff); + this.format_(node, '@' + stateInfo.on.msgId, buff); }.bind(this)); } } else if (token == 'find') { @@ -1218,7 +1005,7 @@ if (tree.firstChild) { var jsonQuery = tree.firstChild.value; node = node.find( - /** @type {chrome.automation.FindParams}*/( + /** @type {chrome.automation.FindParams}*/ ( JSON.parse(jsonQuery))); var formatString = tree.firstChild.nextSibling; if (node) @@ -1278,8 +1065,8 @@ if (this.formatOptions_.braille) msgId = msgId + '_brl'; this.append_(buff, Msgs.getMsg(msgId), options); - } else if (token == 'tableCellRowIndex' || - token == 'tableCellColumnIndex') { + } else if ( + token == 'tableCellRowIndex' || token == 'tableCellColumnIndex') { var value = node[token]; if (value == undefined) return; @@ -1295,13 +1082,13 @@ if (node.name) { this.format_(node, '$name', buff); } else { - var walker = new AutomationTreeWalker(node, - Dir.FORWARD, - {visit: AutomationPredicate.leafOrStaticText, - leaf: AutomationPredicate.leafOrStaticText}); + var walker = new AutomationTreeWalker(node, Dir.FORWARD, { + visit: AutomationPredicate.leafOrStaticText, + leaf: AutomationPredicate.leafOrStaticText + }); var outputStrings = []; while (walker.next().node && - walker.phase == AutomationTreeWalkerPhase.DESCENDANT) { + walker.phase == AutomationTreeWalkerPhase.DESCENDANT) { if (walker.node.name) outputStrings.push(walker.node.name); } @@ -1324,10 +1111,10 @@ if (this.formatOptions_.speech && resolvedInfo.earconId) { options.annotation.push( new Output.EarconAction(resolvedInfo.earconId), - node.location || undefined); + node.location || undefined); } - var msgId = - this.formatOptions_.braille ? resolvedInfo.msgId + '_brl' : + var msgId = this.formatOptions_.braille ? + resolvedInfo.msgId + '_brl' : resolvedInfo.msgId; var msg = Msgs.getMsg(msgId); this.append_(buff, msg, options); @@ -1345,15 +1132,16 @@ if (!this.formatOptions_.speech) return; - options.annotation.push( - new Output.EarconAction(tree.firstChild.value, - node.location || undefined)); + options.annotation.push(new Output.EarconAction( + tree.firstChild.value, node.location || undefined)); this.append_(buff, '', options); } else if (token == 'countChildren') { var role = tree.firstChild.value; - var count = node.children.filter(function(e) { - return e.role == role; - }).length; + var count = node.children + .filter(function(e) { + return e.role == role; + }) + .length; this.append_(buff, String(count)); } } @@ -1395,7 +1183,8 @@ try { if (this.formatOptions_.braille) msg = Msgs.getMsg(msgId + '_brl', msgArgs) || msg; - } catch(e) {} + } catch (e) { + } if (!msg) { console.error('Could not get message ' + msgId); @@ -1481,16 +1270,13 @@ }.bind(this); var unit = range.isInlineText() ? cursors.Unit.TEXT : cursors.Unit.NODE; - while (cursor.node && - range.end.node && - AutomationUtil.getDirection(cursor.node, range.end.node) == - Dir.FORWARD) { + while (cursor.node && range.end.node && + AutomationUtil.getDirection(cursor.node, range.end.node) == + Dir.FORWARD) { var node = cursor.node; rangeBuff.push.apply(rangeBuff, formatNodeAndAncestors(node, prevNode)); prevNode = node; - cursor = cursor.move(unit, - cursors.Movement.DIRECTIONAL, - Dir.FORWARD); + cursor = cursor.move(unit, cursors.Movement.DIRECTIONAL, Dir.FORWARD); // Reached a boundary. if (cursor.node == prevNode) @@ -1525,10 +1311,10 @@ } return rest.concat(contextFirst.reverse()); } - var prevUniqueAncestors = byContextFirst(AutomationUtil.getUniqueAncestors( - node, prevNode)); - var uniqueAncestors = byContextFirst(AutomationUtil.getUniqueAncestors( - prevNode, node)); + var prevUniqueAncestors = + byContextFirst(AutomationUtil.getUniqueAncestors(node, prevNode)); + var uniqueAncestors = + byContextFirst(AutomationUtil.getUniqueAncestors(prevNode, node)); // First, look up the event type's format block. // Navigate is the default event. @@ -1549,12 +1335,10 @@ // Hash the roles we've entered. var enteredRoleSet = {}; for (var j = uniqueAncestors.length - 1, hashNode; - (hashNode = uniqueAncestors[j]); - j--) + (hashNode = uniqueAncestors[j]); j--) enteredRoleSet[hashNode.role] = true; - for (var i = 0, formatPrevNode; - (formatPrevNode = prevUniqueAncestors[i]); + for (var i = 0, formatPrevNode; (formatPrevNode = prevUniqueAncestors[i]); i++) { // This prevents very repetitive announcements. if (enteredRoleSet[formatPrevNode.role] || @@ -1571,8 +1355,7 @@ var originalBuff = buff; var enterRole = {}; for (var j = uniqueAncestors.length - 1, formatNode; - (formatNode = uniqueAncestors[j]); - j--) { + (formatNode = uniqueAncestors[j]); j--) { var roleBlock = getMergedRoleBlock(formatNode.role); if (roleBlock.enter) { if (enterRole[formatNode.role]) @@ -1611,9 +1394,8 @@ var roleBlock = eventBlock[node.role] || {}; var parentRole = (Output.ROLE_INFO_[node.role] || {}).inherits; var parentRoleBlock = eventBlock[parentRole || ''] || {}; - var speakFormat = roleBlock.speak || - parentRoleBlock.speak || - eventBlock['default'].speak; + var speakFormat = + roleBlock.speak || parentRoleBlock.speak || eventBlock['default'].speak; this.format_(node, speakFormat, buff, prevNode); @@ -1649,8 +1431,8 @@ var selStart = node.textSelStart; var selEnd = node.textSelEnd; - if (selStart !== undefined && - selEnd >= rangeStart && selStart <= rangeEnd) { + if (selStart !== undefined && selEnd >= rangeStart && + selStart <= rangeEnd) { // Editable text selection. // |rangeStart| and |rangeEnd| are indices set by the caller and are @@ -1692,8 +1474,7 @@ if (!this.outputContextFirst_) this.ancestry_(node, prevNode, type, buff); - var loc = - range.start.node.boundsForRange(rangeStart, rangeEnd); + var loc = range.start.node.boundsForRange(rangeStart, rangeEnd); if (loc) this.locations_.push(loc); }, @@ -1709,8 +1490,8 @@ opt_options = opt_options || {isUnique: false, annotation: []}; // Reject empty values without meaningful annotations. - if ((!value || value.length == 0) && opt_options.annotation.every( - function(a) { + if ((!value || value.length == 0) && + opt_options.annotation.every(function(a) { return !(a instanceof Output.Action) && !(a instanceof Output.SelectionSpan); @@ -1724,8 +1505,8 @@ // |isUnique| specifies an annotation that cannot be duplicated. if (opt_options.isUnique) { - var annotationSansNodes = opt_options.annotation.filter( - function(annotation) { + var annotationSansNodes = + opt_options.annotation.filter(function(annotation) { return !(annotation instanceof Output.NodeSpan); }); @@ -1816,8 +1597,8 @@ // Keep track of if there's an inline node associated with // |cur|. - var hasInlineNode = cur.getSpansInstanceOf(Output.NodeSpan) - .some(function(s) { + var hasInlineNode = + cur.getSpansInstanceOf(Output.NodeSpan).some(function(s) { if (!s.node) return false; return s.node.display == 'inline' || @@ -1837,7 +1618,8 @@ if (result.length == 0 || (hasInlineNode && prevHasInlineNode && isName && prevIsName)) separator = ''; - else if (result.toString()[result.length - 1] == Output.SPACE || + else if ( + result.toString()[result.length - 1] == Output.SPACE || cur.toString()[0] == Output.SPACE) separator = ''; else @@ -1872,8 +1654,8 @@ while (earconFinder = ancestors.pop()) { var info = Output.ROLE_INFO_[earconFinder.role]; if (info && info.earconId) { - return new Output.EarconAction(info.earconId, - node.location || undefined); + return new Output.EarconAction( + info.earconId, node.location || undefined); break; } earconFinder = earconFinder.parent;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js index f3c99f3..a7ac16c 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js
@@ -22,8 +22,7 @@ * Class to manage the panel. * @constructor */ -Panel = function() { -}; +Panel = function() {}; /** * @enum {string} @@ -84,8 +83,8 @@ /** @type {Panel.Mode} @private */ this.mode_ = Panel.Mode.COLLAPSED; - var blockedSessionQuery = location.search.match( - /[?&]?blockedUserSession=(true|false)/); + var blockedSessionQuery = + location.search.match(/[?&]?blockedUserSession=(true|false)/); /** * Whether the panel is loaded for blocked user session - e.g. on sign-in or * lock screen. @@ -137,7 +136,7 @@ window.addEventListener('message', function(message) { var command = JSON.parse(message.data); - Panel.exec(/** @type {PanelCommand} */(command)); + Panel.exec(/** @type {PanelCommand} */ (command)); }, false); if (this.isUserSessionBlocked_) { @@ -153,8 +152,8 @@ $('close').addEventListener('click', Panel.onClose, false); $('tutorial_next').addEventListener('click', Panel.onTutorialNext, false); - $('tutorial_previous').addEventListener( - 'click', Panel.onTutorialPrevious, false); + $('tutorial_previous') + .addEventListener('click', Panel.onTutorialPrevious, false); $('close_tutorial').addEventListener('click', Panel.onCloseTutorial, false); document.addEventListener('keydown', Panel.onKeyDown, false); @@ -223,9 +222,8 @@ if (this.speechElement_.innerHTML != '') { this.speechElement_.innerHTML += ' '; } - this.speechElement_.innerHTML += '<span class="usertext">' + - escapeForHtml(command.data) + - '</span>'; + this.speechElement_.innerHTML += + '<span class="usertext">' + escapeForHtml(command.data) + '</span>'; break; case PanelCommandType.ADD_ANNOTATION_SPEECH: if (this.speechElement_.innerHTML != '') { @@ -288,8 +286,8 @@ if (this.mode_ == mode) return; - if (this.isUserSessionBlocked_ && - mode != Panel.Mode.COLLAPSED && mode != Panel.Mode.FOCUSED) + if (this.isUserSessionBlocked_ && mode != Panel.Mode.COLLAPSED && + mode != Panel.Mode.FOCUSED) return; this.mode_ = mode; @@ -349,7 +347,8 @@ 'help_commands': chromevoxMenu, 'braille': null, - 'developer': null}; + 'developer': null + }; // Get the key map from the background page. var bkgnd = chrome.extension.getBackgroundPage(); @@ -390,8 +389,7 @@ var menu = category ? categoryToMenu[category] : null; if (binding.title && menu) { menu.addMenuItem( - binding.title, - binding.keySeq, + binding.title, binding.keySeq, BrailleCommandHandler.getDotShortcut(binding.command, true), function() { var CommandHandler = @@ -410,11 +408,14 @@ var title = tabs[j].title; if (tabs[j].active && windows[i].id == lastFocusedWindow.id) title += ' ' + Msgs.getMsg('active_tab'); - tabsMenu.addMenuItem(title, '', '', (function(win, tab) { - bkgnd.chrome.windows.update(win.id, {focused: true}, function() { - bkgnd.chrome.tabs.update(tab.id, {active: true}); - }); - }).bind(this, windows[i], tabs[j])); + tabsMenu.addMenuItem( + title, '', '', (function(win, tab) { + bkgnd.chrome.windows.update( + win.id, {focused: true}, function() { + bkgnd.chrome.tabs.update( + tab.id, {active: true}); + }); + }).bind(this, windows[i], tabs[j])); } } }); @@ -427,11 +428,12 @@ }); var roleListMenuMapping = [ - { menuTitle: 'role_heading', predicate: AutomationPredicate.heading }, - { menuTitle: 'role_landmark', predicate: AutomationPredicate.landmark }, - { menuTitle: 'role_link', predicate: AutomationPredicate.link }, - { menuTitle: 'role_form', predicate: AutomationPredicate.formField }, - { menuTitle: 'role_table', predicate: AutomationPredicate.table }]; + {menuTitle: 'role_heading', predicate: AutomationPredicate.heading}, + {menuTitle: 'role_landmark', predicate: AutomationPredicate.landmark}, + {menuTitle: 'role_link', predicate: AutomationPredicate.link}, + {menuTitle: 'role_form', predicate: AutomationPredicate.formField}, + {menuTitle: 'role_table', predicate: AutomationPredicate.table} + ]; var node = bkgnd.ChromeVoxState.instance.getCurrentRange().start.node; for (var i = 0; i < roleListMenuMapping.length; ++i) { @@ -593,14 +595,16 @@ } var bottomCell2 = row2.insertCell(-1); bottomCell2.id = i + '-brailleCell2'; - bottomCell2.setAttribute('data-companionIDs', - i + '-textCell ' + i + '-brailleCell'); - bottomCell.setAttribute('data-companionIDs', - bottomCell.getAttribute('data-companionIDs') + - ' ' + i + '-brailleCell2'); - topCell.setAttribute('data-companionID2', - bottomCell.getAttribute('data-companionIDs') + - ' ' + i + '-brailleCell2'); + bottomCell2.setAttribute( + 'data-companionIDs', i + '-textCell ' + i + '-brailleCell'); + bottomCell.setAttribute( + 'data-companionIDs', + bottomCell.getAttribute('data-companionIDs') + ' ' + i + + '-brailleCell2'); + topCell.setAttribute( + 'data-companionID2', + bottomCell.getAttribute('data-companionIDs') + ' ' + i + + '-brailleCell2'); bottomCell2.className = 'unhighlighted-cell'; bottomCell = bottomCell2; @@ -846,11 +850,9 @@ var bkgnd = chrome.extension.getBackgroundPage(); bkgnd.chrome.automation.getDesktop(function(desktop) { - onFocus = /** @type {function(chrome.automation.AutomationEvent)} */( + onFocus = /** @type {function(chrome.automation.AutomationEvent)} */ ( onFocus.bind(this, desktop)); - desktop.addEventListener(chrome.automation.EventType.FOCUS, - onFocus, - true); + desktop.addEventListener(chrome.automation.EventType.FOCUS, onFocus, true); // Make sure all menus are cleared to avoid bogous output when we re-open. Panel.clearMenus();
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu.js index b4b3f5c4..53b1cbd 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu.js
@@ -51,12 +51,12 @@ this.items_ = []; /** - * The return value from window.setTimeout for a function to update the - * scroll bars after an item has been added to a menu. Used so that we - * don't re-layout too many times. - * @type {?number} - * @private - */ + * The return value from window.setTimeout for a function to update the + * scroll bars after an item has been added to a menu. Used so that we + * don't re-layout too many times. + * @type {?number} + * @private + */ this.updateScrollbarsTimeout_ = null; /** @@ -85,20 +85,24 @@ this.menuElement.appendChild(menuItem.element); // Sync the active index with focus. - menuItem.element.addEventListener('focus', (function(index, event) { - this.activeIndex_ = index; - }).bind(this, this.items_.length - 1), false); + menuItem.element.addEventListener( + 'focus', (function(index, event) { + this.activeIndex_ = index; + }).bind(this, this.items_.length - 1), + false); // Update the container height, adding a scroll bar if necessary - but // to avoid excessive layout, schedule this once per batch of adding // menu items rather than after each add. if (!this.updateScrollbarsTimeout_) { - this.updateScrollbarsTimeout_ = window.setTimeout((function() { - var menuBounds = this.menuElement.getBoundingClientRect(); - var maxHeight = window.innerHeight - menuBounds.top; - this.menuContainerElement.style.maxHeight = maxHeight + 'px'; - this.updateScrollbarsTimeout_ = null; - }).bind(this), 0); + this.updateScrollbarsTimeout_ = window.setTimeout( + (function() { + var menuBounds = this.menuElement.getBoundingClientRect(); + var maxHeight = window.innerHeight - menuBounds.top; + this.menuContainerElement.style.maxHeight = maxHeight + 'px'; + this.updateScrollbarsTimeout_ = null; + }).bind(this), + 0); } return menuItem; @@ -139,9 +143,11 @@ this.menuBarItemElement.classList.remove('active'); this.activeIndex_ = -1; - window.setTimeout((function() { - this.menuContainerElement.style.visibility = 'hidden'; - }).bind(this), 0); + window.setTimeout( + (function() { + this.menuContainerElement.style.visibility = 'hidden'; + }).bind(this), + 0); }, /** @@ -221,8 +227,7 @@ return; var query = String.fromCharCode(evt.charCode).toLowerCase(); - for (var i = this.activeIndex_ + 1; - i != this.activeIndex_; + for (var i = this.activeIndex_ + 1; i != this.activeIndex_; i = (i + 1) % this.items_.length) { if (this.items_[i].text.toLowerCase().indexOf(query) == 0) { this.activateItem(i); @@ -283,12 +288,11 @@ return; } - this.walker_ = new AutomationTreeWalker( - root, - constants.Dir.FORWARD, - {visit: function(node) { - return !AutomationPredicate.shouldIgnoreNode(node); - }}); + this.walker_ = new AutomationTreeWalker(root, constants.Dir.FORWARD, { + visit: function(node) { + return !AutomationPredicate.shouldIgnoreNode(node); + } + }); this.nodeCount_ = 0; this.selectNext_ = false; this.findMoreNodes_(); @@ -315,12 +319,13 @@ output.withSpeech(range, range, Output.EventType.NAVIGATE); var label = output.toString(); this.addMenuItem(label, '', '', (function() { - var savedNode = node; - return function() { - chrome.extension.getBackgroundPage().ChromeVoxState - .instance['navigateToRange'](cursors.Range.fromNode(savedNode)); - }; - }())); + var savedNode = node; + return function() { + chrome.extension.getBackgroundPage() + .ChromeVoxState.instance['navigateToRange']( + cursors.Range.fromNode(savedNode)); + }; + }())); if (this.selectNext_) { this.activateItem(this.items_.length - 1);
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu_item.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu_item.js index d5b2ff0..316995ca6 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu_item.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_menu_item.js
@@ -24,9 +24,11 @@ this.element.tabIndex = -1; this.element.setAttribute('role', 'menuitem'); - this.element.addEventListener('mouseover', (function(evt) { - this.element.focus(); - }).bind(this), false); + this.element.addEventListener( + 'mouseover', (function(evt) { + this.element.focus(); + }).bind(this), + false); var title = document.createElement('td'); title.className = 'menu-item-title';
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tabs_automation_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tabs_automation_handler.js index 0e23656..5a8512a 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tabs_automation_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tabs_automation_handler.js
@@ -29,8 +29,8 @@ // When the root is focused, simulate what happens on a load complete. if (tabRoot.state[StateType.FOCUSED]) { - var event = new CustomAutomationEvent( - EventType.LOAD_COMPLETE, tabRoot, 'page'); + var event = + new CustomAutomationEvent(EventType.LOAD_COMPLETE, tabRoot, 'page'); this.onLoadComplete(event); } }; @@ -46,8 +46,8 @@ /** @override */ onLoadComplete: function(evt) { var focused = evt.target.find({state: {focused: true}}) || evt.target; - var event = new CustomAutomationEvent( - EventType.FOCUS, focused, evt.eventFrom); + var event = + new CustomAutomationEvent(EventType.FOCUS, focused, evt.eventFrom); this.onFocus(event); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tree_walker.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tree_walker.js index 268ce13e..a2b5d60 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tree_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tree_walker.js
@@ -108,10 +108,10 @@ }; /** @type {AutomationPredicate.Unary} @private */ this.leafPred_ = restrictions.leaf ? restrictions.leaf : - AutomationTreeWalker.falsePredicate_; + AutomationTreeWalker.falsePredicate_; /** @type {AutomationPredicate.Unary} @private */ this.rootPred_ = restrictions.root ? restrictions.root : - AutomationTreeWalker.falsePredicate_; + AutomationTreeWalker.falsePredicate_; /** @const {boolean} @private */ this.skipInitialAncestry_ = restrictions.skipInitialAncestry || false; /** @const {boolean} @private */ @@ -194,8 +194,7 @@ // Exit if we encounter a root-like node and are not searching descendants // of the initial node. - if (searchNode.parent && - this.rootPred_(searchNode.parent) && + if (searchNode.parent && this.rootPred_(searchNode.parent) && this.phase_ != AutomationTreeWalkerPhase.DESCENDANT) break;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tutorial.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tutorial.js index b829712..79f5812 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/tutorial.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/tutorial.js
@@ -23,7 +23,8 @@ this.page_; this.page = sessionStorage['tutorial_page_pos'] !== undefined ? - sessionStorage['tutorial_page_pos'] : 0; + sessionStorage['tutorial_page_pos'] : + 0; }; /** @@ -39,11 +40,11 @@ var prevEarcon; var playEarcon = function(earcon) { if (prevEarcon) { - chrome.extension.getBackgroundPage()['cvox']['ChromeVox'][ - 'earcons']['cancelEarcon'](prevEarcon); + chrome.extension.getBackgroundPage()['cvox']['ChromeVox']['earcons'] + ['cancelEarcon'](prevEarcon); } - chrome.extension.getBackgroundPage()['cvox']['ChromeVox'][ - 'earcons']['playEarcon'](earcon); + chrome.extension.getBackgroundPage()['cvox']['ChromeVox']['earcons'] + ['playEarcon'](earcon); prevEarcon = earcon; }.bind(this, earconId); earconElement.addEventListener('focus', playEarcon, false); @@ -61,59 +62,64 @@ */ Tutorial.PAGES = [ [ - { msgid: 'tutorial_welcome_heading', heading: true }, - { msgid: 'tutorial_welcome_text' }, - { msgid: 'tutorial_enter_to_advance', repeat: true }, + {msgid: 'tutorial_welcome_heading', heading: true}, + {msgid: 'tutorial_welcome_text'}, + {msgid: 'tutorial_enter_to_advance', repeat: true}, ], [ - { msgid: 'tutorial_on_off_heading', heading: true }, - { msgid: 'tutorial_control' }, - { msgid: 'tutorial_on_off' }, - { msgid: 'tutorial_enter_to_advance', repeat: true }, + {msgid: 'tutorial_on_off_heading', heading: true}, + {msgid: 'tutorial_control'}, + {msgid: 'tutorial_on_off'}, + {msgid: 'tutorial_enter_to_advance', repeat: true}, ], [ - { msgid: 'tutorial_modifier_heading', heading: true }, - { msgid: 'tutorial_modifier' }, - { msgid: 'tutorial_chromebook_search', chromebookOnly: true }, - { msgid: 'tutorial_any_key' }, - { msgid: 'tutorial_enter_to_advance', repeat: true }, + {msgid: 'tutorial_modifier_heading', heading: true}, + {msgid: 'tutorial_modifier'}, + {msgid: 'tutorial_chromebook_search', chromebookOnly: true}, + {msgid: 'tutorial_any_key'}, + {msgid: 'tutorial_enter_to_advance', repeat: true}, ], [ - { msgid: 'tutorial_basic_navigation_heading', heading: true }, - { msgid: 'tutorial_basic_navigation' }, - { msgid: 'tutorial_click_next' }, + {msgid: 'tutorial_basic_navigation_heading', heading: true}, + {msgid: 'tutorial_basic_navigation'}, + {msgid: 'tutorial_click_next'}, ], [ - { msgid: 'tutorial_jump_heading', heading: true }, - { msgid: 'tutorial_jump' }, - { msgid: 'tutorial_jump_second_heading', heading: true }, - { msgid: 'tutorial_jump_wrap_heading', heading: true }, - { msgid: 'tutorial_click_next' }, + {msgid: 'tutorial_jump_heading', heading: true}, + {msgid: 'tutorial_jump'}, + {msgid: 'tutorial_jump_second_heading', heading: true}, + {msgid: 'tutorial_jump_wrap_heading', heading: true}, + {msgid: 'tutorial_click_next'}, ], [ - { msgid: 'tutorial_menus_heading', heading: true }, - { msgid: 'tutorial_menus' }, - { msgid: 'tutorial_click_next' }, + {msgid: 'tutorial_menus_heading', heading: true}, + {msgid: 'tutorial_menus'}, + {msgid: 'tutorial_click_next'}, ], [ - { msgid: 'tutorial_chrome_shortcuts_heading', heading: true }, - { msgid: 'tutorial_chrome_shortcuts' }, - { msgid: 'tutorial_chromebook_ctrl_forward', chromebookOnly: true } + {msgid: 'tutorial_chrome_shortcuts_heading', heading: true}, + {msgid: 'tutorial_chrome_shortcuts'}, + {msgid: 'tutorial_chromebook_ctrl_forward', chromebookOnly: true} ], [ - { msgid: 'tutorial_earcon_page_title', heading: true }, - { msgid: 'tutorial_earcon_page_body' }, - { custom: Tutorial.buildEarconPage_ } + {msgid: 'tutorial_earcon_page_title', heading: true}, + {msgid: 'tutorial_earcon_page_body'}, {custom: Tutorial.buildEarconPage_} ], [ - { msgid: 'tutorial_learn_more_heading', heading: true }, - { msgid: 'tutorial_learn_more' }, - { msgid: 'next_command_reference', - link: 'http://www.chromevox.com/next_keyboard_shortcuts.html' }, - { msgid: 'chrome_keyboard_shortcuts', - link: 'https://support.google.com/chromebook/answer/183101?hl=en' }, - { msgid: 'touchscreen_accessibility', - link: 'https://support.google.com/chromebook/answer/6103702?hl=en' }, + {msgid: 'tutorial_learn_more_heading', heading: true}, + {msgid: 'tutorial_learn_more'}, + { + msgid: 'next_command_reference', + link: 'http://www.chromevox.com/next_keyboard_shortcuts.html' + }, + { + msgid: 'chrome_keyboard_shortcuts', + link: 'https://support.google.com/chromebook/answer/183101?hl=en' + }, + { + msgid: 'touchscreen_accessibility', + link: 'https://support.google.com/chromebook/answer/6103702?hl=en' + }, ], ]; @@ -126,7 +132,7 @@ onKeyDown: function(evt) { if (document.activeElement && (document.activeElement.id == 'tutorial_previous' || - document.activeElement.id == 'tutorial_next')) + document.activeElement.id == 'tutorial_next')) return true; if (evt.key == 'Enter') @@ -141,7 +147,8 @@ /** Open the last viewed page in the tutorial. */ lastViewedPage: function() { this.page = sessionStorage['tutorial_page_pos'] !== undefined ? - sessionStorage['tutorial_page_pos'] : 0; + sessionStorage['tutorial_page_pos'] : + 0; if (this.page == -1) this.page = 0; this.showCurrentPage_(); @@ -152,8 +159,8 @@ delete sessionStorage['tutorial_page_pos']; this.page = -1; this.showPage_([ - { msgid: 'update_56_title', heading: true }, - { msgid: 'update_56_intro' }, + {msgid: 'update_56_title', heading: true}, + {msgid: 'update_56_intro'}, { list: true, items: [ @@ -162,7 +169,7 @@ {msgid: 'update_56_item_3', listItem: true}, ], }, - { msgid: 'update_56_OUTTRO' }, + {msgid: 'update_56_OUTTRO'}, ]); },
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/injected/keyboard_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/injected/keyboard_handler.js index baf8ea07f..6caf89a 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/injected/keyboard_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/injected/keyboard_handler.js
@@ -28,10 +28,7 @@ }); // Make the initial request for prefs. - cvox.ExtensionBridge.send({ - 'target': 'Prefs', - 'action': 'getPrefs' - }); + cvox.ExtensionBridge.send({'target': 'Prefs', 'action': 'getPrefs'}); }; KeyboardHandler.prototype = { @@ -40,10 +37,8 @@ * @private */ handleKeyDown_: function(evt) { - cvox.ExtensionBridge.send({ - 'target': 'next', - 'action': 'flushNextUtterance' - }); + cvox.ExtensionBridge.send( + {'target': 'next', 'action': 'flushNextUtterance'}); evt.stickyMode = cvox.ChromeVox.isStickyPrefOn; @@ -55,10 +50,7 @@ * @private */ handleCommand_: function(command) { - cvox.ExtensionBridge.send({ - 'target': 'next', - 'action': 'onCommand', - 'command': command - }); + cvox.ExtensionBridge.send( + {'target': 'next', 'action': 'onCommand', 'command': command}); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/abstract_result.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/abstract_result.js index 7538cf8..017425e 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/abstract_result.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/abstract_result.js
@@ -14,7 +14,7 @@ /** * @constructor */ -cvox.AbstractResult = function() { }; +cvox.AbstractResult = function() {}; /** * Checks the result if it is an unknown result.
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/constants.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/constants.js index 5fcdcc72..ee740f0 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/constants.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/constants.js
@@ -12,8 +12,7 @@ /** * @constructor */ -cvox.SearchConstants = function() { -}; +cvox.SearchConstants = function() {}; /** * Keycodes.
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/context_menu.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/context_menu.js index 7f937b8..a422744 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/context_menu.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/context_menu.js
@@ -17,15 +17,10 @@ /** * @constructor */ -cvox.SearchContextMenu = function() { -}; +cvox.SearchContextMenu = function() {}; /* Globals */ -var Command = { - TOOLS: 'tools', - ADS: 'ads', - MAIN: 'main' -}; +var Command = {TOOLS: 'tools', ADS: 'ads', MAIN: 'main'}; /** * Current focus Search is in. @@ -39,17 +34,17 @@ cvox.SearchContextMenu.contextMenuHandler = function(evt) { var cmd = evt.detail['customCommand']; switch (cmd) { - case Command.TOOLS: - cvox.SearchContextMenu.focusTools(); - break; + case Command.TOOLS: + cvox.SearchContextMenu.focusTools(); + break; - case Command.ADS: - cvox.SearchContextMenu.focusAds(); - break; + case Command.ADS: + cvox.SearchContextMenu.focusAds(); + break; - case Command.MAIN: - cvox.SearchContextMenu.focusMain(); - break; + case Command.MAIN: + cvox.SearchContextMenu.focusMain(); + break; } }; @@ -124,17 +119,17 @@ */ cvox.SearchContextMenu.init = function() { var ACTIONS = [ - { desc: 'Main Results', cmd: Command.MAIN }, - { desc: 'Search Tools', cmd: Command.TOOLS }, - { desc: 'Ads', cmd: Command.ADS } + {desc: 'Main Results', cmd: Command.MAIN}, + {desc: 'Search Tools', cmd: Command.TOOLS}, + {desc: 'Ads', cmd: Command.ADS} ]; /* Attach ContextMenuActions. */ var body = document.querySelector('body'); body.setAttribute('contextMenuActions', JSON.stringify(ACTIONS)); /* Listen for ContextMenu events. */ - body.addEventListener('ATCustomEvent', - cvox.SearchContextMenu.contextMenuHandler, true); + body.addEventListener( + 'ATCustomEvent', cvox.SearchContextMenu.contextMenuHandler, true); window.addEventListener('keydown', cvox.SearchContextMenu.keyhandler, true); cvox.Search.init();
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/loader.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/loader.js index 62c497b..da819da 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/loader.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/loader.js
@@ -13,8 +13,7 @@ /** * @constructor */ -cvox.SearchLoader = function() { -}; +cvox.SearchLoader = function() {}; /** * Called when document ready state changes.
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/results.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/results.js index 8b6b064c..7747a66e 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/results.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/results.js
@@ -17,8 +17,7 @@ /** * @constructor */ -cvox.SearchResults = function() { -}; +cvox.SearchResults = function() {}; /** * Speaks a result based on given selectors. @@ -31,8 +30,8 @@ if (selectText.select) { var elems = result.querySelectorAll(selectText.select); for (var i = 0; i < elems.length; i++) { - cvox.ChromeVox.tts.speak(cvox.DomUtil.getName(elems.item(i)), - cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak( + cvox.DomUtil.getName(elems.item(i)), cvox.QueueMode.QUEUE); } } if (selectText.text) { @@ -46,8 +45,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.UnknownResult = function() { -}; +cvox.UnknownResult = function() {}; goog.inherits(cvox.UnknownResult, cvox.AbstractResult); /* Normal Result Type. */ @@ -55,8 +53,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.NormalResult = function() { -}; +cvox.NormalResult = function() {}; goog.inherits(cvox.NormalResult, cvox.AbstractResult); /** @@ -84,12 +81,10 @@ var MORE_RESULTS_LINK_SELECT = '.mrf'; var NORMAL_SELECTORS = [ - { select: NORMAL_TITLE_SELECT }, - { select: NORMAL_DESC_SELECT }, - { select: NORMAL_URL_SELECT }, - { select: SITE_LINK_SELECT }, - { select: MORE_RESULTS_SELECT }, - { select: MORE_RESULTS_LINK_SELECT }]; + {select: NORMAL_TITLE_SELECT}, {select: NORMAL_DESC_SELECT}, + {select: NORMAL_URL_SELECT}, {select: SITE_LINK_SELECT}, + {select: MORE_RESULTS_SELECT}, {select: MORE_RESULTS_LINK_SELECT} + ]; cvox.SearchResults.speakResultBySelectTexts(result, NORMAL_SELECTORS); var DISCUSS_TITLE_SELECT = '.mas-1st-col div'; @@ -110,8 +105,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.WeatherResult = function() { -}; +cvox.WeatherResult = function() {}; goog.inherits(cvox.WeatherResult, cvox.AbstractResult); /** @@ -137,10 +131,8 @@ var FORE_LOW_SELECT = '.vk_lgy'; var FORE_SELECTORS = [ - { select: FORE_DAY_SELECT }, - { select: FORE_COND_SELECT }, - { select: FORE_HIGH_SELECT }, - { select: FORE_LOW_SELECT } + {select: FORE_DAY_SELECT}, {select: FORE_COND_SELECT}, + {select: FORE_HIGH_SELECT}, {select: FORE_LOW_SELECT} ]; cvox.SearchResults.speakResultBySelectTexts(forecast, FORE_SELECTORS); }; @@ -169,18 +161,12 @@ var WEATHER_WIND_SELECT = '#wob_ws'; var WEATHER_SELECT_TEXTS = [ - { text: WEATHER_INTRO }, - { select: WEATHER_LOC_SELECT }, - { select: WEATHER_WHEN_SELECT }, - { select: WEATHER_COND_SELECT }, - { select: WEATHER_TEMP_SELECT }, - { text: WEATHER_TEMP_UNITS }, - { text: WEATHER_PREC_INTRO }, - { select: WEATHER_PREC_SELECT }, - { text: WEATHER_HUMID_INTRO }, - { select: WEATHER_HUMID_SELECT }, - { text: WEATHER_WIND_INTRO }, - { select: WEATHER_WIND_SELECT } + {text: WEATHER_INTRO}, {select: WEATHER_LOC_SELECT}, + {select: WEATHER_WHEN_SELECT}, {select: WEATHER_COND_SELECT}, + {select: WEATHER_TEMP_SELECT}, {text: WEATHER_TEMP_UNITS}, + {text: WEATHER_PREC_INTRO}, {select: WEATHER_PREC_SELECT}, + {text: WEATHER_HUMID_INTRO}, {select: WEATHER_HUMID_SELECT}, + {text: WEATHER_WIND_INTRO}, {select: WEATHER_WIND_SELECT} ]; cvox.SearchResults.speakResultBySelectTexts(result, WEATHER_SELECT_TEXTS); @@ -199,8 +185,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.KnowResult = function() { -}; +cvox.KnowResult = function() {}; goog.inherits(cvox.KnowResult, cvox.AbstractResult); /** @@ -218,8 +203,7 @@ */ cvox.KnowResult.prototype.speak = function(result) { - cvox.ChromeVox.tts.speak( - cvox.DomUtil.getName(result), cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak(cvox.DomUtil.getName(result), cvox.QueueMode.QUEUE); return true; }; @@ -245,8 +229,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.CalcResult = function() { -}; +cvox.CalcResult = function() {}; goog.inherits(cvox.CalcResult, cvox.AbstractResult); /** @@ -268,10 +251,8 @@ } var CALC_QUERY_SELECT = '#cwles'; var CALC_RESULT_SELECT = '#cwos'; - var CALC_SELECTORS = [ - { select: CALC_QUERY_SELECT }, - { select: CALC_RESULT_SELECT } - ]; + var CALC_SELECTORS = + [{select: CALC_QUERY_SELECT}, {select: CALC_RESULT_SELECT}]; cvox.SearchResults.speakResultBySelectTexts(result, CALC_SELECTORS); return true; }; @@ -281,8 +262,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.GameResult = function() { -}; +cvox.GameResult = function() {}; goog.inherits(cvox.GameResult, cvox.AbstractResult); /** @@ -299,8 +279,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.ImageResult = function() { -}; +cvox.ImageResult = function() {}; goog.inherits(cvox.ImageResult, cvox.AbstractResult); /** @@ -330,7 +309,7 @@ var filename = metaData['fn']; if (filename) { - imageSelectTexts.push({ text: filename }); + imageSelectTexts.push({text: filename}); } var rawDimensions = metaData['is']; @@ -339,12 +318,12 @@ var tmpDiv = document.createElement('div'); tmpDiv.innerHTML = rawDimensions; var dimensions = tmpDiv.textContent || tmpDiv.innerText; - imageSelectTexts.push({ text: dimensions }); + imageSelectTexts.push({text: dimensions}); } var url = metaData['isu']; if (url) { - imageSelectTexts.push({ text: url}); + imageSelectTexts.push({text: url}); } cvox.SearchResults.speakResultBySelectTexts(result, imageSelectTexts); return true; @@ -355,8 +334,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.CategoryResult = function() { -}; +cvox.CategoryResult = function() {}; goog.inherits(cvox.CategoryResult, cvox.AbstractResult); /** @@ -381,8 +359,7 @@ var LABEL_SELECT = '.rg_bb_label'; var label = result.querySelector(LABEL_SELECT); - cvox.ChromeVox.tts.speak( - cvox.DomUtil.getName(label), cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak(cvox.DomUtil.getName(label), cvox.QueueMode.QUEUE); return true; }; @@ -391,8 +368,7 @@ * @constructor * @extends {cvox.AbstractResult} */ -cvox.AdResult = function() { -}; +cvox.AdResult = function() {}; goog.inherits(cvox.AdResult, cvox.AbstractResult); /** @@ -415,10 +391,8 @@ var HEADER_SELECT = 'h3'; var DESC_SELECT = '.ads-creative'; var URL_SELECT = '.ads-visurl'; - var AD_SELECTS = [ - { select: HEADER_SELECT }, - { select: DESC_SELECT }, - { select: URL_SELECT }]; + var AD_SELECTS = + [{select: HEADER_SELECT}, {select: DESC_SELECT}, {select: URL_SELECT}]; cvox.SearchResults.speakResultBySelectTexts(result, AD_SELECTS); return true; }; @@ -430,13 +404,7 @@ * getURL: Function that takes in a result and extracts the URL to follow. */ cvox.SearchResults.RESULT_TYPES = [ - cvox.UnknownResult, - cvox.NormalResult, - cvox.KnowResult, - cvox.WeatherResult, - cvox.AdResult, - cvox.CalcResult, - cvox.GameResult, - cvox.ImageResult, + cvox.UnknownResult, cvox.NormalResult, cvox.KnowResult, cvox.WeatherResult, + cvox.AdResult, cvox.CalcResult, cvox.GameResult, cvox.ImageResult, cvox.CategoryResult ];
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search.js index 479f33b..bca762c 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search.js
@@ -18,8 +18,7 @@ /** * @constructor */ -cvox.Search = function() { -}; +cvox.Search = function() {}; /** * Selectors to match results. @@ -100,7 +99,7 @@ */ cvox.Search.syncToIndex = function() { cvox.ChromeVox.tts.stop(); - var prop = { endCallback: cvox.Search.speakSync_ }; + var prop = {endCallback: cvox.Search.speakSync_}; if (cvox.Search.index === 0) { cvox.ChromeVox.tts.speak('First result', cvox.QueueMode.QUEUE, prop); } else if (cvox.Search.index === cvox.Search.results.length - 1) { @@ -169,12 +168,12 @@ var navToUrl = function() { window.location = url; }; - var prop = { endCallback: navToUrl }; + var prop = {endCallback: navToUrl}; if (url) { var pageNumber = cvox.Search.getPageNumber(url); if (!isNaN(pageNumber)) { - cvox.ChromeVox.tts.speak('Page ' + pageNumber, cvox.QueueMode.FLUSH, - prop); + cvox.ChromeVox.tts.speak( + 'Page ' + pageNumber, cvox.QueueMode.FLUSH, prop); } else { cvox.ChromeVox.tts.speak('Unknown page.', cvox.QueueMode.FLUSH, prop); } @@ -187,8 +186,8 @@ cvox.Search.goToPane = function() { var pane = cvox.Search.panes[cvox.Search.paneIndex]; if (pane.className === cvox.Search.SELECTED_PANE_CLASS) { - cvox.ChromeVox.tts.speak('You are already on that page.', - cvox.QueueMode.QUEUE); + cvox.ChromeVox.tts.speak( + 'You are already on that page.', cvox.QueueMode.QUEUE); return; } var anchor = pane.querySelector('a'); @@ -233,55 +232,55 @@ if (document.activeElement !== searchInput && !cvox.SearchUtil.isSearchWidgetActive()) { switch (evt.keyCode) { - case cvox.SearchConstants.KeyCode.UP: - /* Add results.length because JS Modulo is silly. */ - cvox.Search.index = cvox.SearchUtil.subOneWrap(cvox.Search.index, - cvox.Search.results.length); - if (cvox.Search.index === cvox.Search.results.length - 1) { - cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP); - } - cvox.Search.syncToIndex(); - break; + case cvox.SearchConstants.KeyCode.UP: + /* Add results.length because JS Modulo is silly. */ + cvox.Search.index = cvox.SearchUtil.subOneWrap( + cvox.Search.index, cvox.Search.results.length); + if (cvox.Search.index === cvox.Search.results.length - 1) { + cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP); + } + cvox.Search.syncToIndex(); + break; - case cvox.SearchConstants.KeyCode.DOWN: - cvox.Search.index = cvox.SearchUtil.addOneWrap(cvox.Search.index, - cvox.Search.results.length); - if (cvox.Search.index === 0) { - cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP); - } - cvox.Search.syncToIndex(); - break; + case cvox.SearchConstants.KeyCode.DOWN: + cvox.Search.index = cvox.SearchUtil.addOneWrap( + cvox.Search.index, cvox.Search.results.length); + if (cvox.Search.index === 0) { + cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP); + } + cvox.Search.syncToIndex(); + break; - case cvox.SearchConstants.KeyCode.PAGE_UP: - cvox.Search.navigatePage(false); - break; + case cvox.SearchConstants.KeyCode.PAGE_UP: + cvox.Search.navigatePage(false); + break; - case cvox.SearchConstants.KeyCode.PAGE_DOWN: - cvox.Search.navigatePage(true); - break; + case cvox.SearchConstants.KeyCode.PAGE_DOWN: + cvox.Search.navigatePage(true); + break; - case cvox.SearchConstants.KeyCode.LEFT: - cvox.Search.paneIndex = cvox.SearchUtil.subOneWrap(cvox.Search.paneIndex, - cvox.Search.panes.length); - cvox.Search.syncPaneToIndex(); - break; + case cvox.SearchConstants.KeyCode.LEFT: + cvox.Search.paneIndex = cvox.SearchUtil.subOneWrap( + cvox.Search.paneIndex, cvox.Search.panes.length); + cvox.Search.syncPaneToIndex(); + break; - case cvox.SearchConstants.KeyCode.RIGHT: - cvox.Search.paneIndex = cvox.SearchUtil.addOneWrap(cvox.Search.paneIndex, - cvox.Search.panes.length); - cvox.Search.syncPaneToIndex(); - break; + case cvox.SearchConstants.KeyCode.RIGHT: + cvox.Search.paneIndex = cvox.SearchUtil.addOneWrap( + cvox.Search.paneIndex, cvox.Search.panes.length); + cvox.Search.syncPaneToIndex(); + break; - case cvox.SearchConstants.KeyCode.ENTER: - if (cvox.Search.isPane) { - cvox.Search.goToPane(); - } else { - cvox.Search.goToResult(); - } - break; + case cvox.SearchConstants.KeyCode.ENTER: + if (cvox.Search.isPane) { + cvox.Search.goToPane(); + } else { + cvox.Search.goToResult(); + } + break; - default: - return false; + default: + return false; } evt.preventDefault(); evt.stopPropagation(); @@ -349,7 +348,7 @@ var config = /** @type MutationObserverInit */ - ({ attributes: true, childList: true, characterData: true }); + ({attributes: true, childList: true, characterData: true}); observer.observe(target, config); }; @@ -420,16 +419,16 @@ var selectedHTML = selected.innerHTML; switch (selectedHTML) { - case 'Web': - case 'News': - cvox.Search.selectors = cvox.Search.webSelectors; - break; - case 'Images': - cvox.Search.selectors = cvox.Search.imageSelectors; - cvox.Search.observeMutation(); - break; - default: - return; + case 'Web': + case 'News': + cvox.Search.selectors = cvox.Search.webSelectors; + break; + case 'Images': + cvox.Search.selectors = cvox.Search.imageSelectors; + cvox.Search.observeMutation(); + break; + default: + return; } cvox.Search.populateResults();
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search_tools.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search_tools.js index 28b94a67..1d94c1e 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search_tools.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/search_tools.js
@@ -18,8 +18,7 @@ /** * @constructor */ -cvox.SearchTool = function() { -}; +cvox.SearchTool = function() {}; /** * Index of the current menu in focus. @@ -143,18 +142,18 @@ /* Custom Date Range. */ var CDR_ID = 'cdr_opt'; switch (menuItem.id) { - case cvox.SearchTool.CLEAR_ID: - window.location = menuItem.dataset.url; - break; - case CDR_ID: - var CDR_LINK_SELECTOR = '#cdrlnk'; - var cdrLink = menuItem.querySelector(CDR_LINK_SELECTOR); - cvox.DomUtil.clickElem(cdrLink, false, false, false); - cvox.SearchTool.toggleMenu(); - break; - default: - window.location = cvox.SearchUtil.extractURL(menuItem); - break; + case cvox.SearchTool.CLEAR_ID: + window.location = menuItem.dataset.url; + break; + case CDR_ID: + var CDR_LINK_SELECTOR = '#cdrlnk'; + var cdrLink = menuItem.querySelector(CDR_LINK_SELECTOR); + cvox.DomUtil.clickElem(cdrLink, false, false, false); + cvox.SearchTool.toggleMenu(); + break; + default: + window.location = cvox.SearchUtil.extractURL(menuItem); + break; } }; @@ -169,38 +168,38 @@ } switch (evt.keyCode) { - case cvox.SearchConstants.KeyCode.UP: - cvox.SearchTool.menuItemIndex = cvox.SearchUtil.subOneWrap( - cvox.SearchTool.menuItemIndex, cvox.SearchTool.menuItems.length); - cvox.SearchTool.syncToMenuItem(); - break; + case cvox.SearchConstants.KeyCode.UP: + cvox.SearchTool.menuItemIndex = cvox.SearchUtil.subOneWrap( + cvox.SearchTool.menuItemIndex, cvox.SearchTool.menuItems.length); + cvox.SearchTool.syncToMenuItem(); + break; - case cvox.SearchConstants.KeyCode.DOWN: - cvox.SearchTool.menuItemIndex = cvox.SearchUtil.addOneWrap( - cvox.SearchTool.menuItemIndex, cvox.SearchTool.menuItems.length); - cvox.SearchTool.syncToMenuItem(); - break; + case cvox.SearchConstants.KeyCode.DOWN: + cvox.SearchTool.menuItemIndex = cvox.SearchUtil.addOneWrap( + cvox.SearchTool.menuItemIndex, cvox.SearchTool.menuItems.length); + cvox.SearchTool.syncToMenuItem(); + break; - case cvox.SearchConstants.KeyCode.LEFT: - cvox.SearchTool.toggleMenu(); - cvox.SearchTool.menuIndex = cvox.SearchUtil.subOneWrap( - cvox.SearchTool.menuIndex, cvox.SearchTool.menus.length); - cvox.SearchTool.syncToMenu(); - break; + case cvox.SearchConstants.KeyCode.LEFT: + cvox.SearchTool.toggleMenu(); + cvox.SearchTool.menuIndex = cvox.SearchUtil.subOneWrap( + cvox.SearchTool.menuIndex, cvox.SearchTool.menus.length); + cvox.SearchTool.syncToMenu(); + break; - case cvox.SearchConstants.KeyCode.RIGHT: - cvox.SearchTool.toggleMenu(); - cvox.SearchTool.menuIndex = cvox.SearchUtil.addOneWrap( - cvox.SearchTool.menuIndex, cvox.SearchTool.menus.length); - cvox.SearchTool.syncToMenu(); - break; + case cvox.SearchConstants.KeyCode.RIGHT: + cvox.SearchTool.toggleMenu(); + cvox.SearchTool.menuIndex = cvox.SearchUtil.addOneWrap( + cvox.SearchTool.menuIndex, cvox.SearchTool.menus.length); + cvox.SearchTool.syncToMenu(); + break; - case cvox.SearchConstants.KeyCode.ENTER: - cvox.SearchTool.gotoMenuItem(); - break; + case cvox.SearchConstants.KeyCode.ENTER: + cvox.SearchTool.gotoMenuItem(); + break; - default: - return false; + default: + return false; } evt.preventDefault(); evt.stopPropagation();
diff --git a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js index b40e4dd..9d409c9 100644 --- a/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js +++ b/chrome/browser/resources/chromeos/chromevox/extensions/searchvox/util.js
@@ -10,8 +10,7 @@ goog.provide('cvox.SearchUtil'); /** Utility functions. */ -cvox.SearchUtil = function() { -}; +cvox.SearchUtil = function() {}; /** * Extracts the first URL from an element. @@ -156,29 +155,35 @@ // Send a mousedown (or simply a double click if requested). var evt = document.createEvent('MouseEvents'); var evtType = opt_double ? 'dblclick' : 'mousedown'; - evt.initMouseEvent(evtType, true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + evtType, true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); // Mark any events we generate so we don't try to process our own events. evt.fromCvox = true; try { targetNode.dispatchEvent(evt); - } catch (e) {} - //Send a mouse up + } catch (e) { + } + // Send a mouse up evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('mouseup', true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + 'mouseup', true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); // Mark any events we generate so we don't try to process our own events. evt.fromCvox = true; try { targetNode.dispatchEvent(evt); - } catch (e) {} - //Send a click + } catch (e) { + } + // Send a click evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('click', true, true, document.defaultView, - 1, 0, 0, 0, 0, false, false, shiftKey, false, 0, null); + evt.initMouseEvent( + 'click', true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, + shiftKey, false, 0, null); // Mark any events we generate so we don't try to process our own events. evt.fromCvox = true; try { targetNode.dispatchEvent(evt); - } catch (e) {} + } catch (e) { + } };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille.js index 9b145cb..168cb2e 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille.js
@@ -63,10 +63,12 @@ this.updateLastContentId_(); var outParams = params.toJson(); - var message = {'target': 'BRAILLE', - 'action': 'write', - 'params': outParams, - 'contentId' : this.lastContentId_}; + var message = { + 'target': 'BRAILLE', + 'action': 'write', + 'params': outParams, + 'contentId': this.lastContentId_ + }; cvox.ExtensionBridge.send(message); }; @@ -98,8 +100,8 @@ /** @private */ cvox.ChromeBraille.prototype.updateLastContentId_ = function() { - this.lastContentId_ = cvox.ExtensionBridge.uniqueId() + '.' + - this.nextLocalId_++; + this.lastContentId_ = + cvox.ExtensionBridge.uniqueId() + '.' + this.nextLocalId_++; }; @@ -110,8 +112,7 @@ * if available. * @private */ -cvox.ChromeBraille.prototype.onKeyEvent_ = function(brailleEvt, - content) { +cvox.ChromeBraille.prototype.onKeyEvent_ = function(brailleEvt, content) { var command = cvox.ChromeVoxUserCommands.commands[brailleEvt.command]; if (command) { command({event: brailleEvt, content: content});
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_background.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_background.js index a6d3e8c3..b77c546 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_background.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_background.js
@@ -26,14 +26,14 @@ * Braille translator manager (for mocking in tests) * @implements {cvox.BrailleInterface} */ -cvox.BrailleBackground = function(opt_displayManagerForTest, - opt_inputHandlerForTest, - opt_translatorManagerForTest) { +cvox.BrailleBackground = function( + opt_displayManagerForTest, opt_inputHandlerForTest, + opt_translatorManagerForTest) { /** * @type {!cvox.BrailleTranslatorManager} * @private*/ - this.translatorManager_ = opt_translatorManagerForTest || - new cvox.BrailleTranslatorManager(); + this.translatorManager_ = + opt_translatorManagerForTest || new cvox.BrailleTranslatorManager(); /** * @type {cvox.BrailleDisplayManager} * @private @@ -119,8 +119,7 @@ */ cvox.BrailleBackground.prototype.onBrailleMessage = function(msg) { if (msg['action'] == 'write') { - this.setContent_(cvox.NavBraille.fromJson(msg['params']), - msg['contentId']); + this.setContent_(cvox.NavBraille.fromJson(msg['params']), msg['contentId']); } }; @@ -173,12 +172,8 @@ * @param {cvox.NavBraille} content Content of display when event fired. * @private */ -cvox.BrailleBackground.prototype.sendCommand_ = - function(brailleEvt, content) { - var msg = { - 'message': 'BRAILLE', - 'args': brailleEvt - }; +cvox.BrailleBackground.prototype.sendCommand_ = function(brailleEvt, content) { + var msg = {'message': 'BRAILLE', 'args': brailleEvt}; if (content === this.lastContent_) { msg.contentId = this.lastContentId_; }
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/classic_earcons.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/classic_earcons.js index f089979..707e1ff 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/classic_earcons.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/classic_earcons.js
@@ -58,8 +58,8 @@ this.currentAudio = this.audioMap[earcon]; if (!this.currentAudio) { - this.currentAudio = new Audio(chrome.extension.getURL(this.getBaseUrl() + - earcon + '.ogg')); + this.currentAudio = + new Audio(chrome.extension.getURL(this.getBaseUrl() + earcon + '.ogg')); this.audioMap[earcon] = this.currentAudio; } try {
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/earcons.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/earcons.js index 41a0e57..122e859a 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/earcons.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/earcons.js
@@ -35,10 +35,8 @@ return; } - cvox.ExtensionBridge.send({ - 'target': 'EARCON', - 'action': 'play', - 'earcon': earcon}); + cvox.ExtensionBridge.send( + {'target': 'EARCON', 'action': 'play', 'earcon': earcon}); };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/extension_bridge.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/extension_bridge.js index 0b0a7e79..88f2702 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/extension_bridge.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/extension_bridge.js
@@ -94,12 +94,12 @@ cvox.ExtensionBridge.send = function(message) { var self = cvox.ExtensionBridge; switch (self.context) { - case self.BACKGROUND: - self.sendBackgroundToContentScript(message); - break; - case self.CONTENT_SCRIPT: - self.sendContentScriptToBackground(message); - break; + case self.BACKGROUND: + self.sendBackgroundToContentScript(message); + break; + case self.CONTENT_SCRIPT: + self.sendContentScriptToBackground(message); + break; } }; @@ -240,8 +240,7 @@ } self.backgroundPort.onMessage.addListener(function(message) { if (message[cvox.ExtensionBridge.PONG_MSG]) { - self.gotPongFromBackgroundPage( - message[cvox.ExtensionBridge.PONG_MSG]); + self.gotPongFromBackgroundPage(message[cvox.ExtensionBridge.PONG_MSG]); } else { for (var i = 0; i < self.messageListeners.length; i++) { self.messageListeners[i](message, self.backgroundPort);
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/externs.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/externs.js index d39d52df..91004dfa 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/externs.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/externs.js
@@ -46,8 +46,8 @@ * @param {chrome.virtualKeyboardPrivate.VirtualKeyboardEvent} keyEvent * @param {Function=} opt_callback */ -chrome.virtualKeyboardPrivate.sendKeyEvent = - function(keyEvent, opt_callback) {}; +chrome.virtualKeyboardPrivate.sendKeyEvent = function(keyEvent, opt_callback) { +}; /** * @type {Object} */
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/host.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/host.js index cc3028f..c485669 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/host.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/host.js
@@ -61,7 +61,7 @@ cvox.ChromeVox.version = prefs['version']; cvox.ChromeVox.typingEcho = - /** @type {number} */(JSON.parse(prefs['typingEcho'])); + /** @type {number} */ (JSON.parse(prefs['typingEcho'])); if (prefs['position']) { cvox.ChromeVox.position = @@ -100,7 +100,8 @@ if (msg['message'] == 'DOMAINS_STYLES') { cvox.TraverseMath.getInstance().addDomainsAndStyles( msg['domains'], msg['styles']); - }}); + } + }); cvox.ExtensionBridge.addMessageListener(function(msg, port) { var message = msg['message']; @@ -121,15 +122,9 @@ } }.bind(this)); - cvox.ExtensionBridge.send({ - 'target': 'Prefs', - 'action': 'getPrefs' - }); + cvox.ExtensionBridge.send({'target': 'Prefs', 'action': 'getPrefs'}); - cvox.ExtensionBridge.send({ - 'target': 'Data', - 'action': 'getHistory' - }); + cvox.ExtensionBridge.send({'target': 'Data', 'action': 'getHistory'}); };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/mathjax.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/mathjax.js index c08722b..10aabe7 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/mathjax.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/mathjax.js
@@ -122,10 +122,9 @@ cvox.ChromeMathJax.prototype.portSetup = function(event) { if (event.data == 'cvox.MathJaxPortSetup') { this.port = event.ports[0]; - this.port.onmessage = - goog.bind( - function(event) {this.dispatchMessage(event.data);}, - this); + this.port.onmessage = goog.bind(function(event) { + this.dispatchMessage(event.data); + }, this); return false; } return true; @@ -144,11 +143,11 @@ case 'NodeMml': method = this.convertMarkupToDom; argNames = ['mathml', 'elementId']; - break; + break; case 'Active': method = this.applyBoolean; argNames = ['status']; - break; + break; } if (!method) { @@ -157,9 +156,9 @@ var callback = this.retrieveCallback_(message['id']); var args = message['args']; if (callback && method) { - method.apply(this, - [callback].concat( - argNames.map(function(x) {return args[x];}))); + method.apply(this, [callback].concat(argNames.map(function(x) { + return args[x]; + }))); } }; @@ -168,9 +167,8 @@ * Converts a Boolean string to boolean value and applies a callback function. * @param {function(boolean)} callback A function with one argument. * @param {boolean} bool A truth value. - */ -cvox.ChromeMathJax.prototype.applyBoolean = function( - callback, bool) { + */ +cvox.ChromeMathJax.prototype.applyBoolean = function(callback, bool) { callback(bool); }; @@ -188,21 +186,22 @@ var fetch = goog.bind(function() { retries++; - try {this.postMsg('Active', - function(result) { - if (result) { - callback(result); - } else if (retries < 5) { - setTimeout(fetch, 1000); - } - }); - } catch (x) { // Error usually means that the port is not ready yet. - if (retries < 5) { - setTimeout(fetch, 1000); - } else { - throw x; - }}}, - this); + try { + this.postMsg('Active', function(result) { + if (result) { + callback(result); + } else if (retries < 5) { + setTimeout(fetch, 1000); + } + }); + } catch (x) { // Error usually means that the port is not ready yet. + if (retries < 5) { + setTimeout(fetch, 1000); + } else { + throw x; + } + } + }, this); fetch(); }; @@ -219,8 +218,7 @@ /** * @override */ -cvox.ChromeMathJax.prototype.registerSignal = function( - callback, signal) { +cvox.ChromeMathJax.prototype.registerSignal = function(callback, signal) { this.postMsg('RegSig', callback, {sig: signal}); }; @@ -231,16 +229,14 @@ cvox.ChromeMathJax.prototype.injectScripts = function() { var retries = 0; - var fetch = goog.bind( - function() { - retries++; - if (this.port) { - this.postMsg('InjectScripts', function() {}); - } else if (retries < 10) { - setTimeout(fetch, 500); - } - }, - this); + var fetch = goog.bind(function() { + retries++; + if (this.port) { + this.postMsg('InjectScripts', function() {}); + } else if (retries < 10) { + setTimeout(fetch, 500); + } + }, this); fetch(); }; @@ -250,7 +246,7 @@ * @override */ cvox.ChromeMathJax.prototype.configMediaWiki = function() { - this.postMsg('ConfWikipedia', function() { }); + this.postMsg('ConfWikipedia', function() {}); }; @@ -281,5 +277,4 @@ /** Export platform constructor. */ -cvox.HostFactory.mathJaxConstructor = - cvox.ChromeMathJax; +cvox.HostFactory.mathJaxConstructor = cvox.ChromeMathJax;
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts.js index c2582c8..390c732 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts.js
@@ -58,19 +58,18 @@ /** @override */ cvox.ChromeTts.prototype.stop = function() { cvox.ChromeTts.superClass_.stop.call(this); - cvox.ExtensionBridge.send( - {'target': 'TTS', - 'action': 'stop'}); + cvox.ExtensionBridge.send({'target': 'TTS', 'action': 'stop'}); }; /** @override */ -cvox.ChromeTts.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { - cvox.ExtensionBridge.send( - {'target': 'TTS', - 'action': 'increaseOrDecrease', - 'property': propertyName, - 'increase': increase}); +cvox.ChromeTts.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) { + cvox.ExtensionBridge.send({ + 'target': 'TTS', + 'action': 'increaseOrDecrease', + 'property': propertyName, + 'increase': increase + }); }; /** @@ -81,30 +80,30 @@ */ cvox.ChromeTts.prototype.increaseProperty = function(property_name, announce) { goog.base(this, 'increaseProperty', property_name, announce); - cvox.ExtensionBridge.send( - {'target': 'TTS', - 'action': 'increase' + property_name, - 'announce': announce}); + cvox.ExtensionBridge.send({ + 'target': 'TTS', + 'action': 'increase' + property_name, + 'announce': announce + }); }; /** * Listens for TTS_COMPLETED message and executes the callback function. */ cvox.ChromeTts.prototype.addBridgeListener = function() { - cvox.ExtensionBridge.addMessageListener( - function(msg, port) { - var message = msg['message']; - if (message == 'TTS_CALLBACK') { - var id = msg['id']; - var func = cvox.ChromeTts.functionMap[id]; - if (func != undefined) { - if (!msg['cleanupOnly']) { - func(); - } - delete cvox.ChromeTts.functionMap[id]; - } + cvox.ExtensionBridge.addMessageListener(function(msg, port) { + var message = msg['message']; + if (message == 'TTS_CALLBACK') { + var id = msg['id']; + var func = cvox.ChromeTts.functionMap[id]; + if (func != undefined) { + if (!msg['cleanupOnly']) { + func(); } - }); + delete cvox.ChromeTts.functionMap[id]; + } + } + }); }; /** @@ -115,13 +114,15 @@ * @return {Object} A message. * @private */ -cvox.ChromeTts.prototype.createMessageForProperties_ = - function(textString, queueMode, properties) { - var message = {'target': 'TTS', - 'action': 'speak', - 'text': textString, - 'queueMode': queueMode, - 'properties': properties}; +cvox.ChromeTts.prototype.createMessageForProperties_ = function( + textString, queueMode, properties) { + var message = { + 'target': 'TTS', + 'action': 'speak', + 'text': textString, + 'queueMode': queueMode, + 'properties': properties + }; if (properties['startCallback'] != undefined) { cvox.ChromeTts.functionMap[cvox.ChromeTts.callId] =
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js index bb03cdfa8..e0b90a5 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js
@@ -46,18 +46,17 @@ opt_enableMath = opt_enableMath == undefined ? true : opt_enableMath; goog.base(this); - this.ttsProperties['rate'] = (parseFloat(localStorage['rate']) || - this.propertyDefault['rate']); - this.ttsProperties['pitch'] = (parseFloat(localStorage['pitch']) || - this.propertyDefault['pitch']); - this.ttsProperties['volume'] = (parseFloat(localStorage['volume']) || - this.propertyDefault['volume']); + this.ttsProperties['rate'] = + (parseFloat(localStorage['rate']) || this.propertyDefault['rate']); + this.ttsProperties['pitch'] = + (parseFloat(localStorage['pitch']) || this.propertyDefault['pitch']); + this.ttsProperties['volume'] = + (parseFloat(localStorage['volume']) || this.propertyDefault['volume']); // Use the current locale as the speech language if not otherwise // specified. if (this.ttsProperties['lang'] == undefined) { - this.ttsProperties['lang'] = - chrome.i18n.getUILanguage(); + this.ttsProperties['lang'] = chrome.i18n.getUILanguage(); } this.lastEventType = 'end'; @@ -72,7 +71,7 @@ * regexp:(RegExp), * clear:(boolean)}>} * @private - */ + */ this.punctuationEchoes_ = [ /** * Punctuation echoed for the 'none' option. @@ -111,9 +110,8 @@ * This is important for tts prosity. * @type {!Array<string>} * @private - */ - this.retainPunctuation_ = - [';', '?', '!', '\'']; + */ + this.retainPunctuation_ = [';', '?', '!', '\'']; /** * Mapping for math elements. @@ -133,8 +131,8 @@ * @private * @const */ - this.PHONETIC_MAP_ = /** @type {Object<string>} */( - JSON.parse(Msgs.getMsg('phonetic_map'))); + this.PHONETIC_MAP_ = + /** @type {Object<string>} */ (JSON.parse(Msgs.getMsg('phonetic_map'))); } catch (e) { console.log('Error; unable to parse phonetic map msg.'); } @@ -198,17 +196,9 @@ * @const */ cvox.TtsBackground.ALLOWED_PROPERTIES_ = [ - 'desiredEventTypes', - 'enqueue', - 'extensionId', - 'gender', - 'lang', - 'onEvent', - 'pitch', - 'rate', - 'requiredEventTypes', - 'voiceName', - 'volume']; + 'desiredEventTypes', 'enqueue', 'extensionId', 'gender', 'lang', 'onEvent', + 'pitch', 'rate', 'requiredEventTypes', 'voiceName', 'volume' +]; /** @override */ @@ -285,8 +275,7 @@ // make a note that we're going to stop speech. if (queueMode == cvox.QueueMode.FLUSH || queueMode == cvox.QueueMode.CATEGORY_FLUSH) { - (new PanelCommand( - PanelCommandType.CLEAR_SPEECH)).send(); + (new PanelCommand(PanelCommandType.CLEAR_SPEECH)).send(); if (this.shouldCancel_(this.currentUtterance_, utterance, queueMode)) { this.cancelUtterance_(this.currentUtterance_); @@ -294,8 +283,7 @@ } var i = 0; while (i < this.utteranceQueue_.length) { - if (this.shouldCancel_( - this.utteranceQueue_[i], utterance, queueMode)) { + if (this.shouldCancel_(this.utteranceQueue_[i], utterance, queueMode)) { this.cancelUtterance_(this.utteranceQueue_[i]); this.utteranceQueue_.splice(i, 1); } else { @@ -337,9 +325,8 @@ var utteranceId = utterance.id; utterance.properties['onEvent'] = goog.bind(function(event) { - this.onTtsEvent_(event, utteranceId); - }, - this); + this.onTtsEvent_(event, utteranceId); + }, this); var validatedProperties = {}; for (var i = 0; i < cvox.TtsBackground.ALLOWED_PROPERTIES_.length; i++) { @@ -350,16 +337,14 @@ } // Update the caption panel. - if (utterance.properties && - utterance.properties['pitch'] && + if (utterance.properties && utterance.properties['pitch'] && utterance.properties['pitch'] < this.ttsProperties['pitch']) { (new PanelCommand( - PanelCommandType.ADD_ANNOTATION_SPEECH, - utterance.textString)).send(); + PanelCommandType.ADD_ANNOTATION_SPEECH, utterance.textString)) + .send(); } else { - (new PanelCommand( - PanelCommandType.ADD_NORMAL_SPEECH, - utterance.textString)).send(); + (new PanelCommand(PanelCommandType.ADD_NORMAL_SPEECH, utterance.textString)) + .send(); } chrome.tts.speak(utterance.textString, validatedProperties); @@ -378,8 +363,7 @@ this.lastEventType = event['type']; // Ignore events sent on utterances other than the current one. - if (!this.currentUtterance_ || - utteranceId != this.currentUtterance_.id) { + if (!this.currentUtterance_ || utteranceId != this.currentUtterance_.id) { return; } @@ -442,8 +426,8 @@ * @return {boolean} True if this utterance should be canceled. * @private */ -cvox.TtsBackground.prototype.shouldCancel_ = - function(utteranceToCancel, newUtterance, queueMode) { +cvox.TtsBackground.prototype.shouldCancel_ = function( + utteranceToCancel, newUtterance, queueMode) { if (!utteranceToCancel) { return false; } @@ -456,7 +440,8 @@ case cvox.QueueMode.FLUSH: return true; case cvox.QueueMode.CATEGORY_FLUSH: - return (utteranceToCancel.properties['category'] == + return ( + utteranceToCancel.properties['category'] == newUtterance.properties['category']); } return false; @@ -478,9 +463,9 @@ }; /** @override */ -cvox.TtsBackground.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { - goog.base(this, 'increaseOrDecreaseProperty', propertyName, increase); +cvox.TtsBackground.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) { + goog.base(this, 'increaseOrDecreaseProperty', propertyName, increase); localStorage[propertyName] = this.ttsProperties[propertyName]; }; @@ -550,14 +535,12 @@ } else { pE = this.punctuationEchoes_[this.currentPunctuationEcho_]; } - text = - text.replace(pE.regexp, this.createPunctuationReplace_(pE.clear)); + text = text.replace(pE.regexp, this.createPunctuationReplace_(pE.clear)); // Try pronouncing phonetically for single characters. Cancel previous calls // to pronouncePhonetically_ if we fail to pronounce on this invokation or if // this text is math which should never be pronounced phonetically. - if (properties.math || - !properties['phoneticCharacters'] || + if (properties.math || !properties['phoneticCharacters'] || !this.pronouncePhonetically_(text)) { this.clearTimeout_(); } @@ -565,8 +548,9 @@ // Try looking up in our unicode tables for a short description. if (!properties.math && text.length == 1 && this.mathmap) { text = this.mathmap.store.lookupString( - text.toLowerCase(), - cvox.MathStore.createDynamicConstraint('default', 'short')) || text; + text.toLowerCase(), + cvox.MathStore.createDynamicConstraint('default', 'short')) || + text; } // Remove all whitespace from the beginning and end, and collapse all @@ -626,8 +610,8 @@ return text; } var result = ''; - var dynamicCstr = cvox.MathStore.createDynamicConstraint( - math['domain'], math['style']); + var dynamicCstr = + cvox.MathStore.createDynamicConstraint(math['domain'], math['style']); result = this.mathmap.store.lookupString(text, dynamicCstr); if (result) { return result; @@ -664,12 +648,13 @@ */ cvox.TtsBackground.prototype.createPunctuationReplace_ = function(clear) { return goog.bind(function(match) { - var retain = this.retainPunctuation_.indexOf(match) != -1 ? - match : ' '; + var retain = this.retainPunctuation_.indexOf(match) != -1 ? match : ' '; return clear ? retain : - ' ' + (new goog.i18n.MessageFormat(Msgs.getMsg( - cvox.AbstractTts.CHARACTER_DICTIONARY[match]))) - .format({'COUNT': 1}) + retain + ' '; + ' ' + + (new goog.i18n.MessageFormat( + Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[match]))) + .format({'COUNT': 1}) + + retain + ' '; }, this); }; @@ -721,15 +706,21 @@ cvox.TtsBackground.prototype.updateVoice_ = function(voiceName, opt_callback) { chrome.tts.getVoices(goog.bind(function(voices) { chrome.i18n.getAcceptLanguages(goog.bind(function(acceptLanguages) { - var currentLocale = acceptLanguages[0] || - chrome.i18n.getUILanguage() || ''; + var currentLocale = + acceptLanguages[0] || chrome.i18n.getUILanguage() || ''; var match = voices.find.bind(voices); - var newVoice = - match(function(v) { return v.voiceName == voiceName; }) || - match(function(v) { return v.lang === currentLocale; }) || - match(function(v) { return currentLocale.startsWith(v.lang); }) || - match(function(v) { return v.lang && - v.lang.startsWith(currentLocale); }) || + var newVoice = match(function(v) { + return v.voiceName == voiceName; + }) || + match(function(v) { + return v.lang === currentLocale; + }) || + match(function(v) { + return currentLocale.startsWith(v.lang); + }) || + match(function(v) { + return v.lang && v.lang.startsWith(currentLocale); + }) || voices[0]; if (newVoice) {
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_earcons.js b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_earcons.js index 9a610cf6..f4acb60 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_earcons.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_earcons.js
@@ -74,8 +74,7 @@ /** * @constructor */ -cvox.AbstractEarcons = function() { -}; +cvox.AbstractEarcons = function() {}; /** @@ -92,16 +91,14 @@ * @param {Object=} opt_location A location associated with the earcon such as a * control's bounding rectangle. */ -cvox.AbstractEarcons.prototype.playEarcon = function(earcon, opt_location) { -}; +cvox.AbstractEarcons.prototype.playEarcon = function(earcon, opt_location) {}; /** * Cancels the specified earcon sound. * @param {cvox.Earcon} earcon An earcon identifier. */ -cvox.AbstractEarcons.prototype.cancelEarcon = function(earcon) { -}; +cvox.AbstractEarcons.prototype.cancelEarcon = function(earcon) {}; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_host.js b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_host.js index 805194d3..ad0d69cc 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_host.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_host.js
@@ -15,8 +15,7 @@ /** * @constructor */ -cvox.AbstractHost = function() { -}; +cvox.AbstractHost = function() {}; /** @@ -32,30 +31,26 @@ /** * Do all host-platform-specific initialization. */ -cvox.AbstractHost.prototype.init = function() { -}; +cvox.AbstractHost.prototype.init = function() {}; /** * Used to reinitialize ChromeVox if initialization fails. */ -cvox.AbstractHost.prototype.reinit = function() { -}; +cvox.AbstractHost.prototype.reinit = function() {}; /** * Executed on page load. */ -cvox.AbstractHost.prototype.onPageLoad = function() { -}; +cvox.AbstractHost.prototype.onPageLoad = function() {}; /** * Sends a message to the background page (if it exists) for this host. * @param {Object} message The message to pass to the background page. */ -cvox.AbstractHost.prototype.sendToBackgroundPage = function(message) { -}; +cvox.AbstractHost.prototype.sendToBackgroundPage = function(message) {}; /** @@ -111,8 +106,9 @@ * inactive. */ cvox.AbstractHost.prototype.activateOrDeactivateChromeVox = function(active) { - this.onStateChanged_(active ? cvox.AbstractHost.State.ACTIVE : - cvox.AbstractHost.State.INACTIVE); + this.onStateChanged_( + active ? cvox.AbstractHost.State.ACTIVE : + cvox.AbstractHost.State.INACTIVE); };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_mathjax.js b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_mathjax.js index ce19c056..98fa1636 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_mathjax.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_mathjax.js
@@ -17,8 +17,7 @@ * @constructor * @implements {cvox.MathJaxInterface} */ -cvox.AbstractMathJax = function() { -}; +cvox.AbstractMathJax = function() {}; /** @@ -69,8 +68,8 @@ * an id string. */ cvox.AbstractMathJax.prototype.getAllTexs = function(callback) { - var allTexs = document. - querySelectorAll(cvox.DomUtil.altMathQuerySelector('tex')); + var allTexs = + document.querySelectorAll(cvox.DomUtil.altMathQuerySelector('tex')); for (var i = 0, tex; tex = allTexs[i]; i++) { this.getTex(callback, tex); } @@ -83,8 +82,8 @@ * an id string. */ cvox.AbstractMathJax.prototype.getAllAsciiMaths = function(callback) { - var allAsciiMaths = document. - querySelectorAll(cvox.DomUtil.altMathQuerySelector('asciimath')); + var allAsciiMaths = + document.querySelectorAll(cvox.DomUtil.altMathQuerySelector('asciimath')); for (var i = 0, tex; tex = allAsciiMaths[i]; i++) { this.getAsciiMath(callback, tex); }
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_tts.js b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_tts.js index db87ff6..694d3bc 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_tts.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/abstract_tts.js
@@ -31,11 +31,7 @@ * volume: number}} * @protected */ - this.propertyDefault = { - 'rate': 0.5, - 'pitch': 0.5, - 'volume': 0.5 - }; + this.propertyDefault = {'rate': 0.5, 'pitch': 0.5, 'volume': 0.5}; /** * Min value for TTS properties. @@ -44,11 +40,7 @@ * volume: number}} * @protected */ - this.propertyMin = { - 'rate': 0.0, - 'pitch': 0.0, - 'volume': 0.0 - }; + this.propertyMin = {'rate': 0.0, 'pitch': 0.0, 'volume': 0.0}; /** * Max value for TTS properties. @@ -57,11 +49,7 @@ * volume: number}} * @protected */ - this.propertyMax = { - 'rate': 1.0, - 'pitch': 1.0, - 'volume': 1.0 - }; + this.propertyMax = {'rate': 1.0, 'pitch': 1.0, 'volume': 1.0}; /** * Step value for TTS properties. @@ -70,11 +58,7 @@ * volume: number}} * @protected */ - this.propertyStep = { - 'rate': 0.1, - 'pitch': 0.1, - 'volume': 0.1 - }; + this.propertyStep = {'rate': 0.1, 'pitch': 0.1, 'volume': 0.1}; /** @private */ @@ -124,25 +108,24 @@ /** @override */ -cvox.AbstractTts.prototype.stop = function() { +cvox.AbstractTts.prototype.stop = function() {}; + + +/** @override */ +cvox.AbstractTts.prototype.addCapturingEventListener = function(listener) {}; + + +/** @override */ +cvox.AbstractTts.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) { + var min = this.propertyMin[propertyName]; + var max = this.propertyMax[propertyName]; + var step = this.propertyStep[propertyName]; + var current = this.ttsProperties[propertyName]; + current = increase ? current + step : current - step; + this.ttsProperties[propertyName] = Math.max(Math.min(current, max), min); }; - -/** @override */ -cvox.AbstractTts.prototype.addCapturingEventListener = function(listener) { }; - - -/** @override */ -cvox.AbstractTts.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { - var min = this.propertyMin[propertyName]; - var max = this.propertyMax[propertyName]; - var step = this.propertyStep[propertyName]; - var current = this.ttsProperties[propertyName]; - current = increase ? current + step : current - step; - this.ttsProperties[propertyName] = Math.max(Math.min(current, max), min); - }; - /** * Converts an engine property value to a percentage from 0.00 to 1.00. * @param {string} property The property to convert. @@ -150,7 +133,7 @@ */ cvox.AbstractTts.prototype.propertyToPercentage = function(property) { return (this.ttsProperties[property] - this.propertyMin[property]) / - Math.abs(this.propertyMax[property] - this.propertyMin[property]); + Math.abs(this.propertyMax[property] - this.propertyMin[property]); }; /** @@ -233,23 +216,22 @@ cvox.AbstractTts.prototype.preprocess = function(text, properties) { if (text.length == 1 && text >= 'A' && text <= 'Z') { for (var prop in cvox.AbstractTts.PERSONALITY_CAPITAL) - properties[prop] = cvox.AbstractTts.PERSONALITY_CAPITAL[prop]; + properties[prop] = cvox.AbstractTts.PERSONALITY_CAPITAL[prop]; } // Substitute all symbols in the substitution dictionary. This is pretty // efficient because we use a single regexp that matches all symbols // simultaneously. text = text.replace( - cvox.AbstractTts.substitutionDictionaryRegexp_, - function(symbol) { + cvox.AbstractTts.substitutionDictionaryRegexp_, function(symbol) { return ' ' + cvox.AbstractTts.SUBSTITUTION_DICTIONARY[symbol] + ' '; }); // Handle single characters that we want to make sure we pronounce. if (text.length == 1) { return cvox.AbstractTts.CHARACTER_DICTIONARY[text] ? - (new goog.i18n.MessageFormat(Msgs.getMsg( - cvox.AbstractTts.CHARACTER_DICTIONARY[text]))) + (new goog.i18n.MessageFormat( + Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[text]))) .format({'COUNT': 1}) : text.toUpperCase(); } @@ -259,8 +241,7 @@ // simultaneously, and it calls a function with each match, which we can // use to look up the replacement in our dictionary. text = text.replace( - cvox.AbstractTts.pronunciationDictionaryRegexp_, - function(word) { + cvox.AbstractTts.pronunciationDictionaryRegexp_, function(word) { return cvox.AbstractTts.PRONUNCIATION_DICTIONARY[word.toLowerCase()]; }); @@ -468,7 +449,7 @@ 'gmail': 'gee mail', 'gtalk': 'gee talk', 'http': 'H T T P', - 'https' : 'H T T P S', + 'https': 'H T T P S', 'igoogle': 'eye google', 'pagerank': 'page-rank', 'username': 'user-name', @@ -563,9 +544,11 @@ */ cvox.AbstractTts.repetitionReplace_ = function(match) { var count = match.length; - return ' ' + (new goog.i18n.MessageFormat(Msgs.getMsg( - cvox.AbstractTts.CHARACTER_DICTIONARY[match[0]]))) - .format({'COUNT': count}) + ' '; + return ' ' + + (new goog.i18n.MessageFormat( + Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[match[0]]))) + .format({'COUNT': count}) + + ' '; };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/braille_interface.js b/chrome/browser/resources/chromeos/chromevox/host/interface/braille_interface.js index 754a961..39fe7dc 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/braille_interface.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/braille_interface.js
@@ -18,15 +18,14 @@ /** * @interface */ -cvox.BrailleInterface = function() { }; +cvox.BrailleInterface = function() {}; /** * Sends the given params to the Braille display for output. * @param {!cvox.NavBraille} params Parameters to send to the * platform braille service. */ -cvox.BrailleInterface.prototype.write = - function(params) { }; +cvox.BrailleInterface.prototype.write = function(params) {}; /** * Takes an image in the form of a data url and outputs it to a Braille @@ -34,22 +33,21 @@ * @param {!string} imageDataUrl The image to output, in the form of a * dataUrl. */ -cvox.BrailleInterface.prototype.writeRawImage = - function(imageDataUrl) { }; +cvox.BrailleInterface.prototype.writeRawImage = function(imageDataUrl) {}; /** * Freeze whatever is on the braille display until the next call to thaw(). */ -cvox.BrailleInterface.prototype.freeze = function() { }; +cvox.BrailleInterface.prototype.freeze = function() {}; /** * Un-freeze the braille display so that it can be written to again. */ -cvox.BrailleInterface.prototype.thaw = function() { }; +cvox.BrailleInterface.prototype.thaw = function() {}; /** * @return {!cvox.BrailleDisplayState} The current display state. */ -cvox.BrailleInterface.prototype.getDisplayState = function() { }; +cvox.BrailleInterface.prototype.getDisplayState = function() {};
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/mathjax_interface.js b/chrome/browser/resources/chromeos/chromevox/host/interface/mathjax_interface.js index f15b2d79..630170c3 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/mathjax_interface.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/mathjax_interface.js
@@ -13,7 +13,7 @@ /** * @interface */ -cvox.MathJaxInterface = function() { }; +cvox.MathJaxInterface = function() {}; /** @@ -21,7 +21,7 @@ * @param {function(boolean)} callback A function with the active status as * argument. */ -cvox.MathJaxInterface.prototype.isMathjaxActive = function(callback) { }; +cvox.MathJaxInterface.prototype.isMathjaxActive = function(callback) {}; /** @@ -30,7 +30,7 @@ * @param {function(Node, string)} callback A function taking a node and an id * string. */ -cvox.MathJaxInterface.prototype.getAllJax = function(callback) { }; +cvox.MathJaxInterface.prototype.getAllJax = function(callback) {}; /** @@ -40,20 +40,20 @@ * string. * @param {string} signal The Mathjax signal to fire the callback. */ -cvox.MathJaxInterface.prototype.registerSignal = function(callback, signal) { }; +cvox.MathJaxInterface.prototype.registerSignal = function(callback, signal) {}; /** * Injects some minimalistic MathJax script into the page to translate LaTeX * expressions. */ -cvox.MathJaxInterface.prototype.injectScripts = function() { }; +cvox.MathJaxInterface.prototype.injectScripts = function() {}; /** * Loads configurations for MediaWiki pages (e.g., Wikipedia). */ -cvox.MathJaxInterface.prototype.configMediaWiki = function() { }; +cvox.MathJaxInterface.prototype.configMediaWiki = function() {}; /** @@ -63,7 +63,7 @@ * an id string. * @param {Node} texNode Node with img tag and tex or latex class. */ -cvox.MathJaxInterface.prototype.getTex = function(callback, texNode) { }; +cvox.MathJaxInterface.prototype.getTex = function(callback, texNode) {}; /** @@ -74,4 +74,4 @@ * inlineformula, or displayformula. */ cvox.MathJaxInterface.prototype.getAsciiMath = function( - callback, asciiMathNode) { }; + callback, asciiMathNode) {};
diff --git a/chrome/browser/resources/chromeos/chromevox/host/interface/tts_interface.js b/chrome/browser/resources/chromeos/chromevox/host/interface/tts_interface.js index 0eea258f..7ff3e86 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/interface/tts_interface.js +++ b/chrome/browser/resources/chromeos/chromevox/host/interface/tts_interface.js
@@ -52,27 +52,27 @@ * An interface for clients who want to get notified when an utterance * starts or ends from any source. */ -cvox.TtsCapturingEventListener = function() { }; +cvox.TtsCapturingEventListener = function() {}; /** * Called when any utterance starts. */ -cvox.TtsCapturingEventListener.prototype.onTtsStart = function() { }; +cvox.TtsCapturingEventListener.prototype.onTtsStart = function() {}; /** * Called when any utterance ends. */ -cvox.TtsCapturingEventListener.prototype.onTtsEnd = function() { }; +cvox.TtsCapturingEventListener.prototype.onTtsEnd = function() {}; /** * Called when any utterance gets interrupted. */ -cvox.TtsCapturingEventListener.prototype.onTtsInterrupted = function() { }; +cvox.TtsCapturingEventListener.prototype.onTtsInterrupted = function() {}; /** * @interface */ -cvox.TtsInterface = function() { }; +cvox.TtsInterface = function() {}; /** * Speaks the given string using the specified queueMode and properties. @@ -81,27 +81,27 @@ * @param {Object=} properties Speech properties to use for this utterance. * @return {cvox.TtsInterface} A tts object useful for chaining speak calls. */ -cvox.TtsInterface.prototype.speak = - function(textString, queueMode, properties) { }; +cvox.TtsInterface.prototype.speak = function( + textString, queueMode, properties) {}; /** * Returns true if the TTS is currently speaking. * @return {boolean} True if the TTS is speaking. */ -cvox.TtsInterface.prototype.isSpeaking = function() { }; +cvox.TtsInterface.prototype.isSpeaking = function() {}; /** * Stops speech. */ -cvox.TtsInterface.prototype.stop = function() { }; +cvox.TtsInterface.prototype.stop = function() {}; /** * Adds a listener to get called whenever any utterance starts or ends. * @param {cvox.TtsCapturingEventListener} listener Listener to get called. */ -cvox.TtsInterface.prototype.addCapturingEventListener = function(listener) { }; +cvox.TtsInterface.prototype.addCapturingEventListener = function(listener) {}; /** * Increases a TTS speech property. @@ -109,8 +109,8 @@ * @param {boolean} increase If true, increases the property value by one * step size, otherwise decreases. */ -cvox.TtsInterface.prototype.increaseOrDecreaseProperty = - function(propertyName, increase) { }; +cvox.TtsInterface.prototype.increaseOrDecreaseProperty = function( + propertyName, increase) {}; /** @@ -118,7 +118,7 @@ * @param {string} property The property to convert. * @return {?number} The percentage of the property. */ -cvox.TtsInterface.prototype.propertyToPercentage = function(property) { }; +cvox.TtsInterface.prototype.propertyToPercentage = function(property) {}; /** @@ -126,7 +126,7 @@ * @param {string} property Name of property. * @return {?number} The default value. */ -cvox.TtsInterface.prototype.getDefaultProperty = function(property) { }; +cvox.TtsInterface.prototype.getDefaultProperty = function(property) {}; /** * Toggles on or off speech.
diff --git a/chrome/browser/resources/chromeos/chromevox/host/testing/mathjax.js b/chrome/browser/resources/chromeos/chromevox/host/testing/mathjax.js index 2f9e329..f298db60 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/testing/mathjax.js +++ b/chrome/browser/resources/chromeos/chromevox/host/testing/mathjax.js
@@ -26,46 +26,44 @@ /** * @override */ -cvox.TestMathJax.prototype.isMathjaxActive = function(callback) { }; +cvox.TestMathJax.prototype.isMathjaxActive = function(callback) {}; /** * @override */ -cvox.TestMathJax.prototype.getAllJax = function(callback) { }; +cvox.TestMathJax.prototype.getAllJax = function(callback) {}; /** * @override */ -cvox.TestMathJax.prototype.registerSignal = function( - callback, signal) { }; +cvox.TestMathJax.prototype.registerSignal = function(callback, signal) {}; /** * @override */ -cvox.TestMathJax.prototype.injectScripts = function() { }; +cvox.TestMathJax.prototype.injectScripts = function() {}; /** * @override */ -cvox.TestMathJax.prototype.configMediaWiki = function() { }; +cvox.TestMathJax.prototype.configMediaWiki = function() {}; /** * @override */ -cvox.TestMathJax.prototype.getTex = function(callback, texNode) { }; +cvox.TestMathJax.prototype.getTex = function(callback, texNode) {}; /** * @override */ -cvox.TestMathJax.prototype.getAsciiMath = function(callback, asciiMathNode) { }; +cvox.TestMathJax.prototype.getAsciiMath = function(callback, asciiMathNode) {}; /** Export platform constructor. */ -cvox.HostFactory.mathJaxConstructor = - cvox.TestMathJax; +cvox.HostFactory.mathJaxConstructor = cvox.TestMathJax;
diff --git a/chrome/browser/resources/chromeos/chromevox/host/testing/tts.js b/chrome/browser/resources/chromeos/chromevox/host/testing/tts.js index 168769b..466653d 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/testing/tts.js +++ b/chrome/browser/resources/chromeos/chromevox/host/testing/tts.js
@@ -37,15 +37,13 @@ * @override */ cvox.TestTts.prototype.speak = function(text, queueMode, opt_properties) { - this.utterances_.push({text: text, - queueMode: queueMode, - properties: opt_properties}); + this.utterances_.push( + {text: text, queueMode: queueMode, properties: opt_properties}); if (opt_properties && opt_properties['endCallback'] != undefined) { var len = this.utterances_.length; // 'After' is a sentinel value in the tests that tells TTS to stop and // ends callbacks being called. - if (this.utterances_[len - 1].text != - this.sentinelText_) { + if (this.utterances_[len - 1].text != this.sentinelText_) { opt_properties['endCallback'](); } } @@ -105,15 +103,17 @@ case cvox.AbstractTts.QUEUE_MODE_CATEGORY_FLUSH: queue = queue.filter(function(u) { return (utterance.properties && utterance.properties.category) && - (!u.properties || - u.properties.category != utterance.properties.category); + (!u.properties || + u.properties.category != utterance.properties.category); }); break; } queue.push(utterance); } - return queue.map(function(u) { return u.text; }); + return queue.map(function(u) { + return u.text; + }); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/base_rule_store.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/base_rule_store.js index 079e419..6f082f8 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/base_rule_store.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/base_rule_store.js
@@ -71,14 +71,13 @@ (node.nodeType != Node.ELEMENT_NODE && node.nodeType != Node.TEXT_NODE)) { return null; } - var matchingRules = this.speechRules_.filter( - goog.bind( - function(rule) { - return this.testDynamicConstraints(dynamic, rule) && - this.testPrecondition_(/** @type {!Node} */ (node), rule);}, - this)); + var matchingRules = this.speechRules_.filter(goog.bind(function(rule) { + return this.testDynamicConstraints(dynamic, rule) && + this.testPrecondition_(/** @type {!Node} */ (node), rule); + }, this)); return (matchingRules.length > 0) ? - this.pickMostConstraint_(dynamic, matchingRules) : null; + this.pickMostConstraint_(dynamic, matchingRules) : + null; }; @@ -98,8 +97,7 @@ if (err.name == 'RuleError') { console.log('Rule Error ', prec, '(' + dynamic + '):', err.message); return null; - } - else { + } else { throw err; } } @@ -182,13 +180,13 @@ cvox.BaseRuleStore.prototype.removeDuplicates = function(rule) { for (var i = this.speechRules_.length - 1, oldRule; oldRule = this.speechRules_[i]; i--) { - if (oldRule != rule && - cvox.BaseRuleStore.compareDynamicConstraints_( - oldRule.dynamicCstr, rule.dynamicCstr) && - cvox.BaseRuleStore.comparePreconditions_(oldRule, rule)) { - this.speechRules_.splice(i, 1); - } - } + if (oldRule != rule && + cvox.BaseRuleStore.compareDynamicConstraints_( + oldRule.dynamicCstr, rule.dynamicCstr) && + cvox.BaseRuleStore.comparePreconditions_(oldRule, rule)) { + this.speechRules_.splice(i, 1); + } + } }; @@ -199,8 +197,7 @@ * @param {string} funcName A function name. * @return {Array<Node>} The list of resulting nodes. */ -cvox.BaseRuleStore.prototype.applyCustomQuery = function( - node, funcName) { +cvox.BaseRuleStore.prototype.applyCustomQuery = function(node, funcName) { var func = this.customQueries.lookup(funcName); return func ? func(node) : null; }; @@ -258,19 +255,17 @@ * @return {boolean} True if the preconditions apply to the node. * @protected */ -cvox.BaseRuleStore.prototype.testDynamicConstraints = function( - dynamic, rule) { +cvox.BaseRuleStore.prototype.testDynamicConstraints = function(dynamic, rule) { // We allow a default value for each dynamic constraints attribute. // The idea is that when we can not find a speech rule matching the value for // a particular attribute in the dynamic constraintwe choose the one that has // the value 'default'. var allKeys = /** @type {Array<cvox.SpeechRule.DynamicCstrAttrib>} */ ( Object.keys(dynamic)); - return allKeys.every( - function(key) { - return dynamic[key] == rule.dynamicCstr[key] || - rule.dynamicCstr[key] == 'default'; - }); + return allKeys.every(function(key) { + return dynamic[key] == rule.dynamicCstr[key] || + rule.dynamicCstr[key] == 'default'; + }); }; @@ -309,7 +304,8 @@ for (var i = 0, key; key = this.dynamicCstrAttribs[i]; i++) { if (dynamic[key] == rule.dynamicCstr[key]) { result++; - } else break; + } else + break; } return result; }; @@ -325,23 +321,23 @@ * @private */ cvox.BaseRuleStore.prototype.pickMostConstraint_ = function(dynamic, rules) { - rules.sort(goog.bind( - function(r1, r2) { - var count1 = this.countMatchingDynamicConstraintValues_(dynamic, r1); - var count2 = this.countMatchingDynamicConstraintValues_(dynamic, r2); - // Rule one is a better match, don't swap. - if (count1 > count2) { - return -1; - } - // Rule two is a better match, swap. - if (count2 > count1) { - return 1; - } - // When same number of dynamic constraint attributes matches for - // both rules, compare length of static constraints. - return (r2.precondition.constraints.length - - r1.precondition.constraints.length);}, - this)); + rules.sort(goog.bind(function(r1, r2) { + var count1 = this.countMatchingDynamicConstraintValues_(dynamic, r1); + var count2 = this.countMatchingDynamicConstraintValues_(dynamic, r2); + // Rule one is a better match, don't swap. + if (count1 > count2) { + return -1; + } + // Rule two is a better match, swap. + if (count2 > count1) { + return 1; + } + // When same number of dynamic constraint attributes matches for + // both rules, compare length of static constraints. + return ( + r2.precondition.constraints.length - + r1.precondition.constraints.length); + }, this)); return rules[0]; }; @@ -356,10 +352,9 @@ cvox.BaseRuleStore.prototype.testPrecondition_ = function(node, rule) { var prec = rule.precondition; return this.applyQuery(node, prec.query) === node && - prec.constraints.every( - goog.bind(function(cstr) { - return this.applyConstraint(node, cstr);}, - this)); + prec.constraints.every(goog.bind(function(cstr) { + return this.applyConstraint(node, cstr); + }, this)); }; @@ -372,8 +367,7 @@ * @return {boolean} True if the dynamic constraints are equal. * @private */ -cvox.BaseRuleStore.compareDynamicConstraints_ = function( - cstr1, cstr2) { +cvox.BaseRuleStore.compareDynamicConstraints_ = function(cstr1, cstr2) { if (Object.keys(cstr1).length != Object.keys(cstr2).length) { return false; } @@ -394,8 +388,7 @@ * @return {boolean} True if the static constraints are equal. * @private */ -cvox.BaseRuleStore.compareStaticConstraints_ = function( - cstr1, cstr2) { +cvox.BaseRuleStore.compareStaticConstraints_ = function(cstr1, cstr2) { if (cstr1.length != cstr2.length) { return false; } @@ -420,7 +413,7 @@ var prec2 = rule2.precondition; if (prec1.query != prec2.query) { return false; - } + } return cvox.BaseRuleStore.compareStaticConstraints_( prec1.constraints, prec2.constraints); };
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/math_simple_store.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/math_simple_store.js index 1ca1a9b..92d0b78 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/math_simple_store.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/math_simple_store.js
@@ -25,7 +25,7 @@ */ cvox.MathSimpleStore = function() { goog.base(this); - }; +}; goog.inherits(cvox.MathSimpleStore, cvox.MathStore); @@ -38,14 +38,14 @@ * mapping. */ cvox.MathSimpleStore.prototype.defineRulesFromMappings = function( - name, str, mapping) { + name, str, mapping) { for (var domain in mapping) { for (var style in mapping[domain]) { var content = mapping[domain][style]; var cstr = 'self::text() = "' + str + '"'; var rule = this.defineRule( - name, domain + '.' + style, '[t] "' + content + '"', - 'self::text()', cstr); + name, domain + '.' + style, '[t] "' + content + '"', 'self::text()', + cstr); } } }; @@ -135,9 +135,10 @@ return ''; } return rule.action.components - .map(function(comp) { - return comp.content.slice(1, -1);}) - .join(' '); + .map(function(comp) { + return comp.content.slice(1, -1); + }) + .join(' '); }; @@ -154,9 +155,9 @@ var set = newCstr[key]; if (set) { newCstr[key] = cvox.MathUtil.union(set, cstr[key]); - } else { + } else { newCstr[key] = cstr[key]; - } + } } } return newCstr;
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/math_store.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/math_store.js index 4c33452..f538994 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/math_store.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/math_store.js
@@ -30,7 +30,7 @@ this.dynamicCstrAttribs = [ cvox.SpeechRule.DynamicCstrAttrib.DOMAIN, cvox.SpeechRule.DynamicCstrAttrib.STYLE - ]; + ]; /** * @override @@ -51,9 +51,9 @@ var dynamicCstr = this.parseDynamicConstraint(dynamic); var cstrList = Array.prototype.slice.call(arguments, 4); // We can not use goog.base due to variable number of constraint arguments. - var rule = cvox.MathStore.superClass_.defineRule.apply( - this, [name, dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE], - action, query].concat(cstrList)); + var rule = cvox.MathStore.superClass_.defineRule.apply(this, [ + name, dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE], action, query + ].concat(cstrList)); // In the superclass the dynamic constraint only contains style annotations. // We now set the proper dynamic constraint that contains in addition a // a domain attribute/value pair. @@ -103,12 +103,9 @@ cvox.MathStore.prototype.defineUniqueRuleAlias = function( name, dynamic, query, cstr) { var dynamicCstr = this.parseDynamicConstraint(dynamic); - var rule = this.findRule( - goog.bind( - function(rule) { - return rule.name == name && - this.testDynamicConstraints(dynamicCstr, rule);}, - this)); + var rule = this.findRule(goog.bind(function(rule) { + return rule.name == name && this.testDynamicConstraints(dynamicCstr, rule); + }, this)); if (!rule) { throw new cvox.SpeechRule.OutputError( 'Rule named ' + name + ' with style ' + dynamic + ' does not exist.'); @@ -125,11 +122,12 @@ */ cvox.MathStore.prototype.defineRuleAlias = function(name, query, cstr) { var rule = this.findRule(function(rule) { - return rule.name == name;}); + return rule.name == name; + }); if (!rule) { throw new cvox.SpeechRule.OutputError( - 'Rule with named ' + name + ' does not exist.'); - } + 'Rule with named ' + name + ' does not exist.'); + } this.addAlias_(rule, query, Array.prototype.slice.call(arguments, 2)); }; @@ -141,17 +139,17 @@ * @param {...string} cstr Additional static precondition constraints. */ cvox.MathStore.prototype.defineRulesAlias = function(name, query, cstr) { - var rules = this.findAllRules(function(rule) {return rule.name == name;}); + var rules = this.findAllRules(function(rule) { + return rule.name == name; + }); if (rules.length == 0) { throw new cvox.SpeechRule.OutputError( 'Rule with name ' + name + ' does not exist.'); } var cstrList = Array.prototype.slice.call(arguments, 2); - rules.forEach(goog.bind( - function(rule) { - this.addAlias_(rule, query, cstrList); - }, - this)); + rules.forEach(goog.bind(function(rule) { + this.addAlias_(rule, query, cstrList); + }, this)); }; @@ -164,8 +162,8 @@ */ cvox.MathStore.prototype.addAlias_ = function(rule, query, cstrList) { var prec = new cvox.SpeechRule.Precondition(query, cstrList); - var newRule = new cvox.SpeechRule( - rule.name, rule.dynamicCstr, prec, rule.action); + var newRule = + new cvox.SpeechRule(rule.name, rule.dynamicCstr, prec, rule.action); newRule.name = rule.name; this.addRule(newRule); }; @@ -217,14 +215,14 @@ // Dealing with surrogate pairs. var chr = rest[0]; var code = chr.charCodeAt(0); - if (0xD800 <= code && code <= 0xDBFF && - rest.length > 1 && !isNaN(rest.charCodeAt(1))) { + if (0xD800 <= code && code <= 0xDBFF && rest.length > 1 && + !isNaN(rest.charCodeAt(1))) { descs.push(this.evaluate_(rest.slice(0, 2))); rest = rest.substring(2); } else { descs.push(this.evaluate_(rest[0])); rest = rest.substring(1); - } + } } } } @@ -245,15 +243,14 @@ if (cvox.ChromeVox.host['mathMap']) { // VS: Change this for android! return cvox.ChromeVox.host['mathMap'].evaluate( - text, - cvox.TraverseMath.getInstance().domain, + text, cvox.TraverseMath.getInstance().domain, cvox.TraverseMath.getInstance().style); } - return new cvox.NavMathDescription( - {'text': text, - 'domain': cvox.TraverseMath.getInstance().domain, - 'style': cvox.TraverseMath.getInstance().style - }); + return new cvox.NavMathDescription({ + 'text': text, + 'domain': cvox.TraverseMath.getInstance().domain, + 'style': cvox.TraverseMath.getInstance().style + }); }; @@ -264,5 +261,7 @@ * @private */ cvox.MathStore.removeEmpty_ = function(strs) { - return strs.filter(function(str) {return str;}); + return strs.filter(function(str) { + return str; + }); };
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store.js index 62fa35e..fbe853a 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store.js
@@ -39,6 +39,6 @@ * @param {string} name Rule name which corresponds to the MathML tag name. * @param {string} rule String version of the speech rule. */ -cvox.MathmlStore.prototype.defineDefaultMathmlRule = function(name, rule) { +cvox.MathmlStore.prototype.defineDefaultMathmlRule = function(name, rule) { this.defineRule(name, 'default.default', rule, 'self::mathml:' + name); };
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_rules.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_rules.js index ec16ce9a7..3b286ec5 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_rules.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_rules.js
@@ -21,10 +21,10 @@ cvox.MathmlStoreRules = function() { // Custom functions used in the rules. cvox.MathmlStoreRules.initCustomFunctions_(); - cvox.MathmlStoreRules.initDefaultRules_(); // MathML rules. - cvox.MathmlStoreRules.initMathjaxRules_(); // MathJax Rules - cvox.MathmlStoreRules.initAliases_(); // MathJax Aliases for MathML rules. - cvox.MathmlStoreRules.initSpecializationRules_(); // Square, cube, etc. + cvox.MathmlStoreRules.initDefaultRules_(); // MathML rules. + cvox.MathmlStoreRules.initMathjaxRules_(); // MathJax Rules + cvox.MathmlStoreRules.initAliases_(); // MathJax Aliases for MathML rules. + cvox.MathmlStoreRules.initSpecializationRules_(); // Square, cube, etc. cvox.MathmlStoreRules.initSemanticRules_(); }; goog.addSingletonGetter(cvox.MathmlStoreRules); @@ -111,41 +111,44 @@ defineDefaultMathmlRule('mn', '[n] text()'); // Dealing with fonts. - defineRule('mtext-variant', 'default.default', + defineRule( + 'mtext-variant', 'default.default', '[t] "begin"; [t] @mathvariant (pause:150);' + '[t] text() (pause:150); [t] "end"; ' + '[t] @mathvariant (pause:200)', 'self::mathml:mtext', '@mathvariant', '@mathvariant!="normal"'); - defineRule('mi-variant', 'default.default', - '[t] @mathvariant; [n] text()', + defineRule( + 'mi-variant', 'default.default', '[t] @mathvariant; [n] text()', 'self::mathml:mi', '@mathvariant', '@mathvariant!="normal"'); - defineRuleAlias('mi-variant', 'self::mathml:mn', // mn + defineRuleAlias( + 'mi-variant', 'self::mathml:mn', // mn '@mathvariant', '@mathvariant!="normal"'); - defineRule('mo-variant', 'default.default', - '[t] @mathvariant; [n] text() (rate:-0.1)', - 'self::mathml:mo', '@mathvariant', '@mathvariant!="normal"'); + defineRule( + 'mo-variant', 'default.default', + '[t] @mathvariant; [n] text() (rate:-0.1)', 'self::mathml:mo', + '@mathvariant', '@mathvariant!="normal"'); defineDefaultMathmlRule( - 'ms', - '[t] "string" (pitch:0.5, rate:0.5); [t] text()'); + 'ms', '[t] "string" (pitch:0.5, rate:0.5); [t] text()'); // Script elements. defineDefaultMathmlRule( - 'msup', '[n] ./*[1]; [t] "super";' + + 'msup', + '[n] ./*[1]; [t] "super";' + '[n] ./*[2] (pitch:0.35); [p] (pause:300)'); defineDefaultMathmlRule( 'msubsup', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + - '[t] "super"; [n] ./*[3] (pitch:0.35); [p] (pause:300)' - ); + '[t] "super"; [n] ./*[3] (pitch:0.35); [p] (pause:300)'); defineDefaultMathmlRule( 'msub', '[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:300)'); defineDefaultMathmlRule( - 'mover', '[n] ./*[2] (pitch:0.35); [p] (pause:200);' + + 'mover', + '[n] ./*[2] (pitch:0.35); [p] (pause:200);' + ' [t] "over"; [n] ./*[1]; [p] (pause:400)'); defineDefaultMathmlRule( 'munder', @@ -160,13 +163,16 @@ defineDefaultMathmlRule( 'msqrt', '[t] "Square root of"; [m] ./* (rate:0.2); [p] (pause:400)'); defineDefaultMathmlRule( - 'mroot', '[t] "root of order"; [n] ./*[2]; [t] "of";' + + 'mroot', + '[t] "root of order"; [n] ./*[2]; [t] "of";' + '[n] ./*[1] (rate:0.2); [p] (pause:400)'); defineDefaultMathmlRule( - 'mfrac', ' [p] (pause:400); [n] ./*[1] (pitch:0.3);' + + 'mfrac', + ' [p] (pause:400); [n] ./*[1] (pitch:0.3);' + ' [t] "divided by"; [n] ./*[2] (pitch:-0.3); [p] (pause:400)'); defineRule( - 'mfrac', 'default.short', '[p] (pause:200); [t] "start frac";' + + 'mfrac', 'default.short', + '[p] (pause:200); [t] "start frac";' + '[n] ./*[1] (pitch:0.3); [t] "over"; ' + '[n] ./*[2] (pitch:-0.3); [p] (pause:400); [t] "end frac"', 'self::mathml:mfrac'); @@ -231,9 +237,7 @@ '[m] ./* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)', 'self::mathml:mtr'); - defineRule( - 'mtd', 'default.default', - '[m] ./*', 'self::mathml:mtd'); + defineRule('mtd', 'default.default', '[m] ./*', 'self::mathml:mtd'); // Mtable superbrief rules. defineRule( @@ -244,80 +248,77 @@ // Mtable short rules. defineRule( - 'mtable', 'default.short', - '[t] "matrix"; [m] ./*', + 'mtable', 'default.short', '[t] "matrix"; [m] ./*', 'self::mathml:mtable'); - defineRule( - 'mtr', 'default.short', - '[m] ./*', 'self::mathml:mtr'); + defineRule('mtr', 'default.short', '[m] ./*', 'self::mathml:mtr'); defineRule( 'mtd', 'default.short', '[t] "Element"; [t] count(./preceding-sibling::mathml:mtd)+1;' + '[t] count(./parent::mathml:mtr/preceding-sibling::mathml:mtr)+1;' + - '[p] (pause:500); [m] ./*', + '[p] (pause:500); [m] ./*', 'self::mathml:mtd'); // Mmultiscripts rules. defineRule( 'mmultiscripts-4', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + - '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + - '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + + '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + + '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts'); defineRule( 'mmultiscripts-3-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + - '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + + '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-2', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + - '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + + '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);', 'self::mathml:mmultiscripts', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-3', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + - '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + - '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);' + + '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + + '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[5]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-3-4', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + - '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + - '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + + '[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);' + + '[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[6]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-2-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);' + + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]'); defineRule( 'mmultiscripts-1-1', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', + '[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]', './mathml:none=./*[5]'); defineRule( 'mmultiscripts-1-2', 'default.default', '[n] ./*[1]; [p] (pause:200);' + - '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);', + '[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);', 'self::mathml:mmultiscripts', './mathml:none=./*[2]', './mathml:none=./*[3]', './mathml:mprescripts=./*[4]', './mathml:none=./*[6]'); @@ -330,30 +331,30 @@ */ cvox.MathmlStoreRules.initMathjaxRules_ = function() { // Initial rule - defineRule('mj-math', 'default.default', - '[n] ./*[1]/*[1]/*[1]', 'self::span[@class="math"]'); + defineRule( + 'mj-math', 'default.default', '[n] ./*[1]/*[1]/*[1]', + 'self::span[@class="math"]'); // Token Elements defineRule( - 'mj-leaf', 'default.default', - '[n] CQFlookupleaf', 'self::span[@class="mi"]'); + 'mj-leaf', 'default.default', '[n] CQFlookupleaf', + 'self::span[@class="mi"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mo"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mn"]'); defineRuleAlias('mj-leaf', 'self::span[@class="mtext"]'); defineRule( - 'mj-mo-ext', 'default.default', - '[n] CQFextender', 'self::span[@class="mo"]', - './*[1]/*[1]/text()', './*[1]/*[2]/text()'); + 'mj-mo-ext', 'default.default', '[n] CQFextender', + 'self::span[@class="mo"]', './*[1]/*[1]/text()', './*[1]/*[2]/text()'); defineRule( - 'mj-texatom', 'default.default', - '[n] ./*[1]', 'self::span[@class="texatom"]'); + 'mj-texatom', 'default.default', '[n] ./*[1]', + 'self::span[@class="texatom"]'); // Script elements. defineRule( 'mj-msubsup', 'default.default', '[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35);' + - '[p] (pause:200); [t] "super"; [n] ./*[1]/*[2]/*[1] (pitch:0.35);' + - '[p] (pause:300)', + '[p] (pause:200); [t] "super"; [n] ./*[1]/*[2]/*[1] (pitch:0.35);' + + '[p] (pause:300)', 'self::span[@class="msubsup"]'); defineRule( 'mj-msub', 'default.default', @@ -369,7 +370,7 @@ 'mj-munderover', 'default.default', '[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "under and";' + '[n] ./*[1]/*[3]/*[1] (pitch:-0.35); [t] "over";' + - '[n] ./*[1]/*[1]/*[1]; [p] (pause:400)', + '[n] ./*[1]/*[1]/*[1]; [p] (pause:400)', 'self::span[@class="munderover"]'); defineRule( 'mj-munder', 'default.default', @@ -388,7 +389,7 @@ 'mj-mfrac', 'default.default', '[p] (pause:250); [n] ./*[1]/*[1]/*[1] (pitch:0.3); [p] (pause:250);' + ' [t] "divided by"; [n] ./*[1]/*[2]/*[1] (pitch:-0.3);' + - '[p] (pause:400)', + '[p] (pause:400)', 'self::span[@class="mfrac"]'); defineRule( 'mj-msqrt', 'default.default', @@ -405,7 +406,7 @@ 'mj-mfenced', 'default.default', '[t] "opening"; [n] ./*[1]; ' + '[m] ./*[position()>1 and position()<last()];' + - ' [t] "closing"; [n] ./*[last()]', + ' [t] "closing"; [n] ./*[last()]', 'self::span[@class="mfenced"]'); // Mtable short rules. @@ -434,11 +435,9 @@ defineRuleAlias('mrow', 'self::span[@class="mrow"]'); // The following rules fix bugs in MathJax's LaTeX translation. - defineRuleAlias( - 'mj-msub', 'self::span[@class="msubsup"]', 'CQFmathmlmsub'); + defineRuleAlias('mj-msub', 'self::span[@class="msubsup"]', 'CQFmathmlmsub'); - defineRuleAlias( - 'mj-msup', 'self::span[@class="msubsup"]', 'CQFmathmlmsup'); + defineRuleAlias('mj-msup', 'self::span[@class="msubsup"]', 'CQFmathmlmsup'); defineRuleAlias( 'mj-munder', 'self::span[@class="munderover"]', 'CQFmathmlmunder'); @@ -460,16 +459,16 @@ '[n] ./*[1]; [t] "square" (pitch:0.35); [p] (pause:300)', 'self::mathml:msup', './*[2][text()=2]'); defineRuleAlias( - 'square', 'self::mathml:msup', - './mathml:mrow=./*[2]', 'count(./*[2]/*)=1', './*[2]/*[1][text()=2]'); + 'square', 'self::mathml:msup', './mathml:mrow=./*[2]', + 'count(./*[2]/*)=1', './*[2]/*[1][text()=2]'); defineRule( 'cube', 'default.default', '[n] ./*[1]; [t] "cube" (pitch:0.35); [p] (pause:300)', 'self::mathml:msup', './*[2][text()=3]'); defineRuleAlias( - 'cube', 'self::mathml:msup', - './mathml:mrow=./*[2]', 'count(./*[2]/*)=1', './*[2]/*[1][text()=3]'); + 'cube', 'self::mathml:msup', './mathml:mrow=./*[2]', 'count(./*[2]/*)=1', + './*[2]/*[1][text()=3]'); defineRule( 'square-sub', 'default.default', @@ -477,8 +476,8 @@ '[p] (pause:300); [t] "square" (pitch:0.35); [p] (pause:400)', 'self::mathml:msubsup', './*[3][text()=2]'); defineRuleAlias( - 'square-sub', 'self::mathml:msubsup', - './mathml:mrow=./*[3]', 'count(./*[3]/*)=1', './*[3]/*[1][text()=2]'); + 'square-sub', 'self::mathml:msubsup', './mathml:mrow=./*[3]', + 'count(./*[3]/*)=1', './*[3]/*[1][text()=2]'); defineRule( 'cube-sub', 'default.default', @@ -486,8 +485,8 @@ '[p] (pause:300); [t] "cube" (pitch:0.35); [p] (pause:400)', 'self::mathml:msubsup', './*[3][text()=3]'); defineRuleAlias( - 'cube-sub', 'self::mathml:msubsup', - './mathml:mrow=./*[3]', 'count(./*[3]/*)=1', './*[3]/*[1][text()=3]'); + 'cube-sub', 'self::mathml:msubsup', './mathml:mrow=./*[3]', + 'count(./*[3]/*)=1', './*[3]/*[1][text()=3]'); // MathJax defineRule( @@ -550,9 +549,7 @@ */ cvox.MathmlStoreRules.initSemanticRules_ = function() { // Initial rule - defineRule( - 'stree', 'default.default', - '[n] ./*[1]', 'self::stree'); + defineRule('stree', 'default.default', '[n] ./*[1]', 'self::stree'); defineRule( 'multrel', 'default.default', @@ -564,7 +561,7 @@ '[t] "equation sequence"; [m] ./children/* ' + '(context:"part",ctxtFunc:CTXFnodeCounter,separator:./text())', 'self::relseq[@role="equality"]', 'count(./children/*)>2', - './children/punct[@role="ellipsis"]');// Make that better! + './children/punct[@role="ellipsis"]'); // Make that better! defineRule( 'multi-equality', 'default.default', @@ -600,21 +597,19 @@ './children/function or ./children/appl'); defineRule( - 'multrel', 'default.default', - '[m] children/* (separator:./text())', + 'multrel', 'default.default', '[m] children/* (separator:./text())', 'self::relseq'); defineRule( 'binary-operation', 'default.default', - '[m] children/* (separator:text());', - 'self::infixop'); + '[m] children/* (separator:text());', 'self::infixop'); defineRule( 'variable-addition', 'default.default', '[t] "sum with variable number of summands";' + '[p] (pause:400); [m] children/* (separator:./text())', 'self::infixop[@role="addition"]', 'count(children/*)>2', - 'children/punct[@role="ellipsis"]');// Make that better! + 'children/punct[@role="ellipsis"]'); // Make that better! defineRule( 'multi-addition', 'default.default', @@ -626,12 +621,11 @@ defineRule( 'prefix', 'default.default', '[t] "prefix"; [n] text(); [t] "of" (pause 150);' + - '[n] children/*[1]', + '[n] children/*[1]', 'self::prefixop'); defineRule( - 'negative', 'default.default', - '[t] "negative"; [n] children/*[1]', + 'negative', 'default.default', '[t] "negative"; [n] children/*[1]', 'self::prefixop', 'self::prefixop[@role="negative"]'); // Postfix Operator @@ -640,13 +634,9 @@ '[n] children/*[1]; [t] "postfix"; [n] text() (pause 300)', 'self::postfixop'); - defineRule( - 'identifier', 'default.default', - '[n] text()', 'self::identifier'); + defineRule('identifier', 'default.default', '[n] text()', 'self::identifier'); - defineRule( - 'number', 'default.default', - '[n] text()', 'self::number'); + defineRule('number', 'default.default', '[n] text()', 'self::number'); defineRule( 'fraction', 'default.default', @@ -657,46 +647,39 @@ defineRule( 'superscript', 'default.default', '[n] children/*[1]; [t] "super"; [n] children/*[2] (pitch:0.35);' + - '[p] (pause:300)', + '[p] (pause:300)', 'self::superscript'); defineRule( 'subscript', 'default.default', '[n] children/*[1]; [t] "sub"; [n] children/*[2] (pitch:-0.35);' + - '[p] (pause:300)', + '[p] (pause:300)', 'self::subscript'); defineRule( 'ellipsis', 'default.default', - '[p] (pause:200); [t] "dot dot dot"; [p] (pause:300)', - 'self::punct', 'self::punct[@role="ellipsis"]'); + '[p] (pause:200); [t] "dot dot dot"; [p] (pause:300)', 'self::punct', + 'self::punct[@role="ellipsis"]'); defineRule( - 'fence-single', 'default.default', - '[n] text()', - 'self::punct', 'self::punct[@role="openfence"]'); - defineRuleAlias('fence-single', 'self::punct', - 'self::punct[@role="closefence"]'); - defineRuleAlias('fence-single', 'self::punct', - 'self::punct[@role="vbar"]'); - defineRuleAlias('fence-single', 'self::punct', - 'self::punct[@role="application"]'); + 'fence-single', 'default.default', '[n] text()', 'self::punct', + 'self::punct[@role="openfence"]'); + defineRuleAlias( + 'fence-single', 'self::punct', 'self::punct[@role="closefence"]'); + defineRuleAlias('fence-single', 'self::punct', 'self::punct[@role="vbar"]'); + defineRuleAlias( + 'fence-single', 'self::punct', 'self::punct[@role="application"]'); // TODO (sorge) Refine punctuations further. defineRule( - 'omit-punct', 'default.default', - '[p] (pause:200);', - 'self::punct'); + 'omit-punct', 'default.default', '[p] (pause:200);', 'self::punct'); - defineRule( - 'omit-empty', 'default.default', - '', - 'self::empty'); + defineRule('omit-empty', 'default.default', '', 'self::empty'); // Fences rules. defineRule( 'fences-open-close', 'default.default', '[p] (pause:100); [t] "open"; [n] children/*[1]; [p] (pause:200);' + - '[t] "close"', + '[t] "close"', 'self::fenced[@role="leftright"]'); defineRule( @@ -707,19 +690,18 @@ defineRule( 'fences-neutral', 'default.default', '[p] (pause:100); [t] "absolute value of"; [n] children/*[1];' + - '[p] (pause:350);', + '[p] (pause:350);', 'self::fenced', 'self::fenced[@role="neutral"]'); defineRule( 'omit-fences', 'default.default', - '[p] (pause:500); [n] children/*[1]; [p] (pause:200);', - 'self::fenced'); + '[p] (pause:500); [n] children/*[1]; [p] (pause:200);', 'self::fenced'); // Matrix rules. defineRule( 'matrix', 'default.default', '[t] "matrix"; [m] children/* ' + - '(ctxtFunc:CTXFnodeCounter,context:"row",pause:100)', + '(ctxtFunc:CTXFnodeCounter,context:"row",pause:100)', 'self::matrix'); defineRule( @@ -728,30 +710,30 @@ 'self::row[@role="matrix"]'); defineRule( - 'matrix-cell', 'default.default', - '[n] children/*[1]', 'self::cell[@role="matrix"]'); + 'matrix-cell', 'default.default', '[n] children/*[1]', + 'self::cell[@role="matrix"]'); // Vector rules. defineRule( 'vector', 'default.default', '[t] "vector"; [m] children/* ' + - '(ctxtFunc:CTXFnodeCounter,context:"element",pause:100)', + '(ctxtFunc:CTXFnodeCounter,context:"element",pause:100)', 'self::vector'); // Cases rules. defineRule( 'cases', 'default.default', '[t] "case statement"; [m] children/* ' + - '(ctxtFunc:CTXFnodeCounter,context:"case",pause:100)', + '(ctxtFunc:CTXFnodeCounter,context:"case",pause:100)', 'self::cases'); defineRule( - 'cases-row', 'default.default', - '[m] children/*', 'self::row[@role="cases"]'); + 'cases-row', 'default.default', '[m] children/*', + 'self::row[@role="cases"]'); defineRule( - 'cases-cell', 'default.default', - '[n] children/*[1]', 'self::cell[@role="cases"]'); + 'cases-cell', 'default.default', '[n] children/*[1]', + 'self::cell[@role="cases"]'); defineRule( 'row', 'default.default', @@ -761,46 +743,42 @@ defineRule( 'cases-end', 'default.default', '[t] "case statement"; ' + - '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"case",pause:100);' + - '[t] "end cases"', + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"case",pause:100);' + + '[t] "end cases"', 'self::cases', 'following-sibling::*'); // Multiline rules. defineRule( 'multiline', 'default.default', '[t] "multiline equation";' + - '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"line",pause:100)', + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"line",pause:100)', 'self::multiline'); - defineRule( - 'line', 'default.default', - '[m] children/*', 'self::line'); + defineRule('line', 'default.default', '[m] children/*', 'self::line'); // Table rules. defineRule( 'table', 'default.default', '[t] "multiline equation";' + - '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"row",pause:200)', + '[m] children/* (ctxtFunc:CTXFnodeCounter,context:"row",pause:200)', 'self::table'); defineRule( - 'table-row', 'default.default', - '[m] children/* (pause:100)', 'self::row[@role="table"]'); + 'table-row', 'default.default', '[m] children/* (pause:100)', + 'self::row[@role="table"]'); - defineRuleAlias( - 'cases-cell', 'self::cell[@role="table"]'); + defineRuleAlias('cases-cell', 'self::cell[@role="table"]'); // Rules for punctuated expressions. defineRule( - 'end-punct', 'default.default', - '[m] children/*; [p] (pause:300)', + 'end-punct', 'default.default', '[m] children/*; [p] (pause:300)', 'self::punctuated', '@role="endpunct"'); defineRule( 'start-punct', 'default.default', - '[n] content/*[1]; [p] (pause:200); [m] children/*', - 'self::punctuated', '@role="startpunct"'); + '[n] content/*[1]; [p] (pause:200); [m] children/*', 'self::punctuated', + '@role="startpunct"'); defineRule( 'integral-punct', 'default.default', @@ -808,56 +786,53 @@ 'self::punctuated', '@role="integral"'); defineRule( - 'punctuated', 'default.default', - '[m] children/* (pause:100)', + 'punctuated', 'default.default', '[m] children/* (pause:100)', 'self::punctuated'); // Function rules - defineRule( - 'function', 'default.default', - '[n] text()', 'self::function'); + defineRule('function', 'default.default', '[n] text()', 'self::function'); defineRule( - 'appl', 'default.default', - '[n] children/*[1]; [n] content/*[1]; [n] children/*[2]', 'self::appl'); + 'appl', 'default.default', + '[n] children/*[1]; [n] content/*[1]; [n] children/*[2]', 'self::appl'); // Limit operator rules defineRule( - 'limboth', 'default.default', - '[n] children/*[1]; [t] "from"; [n] children/*[2]; [t] "to";' + - '[n] children/*[3]', 'self::limboth'); + 'limboth', 'default.default', + '[n] children/*[1]; [t] "from"; [n] children/*[2]; [t] "to";' + + '[n] children/*[3]', + 'self::limboth'); defineRule( - 'sum-only', 'default.default', - '[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];' + - '[p] (pause 250);', - 'self::limboth', 'self::limboth[@role="sum"]'); + 'sum-only', 'default.default', + '[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];' + + '[p] (pause 250);', + 'self::limboth', 'self::limboth[@role="sum"]'); defineRule( - 'limlower', 'default.default', - '[n] children/*[1]; [t] "over"; [n] children/*[2];', 'self::limlower'); + 'limlower', 'default.default', + '[n] children/*[1]; [t] "over"; [n] children/*[2];', 'self::limlower'); defineRule( - 'limupper', 'default.default', - '[n] children/*[1]; [t] "under"; [n] children/*[2];', 'self::limupper'); + 'limupper', 'default.default', + '[n] children/*[1]; [t] "under"; [n] children/*[2];', 'self::limupper'); // Bigoperator rules - defineRule( - 'largeop', 'default.default', - '[n] text()', 'self::largeop'); + defineRule('largeop', 'default.default', '[n] text()', 'self::largeop'); defineRule( - 'bigop', 'default.default', - '[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];' + - '[p] (pause 250);', - 'self::bigop'); + 'bigop', 'default.default', + '[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];' + + '[p] (pause 250);', + 'self::bigop'); // Integral rules defineRule( - 'integral', 'default.default', - '[n] children/*[1]; [p] (pause 100); [n] children/*[2]; [p] (pause 200);' + - '[n] children/*[3] (rate:0.35);', 'self::integral'); + 'integral', 'default.default', + '[n] children/*[1]; [p] (pause 100); [n] children/*[2]; [p] (pause 200);' + + '[n] children/*[3] (rate:0.35);', + 'self::integral'); defineRule( @@ -872,8 +847,8 @@ defineRule( 'text-no-mult', 'default.default', - '[n] children/*[1]; [p] (pause:200); [n] children/*[2]', - 'self::infixop', 'children/text'); + '[n] children/*[1]; [p] (pause:200); [n] children/*[2]', 'self::infixop', + 'children/text'); }; -}); // goog.scope +}); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_util.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_util.js index 7c1d401..3a36b92 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_util.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/mathml_store_util.js
@@ -124,9 +124,9 @@ if (separators.match(/^\s+$/)) { return null; } else { - var sepList = separators.replace(/\s/g, '') - .split('') - .filter(function(x) {return x;}); + var sepList = separators.replace(/\s/g, '').split('').filter(function(x) { + return x; + }); } } else { // When no separator is given MathML uses comma as default.
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule.js index cf07c6b..079f9ed 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule.js
@@ -54,8 +54,7 @@ cstrStrings.push(this.dynamicCstr[key]); } return this.name + ' | ' + cstrStrings.join('.') + ' | ' + - this.precondition.toString() + ' ==> ' + - this.action.toString(); + this.precondition.toString() + ' ==> ' + this.action.toString(); }; @@ -78,11 +77,16 @@ */ cvox.SpeechRule.Type.fromString = function(str) { switch (str) { - case '[n]': return cvox.SpeechRule.Type.NODE; - case '[m]': return cvox.SpeechRule.Type.MULTI; - case '[t]': return cvox.SpeechRule.Type.TEXT; - case '[p]': return cvox.SpeechRule.Type.PERSONALITY; - default: throw 'Parse error: ' + str; + case '[n]': + return cvox.SpeechRule.Type.NODE; + case '[m]': + return cvox.SpeechRule.Type.MULTI; + case '[t]': + return cvox.SpeechRule.Type.TEXT; + case '[p]': + return cvox.SpeechRule.Type.PERSONALITY; + default: + throw 'Parse error: ' + str; } }; @@ -94,11 +98,16 @@ */ cvox.SpeechRule.Type.toString = function(speechType) { switch (speechType) { - case cvox.SpeechRule.Type.NODE: return '[n]'; - case cvox.SpeechRule.Type.MULTI: return '[m]'; - case cvox.SpeechRule.Type.TEXT: return '[t]'; - case cvox.SpeechRule.Type.PERSONALITY: return '[p]'; - default: throw 'Unknown type error: ' + speechType; + case cvox.SpeechRule.Type.NODE: + return '[n]'; + case cvox.SpeechRule.Type.MULTI: + return '[m]'; + case cvox.SpeechRule.Type.TEXT: + return '[t]'; + case cvox.SpeechRule.Type.PERSONALITY: + return '[p]'; + default: + throw 'Unknown type error: ' + speechType; } }; @@ -163,7 +172,7 @@ } output.content = rest.substring(0, bracket).trim(); rest = rest.slice(bracket).trimLeft(); - break; + break; } output = new cvox.SpeechRule.Component(output); if (rest) { @@ -251,8 +260,12 @@ */ cvox.SpeechRule.Action.fromString = function(input) { var comps = cvox.SpeechRule.splitString_(input, ';') - .filter(function(x) {return x.match(/\S/);}) - .map(function(x) {return x.trim();}); + .filter(function(x) { + return x.match(/\S/); + }) + .map(function(x) { + return x.trim(); + }); var newComps = []; for (var i = 0; i < comps.length; i++) { var comp = cvox.SpeechRule.Component.fromString(comps[i]); @@ -260,7 +273,7 @@ newComps.push(comp); } } -return new cvox.SpeechRule.Action(newComps); + return new cvox.SpeechRule.Action(newComps); }; @@ -268,7 +281,9 @@ * @override */ cvox.SpeechRule.Action.prototype.toString = function() { - var comps = this.components.map(function(c) { return c.toString(); }); + var comps = this.components.map(function(c) { + return c.toString(); + }); return comps.join('; '); }; @@ -323,8 +338,7 @@ strList.push(prefix + str); prefix = ''; str = ''; - } else if ( - (str.substring(0, sepPos).match(/"/g) || []).length % 2 == 0) { + } else if ((str.substring(0, sepPos).match(/"/g) || []).length % 2 == 0) { strList.push(prefix + str.substring(0, sepPos)); prefix = ''; str = str.substring(sepPos + 1); @@ -352,8 +366,7 @@ * attributes later. * @enum {string} */ -cvox.SpeechRule.DynamicCstrAttrib = -{ +cvox.SpeechRule.DynamicCstrAttrib = { STYLE: 'style' };
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_engine.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_engine.js index d7be382..a361cd70 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_engine.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_engine.js
@@ -55,8 +55,7 @@ } catch (err) { if (err.name == 'StoreError') { console.log('Store Error:', err.message); - } - else { + } else { throw err; } } @@ -146,8 +145,7 @@ selected = this.activeStore_.applySelector(node, content); if (selected.length > 0) { navs = this.evaluateNodeList_( - selected, - component['sepFunc'], + selected, component['sepFunc'], this.constructString(node, component['separator']), component['ctxtFunc'], this.constructString(node, component['context'])); @@ -166,9 +164,8 @@ // Adding overall context if it exists. if (navs[0] && component['context'] && component.type != cvox.SpeechRule.Type.MULTI) { - navs[0]['context'] = - this.constructString(node, component['context']) + - (navs[0]['context'] || ''); + navs[0]['context'] = this.constructString(node, component['context']) + + (navs[0]['context'] || ''); } // Adding personality to the nav descriptions. result = result.concat(this.addPersonality_(navs, component)); @@ -199,9 +196,13 @@ var sep = separator || ''; var cont = context || ''; var cFunc = this.activeStore_.contextFunctions.lookup(ctxtFunc); - var ctxtClosure = cFunc ? cFunc(nodes, cont) : function() {return cont;}; + var ctxtClosure = cFunc ? cFunc(nodes, cont) : function() { + return cont; + }; var sFunc = this.activeStore_.contextFunctions.lookup(sepFunc); - var sepClosure = sFunc ? sFunc(nodes, sep) : function() {return sep;}; + var sepClosure = sFunc ? sFunc(nodes, sep) : function() { + return sep; + }; var result = []; for (var i = 0, node; node = nodes[i]; i++) { var navs = this.evaluateTree_(node); @@ -228,11 +229,12 @@ * pause: string}} * @const */ -cvox.SpeechRuleEngine.propMap = {'pitch': cvox.AbstractTts.RELATIVE_PITCH, - 'rate': cvox.AbstractTts.RELATIVE_RATE, - 'volume': cvox.AbstractTts.RELATIVE_VOLUME, - 'pause': cvox.AbstractTts.PAUSE - }; +cvox.SpeechRuleEngine.propMap = { + 'pitch': cvox.AbstractTts.RELATIVE_PITCH, + 'rate': cvox.AbstractTts.RELATIVE_RATE, + 'volume': cvox.AbstractTts.RELATIVE_VOLUME, + 'pause': cvox.AbstractTts.PAUSE +}; /** @@ -318,8 +320,8 @@ cvox.SpeechRuleEngine.outputDebug = function(output) { if (cvox.SpeechRuleEngine.debugMode) { var outputList = Array.prototype.slice.call(arguments, 0); - console.log.apply(console, - ['Speech Rule Engine Debugger:'].concat(outputList)); + console.log.apply( + console, ['Speech Rule Engine Debugger:'].concat(outputList)); } }; @@ -330,9 +332,14 @@ * engine. */ cvox.SpeechRuleEngine.prototype.toString = function() { - var allRules = this.activeStore_.findAllRules(function(x) {return true;}); - return allRules.map(function(rule) {return rule.toString();}). - join('\n'); + var allRules = this.activeStore_.findAllRules(function(x) { + return true; + }); + return allRules + .map(function(rule) { + return rule.toString(); + }) + .join('\n'); }; @@ -347,10 +354,10 @@ var prec = rule.precondition; cvox.SpeechRuleEngine.outputDebug( prec.query, store.applyQuery(node, prec.query)); - prec.constraints.forEach( - function(cstr) { - cvox.SpeechRuleEngine.outputDebug( - cstr, store.applyConstraint(node, cstr));}); + prec.constraints.forEach(function(cstr) { + cvox.SpeechRuleEngine.outputDebug( + cstr, store.applyConstraint(node, cstr)); + }); } }; @@ -362,8 +369,9 @@ */ cvox.SpeechRuleEngine.debugNamedSpeechRule = function(name, node) { var store = cvox.SpeechRuleEngine.getInstance().activeStore_; - var allRules = store.findAllRules( - function(rule) {return rule.name == name;}); + var allRules = store.findAllRules(function(rule) { + return rule.name == name; + }); for (var i = 0, rule; rule = allRules[i]; i++) { cvox.SpeechRuleEngine.outputDebug('Rule', name, 'number', i); cvox.SpeechRuleEngine.debugSpeechRule(rule, node);
diff --git a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_functions.js b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_functions.js index 83f5ed90..95af67e 100644 --- a/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_functions.js +++ b/chrome/browser/resources/chromeos/chromevox/speech_rules/speech_rule_functions.js
@@ -17,7 +17,7 @@ /** * @constructor */ -cvox.SpeechRuleFunctions = function() { }; +cvox.SpeechRuleFunctions = function() {}; /** @@ -70,11 +70,11 @@ */ cvox.SpeechRuleFunctions.CustomQueries = function() { var store = - /** @type {Object<cvox.SpeechRuleFunctions.CustomQuery>} */ ({}); + /** @type {Object<cvox.SpeechRuleFunctions.CustomQuery>} */ ({}); goog.base(this, 'CQF', store); }; -goog.inherits(cvox.SpeechRuleFunctions.CustomQueries, - cvox.SpeechRuleFunctions.Store_); +goog.inherits( + cvox.SpeechRuleFunctions.CustomQueries, cvox.SpeechRuleFunctions.Store_); /** @@ -90,11 +90,11 @@ */ cvox.SpeechRuleFunctions.CustomStrings = function() { var store = - /** @type {Object<cvox.SpeechRuleFunctions.CustomString>} */ ({}); + /** @type {Object<cvox.SpeechRuleFunctions.CustomString>} */ ({}); goog.base(this, 'CSF', store); }; -goog.inherits(cvox.SpeechRuleFunctions.CustomStrings, - cvox.SpeechRuleFunctions.Store_); +goog.inherits( + cvox.SpeechRuleFunctions.CustomStrings, cvox.SpeechRuleFunctions.Store_); /** @@ -110,12 +110,12 @@ */ cvox.SpeechRuleFunctions.ContextFunctions = function() { var store = - /** @type {Object<cvox.SpeechRuleFunctions.ContextFunction>} */ - ({}); + /** @type {Object<cvox.SpeechRuleFunctions.ContextFunction>} */ + ({}); goog.base(this, 'CTXF', store); }; -goog.inherits(cvox.SpeechRuleFunctions.ContextFunctions, - cvox.SpeechRuleFunctions.Store_); +goog.inherits( + cvox.SpeechRuleFunctions.ContextFunctions, cvox.SpeechRuleFunctions.Store_); /** @@ -124,14 +124,13 @@ * @return {!boolean} True if the name is valid. * @private */ -cvox.SpeechRuleFunctions.Store_.prototype. - checkCustomFunctionSyntax_ = function(name) { - var reg = new RegExp('^' + this.prefix_); - if (!name.match(reg)) { - console.log( - 'FunctionError: Invalid function name. Expected prefix' + - this.prefix_); - return false; - } - return true; - }; +cvox.SpeechRuleFunctions.Store_.prototype.checkCustomFunctionSyntax_ = function( + name) { + var reg = new RegExp('^' + this.prefix_); + if (!name.match(reg)) { + console.log( + 'FunctionError: Invalid function name. Expected prefix' + this.prefix_); + return false; + } + return true; +};
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/assert_additions.js b/chrome/browser/resources/chromeos/chromevox/testing/assert_additions.js index 6838dfa..9e7a597 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/assert_additions.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/assert_additions.js
@@ -19,8 +19,9 @@ */ function assertNotNullNorUndefined(obj, opt_message) { if (obj === undefined || obj === null) { - throw new Error('Can\'t be null or undefined: ' + (opt_message || '') + - '\n' + 'Actual: ' + obj); + throw new Error( + 'Can\'t be null or undefined: ' + (opt_message || '') + '\n' + + 'Actual: ' + obj); } } @@ -36,8 +37,8 @@ fn(); } catch (e) { if (error && e.name != error) { - throw new Error('Expected to throw ' + error + ' but threw ' + e.name + - ' - ' + msg); + throw new Error( + 'Expected to throw ' + error + ' but threw ' + e.name + ' - ' + msg); } return; } @@ -61,8 +62,9 @@ } } if (!same) { - throw new Error('Expected ' + JSON.stringify(array1) + - ', got ' + JSON.stringify(array2)); + throw new Error( + 'Expected ' + JSON.stringify(array1) + ', got ' + + JSON.stringify(array2)); } } @@ -74,8 +76,9 @@ */ function assertEqualsJSON(expected, actual, opt_message) { if (JSON.stringify(actual) !== JSON.stringify(expected)) { - throw new Error((opt_message ? opt_message + '\n' : '') + - 'Expected ' + JSON.stringify(expected) + '\n' + + throw new Error( + (opt_message ? opt_message + '\n' : '') + 'Expected ' + + JSON.stringify(expected) + '\n' + 'Got ' + JSON.stringify(actual)); } }
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js index 0cdf1cd..baddffbd 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js
@@ -2,9 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -GEN_INCLUDE([ - 'common.js', - 'callback_helper.js']); +GEN_INCLUDE(['common.js', 'callback_helper.js']); /** * Base test fixture for ChromeVox end to end tests. @@ -34,25 +32,25 @@ /** @override */ testGenCppIncludes: function() { - GEN_BLOCK(function() {/*! + GEN_BLOCK(function() { /*! #include "ash/accessibility_delegate.h" #include "base/bind.h" #include "base/callback.h" #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/common/extensions/extension_constants.h" - */}); + */ }); }, /** @override */ testGenPreamble: function() { - GEN_BLOCK(function() {/*! + GEN_BLOCK(function() { /*! base::Closure load_cb = base::Bind(&chromeos::AccessibilityManager::EnableSpokenFeedback, base::Unretained(chromeos::AccessibilityManager::Get()), true, ash::A11Y_NOTIFICATION_NONE); WaitForExtension(extension_misc::kChromeVoxExtensionId, load_cb); - */}); + */ }); }, /** @@ -78,10 +76,7 @@ */ runWithTab: function(doc, opt_callback) { var url = TestUtils.createUrlForDoc(doc); - var createParams = { - active: true, - url: url - }; + var createParams = {active: true, url: url}; chrome.tabs.create(createParams, function(tab) { if (opt_callback) opt_callback(tab.url); @@ -94,11 +89,13 @@ * @param {string} elementQueryString */ incrementSelectedIndex: function(tabId, elementQueryString) { - var code = TestUtils.extractHtmlFromCommentEncodedString(function() {/*! + var code = TestUtils.extractHtmlFromCommentEncodedString( + function() { /*! var target = document.body.querySelector('$0'); target.focus(); target.selectedIndex++; - */}, [elementQueryString]); + */ }, + [elementQueryString]); chrome.tabs.executeScript(tabId, {code: code}); },
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js index bd1684e..3b46331 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js
@@ -66,10 +66,7 @@ }; r.addEventListener('focus', listener, true); r.addEventListener('loadComplete', listener, true); - var createParams = { - active: true, - url: url - }; + var createParams = {active: true, url: url}; chrome.tabs.create(createParams); }.bind(this)); },
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js index 4c99e15..2f5b582e 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js
@@ -3,8 +3,7 @@ // found in the LICENSE file. GEN_INCLUDE(['assert_additions.js']); -GEN_INCLUDE(['common.js', - 'callback_helper.js']); +GEN_INCLUDE(['common.js', 'callback_helper.js']); /** * Base test fixture for ChromeVox unit tests. @@ -123,7 +122,7 @@ cvox.ChromeVoxEventWatcher.addReadyCallback(this.newCallback(function() { func.apply(this, calmArguments); })); - return this; // for chaining. + return this; // for chaining. }, /** @@ -132,10 +131,10 @@ * @return {ChromeVoxUnitTestBase} this. */ assertSpoken: function(expectedText) { - assertEquals(expectedText, - cvox.ChromeVoxTester.testTts().getUtterancesAsString()); + assertEquals( + expectedText, cvox.ChromeVoxTester.testTts().getUtterancesAsString()); cvox.ChromeVoxTester.clearUtterances(); - return this; // for chaining. + return this; // for chaining. }, /** @@ -154,11 +153,11 @@ for (var i = 0; i < expectedList.length; i++) { var text = expectedList[i][0]; var queueMode = expectedList[i][1]; - this.assertSingleUtterance_(text, queueMode, - ulist[i].text, ulist[i].queueMode); + this.assertSingleUtterance_( + text, queueMode, ulist[i].text, ulist[i].queueMode); } cvox.ChromeVoxTester.clearUtterances(); - return this; // for chaining. + return this; // for chaining. }, assertSingleUtterance_: function( @@ -174,7 +173,7 @@ */ setFocus: function(id) { $(id).focus(); - return this; // for chaining. + return this; // for chaining. }, /** @@ -184,7 +183,7 @@ */ userCommand: function(command) { cvox.ChromeVoxUserCommands.commands[command](); - return this; // for chaining. + return this; // for chaining. }, /**
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/common.js b/chrome/browser/resources/chromeos/chromevox/testing/common.js index 9c0fc0b..1a654c9 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/common.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/common.js
@@ -32,8 +32,8 @@ * $0, ... within the code block. * @return {string} The html text. */ -TestUtils.extractHtmlFromCommentEncodedString = - function(commentEncodedHtml, opt_args) { +TestUtils.extractHtmlFromCommentEncodedString = function( + commentEncodedHtml, opt_args) { var stringified = commentEncodedHtml.toString(); if (opt_args) { for (var i = 0; i < opt_args.length; i++) @@ -43,16 +43,16 @@ }; - /** - * Creates a data url for a document. - * @param {function() : void} doc Snippet wrapped inside of a function. - * @return {string} - */ +/** + * Creates a data url for a document. + * @param {function() : void} doc Snippet wrapped inside of a function. + * @return {string} + */ TestUtils.createUrlForDoc = function(doc) { var docString = TestUtils.extractHtmlFromCommentEncodedString(doc); - return TestUtils.collapseWhitespace('data:text/html,<!doctype html>' + - docString.replace(/[\n\r]/g, '') - .trim()); + return TestUtils.collapseWhitespace( + 'data:text/html,<!doctype html>' + + docString.replace(/[\n\r]/g, '').trim()); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/mock_feedback.js b/chrome/browser/resources/chromeos/chromevox/testing/mock_feedback.js index ec90c10..8e4ce8e7 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/mock_feedback.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/mock_feedback.js
@@ -153,7 +153,9 @@ return !!MockFeedback.matchAndConsume_( text, {}, this.pendingUtterances_); }.bind(this), - toString: function() { return 'Speak \'' + text + '\''; } + toString: function() { + return 'Speak \'' + text + '\''; + } }); }.bind(this)); return this; @@ -172,7 +174,7 @@ perform: function() { return !!MockFeedback.matchAndConsume_( text, {queueMode: queueMode}, this.pendingUtterances_); - }.bind(this), + }.bind(this), toString: function() { return 'Speak \'' + text + '\' with mode ' + queueMode; } @@ -233,7 +235,9 @@ } return true; }.bind(this), - toString: function() { return 'Do not speak \'' + text + '\''; } + toString: function() { + return 'Do not speak \'' + text + '\''; + } }); }.bind(this)); return this; @@ -251,8 +255,8 @@ var props = opt_props || {}; this.pendingActions_.push({ perform: function() { - var match = MockFeedback.matchAndConsume_( - text, props, this.pendingBraille_); + var match = + MockFeedback.matchAndConsume_(text, props, this.pendingBraille_); if (match) this.lastMatchedBraille_ = match; return !!match; @@ -273,8 +277,8 @@ assertFalse(this.replaying_); this.pendingActions_.push({ perform: function() { - var match = MockFeedback.matchAndConsume_( - earconName, {}, this.pendingEarcons_); + var match = + MockFeedback.matchAndConsume_(earconName, {}, this.pendingEarcons_); return !!match; }.bind(this), toString: function() { @@ -347,9 +351,7 @@ }; } this.pendingUtterances_.push( - {text: textString, - queueMode: queueMode, - callback: callback}); + {text: textString, queueMode: queueMode, callback: callback}); this.process_(); }, @@ -392,8 +394,8 @@ // If there are pending actions and no matching feedback for a few // seconds, log the pending state to ease debugging. if (!this.logTimeoutId_) { - this.logTimeoutId_ = window.setTimeout( - this.logPendingState_.bind(this), 2000); + this.logTimeoutId_ = + window.setTimeout(this.logPendingState_.bind(this), 2000); } } } finally { @@ -407,15 +409,18 @@ console.log('Still waiting for ' + this.pendingActions_[0].toString()); function logPending(desc, list) { if (list.length > 0) - console.log('Pending ' + desc + ':\n ' + + console.log( + 'Pending ' + desc + ':\n ' + list.map(function(i) { - var ret = '\'' + i.text + '\''; - if ('startIndex' in i) - ret += ' startIndex=' + i.startIndex; - if ('endIndex' in i) - ret += ' endIndex=' + i.endIndex; - return ret; - }).join('\n ') + '\n '); + var ret = '\'' + i.text + '\''; + if ('startIndex' in i) + ret += ' startIndex=' + i.startIndex; + if ('endIndex' in i) + ret += ' endIndex=' + i.endIndex; + return ret; + }) + .join('\n ') + + '\n '); } logPending('speech utterances', this.pendingUtterances_); logPending('braille', this.pendingBraille_);
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/snippets.js b/chrome/browser/resources/chromeos/chromevox/testing/snippets.js index 63b38ada..4e0de62 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/snippets.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/snippets.js
@@ -6,16 +6,18 @@ * @fileoverview Contains html snippets shared by multiple tests. */ -function toolbarDoc() {/*! - <div tabindex=0 role="toolbar"> - <button>Back</button> - <button>Forward</button> - </div> -*/} +function toolbarDoc() { /*! + <div tabindex=0 role="toolbar"> + <button>Back</button> + <button>Forward</button> + </div> + */ +} -function headingDoc() {/*! - <h1>World</h1> - <p>Canada</p> - <h2>United States</h2> - <a href="whitehouse.gov">White House</a> -*/} +function headingDoc() { /*! + <h1>World</h1> + <p>Canada</p> + <h2>United States</h2> + <a href="whitehouse.gov">White House</a> + */ +}
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/test_msgs.js b/chrome/browser/resources/chromeos/chromevox/testing/test_msgs.js index beec2a6..1e1d573 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/test_msgs.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/test_msgs.js
@@ -46,17 +46,16 @@ } var messageString = TestMsgs.Untranslated[messageId.toUpperCase()]; if (messageString === undefined) { - var messageObj = cvox.TestMessages[( - 'chromevox_' + messageId).toUpperCase()]; + var messageObj = + cvox.TestMessages[('chromevox_' + messageId).toUpperCase()]; if (messageObj === undefined) throw Error('missing-msg: ' + messageId); var messageString = messageObj.message; var placeholders = messageObj.placeholders; if (placeholders) { for (name in placeholders) { - messageString = messageString.replace( - '$' + name + '$', - placeholders[name].content); + messageString = + messageString.replace('$' + name + '$', placeholders[name].content); } } }
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/tester.js b/chrome/browser/resources/chromeos/chromevox/testing/tester.js index bab5c6a..f002f083 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/tester.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/tester.js
@@ -38,7 +38,7 @@ // TODO(deboer): Factor this out as 'TestEarcons' cvox.ChromeVox.earcons = new cvox.AbstractEarcons(); - cvox.ChromeVox.earcons.playEarcon = function(earcon) { }; + cvox.ChromeVox.earcons.playEarcon = function(earcon) {}; cvox.ChromeVox.braille = new cvox.BrailleInterface(); cvox.ChromeVox.braille.write = function(params) {}; @@ -108,15 +108,14 @@ cvox.ChromeVoxTester.setStrategy = function(strategy) { cvox.ChromeVox.navigationManager.ensureNotSubnavigating(); cvox.ChromeVox.navigationManager.setGranularity( - cvox.ChromeVoxTester.STRATEGY_MAP[strategy]); + cvox.ChromeVoxTester.STRATEGY_MAP[strategy]); }; /** * Starts reading the page from the current node. */ cvox.ChromeVoxTester.readFromHere = function() { - cvox.ChromeVox.navigationManager.startReading( - cvox.QueueMode.FLUSH); + cvox.ChromeVox.navigationManager.startReading(cvox.QueueMode.FLUSH); }; /** @@ -124,8 +123,8 @@ * @param {Node} node The node to sync to. */ cvox.ChromeVoxTester.syncToNode = function(node) { - cvox.ChromeVox.navigationManager - .updateSel(cvox.CursorSelection.fromNode(node)); + cvox.ChromeVox.navigationManager.updateSel( + cvox.CursorSelection.fromNode(node)); cvox.ChromeVox.navigationManager.sync(); };
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_node_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_node_walker.js index f360aefc..af867d6 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_node_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_node_walker.js
@@ -43,8 +43,8 @@ return null; } do { - node = cvox.DomUtil.directedNextLeafLikeNode(node, r, - goog.bind(this.stopNodeDescent, this)); + node = cvox.DomUtil.directedNextLeafLikeNode( + node, r, goog.bind(this.stopNodeDescent, this)); if (!node) { return null; } @@ -85,7 +85,7 @@ var node = sel.start.node; while (node != document.body && node.parentNode && - this.stopNodeDescent(node.parentNode)) { + this.stopNodeDescent(node.parentNode)) { node = node.parentNode; } @@ -96,7 +96,7 @@ var n = cvox.CursorSelection.fromNode(node); if (!cvox.DomUtil.hasContent(node)) { n = this.next(/** @type {!cvox.CursorSelection} */ - (cvox.CursorSelection.fromNode(node)).setReversed(r)); + (cvox.CursorSelection.fromNode(node)).setReversed(r)); } if (n) { return n.setReversed(r);
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_selection_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_selection_walker.js index 00ea3cc..050b203 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_selection_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_selection_walker.js
@@ -28,7 +28,7 @@ cvox.AbstractWalker.call(this); this.objWalker_ = new cvox.BareObjectWalker(); this.tc_ = cvox.TraverseContent.getInstance(); - this.grain /** @protected */ = ''; // child must override + this.grain /** @protected */ = ''; // child must override }; goog.inherits(cvox.AbstractSelectionWalker, cvox.AbstractWalker); @@ -38,8 +38,8 @@ cvox.AbstractSelectionWalker.prototype.next = function(sel) { var r = sel.isReversed(); this.tc_.syncToCursorSelection(sel.clone().setReversed(false)); - var ret = r ? this.tc_.prevElement(this.grain) : - this.tc_.nextElement(this.grain); + var ret = + r ? this.tc_.prevElement(this.grain) : this.tc_.nextElement(this.grain); if (ret == null) { // Unfortunately, we can't trust TraverseContent; fall back to ObjectWalker. return this.objWalker_.next(sel); @@ -54,7 +54,7 @@ // object walker. if (objSel && (retSel.end.node.constructor.name != 'Text' || - objSel.end.node.constructor.name != 'Text') && + objSel.end.node.constructor.name != 'Text') && !cvox.DomUtil.isDescendantOfNode(retSel.end.node, sel.end.node) && !cvox.DomUtil.isDescendantOfNode(retSel.end.node, objSel.end.node)) { return objSel; @@ -74,15 +74,14 @@ // Find the deepest visible node; written specifically here because we want // to move across siblings if necessary and take the deepest node which can // be BODY. - while (node && - cvox.DomUtil.directedFirstChild(node, r) && - !cvox.TraverseUtil.treatAsLeafNode(node)) { + while (node && cvox.DomUtil.directedFirstChild(node, r) && + !cvox.TraverseUtil.treatAsLeafNode(node)) { var child = cvox.DomUtil.directedFirstChild(node, r); // Find the first visible child. while (child) { - if (cvox.DomUtil.isVisible(child, - {checkAncestors: false, checkDescendants: false})) { + if (cvox.DomUtil.isVisible( + child, {checkAncestors: false, checkDescendants: false})) { node = child; break; } else { @@ -123,7 +122,7 @@ if (objSel && (newSel.end.node.constructor.name != 'Text' || - objSel.end.node.constructor.name != 'Text') && + objSel.end.node.constructor.name != 'Text') && !cvox.DomUtil.isDescendantOfNode(newSel.end.node, sel.end.node) && !cvox.DomUtil.isDescendantOfNode(newSel.end.node, objSel.end.node)) { return objSel; @@ -136,8 +135,7 @@ */ cvox.AbstractSelectionWalker.prototype.getDescription = function(prevSel, sel) { var description = cvox.DescriptionUtil.getDescriptionFromAncestors( - cvox.DomUtil.getUniqueAncestors(prevSel.end.node, sel.start.node), - true, + cvox.DomUtil.getUniqueAncestors(prevSel.end.node, sel.start.node), true, cvox.ChromeVox.verbosity); description.text = sel.getText() || description.text; return [description];
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_shifter.js b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_shifter.js index 3da5099..0d72269 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_shifter.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_shifter.js
@@ -138,11 +138,11 @@ /** * Delegates to current walker. - * @param {string} name Action name. + * @param {string} name Action name. * @return {boolean} True if this shifter contains action. */ cvox.AbstractShifter.prototype.hasAction = function(name) { -return this.currentWalker_.hasAction(name); + return this.currentWalker_.hasAction(name); };
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_walker.js index c704cd9f..bf77fd9 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/abstract_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/abstract_walker.js
@@ -46,8 +46,7 @@ /** * @constructor */ -cvox.AbstractWalker = function() { -}; +cvox.AbstractWalker = function() {}; /** @@ -86,8 +85,8 @@ cvox.AbstractWalker.prototype.begin = function(kwargs) { kwargs = kwargs || {reversed: false}; - return /** @type {!cvox.CursorSelection} */ (this.sync( - cvox.CursorSelection.fromBody().setReversed(kwargs.reversed))); + return /** @type {!cvox.CursorSelection} */ ( + this.sync(cvox.CursorSelection.fromBody().setReversed(kwargs.reversed))); };
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/layout_line_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/layout_line_walker.js index 351f167..bc9315f 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/layout_line_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/layout_line_walker.js
@@ -153,14 +153,12 @@ // Some ranges from the browser give us 0-sized rects (such as in the case of // select's). Detect these cases and use a more reliable method (take the // bounding rect of the actual element rather than the range). - if (lRect.width == 0 && - lRect.height == 0 && + if (lRect.width == 0 && lRect.height == 0 && lSel.end.node.nodeType == Node.ELEMENT_NODE) { lRect = lSel.end.node.getBoundingClientRect(); } - if (rRect.width == 0 && - rRect.height == 0 && + if (rRect.width == 0 && rRect.height == 0 && rSel.start.node.nodeType == Node.ELEMENT_NODE) { rRect = rSel.start.node.getBoundingClientRect(); }
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/math_shifter.js b/chrome/browser/resources/chromeos/chromevox/walkers/math_shifter.js index 6488bf7..0e1a2a5 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/math_shifter.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/math_shifter.js
@@ -48,7 +48,7 @@ */ this.bumped_ = false; -cvox.TraverseMath.getInstance().initialize(sel.start.node); + cvox.TraverseMath.getInstance().initialize(sel.start.node); }; goog.inherits(cvox.MathShifter, cvox.AbstractShifter); @@ -110,7 +110,7 @@ */ cvox.MathShifter.prototype.getGranularityMsg = function() { return this.direction_ ? 'up to level ' + this.level_ : - 'down to level ' + this.level_; + 'down to level ' + this.level_; }; @@ -141,7 +141,7 @@ */ cvox.MathShifter.create = function(sel) { if (cvox.DomPredicates.mathPredicate( - cvox.DomUtil.getAncestors(sel.start.node))) { + cvox.DomUtil.getAncestors(sel.start.node))) { var mathNode = cvox.DomUtil.getContainingMath(sel.end.node); cvox.TraverseMath.getInstance().initialize(mathNode); cvox.SpeechRuleEngine.getInstance().parameterize(
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/object_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/object_walker.js index 63b328a9..337ee1b 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/object_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/object_walker.js
@@ -35,10 +35,7 @@ */ cvox.AbstractNodeWalker.prototype.getDescription = function(prevSel, sel) { return cvox.DescriptionUtil.getDescriptionFromNavigation( - prevSel.end.node, - sel.start.node, - true, - cvox.ChromeVox.verbosity); + prevSel.end.node, sel.start.node, true, cvox.ChromeVox.verbosity); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/structural_line_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/structural_line_walker.js index a1f565b3..d87dcee 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/structural_line_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/structural_line_walker.js
@@ -37,8 +37,9 @@ */ cvox.StructuralLineWalker.prototype.getDescription = function(prevSel, sel) { var desc = goog.base(this, 'getDescription', prevSel, sel); - desc[0].text = cvox.DomUtil.getPrefixText( - sel.absStart().node, sel.absStart().index) + desc[0].text; + desc[0].text = + cvox.DomUtil.getPrefixText(sel.absStart().node, sel.absStart().index) + + desc[0].text; return desc; };
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/table_shifter.js b/chrome/browser/resources/chromeos/chromevox/walkers/table_shifter.js index 98409b7..8ba377f 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/table_shifter.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/table_shifter.js
@@ -53,7 +53,7 @@ cvox.TableShifter.prototype.sync = function(sel) { if (sel.start.node.tagName == 'TABLE') { return sel.isReversed() ? this.currentWalker_.goToLastCell(sel) : - this.currentWalker_.goToFirstCell(sel); + this.currentWalker_.goToFirstCell(sel); } return this.currentWalker_.sync(sel); }; @@ -93,10 +93,8 @@ })); } if (this.currentWalker_.tt.isSpanned()) { - descs.push(new cvox.NavDescription({ - text: '', - annotation: Msgs.getMsg('spanned') - })); + descs.push(new cvox.NavDescription( + {text: '', annotation: Msgs.getMsg('spanned')})); } this.begin_ = false; }
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/table_walker.js b/chrome/browser/resources/chromeos/chromevox/walkers/table_walker.js index 8e6a0e2..ed06a167 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/table_walker.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/table_walker.js
@@ -49,7 +49,7 @@ */ cvox.TableWalker.prototype.sync = function(sel) { return this.goTo_(sel, goog.bind(function(position) { - return this.tt.goToCell(position); + return this.tt.goToCell(position); }, this)); }; @@ -68,9 +68,8 @@ this.tt.goToCell(position); var descs = cvox.DescriptionUtil.getCollectionDescription(prevSel, sel); if (descs.length == 0) { - descs.push(new cvox.NavDescription({ - annotation: Msgs.getMsg('empty_cell') - })); + descs.push( + new cvox.NavDescription({annotation: Msgs.getMsg('empty_cell')})); } return descs; }; @@ -179,8 +178,8 @@ */ cvox.TableWalker.prototype.nextRow = function(sel) { return this.goTo_(sel, goog.bind(function(position) { - return this.tt.goToCell([position[0] + (sel.isReversed() ? -1 : 1), - position[1]]); + return this.tt.goToCell( + [position[0] + (sel.isReversed() ? -1 : 1), position[1]]); }, this)); }; @@ -193,8 +192,8 @@ */ cvox.TableWalker.prototype.nextCol = function(sel) { return this.goTo_(sel, goog.bind(function(position) { - return this.tt.goToCell([position[0], - position[1] + (sel.isReversed() ? -1 : 1)]); + return this.tt.goToCell( + [position[0], position[1] + (sel.isReversed() ? -1 : 1)]); }, this)); }; @@ -204,9 +203,9 @@ * @export */ cvox.TableWalker.prototype.announceHeaders = function(sel) { - cvox.ChromeVox.tts.speak(this.getHeaderText_(sel), - cvox.QueueMode.FLUSH, - cvox.AbstractTts.PERSONALITY_ANNOTATION); + cvox.ChromeVox.tts.speak( + this.getHeaderText_(sel), cvox.QueueMode.FLUSH, + cvox.AbstractTts.PERSONALITY_ANNOTATION); return sel; }; @@ -217,9 +216,7 @@ */ cvox.TableWalker.prototype.speakTableLocation = function(sel) { cvox.ChromeVox.navigationManager.speakDescriptionArray( - this.getLocationDescription_(sel), - cvox.QueueMode.FLUSH, - null); + this.getLocationDescription_(sel), cvox.QueueMode.FLUSH, null); return sel; }; @@ -258,8 +255,7 @@ return Msgs.getMsg('not_inside_table'); } return ( - this.getRowHeaderText_(position) + - ' ' + + this.getRowHeaderText_(position) + ' ' + this.getColHeaderText_(position)); }; @@ -279,9 +275,8 @@ if (locationInfo == null) { return null; } - return [new cvox.NavDescription({ - text: Msgs.getMsg('table_location', locationInfo) - })]; + return [new cvox.NavDescription( + {text: Msgs.getMsg('table_location', locationInfo)})]; }; /** @@ -299,14 +294,14 @@ var firstCellInRow = this.tt.getCellAt([position[0], 0]); rowHeaderText += cvox.DomUtil.collapseWhitespace( cvox.DomUtil.getValue(firstCellInRow) + ' ' + - cvox.DomUtil.getName(firstCellInRow)); + cvox.DomUtil.getName(firstCellInRow)); return Msgs.getMsg('row_header') + rowHeaderText; } for (var i = 0; i < rowHeaders.length; ++i) { rowHeaderText += cvox.DomUtil.collapseWhitespace( cvox.DomUtil.getValue(rowHeaders[i]) + ' ' + - cvox.DomUtil.getName(rowHeaders[i])); + cvox.DomUtil.getName(rowHeaders[i])); } if (rowHeaderText == '') { return Msgs.getMsg('empty_row_header'); @@ -336,7 +331,7 @@ for (var i = 0; i < colHeaders.length; ++i) { colHeaderText += cvox.DomUtil.collapseWhitespace( cvox.DomUtil.getValue(colHeaders[i]) + ' ' + - cvox.DomUtil.getName(colHeaders[i])); + cvox.DomUtil.getName(colHeaders[i])); } if (colHeaderText == '') { return Msgs.getMsg('empty_row_header'); @@ -358,11 +353,10 @@ } // + 1 to account for 0-indexed return [ - position[0] + 1, - this.tt.rowCount, - position[1] + 1, - this.tt.colCount - ].map(function(x) {return Msgs.getNumber(x);}); + position[0] + 1, this.tt.rowCount, position[1] + 1, this.tt.colCount + ].map(function(x) { + return Msgs.getNumber(x); + }); }; /** @@ -396,8 +390,8 @@ if (!f(position)) { return null; } - return cvox.CursorSelection.fromNode(this.tt.getCell()). - setReversed(sel.isReversed()); + return cvox.CursorSelection.fromNode(this.tt.getCell()) + .setReversed(sel.isReversed()); }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/walkers/walker_unittest_base.js b/chrome/browser/resources/chromeos/chromevox/walkers/walker_unittest_base.js index 7cb837f..6efe7fa 100644 --- a/chrome/browser/resources/chromeos/chromevox/walkers/walker_unittest_base.js +++ b/chrome/browser/resources/chromeos/chromevox/walkers/walker_unittest_base.js
@@ -15,10 +15,7 @@ __proto__: ChromeVoxUnitTestBase.prototype, /** @override */ - closureModuleDeps: [ - 'TestMsgs', - 'cvox.CursorSelection' - ], + closureModuleDeps: ['TestMsgs', 'cvox.CursorSelection'], /** * Common set up for all walker test cases. @@ -162,9 +159,11 @@ * @type {Array.string} * @const */ -CvoxWalkerUnitTestBase.DESC_WHITELIST = ['selText', 'selNodeId', -'selParentNodeId', 'selStartIndex', 'selEndIndex', 'selReversed', 'descText', -'descContext', 'descAnnotation', 'descUserValue', 'descPersonality']; +CvoxWalkerUnitTestBase.DESC_WHITELIST = [ + 'selText', 'selNodeId', 'selParentNodeId', 'selStartIndex', 'selEndIndex', + 'selReversed', 'descText', 'descContext', 'descAnnotation', 'descUserValue', + 'descPersonality' +]; /** * Adds common walker tests @@ -176,9 +175,9 @@ * not null. */ TEST_F(testFixture, 'testSyncToPage', function() { - this.loadDoc(function() {/*! + this.loadDoc(function() { /*! <div><p id="a">a</p></div> - */}); + */ }); var ret = this.walker.begin(); assertNotEquals(null, ret); ret = this.walker.begin({reversed: true}); @@ -191,7 +190,7 @@ * for TableWalker, sync can return null. Override if it doesn't work yet. */ TEST_F(testFixture, 'testSyncInvariant', function() { - this.loadDoc(function() {/*! + this.loadDoc(function() { /*! <div id="outer"> <p id="a">a</p> <p id="b">b</p> @@ -201,9 +200,8 @@ <p id="e">e</p> <h1 id="B">h1</h1> </div> - */}); - var sel = cvox.CursorSelection.fromNode( - $('outer').firstChild); + */ }); + var sel = cvox.CursorSelection.fromNode($('outer').firstChild); var sync = this.walker.sync(sel); var syncsync = this.walker.sync(sync); assertEquals(true, sync.equals(syncsync));
diff --git a/chrome/browser/resources/chromeos/login/OWNERS b/chrome/browser/resources/chromeos/login/OWNERS index e7a8a06..675ddd2 100644 --- a/chrome/browser/resources/chromeos/login/OWNERS +++ b/chrome/browser/resources/chromeos/login/OWNERS
@@ -1,2 +1,3 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org
diff --git a/chrome/browser/resources/local_ntp/local_ntp.css b/chrome/browser/resources/local_ntp/local_ntp.css index 6c53cac..e049ee5 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.css +++ b/chrome/browser/resources/local_ntp/local_ntp.css
@@ -51,33 +51,27 @@ #fakebox { background-color: #fff; - border: 1px solid rgb(185, 185, 185); - border-radius: 1px; - border-top-color: rgb(160, 160, 160); + border-radius: 2px; + box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08); cursor: text; font-size: 18px; - height: 36px; + height: 44px; line-height: 36px; max-width: 672px; + outline: none; position: relative; - transform: translate3d(0, 0, 0); - transition: transform 100ms linear, border-color 100ms linear; - /* #fakebox width (here and below) should be 2px less than #mv-tiles - to account for its border. */ - width: 298px; + transition: box-shadow 200ms cubic-bezier(0.4, 0, 0.2, 1); + /* #fakebox width is set dynamically from JS. */ + width: 300px; } .non-google-page #fakebox { display: none; } -#fakebox:hover { - border: 1px solid rgb(169, 169, 169); - border-top-color: rgb(144, 144, 144); -} - +#fakebox:hover, body.fakebox-focused #fakebox { - border: 1px solid rgb(77, 144, 254); + box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.08); } #fakebox > input { @@ -99,18 +93,18 @@ } #fakebox-text { - bottom: 0; + bottom: 4px; color: #bbb; font-family: arial, sans-serif; font-size: 16px; - left: 9px; + left: 13px; margin-top: 1px; overflow: hidden; position: absolute; - right: 9px; + right: 13px; text-align: initial; text-overflow: ellipsis; - top: 0; + top: 4px; vertical-align: middle; visibility: inherit; white-space: nowrap; @@ -118,22 +112,22 @@ html[dir=rtl] #fakebox-text { left: auto; - right: 9px; + right: 13px; } #cursor { background: #333; - bottom: 5px; - left: 9px; + bottom: 12px; + left: 13px; position: absolute; - top: 5px; + top: 12px; visibility: hidden; width: 1px; } html[dir=rtl] #cursor { left: auto; - right: 9px; + right: 13px; } @keyframes blink {
diff --git a/chrome/browser/resources/pdf/browser_api.js b/chrome/browser/resources/pdf/browser_api.js index 8b5ef44..85822de 100644 --- a/chrome/browser/resources/pdf/browser_api.js +++ b/chrome/browser/resources/pdf/browser_api.js
@@ -71,13 +71,12 @@ * @param {BrowserApi.ZoomBehavior} zoomBehavior How to manage zoom. */ static create(streamInfo, zoomBehavior) { - return Promise.all([ - lookupDefaultZoom(streamInfo), - lookupInitialZoom(streamInfo) - ]).then(function(zoomFactors) { - return new BrowserApi( - streamInfo, zoomFactors[0], zoomFactors[1], zoomBehavior); - }); + return Promise + .all([lookupDefaultZoom(streamInfo), lookupInitialZoom(streamInfo)]) + .then(function(zoomFactors) { + return new BrowserApi( + streamInfo, zoomFactors[0], zoomFactors[1], zoomBehavior); + }); } /** @@ -171,30 +170,32 @@ */ function createBrowserApiForMimeHandlerView() { return new Promise(function(resolve, reject) { - chrome.mimeHandlerPrivate.getStreamInfo(resolve); - }).then(function(streamInfo) { - let promises = []; - let zoomBehavior = BrowserApi.ZoomBehavior.NONE; - if (streamInfo.tabId != -1) { - zoomBehavior = streamInfo.embedded ? - BrowserApi.ZoomBehavior.PROPAGATE_PARENT : - BrowserApi.ZoomBehavior.MANAGE; - promises.push(new Promise(function(resolve) { - chrome.tabs.get(streamInfo.tabId, resolve); - }).then(function(tab) { - if (tab) - streamInfo.tabUrl = tab.url; - })); - } - if (zoomBehavior == BrowserApi.ZoomBehavior.MANAGE) { - promises.push(new Promise(function(resolve) { - chrome.tabs.setZoomSettings( - streamInfo.tabId, {mode: 'manual', scope: 'per-tab'}, resolve); - })); - } - return Promise.all(promises).then( - function() { return BrowserApi.create(streamInfo, zoomBehavior); }); - }); + chrome.mimeHandlerPrivate.getStreamInfo(resolve); + }) + .then(function(streamInfo) { + let promises = []; + let zoomBehavior = BrowserApi.ZoomBehavior.NONE; + if (streamInfo.tabId != -1) { + zoomBehavior = streamInfo.embedded ? + BrowserApi.ZoomBehavior.PROPAGATE_PARENT : + BrowserApi.ZoomBehavior.MANAGE; + promises.push(new Promise(function(resolve) { + chrome.tabs.get(streamInfo.tabId, resolve); + }).then(function(tab) { + if (tab) + streamInfo.tabUrl = tab.url; + })); + } + if (zoomBehavior == BrowserApi.ZoomBehavior.MANAGE) { + promises.push(new Promise(function(resolve) { + chrome.tabs.setZoomSettings( + streamInfo.tabId, {mode: 'manual', scope: 'per-tab'}, resolve); + })); + } + return Promise.all(promises).then(function() { + return BrowserApi.create(streamInfo, zoomBehavior); + }); + }); } /** @@ -212,18 +213,19 @@ tabId: -1, }; return new Promise(function(resolve, reject) { - if (!chrome.tabs) { - resolve(); - return; - } - chrome.tabs.getCurrent(function(tab) { - streamInfo.tabId = tab.id; - streamInfo.tabUrl = tab.url; - resolve(); - }); - }).then(function() { - return BrowserApi.create(streamInfo, BrowserApi.ZoomBehavior.NONE); - }); + if (!chrome.tabs) { + resolve(); + return; + } + chrome.tabs.getCurrent(function(tab) { + streamInfo.tabId = tab.id; + streamInfo.tabUrl = tab.url; + resolve(); + }); + }) + .then(function() { + return BrowserApi.create(streamInfo, BrowserApi.ZoomBehavior.NONE); + }); } /**
diff --git a/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js b/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js index 9d63990..1e7164a 100644 --- a/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js +++ b/chrome/browser/resources/pdf/elements/viewer-bookmark/viewer-bookmark.js
@@ -3,90 +3,75 @@ // found in the LICENSE file. (function() { - /** Amount that each level of bookmarks is indented by (px). */ - var BOOKMARK_INDENT = 20; +/** Amount that each level of bookmarks is indented by (px). */ +var BOOKMARK_INDENT = 20; - Polymer({ - is: 'viewer-bookmark', +Polymer({ + is: 'viewer-bookmark', - properties: { - /** - * A bookmark object, each containing a: - * - title - * - page (optional) - * - children (an array of bookmarks) - */ - bookmark: { - type: Object, - observer: 'bookmarkChanged_' - }, + properties: { + /** + * A bookmark object, each containing a: + * - title + * - page (optional) + * - children (an array of bookmarks) + */ + bookmark: {type: Object, observer: 'bookmarkChanged_'}, - depth: { - type: Number, - observer: 'depthChanged' - }, + depth: {type: Number, observer: 'depthChanged'}, - childDepth: Number, + childDepth: Number, - childrenShown: { - type: Boolean, - reflectToAttribute: true, - value: false - }, + childrenShown: {type: Boolean, reflectToAttribute: true, value: false}, - keyEventTarget: { - type: Object, - value: function() { - return this.$.item; - } + keyEventTarget: { + type: Object, + value: function() { + return this.$.item; } - }, - - behaviors: [ - Polymer.IronA11yKeysBehavior - ], - - keyBindings: { - 'enter': 'onEnter_', - 'space': 'onSpace_' - }, - - bookmarkChanged_: function() { - this.$.expand.style.visibility = - this.bookmark.children.length > 0 ? 'visible' : 'hidden'; - }, - - depthChanged: function() { - this.childDepth = this.depth + 1; - this.$.item.style.webkitPaddingStart = - (this.depth * BOOKMARK_INDENT) + 'px'; - }, - - onClick: function() { - if (this.bookmark.hasOwnProperty('page')) - this.fire('change-page', {page: this.bookmark.page}); - else if (this.bookmark.hasOwnProperty('uri')) - this.fire('navigate', {uri: this.bookmark.uri, newtab: true}); - }, - - onEnter_: function(e) { - // Don't allow events which have propagated up from the expand button to - // trigger a click. - if (e.detail.keyboardEvent.target != this.$.expand) - this.onClick(); - }, - - onSpace_: function(e) { - // paper-icon-button stops propagation of space events, so there's no need - // to check the event source here. - this.onClick(); - // Prevent default space scroll behavior. - e.detail.keyboardEvent.preventDefault(); - }, - - toggleChildren: function(e) { - this.childrenShown = !this.childrenShown; - e.stopPropagation(); // Prevent the above onClick handler from firing. } - }); + }, + + behaviors: [Polymer.IronA11yKeysBehavior], + + keyBindings: {'enter': 'onEnter_', 'space': 'onSpace_'}, + + bookmarkChanged_: function() { + this.$.expand.style.visibility = + this.bookmark.children.length > 0 ? 'visible' : 'hidden'; + }, + + depthChanged: function() { + this.childDepth = this.depth + 1; + this.$.item.style.webkitPaddingStart = + (this.depth * BOOKMARK_INDENT) + 'px'; + }, + + onClick: function() { + if (this.bookmark.hasOwnProperty('page')) + this.fire('change-page', {page: this.bookmark.page}); + else if (this.bookmark.hasOwnProperty('uri')) + this.fire('navigate', {uri: this.bookmark.uri, newtab: true}); + }, + + onEnter_: function(e) { + // Don't allow events which have propagated up from the expand button to + // trigger a click. + if (e.detail.keyboardEvent.target != this.$.expand) + this.onClick(); + }, + + onSpace_: function(e) { + // paper-icon-button stops propagation of space events, so there's no need + // to check the event source here. + this.onClick(); + // Prevent default space scroll behavior. + e.detail.keyboardEvent.preventDefault(); + }, + + toggleChildren: function(e) { + this.childrenShown = !this.childrenShown; + e.stopPropagation(); // Prevent the above onClick handler from firing. + } +}); })();
diff --git a/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js b/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js index 1aa2b5c..32f3fd3 100644 --- a/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js +++ b/chrome/browser/resources/pdf/elements/viewer-bookmarks-content/viewer-bookmarks-content.js
@@ -2,6 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -Polymer({ - is: 'viewer-bookmarks-content' -}); +Polymer({is: 'viewer-bookmarks-content'});
diff --git a/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js b/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js index 09f1b80..70147ab5 100644 --- a/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js +++ b/chrome/browser/resources/pdf/elements/viewer-page-indicator/viewer-page-indicator.js
@@ -6,21 +6,11 @@ is: 'viewer-page-indicator', properties: { - label: { - type: String, - value: '1' - }, + label: {type: String, value: '1'}, - index: { - type: Number, - observer: 'indexChanged' - }, + index: {type: Number, observer: 'indexChanged'}, - pageLabels: { - type: Array, - value: null, - observer: 'pageLabelsChanged' - } + pageLabels: {type: Array, value: null, observer: 'pageLabelsChanged'} }, /** @type {number|undefined} */ @@ -41,18 +31,18 @@ /** @param {number} displayTime */ fadeIn: function(displayTime) { var percent = window.scrollY / - (document.body.scrollHeight - - document.documentElement.clientHeight); - this.style.top = percent * - (document.documentElement.clientHeight - this.offsetHeight) + 'px'; -// <if expr="is_macosx"> + (document.body.scrollHeight - document.documentElement.clientHeight); + this.style.top = + percent * (document.documentElement.clientHeight - this.offsetHeight) + + 'px'; + // <if expr="is_macosx"> // On the Mac, if overlay scrollbars are enabled, prevent them from // overlapping the triangle. if (window.innerWidth == document.body.scrollWidth) this.style.right = '16px'; else this.style.right = '0px'; -// </if> + // </if> this.style.opacity = 1; clearTimeout(this.timerId);
diff --git a/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js b/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js index 12188d7..198b551 100644 --- a/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js +++ b/chrome/browser/resources/pdf/elements/viewer-page-selector/viewer-page-selector.js
@@ -9,21 +9,14 @@ /** * The number of pages the document contains. */ - docLength: { - type: Number, - value: 1, - observer: 'docLengthChanged_' - }, + docLength: {type: Number, value: 1, observer: 'docLengthChanged_'}, /** * The current page being viewed (1-based). A change to pageNo is mirrored * immediately to the input field. A change to the input field is not * mirrored back until pageNoCommitted() is called and change-page is fired. */ - pageNo: { - type: Number, - value: 1 - }, + pageNo: {type: Number, value: 1}, strings: Object, },
diff --git a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js index d4e8cbd..07b0390 100644 --- a/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js +++ b/chrome/browser/resources/pdf/elements/viewer-pdf-toolbar/viewer-pdf-toolbar.js
@@ -2,145 +2,126 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { - Polymer({ - is: 'viewer-pdf-toolbar', +Polymer({ + is: 'viewer-pdf-toolbar', - behaviors: [ - Polymer.NeonAnimationRunnerBehavior - ], + behaviors: [Polymer.NeonAnimationRunnerBehavior], - properties: { - /** - * The current loading progress of the PDF document (0 - 100). - */ - loadProgress: { - type: Number, - observer: 'loadProgressChanged' - }, + properties: { + /** + * The current loading progress of the PDF document (0 - 100). + */ + loadProgress: {type: Number, observer: 'loadProgressChanged'}, - /** - * The title of the PDF document. - */ - docTitle: String, + /** + * The title of the PDF document. + */ + docTitle: String, - /** - * The number of the page being viewed (1-based). - */ - pageNo: Number, + /** + * The number of the page being viewed (1-based). + */ + pageNo: Number, - /** - * Tree of PDF bookmarks (or null if the document has no bookmarks). - */ - bookmarks: { - type: Object, - value: null - }, + /** + * Tree of PDF bookmarks (or null if the document has no bookmarks). + */ + bookmarks: {type: Object, value: null}, - /** - * The number of pages in the PDF document. - */ - docLength: Number, + /** + * The number of pages in the PDF document. + */ + docLength: Number, - /** - * Whether the toolbar is opened and visible. - */ - opened: { - type: Boolean, - value: true - }, + /** + * Whether the toolbar is opened and visible. + */ + opened: {type: Boolean, value: true}, - strings: Object, + strings: Object, - animationConfig: { - value: function() { - return { - 'entry': { - name: 'transform-animation', - node: this, - transformFrom: 'translateY(-100%)', - transformTo: 'translateY(0%)', - timing: { - easing: 'cubic-bezier(0, 0, 0.2, 1)', - duration: 250 - } - }, - 'exit': { - name: 'slide-up-animation', - node: this, - timing: { - easing: 'cubic-bezier(0.4, 0, 1, 1)', - duration: 250 - } - } - }; - } + animationConfig: { + value: function() { + return { + 'entry': { + name: 'transform-animation', + node: this, + transformFrom: 'translateY(-100%)', + transformTo: 'translateY(0%)', + timing: {easing: 'cubic-bezier(0, 0, 0.2, 1)', duration: 250} + }, + 'exit': { + name: 'slide-up-animation', + node: this, + timing: {easing: 'cubic-bezier(0.4, 0, 1, 1)', duration: 250} + } + }; } - }, - - listeners: { - 'neon-animation-finish': '_onAnimationFinished' - }, - - _onAnimationFinished: function() { - this.style.transform = this.opened ? 'none' : 'translateY(-100%)'; - }, - - loadProgressChanged: function() { - if (this.loadProgress >= 100) { - this.$.pageselector.classList.toggle('invisible', false); - this.$.buttons.classList.toggle('invisible', false); - this.$.progress.style.opacity = 0; - } - }, - - hide: function() { - if (this.opened) - this.toggleVisibility(); - }, - - show: function() { - if (!this.opened) { - this.toggleVisibility(); - } - }, - - toggleVisibility: function() { - this.opened = !this.opened; - this.cancelAnimation(); - this.playAnimation(this.opened ? 'entry' : 'exit'); - }, - - selectPageNumber: function() { - this.$.pageselector.select(); - }, - - shouldKeepOpen: function() { - return this.$.bookmarks.dropdownOpen || this.loadProgress < 100 || - this.$.pageselector.isActive(); - }, - - hideDropdowns: function() { - if (this.$.bookmarks.dropdownOpen) { - this.$.bookmarks.toggleDropdown(); - return true; - } - return false; - }, - - setDropdownLowerBound: function(lowerBound) { - this.$.bookmarks.lowerBound = lowerBound; - }, - - rotateRight: function() { - this.fire('rotate-right'); - }, - - download: function() { - this.fire('save'); - }, - - print: function() { - this.fire('print'); } - }); + }, + + listeners: {'neon-animation-finish': '_onAnimationFinished'}, + + _onAnimationFinished: function() { + this.style.transform = this.opened ? 'none' : 'translateY(-100%)'; + }, + + loadProgressChanged: function() { + if (this.loadProgress >= 100) { + this.$.pageselector.classList.toggle('invisible', false); + this.$.buttons.classList.toggle('invisible', false); + this.$.progress.style.opacity = 0; + } + }, + + hide: function() { + if (this.opened) + this.toggleVisibility(); + }, + + show: function() { + if (!this.opened) { + this.toggleVisibility(); + } + }, + + toggleVisibility: function() { + this.opened = !this.opened; + this.cancelAnimation(); + this.playAnimation(this.opened ? 'entry' : 'exit'); + }, + + selectPageNumber: function() { + this.$.pageselector.select(); + }, + + shouldKeepOpen: function() { + return this.$.bookmarks.dropdownOpen || this.loadProgress < 100 || + this.$.pageselector.isActive(); + }, + + hideDropdowns: function() { + if (this.$.bookmarks.dropdownOpen) { + this.$.bookmarks.toggleDropdown(); + return true; + } + return false; + }, + + setDropdownLowerBound: function(lowerBound) { + this.$.bookmarks.lowerBound = lowerBound; + }, + + rotateRight: function() { + this.fire('rotate-right'); + }, + + download: function() { + this.fire('save'); + }, + + print: function() { + this.fire('print'); + } +}); })();
diff --git a/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js b/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js index 17a04c04..53e9acc5 100644 --- a/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js +++ b/chrome/browser/resources/pdf/elements/viewer-toolbar-dropdown/viewer-toolbar-dropdown.js
@@ -3,136 +3,132 @@ // found in the LICENSE file. (function() { - /** - * Size of additional padding in the inner scrollable section of the dropdown. - */ - var DROPDOWN_INNER_PADDING = 12; +/** + * Size of additional padding in the inner scrollable section of the dropdown. + */ +var DROPDOWN_INNER_PADDING = 12; - /** Size of vertical padding on the outer #dropdown element. */ - var DROPDOWN_OUTER_PADDING = 2; +/** Size of vertical padding on the outer #dropdown element. */ +var DROPDOWN_OUTER_PADDING = 2; - /** Minimum height of toolbar dropdowns (px). */ - var MIN_DROPDOWN_HEIGHT = 200; +/** Minimum height of toolbar dropdowns (px). */ +var MIN_DROPDOWN_HEIGHT = 200; - Polymer({ - is: 'viewer-toolbar-dropdown', +Polymer({ + is: 'viewer-toolbar-dropdown', - properties: { - /** String to be displayed at the top of the dropdown. */ - header: String, + properties: { + /** String to be displayed at the top of the dropdown. */ + header: String, - /** Icon to display when the dropdown is closed. */ - closedIcon: String, + /** Icon to display when the dropdown is closed. */ + closedIcon: String, - /** Icon to display when the dropdown is open. */ - openIcon: String, + /** Icon to display when the dropdown is open. */ + openIcon: String, - /** True if the dropdown is currently open. */ - dropdownOpen: { - type: Boolean, - reflectToAttribute: true, - value: false - }, + /** True if the dropdown is currently open. */ + dropdownOpen: {type: Boolean, reflectToAttribute: true, value: false}, - /** Toolbar icon currently being displayed. */ - dropdownIcon: { - type: String, - computed: 'computeIcon_(dropdownOpen, closedIcon, openIcon)' - }, - - /** Lowest vertical point that the dropdown should occupy (px). */ - lowerBound: { - type: Number, - observer: 'lowerBoundChanged_' - }, - - /** - * True if the max-height CSS property for the dropdown scroll container - * is valid. If false, the height will be updated the next time the - * dropdown is visible. - */ - maxHeightValid_: false, - - /** Current animation being played, or null if there is none. */ - animation_: Object + /** Toolbar icon currently being displayed. */ + dropdownIcon: { + type: String, + computed: 'computeIcon_(dropdownOpen, closedIcon, openIcon)' }, - computeIcon_: function(dropdownOpen, closedIcon, openIcon) { - return dropdownOpen ? openIcon : closedIcon; - }, - - lowerBoundChanged_: function() { - this.maxHeightValid_ = false; - if (this.dropdownOpen) - this.updateMaxHeight(); - }, - - toggleDropdown: function() { - this.dropdownOpen = !this.dropdownOpen; - if (this.dropdownOpen) { - this.$.dropdown.style.display = 'block'; - if (!this.maxHeightValid_) - this.updateMaxHeight(); - } - this.cancelAnimation_(); - this.playAnimation_(this.dropdownOpen); - }, - - updateMaxHeight: function() { - var scrollContainer = this.$['scroll-container']; - var height = this.lowerBound - - scrollContainer.getBoundingClientRect().top - - DROPDOWN_INNER_PADDING; - height = Math.max(height, MIN_DROPDOWN_HEIGHT); - scrollContainer.style.maxHeight = height + 'px'; - this.maxHeightValid_ = true; - }, - - cancelAnimation_: function() { - if (this._animation) - this._animation.cancel(); - }, + /** Lowest vertical point that the dropdown should occupy (px). */ + lowerBound: {type: Number, observer: 'lowerBoundChanged_'}, /** - * Start an animation on the dropdown. - * @param {boolean} isEntry True to play entry animation, false to play - * exit. - * @private + * True if the max-height CSS property for the dropdown scroll container + * is valid. If false, the height will be updated the next time the + * dropdown is visible. */ - playAnimation_: function(isEntry) { - this.animation_ = isEntry ? this.animateEntry_() : this.animateExit_(); - this.animation_.onfinish = function() { - this.animation_ = null; - if (!this.dropdownOpen) - this.$.dropdown.style.display = 'none'; - }.bind(this); - }, + maxHeightValid_: false, - animateEntry_: function() { - var maxHeight = this.$.dropdown.getBoundingClientRect().height - - DROPDOWN_OUTER_PADDING; + /** Current animation being played, or null if there is none. */ + animation_: Object + }, - if (maxHeight < 0) - maxHeight = 0; + computeIcon_: function(dropdownOpen, closedIcon, openIcon) { + return dropdownOpen ? openIcon : closedIcon; + }, - var fade = new KeyframeEffect(this.$.dropdown, [ - {opacity: 0}, - {opacity: 1} - ], {duration: 150, easing: 'cubic-bezier(0, 0, 0.2, 1)'}); - var slide = new KeyframeEffect(this.$.dropdown, [ - {height: '20px', transform: 'translateY(-10px)'}, - {height: maxHeight + 'px', transform: 'translateY(0)'} - ], {duration: 250, easing: 'cubic-bezier(0, 0, 0.2, 1)'}); + lowerBoundChanged_: function() { + this.maxHeightValid_ = false; + if (this.dropdownOpen) + this.updateMaxHeight(); + }, - return document.timeline.play(new GroupEffect([fade, slide])); - }, - - animateExit_: function() { - return this.$.dropdown.animate([ - {transform: 'translateY(0)', opacity: 1}, - {transform: 'translateY(-5px)', opacity: 0} - ], {duration: 100, easing: 'cubic-bezier(0.4, 0, 1, 1)'}); + toggleDropdown: function() { + this.dropdownOpen = !this.dropdownOpen; + if (this.dropdownOpen) { + this.$.dropdown.style.display = 'block'; + if (!this.maxHeightValid_) + this.updateMaxHeight(); } - }); + this.cancelAnimation_(); + this.playAnimation_(this.dropdownOpen); + }, + + updateMaxHeight: function() { + var scrollContainer = this.$['scroll-container']; + var height = this.lowerBound - scrollContainer.getBoundingClientRect().top - + DROPDOWN_INNER_PADDING; + height = Math.max(height, MIN_DROPDOWN_HEIGHT); + scrollContainer.style.maxHeight = height + 'px'; + this.maxHeightValid_ = true; + }, + + cancelAnimation_: function() { + if (this._animation) + this._animation.cancel(); + }, + + /** + * Start an animation on the dropdown. + * @param {boolean} isEntry True to play entry animation, false to play + * exit. + * @private + */ + playAnimation_: function(isEntry) { + this.animation_ = isEntry ? this.animateEntry_() : this.animateExit_(); + this.animation_.onfinish = function() { + this.animation_ = null; + if (!this.dropdownOpen) + this.$.dropdown.style.display = 'none'; + }.bind(this); + }, + + animateEntry_: function() { + var maxHeight = + this.$.dropdown.getBoundingClientRect().height - DROPDOWN_OUTER_PADDING; + + if (maxHeight < 0) + maxHeight = 0; + + var fade = new KeyframeEffect( + this.$.dropdown, [{opacity: 0}, {opacity: 1}], + {duration: 150, easing: 'cubic-bezier(0, 0, 0.2, 1)'}); + var slide = new KeyframeEffect( + this.$.dropdown, + [ + {height: '20px', transform: 'translateY(-10px)'}, + {height: maxHeight + 'px', transform: 'translateY(0)'} + ], + {duration: 250, easing: 'cubic-bezier(0, 0, 0.2, 1)'}); + + return document.timeline.play(new GroupEffect([fade, slide])); + }, + + animateExit_: function() { + return this.$.dropdown.animate( + [ + {transform: 'translateY(0)', opacity: 1}, + {transform: 'translateY(-5px)', opacity: 0} + ], + {duration: 100, easing: 'cubic-bezier(0.4, 0, 1, 1)'}); + } +}); })();
diff --git a/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js b/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js index df556ace..6558c15 100644 --- a/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js +++ b/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-button.js
@@ -18,41 +18,25 @@ * perform the conversion manually. * @private */ - icons_: { - type: Array, - value: [''], - computed: 'computeIconsArray_(icons)' - }, + icons_: {type: Array, value: [''], computed: 'computeIconsArray_(icons)'}, tooltips: Array, - closed: { - type: Boolean, - reflectToAttribute: true, - value: false - }, + closed: {type: Boolean, reflectToAttribute: true, value: false}, - delay: { - type: Number, - observer: 'delayChanged_' - }, + delay: {type: Number, observer: 'delayChanged_'}, /** * Index of the icon currently being displayed. */ - activeIndex: { - type: Number, - value: 0 - }, + activeIndex: {type: Number, value: 0}, /** * Icon currently being displayed on the FAB. * @private */ - visibleIcon_: { - type: String, - computed: 'computeVisibleIcon_(icons_, activeIndex)' - }, + visibleIcon_: + {type: String, computed: 'computeVisibleIcon_(icons_, activeIndex)'}, visibleTooltip_: { type: String,
diff --git a/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js b/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js index 3ade73b7..6a4af8f 100644 --- a/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js +++ b/chrome/browser/resources/pdf/elements/viewer-zoom-toolbar/viewer-zoom-toolbar.js
@@ -4,96 +4,88 @@ (function() { - var FIT_TO_PAGE = 0; - var FIT_TO_WIDTH = 1; +var FIT_TO_PAGE = 0; +var FIT_TO_WIDTH = 1; - Polymer({ - is: 'viewer-zoom-toolbar', +Polymer({ + is: 'viewer-zoom-toolbar', - properties: { - strings: { - type: Object, - observer: 'updateTooltips_' - }, + properties: { + strings: {type: Object, observer: 'updateTooltips_'}, - visible_: { - type: Boolean, - value: true - } - }, + visible_: {type: Boolean, value: true} + }, - isVisible: function() { - return this.visible_; - }, + isVisible: function() { + return this.visible_; + }, - /** - * @private - * Change button tooltips to match any changes to localized strings. - */ - updateTooltips_: function() { - this.$['fit-button'].tooltips = [ - this.strings.tooltipFitToPage, - this.strings.tooltipFitToWidth - ]; - this.$['zoom-in-button'].tooltips = [this.strings.tooltipZoomIn]; - this.$['zoom-out-button'].tooltips = [this.strings.tooltipZoomOut]; - }, + /** + * @private + * Change button tooltips to match any changes to localized strings. + */ + updateTooltips_: function() { + this.$['fit-button'].tooltips = + [this.strings.tooltipFitToPage, this.strings.tooltipFitToWidth]; + this.$['zoom-in-button'].tooltips = [this.strings.tooltipZoomIn]; + this.$['zoom-out-button'].tooltips = [this.strings.tooltipZoomOut]; + }, - /** - * Handle clicks of the fit-button. - */ - fitToggle: function() { - if (this.$['fit-button'].activeIndex == FIT_TO_WIDTH) - this.fire('fit-to-width'); - else - this.fire('fit-to-page'); - }, + /** + * Handle clicks of the fit-button. + */ + fitToggle: function() { + if (this.$['fit-button'].activeIndex == FIT_TO_WIDTH) + this.fire('fit-to-width'); + else + this.fire('fit-to-page'); + }, - /** - * Handle the keyboard shortcut equivalent of fit-button clicks. - */ - fitToggleFromHotKey: function() { - this.fitToggle(); + /** + * Handle the keyboard shortcut equivalent of fit-button clicks. + */ + fitToggleFromHotKey: function() { + this.fitToggle(); - // Toggle the button state since there was no mouse click. - var button = this.$['fit-button']; - if (button.activeIndex == FIT_TO_WIDTH) - button.activeIndex = FIT_TO_PAGE; - else - button.activeIndex = FIT_TO_WIDTH; - }, + // Toggle the button state since there was no mouse click. + var button = this.$['fit-button']; + if (button.activeIndex == FIT_TO_WIDTH) + button.activeIndex = FIT_TO_PAGE; + else + button.activeIndex = FIT_TO_WIDTH; + }, - /** - * Handle clicks of the zoom-in-button. - */ - zoomIn: function() { - this.fire('zoom-in'); - }, + /** + * Handle clicks of the zoom-in-button. + */ + zoomIn: function() { + this.fire('zoom-in'); + }, - /** - * Handle clicks of the zoom-out-button. - */ - zoomOut: function() { - this.fire('zoom-out'); - }, + /** + * Handle clicks of the zoom-out-button. + */ + zoomOut: function() { + this.fire('zoom-out'); + }, - show: function() { - if (!this.visible_) { - this.visible_ = true; - this.$['fit-button'].show(); - this.$['zoom-in-button'].show(); - this.$['zoom-out-button'].show(); - } - }, + show: function() { + if (!this.visible_) { + this.visible_ = true; + this.$['fit-button'].show(); + this.$['zoom-in-button'].show(); + this.$['zoom-out-button'].show(); + } + }, - hide: function() { - if (this.visible_) { - this.visible_ = false; - this.$['fit-button'].hide(); - this.$['zoom-in-button'].hide(); - this.$['zoom-out-button'].hide(); - } - }, - }); + hide: function() { + if (this.visible_) { + this.visible_ = false; + this.$['fit-button'].hide(); + this.$['zoom-in-button'].hide(); + this.$['zoom-out-button'].hide(); + } + }, +}); })();
diff --git a/chrome/browser/resources/pdf/gesture_detector.js b/chrome/browser/resources/pdf/gesture_detector.js index d73a85b7..811bfe28 100644 --- a/chrome/browser/resources/pdf/gesture_detector.js +++ b/chrome/browser/resources/pdf/gesture_detector.js
@@ -20,20 +20,20 @@ this.element_.addEventListener( 'touchstart', /** @type {function(!Event)} */ (this.onTouchStart_.bind(this)), - { passive: true }); + {passive: true}); this.element_.addEventListener( 'touchmove', /** @type {function(!Event)} */ (this.onTouch_.bind(this)), - { passive: false }); + {passive: false}); this.element_.addEventListener( 'touchend', /** @type {function(!Event)} */ (this.onTouch_.bind(this)), - { passive: true }); + {passive: true}); this.element_.addEventListener( 'touchcancel', /** @type {function(!Event)} */ (this.onTouch_.bind(this)), - { passive: true }); + {passive: true}); this.pinchStartEvent_ = null; this.lastTouchTouchesCount_ = 0; @@ -42,11 +42,8 @@ this.lastEvent_ = null; /** @private {!Map<string, !Array<!Function>>} */ - this.listeners_ = new Map([ - ['pinchstart', []], - ['pinchupdate', []], - ['pinchend', []] - ]); + this.listeners_ = + new Map([['pinchstart', []], ['pinchupdate', []], ['pinchend', []]]); } /** @@ -92,10 +89,7 @@ this.pinchStartEvent_ = event; this.lastEvent_ = event; - this.notify_({ - type: 'pinchstart', - center: GestureDetector.center_(event) - }); + this.notify_({type: 'pinchstart', center: GestureDetector.center_(event)}); } /** @@ -112,8 +106,8 @@ // Check if the pinch ends with the current event. if (event.touches.length < 2 || lastEvent.touches.length !== event.touches.length) { - let startScaleRatio = GestureDetector.pinchScaleRatio_( - lastEvent, this.pinchStartEvent_); + let startScaleRatio = + GestureDetector.pinchScaleRatio_(lastEvent, this.pinchStartEvent_); let center = GestureDetector.center_(lastEvent); let endEvent = { type: 'pinchend', @@ -131,8 +125,8 @@ event.preventDefault(); let scaleRatio = GestureDetector.pinchScaleRatio_(event, lastEvent); - let startScaleRatio = GestureDetector.pinchScaleRatio_( - event, this.pinchStartEvent_); + let startScaleRatio = + GestureDetector.pinchScaleRatio_(event, this.pinchStartEvent_); let center = GestureDetector.center_(event); this.notify_({ type: 'pinchupdate',
diff --git a/chrome/browser/resources/pdf/main.js b/chrome/browser/resources/pdf/main.js index 901b8e67..6a1061c 100644 --- a/chrome/browser/resources/pdf/main.js +++ b/chrome/browser/resources/pdf/main.js
@@ -12,44 +12,44 @@ (function() { - /** - * Stores any pending messages received which should be passed to the - * PDFViewer when it is created. - * @type Array - */ - var pendingMessages = []; +/** + * Stores any pending messages received which should be passed to the + * PDFViewer when it is created. + * @type Array + */ +var pendingMessages = []; - /** - * Handles events that are received prior to the PDFViewer being created. - * @param {Object} message A message event received. - */ - function handleScriptingMessage(message) { - pendingMessages.push(message); - } +/** + * Handles events that are received prior to the PDFViewer being created. + * @param {Object} message A message event received. + */ +function handleScriptingMessage(message) { + pendingMessages.push(message); +} - /** - * Initialize the global PDFViewer and pass any outstanding messages to it. - * @param {Object} browserApi An object providing an API to the browser. - */ - function initViewer(browserApi) { - // PDFViewer will handle any messages after it is created. - window.removeEventListener('message', handleScriptingMessage, false); - viewer = new PDFViewer(browserApi); - while (pendingMessages.length > 0) - viewer.handleScriptingMessage(pendingMessages.shift()); - } +/** + * Initialize the global PDFViewer and pass any outstanding messages to it. + * @param {Object} browserApi An object providing an API to the browser. + */ +function initViewer(browserApi) { + // PDFViewer will handle any messages after it is created. + window.removeEventListener('message', handleScriptingMessage, false); + viewer = new PDFViewer(browserApi); + while (pendingMessages.length > 0) + viewer.handleScriptingMessage(pendingMessages.shift()); +} - /** - * Entrypoint for starting the PDF viewer. This function obtains the browser - * API for the PDF and constructs a PDFViewer object with it. - */ - function main() { - // Set up an event listener to catch scripting messages which are sent prior - // to the PDFViewer being created. - window.addEventListener('message', handleScriptingMessage, false); +/** + * Entrypoint for starting the PDF viewer. This function obtains the browser + * API for the PDF and constructs a PDFViewer object with it. + */ +function main() { + // Set up an event listener to catch scripting messages which are sent prior + // to the PDFViewer being created. + window.addEventListener('message', handleScriptingMessage, false); - createBrowserApi().then(initViewer); - } + createBrowserApi().then(initViewer); +} - main(); +main(); })();
diff --git a/chrome/browser/resources/pdf/navigator.js b/chrome/browser/resources/pdf/navigator.js index d619c42..ebc18db 100644 --- a/chrome/browser/resources/pdf/navigator.js +++ b/chrome/browser/resources/pdf/navigator.js
@@ -179,10 +179,8 @@ */ isValidUrl_: function(url) { // Make sure |url| starts with a valid scheme. - if (!url.startsWith('http://') && - !url.startsWith('https://') && - !url.startsWith('ftp://') && - !url.startsWith('file://') && + if (!url.startsWith('http://') && !url.startsWith('https://') && + !url.startsWith('ftp://') && !url.startsWith('file://') && !url.startsWith('mailto:')) { return false; } @@ -193,11 +191,8 @@ // Make sure |url| is not only a scheme. - if (url == 'http://' || - url == 'https://' || - url == 'ftp://' || - url == 'file://' || - url == 'mailto:') { + if (url == 'http://' || url == 'https://' || url == 'ftp://' || + url == 'file://' || url == 'mailto:') { return false; } @@ -226,8 +221,8 @@ var schemeEndIndex = this.originalUrl_.indexOf('://'); var firstSlash = this.originalUrl_.indexOf('/', schemeEndIndex + 3); // e.g. http://www.foo.com/bar -> http://www.foo.com - var domain = firstSlash != -1 ? - this.originalUrl_.substr(0, firstSlash) : this.originalUrl_; + var domain = firstSlash != -1 ? this.originalUrl_.substr(0, firstSlash) : + this.originalUrl_; return domain + url; } @@ -245,7 +240,8 @@ if (!isRelative) { var domainSeparatorIndex = url.indexOf('/'); var domainName = domainSeparatorIndex == -1 ? - url : url.substr(0, domainSeparatorIndex); + url : + url.substr(0, domainSeparatorIndex); var domainDotCount = (domainName.match(/\./g) || []).length; if (domainDotCount < 2) isRelative = true; @@ -253,8 +249,8 @@ if (isRelative) { var slashIndex = this.originalUrl_.lastIndexOf('/'); - var path = slashIndex != -1 ? - this.originalUrl_.substr(0, slashIndex) : this.originalUrl_; + var path = slashIndex != -1 ? this.originalUrl_.substr(0, slashIndex) : + this.originalUrl_; return path + '/' + url; }
diff --git a/chrome/browser/resources/pdf/open_pdf_params_parser.js b/chrome/browser/resources/pdf/open_pdf_params_parser.js index 8d1ac21..2eefdec 100644 --- a/chrome/browser/resources/pdf/open_pdf_params_parser.js +++ b/chrome/browser/resources/pdf/open_pdf_params_parser.js
@@ -42,8 +42,10 @@ } // Handle #zoom=scale,left,top. - var position = {x: parseFloat(paramValueSplit[1]), - y: parseFloat(paramValueSplit[2])}; + var position = { + x: parseFloat(paramValueSplit[1]), + y: parseFloat(paramValueSplit[2]) + }; viewportPosition['position'] = position; viewportPosition['zoom'] = zoomFactor; }, @@ -123,10 +125,8 @@ if (viewportPosition.page === undefined && 'nameddest' in paramsDictionary) { - this.outstandingRequests_.push({ - callback: callback, - viewportPosition: viewportPosition - }); + this.outstandingRequests_.push( + {callback: callback, viewportPosition: viewportPosition}); this.getNamedDestinationsFunction_(paramsDictionary['nameddest']); } else { callback(viewportPosition);
diff --git a/chrome/browser/resources/pdf/pdf.js b/chrome/browser/resources/pdf/pdf.js index 898935e..56580f1 100644 --- a/chrome/browser/resources/pdf/pdf.js +++ b/chrome/browser/resources/pdf/pdf.js
@@ -51,9 +51,9 @@ activeElement = activeElement.shadowRoot.activeElement; } - return (activeElement.isContentEditable || - activeElement.tagName == 'INPUT' || - activeElement.tagName == 'TEXTAREA'); + return ( + activeElement.isContentEditable || activeElement.tagName == 'INPUT' || + activeElement.tagName == 'TEXTAREA'); } /** @@ -117,8 +117,8 @@ if (this.isPrintPreview_) this.pageIndicator_ = $('page-indicator'); this.passwordScreen_ = $('password-screen'); - this.passwordScreen_.addEventListener('password-submitted', - this.onPasswordSubmitted_.bind(this)); + this.passwordScreen_.addEventListener( + 'password-submitted', this.onPasswordSubmitted_.bind(this)); this.errorScreen_ = $('error-screen'); // Can only reload if we are in a normal tab. if (chrome.tabs && this.browserApi_.getStreamInfo().tabId != -1) { @@ -133,15 +133,12 @@ (toolbarEnabled) ? PDFViewer.MATERIAL_TOOLBAR_HEIGHT : 0; var defaultZoom = this.browserApi_.getZoomBehavior() == BrowserApi.ZoomBehavior.MANAGE ? - this.browserApi_.getDefaultZoom() : 1.0; - this.viewport_ = new Viewport(window, - this.sizer_, - this.viewportChanged_.bind(this), - this.beforeZoom_.bind(this), - this.afterZoom_.bind(this), - getScrollbarWidth(), - defaultZoom, - topToolbarHeight); + this.browserApi_.getDefaultZoom() : + 1.0; + this.viewport_ = new Viewport( + window, this.sizer_, this.viewportChanged_.bind(this), + this.beforeZoom_.bind(this), this.afterZoom_.bind(this), + getScrollbarWidth(), defaultZoom, topToolbarHeight); // Create the plugin object dynamically so we can set its src. The plugin // element is sized to fill the entire window and is set to be fixed @@ -152,18 +149,18 @@ // chrome/renderer/printing/print_web_view_helper.cc actually references it. this.plugin_.id = 'plugin'; this.plugin_.type = 'application/x-google-chrome-pdf'; - this.plugin_.addEventListener('message', this.handlePluginMessage_.bind(this), - false); + this.plugin_.addEventListener( + 'message', this.handlePluginMessage_.bind(this), false); // Handle scripting messages from outside the extension that wish to interact // with it. We also send a message indicating that extension has loaded and // is ready to receive messages. - window.addEventListener('message', this.handleScriptingMessage.bind(this), - false); + window.addEventListener( + 'message', this.handleScriptingMessage.bind(this), false); this.plugin_.setAttribute('src', this.originalUrl_); - this.plugin_.setAttribute('stream-url', - this.browserApi_.getStreamInfo().streamUrl); + this.plugin_.setAttribute( + 'stream-url', this.browserApi_.getStreamInfo().streamUrl); var headers = ''; for (var header in this.browserApi_.getStreamInfo().responseHeaders) { headers += header + ': ' + @@ -176,8 +173,8 @@ this.plugin_.setAttribute('top-toolbar-height', topToolbarHeight); if (this.browserApi_.getStreamInfo().embedded) { - this.plugin_.setAttribute('top-level-url', - this.browserApi_.getStreamInfo().tabUrl); + this.plugin_.setAttribute( + 'top-level-url', this.browserApi_.getStreamInfo().tabUrl); } else { this.plugin_.setAttribute('full-frame', ''); } @@ -185,14 +182,13 @@ // Setup the button event listeners. this.zoomToolbar_ = $('zoom-toolbar'); - this.zoomToolbar_.addEventListener('fit-to-width', - this.viewport_.fitToWidth.bind(this.viewport_)); - this.zoomToolbar_.addEventListener('fit-to-page', - this.fitToPage_.bind(this)); - this.zoomToolbar_.addEventListener('zoom-in', - this.viewport_.zoomIn.bind(this.viewport_)); - this.zoomToolbar_.addEventListener('zoom-out', - this.viewport_.zoomOut.bind(this.viewport_)); + this.zoomToolbar_.addEventListener( + 'fit-to-width', this.viewport_.fitToWidth.bind(this.viewport_)); + this.zoomToolbar_.addEventListener('fit-to-page', this.fitToPage_.bind(this)); + this.zoomToolbar_.addEventListener( + 'zoom-in', this.viewport_.zoomIn.bind(this.viewport_)); + this.zoomToolbar_.addEventListener( + 'zoom-out', this.viewport_.zoomOut.bind(this.viewport_)); this.gestureDetector_ = new GestureDetector(this.plugin_); this.gestureDetector_.addEventListener( @@ -208,12 +204,12 @@ this.toolbar_.hidden = false; this.toolbar_.addEventListener('save', this.save_.bind(this)); this.toolbar_.addEventListener('print', this.print_.bind(this)); - this.toolbar_.addEventListener('rotate-right', - this.rotateClockwise_.bind(this)); + this.toolbar_.addEventListener( + 'rotate-right', this.rotateClockwise_.bind(this)); // Must attach to mouseup on the plugin element, since it eats mousedown // and click events. - this.plugin_.addEventListener('mouseup', - this.toolbar_.hideDropdowns.bind(this.toolbar_)); + this.plugin_.addEventListener( + 'mouseup', this.toolbar_.hideDropdowns.bind(this.toolbar_)); this.toolbar_.docTitle = getFilenameFromURL(this.originalUrl_); } @@ -223,9 +219,9 @@ }.bind(this)); document.body.addEventListener('navigate', function(e) { - var disposition = - e.detail.newtab ? Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB : - Navigator.WindowOpenDisposition.CURRENT_TAB; + var disposition = e.detail.newtab ? + Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB : + Navigator.WindowOpenDisposition.CURRENT_TAB; this.navigator_.navigate(e.detail.uri, disposition); }.bind(this)); @@ -245,8 +241,8 @@ document.addEventListener('keydown', this.handleKeyEvent_.bind(this)); document.addEventListener('mousemove', this.handleMouseEvent_.bind(this)); document.addEventListener('mouseout', this.handleMouseEvent_.bind(this)); - document.addEventListener('contextmenu', - this.handleContextMenuEvent_.bind(this)); + document.addEventListener( + 'contextmenu', this.handleContextMenuEvent_.bind(this)); var tabId = this.browserApi_.getStreamInfo().tabId; this.navigator_ = new Navigator( @@ -365,14 +361,12 @@ return; case 65: // 'a' key. if (e.ctrlKey || e.metaKey) { - this.plugin_.postMessage({ - type: 'selectAll' - }); + this.plugin_.postMessage({type: 'selectAll'}); // Since we do selection ourselves. e.preventDefault(); } return; - case 71: // 'g' key. + case 71: // 'g' key. if (this.toolbar_ && (e.ctrlKey || e.metaKey) && e.altKey) { this.toolbarManager_.showToolbars(); this.toolbar_.selectPageNumber(); @@ -394,10 +388,8 @@ // Give print preview a chance to handle the key event. if (!fromScriptingAPI && this.isPrintPreview_) { - this.sendScriptingMessage_({ - type: 'sendKeyEvent', - keyEvent: SerializeKeyEvent(e) - }); + this.sendScriptingMessage_( + {type: 'sendKeyEvent', keyEvent: SerializeKeyEvent(e)}); } else { // Show toolbars as a fallback. if (!(e.shiftKey || e.ctrlKey || e.altKey)) @@ -428,9 +420,7 @@ * Rotate the plugin clockwise. */ rotateClockwise_: function() { - this.plugin_.postMessage({ - type: 'rotateClockwise' - }); + this.plugin_.postMessage({type: 'rotateClockwise'}); }, /** @@ -438,9 +428,7 @@ * Rotate the plugin counter-clockwise. */ rotateCounterClockwise_: function() { - this.plugin_.postMessage({ - type: 'rotateCounterclockwise' - }); + this.plugin_.postMessage({type: 'rotateCounterclockwise'}); }, /** @@ -457,9 +445,7 @@ * Notify the plugin to print. */ print_: function() { - this.plugin_.postMessage({ - type: 'print' - }); + this.plugin_.postMessage({type: 'print'}); }, /** @@ -467,9 +453,7 @@ * Notify the plugin to save. */ save_: function() { - this.plugin_.postMessage({ - type: 'save' - }); + this.plugin_.postMessage({type: 'save'}); }, /** @@ -478,10 +462,8 @@ * @param {string} name The namedDestination to fetch page number from plugin. */ getNamedDestination_: function(name) { - this.plugin_.postMessage({ - type: 'getNamedDestination', - namedDestination: name - }); + this.plugin_.postMessage( + {type: 'getNamedDestination', namedDestination: name}); }, /** @@ -492,10 +474,8 @@ sendDocumentLoadedMessage_: function() { if (this.loadState_ == LoadState.LOADING) return; - this.sendScriptingMessage_({ - type: 'documentLoaded', - load_state: this.loadState_ - }); + this.sendScriptingMessage_( + {type: 'documentLoaded', load_state: this.loadState_}); }, /** @@ -545,8 +525,7 @@ if (this.lastViewportPosition_) this.viewport_.position = this.lastViewportPosition_; this.paramsParser_.getViewportFromUrlParams( - this.originalUrl_, - this.handleURLParams_.bind(this)); + this.originalUrl_, this.handleURLParams_.bind(this)); this.loadState_ = LoadState.SUCCESS; this.sendDocumentLoadedMessage_(); while (this.delayedScriptingMessages_.length > 0) @@ -579,10 +558,8 @@ * @param {Object} event a password-submitted event. */ onPasswordSubmitted_: function(event) { - this.plugin_.postMessage({ - type: 'getPasswordComplete', - password: event.detail.password - }); + this.plugin_.postMessage( + {type: 'getPasswordComplete', password: event.detail.password}); }, /** @@ -682,9 +659,7 @@ * reacting to scroll events while zoom is taking place to avoid flickering. */ beforeZoom_: function() { - this.plugin_.postMessage({ - type: 'stopScrolling' - }); + this.plugin_.postMessage({type: 'stopScrolling'}); if (this.viewport_.pinchPhase == Viewport.PinchPhase.PINCH_START) { var position = this.viewport_.position; @@ -777,8 +752,8 @@ // than the spec. In RTL layout, the zoom toolbar is on the left side, but // the scrollbar is still on the right, so this is not necessary. if (!isRTL()) { - this.zoomToolbar_.style.right = -verticalScrollbarWidth + - (scrollbarWidth / 2) + 'px'; + this.zoomToolbar_.style.right = + -verticalScrollbarWidth + (scrollbarWidth / 2) + 'px'; } // Having a horizontal scrollbar is much rarer so we don't offset the // toolbar from the bottom any more than what the spec says. This means @@ -890,8 +865,8 @@ grayscale: message.data.grayscale, // If the PDF isn't modifiable we send 0 as the page count so that no // blank placeholder pages get appended to the PDF. - pageCount: (message.data.modifiable ? - message.data.pageNumbers.length : 0) + pageCount: + (message.data.modifiable ? message.data.pageNumbers.length : 0) }); return true; case 'sendKeyEvent':
diff --git a/chrome/browser/resources/pdf/pdf_scripting_api.js b/chrome/browser/resources/pdf/pdf_scripting_api.js index 102130e..fd5e2e1 100644 --- a/chrome/browser/resources/pdf/pdf_scripting_api.js +++ b/chrome/browser/resources/pdf/pdf_scripting_api.js
@@ -39,11 +39,7 @@ * has finished loading or failed to load. * @enum {string} */ -var LoadState = { - LOADING: 'loading', - SUCCESS: 'success', - FAILED: 'failed' -}; +var LoadState = {LOADING: 'loading', SUCCESS: 'success', FAILED: 'failed'}; /** * Create a new PDFScriptingAPI. This provides a scripting interface to @@ -60,8 +56,8 @@ window.addEventListener('message', function(event) { if (event.origin != 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai' && event.origin != 'chrome://print') { - console.error('Received message that was not from the extension: ' + - event); + console.error( + 'Received message that was not from the extension: ' + event); return; } switch (event.data.type) { @@ -77,11 +73,9 @@ */ var viewportData = event.data; if (this.viewportChangedCallback_) - this.viewportChangedCallback_(viewportData.pageX, - viewportData.pageY, - viewportData.pageWidth, - viewportData.viewportWidth, - viewportData.viewportHeight); + this.viewportChangedCallback_( + viewportData.pageX, viewportData.pageY, viewportData.pageWidth, + viewportData.viewportWidth, viewportData.viewportHeight); break; case 'documentLoaded': var data = /** @type {{load_state: LoadState}} */ (event.data); @@ -119,20 +113,18 @@ this.pendingScriptingMessages_.push(message); }, - /** - * Sets the plugin element containing the PDF viewer. The element will usually - * be passed into the PDFScriptingAPI constructor but may also be set later. - * @param {Object} plugin the plugin element containing the PDF viewer. - */ + /** + * Sets the plugin element containing the PDF viewer. The element will usually + * be passed into the PDFScriptingAPI constructor but may also be set later. + * @param {Object} plugin the plugin element containing the PDF viewer. + */ setPlugin: function(plugin) { this.plugin_ = plugin; if (this.plugin_) { // Send a message to ensure the postMessage channel is initialized which // allows us to receive messages. - this.sendMessage_({ - type: 'initialize' - }); + this.sendMessage_({type: 'initialize'}); // Flush pending messages. while (this.pendingScriptingMessages_.length > 0) this.sendMessage_(this.pendingScriptingMessages_.shift()); @@ -190,11 +182,7 @@ * @param {number} index the index of the page to load. */ loadPreviewPage: function(url, index) { - this.sendMessage_({ - type: 'loadPreviewPage', - url: url, - index: index - }); + this.sendMessage_({type: 'loadPreviewPage', url: url, index: index}); }, /** @@ -202,9 +190,7 @@ * load. */ selectAll: function() { - this.sendMessage_({ - type: 'selectAll' - }); + this.sendMessage_({type: 'selectAll'}); }, /** @@ -218,9 +204,7 @@ if (this.selectedTextCallback_) return false; this.selectedTextCallback_ = callback; - this.sendMessage_({ - type: 'getSelectedText' - }); + this.sendMessage_({type: 'getSelectedText'}); return true; }, @@ -228,9 +212,7 @@ * Print the document. May only be called after document load. */ print: function() { - this.sendMessage_({ - type: 'print' - }); + this.sendMessage_({type: 'print'}); }, /** @@ -238,10 +220,8 @@ * @param {Event} keyEvent the key event to send to the extension. */ sendKeyEvent: function(keyEvent) { - this.sendMessage_({ - type: 'sendKeyEvent', - keyEvent: SerializeKeyEvent(keyEvent) - }); + this.sendMessage_( + {type: 'sendKeyEvent', keyEvent: SerializeKeyEvent(keyEvent)}); }, }; @@ -255,8 +235,8 @@ */ function PDFCreateOutOfProcessPlugin(src) { var client = new PDFScriptingAPI(window, null); - var iframe = assertInstanceof(window.document.createElement('iframe'), - HTMLIFrameElement); + var iframe = assertInstanceof( + window.document.createElement('iframe'), HTMLIFrameElement); iframe.setAttribute('src', 'pdf_preview.html?' + src); // Prevent the frame from being tab-focusable. iframe.setAttribute('tabindex', '-1');
diff --git a/chrome/browser/resources/pdf/viewport.js b/chrome/browser/resources/pdf/viewport.js index 6d027f1..54f166b 100644 --- a/chrome/browser/resources/pdf/viewport.js +++ b/chrome/browser/resources/pdf/viewport.js
@@ -9,9 +9,10 @@ * @return {number} the height of the intersection of the rects */ function getIntersectionHeight(rect1, rect2) { - return Math.max(0, + return Math.max( + 0, Math.min(rect1.y + rect1.height, rect2.y + rect2.height) - - Math.max(rect1.y, rect2.y)); + Math.max(rect1.y, rect2.y)); } /** @@ -30,10 +31,7 @@ * @return {!Object} The vector. */ function vectorDelta(p1, p2) { - return { - x: p2.x - p1.x, - y: p2.y - p1.y - }; + return {x: p2.x - p1.x, y: p2.y - p1.y}; } function frameToPluginCoordinate(coordinateInFrame) { @@ -58,14 +56,9 @@ * @param {number} topToolbarHeight The number of pixels that should initially * be left blank above the document for the toolbar. */ -function Viewport(window, - sizer, - viewportChangedCallback, - beforeZoomCallback, - afterZoomCallback, - scrollbarWidth, - defaultZoom, - topToolbarHeight) { +function Viewport( + window, sizer, viewportChangedCallback, beforeZoomCallback, + afterZoomCallback, scrollbarWidth, defaultZoom, topToolbarHeight) { this.window_ = window; this.sizer_ = sizer; this.viewportChangedCallback_ = viewportChangedCallback; @@ -127,8 +120,10 @@ * components/ui/zoom/page_zoom_constants.h and * chrome/browser/resources/settings/appearance_page/appearance_page.js */ -Viewport.ZOOM_FACTORS = [0.25, 1 / 3, 0.5, 2 / 3, 0.75, 0.8, 0.9, - 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5]; +Viewport.ZOOM_FACTORS = [ + 0.25, 1 / 3, 0.5, 2 / 3, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, + 4, 5 +]; /** * The minimum and maximum range to be used to clip zoom factor. @@ -141,7 +136,12 @@ /** * The width of the page shadow around pages in pixels. */ -Viewport.PAGE_SHADOW = {top: 3, bottom: 7, left: 5, right: 5}; +Viewport.PAGE_SHADOW = { + top: 3, + bottom: 7, + left: 5, + right: 5 +}; Viewport.prototype = { /** @@ -173,10 +173,7 @@ documentNeedsScrollbars_: function(zoom) { var zoomedDimensions = this.getZoomedDocumentDimensions_(zoom); if (!zoomedDimensions) { - return { - horizontal: false, - vertical: false - }; + return {horizontal: false, vertical: false}; } // If scrollbars are required for one direction, expand the document in the @@ -211,8 +208,8 @@ var zoomedDimensions = this.getZoomedDocumentDimensions_(this.zoom); if (zoomedDimensions) { this.sizer_.style.width = zoomedDimensions.width + 'px'; - this.sizer_.style.height = zoomedDimensions.height + - this.topToolbarHeight_ + 'px'; + this.sizer_.style.height = + zoomedDimensions.height + this.topToolbarHeight_ + 'px'; } }, @@ -329,7 +326,7 @@ setZoomInternal_: function(newZoom) { if (!this.allowedToChangeZoom_) { throw 'Called Viewport.setZoomInternal_ without calling ' + - 'Viewport.mightZoom_.'; + 'Viewport.mightZoom_.'; } // Record the scroll position (relative to the top-left of the window). var currentScrollPos = { @@ -353,9 +350,10 @@ * @param {!Object} center The pinch center in content coordinates. */ setPinchZoomInternal_: function(scaleDelta, center) { - assert(this.allowedToChangeZoom_, + assert( + this.allowedToChangeZoom_, 'Called Viewport.setPinchZoomInternal_ without calling ' + - 'Viewport.mightZoom_.'); + 'Viewport.mightZoom_.'); this.internalZoom_ = clampScale(this.internalZoom_ * scaleDelta); var newCenterInContent = this.frameToContent(center); @@ -372,10 +370,7 @@ this.contentSizeChanged_(); // Scroll to the scaled scroll position. - this.position = { - x: currentScrollPos.x, - y: currentScrollPos.y - }; + this.position = {x: currentScrollPos.x, y: currentScrollPos.y}; }, /** @@ -399,8 +394,9 @@ */ setZoom: function(newZoom) { this.fittingType_ = Viewport.FittingType.NONE; - newZoom = Math.max(Viewport.ZOOM_FACTOR_RANGE.min, - Math.min(newZoom, Viewport.ZOOM_FACTOR_RANGE.max)); + newZoom = Math.max( + Viewport.ZOOM_FACTOR_RANGE.min, + Math.min(newZoom, Viewport.ZOOM_FACTOR_RANGE.max)); this.mightZoom_(function() { this.setZoomInternal_(newZoom); this.updateViewport_(); @@ -461,8 +457,8 @@ top = this.pageDimensions_[page - 1].y + this.pageDimensions_[page - 1].height; } - var bottom = this.pageDimensions_[page].y + - this.pageDimensions_[page].height; + var bottom = + this.pageDimensions_[page].y + this.pageDimensions_[page].height; if (top <= y && bottom > y) return page; @@ -490,11 +486,13 @@ width: this.size.width / this.zoom, height: this.size.height / this.zoom }; - var firstVisiblePageVisibility = getIntersectionHeight( - this.pageDimensions_[firstVisiblePage], viewportRect) / + var firstVisiblePageVisibility = + getIntersectionHeight( + this.pageDimensions_[firstVisiblePage], viewportRect) / this.pageDimensions_[firstVisiblePage].height; - var nextPageVisibility = getIntersectionHeight( - this.pageDimensions_[firstVisiblePage + 1], viewportRect) / + var nextPageVisibility = + getIntersectionHeight( + this.pageDimensions_[firstVisiblePage + 1], viewportRect) / this.pageDimensions_[firstVisiblePage + 1].height; if (nextPageVisibility > firstVisiblePageVisibility) return firstVisiblePage + 1; @@ -573,8 +571,8 @@ return; // When computing fit-to-width, the maximum width of a page in the // document is used, which is equal to the size of the document width. - this.setZoomInternal_(this.computeFittingZoom_(this.documentDimensions_, - true)); + this.setZoomInternal_( + this.computeFittingZoom_(this.documentDimensions_, true)); var page = this.getMostVisiblePage(); this.updateViewport_(); }.bind(this)); @@ -600,10 +598,7 @@ }; this.setZoomInternal_(this.computeFittingZoom_(dimensions, false)); if (scrollToTopOfPage) { - this.position = { - x: 0, - y: this.pageDimensions_[page].y * this.zoom - }; + this.position = {x: 0, y: this.pageDimensions_[page].y * this.zoom}; } this.updateViewport_(); }.bind(this)); @@ -656,15 +651,15 @@ pinchZoom: function(e) { this.mightZoom_(function() { this.pinchPhase_ = e.direction == 'out' ? - Viewport.PinchPhase.PINCH_UPDATE_ZOOM_OUT : - Viewport.PinchPhase.PINCH_UPDATE_ZOOM_IN; + Viewport.PinchPhase.PINCH_UPDATE_ZOOM_OUT : + Viewport.PinchPhase.PINCH_UPDATE_ZOOM_IN; var scaleDelta = e.startScaleRatio / this.prevScale_; this.pinchPanVector_ = vectorDelta(e.center, this.firstPinchCenterInFrame_); - var needsScrollbars = this.documentNeedsScrollbars_( - this.zoomManager_.applyBrowserZoom( + var needsScrollbars = + this.documentNeedsScrollbars_(this.zoomManager_.applyBrowserZoom( clampScale(this.internalZoom_ * scaleDelta))); this.pinchCenter_ = e.center; @@ -686,8 +681,7 @@ this.keepContentCentered_ = false; } - this.setPinchZoomInternal_( - scaleDelta, frameToPluginCoordinate(e.center)); + this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center)); this.updateViewport_(); this.prevScale_ = e.startScaleRatio; }.bind(this)); @@ -712,8 +706,7 @@ var scaleDelta = e.startScaleRatio / this.prevScale_; this.pinchCenter_ = e.center; - this.setPinchZoomInternal_( - scaleDelta, frameToPluginCoordinate(e.center)); + this.setPinchZoomInternal_(scaleDelta, frameToPluginCoordinate(e.center)); this.updateViewport_(); }.bind(this)); @@ -760,13 +753,10 @@ this.documentDimensions_ = documentDimensions; this.pageDimensions_ = this.documentDimensions_.pageDimensions; if (initialDimensions) { - this.setZoomInternal_( - Math.min(this.defaultZoom_, - this.computeFittingZoom_(this.documentDimensions_, true))); - this.position = { - x: 0, - y: -this.topToolbarHeight_ - }; + this.setZoomInternal_(Math.min( + this.defaultZoom_, + this.computeFittingZoom_(this.documentDimensions_, true))); + this.position = {x: 0, y: -this.topToolbarHeight_}; } this.contentSizeChanged_(); this.resize_(); @@ -781,12 +771,7 @@ */ getPageScreenRect: function(page) { if (!this.documentDimensions_) { - return { - x: 0, - y: 0, - width: 0, - height: 0 - }; + return {x: 0, y: 0, width: 0, height: 0}; } if (page >= this.pageDimensions_.length) page = this.pageDimensions_.length - 1; @@ -810,8 +795,8 @@ Viewport.PAGE_SHADOW.left; // Compute the space on the left of the document if the document fits // completely in the screen. - var spaceOnLeft = (this.size.width - - this.documentDimensions_.width * this.zoom) / 2; + var spaceOnLeft = + (this.size.width - this.documentDimensions_.width * this.zoom) / 2; spaceOnLeft = Math.max(spaceOnLeft, 0); return {
diff --git a/chrome/browser/resources/pdf/viewport_scroller.js b/chrome/browser/resources/pdf/viewport_scroller.js index eeef839..8246e54 100644 --- a/chrome/browser/resources/pdf/viewport_scroller.js +++ b/chrome/browser/resources/pdf/viewport_scroller.js
@@ -44,9 +44,9 @@ */ startDragScrollTimer_: function() { if (this.timerId_ === null) { - this.timerId_ = - this.window_.setInterval(this.dragScrollPage_.bind(this), - ViewportScroller.DRAG_TIMER_INTERVAL_MS_); + this.timerId_ = this.window_.setInterval( + this.dragScrollPage_.bind(this), + ViewportScroller.DRAG_TIMER_INTERVAL_MS_); this.lastFrameTime_ = Date.now(); } }, @@ -71,7 +71,7 @@ var position = this.viewport_.position; var currentFrameTime = Date.now(); var timeAdjustment = (currentFrameTime - this.lastFrameTime_) / - ViewportScroller.DRAG_TIMER_INTERVAL_MS_; + ViewportScroller.DRAG_TIMER_INTERVAL_MS_; position.y += (this.scrollVelocity_.y * timeAdjustment); position.x += (this.scrollVelocity_.x * timeAdjustment); this.viewport_.position = position; @@ -86,18 +86,19 @@ * @return {Object} Object with x and y direction scroll velocity. */ calculateVelocity_: function(event) { - var x = Math.min(Math.max(-event.offsetX, - event.offsetX - this.plugin_.offsetWidth, 0), - ViewportScroller.MAX_DRAG_SCROLL_DISTANCE_) * - Math.sign(event.offsetX); - var y = Math.min(Math.max(-event.offsetY, - event.offsetY - this.plugin_.offsetHeight, 0), - ViewportScroller.MAX_DRAG_SCROLL_DISTANCE_) * - Math.sign(event.offsetY); - return { - x: x, - y: y - }; + var x = + Math.min( + Math.max( + -event.offsetX, event.offsetX - this.plugin_.offsetWidth, 0), + ViewportScroller.MAX_DRAG_SCROLL_DISTANCE_) * + Math.sign(event.offsetX); + var y = + Math.min( + Math.max( + -event.offsetY, event.offsetY - this.plugin_.offsetHeight, 0), + ViewportScroller.MAX_DRAG_SCROLL_DISTANCE_) * + Math.sign(event.offsetY); + return {x: x, y: y}; }, /** @@ -123,13 +124,13 @@ if (isSelecting) { if (!this.mousemoveCallback_) this.mousemoveCallback_ = this.onMousemove_.bind(this); - this.plugin_.addEventListener('mousemove', this.mousemoveCallback_, - false); + this.plugin_.addEventListener( + 'mousemove', this.mousemoveCallback_, false); } else { this.stopDragScrollTimer_(); if (this.mousemoveCallback_) { - this.plugin_.removeEventListener('mousemove', this.mousemoveCallback_, - false); + this.plugin_.removeEventListener( + 'mousemove', this.mousemoveCallback_, false); } } }
diff --git a/chrome/browser/resources/pdf/zoom_manager.js b/chrome/browser/resources/pdf/zoom_manager.js index 5ed2c74a..eec9115 100644 --- a/chrome/browser/resources/pdf/zoom_manager.js +++ b/chrome/browser/resources/pdf/zoom_manager.js
@@ -145,16 +145,16 @@ if (this.floatingPointEquals(this.browserZoom_, zoom)) return; - this.changingBrowserZoom_ = this.setBrowserZoomFunction_(zoom).then( - function() { - this.browserZoom_ = zoom; - this.changingBrowserZoom_ = null; + this.changingBrowserZoom_ = + this.setBrowserZoomFunction_(zoom).then(function() { + this.browserZoom_ = zoom; + this.changingBrowserZoom_ = null; - // The extension's zoom level may have changed while the browser zoom - // change was in progress. We call back into onPdfZoomChange to ensure the - // browser zoom is up to date. - this.onPdfZoomChange(); - }.bind(this)); + // The extension's zoom level may have changed while the browser zoom + // change was in progress. We call back into onPdfZoomChange to ensure + // the browser zoom is up to date. + this.onPdfZoomChange(); + }.bind(this)); } /**
diff --git a/chrome/browser/resources/print_preview/cloud_print_interface.js b/chrome/browser/resources/print_preview/cloud_print_interface.js index 4c40894b..cce11fc6 100644 --- a/chrome/browser/resources/print_preview/cloud_print_interface.js +++ b/chrome/browser/resources/print_preview/cloud_print_interface.js
@@ -14,8 +14,7 @@ PRINTER_DONE: 'cloudprint.CloudPrintInterface.PRINTER_DONE', PRINTER_FAILED: 'cloudprint.CloudPrintInterface.PRINTER_FAILED', PROCESS_INVITE_DONE: 'cloudprint.CloudPrintInterface.PROCESS_INVITE_DONE', - PROCESS_INVITE_FAILED: - 'cloudprint.CloudPrintInterface.PROCESS_INVITE_FAILED', + PROCESS_INVITE_FAILED: 'cloudprint.CloudPrintInterface.PROCESS_INVITE_FAILED', SEARCH_DONE: 'cloudprint.CloudPrintInterface.SEARCH_DONE', SEARCH_FAILED: 'cloudprint.CloudPrintInterface.SEARCH_FAILED', SUBMIT_DONE: 'cloudprint.CloudPrintInterface.SUBMIT_DONE', @@ -153,9 +152,7 @@ * @enum {string} * @private */ - CloudPrintInterface.JsonFields_ = { - PRINTER: 'printer' - }; + CloudPrintInterface.JsonFields_ = {PRINTER: 'printer'}; /** * Could Print origins used to search printers. @@ -164,10 +161,10 @@ * @private */ CloudPrintInterface.CLOUD_ORIGINS_ = [ - print_preview.DestinationOrigin.COOKIES, - print_preview.DestinationOrigin.DEVICE - // TODO(vitalybuka): Enable when implemented. - // ready print_preview.DestinationOrigin.PROFILE + print_preview.DestinationOrigin.COOKIES, + print_preview.DestinationOrigin.DEVICE + // TODO(vitalybuka): Enable when implemented. + // ready print_preview.DestinationOrigin.PROFILE ]; CloudPrintInterface.prototype = { @@ -221,19 +218,14 @@ search_: function(isRecent, account, origins) { var params = [ new HttpParam('connection_status', 'ALL'), - new HttpParam('client', 'chrome'), - new HttpParam('use_cdd', 'true') + new HttpParam('client', 'chrome'), new HttpParam('use_cdd', 'true') ]; if (isRecent) { params.push(new HttpParam('q', '^recent')); } origins.forEach(function(origin) { var cpRequest = this.buildRequest_( - 'GET', - 'search', - params, - origin, - account, + 'GET', 'search', params, origin, account, this.onSearchDone_.bind(this, isRecent)); this.outstandingCloudSearchRequests_.push(cpRequest); this.sendOrQueueRequest_(cpRequest); @@ -249,12 +241,8 @@ new HttpParam('client', 'chrome'), ]; this.sendOrQueueRequest_(this.buildRequest_( - 'GET', - 'invites', - params, - print_preview.DestinationOrigin.COOKIES, - account, - this.onInvitesDone_.bind(this))); + 'GET', 'invites', params, print_preview.DestinationOrigin.COOKIES, + account, this.onInvitesDone_.bind(this))); }, /** @@ -270,10 +258,7 @@ new HttpParam('use_cdd', 'true'), ]; this.sendOrQueueRequest_(this.buildRequest_( - 'POST', - 'processinvite', - params, - invitation.destination.origin, + 'POST', 'processinvite', params, invitation.destination.origin, invitation.destination.account, this.onProcessInviteDone_.bind(this, invitation, accept))); }, @@ -298,19 +283,14 @@ new HttpParam('printerid', destination.id), new HttpParam('contentType', 'dataUrl'), new HttpParam('title', documentInfo.title), - new HttpParam('ticket', - printTicketStore.createPrintTicket(destination)), + new HttpParam( + 'ticket', printTicketStore.createPrintTicket(destination)), new HttpParam('content', 'data:application/pdf;base64,' + data), - new HttpParam('tag', - '__google__chrome_version=' + chromeVersion), + new HttpParam('tag', '__google__chrome_version=' + chromeVersion), new HttpParam('tag', '__google__os=' + navigator.platform) ]; var cpRequest = this.buildRequest_( - 'POST', - 'submit', - params, - destination.origin, - destination.account, + 'POST', 'submit', params, destination.origin, destination.account, this.onSubmitDone_.bind(this)); this.sendOrQueueRequest_(cpRequest); }, @@ -327,16 +307,11 @@ */ printer: function(printerId, origin, account) { var params = [ - new HttpParam('printerid', printerId), - new HttpParam('use_cdd', 'true'), + new HttpParam('printerid', printerId), new HttpParam('use_cdd', 'true'), new HttpParam('printer_connection_status', 'true') ]; this.sendOrQueueRequest_(this.buildRequest_( - 'GET', - 'printer', - params, - origin, - account || '', + 'GET', 'printer', params, origin, account || '', this.onPrinterDone_.bind(this, printerId))); }, @@ -409,14 +384,13 @@ var xhr = new XMLHttpRequest(); xhr.open(method, url, true); - xhr.withCredentials = - (origin == print_preview.DestinationOrigin.COOKIES); + xhr.withCredentials = (origin == print_preview.DestinationOrigin.COOKIES); for (var header in headers) { xhr.setRequestHeader(header, headers[header]); } - return new cloudprint.CloudPrintRequest(xhr, body, origin, account, - callback); + return new cloudprint.CloudPrintRequest( + xhr, body, origin, account, callback); }, /** @@ -516,8 +490,8 @@ return true; } if (event.accessToken) { - request.xhr.setRequestHeader('Authorization', - 'Bearer ' + event.accessToken); + request.xhr.setRequestHeader( + 'Authorization', 'Bearer ' + event.accessToken); this.sendRequest_(request); } else { // No valid token. // Without abort status does not exist. @@ -537,8 +511,8 @@ onReadyStateChange_: function(request) { if (request.xhr.readyState == 4) { if (request.xhr.status == 200) { - request.result = /** @type {Object} */ ( - JSON.parse(request.xhr.responseText)); + request.result = + /** @type {Object} */ (JSON.parse(request.xhr.responseText)); if (request.origin == print_preview.DestinationOrigin.COOKIES && request.result['success']) { this.xsrfTokens_[request.result['request']['user']] = @@ -569,9 +543,7 @@ }); var activeUser = ''; if (request.origin == print_preview.DestinationOrigin.COOKIES) { - activeUser = - request.result && - request.result['request'] && + activeUser = request.result && request.result['request'] && request.result['request']['user']; } var event = null; @@ -596,8 +568,7 @@ event.isRecent = isRecent; } else { event = this.createErrorEvent_( - CloudPrintInterfaceEventType.SEARCH_FAILED, - request); + CloudPrintInterfaceEventType.SEARCH_FAILED, request); } event.user = activeUser; event.searchDone = lastRequestForThisOrigin; @@ -612,18 +583,17 @@ */ onInvitesDone_: function(request) { var event = null; - var activeUser = - (request.result && - request.result['request'] && - request.result['request']['user']) || ''; + var activeUser = (request.result && request.result['request'] && + request.result['request']['user']) || + ''; if (request.xhr.status == 200 && request.result['success']) { // Extract invitations. var invitationListJson = request.result['invites'] || []; var invitationList = []; invitationListJson.forEach(function(invitationJson) { try { - invitationList.push(cloudprint.InvitationParser.parse( - invitationJson, activeUser)); + invitationList.push( + cloudprint.InvitationParser.parse(invitationJson, activeUser)); } catch (e) { console.error('Unable to parse invitation: ' + e); } @@ -649,10 +619,9 @@ */ onProcessInviteDone_: function(invitation, accept, request) { var event = null; - var activeUser = - (request.result && - request.result['request'] && - request.result['request']['user']) || ''; + var activeUser = (request.result && request.result['request'] && + request.result['request']['user']) || + ''; if (request.xhr.status == 200 && request.result['success']) { event = new Event(CloudPrintInterfaceEventType.PROCESS_INVITE_DONE); if (accept) { @@ -681,8 +650,8 @@ */ onSubmitDone_: function(request) { if (request.xhr.status == 200 && request.result['success']) { - var submitDoneEvent = new Event( - CloudPrintInterfaceEventType.SUBMIT_DONE); + var submitDoneEvent = + new Event(CloudPrintInterfaceEventType.SUBMIT_DONE); submitDoneEvent.jobId = request.result['job']['id']; this.dispatchEvent(submitDoneEvent); } else { @@ -703,8 +672,7 @@ // Special handling of the first printer request. It does not matter at // this point, whether printer was found or not. if (request.origin == print_preview.DestinationOrigin.COOKIES && - request.result && - request.account && + request.result && request.account && request.result['request']['user'] && request.result['request']['users'] && request.account != request.result['request']['user']) { @@ -715,8 +683,7 @@ this.userInfo_.activeUser = request.account; // Repeat the request for the newly activated account. this.printer( - request.result['request']['params']['printerid'], - request.origin, + request.result['request']['params']['printerid'], request.origin, request.account); // Stop processing this request, wait for the new response. return; @@ -734,7 +701,8 @@ printer = cloudprint.CloudDestinationParser.parse( printerJson, request.origin, activeUser); } catch (err) { - console.error('Failed to parse cloud print destination: ' + + console.error( + 'Failed to parse cloud print destination: ' + JSON.stringify(printerJson)); return; }
diff --git a/chrome/browser/resources/print_preview/common/overlay.js b/chrome/browser/resources/print_preview/common/overlay.js index 9ff7f753..dc08306 100644 --- a/chrome/browser/resources/print_preview/common/overlay.js +++ b/chrome/browser/resources/print_preview/common/overlay.js
@@ -37,7 +37,8 @@ this.cancel(); } else if (e.keyCode == 13) { var activeElementTag = document.activeElement ? - document.activeElement.tagName.toUpperCase() : ''; + document.activeElement.tagName.toUpperCase() : + ''; if (activeElementTag != 'BUTTON' && activeElementTag != 'SELECT') { if (this.onEnterPressedInternal()) { e.stopPropagation(); @@ -49,15 +50,13 @@ }.bind(this)); this.tracker.add( - this.getChildElement('.page > .close-button'), - 'click', + this.getChildElement('.page > .close-button'), 'click', this.cancel.bind(this)); this.tracker.add( this.getElement(), 'click', this.onOverlayClick_.bind(this)); this.tracker.add( - this.getChildElement('.page'), - 'animationend', + this.getChildElement('.page'), 'animationend', this.onAnimationEnd_.bind(this)); }, @@ -126,7 +125,5 @@ }; // Export - return { - Overlay: Overlay - }; + return {Overlay: Overlay}; });
diff --git a/chrome/browser/resources/print_preview/common/search_box.js b/chrome/browser/resources/print_preview/common/search_box.js index c94fd09f..d8db6929 100644 --- a/chrome/browser/resources/print_preview/common/search_box.js +++ b/chrome/browser/resources/print_preview/common/search_box.js
@@ -24,7 +24,7 @@ * Timeout used to control incremental search. * @private {?number} */ - this.timeout_ = null; + this.timeout_ = null; /** * Input box where the query is entered. @@ -37,9 +37,7 @@ * Enumeration of event types dispatched from the search box. * @enum {string} */ - SearchBox.EventType = { - SEARCH: 'print_preview.SearchBox.SEARCH' - }; + SearchBox.EventType = {SEARCH: 'print_preview.SearchBox.SEARCH'}; /** * Delay in milliseconds before dispatching a SEARCH event. @@ -64,18 +62,18 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'search-box-template')); - this.input_ = assertInstanceof(this.getChildElement('.search-box-input'), - HTMLInputElement); + this.setElementInternal( + this.cloneTemplateInternal('search-box-template')); + this.input_ = assertInstanceof( + this.getChildElement('.search-box-input'), HTMLInputElement); this.input_.setAttribute('placeholder', this.searchBoxPlaceholderText_); }, /** @override */ enterDocument: function() { print_preview.Component.prototype.enterDocument.call(this); - this.tracker.add(assert(this.input_), 'input', - this.onInputInput_.bind(this)); + this.tracker.add( + assert(this.input_), 'input', this.onInputInput_.bind(this)); }, /** @override */ @@ -124,7 +122,5 @@ }; // Export - return { - SearchBox: SearchBox - }; + return {SearchBox: SearchBox}; });
diff --git a/chrome/browser/resources/print_preview/common/search_bubble.js b/chrome/browser/resources/print_preview/common/search_bubble.js index 9f85bc4..ab78aa57 100644 --- a/chrome/browser/resources/print_preview/common/search_bubble.js +++ b/chrome/browser/resources/print_preview/common/search_bubble.js
@@ -91,8 +91,8 @@ return; // Position the bubble below the location of the owner. - var left = owner.offsetLeft + owner.offsetWidth / 2 - - this.offsetWidth / 2; + var left = + owner.offsetLeft + owner.offsetWidth / 2 - this.offsetWidth / 2; var top = owner.offsetTop + owner.offsetHeight; // Update the position in the CSS. Cache the last values for @@ -109,7 +109,5 @@ }; // Export - return { - SearchBubble: SearchBubble - }; + return {SearchBubble: SearchBubble}; });
diff --git a/chrome/browser/resources/print_preview/component.js b/chrome/browser/resources/print_preview/component.js index 13a7a2f2..02109b85 100644 --- a/chrome/browser/resources/print_preview/component.js +++ b/chrome/browser/resources/print_preview/component.js
@@ -25,13 +25,13 @@ * Component's event tracker. * @private {!EventTracker} */ - this.tracker_ = new EventTracker(); + this.tracker_ = new EventTracker(); /** * Component's WebUI listener tracker. * @private {!WebUIListenerTracker} */ - this.listenerTracker_ = new WebUIListenerTracker(); + this.listenerTracker_ = new WebUIListenerTracker(); /** * Child components of the component. @@ -203,8 +203,8 @@ */ cloneTemplateInternal: function(templateId, opt_keepHidden) { var templateEl = $(templateId); - assert(templateEl != null, - 'Could not find element with ID: ' + templateId); + assert( + templateEl != null, 'Could not find element with ID: ' + templateId); var el = assertInstanceof(templateEl.cloneNode(true), HTMLElement); el.id = ''; if (!opt_keepHidden) { @@ -214,7 +214,5 @@ } }; - return { - Component: Component - }; + return {Component: Component}; });
diff --git a/chrome/browser/resources/print_preview/data/app_state.js b/chrome/browser/resources/print_preview/data/app_state.js index 4846941c..6bc3976 100644 --- a/chrome/browser/resources/print_preview/data/app_state.js +++ b/chrome/browser/resources/print_preview/data/app_state.js
@@ -132,8 +132,8 @@ * which is currently the selected destination. */ get selectedDestination() { - return (this.state_[print_preview.AppStateField.RECENT_DESTINATIONS]. - length > 0) ? + return (this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] + .length > 0) ? this.state_[print_preview.AppStateField.RECENT_DESTINATIONS][0] : null; }, @@ -142,9 +142,8 @@ * @return {boolean} Whether the selected destination is valid. */ isSelectedDestinationValid: function() { - return !!this.selectedDestination && - !!this.selectedDestination.id && - !!this.selectedDestination.origin; + return !!this.selectedDestination && !!this.selectedDestination.id && + !!this.selectedDestination.origin; }, /** @@ -176,7 +175,8 @@ getField: function(field) { if (field == print_preview.AppStateField.CUSTOM_MARGINS) { return this.state_[field] ? - print_preview.Margins.parse(this.state_[field]) : null; + print_preview.Margins.parse(this.state_[field]) : + null; } else { return this.state_[field]; } @@ -193,9 +193,9 @@ try { var state = JSON.parse(serializedAppStateStr); if (state[print_preview.AppStateField.VERSION] == AppState.VERSION_) { - this.state_ = /** @type {Object} */(state); + this.state_ = /** @type {Object} */ (state); } - } catch(e) { + } catch (e) { console.error('Unable to parse state: ' + e); // Proceed with default state. } @@ -206,17 +206,19 @@ } if (!this.state_[print_preview.AppStateField.RECENT_DESTINATIONS]) { this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] = []; - } else if (!(this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] - instanceof Array)) { + } else if (!(this.state_[print_preview.AppStateField + .RECENT_DESTINATIONS] instanceof + Array)) { var tmp = this.state_[print_preview.AppStateField.RECENT_DESTINATIONS]; this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] = [tmp]; - } else if (!this.state_[ - print_preview.AppStateField.RECENT_DESTINATIONS][0] || + } else if ( + !this.state_[print_preview.AppStateField.RECENT_DESTINATIONS][0] || !this.state_[print_preview.AppStateField.RECENT_DESTINATIONS][0].id) { // read in incorrectly this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] = []; - } else if (this.state_[print_preview.AppStateField.RECENT_DESTINATIONS]. - length > AppState.NUM_DESTINATIONS_) { + } else if ( + this.state_[print_preview.AppStateField.RECENT_DESTINATIONS].length > + AppState.NUM_DESTINATIONS_) { this.state_[print_preview.AppStateField.RECENT_DESTINATIONS].length = AppState.NUM_DESTINATIONS_; } @@ -256,11 +258,12 @@ // Determine if this destination is already in the recent destinations, // and where in the array it is located. var newDestination = new RecentDestination(dest); - var indexFound = this.state_[ - print_preview.AppStateField.RECENT_DESTINATIONS].findIndex( - function(recent) { - return (newDestination.id == recent.id && - newDestination.origin == recent.origin); + var indexFound = + this.state_[print_preview.AppStateField.RECENT_DESTINATIONS] + .findIndex(function(recent) { + return ( + newDestination.id == recent.id && + newDestination.origin == recent.origin); }); // No change @@ -273,7 +276,7 @@ // index n. if (indexFound == -1 && this.state_[print_preview.AppStateField.RECENT_DESTINATIONS].length == - AppState.NUM_DESTINATIONS_) { + AppState.NUM_DESTINATIONS_) { indexFound = AppState.NUM_DESTINATIONS_ - 1; } if (indexFound != -1) @@ -305,12 +308,10 @@ * @private */ persist_: function() { - chrome.send(AppState.NATIVE_FUNCTION_NAME_, - [JSON.stringify(this.state_)]); + chrome.send( + AppState.NATIVE_FUNCTION_NAME_, [JSON.stringify(this.state_)]); } }; - return { - AppState: AppState - }; + return {AppState: AppState}; });
diff --git a/chrome/browser/resources/print_preview/data/capabilities_holder.js b/chrome/browser/resources/print_preview/data/capabilities_holder.js index ffa0f897..1201ae2d 100644 --- a/chrome/browser/resources/print_preview/data/capabilities_holder.js +++ b/chrome/browser/resources/print_preview/data/capabilities_holder.js
@@ -34,7 +34,5 @@ }; // Export - return { - CapabilitiesHolder: CapabilitiesHolder - }; + return {CapabilitiesHolder: CapabilitiesHolder}; });
diff --git a/chrome/browser/resources/print_preview/data/cloud_parsers.js b/chrome/browser/resources/print_preview/data/cloud_parsers.js index 83d62136..24ab1b0 100644 --- a/chrome/browser/resources/print_preview/data/cloud_parsers.js +++ b/chrome/browser/resources/print_preview/data/cloud_parsers.js
@@ -77,8 +77,9 @@ account: account, tags: tags, isOwned: arrayContains(tags, CloudDestinationParser.OWNED_TAG_), - lastAccessTime: parseInt( - json[CloudDestinationParser.Field_.LAST_ACCESS], 10) || Date.now(), + lastAccessTime: + parseInt(json[CloudDestinationParser.Field_.LAST_ACCESS], 10) || + Date.now(), cloudID: id, description: json[CloudDestinationParser.Field_.DESCRIPTION] }; @@ -86,13 +87,11 @@ id, CloudDestinationParser.parseType_( json[CloudDestinationParser.Field_.TYPE]), - origin, - json[CloudDestinationParser.Field_.DISPLAY_NAME], + origin, json[CloudDestinationParser.Field_.DISPLAY_NAME], arrayContains(tags, CloudDestinationParser.RECENT_TAG_) /*isRecent*/, - connectionStatus, - optionalParams); + connectionStatus, optionalParams); if (json.hasOwnProperty(CloudDestinationParser.Field_.CAPABILITIES)) { - cloudDest.capabilities = /** @type {!print_preview.Cdd} */( + cloudDest.capabilities = /** @type {!print_preview.Cdd} */ ( json[CloudDestinationParser.Field_.CAPABILITIES]); } return cloudDest; @@ -124,23 +123,16 @@ * @enum {string} * @private */ - InvitationParser.Field_ = { - PRINTER: 'printer', - RECEIVER: 'receiver', - SENDER: 'sender' - }; + InvitationParser + .Field_ = {PRINTER: 'printer', RECEIVER: 'receiver', SENDER: 'sender'}; /** * Enumeration of cloud destination types that are supported by print preview. * @enum {string} * @private */ - InvitationParser.AclType_ = { - DOMAIN: 'DOMAIN', - GROUP: 'GROUP', - PUBLIC: 'PUBLIC', - USER: 'USER' - }; + InvitationParser.AclType_ = + {DOMAIN: 'DOMAIN', GROUP: 'GROUP', PUBLIC: 'PUBLIC', USER: 'USER'}; /** * Parses printer sharing invitation from JSON from GCP invite API response. @@ -167,8 +159,9 @@ var receiverType = receiver['type']; if (receiverType == InvitationParser.AclType_.USER) { // It's a personal invitation, empty name indicates just that. - } else if (receiverType == InvitationParser.AclType_.GROUP || - receiverType == InvitationParser.AclType_.DOMAIN) { + } else if ( + receiverType == InvitationParser.AclType_.GROUP || + receiverType == InvitationParser.AclType_.DOMAIN) { receiverName = nameFormatter(receiver['name'], receiver['scope']); } else { throw Error('Invitation of unsupported receiver type'); @@ -176,8 +169,7 @@ var destination = cloudprint.CloudDestinationParser.parse( json[InvitationParser.Field_.PRINTER], - print_preview.DestinationOrigin.COOKIES, - account); + print_preview.DestinationOrigin.COOKIES, account); return new print_preview.Invitation( senderName, receiverName, destination, receiver, account);
diff --git a/chrome/browser/resources/print_preview/data/coordinate2d.js b/chrome/browser/resources/print_preview/data/coordinate2d.js index 7352af77..b336f74 100644 --- a/chrome/browser/resources/print_preview/data/coordinate2d.js +++ b/chrome/browser/resources/print_preview/data/coordinate2d.js
@@ -63,14 +63,10 @@ * @return {boolean} Whether another point is equal to this one. */ equals: function(other) { - return other != null && - this.x_ == other.x_ && - this.y_ == other.y_; + return other != null && this.x_ == other.x_ && this.y_ == other.y_; } }; // Export - return { - Coordinate2d: Coordinate2d - }; + return {Coordinate2d: Coordinate2d}; });
diff --git a/chrome/browser/resources/print_preview/data/destination.js b/chrome/browser/resources/print_preview/data/destination.js index c8595eb0..37f25bec 100644 --- a/chrome/browser/resources/print_preview/data/destination.js +++ b/chrome/browser/resources/print_preview/data/destination.js
@@ -122,8 +122,8 @@ * for the destination. * @constructor */ - function Destination(id, type, origin, displayName, isRecent, - connectionStatus, opt_params) { + function Destination( + id, type, origin, displayName, isRecent, connectionStatus, opt_params) { /** * ID of the destination. * @private {string} @@ -208,8 +208,8 @@ * accessed. * @private {number} */ - this.lastAccessTime_ = (opt_params && opt_params.lastAccessTime) || - Date.now(); + this.lastAccessTime_ = + (opt_params && opt_params.lastAccessTime) || Date.now(); /** * Cloud ID for Privet printers. @@ -240,12 +240,13 @@ * @private {print_preview.DestinationProvisionalType} */ this.provisionalType_ = (opt_params && opt_params.provisionalType) || - print_preview.DestinationProvisionalType.NONE; + print_preview.DestinationProvisionalType.NONE; - assert(this.provisionalType_ != - print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION || - this.isExtension, - 'Provisional USB destination only supprted with extension origin.'); + assert( + this.provisionalType_ != + print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION || + this.isExtension, + 'Provisional USB destination only supprted with extension origin.'); } /** @@ -253,10 +254,8 @@ * @type {!Array<string>} * @const */ - Destination.LOCATION_TAG_PREFIXES = [ - '__cp__location=', - '__cp__printer-location=' - ]; + Destination.LOCATION_TAG_PREFIXES = + ['__cp__location=', '__cp__printer-location=']; /** * Enumeration of Google-promoted destination IDs. @@ -337,11 +336,11 @@ /** @return {boolean} Whether the destination is local or cloud-based. */ get isLocal() { return this.origin_ == print_preview.DestinationOrigin.LOCAL || - this.origin_ == print_preview.DestinationOrigin.EXTENSION || - this.origin_ == print_preview.DestinationOrigin.CROS || - (this.origin_ == print_preview.DestinationOrigin.PRIVET && - this.connectionStatus_ != - print_preview.DestinationConnectionStatus.UNREGISTERED); + this.origin_ == print_preview.DestinationOrigin.EXTENSION || + this.origin_ == print_preview.DestinationOrigin.CROS || + (this.origin_ == print_preview.DestinationOrigin.PRIVET && + this.connectionStatus_ != + print_preview.DestinationConnectionStatus.UNREGISTERED); }, /** @return {boolean} Whether the destination is a Privet local printer */ @@ -452,9 +451,12 @@ /** @return {boolean} Whether the destination is considered offline. */ get isOffline() { - return arrayContains([print_preview.DestinationConnectionStatus.OFFLINE, - print_preview.DestinationConnectionStatus.DORMANT], - this.connectionStatus_); + return arrayContains( + [ + print_preview.DestinationConnectionStatus.OFFLINE, + print_preview.DestinationConnectionStatus.DORMANT + ], + this.connectionStatus_); }, /** @return {string} Human readable status for offline destination. */ @@ -498,8 +500,7 @@ if (this.isLocal) { return Destination.IconUrl_.LOCAL; } - if (this.type_ == print_preview.DestinationType.MOBILE && - this.isOwned_) { + if (this.type_ == print_preview.DestinationType.MOBILE && this.isOwned_) { return Destination.IconUrl_.MOBILE; } if (this.type_ == print_preview.DestinationType.MOBILE) { @@ -547,7 +548,7 @@ */ get isProvisional() { return this.provisionalType_ != - print_preview.DestinationProvisionalType.NONE; + print_preview.DestinationProvisionalType.NONE; }, /**
diff --git a/chrome/browser/resources/print_preview/data/destination_match.js b/chrome/browser/resources/print_preview/data/destination_match.js index 6a87f681..3152abe 100644 --- a/chrome/browser/resources/print_preview/data/destination_match.js +++ b/chrome/browser/resources/print_preview/data/destination_match.js
@@ -18,7 +18,6 @@ */ function DestinationMatch( origins, idRegExp, displayNameRegExp, skipVirtualDestinations) { - /** @private {!Array<!print_preview.DestinationOrigin>} */ this.origins_ = origins; @@ -48,9 +47,8 @@ * @return {boolean} Whether destination is the same as initial. */ matchIdAndOrigin: function(id, origin) { - return this.matchOrigin(origin) && - !!this.idRegExp_ && - this.idRegExp_.test(id); + return this.matchOrigin(origin) && !!this.idRegExp_ && + this.idRegExp_.test(id); }, /** @@ -89,13 +87,10 @@ destination.id); } return arrayContains( - [print_preview.Destination.GooglePromotedId.DOCS], - destination.id); + [print_preview.Destination.GooglePromotedId.DOCS], destination.id); } }; // Export - return { - DestinationMatch: DestinationMatch - }; + return {DestinationMatch: DestinationMatch}; });
diff --git a/chrome/browser/resources/print_preview/data/destination_store.js b/chrome/browser/resources/print_preview/data/destination_store.js index a52b6d0..dd5027e7 100644 --- a/chrome/browser/resources/print_preview/data/destination_store.js +++ b/chrome/browser/resources/print_preview/data/destination_store.js
@@ -189,8 +189,7 @@ 'print_preview.DestinationStore.PROVISIONAL_DESTINATION_RESOLVED', CACHED_SELECTED_DESTINATION_INFO_READY: 'print_preview.DestinationStore.CACHED_SELECTED_DESTINATION_INFO_READY', - SELECTED_DESTINATION_CAPABILITIES_READY: - 'print_preview.DestinationStore' + + SELECTED_DESTINATION_CAPABILITIES_READY: 'print_preview.DestinationStore' + '.SELECTED_DESTINATION_CAPABILITIES_READY', }; @@ -402,10 +401,8 @@ for (var i = 0, media; (media = mediaSize.option[i]); i++) { // No need to patch capabilities with localized names provided. if (!media.custom_display_name_localized) { - media.custom_display_name = - media.custom_display_name || - DestinationStore.MEDIA_DISPLAY_NAMES_[media.name] || - media.name; + media.custom_display_name = media.custom_display_name || + DestinationStore.MEDIA_DISPLAY_NAMES_[media.name] || media.name; } } return capabilities; @@ -457,9 +454,10 @@ var category; if (name.startsWith('NA_')) { category = categoryStandardNA; - } else if (name.startsWith('PRC_') || name.startsWith('ROC_') || - name == 'OM_DAI_PA_KAI' || name == 'OM_JUURO_KU_KAI' || - name == 'OM_PA_KAI') { + } else if ( + name.startsWith('PRC_') || name.startsWith('ROC_') || + name == 'OM_DAI_PA_KAI' || name == 'OM_JUURO_KU_KAI' || + name == 'OM_PA_KAI') { category = categoryStandardCN; } else if (name.startsWith('ISO_')) { category = categoryStandardISO; @@ -484,8 +482,9 @@ // Then put it all back together. mediaSize.option = categoryStandardNA; - mediaSize.option.push(...categoryStandardCN, ...categoryStandardISO, - ...categoryStandardJP, ...categoryStandardMisc, ...categoryCustom); + mediaSize.option.push( + ...categoryStandardCN, ...categoryStandardISO, ...categoryStandardJP, + ...categoryStandardMisc, ...categoryCustom); return capabilities; }; @@ -526,8 +525,8 @@ */ get isLocalDestinationSearchInProgress() { return this.isLocalDestinationSearchInProgress_ || - this.isPrivetDestinationSearchInProgress_ || - this.isExtensionDestinationSearchInProgress_; + this.isPrivetDestinationSearchInProgress_ || + this.isExtensionDestinationSearchInProgress_; }, /** @@ -535,7 +534,7 @@ */ get isCloudDestinationSearchInProgress() { return !!this.cloudPrintInterface_ && - this.cloudPrintInterface_.isCloudDestinationSearchInProgress; + this.cloudPrintInterface_.isCloudDestinationSearchInProgress; }, /** @@ -551,8 +550,7 @@ * default destination selection rules. */ init: function( - isInAppKioskMode, - systemDefaultDestinationId, + isInAppKioskMode, systemDefaultDestinationId, serializedDefaultDestinationSelectionRulesStr) { this.pdfPrinterEnabled_ = !isInAppKioskMode; this.systemDefaultDestinationId_ = systemDefaultDestinationId; @@ -593,13 +591,11 @@ account = this.appState_.recentDestinations[i].account || ''; name = this.appState_.recentDestinations[i].name || ''; capabilities = this.appState_.recentDestinations[i].capabilities; - extensionId = this.appState_.recentDestinations[i].extensionId || - ''; + extensionId = this.appState_.recentDestinations[i].extensionId || ''; extensionName = this.appState_.recentDestinations[i].extensionName || ''; - var candidate = - this.destinationMap_[this.getDestinationKey_(origin, - id, account)]; + var candidate = this.destinationMap_[this.getDestinationKey_( + origin, id, account)]; if (candidate != null) { if (!foundDestination) this.selectDestination(candidate); @@ -607,17 +603,13 @@ foundDestination = true; } else if (!foundDestination) { foundDestination = this.fetchPreselectedDestination_( - origin, - id, - account, - name, - capabilities, - extensionId, - extensionName); + origin, id, account, name, capabilities, extensionId, + extensionName); } } } - if (foundDestination) return; + if (foundDestination) + return; // Try the system default id = this.systemDefaultDestinationId_ || ''; @@ -633,12 +625,7 @@ } if (this.fetchPreselectedDestination_( - origin, - id, - account, - name, - capabilities, - extensionId, + origin, id, account, name, capabilities, extensionId, extensionName)) { return; } @@ -671,9 +658,9 @@ origin == print_preview.DestinationOrigin.CROS) { this.nativeLayer_.getPrinterCapabilities(id).then( this.onLocalDestinationCapabilitiesSet_.bind(this), - this.onGetCapabilitiesFail_.bind(this, - /** @type {print_preview.DestinationOrigin} */ (origin), - id)); + this.onGetCapabilitiesFail_.bind( + this, + /** @type {print_preview.DestinationOrigin} */ (origin), id)); return true; } @@ -682,8 +669,7 @@ origin == print_preview.DestinationOrigin.DEVICE)) { this.cloudPrintInterface_.printer( id, - /** @type {print_preview.DestinationOrigin} */(origin), - account); + /** @type {print_preview.DestinationOrigin} */ (origin), account); return true; } @@ -697,11 +683,8 @@ // destination store. When the real destination is created, this // destination will be overwritten. this.selectedDestination_ = new print_preview.Destination( - id, - print_preview.DestinationType.LOCAL, - print_preview.DestinationOrigin.PRIVET, - name, - false /*isRecent*/, + id, print_preview.DestinationType.LOCAL, + print_preview.DestinationOrigin.PRIVET, name, false /*isRecent*/, print_preview.DestinationConnectionStatus.ONLINE); if (capabilities) { @@ -750,26 +733,24 @@ fetchMatchingDestination_: function(destinationMatch) { this.autoSelectMatchingDestination_ = destinationMatch; - if (destinationMatch.matchOrigin( - print_preview.DestinationOrigin.LOCAL) || - destinationMatch.matchOrigin( - print_preview.DestinationOrigin.CROS)) { + if (destinationMatch.matchOrigin(print_preview.DestinationOrigin.LOCAL) || + destinationMatch.matchOrigin(print_preview.DestinationOrigin.CROS)) { this.startLoadLocalDestinations(); } if (destinationMatch.matchOrigin( - print_preview.DestinationOrigin.PRIVET)) { + print_preview.DestinationOrigin.PRIVET)) { this.startLoadPrivetDestinations(); } if (destinationMatch.matchOrigin( - print_preview.DestinationOrigin.EXTENSION)) { + print_preview.DestinationOrigin.EXTENSION)) { this.startLoadExtensionDestinations(); } if (destinationMatch.matchOrigin( - print_preview.DestinationOrigin.COOKIES) || + print_preview.DestinationOrigin.COOKIES) || destinationMatch.matchOrigin( - print_preview.DestinationOrigin.DEVICE) || + print_preview.DestinationOrigin.DEVICE) || destinationMatch.matchOrigin( - print_preview.DestinationOrigin.PROFILE)) { + print_preview.DestinationOrigin.PROFILE)) { this.startLoadCloudDestinations(); } }, @@ -789,9 +770,8 @@ matchRules = JSON.parse(serializedDefaultDestinationSelectionRulesStr); } - } catch(e) { - console.error( - 'Failed to parse defaultDestinationSelectionRules: ' + e); + } catch (e) { + console.error('Failed to parse defaultDestinationSelectionRules: ' + e); } if (!matchRules) return null; @@ -835,9 +815,7 @@ } return new print_preview.DestinationMatch( - origins, - idRegExp, - displayNameRegExp, + origins, idRegExp, displayNameRegExp, true /*skipVirtualDestinations*/); }, @@ -854,8 +832,7 @@ } if (this.systemDefaultDestinationId_) { return this.createExactDestinationMatch_( - this.platformOrigin_, - this.systemDefaultDestinationId_); + this.platformOrigin_, this.systemDefaultDestinationId_); } return null; }, @@ -872,8 +849,7 @@ return new print_preview.DestinationMatch( [origin], new RegExp('^' + id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$'), - null /*displayNameRegExp*/, - false /*skipVirtualDestinations*/); + null /*displayNameRegExp*/, false /*skipVirtualDestinations*/); }, /** @@ -937,8 +913,9 @@ return; } - assert(!destination.isProvisional, - 'Unable to select provisonal destinations'); + assert( + !destination.isProvisional, + 'Unable to select provisonal destinations'); // Update and persist selected destination. this.selectedDestination_ = destination; @@ -950,11 +927,11 @@ return otherDestination.cloudID == destination.cloudID && otherDestination != destination; })) { - this.metrics_.record(destination.isPrivet ? - print_preview.Metrics.DestinationSearchBucket. - PRIVET_DUPLICATE_SELECTED : - print_preview.Metrics.DestinationSearchBucket. - CLOUD_DUPLICATE_SELECTED); + this.metrics_.record( + destination.isPrivet ? print_preview.Metrics.DestinationSearchBucket + .PRIVET_DUPLICATE_SELECTED : + print_preview.Metrics.DestinationSearchBucket + .CLOUD_DUPLICATE_SELECTED); } // Notify about selected destination change. cr.dispatchSimpleEvent( @@ -963,25 +940,27 @@ // known yet. if (destination.capabilities == null) { if (destination.isPrivet) { - this.nativeLayer_.getPrivetPrinterCapabilities(destination.id).then( - this.onPrivetCapabilitiesSet_.bind(this), - this.onGetCapabilitiesFail_.bind(this, destination.origin, - destination.id)); + this.nativeLayer_.getPrivetPrinterCapabilities(destination.id) + .then( + this.onPrivetCapabilitiesSet_.bind(this), + this.onGetCapabilitiesFail_.bind( + this, destination.origin, destination.id)); } else if (destination.isExtension) { this.nativeLayer_.getExtensionPrinterCapabilities(destination.id) .then( this.onExtensionCapabilitiesSet_.bind(this, destination.id), - this.onGetCapabilitiesFail_.bind(this, destination.origin, - destination.id) - ); + this.onGetCapabilitiesFail_.bind( + this, destination.origin, destination.id)); } else if (destination.isLocal) { - this.nativeLayer_.getPrinterCapabilities(destination.id).then( - this.onLocalDestinationCapabilitiesSet_.bind(this), - this.onGetCapabilitiesFail_.bind(this, destination.origin, - destination.id)); + this.nativeLayer_.getPrinterCapabilities(destination.id) + .then( + this.onLocalDestinationCapabilitiesSet_.bind(this), + this.onGetCapabilitiesFail_.bind( + this, destination.origin, destination.id)); } else { - assert(this.cloudPrintInterface_ != null, - 'Cloud destination selected, but GCP is not enabled'); + assert( + this.cloudPrintInterface_ != null, + 'Cloud destination selected, but GCP is not enabled'); this.cloudPrintInterface_.printer( destination.id, destination.origin, destination.account); } @@ -1023,8 +1002,7 @@ selectPdfDestination_: function() { var saveToPdfKey = this.getDestinationKey_( print_preview.DestinationOrigin.LOCAL, - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF, - ''); + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF, ''); this.selectDestination( this.destinationMap_[saveToPdfKey] || this.destinations_[0] || null); }, @@ -1038,16 +1016,11 @@ if (this.systemDefaultDestinationId_) { if (this.autoSelectMatchingDestination_ && !this.autoSelectMatchingDestination_.matchIdAndOrigin( - this.systemDefaultDestinationId_, - this.platformOrigin_)) { + this.systemDefaultDestinationId_, this.platformOrigin_)) { if (this.fetchPreselectedDestination_( - this.platformOrigin_, - this.systemDefaultDestinationId_, - '' /*account*/, - '' /*name*/, - null /*capabilities*/, - '' /*extensionId*/, - '' /*extensionName*/)) { + this.platformOrigin_, this.systemDefaultDestinationId_, + '' /*account*/, '' /*name*/, null /*capabilities*/, + '' /*extensionId*/, '' /*extensionName*/)) { return; } } @@ -1073,14 +1046,13 @@ return; this.isPrivetDestinationSearchInProgress_ = true; this.nativeLayer_.getPrivetPrinters().then( - this.endPrivetPrinterSearch_.bind(this), - function() { + this.endPrivetPrinterSearch_.bind(this), function() { // Rejected by C++, indicating privet printing is disabled. this.hasLoadedAllPrivetDestinations_ = true; this.isPrivetDestinationSearchInProgress_ = false; }.bind(this)); cr.dispatchSimpleEvent( - this, DestinationStore.EventType.DESTINATION_SEARCH_STARTED); + this, DestinationStore.EventType.DESTINATION_SEARCH_STARTED); }, /** Initializes loading of extension managed print destinations. */ @@ -1259,8 +1231,8 @@ assert(destination.constructor !== Array, 'Single printer expected'); destination.capabilities_ = DestinationStore.localizeCapabilities_( assert(destination.capabilities_)); - destination.capabilities_ = DestinationStore.sortMediaSizes_( - destination.capabilities_); + destination.capabilities_ = + DestinationStore.sortMediaSizes_(destination.capabilities_); var existingDestination = this.destinationMap_[this.getKey_(destination)]; if (existingDestination != null) { existingDestination.capabilities = destination.capabilities; @@ -1303,8 +1275,7 @@ if (this.autoSelectMatchingDestination_ && this.autoSelectMatchingDestination_.matchOrigin( print_preview.DestinationOrigin.EXTENSION) && - this.selectedDestination_ && - this.selectedDestination_.isExtension) { + this.selectedDestination_ && this.selectedDestination_.isExtension) { this.selectDefaultDestination_(); } }, @@ -1319,18 +1290,20 @@ var key = this.getKey_(destination); var existingDestination = this.destinationMap_[key]; if (existingDestination == null) { - destination.isRecent |= this.appState_.recentDestinations.some( - function(recent) { - return (destination.id == recent.id && - destination.origin == recent.origin); + destination.isRecent |= + this.appState_.recentDestinations.some(function(recent) { + return ( + destination.id == recent.id && + destination.origin == recent.origin); }, this); this.destinations_.push(destination); this.destinationMap_[key] = destination; return true; - } else if (existingDestination.connectionStatus == - print_preview.DestinationConnectionStatus.UNKNOWN && - destination.connectionStatus != - print_preview.DestinationConnectionStatus.UNKNOWN) { + } else if ( + existingDestination.connectionStatus == + print_preview.DestinationConnectionStatus.UNKNOWN && + destination.connectionStatus != + print_preview.DestinationConnectionStatus.UNKNOWN) { existingDestination.connectionStatus = destination.connectionStatus; return true; } else { @@ -1366,8 +1339,7 @@ print_preview.Destination.GooglePromotedId.SAVE_AS_PDF, print_preview.DestinationType.LOCAL, print_preview.DestinationOrigin.LOCAL, - loadTimeData.getString('printToPDF'), - false /*isRecent*/, + loadTimeData.getString('printToPDF'), false /*isRecent*/, print_preview.DestinationConnectionStatus.ONLINE)); } }, @@ -1423,15 +1395,13 @@ // PDF is special since we don't need to query the device for // capabilities. var origin = destinationId == - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF ? - print_preview.DestinationOrigin.LOCAL : this.platformOrigin_; - var key = this.getDestinationKey_( - origin, - destinationId, - ''); + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF ? + print_preview.DestinationOrigin.LOCAL : + this.platformOrigin_; + var key = this.getDestinationKey_(origin, destinationId, ''); var destination = this.destinationMap_[key]; - var capabilities = DestinationStore.localizeCapabilities_( - settingsInfo.capabilities); + var capabilities = + DestinationStore.localizeCapabilities_(settingsInfo.capabilities); // Special case for PDF printer (until local printers capabilities are // reported in CDD format too). if (destinationId == @@ -1449,11 +1419,12 @@ destination.capabilities = capabilities; } else { var isEnterprisePrinter = settingsInfo['cupsEnterprisePrinter']; - destination = print_preview.LocalDestinationParser.parse( - {deviceName: destinationId, - printerName: printerName, - cupsEnterprisePrinter: isEnterprisePrinter, - printerDescription: printerDescription}); + destination = print_preview.LocalDestinationParser.parse({ + deviceName: destinationId, + printerName: printerName, + cupsEnterprisePrinter: isEnterprisePrinter, + printerDescription: printerDescription + }); destination.capabilities = capabilities; this.insertDestination_(destination); } @@ -1476,8 +1447,8 @@ * @private */ onGetCapabilitiesFail_: function(origin, destinationId) { - console.warn('Failed to get print capabilities for printer ' + - destinationId); + console.warn( + 'Failed to get print capabilities for printer ' + destinationId); if (this.autoSelectMatchingDestination_ && this.autoSelectMatchingDestination_.matchIdAndOrigin( destinationId, origin)) { @@ -1619,8 +1590,7 @@ */ onExtensionCapabilitiesSet_: function(printerId, capabilities) { var destinationKey = this.getDestinationKey_( - print_preview.DestinationOrigin.EXTENSION, - printerId, + print_preview.DestinationOrigin.EXTENSION, printerId, '' /* account */); var destination = this.destinationMap_[destinationKey]; if (!destination) @@ -1668,7 +1638,5 @@ }; // Export - return { - DestinationStore: DestinationStore - }; + return {DestinationStore: DestinationStore}; });
diff --git a/chrome/browser/resources/print_preview/data/document_info.js b/chrome/browser/resources/print_preview/data/document_info.js index 990ac212..2e286f3 100644 --- a/chrome/browser/resources/print_preview/data/document_info.js +++ b/chrome/browser/resources/print_preview/data/document_info.js
@@ -59,7 +59,7 @@ // page-related information won't be set until preview generation occurs, // so we'll use some defaults until then. This way, the print ticket store // will be valid even if no preview can be generated. - var initialPageSize = new print_preview.Size(612, 792); // 8.5"x11" + var initialPageSize = new print_preview.Size(612, 792); // 8.5"x11" /** * Size of the pages of the document in points. @@ -95,9 +95,7 @@ * Event types dispatched by this data model. * @enum {string} */ - DocumentInfo.EventType = { - CHANGE: 'print_preview.DocumentInfo.CHANGE' - }; + DocumentInfo.EventType = {CHANGE: 'print_preview.DocumentInfo.CHANGE'}; DocumentInfo.prototype = { __proto__: cr.EventTarget.prototype, @@ -223,7 +221,5 @@ }; // Export - return { - DocumentInfo: DocumentInfo - }; + return {DocumentInfo: DocumentInfo}; });
diff --git a/chrome/browser/resources/print_preview/data/invitation.js b/chrome/browser/resources/print_preview/data/invitation.js index d62434d..8aef4f3b 100644 --- a/chrome/browser/resources/print_preview/data/invitation.js +++ b/chrome/browser/resources/print_preview/data/invitation.js
@@ -87,7 +87,5 @@ }; // Export - return { - Invitation: Invitation - }; + return {Invitation: Invitation}; });
diff --git a/chrome/browser/resources/print_preview/data/invitation_store.js b/chrome/browser/resources/print_preview/data/invitation_store.js index 9524ca2..cbf037f 100644 --- a/chrome/browser/resources/print_preview/data/invitation_store.js +++ b/chrome/browser/resources/print_preview/data/invitation_store.js
@@ -70,8 +70,7 @@ * @enum {string} */ InvitationStore.EventType = { - INVITATION_PROCESSED: - 'print_preview.InvitationStore.INVITATION_PROCESSED', + INVITATION_PROCESSED: 'print_preview.InvitationStore.INVITATION_PROCESSED', INVITATION_SEARCH_DONE: 'print_preview.InvitationStore.INVITATION_SEARCH_DONE' }; @@ -221,7 +220,5 @@ }; // Export - return { - InvitationStore: InvitationStore - }; + return {InvitationStore: InvitationStore}; });
diff --git a/chrome/browser/resources/print_preview/data/local_parsers.js b/chrome/browser/resources/print_preview/data/local_parsers.js index cb34a4a..9c59fd7 100644 --- a/chrome/browser/resources/print_preview/data/local_parsers.js +++ b/chrome/browser/resources/print_preview/data/local_parsers.js
@@ -15,23 +15,23 @@ * @return {!print_preview.Destination} Parsed local print destination. */ LocalDestinationParser.parse = function(destinationInfo) { - var options = {description: destinationInfo.printerDescription, - isEnterprisePrinter: destinationInfo.cupsEnterprisePrinter}; + var options = { + description: destinationInfo.printerDescription, + isEnterprisePrinter: destinationInfo.cupsEnterprisePrinter + }; if (destinationInfo.printerOptions) { // Convert options into cloud print tags format. - options.tags = Object.keys(destinationInfo.printerOptions).map( - function(key) {return '__cp__' + key + '=' + this[key];}, - destinationInfo.printerOptions); + options.tags = + Object.keys(destinationInfo.printerOptions).map(function(key) { + return '__cp__' + key + '=' + this[key]; + }, destinationInfo.printerOptions); } return new print_preview.Destination( - destinationInfo.deviceName, - print_preview.DestinationType.LOCAL, + destinationInfo.deviceName, print_preview.DestinationType.LOCAL, cr.isChromeOS ? print_preview.DestinationOrigin.CROS : print_preview.DestinationOrigin.LOCAL, - destinationInfo.printerName, - false /*isRecent*/, - print_preview.DestinationConnectionStatus.ONLINE, - options); + destinationInfo.printerName, false /*isRecent*/, + print_preview.DestinationConnectionStatus.ONLINE, options); }; function PrivetDestinationParser() {} @@ -47,21 +47,16 @@ if (destinationInfo.hasLocalPrinting) { returnedPrinters.push(new print_preview.Destination( - destinationInfo.serviceName, - print_preview.DestinationType.LOCAL, - print_preview.DestinationOrigin.PRIVET, - destinationInfo.name, - false /*isRecent*/, - print_preview.DestinationConnectionStatus.ONLINE, + destinationInfo.serviceName, print_preview.DestinationType.LOCAL, + print_preview.DestinationOrigin.PRIVET, destinationInfo.name, + false /*isRecent*/, print_preview.DestinationConnectionStatus.ONLINE, {cloudID: destinationInfo.cloudID})); } if (destinationInfo.isUnregistered) { returnedPrinters.push(new print_preview.Destination( - destinationInfo.serviceName, - print_preview.DestinationType.GOOGLE, - print_preview.DestinationOrigin.PRIVET, - destinationInfo.name, + destinationInfo.serviceName, print_preview.DestinationType.GOOGLE, + print_preview.DestinationOrigin.PRIVET, destinationInfo.name, false /*isRecent*/, print_preview.DestinationConnectionStatus.UNREGISTERED)); } @@ -78,22 +73,20 @@ * @return {!print_preview.Destination} Parsed destination. */ ExtensionDestinationParser.parse = function(destinationInfo) { - var provisionalType = - destinationInfo.provisional ? - print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION : - print_preview.DestinationProvisionalType.NONE; + var provisionalType = destinationInfo.provisional ? + print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION : + print_preview.DestinationProvisionalType.NONE; return new print_preview.Destination( - destinationInfo.id, - print_preview.DestinationType.LOCAL, - print_preview.DestinationOrigin.EXTENSION, - destinationInfo.name, - false /* isRecent */, - print_preview.DestinationConnectionStatus.ONLINE, - {description: destinationInfo.description || '', - extensionId: destinationInfo.extensionId, - extensionName: destinationInfo.extensionName || '', - provisionalType: provisionalType}); + destinationInfo.id, print_preview.DestinationType.LOCAL, + print_preview.DestinationOrigin.EXTENSION, destinationInfo.name, + false /* isRecent */, print_preview.DestinationConnectionStatus.ONLINE, + { + description: destinationInfo.description || '', + extensionId: destinationInfo.extensionId, + extensionName: destinationInfo.extensionName || '', + provisionalType: provisionalType + }); }; // Export
diff --git a/chrome/browser/resources/print_preview/data/margins.js b/chrome/browser/resources/print_preview/data/margins.js index 716ab3a..ba8239b 100644 --- a/chrome/browser/resources/print_preview/data/margins.js +++ b/chrome/browser/resources/print_preview/data/margins.js
@@ -107,7 +107,5 @@ }; // Export - return { - Margins: Margins - }; + return {Margins: Margins}; });
diff --git a/chrome/browser/resources/print_preview/data/measurement_system.js b/chrome/browser/resources/print_preview/data/measurement_system.js index f661b0c..323c195 100644 --- a/chrome/browser/resources/print_preview/data/measurement_system.js +++ b/chrome/browser/resources/print_preview/data/measurement_system.js
@@ -9,8 +9,8 @@ * @enum {number} */ print_preview.MeasurementSystemUnitType = { - METRIC: 0, // millimeters - IMPERIAL: 1 // inches + METRIC: 0, // millimeters + IMPERIAL: 1 // inches }; cr.define('print_preview', function() { @@ -54,10 +54,10 @@ * @private */ MeasurementSystem.Precision_ = {}; - MeasurementSystem.Precision_[ - print_preview.MeasurementSystemUnitType.METRIC] = 0.5; - MeasurementSystem.Precision_[ - print_preview.MeasurementSystemUnitType.IMPERIAL] = 0.01; + MeasurementSystem.Precision_[print_preview.MeasurementSystemUnitType.METRIC] = + 0.5; + MeasurementSystem + .Precision_[print_preview.MeasurementSystemUnitType.IMPERIAL] = 0.01; /** * Maximum number of decimal places to keep for local unit. @@ -65,10 +65,10 @@ * @private */ MeasurementSystem.DecimalPlaces_ = {}; - MeasurementSystem.DecimalPlaces_[ - print_preview.MeasurementSystemUnitType.METRIC] = 1; - MeasurementSystem.DecimalPlaces_[ - print_preview.MeasurementSystemUnitType.IMPERIAL] = 2; + MeasurementSystem + .DecimalPlaces_[print_preview.MeasurementSystemUnitType.METRIC] = 1; + MeasurementSystem + .DecimalPlaces_[print_preview.MeasurementSystemUnitType.IMPERIAL] = 2; /** * Number of points per inch. @@ -91,8 +91,8 @@ get unitSymbol() { if (this.unitType_ == print_preview.MeasurementSystemUnitType.METRIC) { return 'mm'; - } else if (this.unitType_ == - print_preview.MeasurementSystemUnitType.IMPERIAL) { + } else if ( + this.unitType_ == print_preview.MeasurementSystemUnitType.IMPERIAL) { return '"'; } else { throw Error('Unit type not supported: ' + this.unitType_); @@ -160,7 +160,5 @@ }; // Export - return { - MeasurementSystem: MeasurementSystem - }; + return {MeasurementSystem: MeasurementSystem}; });
diff --git a/chrome/browser/resources/print_preview/data/page_number_set.js b/chrome/browser/resources/print_preview/data/page_number_set.js index 0917f3bc..81fb7b6 100644 --- a/chrome/browser/resources/print_preview/data/page_number_set.js +++ b/chrome/browser/resources/print_preview/data/page_number_set.js
@@ -58,7 +58,5 @@ }; // Export - return { - PageNumberSet: PageNumberSet - }; + return {PageNumberSet: PageNumberSet}; });
diff --git a/chrome/browser/resources/print_preview/data/print_ticket_store.js b/chrome/browser/resources/print_preview/data/print_ticket_store.js index 0b0922a..8b8f16b 100644 --- a/chrome/browser/resources/print_preview/data/print_ticket_store.js +++ b/chrome/browser/resources/print_preview/data/print_ticket_store.js
@@ -147,11 +147,8 @@ * @private */ this.mediaSize_ = new print_preview.ticket_items.MediaSize( - this.appState_, - this.destinationStore_, - this.documentInfo_, - this.marginsType_, - this.customMargins_); + this.appState_, this.destinationStore_, this.documentInfo_, + this.marginsType_, this.customMargins_); /** * Landscape ticket item. @@ -159,11 +156,8 @@ * @private */ this.landscape_ = new print_preview.ticket_items.Landscape( - this.appState_, - this.destinationStore_, - this.documentInfo_, - this.marginsType_, - this.customMargins_); + this.appState_, this.destinationStore_, this.documentInfo_, + this.marginsType_, this.customMargins_); /** * Header-footer ticket item. @@ -171,12 +165,8 @@ * @private */ this.headerFooter_ = new print_preview.ticket_items.HeaderFooter( - this.appState_, - this.documentInfo_, - this.marginsType_, - this.customMargins_, - this.mediaSize_, - this.landscape_); + this.appState_, this.documentInfo_, this.marginsType_, + this.customMargins_, this.mediaSize_, this.landscape_); /** * Fit-to-page ticket item. @@ -336,86 +326,83 @@ */ init: function( thousandsDelimeter, decimalDelimeter, unitType, selectionOnly) { - this.measurementSystem_.setSystem(thousandsDelimeter, decimalDelimeter, - unitType); + this.measurementSystem_.setSystem( + thousandsDelimeter, decimalDelimeter, unitType); this.selectionOnly_.updateValue(selectionOnly); // Initialize ticket with user's previous values. if (this.appState_.hasField( - print_preview.AppStateField.IS_COLOR_ENABLED)) { + print_preview.AppStateField.IS_COLOR_ENABLED)) { this.color_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_COLOR_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_COLOR_ENABLED))); } if (this.appState_.hasField(print_preview.AppStateField.DPI)) { this.dpi_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.DPI))); + /** @type {!Object} */ ( + this.appState_.getField(print_preview.AppStateField.DPI))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_DUPLEX_ENABLED)) { + print_preview.AppStateField.IS_DUPLEX_ENABLED)) { this.duplex_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_DUPLEX_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_DUPLEX_ENABLED))); } if (this.appState_.hasField(print_preview.AppStateField.MEDIA_SIZE)) { this.mediaSize_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.MEDIA_SIZE))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.MEDIA_SIZE))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_LANDSCAPE_ENABLED)) { + print_preview.AppStateField.IS_LANDSCAPE_ENABLED)) { this.landscape_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_LANDSCAPE_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_LANDSCAPE_ENABLED))); } // Initialize margins after landscape because landscape may reset margins. if (this.appState_.hasField(print_preview.AppStateField.MARGINS_TYPE)) { this.marginsType_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.MARGINS_TYPE))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.MARGINS_TYPE))); } - if (this.appState_.hasField( - print_preview.AppStateField.CUSTOM_MARGINS)) { + if (this.appState_.hasField(print_preview.AppStateField.CUSTOM_MARGINS)) { this.customMargins_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.CUSTOM_MARGINS))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.CUSTOM_MARGINS))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED)) { + print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED)) { this.headerFooter_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_COLLATE_ENABLED)) { + print_preview.AppStateField.IS_COLLATE_ENABLED)) { this.collate_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_COLLATE_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_COLLATE_ENABLED))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED)) { + print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED)) { this.fitToPage_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED))); } - if (this.appState_.hasField( - print_preview.AppStateField.SCALING)) { + if (this.appState_.hasField(print_preview.AppStateField.SCALING)) { this.scaling_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.SCALING))); + /** @type {!Object} */ ( + this.appState_.getField(print_preview.AppStateField.SCALING))); } if (this.appState_.hasField( - print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED)) { + print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED)) { this.cssBackground_.updateValue( - /** @type {!Object} */(this.appState_.getField( - print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED))); + /** @type {!Object} */ (this.appState_.getField( + print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED))); } - if (this.appState_.hasField( - print_preview.AppStateField.VENDOR_OPTIONS)) { + if (this.appState_.hasField(print_preview.AppStateField.VENDOR_OPTIONS)) { this.vendorItems_.updateValue( - /** @type {!Object<string>} */(this.appState_.getField( - print_preview.AppStateField.VENDOR_OPTIONS))); + /** @type {!Object<string>} */ (this.appState_.getField( + print_preview.AppStateField.VENDOR_OPTIONS))); } }, @@ -427,15 +414,16 @@ return this.isTicketValidForPreview() && (!this.copies_.isCapabilityAvailable() || this.copies_.isValid()) && (!this.pageRange_.isCapabilityAvailable() || - this.pageRange_.isValid()); + this.pageRange_.isValid()); }, /** @return {boolean} Whether the ticket is valid for preview generation. */ isTicketValidForPreview: function() { - return (!this.marginsType_.isCapabilityAvailable() || - !this.marginsType_.isValueEqual( - print_preview.ticket_items.MarginsTypeValue.CUSTOM) || - this.customMargins_.isValid()); + return ( + !this.marginsType_.isCapabilityAvailable() || + !this.marginsType_.isValueEqual( + print_preview.ticket_items.MarginsTypeValue.CUSTOM) || + this.customMargins_.isValid()); }, /** @@ -444,18 +432,17 @@ * @return {string} Google Cloud Print print ticket. */ createPrintTicket: function(destination) { - assert(!destination.isLocal || - destination.isPrivet || destination.isExtension, - 'Trying to create a Google Cloud Print print ticket for a local ' + - ' non-privet and non-extension destination'); + assert( + !destination.isLocal || destination.isPrivet || + destination.isExtension, + 'Trying to create a Google Cloud Print print ticket for a local ' + + ' non-privet and non-extension destination'); - assert(destination.capabilities, - 'Trying to create a Google Cloud Print print ticket for a ' + - 'destination with no print capabilities'); - var cjt = { - version: '1.0', - print: {} - }; + assert( + destination.capabilities, + 'Trying to create a Google Cloud Print print ticket for a ' + + 'destination with no print capabilities'); + var cjt = {version: '1.0', print: {}}; if (this.collate.isCapabilityAvailable() && this.collate.isUserEdited()) { cjt.print.collate = {collate: this.collate.getValue()}; } @@ -474,8 +461,9 @@ cjt.print.copies = {copies: this.copies.getValueAsNumber()}; } if (this.duplex.isCapabilityAvailable() && this.duplex.isUserEdited()) { - cjt.print.duplex = - {type: this.duplex.getValue() ? 'LONG_EDGE' : 'NO_DUPLEX'}; + cjt.print.duplex = { + type: this.duplex.getValue() ? 'LONG_EDGE' : 'NO_DUPLEX' + }; } if (this.mediaSize.isCapabilityAvailable()) { var value = this.mediaSize.getValue(); @@ -493,8 +481,9 @@ if (this.landscape.hasOption('AUTO')) cjt.print.page_orientation = {type: 'AUTO'}; } else if (this.landscape.isUserEdited()) { - cjt.print.page_orientation = - {type: this.landscape.getValue() ? 'LANDSCAPE' : 'PORTRAIT'}; + cjt.print.page_orientation = { + type: this.landscape.getValue() ? 'LANDSCAPE' : 'PORTRAIT' + }; } if (this.dpi.isCapabilityAvailable()) { var value = this.dpi.getValue(); @@ -530,14 +519,14 @@ this.tracker_.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - SELECTED_DESTINATION_CAPABILITIES_READY, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, this.onSelectedDestinationCapabilitiesReady_.bind(this)); this.tracker_.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - CACHED_SELECTED_DESTINATION_INFO_READY, + print_preview.DestinationStore.EventType + .CACHED_SELECTED_DESTINATION_INFO_READY, this.onSelectedDestinationCapabilitiesReady_.bind(this)); // TODO(rltoscano): Print ticket store shouldn't be re-dispatching these @@ -545,8 +534,7 @@ // for the events from document info instead. Will move this when // consumers are all migrated. this.tracker_.add( - this.documentInfo_, - print_preview.DocumentInfo.EventType.CHANGE, + this.documentInfo_, print_preview.DocumentInfo.EventType.CHANGE, this.onDocumentInfoChange_.bind(this)); }, @@ -572,8 +560,8 @@ * @private */ onSelectedDestinationCapabilitiesReady_: function() { - var caps = assert( - this.destinationStore_.selectedDestination.capabilities); + var caps = + assert(this.destinationStore_.selectedDestination.capabilities); var isFirstUpdate = this.capabilitiesHolder_.get() == null; this.capabilitiesHolder_.set(caps); if (isFirstUpdate) { @@ -596,7 +584,5 @@ }; // Export - return { - PrintTicketStore: PrintTicketStore - }; + return {PrintTicketStore: PrintTicketStore}; });
diff --git a/chrome/browser/resources/print_preview/data/printable_area.js b/chrome/browser/resources/print_preview/data/printable_area.js index 5ab0ab6..ae0f076 100644 --- a/chrome/browser/resources/print_preview/data/printable_area.js +++ b/chrome/browser/resources/print_preview/data/printable_area.js
@@ -51,14 +51,11 @@ * @return {boolean} Whether another printable area is equal to this one. */ equals: function(other) { - return other != null && - this.origin_.equals(other.origin_) && + return other != null && this.origin_.equals(other.origin_) && this.size_.equals(other.size_); } }; // Export - return { - PrintableArea: PrintableArea - }; + return {PrintableArea: PrintableArea}; });
diff --git a/chrome/browser/resources/print_preview/data/size.js b/chrome/browser/resources/print_preview/data/size.js index 7e6171314..078ce7d 100644 --- a/chrome/browser/resources/print_preview/data/size.js +++ b/chrome/browser/resources/print_preview/data/size.js
@@ -43,14 +43,11 @@ * @return {boolean} Whether this size object is equal to another. */ equals: function(other) { - return other != null && - this.width_ == other.width_ && + return other != null && this.width_ == other.width_ && this.height_ == other.height_; } }; // Export - return { - Size: Size - }; + return {Size: Size}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/collate.js b/chrome/browser/resources/print_preview/data/ticket_items/collate.js index e2055ad..ec59d89 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/collate.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/collate.js
@@ -17,9 +17,7 @@ */ function Collate(appState, destinationStore) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_COLLATE_ENABLED, + this, appState, print_preview.AppStateField.IS_COLLATE_ENABLED, destinationStore); } @@ -53,16 +51,12 @@ */ getCollateCapability_: function() { var dest = this.getSelectedDestInternal(); - return (dest && - dest.capabilities && - dest.capabilities.printer && + return (dest && dest.capabilities && dest.capabilities.printer && dest.capabilities.printer.collate) || - null; + null; } }; // Export - return { - Collate: Collate - }; + return {Collate: Collate}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/color.js b/chrome/browser/resources/print_preview/data/ticket_items/color.js index ccbbcbf..67d2dec 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/color.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/color.js
@@ -17,9 +17,7 @@ */ function Color(appState, destinationStore) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_COLOR_ENABLED, + this, appState, print_preview.AppStateField.IS_COLOR_ENABLED, destinationStore); } @@ -62,11 +60,9 @@ /** @return {Object} Color capability of the selected destination. */ get capability() { var dest = this.getSelectedDestInternal(); - return (dest && - dest.capabilities && - dest.capabilities.printer && + return (dest && dest.capabilities && dest.capabilities.printer && dest.capabilities.printer.color) || - null; + null; }, /** @return {Object} Color option corresponding to the current value. */ @@ -91,8 +87,8 @@ /** @override */ getDefaultValueInternal: function() { var capability = this.capability; - var defaultOption = capability ? - this.getDefaultColorOption_(capability.option) : null; + var defaultOption = + capability ? this.getDefaultColorOption_(capability.option) : null; return defaultOption && (Color.COLOR_TYPES_.indexOf(defaultOption.type) >= 0); }, @@ -129,7 +125,5 @@ }; // Export - return { - Color: Color - }; + return {Color: Color}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/copies.js b/chrome/browser/resources/print_preview/data/ticket_items/copies.js index 155af71..936342cb 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/copies.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/copies.js
@@ -55,16 +55,12 @@ */ getCopiesCapability_: function() { var dest = this.getSelectedDestInternal(); - return (dest && - dest.capabilities && - dest.capabilities.printer && + return (dest && dest.capabilities && dest.capabilities.printer && dest.capabilities.printer.copies) || - null; + null; } }; // Export - return { - Copies: Copies - }; + return {Copies: Copies}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/css_background.js b/chrome/browser/resources/print_preview/data/ticket_items/css_background.js index 03fde6c..ab20587 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/css_background.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/css_background.js
@@ -17,11 +17,8 @@ */ function CssBackground(appState, documentInfo) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED, - null /*destinationStore*/, - documentInfo); + this, appState, print_preview.AppStateField.IS_CSS_BACKGROUND_ENABLED, + null /*destinationStore*/, documentInfo); } CssBackground.prototype = { @@ -49,7 +46,5 @@ }; // Export - return { - CssBackground: CssBackground - }; + return {CssBackground: CssBackground}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/custom_margins.js b/chrome/browser/resources/print_preview/data/ticket_items/custom_margins.js index dfa7423..97c0ed8 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/custom_margins.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/custom_margins.js
@@ -33,11 +33,8 @@ */ function CustomMargins(appState, documentInfo) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.CUSTOM_MARGINS, - null /*destinationStore*/, - documentInfo); + this, appState, print_preview.AppStateField.CUSTOM_MARGINS, + null /*destinationStore*/, documentInfo); } /** @@ -62,7 +59,7 @@ * @const * @private */ - CustomMargins.MINIMUM_MARGINS_DISTANCE_ = 72; // 1 inch. + CustomMargins.MINIMUM_MARGINS_DISTANCE_ = 72; // 1 inch. CustomMargins.prototype = { __proto__: print_preview.ticket_items.TicketItem.prototype, @@ -135,13 +132,13 @@ /** @override */ getDefaultValueInternal: function() { return this.getDocumentInfoInternal().margins || - new print_preview.Margins(72, 72, 72, 72); + new print_preview.Margins(72, 72, 72, 72); }, /** @override */ getCapabilityNotAvailableValueInternal: function() { return this.getDocumentInfoInternal().margins || - new print_preview.Margins(72, 72, 72, 72); + new print_preview.Margins(72, 72, 72, 72); }, /** @@ -158,14 +155,12 @@ this.getDocumentInfoInternal().pageSize.height : this.getDocumentInfoInternal().pageSize.width; - var totalMargin = dimensionLength - - CustomMargins.MINIMUM_MARGINS_DISTANCE_; + var totalMargin = + dimensionLength - CustomMargins.MINIMUM_MARGINS_DISTANCE_; return Math.round(totalMargin > 0 ? totalMargin - oppositeMargin : 0); } }; // Export - return { - CustomMargins: CustomMargins - }; + return {CustomMargins: CustomMargins}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/dpi.js b/chrome/browser/resources/print_preview/data/ticket_items/dpi.js index 674a98c..7a514f1 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/dpi.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/dpi.js
@@ -16,10 +16,7 @@ */ function Dpi(appState, destinationStore) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.DPI, - destinationStore); + this, appState, print_preview.AppStateField.DPI, destinationStore); } Dpi.prototype = { @@ -31,34 +28,32 @@ return false; return this.capability.option.some(function(option) { return option.horizontal_dpi == value.horizontal_dpi && - option.vertical_dpi == value.vertical_dpi && - option.vendor_id == value.vendor_id; + option.vertical_dpi == value.vertical_dpi && + option.vendor_id == value.vendor_id; }); }, /** @override */ isCapabilityAvailable: function() { - return !!this.capability && - !!this.capability.option && - this.capability.option.length > 1; + return !!this.capability && !!this.capability.option && + this.capability.option.length > 1; }, /** @override */ isValueEqual: function(value) { var myValue = this.getValue(); return myValue.horizontal_dpi == value.horizontal_dpi && - myValue.vertical_dpi == value.vertical_dpi && - myValue.vendor_id == value.vendor_id; + myValue.vertical_dpi == value.vertical_dpi && + myValue.vendor_id == value.vendor_id; }, /** @return {Object} DPI capability of the selected destination. */ get capability() { var destination = this.getSelectedDestInternal(); - return (destination && - destination.capabilities && + return (destination && destination.capabilities && destination.capabilities.printer && destination.capabilities.printer.dpi) || - null; + null; }, /** @override */ @@ -76,7 +71,5 @@ }; // Export - return { - Dpi: Dpi - }; + return {Dpi: Dpi}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/duplex.js b/chrome/browser/resources/print_preview/data/ticket_items/duplex.js index 0fcf3bb..9930e1ca 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/duplex.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/duplex.js
@@ -17,9 +17,7 @@ */ function Duplex(appState, destinationStore) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_DUPLEX_ENABLED, + this, appState, print_preview.AppStateField.IS_DUPLEX_ENABLED, destinationStore); } @@ -67,16 +65,12 @@ */ getDuplexCapability_: function() { var dest = this.getSelectedDestInternal(); - return (dest && - dest.capabilities && - dest.capabilities.printer && + return (dest && dest.capabilities && dest.capabilities.printer && dest.capabilities.printer.duplex) || - null; + null; } }; // Export - return { - Duplex: Duplex - }; + return {Duplex: Duplex}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/fit_to_page.js b/chrome/browser/resources/print_preview/data/ticket_items/fit_to_page.js index 332e585..6dc52f7 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/fit_to_page.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/fit_to_page.js
@@ -18,11 +18,8 @@ */ function FitToPage(appState, documentInfo, destinationStore) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED, - destinationStore, - documentInfo); + this, appState, print_preview.AppStateField.IS_FIT_TO_PAGE_ENABLED, + destinationStore, documentInfo); } FitToPage.prototype = { @@ -37,8 +34,8 @@ isCapabilityAvailable: function() { return !this.getDocumentInfoInternal().isModifiable && (!this.getSelectedDestInternal() || - this.getSelectedDestInternal().id != - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF); + this.getSelectedDestInternal().id != + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF); }, /** @override */ @@ -53,12 +50,10 @@ getCapabilityNotAvailableValueInternal: function() { return !this.getSelectedDestInternal() || this.getSelectedDestInternal().id != - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; } }; // Export - return { - FitToPage: FitToPage - }; + return {FitToPage: FitToPage}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/header_footer.js b/chrome/browser/resources/print_preview/data/ticket_items/header_footer.js index 9cb9e9c7..b144537 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/header_footer.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/header_footer.js
@@ -23,14 +23,12 @@ * @constructor * @extends {print_preview.ticket_items.TicketItem} */ - function HeaderFooter(appState, documentInfo, marginsType, customMargins, - mediaSize, landscape) { + function HeaderFooter( + appState, documentInfo, marginsType, customMargins, mediaSize, + landscape) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED, - null /*destinationStore*/, - documentInfo); + this, appState, print_preview.AppStateField.IS_HEADER_FOOTER_ENABLED, + null /*destinationStore*/, documentInfo); /** * Ticket item that stores which predefined margins to print with. @@ -86,8 +84,8 @@ return false; } var microns = this.landscape_.getValue() ? - this.mediaSize_.getValue().width_microns : - this.mediaSize_.getValue().height_microns; + this.mediaSize_.getValue().width_microns : + this.mediaSize_.getValue().height_microns; if (microns < HeaderFooter.MINIMUM_HEIGHT_MICRONS_) { // If this is a small paper size, there is not space for headers // and footers regardless of the margins. @@ -108,9 +106,8 @@ margins = this.getDocumentInfoInternal().margins; } var orientEnum = print_preview.ticket_items.CustomMarginsOrientation; - return margins == null || - margins.get(orientEnum.TOP) > 0 || - margins.get(orientEnum.BOTTOM) > 0; + return margins == null || margins.get(orientEnum.TOP) > 0 || + margins.get(orientEnum.BOTTOM) > 0; }, /** @override */ @@ -148,7 +145,5 @@ }; // Export - return { - HeaderFooter: HeaderFooter - }; + return {HeaderFooter: HeaderFooter}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/landscape.js b/chrome/browser/resources/print_preview/data/ticket_items/landscape.js index c7a33bd..df4dc00d 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/landscape.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/landscape.js
@@ -22,14 +22,11 @@ * @constructor * @extends {print_preview.ticket_items.TicketItem} */ - function Landscape(appState, destinationStore, documentInfo, marginsType, - customMargins) { + function Landscape( + appState, destinationStore, documentInfo, marginsType, customMargins) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.IS_LANDSCAPE_ENABLED, - destinationStore, - documentInfo); + this, appState, print_preview.AppStateField.IS_LANDSCAPE_ENABLED, + destinationStore, documentInfo); /** * Margins ticket item. Reset when landscape ticket item changes. @@ -63,8 +60,7 @@ var hasLandscapeOption = false; cap.option.forEach(function(option) { hasAutoOrPortraitOption = hasAutoOrPortraitOption || - option.type == 'AUTO' || - option.type == 'PORTRAIT'; + option.type == 'AUTO' || option.type == 'PORTRAIT'; hasLandscapeOption = hasLandscapeOption || option.type == 'LANDSCAPE'; }); // TODO(rltoscano): Technically, the print destination can still change @@ -73,8 +69,7 @@ // case so it would be a bad user experience. return this.getDocumentInfoInternal().isModifiable && !this.getDocumentInfoInternal().hasCssMediaStyles && - hasAutoOrPortraitOption && - hasLandscapeOption; + hasAutoOrPortraitOption && hasLandscapeOption; }, /** @override */ @@ -103,7 +98,7 @@ if (updateMargins) { // Reset the user set margins when page orientation changes. this.marginsType_.updateValue( - print_preview.ticket_items.MarginsTypeValue.DEFAULT); + print_preview.ticket_items.MarginsTypeValue.DEFAULT); this.customMargins_.updateValue(null); } }, @@ -127,16 +122,12 @@ */ getPageOrientationCapability_: function() { var dest = this.getSelectedDestInternal(); - return (dest && - dest.capabilities && - dest.capabilities.printer && + return (dest && dest.capabilities && dest.capabilities.printer && dest.capabilities.printer.page_orientation) || - null; + null; } }; // Export - return { - Landscape: Landscape - }; + return {Landscape: Landscape}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/margins_type.js b/chrome/browser/resources/print_preview/data/ticket_items/margins_type.js index 73fa0b1e..808e148 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/margins_type.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/margins_type.js
@@ -35,11 +35,8 @@ */ function MarginsType(appState, documentInfo, customMargins) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.MARGINS_TYPE, - null /*destinationStore*/, - documentInfo); + this, appState, print_preview.AppStateField.MARGINS_TYPE, + null /*destinationStore*/, documentInfo); /** * Custom margins ticket item, used to write when margins type changes. @@ -77,7 +74,7 @@ print_preview.ticket_items.TicketItem.prototype.updateValueInternal.call( this, value); if (this.isValueEqual( - print_preview.ticket_items.MarginsTypeValue.CUSTOM)) { + print_preview.ticket_items.MarginsTypeValue.CUSTOM)) { // If CUSTOM, set the value of the custom margins so that it won't be // overridden by the default value. this.customMargins_.updateValue(this.customMargins_.getValue()); @@ -86,7 +83,5 @@ }; // Export - return { - MarginsType: MarginsType - }; + return {MarginsType: MarginsType}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/media_size.js b/chrome/browser/resources/print_preview/data/ticket_items/media_size.js index 1f31763..09abc7a3 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/media_size.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/media_size.js
@@ -23,11 +23,8 @@ function MediaSize( appState, destinationStore, documentInfo, marginsType, customMargins) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.MEDIA_SIZE, - destinationStore, - documentInfo); + this, appState, print_preview.AppStateField.MEDIA_SIZE, + destinationStore, documentInfo); /** * Margins ticket item. Reset when this item changes. @@ -52,9 +49,9 @@ } return this.capability.option.some(function(option) { return option.width_microns == value.width_microns && - option.height_microns == value.height_microns && - option.is_continuous_feed == value.is_continuous_feed && - option.vendor_id == value.vendor_id; + option.height_microns == value.height_microns && + option.is_continuous_feed == value.is_continuous_feed && + option.vendor_id == value.vendor_id; }); }, @@ -73,19 +70,18 @@ isValueEqual: function(value) { var myValue = this.getValue(); return myValue.width_microns == value.width_microns && - myValue.height_microns == value.height_microns && - myValue.is_continuous_feed == value.is_continuous_feed && - myValue.vendor_id == value.vendor_id; + myValue.height_microns == value.height_microns && + myValue.is_continuous_feed == value.is_continuous_feed && + myValue.vendor_id == value.vendor_id; }, /** @return {Object} Media size capability of the selected destination. */ get capability() { var destination = this.getSelectedDestInternal(); - return (destination && - destination.capabilities && + return (destination && destination.capabilities && destination.capabilities.printer && destination.capabilities.printer.media_size) || - null; + null; }, /** @override */ @@ -116,7 +112,5 @@ }; // Export - return { - MediaSize: MediaSize - }; + return {MediaSize: MediaSize}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/page_range.js b/chrome/browser/resources/print_preview/data/ticket_items/page_range.js index f0120010..5eb176f8 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/page_range.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/page_range.js
@@ -15,10 +15,7 @@ */ function PageRange(documentInfo) { print_preview.ticket_items.TicketItem.call( - this, - null /*appState*/, - null /*field*/, - null /*destinationStore*/, + this, null /*appState*/, null /*field*/, null /*destinationStore*/, documentInfo); } @@ -70,7 +67,7 @@ * @private */ getValueAsString_: function() { - return /** @type {string} */(this.getValue()); + return /** @type {string} */ (this.getValue()); }, /** @@ -107,13 +104,11 @@ checkValidity: function() { var pageRanges = pageRangeTextToPageRanges( this.getValueAsString_(), this.getDocumentInfoInternal().pageCount); - return pageRanges instanceof Array ? - PageRangeStatus.NO_ERROR : pageRanges; + return pageRanges instanceof Array ? PageRangeStatus.NO_ERROR : + pageRanges; }, }; // Export - return { - PageRange: PageRange - }; + return {PageRange: PageRange}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/rasterize.js b/chrome/browser/resources/print_preview/data/ticket_items/rasterize.js index cf0ebec..5827ba5 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/rasterize.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/rasterize.js
@@ -44,7 +44,5 @@ }; // Export - return { - Rasterize: Rasterize - }; + return {Rasterize: Rasterize}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/scaling.js b/chrome/browser/resources/print_preview/data/ticket_items/scaling.js index e3703d4..e1099da 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/scaling.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/scaling.js
@@ -19,10 +19,7 @@ */ function Scaling(appState, destinationStore, documentInfo) { print_preview.ticket_items.TicketItem.call( - this, - appState, - print_preview.AppStateField.SCALING, - destinationStore, + this, appState, print_preview.AppStateField.SCALING, destinationStore, documentInfo); } @@ -46,9 +43,9 @@ var knownSizeToSaveAsPdf = (!this.getDocumentInfoInternal().isModifiable || this.getDocumentInfoInternal().hasCssMediaStyles) && - this.getSelectedDestInternal() && - this.getSelectedDestInternal().id == - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; + this.getSelectedDestInternal() && + this.getSelectedDestInternal().id == + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; return !knownSizeToSaveAsPdf; }, @@ -69,7 +66,5 @@ }; // Export - return { - Scaling: Scaling - }; + return {Scaling: Scaling}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/selection_only.js b/chrome/browser/resources/print_preview/data/ticket_items/selection_only.js index 4002f68..f6bfaf7 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/selection_only.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/selection_only.js
@@ -15,10 +15,7 @@ */ function SelectionOnly(documentInfo) { print_preview.ticket_items.TicketItem.call( - this, - null /*appState*/, - null /*field*/, - null /*destinationStore*/, + this, null /*appState*/, null /*field*/, null /*destinationStore*/, documentInfo); } @@ -33,7 +30,7 @@ /** @override */ isCapabilityAvailable: function() { return this.getDocumentInfoInternal().isModifiable && - this.getDocumentInfoInternal().hasSelection; + this.getDocumentInfoInternal().hasSelection; }, /** @override */ @@ -48,7 +45,5 @@ }; // Export - return { - SelectionOnly: SelectionOnly - }; + return {SelectionOnly: SelectionOnly}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js b/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js index f2ea4dc8..ff31b24 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/ticket_item.js
@@ -190,7 +190,8 @@ */ getSelectedDestInternal: function() { return this.destinationStore_ ? - this.destinationStore_.selectedDestination : null; + this.destinationStore_.selectedDestination : + null; }, /** @@ -227,21 +228,18 @@ if (this.destinationStore_) { this.tracker_.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - SELECTED_DESTINATION_CAPABILITIES_READY, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, this.dispatchChangeEventInternal.bind(this)); } if (this.documentInfo_) { this.tracker_.add( - this.documentInfo_, - print_preview.DocumentInfo.EventType.CHANGE, + this.documentInfo_, print_preview.DocumentInfo.EventType.CHANGE, this.dispatchChangeEventInternal.bind(this)); } }, }; // Export - return { - TicketItem: TicketItem - }; + return {TicketItem: TicketItem}; });
diff --git a/chrome/browser/resources/print_preview/data/ticket_items/vendor_items.js b/chrome/browser/resources/print_preview/data/ticket_items/vendor_items.js index ae27fbb65..82a65d3 100644 --- a/chrome/browser/resources/print_preview/data/ticket_items/vendor_items.js +++ b/chrome/browser/resources/print_preview/data/ticket_items/vendor_items.js
@@ -63,16 +63,16 @@ /** @return {Object} Vendor capabilities of the selected destination. */ get capability() { var destination = this.destinationStore_ ? - this.destinationStore_.selectedDestination : null; + this.destinationStore_.selectedDestination : + null; if (!destination) return null; if (destination.type == print_preview.DestinationType.MOBILE) { return null; } - return (destination.capabilities && - destination.capabilities.printer && + return (destination.capabilities && destination.capabilities.printer && destination.capabilities.printer.vendor_capability) || - null; + null; }, /** @@ -106,7 +106,5 @@ }; // Export - return { - VendorItems: VendorItems - }; + return {VendorItems: VendorItems}; });
diff --git a/chrome/browser/resources/print_preview/data/user_info.js b/chrome/browser/resources/print_preview/data/user_info.js index 64adba9..5076052 100644 --- a/chrome/browser/resources/print_preview/data/user_info.js +++ b/chrome/browser/resources/print_preview/data/user_info.js
@@ -87,7 +87,5 @@ }, }; - return { - UserInfo: UserInfo - }; + return {UserInfo: UserInfo}; });
diff --git a/chrome/browser/resources/print_preview/metrics.js b/chrome/browser/resources/print_preview/metrics.js index f301ef0f..dd4d1ae3 100644 --- a/chrome/browser/resources/print_preview/metrics.js +++ b/chrome/browser/resources/print_preview/metrics.js
@@ -114,10 +114,10 @@ * @param {number} bucket Value to record. */ record: function(bucket) { - chrome.send('metricsHandler:recordInHistogram', - [this.histogram_, - ((bucket > this.maxBucket_) ? this.maxBucket_ : bucket), - this.maxBucket_]); + chrome.send('metricsHandler:recordInHistogram', [ + this.histogram_, + ((bucket > this.maxBucket_) ? this.maxBucket_ : bucket), this.maxBucket_ + ]); } }; @@ -128,8 +128,7 @@ */ function DestinationSearchMetricsContext() { MetricsContext.call( - this, - 'PrintPreview.DestinationAction', + this, 'PrintPreview.DestinationAction', Metrics.DestinationSearchBucket.DESTINATION_SEARCH_MAX_BUCKET); } @@ -143,14 +142,12 @@ * @extends {print_preview.MetricsContext} */ function GcpPromoMetricsContext() { - MetricsContext.call(this, - 'PrintPreview.GcpPromo', - Metrics.GcpPromoBucket.GCP_PROMO_MAX_BUCKET); + MetricsContext.call( + this, 'PrintPreview.GcpPromo', + Metrics.GcpPromoBucket.GCP_PROMO_MAX_BUCKET); } - GcpPromoMetricsContext.prototype = { - __proto__: MetricsContext.prototype - }; + GcpPromoMetricsContext.prototype = {__proto__: MetricsContext.prototype}; /** * Print settings UI specific usage statistics context. @@ -159,8 +156,7 @@ */ function PrintSettingsUiMetricsContext() { MetricsContext.call( - this, - 'PrintPreview.PrintSettingsUi', + this, 'PrintPreview.PrintSettingsUi', Metrics.PrintSettingsUiBucket.PRINT_SETTINGS_UI_MAX_BUCKET); }
diff --git a/chrome/browser/resources/print_preview/native_layer.js b/chrome/browser/resources/print_preview/native_layer.js index dbe4836..276cf72 100644 --- a/chrome/browser/resources/print_preview/native_layer.js +++ b/chrome/browser/resources/print_preview/native_layer.js
@@ -63,7 +63,7 @@ * success: boolean, * capabilities: Object, * }} -*/ + */ print_preview.PrinterSetupResponse; cr.define('print_preview', function() { @@ -78,17 +78,13 @@ global.setUseCloudPrint = this.onSetUseCloudPrint_.bind(this); global.reloadPrintersList = this.onReloadPrintersList_.bind(this); global.printToCloud = this.onPrintToCloud_.bind(this); - global.fileSelectionCancelled = - this.onFileSelectionCancelled_.bind(this); - global.fileSelectionCompleted = - this.onFileSelectionCompleted_.bind(this); + global.fileSelectionCancelled = this.onFileSelectionCancelled_.bind(this); + global.fileSelectionCompleted = this.onFileSelectionCompleted_.bind(this); global.printPreviewFailed = this.onPrintPreviewFailed_.bind(this); - global.invalidPrinterSettings = - this.onInvalidPrinterSettings_.bind(this); + global.invalidPrinterSettings = this.onInvalidPrinterSettings_.bind(this); global.onDidGetDefaultPageLayout = this.onDidGetDefaultPageLayout_.bind(this); - global.onDidGetPreviewPageCount = - this.onDidGetPreviewPageCount_.bind(this); + global.onDidGetPreviewPageCount = this.onDidGetPreviewPageCount_.bind(this); global.onDidPreviewPage = this.onDidPreviewPage_.bind(this); global.updatePrintPreview = this.onUpdatePrintPreview_.bind(this); global.onDidGetAccessToken = this.onDidGetAccessToken_.bind(this); @@ -159,21 +155,14 @@ * Constant values matching printing::DuplexMode enum. * @enum {number} */ - NativeLayer.DuplexMode = { - SIMPLEX: 0, - LONG_EDGE: 1, - UNKNOWN_DUPLEX_MODE: -1 - }; + NativeLayer.DuplexMode = {SIMPLEX: 0, LONG_EDGE: 1, UNKNOWN_DUPLEX_MODE: -1}; /** * Enumeration of color modes used by Chromium. * @enum {number} * @private */ - NativeLayer.ColorMode_ = { - GRAY: 1, - COLOR: 2 - }; + NativeLayer.ColorMode_ = {GRAY: 1, COLOR: 2}; /** * Version of the serialized state of the print preview. @@ -202,33 +191,34 @@ * @return {!Promise<!print_preview.NativeInitialSettings>} */ getInitialSettings: function() { - return cr.sendWithPromise('getInitialSettings').then( - /** - * @param {!Object} initialSettings Object containing the raw - * Print Preview settings. - */ - function(initialSettings) { - var numberFormatSymbols = - print_preview.MeasurementSystem.parseNumberFormat( - initialSettings['numberFormat']); - var unitType = print_preview.MeasurementSystemUnitType.IMPERIAL; - if (initialSettings['measurementSystem'] != null) { - unitType = initialSettings['measurementSystem']; - } - return new print_preview.NativeInitialSettings( - initialSettings['printAutomaticallyInKioskMode'] || false, - initialSettings['appKioskMode'] || false, - numberFormatSymbols[0] || ',', - numberFormatSymbols[1] || '.', - unitType, - initialSettings['previewModifiable'] || false, - initialSettings['initiatorTitle'] || '', - initialSettings['documentHasSelection'] || false, - initialSettings['shouldPrintSelectionOnly'] || false, - initialSettings['printerName'] || null, - initialSettings['appState'] || null, - initialSettings['defaultDestinationSelectionRules'] || null); - }); + return cr.sendWithPromise('getInitialSettings') + .then( + /** + * @param {!Object} initialSettings Object containing the raw + * Print Preview settings. + */ + function(initialSettings) { + var numberFormatSymbols = + print_preview.MeasurementSystem.parseNumberFormat( + initialSettings['numberFormat']); + var unitType = print_preview.MeasurementSystemUnitType.IMPERIAL; + if (initialSettings['measurementSystem'] != null) { + unitType = initialSettings['measurementSystem']; + } + return new print_preview.NativeInitialSettings( + initialSettings['printAutomaticallyInKioskMode'] || false, + initialSettings['appKioskMode'] || false, + numberFormatSymbols[0] || ',', + numberFormatSymbols[1] || '.', unitType, + initialSettings['previewModifiable'] || false, + initialSettings['initiatorTitle'] || '', + initialSettings['documentHasSelection'] || false, + initialSettings['shouldPrintSelectionOnly'] || false, + initialSettings['printerName'] || null, + initialSettings['appState'] || null, + initialSettings['defaultDestinationSelectionRules'] || + null); + }); }, /** @@ -290,8 +280,8 @@ * @return {!Promise<!print_preview.Cdd>} */ getExtensionPrinterCapabilities: function(destinationId) { - return cr.sendWithPromise('getExtensionPrinterCapabilities', - destinationId); + return cr.sendWithPromise( + 'getExtensionPrinterCapabilities', destinationId); }, /** @@ -326,8 +316,8 @@ var option = destination.isLocal ? color.getSelectedOption() : null; var nativeColorModel = parseInt(option ? option.vendor_id : null, 10); if (isNaN(nativeColorModel)) { - return color.getValue() ? - NativeLayer.ColorMode_.COLOR : NativeLayer.ColorMode_.GRAY; + return color.getValue() ? NativeLayer.ColorMode_.COLOR : + NativeLayer.ColorMode_.GRAY; } return nativeColorModel; }, @@ -349,8 +339,9 @@ */ startGetPreview: function( destination, printTicketStore, documentInfo, generateDraft, requestId) { - assert(printTicketStore.isTicketValidForPreview(), - 'Trying to generate preview when ticket is not valid'); + assert( + printTicketStore.isTicketValidForPreview(), + 'Trying to generate preview when ticket is not valid'); var ticket = { 'pageRange': printTicketStore.pageRange.getDocumentPageRanges(), @@ -372,13 +363,16 @@ 'copies': 1, 'deviceName': destination.id, 'dpiHorizontal': 'horizontal_dpi' in printTicketStore.dpi.getValue() ? - printTicketStore.dpi.getValue().horizontal_dpi : 0, + printTicketStore.dpi.getValue().horizontal_dpi : + 0, 'dpiVertical': 'vertical_dpi' in printTicketStore.dpi.getValue() ? - printTicketStore.dpi.getValue().vertical_dpi : 0, + printTicketStore.dpi.getValue().vertical_dpi : + 0, 'duplex': printTicketStore.duplex.getValue() ? - NativeLayer.DuplexMode.LONG_EDGE : NativeLayer.DuplexMode.SIMPLEX, + NativeLayer.DuplexMode.LONG_EDGE : + NativeLayer.DuplexMode.SIMPLEX, 'printToPDF': destination.id == - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF, + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF, 'printWithCloudPrint': !destination.isLocal, 'printWithPrivet': destination.isPrivet, 'printWithExtension': destination.isExtension, @@ -406,10 +400,9 @@ }; } - chrome.send( - 'getPreview', - [JSON.stringify(ticket), - requestId > 0 ? documentInfo.pageCount : -1]); + chrome.send('getPreview', [ + JSON.stringify(ticket), requestId > 0 ? documentInfo.pageCount : -1 + ]); }, /** @@ -425,14 +418,16 @@ * @param {boolean=} opt_showSystemDialog Whether to open system dialog for * advanced settings. */ - startPrint: function(destination, printTicketStore, cloudPrintInterface, - documentInfo, opt_isOpenPdfInPreview, - opt_showSystemDialog) { - assert(printTicketStore.isTicketValid(), - 'Trying to print when ticket is not valid'); + startPrint: function( + destination, printTicketStore, cloudPrintInterface, documentInfo, + opt_isOpenPdfInPreview, opt_showSystemDialog) { + assert( + printTicketStore.isTicketValid(), + 'Trying to print when ticket is not valid'); - assert(!opt_showSystemDialog || (cr.isWindows && destination.isLocal), - 'Implemented for Windows only'); + assert( + !opt_showSystemDialog || (cr.isWindows && destination.isLocal), + 'Implemented for Windows only'); var ticket = { 'mediaSize': printTicketStore.mediaSize.getValue(), @@ -442,7 +437,8 @@ 'headerFooterEnabled': false, // Only used in print preview 'marginsType': printTicketStore.marginsType.getValue(), 'duplex': printTicketStore.duplex.getValue() ? - NativeLayer.DuplexMode.LONG_EDGE : NativeLayer.DuplexMode.SIMPLEX, + NativeLayer.DuplexMode.LONG_EDGE : + NativeLayer.DuplexMode.SIMPLEX, 'copies': printTicketStore.copies.getValueAsNumber(), 'collate': printTicketStore.collate.getValue(), 'shouldPrintBackgrounds': printTicketStore.cssBackground.getValue(), @@ -456,9 +452,11 @@ 'rasterizePDF': printTicketStore.rasterize.getValue(), 'scaleFactor': printTicketStore.scaling.getValueAsNumber(), 'dpiHorizontal': 'horizontal_dpi' in printTicketStore.dpi.getValue() ? - printTicketStore.dpi.getValue().horizontal_dpi : 0, + printTicketStore.dpi.getValue().horizontal_dpi : + 0, 'dpiVertical': 'vertical_dpi' in printTicketStore.dpi.getValue() ? - printTicketStore.dpi.getValue().vertical_dpi : 0, + printTicketStore.dpi.getValue().vertical_dpi : + 0, 'deviceName': destination.id, 'fitToPageEnabled': printTicketStore.fitToPage.getValue(), 'pageWidth': documentInfo.pageSize.width, @@ -558,8 +556,8 @@ * @private */ onSetUseCloudPrint_: function(settings) { - var cloudPrintEnableEvent = new Event( - NativeLayer.EventType.CLOUD_PRINT_ENABLE); + var cloudPrintEnableEvent = + new Event(NativeLayer.EventType.CLOUD_PRINT_ENABLE); cloudPrintEnableEvent.baseCloudPrintUrl = settings['cloudPrintUrl'] || ''; cloudPrintEnableEvent.appKioskMode = settings['appKioskMode'] || false; this.eventTarget_.dispatchEvent(cloudPrintEnableEvent); @@ -567,8 +565,8 @@ /** Reloads the printer list. */ onReloadPrintersList_: function() { - cr.dispatchSimpleEvent(this.eventTarget_, - NativeLayer.EventType.DESTINATIONS_RELOAD); + cr.dispatchSimpleEvent( + this.eventTarget_, NativeLayer.EventType.DESTINATIONS_RELOAD); }, /** @@ -579,8 +577,7 @@ * @private */ onPrintToCloud_: function(data) { - var printToCloudEvent = new Event( - NativeLayer.EventType.PRINT_TO_CLOUD); + var printToCloudEvent = new Event(NativeLayer.EventType.PRINT_TO_CLOUD); printToCloudEvent.data = data; this.eventTarget_.dispatchEvent(printToCloudEvent); }, @@ -623,8 +620,8 @@ * @private */ onInvalidPrinterSettings_: function() { - cr.dispatchSimpleEvent(this.eventTarget_, - NativeLayer.EventType.SETTINGS_INVALID); + cr.dispatchSimpleEvent( + this.eventTarget_, NativeLayer.EventType.SETTINGS_INVALID); }, /** @@ -638,8 +635,8 @@ * @private */ onDidGetDefaultPageLayout_: function(pageLayout, hasCustomPageSizeStyle) { - var pageLayoutChangeEvent = new Event( - NativeLayer.EventType.PAGE_LAYOUT_READY); + var pageLayoutChangeEvent = + new Event(NativeLayer.EventType.PAGE_LAYOUT_READY); pageLayoutChangeEvent.pageLayout = pageLayout; pageLayoutChangeEvent.hasCustomPageSizeStyle = hasCustomPageSizeStyle; this.eventTarget_.dispatchEvent(pageLayoutChangeEvent); @@ -655,10 +652,10 @@ * the document to page, rounded to the nearest integer. * @private */ - onDidGetPreviewPageCount_: function(pageCount, previewResponseId, - fitToPageScaling) { - var pageCountChangeEvent = new Event( - NativeLayer.EventType.PAGE_COUNT_READY); + onDidGetPreviewPageCount_: function( + pageCount, previewResponseId, fitToPageScaling) { + var pageCountChangeEvent = + new Event(NativeLayer.EventType.PAGE_COUNT_READY); pageCountChangeEvent.pageCount = pageCount; pageCountChangeEvent.previewResponseId = previewResponseId; pageCountChangeEvent.fitToPageScaling = fitToPageScaling; @@ -676,8 +673,8 @@ * @private */ onDidPreviewPage_: function(pageNumber, previewUid, previewResponseId) { - var pagePreviewGenEvent = new Event( - NativeLayer.EventType.PAGE_PREVIEW_READY); + var pagePreviewGenEvent = + new Event(NativeLayer.EventType.PAGE_PREVIEW_READY); pagePreviewGenEvent.pageIndex = pageNumber; pagePreviewGenEvent.previewUid = previewUid; pagePreviewGenEvent.previewResponseId = previewResponseId; @@ -691,8 +688,8 @@ * @private */ onDidGetAccessToken_: function(authType, accessToken) { - var getAccessTokenEvent = new Event( - NativeLayer.EventType.ACCESS_TOKEN_READY); + var getAccessTokenEvent = + new Event(NativeLayer.EventType.ACCESS_TOKEN_READY); getAccessTokenEvent.authType = authType; getAccessTokenEvent.accessToken = accessToken; this.eventTarget_.dispatchEvent(getAccessTokenEvent); @@ -708,8 +705,8 @@ * @private */ onUpdatePrintPreview_: function(previewUid, previewResponseId) { - var previewGenDoneEvent = new Event( - NativeLayer.EventType.PREVIEW_GENERATION_DONE); + var previewGenDoneEvent = + new Event(NativeLayer.EventType.PREVIEW_GENERATION_DONE); previewGenDoneEvent.previewUid = previewUid; previewGenDoneEvent.previewResponseId = previewResponseId; this.eventTarget_.dispatchEvent(previewGenDoneEvent); @@ -724,8 +721,8 @@ * @private */ onPrintPresetOptionsFromDocument_: function(options) { - var printPresetOptionsEvent = new Event( - NativeLayer.EventType.PRINT_PRESET_OPTIONS); + var printPresetOptionsEvent = + new Event(NativeLayer.EventType.PRINT_PRESET_OPTIONS); printPresetOptionsEvent.optionsFromDocument = options; this.eventTarget_.dispatchEvent(printPresetOptionsEvent); }, @@ -737,8 +734,8 @@ * @private */ failedToResolveProvisionalDestination_: function(destinationId) { - var evt = new Event( - NativeLayer.EventType.PROVISIONAL_DESTINATION_RESOLVED); + var evt = + new Event(NativeLayer.EventType.PROVISIONAL_DESTINATION_RESOLVED); evt.provisionalId = destinationId; evt.destination = null; this.eventTarget_.dispatchEvent(evt); @@ -757,16 +754,16 @@ * destination info. * @private */ - onProvisionalDestinationResolved_: function(provisionalDestinationId, - destinationInfo) { - var evt = new Event( - NativeLayer.EventType.PROVISIONAL_DESTINATION_RESOLVED); + onProvisionalDestinationResolved_: function( + provisionalDestinationId, destinationInfo) { + var evt = + new Event(NativeLayer.EventType.PROVISIONAL_DESTINATION_RESOLVED); evt.provisionalId = provisionalDestinationId; evt.destination = destinationInfo; this.eventTarget_.dispatchEvent(evt); }, - /** + /** * Allows for onManipulateSettings to be called * from the native layer. * @private @@ -835,19 +832,10 @@ * @constructor */ function NativeInitialSettings( - isInKioskAutoPrintMode, - isInAppKioskMode, - thousandsDelimeter, - decimalDelimeter, - unitType, - isDocumentModifiable, - documentTitle, - documentHasSelection, - selectionOnly, - systemDefaultDestinationId, - serializedAppStateStr, - serializedDefaultDestinationSelectionRulesStr) { - + isInKioskAutoPrintMode, isInAppKioskMode, thousandsDelimeter, + decimalDelimeter, unitType, isDocumentModifiable, documentTitle, + documentHasSelection, selectionOnly, systemDefaultDestinationId, + serializedAppStateStr, serializedDefaultDestinationSelectionRulesStr) { /** * Whether the print preview should be in auto-print mode. * @private {boolean}
diff --git a/chrome/browser/resources/print_preview/preview_generator.js b/chrome/browser/resources/print_preview/preview_generator.js index 0e492e7..37c81e4c 100644 --- a/chrome/browser/resources/print_preview/preview_generator.js +++ b/chrome/browser/resources/print_preview/preview_generator.js
@@ -18,7 +18,7 @@ * @extends {cr.EventTarget} */ function PreviewGenerator( - destinationStore, printTicketStore, nativeLayer, documentInfo) { + destinationStore, printTicketStore, nativeLayer, documentInfo) { cr.EventTarget.call(this); /** @@ -206,11 +206,8 @@ this.inFlightRequestId_++; this.generateDraft_ = this.documentInfo_.isModifiable && previewChanged; this.nativeLayer_.startGetPreview( - this.destinationStore_.selectedDestination, - this.printTicketStore_, - this.documentInfo_, - this.generateDraft_, - this.inFlightRequestId_); + this.destinationStore_.selectedDestination, this.printTicketStore_, + this.documentInfo_, this.generateDraft_, this.inFlightRequestId_); return true; }, @@ -274,13 +271,13 @@ * @private */ dispatchPreviewStartEvent_: function(previewUid, index) { - var previewStartEvent = new Event( - PreviewGenerator.EventType.PREVIEW_START); + var previewStartEvent = + new Event(PreviewGenerator.EventType.PREVIEW_START); if (!this.documentInfo_.isModifiable) { index = -1; } - previewStartEvent.previewUrl = 'chrome://print/' + - previewUid.toString() + '/' + index + '/print.pdf'; + previewStartEvent.previewUrl = 'chrome://print/' + previewUid.toString() + + '/' + index + '/print.pdf'; this.dispatchEvent(previewStartEvent); }, @@ -300,18 +297,18 @@ !ticketStore.scaling.isValueEqual(this.scalingValue_) || !ticketStore.fitToPage.isValueEqual(this.isFitToPageEnabled_) || (!ticketStore.marginsType.isValueEqual(this.marginsType_) && - !ticketStore.marginsType.isValueEqual( - print_preview.ticket_items.MarginsTypeValue.CUSTOM)) || + !ticketStore.marginsType.isValueEqual( + print_preview.ticket_items.MarginsTypeValue.CUSTOM)) || (ticketStore.marginsType.isValueEqual( - print_preview.ticket_items.MarginsTypeValue.CUSTOM) && - !ticketStore.customMargins.isValueEqual( - this.documentInfo_.margins)) || + print_preview.ticket_items.MarginsTypeValue.CUSTOM) && + !ticketStore.customMargins.isValueEqual( + this.documentInfo_.margins)) || !ticketStore.cssBackground.isValueEqual( this.isCssBackgroundEnabled_) || !ticketStore.selectionOnly.isValueEqual( this.isSelectionOnlyEnabled_) || (this.selectedDestination_ != - this.destinationStore_.selectedDestination); + this.destinationStore_.selectedDestination); }, /** @@ -321,8 +318,8 @@ hasPreviewPageRangeChanged_: function() { return this.pageRanges_ == null || !areRangesEqual( - this.printTicketStore_.pageRange.getPageRanges(), - this.pageRanges_); + this.printTicketStore_.pageRange.getPageRanges(), + this.pageRanges_); }, /** @@ -336,8 +333,7 @@ // in-flight request. var origin = new print_preview.Coordinate2d( - event.pageLayout.printableAreaX, - event.pageLayout.printableAreaY); + event.pageLayout.printableAreaX, event.pageLayout.printableAreaY); var size = new print_preview.Size( event.pageLayout.printableAreaWidth, event.pageLayout.printableAreaHeight); @@ -350,16 +346,14 @@ var o = print_preview.ticket_items.CustomMarginsOrientation; var pageSize = new print_preview.Size( - event.pageLayout.contentWidth + - margins.get(o.LEFT) + margins.get(o.RIGHT), - event.pageLayout.contentHeight + - margins.get(o.TOP) + margins.get(o.BOTTOM)); + event.pageLayout.contentWidth + margins.get(o.LEFT) + + margins.get(o.RIGHT), + event.pageLayout.contentHeight + margins.get(o.TOP) + + margins.get(o.BOTTOM)); this.documentInfo_.updatePageInfo( - new print_preview.PrintableArea(origin, size), - pageSize, - event.hasCustomPageSizeStyle, - margins); + new print_preview.PrintableArea(origin, size), pageSize, + event.hasCustomPageSizeStyle, margins); }, /** @@ -370,7 +364,7 @@ */ onPageCountReady_: function(event) { if (this.inFlightRequestId_ != event.previewResponseId) { - return; // Ignore old response. + return; // Ignore old response. } this.documentInfo_.updatePageCount(event.pageCount); this.pageRanges_ = this.printTicketStore_.pageRange.getPageRanges(); @@ -384,7 +378,7 @@ */ onPagePreviewReady_: function(event) { if (this.inFlightRequestId_ != event.previewResponseId) { - return; // Ignore old response. + return; // Ignore old response. } var pageNumber = event.pageIndex + 1; var pageNumberSet = this.printTicketStore_.pageRange.getPageNumberSet(); @@ -406,7 +400,7 @@ */ onPreviewGenerationDone_: function(event) { if (this.inFlightRequestId_ != event.previewResponseId) { - return; // Ignore old response. + return; // Ignore old response. } if (!this.generateDraft_) { // Dispatch a PREVIEW_START event since not generating a draft PDF, @@ -429,7 +423,5 @@ }; // Export - return { - PreviewGenerator: PreviewGenerator - }; + return {PreviewGenerator: PreviewGenerator}; });
diff --git a/chrome/browser/resources/print_preview/previewarea/margin_control.js b/chrome/browser/resources/print_preview/previewarea/margin_control.js index f324dc9..72fe4bc 100644 --- a/chrome/browser/resources/print_preview/previewarea/margin_control.js +++ b/chrome/browser/resources/print_preview/previewarea/margin_control.js
@@ -219,8 +219,7 @@ */ setPositionInPts: function(posInPts) { this.positionInPts_ = posInPts; - var orientationEnum = - print_preview.ticket_items.CustomMarginsOrientation; + var orientationEnum = print_preview.ticket_items.CustomMarginsOrientation; var x = this.translateTransform_.x; var y = this.translateTransform_.y; var width = null, height = null; @@ -270,8 +269,7 @@ */ convertPixelsToPts: function(pixels) { var pts; - var orientationEnum = - print_preview.ticket_items.CustomMarginsOrientation; + var orientationEnum = print_preview.ticket_items.CustomMarginsOrientation; if (this.orientation_ == orientationEnum.TOP) { pts = pixels - this.translateTransform_.y + MarginControl.RADIUS_; pts /= this.scaleTransform_; @@ -307,8 +305,8 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'margin-control-template')); + this.setElementInternal( + this.cloneTemplateInternal('margin-control-template')); this.getElement().classList.add('margin-control-' + this.orientation_); this.textbox_ = this.getElement().getElementsByClassName( MarginControl.Classes_.TEXTBOX)[0]; @@ -324,12 +322,9 @@ this.tracker.add( this.getElement(), 'mousedown', this.onMouseDown_.bind(this)); this.tracker.add( - this.getElement(), - 'transitionend', - this.onTransitionEnd_.bind(this)); + this.getElement(), 'transitionend', this.onTransitionEnd_.bind(this)); assert(this.textbox_); - this.tracker.add( - this.textbox_, 'input', this.onTextboxInput_.bind(this)); + this.tracker.add(this.textbox_, 'input', this.onTextboxInput_.bind(this)); this.tracker.add( this.textbox_, 'keydown', this.onTextboxKeyDown_.bind(this)); this.tracker.add( @@ -369,10 +364,9 @@ * @private */ onMouseDown_: function(event) { - if (!this.textbox_.disabled && - event.button == 0 && + if (!this.textbox_.disabled && event.button == 0 && (event.target == this.getElement() || - event.target == this.marginLineEl_)) { + event.target == this.marginLineEl_)) { this.mouseStartPositionInPixels_ = new print_preview.Coordinate2d(event.x, event.y); this.marginStartPositionInPixels_ = new print_preview.Coordinate2d( @@ -449,7 +443,5 @@ }; // Export - return { - MarginControl: MarginControl - }; + return {MarginControl: MarginControl}; });
diff --git a/chrome/browser/resources/print_preview/previewarea/margin_control_container.js b/chrome/browser/resources/print_preview/previewarea/margin_control_container.js index 33ab6b2..9a6f8042 100644 --- a/chrome/browser/resources/print_preview/previewarea/margin_control_container.js +++ b/chrome/browser/resources/print_preview/previewarea/margin_control_container.js
@@ -20,9 +20,9 @@ * @constructor * @extends {print_preview.Component} */ - function MarginControlContainer(documentInfo, marginsTypeTicketItem, - customMarginsTicketItem, measurementSystem, - dragChangedCallback) { + function MarginControlContainer( + documentInfo, marginsTypeTicketItem, customMarginsTicketItem, + measurementSystem, dragChangedCallback) { print_preview.Component.call(this); /** @@ -69,8 +69,8 @@ */ this.controls_ = {}; for (var key in print_preview.ticket_items.CustomMarginsOrientation) { - var orientation = print_preview.ticket_items.CustomMarginsOrientation[ - key]; + var orientation = + print_preview.ticket_items.CustomMarginsOrientation[key]; var control = new print_preview.MarginControl(orientation); this.controls_[orientation] = control; this.addChild(control); @@ -130,7 +130,7 @@ return orientation == print_preview.ticket_items.CustomMarginsOrientation.TOP || orientation == - print_preview.ticket_items.CustomMarginsOrientation.BOTTOM; + print_preview.ticket_items.CustomMarginsOrientation.BOTTOM; }; MarginControlContainer.prototype = { @@ -175,11 +175,10 @@ this.clippingSize_ = clipSize; for (var orientation in this.controls_) { var el = this.controls_[orientation].getElement(); - el.style.clip = 'rect(' + - (-el.offsetTop) + 'px, ' + + el.style.clip = 'rect(' + (-el.offsetTop) + 'px, ' + (clipSize.width - el.offsetLeft) + 'px, ' + - (clipSize.height - el.offsetTop) + 'px, ' + - (-el.offsetLeft) + 'px)'; + (clipSize.height - el.offsetTop) + 'px, ' + (-el.offsetLeft) + + 'px)'; } }, @@ -205,8 +204,7 @@ this.getElement(), 'mouseout', this.onMouseOut_.bind(this)); this.tracker.add( - this.documentInfo_, - print_preview.DocumentInfo.EventType.CHANGE, + this.documentInfo_, print_preview.DocumentInfo.EventType.CHANGE, this.onTicketChange_.bind(this)); this.tracker.add( this.marginsTypeTicketItem_, @@ -261,9 +259,9 @@ } else { newPosInPts = control.convertPixelsToPts(posInPixels.x); } - newPosInPts = Math.min(this.customMarginsTicketItem_.getMarginMax( - control.getOrientation()), - newPosInPts); + newPosInPts = Math.min( + this.customMarginsTicketItem_.getMarginMax(control.getOrientation()), + newPosInPts); newPosInPts = Math.max(0, newPosInPts); newPosInPts = Math.round(newPosInPts); control.setPositionInPts(newPosInPts); @@ -281,9 +279,9 @@ if (value.length == 0) { return null; } - var validationRegex = new RegExp('^(^-?)(\\d)+(\\' + - this.measurementSystem_.thousandsDelimeter + '\\d{3})*(\\' + - this.measurementSystem_.decimalDelimeter + '\\d*)?' + + var validationRegex = new RegExp( + '^(^-?)(\\d)+(\\' + this.measurementSystem_.thousandsDelimeter + + '\\d{3})*(\\' + this.measurementSystem_.decimalDelimeter + '\\d*)?' + '(' + this.measurementSystem_.unitSymbol + ')?$'); if (validationRegex.test(value)) { // Replacing decimal point with the dot symbol in order to use @@ -476,7 +474,5 @@ }; // Export - return { - MarginControlContainer: MarginControlContainer - }; + return {MarginControlContainer: MarginControlContainer}; });
diff --git a/chrome/browser/resources/print_preview/previewarea/preview_area.js b/chrome/browser/resources/print_preview/previewarea/preview_area.js index 9860795..994668d 100644 --- a/chrome/browser/resources/print_preview/previewarea/preview_area.js +++ b/chrome/browser/resources/print_preview/previewarea/preview_area.js
@@ -116,8 +116,7 @@ * @private */ this.marginControlContainer_ = new print_preview.MarginControlContainer( - this.documentInfo_, - this.printTicketStore_.marginsType, + this.documentInfo_, this.printTicketStore_.marginsType, this.printTicketStore_.customMargins, this.printTicketStore_.measurementSystem, this.onMarginDragChanged_.bind(this)); @@ -225,8 +224,8 @@ 'preview-area-custom-message'; PreviewArea.MessageIdClassMap_[print_preview.PreviewAreaMessageId_.LOADING] = 'preview-area-loading-message'; - PreviewArea.MessageIdClassMap_[ - print_preview.PreviewAreaMessageId_.PREVIEW_FAILED] = + PreviewArea + .MessageIdClassMap_[print_preview.PreviewAreaMessageId_.PREVIEW_FAILED] = 'preview-area-preview-failed-message'; /** @@ -314,45 +313,33 @@ print_preview.Component.prototype.enterDocument.call(this); this.tracker.add( - assert(this.openSystemDialogButton_), - 'click', + assert(this.openSystemDialogButton_), 'click', this.onOpenSystemDialogButtonClick_.bind(this)); var TicketStoreEvent = print_preview.PrintTicketStore.EventType; - [ - TicketStoreEvent.INITIALIZE, - TicketStoreEvent.TICKET_CHANGE, - TicketStoreEvent.CAPABILITIES_CHANGE, - TicketStoreEvent.DOCUMENT_CHANGE - ].forEach(function(eventType) { - this.tracker.add(this.printTicketStore_, eventType, - this.onTicketChange_.bind(this)); - }.bind(this)); + [TicketStoreEvent.INITIALIZE, TicketStoreEvent.TICKET_CHANGE, + TicketStoreEvent.CAPABILITIES_CHANGE, TicketStoreEvent.DOCUMENT_CHANGE] + .forEach(function(eventType) { + this.tracker.add( + this.printTicketStore_, eventType, + this.onTicketChange_.bind(this)); + }.bind(this)); - [ - this.printTicketStore_.color, - this.printTicketStore_.cssBackground, - this.printTicketStore_.customMargins, - this.printTicketStore_.fitToPage, - this.printTicketStore_.headerFooter, - this.printTicketStore_.landscape, - this.printTicketStore_.marginsType, - this.printTicketStore_.pageRange, - this.printTicketStore_.rasterize, - this.printTicketStore_.selectionOnly, - this.printTicketStore_.scaling - ].forEach(function(setting) { - this.tracker.add( - setting, - print_preview.ticket_items.TicketItem.EventType.CHANGE, - this.onTicketChange_.bind(this)); - }.bind(this)); + [this.printTicketStore_.color, this.printTicketStore_.cssBackground, + this.printTicketStore_.customMargins, this.printTicketStore_.fitToPage, + this.printTicketStore_.headerFooter, this.printTicketStore_.landscape, + this.printTicketStore_.marginsType, this.printTicketStore_.pageRange, + this.printTicketStore_.rasterize, this.printTicketStore_.selectionOnly, + this.printTicketStore_.scaling] + .forEach(function(setting) { + this.tracker.add( + setting, print_preview.ticket_items.TicketItem.EventType.CHANGE, + this.onTicketChange_.bind(this)); + }.bind(this)); if (this.checkPluginCompatibility_()) { this.previewGenerator_ = new print_preview.PreviewGenerator( - this.destinationStore_, - this.printTicketStore_, - this.nativeLayer_, + this.destinationStore_, this.printTicketStore_, this.nativeLayer_, this.documentInfo_); this.tracker.add( this.previewGenerator_, @@ -442,7 +429,7 @@ jumpingDotsEl.classList.add('jumping-dots'); } var messageEl = this.getElement().getElementsByClassName( - PreviewArea.MessageIdClassMap_[messageId])[0]; + PreviewArea.MessageIdClassMap_[messageId])[0]; setIsVisible(messageEl, true); this.setOverlayVisible_(true); @@ -455,8 +442,7 @@ */ setOverlayVisible_: function(visible) { this.overlayEl_.classList.toggle( - PreviewArea.Classes_.INVISIBLE, - !visible); + PreviewArea.Classes_.INVISIBLE, !visible); this.overlayEl_.setAttribute('aria-hidden', !visible); // Hide/show all controls that will overlap when the overlay is visible. @@ -486,7 +472,7 @@ */ createPlugin_: function(srcUrl) { assert(!this.plugin_); - this.plugin_ = /** @type {print_preview.PDFPlugin} */( + this.plugin_ = /** @type {print_preview.PDFPlugin} */ ( PDFCreateOutOfProcessPlugin(srcUrl)); this.plugin_.setKeyEventCallback(this.keyEventCallback_); @@ -497,8 +483,8 @@ // chrome/renderer/printing/print_web_view_helper.cc actually references // it. this.plugin_.setAttribute('id', 'pdf-viewer'); - this.getChildElement('.preview-area-plugin-wrapper'). - appendChild(/** @type {Node} */(this.plugin_)); + this.getChildElement('.preview-area-plugin-wrapper') + .appendChild(/** @type {Node} */ (this.plugin_)); this.plugin_.setLoadCallback(this.onPluginLoad_.bind(this)); this.plugin_.setViewportChangedCallback( @@ -542,8 +528,8 @@ this, PreviewArea.EventType.PREVIEW_GENERATION_IN_PROGRESS); if (this.loadingTimeout_ == null) { this.loadingTimeout_ = setTimeout( - this.showMessage_.bind(this, - print_preview.PreviewAreaMessageId_.LOADING), + this.showMessage_.bind( + this, print_preview.PreviewAreaMessageId_.LOADING), PreviewArea.LOADING_TIMEOUT_); } } else { @@ -563,8 +549,7 @@ this.createPlugin_(event.previewUrl); } this.plugin_.resetPrintPreviewMode( - event.previewUrl, - !this.printTicketStore_.color.getValue(), + event.previewUrl, !this.printTicketStore_.color.getValue(), this.printTicketStore_.pageRange.getPageNumberSet().asArray(), this.documentInfo_.isModifiable); @@ -632,11 +617,8 @@ * margins component if shown. * @private */ - onPreviewVisualStateChange_: function(pageX, - pageY, - pageWidth, - viewportWidth, - viewportHeight) { + onPreviewVisualStateChange_: function( + pageX, pageY, pageWidth, viewportWidth, viewportHeight) { this.marginControlContainer_.updateTranslationTransform( new print_preview.Coordinate2d(pageX, pageY)); this.marginControlContainer_.updateScaleTransform( @@ -663,7 +645,5 @@ }; // Export - return { - PreviewArea: PreviewArea - }; + return {PreviewArea: PreviewArea}; });
diff --git a/chrome/browser/resources/print_preview/print_header.js b/chrome/browser/resources/print_preview/print_header.js index 9a132f8..901718c 100644 --- a/chrome/browser/resources/print_preview/print_header.js +++ b/chrome/browser/resources/print_preview/print_header.js
@@ -98,12 +98,10 @@ // User events this.tracker.add( - this.getChildElement('button.cancel'), - 'click', + this.getChildElement('button.cancel'), 'click', this.onCancelButtonClick_.bind(this)); this.tracker.add( - this.getChildElement('button.print'), - 'click', + this.getChildElement('button.print'), 'click', this.onPrintButtonClick_.bind(this)); // Data events. @@ -144,8 +142,7 @@ updatePrintButtonEnabledState_: function() { this.getChildElement('button.print').disabled = this.destinationStore_.selectedDestination == null || - !this.isEnabled_ || - !this.isPrintButtonEnabled_ || + !this.isEnabled_ || !this.isPrintButtonEnabled_ || !this.printTicketStore_.isTicketValid(); }, @@ -161,9 +158,9 @@ var saveToPdfOrDrive = this.destinationStore_.selectedDestination && (this.destinationStore_.selectedDestination.id == - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF || + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF || this.destinationStore_.selectedDestination.id == - print_preview.Destination.GooglePromotedId.DOCS); + print_preview.Destination.GooglePromotedId.DOCS); var numPages = this.printTicketStore_.pageRange.getPageNumberSet().size; var numSheets = numPages; @@ -178,7 +175,8 @@ var pagesLabel = loadTimeData.getString('printPreviewPageLabelPlural'); var summaryLabel; if (numSheets > 1) { - summaryLabel = saveToPdfOrDrive ? pagesLabel : + summaryLabel = saveToPdfOrDrive ? + pagesLabel : loadTimeData.getString('printPreviewSheetsLabelPlural'); } else { summaryLabel = loadTimeData.getString( @@ -192,22 +190,19 @@ html = loadTimeData.getStringF( 'printPreviewSummaryFormatLong', '<b>' + numSheets.toLocaleString() + '</b>', - '<b>' + summaryLabel + '</b>', - numPages.toLocaleString(), + '<b>' + summaryLabel + '</b>', numPages.toLocaleString(), pagesLabel); - label = loadTimeData.getStringF('printPreviewSummaryFormatLong', - numSheets.toLocaleString(), - summaryLabel, - numPages.toLocaleString(), - pagesLabel); + label = loadTimeData.getStringF( + 'printPreviewSummaryFormatLong', numSheets.toLocaleString(), + summaryLabel, numPages.toLocaleString(), pagesLabel); } else { html = loadTimeData.getStringF( 'printPreviewSummaryFormatShort', '<b>' + numSheets.toLocaleString() + '</b>', '<b>' + summaryLabel + '</b>'); - label = loadTimeData.getStringF('printPreviewSummaryFormatShort', - numSheets.toLocaleString(), - summaryLabel); + label = loadTimeData.getStringF( + 'printPreviewSummaryFormatShort', numSheets.toLocaleString(), + summaryLabel); } // Removing extra spaces from within the string. @@ -228,7 +223,8 @@ print_preview.Destination.GooglePromotedId.SAVE_AS_PDF) { this.getChildElement('button.print').classList.add('loading'); this.getChildElement('button.cancel').classList.add('loading'); - var isSaveLabel = (this.destinationStore_.selectedDestination.id == + var isSaveLabel = + (this.destinationStore_.selectedDestination.id == print_preview.Destination.GooglePromotedId.DOCS); this.getChildElement('.summary').innerHTML = loadTimeData.getString(isSaveLabel ? 'saving' : 'printing'); @@ -279,7 +275,5 @@ }; // Export - return { - PrintHeader: PrintHeader - }; + return {PrintHeader: PrintHeader}; });
diff --git a/chrome/browser/resources/print_preview/print_preview.js b/chrome/browser/resources/print_preview/print_preview.js index 1da05fe34..1162a515 100644 --- a/chrome/browser/resources/print_preview/print_preview.js +++ b/chrome/browser/resources/print_preview/print_preview.js
@@ -124,8 +124,8 @@ * @type {!print_preview.DestinationSettings} * @private */ - this.destinationSettings_ = new print_preview.DestinationSettings( - this.destinationStore_); + this.destinationSettings_ = + new print_preview.DestinationSettings(this.destinationStore_); this.addChild(this.destinationSettings_); /** @@ -133,8 +133,8 @@ * @type {!print_preview.PageSettings} * @private */ - this.pageSettings_ = new print_preview.PageSettings( - this.printTicketStore_.pageRange); + this.pageSettings_ = + new print_preview.PageSettings(this.printTicketStore_.pageRange); this.addChild(this.pageSettings_); /** @@ -164,7 +164,7 @@ new print_preview.ColorSettings(this.printTicketStore_.color); this.addChild(this.colorSettings_); - /** + /** * Component that renders the media size settings. * @type {!print_preview.MediaSizeSettings} * @private @@ -196,9 +196,8 @@ * @type {!print_preview.ScalingSettings} * @private */ - this.scalingSettings_ = - new print_preview.ScalingSettings(this.printTicketStore_.scaling, - this.printTicketStore_.fitToPage); + this.scalingSettings_ = new print_preview.ScalingSettings( + this.printTicketStore_.scaling, this.printTicketStore_.fitToPage); this.addChild(this.scalingSettings_); /** @@ -207,12 +206,10 @@ * @private */ this.otherOptionsSettings_ = new print_preview.OtherOptionsSettings( - this.printTicketStore_.duplex, - this.printTicketStore_.fitToPage, + this.printTicketStore_.duplex, this.printTicketStore_.fitToPage, this.printTicketStore_.cssBackground, this.printTicketStore_.selectionOnly, - this.printTicketStore_.headerFooter, - this.printTicketStore_.rasterize); + this.printTicketStore_.headerFooter, this.printTicketStore_.rasterize); this.addChild(this.otherOptionsSettings_); /** @@ -229,22 +226,16 @@ * @type {!print_preview.AdvancedSettings} * @private */ - this.advancedSettings_ = new print_preview.AdvancedSettings( - this.printTicketStore_); + this.advancedSettings_ = + new print_preview.AdvancedSettings(this.printTicketStore_); this.addChild(this.advancedSettings_); var settingsSections = [ - this.destinationSettings_, - this.pageSettings_, - this.copiesSettings_, - this.mediaSizeSettings_, - this.layoutSettings_, - this.marginSettings_, - this.colorSettings_, - this.dpiSettings_, - this.scalingSettings_, - this.otherOptionsSettings_, - this.advancedOptionsSettings_]; + this.destinationSettings_, this.pageSettings_, this.copiesSettings_, + this.mediaSizeSettings_, this.layoutSettings_, this.marginSettings_, + this.colorSettings_, this.dpiSettings_, this.scalingSettings_, + this.otherOptionsSettings_, this.advancedOptionsSettings_ + ]; /** * Component representing more/less settings button. @@ -260,10 +251,9 @@ * @type {!print_preview.PreviewArea} * @private */ - this.previewArea_ = new print_preview.PreviewArea(this.destinationStore_, - this.printTicketStore_, - this.nativeLayer_, - this.documentInfo_); + this.previewArea_ = new print_preview.PreviewArea( + this.destinationStore_, this.printTicketStore_, this.nativeLayer_, + this.documentInfo_); this.addChild(this.previewArea_); /** @@ -341,12 +331,13 @@ this.onInitialSettingsSet_.bind(this)); print_preview.PrintPreviewFocusManager.getInstance().initialize(); cr.ui.FocusOutlineManager.forDocument(document); - this.listenerTracker.add('print-failed', - this.onPrintFailed_.bind(this)); - this.listenerTracker.add('privet-printer-added', + this.listenerTracker.add('print-failed', this.onPrintFailed_.bind(this)); + this.listenerTracker.add( + 'privet-printer-added', this.destinationStore_.onPrivetPrinterAdded_.bind( this.destinationStore_)); - this.listenerTracker.add('extension-printers-added', + this.listenerTracker.add( + 'extension-printers-added', this.destinationStore_.onExtensionPrintersAdded_.bind( this.destinationStore_)); }, @@ -390,14 +381,12 @@ if ($('system-dialog-link')) { this.tracker.add( - getRequiredElement('system-dialog-link'), - 'click', + getRequiredElement('system-dialog-link'), 'click', this.openSystemPrintDialog_.bind(this)); } if ($('open-pdf-in-preview-link')) { this.tracker.add( - getRequiredElement('open-pdf-in-preview-link'), - 'click', + getRequiredElement('open-pdf-in-preview-link'), 'click', this.onOpenPdfInPreviewLinkClick_.bind(this)); } @@ -420,8 +409,8 @@ this.tracker.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - SELECTED_DESTINATION_CAPABILITIES_READY, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, this.printIfReady_.bind(this)); this.tracker.add( this.destinationStore_, @@ -478,17 +467,14 @@ // TODO(rltoscano): Move no-destinations-promo into its own component // instead being part of PrintPreview. this.tracker.add( - this.getChildElement('#no-destinations-promo .close-button'), - 'click', + this.getChildElement('#no-destinations-promo .close-button'), 'click', this.onNoDestinationsPromoClose_.bind(this)); this.tracker.add( this.getChildElement('#no-destinations-promo .not-now-button'), - 'click', - this.onNoDestinationsPromoClose_.bind(this)); + 'click', this.onNoDestinationsPromoClose_.bind(this)); this.tracker.add( this.getChildElement('#no-destinations-promo .add-printer-button'), - 'click', - this.onNoDestinationsPromoClick_.bind(this)); + 'click', this.onNoDestinationsPromoClick_.bind(this)); }, /** @override */ @@ -542,12 +528,14 @@ * @private */ printDocumentOrOpenPdfPreview_: function(isPdfPreview) { - assert(this.uiState_ == PrintPreviewUiState_.READY, - 'Print document request received when not in ready state: ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.READY, + 'Print document request received when not in ready state: ' + + this.uiState_); if (isPdfPreview) { this.uiState_ = PrintPreviewUiState_.OPENING_PDF_PREVIEW; - } else if (this.destinationStore_.selectedDestination.id == + } else if ( + this.destinationStore_.selectedDestination.id == print_preview.Destination.GooglePromotedId.SAVE_AS_PDF) { this.uiState_ = PrintPreviewUiState_.FILE_SELECTION; } else { @@ -564,7 +552,7 @@ !this.destinationStore_.selectedDestination.isExtension && this.destinationStore_.selectedDestination.id != print_preview.Destination.GooglePromotedId.SAVE_AS_PDF) || - this.uiState_ == PrintPreviewUiState_.OPENING_PDF_PREVIEW) { + this.uiState_ == PrintPreviewUiState_.OPENING_PDF_PREVIEW) { // Hide the dialog for now. The actual print command will be issued // when the preview generation is done. this.nativeLayer_.startHideDialog(); @@ -591,21 +579,20 @@ if (this.isPreviewGenerationInProgress_) { return print_preview.PrintAttemptResult_.READY_WAITING_FOR_PREVIEW; } - assert(this.printTicketStore_.isTicketValid(), + assert( + this.printTicketStore_.isTicketValid(), 'Trying to print with invalid ticket'); if (getIsVisible(this.moreSettings_.getElement())) { new print_preview.PrintSettingsUiMetricsContext().record( this.moreSettings_.isExpanded ? - print_preview.Metrics.PrintSettingsUiBucket. - PRINT_WITH_SETTINGS_EXPANDED : - print_preview.Metrics.PrintSettingsUiBucket. - PRINT_WITH_SETTINGS_COLLAPSED); + print_preview.Metrics.PrintSettingsUiBucket + .PRINT_WITH_SETTINGS_EXPANDED : + print_preview.Metrics.PrintSettingsUiBucket + .PRINT_WITH_SETTINGS_COLLAPSED); } this.nativeLayer_.startPrint( assert(this.destinationStore_.selectedDestination), - this.printTicketStore_, - this.cloudPrintInterface_, - this.documentInfo_, + this.printTicketStore_, this.cloudPrintInterface_, this.documentInfo_, this.uiState_ == PrintPreviewUiState_.OPENING_PDF_PREVIEW, this.showSystemDialogBeforeNextPrint_); this.showSystemDialogBeforeNextPrint_ = false; @@ -651,9 +638,10 @@ * @private */ onInitialSettingsSet_: function(settings) { - assert(this.uiState_ == PrintPreviewUiState_.INITIALIZING, - 'Updating initial settings when not in initializing state: ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.INITIALIZING, + 'Updating initial settings when not in initializing state: ' + + this.uiState_); this.uiState_ = PrintPreviewUiState_.READY; this.isInKioskAutoPrintMode_ = settings.isInKioskAutoPrintMode; @@ -662,25 +650,22 @@ // The following components must be initialized in this order. this.appState_.init(settings.serializedAppStateStr); this.documentInfo_.init( - settings.isDocumentModifiable, - settings.documentTitle, + settings.isDocumentModifiable, settings.documentTitle, settings.documentHasSelection); this.printTicketStore_.init( - settings.thousandsDelimeter, - settings.decimalDelimeter, - settings.unitType, - settings.selectionOnly); + settings.thousandsDelimeter, settings.decimalDelimeter, + settings.unitType, settings.selectionOnly); this.destinationStore_.init( - settings.isInAppKioskMode, - settings.systemDefaultDestinationId, + settings.isInAppKioskMode, settings.systemDefaultDestinationId, settings.serializedDefaultDestinationSelectionRulesStr); this.appState_.setInitialized(); $('document-title').innerText = settings.documentTitle; this.hideSystemDialogLink_ = settings.isInAppKioskMode; if ($('system-dialog-link')) { - setIsVisible(getRequiredElement('system-dialog-link'), - this.shouldShowSystemDialogLink_()); + setIsVisible( + getRequiredElement('system-dialog-link'), + this.shouldShowSystemDialogLink_()); } }, @@ -693,9 +678,7 @@ */ onCloudPrintEnable_: function(event) { this.cloudPrintInterface_ = new cloudprint.CloudPrintInterface( - event.baseCloudPrintUrl, - this.nativeLayer_, - this.userInfo_, + event.baseCloudPrintUrl, this.nativeLayer_, this.userInfo_, event.appKioskMode); this.tracker.add( this.cloudPrintInterface_, @@ -728,17 +711,17 @@ * @private */ onPrintToCloud_: function(event) { - assert(this.uiState_ == PrintPreviewUiState_.PRINTING, - 'Document ready to be sent to the cloud when not in printing ' + - 'state: ' + this.uiState_); - assert(this.cloudPrintInterface_ != null, - 'Google Cloud Print is not enabled'); + assert( + this.uiState_ == PrintPreviewUiState_.PRINTING, + 'Document ready to be sent to the cloud when not in printing ' + + 'state: ' + this.uiState_); + assert( + this.cloudPrintInterface_ != null, + 'Google Cloud Print is not enabled'); assert(this.destinationStore_.selectedDestination != null); this.cloudPrintInterface_.submit( - this.destinationStore_.selectedDestination, - this.printTicketStore_, - this.documentInfo_, - event.data); + this.destinationStore_.selectedDestination, this.printTicketStore_, + this.documentInfo_, event.data); }, /** @@ -747,9 +730,10 @@ * @private */ onFileSelectionCancel_: function() { - assert(this.uiState_ == PrintPreviewUiState_.FILE_SELECTION, - 'File selection cancelled when not in file-selection state: ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.FILE_SELECTION, + 'File selection cancelled when not in file-selection state: ' + + this.uiState_); this.setIsEnabled_(true); this.uiState_ = PrintPreviewUiState_.READY; }, @@ -759,9 +743,10 @@ * @private */ onFileSelectionComplete_: function() { - assert(this.uiState_ == PrintPreviewUiState_.FILE_SELECTION, - 'File selection completed when not in file-selection state: ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.FILE_SELECTION, + 'File selection completed when not in file-selection state: ' + + this.uiState_); this.previewArea_.showCustomMessage( loadTimeData.getString('printingToPDFInProgress')); this.uiState_ = PrintPreviewUiState_.PRINTING; @@ -773,9 +758,10 @@ * @private */ onCloudPrintSubmitDone_: function(event) { - assert(this.uiState_ == PrintPreviewUiState_.PRINTING, - 'Submited job to Google Cloud Print but not in printing state ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.PRINTING, + 'Submited job to Google Cloud Print but not in printing state ' + + this.uiState_); this.close_(); }, @@ -787,7 +773,7 @@ */ onCloudPrintError_: function(event) { if (event.status == 0) { - return; // Ignore, the system does not have internet connectivity. + return; // Ignore, the system does not have internet connectivity. } if (event.status == 403) { if (!this.isInAppKioskMode_) { @@ -797,8 +783,9 @@ this.printHeader_.setErrorMessage(event.message); } if (event.status == 200) { - console.error('Google Cloud Print Error: (' + event.errorCode + ') ' + - event.message); + console.error( + 'Google Cloud Print Error: (' + event.errorCode + ') ' + + event.message); } else { console.error('Google Cloud Print Error: HTTP status ' + event.status); } @@ -842,9 +829,10 @@ onOpenPdfInPreviewLinkClick_: function() { if ($('open-pdf-in-preview-link').classList.contains('disabled')) return; - assert(this.uiState_ == PrintPreviewUiState_.READY, - 'Trying to open pdf in preview when not in ready state: ' + - this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.READY, + 'Trying to open pdf in preview when not in ready state: ' + + this.uiState_); setIsVisible(getRequiredElement('open-preview-app-throbber'), true); this.previewArea_.showCustomMessage( loadTimeData.getString('openingPDFInPreview')); @@ -857,8 +845,9 @@ * @private */ onPrintButtonClick_: function() { - assert(this.uiState_ == PrintPreviewUiState_.READY, - 'Trying to print when not in ready state: ' + this.uiState_); + assert( + this.uiState_ == PrintPreviewUiState_.READY, + 'Trying to print when not in ready state: ' + this.uiState_); this.printDocumentOrOpenPdfPreview_(false /*isPdfPreview*/); }, @@ -875,11 +864,11 @@ * Called when the register promo for Cloud Print is clicked. * @private */ - onCloudPrintRegisterPromoClick_: function(e) { - var devicesUrl = 'chrome://devices/register?id=' + e.destination.id; - this.nativeLayer_.startForceOpenNewTab(devicesUrl); - this.destinationStore_.waitForRegister(e.destination.id); - }, + onCloudPrintRegisterPromoClick_: function(e) { + var devicesUrl = 'chrome://devices/register?id=' + e.destination.id; + this.nativeLayer_.startForceOpenNewTab(devicesUrl); + this.destinationStore_.waitForRegister(e.destination.id); + }, /** * Consume escape key presses and ctrl + shift + p. Delegate everything else @@ -924,7 +913,8 @@ this.destinationStore_.selectedDestination && this.printTicketStore_.isTicketValid() && this.printHeader_.isPrintButtonEnabled) { - assert(this.uiState_ == PrintPreviewUiState_.READY, + assert( + this.uiState_ == PrintPreviewUiState_.READY, 'Trying to print when not in ready state: ' + this.uiState_); var activeElementTag = document.activeElement.tagName.toUpperCase(); if (activeElementTag != 'BUTTON' && activeElementTag != 'SELECT' && @@ -1031,8 +1021,7 @@ */ onPageCountReady_: function(event) { if (event.fitToPageScaling >= 0) { - this.scalingSettings_.updateFitToPageScaling( - event.fitToPageScaling); + this.scalingSettings_.updateFitToPageScaling(event.fitToPageScaling); } }, @@ -1056,7 +1045,7 @@ */ onManipulateSettingsForTest_: function(event) { var settings = - /** @type {print_preview.PreviewSettings} */(event.settings); + /** @type {print_preview.PreviewSettings} */ (event.settings); if ('selectSaveAsPdfDestination' in settings) { this.saveAsPdfForTest_(); // No parameters. } else if ('layoutSettings' in settings) { @@ -1081,7 +1070,7 @@ saveAsPdfForTest_: function() { if (this.destinationStore_.selectedDestination && print_preview.Destination.GooglePromotedId.SAVE_AS_PDF == - this.destinationStore_.selectedDestination.id) { + this.destinationStore_.selectedDestination.id) { this.nativeLayer_.previewReadyForTest(); return; } @@ -1197,9 +1186,9 @@ return true; var selectedDest = this.destinationStore_.selectedDestination; return !!selectedDest && - selectedDest.origin == print_preview.DestinationOrigin.LOCAL && - selectedDest.id != - print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; + selectedDest.origin == print_preview.DestinationOrigin.LOCAL && + selectedDest.id != + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF; }, /** @@ -1209,8 +1198,9 @@ */ onDestinationSelect_: function() { if ($('system-dialog-link')) { - setIsVisible(getRequiredElement('system-dialog-link'), - this.shouldShowSystemDialogLink_()); + setIsVisible( + getRequiredElement('system-dialog-link'), + this.shouldShowSystemDialogLink_()); } // Reset if we had a bad settings fetch since the user selected a new // printer. @@ -1229,15 +1219,13 @@ * @private */ onDestinationSearchDone_: function() { - var isPromoVisible = cr.isChromeOS && - this.cloudPrintInterface_ && - this.userInfo_.activeUser && - !this.appState_.isGcpPromoDismissed && + var isPromoVisible = cr.isChromeOS && this.cloudPrintInterface_ && + this.userInfo_.activeUser && !this.appState_.isGcpPromoDismissed && !this.destinationStore_.isLocalDestinationSearchInProgress && !this.destinationStore_.isCloudDestinationSearchInProgress && this.destinationStore_.hasOnlyDefaultCloudDestinations(); - setIsVisible(this.getChildElement('#no-destinations-promo'), - isPromoVisible); + setIsVisible( + this.getChildElement('#no-destinations-promo'), isPromoVisible); if (isPromoVisible) { new print_preview.GcpPromoMetricsContext().record( print_preview.Metrics.GcpPromoBucket.PROMO_SHOWN); @@ -1265,16 +1253,15 @@ new print_preview.GcpPromoMetricsContext().record( print_preview.Metrics.GcpPromoBucket.PROMO_CLICKED); this.appState_.persistIsGcpPromoDismissed(true); - window.open(this.cloudPrintInterface_.baseUrl + '?user=' + - this.userInfo_.activeUser + '#printers'); + window.open( + this.cloudPrintInterface_.baseUrl + + '?user=' + this.userInfo_.activeUser + '#printers'); this.close_(); } }; // Export - return { - PrintPreview: PrintPreview - }; + return {PrintPreview: PrintPreview}; }); // Pull in all other scripts in a single shot.
diff --git a/chrome/browser/resources/print_preview/print_preview_animations.js b/chrome/browser/resources/print_preview/print_preview_animations.js index 8a8e831c..86ead3a 100644 --- a/chrome/browser/resources/print_preview/print_preview_animations.js +++ b/chrome/browser/resources/print_preview/print_preview_animations.js
@@ -10,8 +10,7 @@ function addAnimation(code) { var name = 'anim' + animationCounter; animationCounter++; - var rules = document.createTextNode( - '@keyframes ' + name + ' {' + code + '}'); + var rules = document.createTextNode('@keyframes ' + name + ' {' + code + '}'); var el = document.createElement('style'); el.type = 'text/css'; el.appendChild(rules); @@ -130,11 +129,11 @@ // To make the option visible during the first fade in. el.hidden = false; - var leftColumn = assertInstanceof(el.querySelector('.left-column'), - HTMLElement); + var leftColumn = + assertInstanceof(el.querySelector('.left-column'), HTMLElement); wrapContentsInDiv(leftColumn, ['invisible']); - var rightColumn = assertInstanceof(el.querySelector('.right-column'), - HTMLElement); + var rightColumn = + assertInstanceof(el.querySelector('.right-column'), HTMLElement); wrapContentsInDiv(rightColumn, ['invisible']); var toAnimate = el.querySelectorAll('.collapsible'); @@ -153,11 +152,11 @@ if (!el.classList.contains('visible')) return; - var leftColumn = assertInstanceof(el.querySelector('.left-column'), - HTMLElement); + var leftColumn = + assertInstanceof(el.querySelector('.left-column'), HTMLElement); wrapContentsInDiv(leftColumn, ['visible']); - var rightColumn = assertInstanceof(el.querySelector('.right-column'), - HTMLElement); + var rightColumn = + assertInstanceof(el.querySelector('.right-column'), HTMLElement); if (rightColumn) wrapContentsInDiv(rightColumn, ['visible']);
diff --git a/chrome/browser/resources/print_preview/print_preview_focus_manager.js b/chrome/browser/resources/print_preview/print_preview_focus_manager.js index 921b53a..47bb04b8 100644 --- a/chrome/browser/resources/print_preview/print_preview_focus_manager.js +++ b/chrome/browser/resources/print_preview/print_preview_focus_manager.js
@@ -11,8 +11,7 @@ * @constructor * @extends {cr.ui.FocusManager} */ - function PrintPreviewFocusManager() { - } + function PrintPreviewFocusManager() {} cr.addSingletonGetter(PrintPreviewFocusManager); @@ -30,7 +29,5 @@ }; // Export - return { - PrintPreviewFocusManager: PrintPreviewFocusManager - }; + return {PrintPreviewFocusManager: PrintPreviewFocusManager}; });
diff --git a/chrome/browser/resources/print_preview/print_preview_utils.js b/chrome/browser/resources/print_preview/print_preview_utils.js index 56e2813..7836ad79 100644 --- a/chrome/browser/resources/print_preview/print_preview_utils.js +++ b/chrome/browser/resources/print_preview/print_preview_utils.js
@@ -46,10 +46,9 @@ if (array1.length != array2.length) return false; for (var i = 0; i < array1.length; i++) - if (array1[i].from != array2[i].from || - array1[i].to != array2[i].to) { - return false; - } + if (array1[i].from != array2[i].from || array1[i].to != array2[i].to) { + return false; + } return true; } @@ -73,11 +72,7 @@ } /** @enum {number} */ -var PageRangeStatus = { - NO_ERROR: 0, - SYNTAX_ERROR: -1, - LIMIT_ERROR: -2 -}; +var PageRangeStatus = {NO_ERROR: 0, SYNTAX_ERROR: -1, LIMIT_ERROR: -2}; /** * Returns a list of ranges in |pageRangeText|. The ranges are @@ -111,8 +106,8 @@ } var MAX_PAGE_NUMBER = 1000000000; - var totalPageCount = opt_totalPageCount ? opt_totalPageCount : - MAX_PAGE_NUMBER; + var totalPageCount = + opt_totalPageCount ? opt_totalPageCount : MAX_PAGE_NUMBER; var regex = /^\s*([0-9]*)\s*-\s*([0-9]*)\s*$/; var parts = pageRangeText.split(/,/); @@ -159,8 +154,8 @@ var pageList = []; if (pageRanges instanceof Array) { for (var i = 0; i < pageRanges.length; ++i) { - for (var j = pageRanges[i].from; j <= Math.min(pageRanges[i].to, - totalPageCount); ++j) { + for (var j = pageRanges[i].from; + j <= Math.min(pageRanges[i].to, totalPageCount); ++j) { pageList.push(j); } } @@ -183,7 +178,7 @@ return pageSet; pageSet = pageList.slice(0); pageSet.sort(function(a, b) { - return /** @type {number} */(a) - /** @type {number} */(b); + return /** @type {number} */ (a) - /** @type {number} */ (b); }); pageSet = removeDuplicates(pageSet); return pageSet; @@ -240,6 +235,5 @@ function getStringForCurrentLocale(localizedStrings) { // First try to find an exact match and then look for the language only. return getStringForLocale(localizedStrings, navigator.language) || - getStringForLocale(localizedStrings, - navigator.language.split('-')[0]); + getStringForLocale(localizedStrings, navigator.language.split('-')[0]); }
diff --git a/chrome/browser/resources/print_preview/search/cloud_destination_list.js b/chrome/browser/resources/print_preview/search/cloud_destination_list.js index 1b8d2aa..7f0bcdd 100644 --- a/chrome/browser/resources/print_preview/search/cloud_destination_list.js +++ b/chrome/browser/resources/print_preview/search/cloud_destination_list.js
@@ -14,9 +14,7 @@ */ function CloudDestinationList(eventTarget) { print_preview.DestinationList.call( - this, - eventTarget, - loadTimeData.getString('cloudDestinationsTitle'), + this, eventTarget, loadTimeData.getString('cloudDestinationsTitle'), loadTimeData.getString('manage')); } @@ -30,13 +28,12 @@ var docsId = print_preview.Destination.GooglePromotedId.DOCS; this.setActionLinkTextInternal(loadTimeData.getString( destinations.length == 1 && destinations[0].id == docsId ? - 'setupCloudPrinters' : 'manage')); + 'setupCloudPrinters' : + 'manage')); print_preview.DestinationList.prototype.updateDestinations.call( this, destinations); } }; - return { - CloudDestinationList: CloudDestinationList - }; + return {CloudDestinationList: CloudDestinationList}; });
diff --git a/chrome/browser/resources/print_preview/search/destination_list.js b/chrome/browser/resources/print_preview/search/destination_list.js index a668637..5d0d666 100644 --- a/chrome/browser/resources/print_preview/search/destination_list.js +++ b/chrome/browser/resources/print_preview/search/destination_list.js
@@ -145,10 +145,10 @@ numItems = Math.min(numItems, this.destinations_.length); var headerHeight = this.getChildElement('.destination-list > header').offsetHeight; - return headerHeight + (numItems > 0 ? - numItems * DestinationList.HEIGHT_OF_ITEM_ : - // To account for "No destinations found" message. - DestinationList.HEIGHT_OF_ITEM_); + return headerHeight + + (numItems > 0 ? numItems * DestinationList.HEIGHT_OF_ITEM_ : + // To account for "No destinations found" message. + DestinationList.HEIGHT_OF_ITEM_); }, /** @@ -181,8 +181,8 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'destination-list-template')); + this.setElementInternal( + this.cloneTemplateInternal('destination-list-template')); this.getChildElement('.title').textContent = this.title_; if (this.actionLinkLabel_) { var actionLinkEl = this.getChildElement('.action-link'); @@ -195,12 +195,10 @@ enterDocument: function() { print_preview.Component.prototype.enterDocument.call(this); this.tracker.add( - this.getChildElement('.action-link'), - 'click', + this.getChildElement('.action-link'), 'click', this.onActionLinkClick_.bind(this)); this.tracker.add( - this.getChildElement('.show-all-button'), - 'click', + this.getChildElement('.show-all-button'), 'click', this.setIsShowAll.bind(this, true)); }, @@ -232,7 +230,8 @@ getDestinationItem: function(destinationId) { return this.listItems_.find(function(listItem) { return listItem.destination.id == destinationId; - }) || null; + }) || + null; }, /** @@ -276,8 +275,9 @@ */ renderDestinationsList_: function(destinations) { // Update item counters, footers and other misc controls. - setIsVisible(this.getChildElement('.no-destinations-message'), - destinations.length == 0); + setIsVisible( + this.getChildElement('.no-destinations-message'), + destinations.length == 0); setIsVisible(this.getChildElement('.destination-list > footer'), false); var numItems = destinations.length; if (destinations.length > this.shortListSize_ && !this.isShowAll_) { @@ -309,7 +309,8 @@ // We need to use activeElement instead of :focus selector, which doesn't // work in an inactive page. See crbug.com/723579. var focusedEl = listEl.contains(document.activeElement) ? - document.activeElement : null; + document.activeElement : + null; for (var i = 0; i < numItems; i++) { var destination = assert(destinations[i]); var listItem = visibleListItems[destination.id]; @@ -335,8 +336,8 @@ var itemEl = listItem.getElement(); // Preserve focused inner element, if there's one. - var focusedInnerEl = focusedEl && itemEl.contains(focusedEl) ? - focusedEl : null; + var focusedInnerEl = + focusedEl && itemEl.contains(focusedEl) ? focusedEl : null; if (focusedEl) itemEl.classList.add('moving'); // Move it to the end of the list. @@ -368,13 +369,11 @@ * @private */ onActionLinkClick_: function() { - cr.dispatchSimpleEvent(this, - DestinationList.EventType.ACTION_LINK_ACTIVATED); + cr.dispatchSimpleEvent( + this, DestinationList.EventType.ACTION_LINK_ACTIVATED); } }; // Export - return { - DestinationList: DestinationList - }; + return {DestinationList: DestinationList}; });
diff --git a/chrome/browser/resources/print_preview/search/destination_list_item.js b/chrome/browser/resources/print_preview/search/destination_list_item.js index acaa95b..d925eef5b 100644 --- a/chrome/browser/resources/print_preview/search/destination_list_item.js +++ b/chrome/browser/resources/print_preview/search/destination_list_item.js
@@ -58,8 +58,8 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'destination-list-item-template')); + this.setElementInternal( + this.cloneTemplateInternal('destination-list-item-template')); this.updateUi_(); }, @@ -70,8 +70,7 @@ this.tracker.add( this.getElement(), 'keydown', this.onKeyDown_.bind(this)); this.tracker.add( - this.getChildElement('.register-promo-button'), - 'click', + this.getChildElement('.register-promo-button'), 'click', this.onRegisterPromoClicked_.bind(this)); }, @@ -130,8 +129,7 @@ this.onDestinationActivated_(); } else { this.updateConfiguringMessage_(false); - setIsVisible( - this.getChildElement('.configuring-failed-text'), true); + setIsVisible(this.getChildElement('.configuring-failed-text'), true); } }, @@ -182,15 +180,14 @@ var extensionIconEl = this.getChildElement('.extension-icon'); extensionIconEl.style.backgroundImage = '-webkit-image-set(' + - 'url(chrome://extension-icon/' + - this.destination_.extensionId + '/24/1) 1x,' + - 'url(chrome://extension-icon/' + - this.destination_.extensionId + '/48/1) 2x)'; + 'url(chrome://extension-icon/' + this.destination_.extensionId + + '/24/1) 1x,' + + 'url(chrome://extension-icon/' + this.destination_.extensionId + + '/48/1) 2x)'; extensionIconEl.title = loadTimeData.getStringF( - 'extensionDestinationIconTooltip', - this.destination_.extensionName); + 'extensionDestinationIconTooltip', this.destination_.extensionName); extensionIconEl.onclick = this.onExtensionIconClicked_.bind(this); - extensionIconEl.onkeydown = /** @type {function(Event)} */( + extensionIconEl.onkeydown = /** @type {function(Event)} */ ( this.onExtensionIconKeyDown_.bind(this)); } @@ -213,8 +210,7 @@ if (cr.isChromeOS) { // Reset the configuring messages for CUPS printers. this.updateConfiguringMessage_(false); - setIsVisible( - this.getChildElement('.configuring-failed-text'), false); + setIsVisible(this.getChildElement('.configuring-failed-text'), false); } }, @@ -246,8 +242,7 @@ * @private */ updateConfiguringMessage_: function(show) { - setIsVisible( - this.getChildElement('.configuring-in-progress-text'), show); + setIsVisible(this.getChildElement('.configuring-in-progress-text'), show); this.getChildElement('.configuring-text-jumping-dots') .classList.toggle('jumping-dots', show); }, @@ -278,7 +273,7 @@ */ onDestinationActivated_: function() { if (this.destination_.connectionStatus != - print_preview.DestinationConnectionStatus.UNREGISTERED) { + print_preview.DestinationConnectionStatus.UNREGISTERED) { var selectEvt = new Event(DestinationListItem.EventType.SELECT); selectEvt.destination = this.destination_; this.eventTarget_.dispatchEvent(selectEvt); @@ -295,7 +290,8 @@ if (!hasKeyModifiers(e)) { if (e.keyCode == 13) { var activeElementTag = document.activeElement ? - document.activeElement.tagName.toUpperCase() : ''; + document.activeElement.tagName.toUpperCase() : + ''; if (activeElementTag == 'LI') { e.stopPropagation(); e.preventDefault(); @@ -310,8 +306,8 @@ * @private */ onRegisterPromoClicked_: function() { - var promoClickedEvent = new Event( - DestinationListItem.EventType.REGISTER_PROMO_CLICKED); + var promoClickedEvent = + new Event(DestinationListItem.EventType.REGISTER_PROMO_CLICKED); promoClickedEvent.destination = this.destination_; this.eventTarget_.dispatchEvent(promoClickedEvent); }, @@ -344,7 +340,5 @@ }; // Export - return { - DestinationListItem: DestinationListItem - }; + return {DestinationListItem: DestinationListItem}; });
diff --git a/chrome/browser/resources/print_preview/search/destination_search.js b/chrome/browser/resources/print_preview/search/destination_search.js index c791bf68..fcdca6c 100644 --- a/chrome/browser/resources/print_preview/search/destination_search.js +++ b/chrome/browser/resources/print_preview/search/destination_search.js
@@ -102,10 +102,10 @@ * @private */ this.localList_ = new print_preview.DestinationList( - this, - loadTimeData.getString('localDestinationsTitle'), + this, loadTimeData.getString('localDestinationsTitle'), loadTimeData.getBoolean('showLocalManageButton') ? - loadTimeData.getString('manage') : null); + loadTimeData.getString('manage') : + null); this.addChild(this.localList_); /** @@ -179,8 +179,8 @@ /** @override */ onCancelInternal: function() { - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket. - DESTINATION_CLOSED_UNCHANGED); + this.metrics_.record(print_preview.Metrics.DestinationSearchBucket + .DESTINATION_CLOSED_UNCHANGED); }, /** Shows the Google Cloud Print promotion banner. */ @@ -201,46 +201,38 @@ print_preview.Overlay.prototype.enterDocument.call(this); this.tracker.add( - this.getChildElement('.account-select'), - 'change', + this.getChildElement('.account-select'), 'change', this.onAccountChange_.bind(this)); this.tracker.add( - this.getChildElement('.sign-in'), - 'click', + this.getChildElement('.sign-in'), 'click', this.onSignInActivated_.bind(this)); this.tracker.add( - this.getChildElement('.invitation-accept-button'), - 'click', + this.getChildElement('.invitation-accept-button'), 'click', this.onInvitationProcessButtonClick_.bind(this, true /*accept*/)); this.tracker.add( - this.getChildElement('.invitation-reject-button'), - 'click', + this.getChildElement('.invitation-reject-button'), 'click', this.onInvitationProcessButtonClick_.bind(this, false /*accept*/)); this.tracker.add( - this.getChildElement('.cloudprint-promo > .close-button'), - 'click', + this.getChildElement('.cloudprint-promo > .close-button'), 'click', this.onCloudprintPromoCloseButtonClick_.bind(this)); this.tracker.add( - this.searchBox_, - print_preview.SearchBox.EventType.SEARCH, + this.searchBox_, print_preview.SearchBox.EventType.SEARCH, this.onSearch_.bind(this)); this.tracker.add( - this, - print_preview.DestinationListItem.EventType.CONFIGURE_REQUEST, + this, print_preview.DestinationListItem.EventType.CONFIGURE_REQUEST, this.onDestinationConfigureRequest_.bind(this)); this.tracker.add( - this, - print_preview.DestinationListItem.EventType.SELECT, + this, print_preview.DestinationListItem.EventType.SELECT, this.onDestinationSelect_.bind(this)); this.tracker.add( this, print_preview.DestinationListItem.EventType.REGISTER_PROMO_CLICKED, function() { - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket. - REGISTER_PROMO_SELECTED); + this.metrics_.record(print_preview.Metrics.DestinationSearchBucket + .REGISTER_PROMO_SELECTED); }.bind(this)); this.tracker.add( @@ -284,13 +276,11 @@ this.onManageCloudDestinationsActivated_.bind(this)); this.tracker.add( - this.userInfo_, - print_preview.UserInfo.EventType.USERS_CHANGED, + this.userInfo_, print_preview.UserInfo.EventType.USERS_CHANGED, this.onUsersChanged_.bind(this)); this.tracker.add( - this.getChildElement('.button-strip .cancel-button'), - 'click', + this.getChildElement('.button-strip .cancel-button'), 'click', this.cancel.bind(this)); this.tracker.add(window, 'resize', this.onWindowResize_.bind(this)); @@ -308,8 +298,7 @@ this.localList_.render(this.getChildElement('.local-list')); this.cloudList_.render(this.getChildElement('.cloud-list')); this.getChildElement('.promo-text').innerHTML = loadTimeData.getStringF( - 'cloudPrintPromotion', - '<a is="action-link" class="sign-in">', + 'cloudPrintPromotion', '<a is="action-link" class="sign-in">', '</a>'); this.getChildElement('.account-select-label').textContent = loadTimeData.getString('accountSelectTitle'); @@ -371,7 +360,7 @@ localDestinations.push(destination); } else { if (destination.connectionStatus == - print_preview.DestinationConnectionStatus.UNREGISTERED) { + print_preview.DestinationConnectionStatus.UNREGISTERED) { unregisteredCloudDestinations.push(destination); } else { cloudDestinations.push(destination); @@ -386,11 +375,13 @@ this.registerPromoShownMetricRecorded_ = true; } - var finalCloudDestinations = unregisteredCloudDestinations.slice( - 0, DestinationSearch.MAX_PROMOTED_UNREGISTERED_PRINTERS_).concat( - cloudDestinations, - unregisteredCloudDestinations.slice( - DestinationSearch.MAX_PROMOTED_UNREGISTERED_PRINTERS_)); + var finalCloudDestinations = + unregisteredCloudDestinations + .slice(0, DestinationSearch.MAX_PROMOTED_UNREGISTERED_PRINTERS_) + .concat( + cloudDestinations, + unregisteredCloudDestinations.slice( + DestinationSearch.MAX_PROMOTED_UNREGISTERED_PRINTERS_)); this.recentList_.updateDestinations(recentDestinations); this.localList_.updateDestinations(localDestinations); @@ -420,7 +411,9 @@ }, 0); }; var getCounts = function(lists, count) { - return lists.map(function(list) { return count; }); + return lists.map(function(list) { + return count; + }); }; var availableHeight = this.getAvailableListsHeight_(); @@ -488,11 +481,12 @@ */ updateInvitations_: function() { var invitations = this.userInfo_.activeUser ? - this.invitationStore_.invitations(this.userInfo_.activeUser) : []; + this.invitationStore_.invitations(this.userInfo_.activeUser) : + []; if (invitations.length > 0) { if (this.invitation_ != invitations[0]) { - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket. - INVITATION_AVAILABLE); + this.metrics_.record(print_preview.Metrics.DestinationSearchBucket + .INVITATION_AVAILABLE); } this.invitation_ = invitations[0]; this.showInvitation_(this.invitation_); @@ -512,14 +506,12 @@ var invitationText = ''; if (invitation.asGroupManager) { invitationText = loadTimeData.getStringF( - 'groupPrinterSharingInviteText', - HTMLEscape(invitation.sender), + 'groupPrinterSharingInviteText', HTMLEscape(invitation.sender), HTMLEscape(invitation.destination.displayName), HTMLEscape(invitation.receiver)); } else { invitationText = loadTimeData.getStringF( - 'printerSharingInviteText', - HTMLEscape(invitation.sender), + 'printerSharingInviteText', HTMLEscape(invitation.sender), HTMLEscape(invitation.destination.displayName)); } this.getChildElement('.invitation-text').innerHTML = invitationText; @@ -556,7 +548,8 @@ accountSelectEl.add(option); accountSelectEl.selectedIndex = this.userInfo_.activeUser ? - this.userInfo_.users.indexOf(this.userInfo_.activeUser) : -1; + this.userInfo_.users.indexOf(this.userInfo_.activeUser) : + -1; } setIsVisible(this.getChildElement('.user-info'), loggedIn); @@ -591,10 +584,11 @@ var destinationItem = (destination.isLocal || destination.origin == print_preview.DestinationOrigin.DEVICE) ? - this.localList_.getDestinationItem(destination.id) : - this.cloudList_.getDestinationItem(destination.id); - assert(destinationItem != null, - 'User does not select a valid destination item.'); + this.localList_.getDestinationItem(destination.id) : + this.cloudList_.getDestinationItem(destination.id); + assert( + destinationItem != null, + 'User does not select a valid destination item.'); // Another printer setup is in process or the printer doesn't need to be // set up. Reject the setup request directly. @@ -616,24 +610,26 @@ * @private */ handleConfigureDestination_: function(destination) { - assert(destination.origin == print_preview.DestinationOrigin.CROS, - 'Only local printer on Chrome OS requires setup.'); + assert( + destination.origin == print_preview.DestinationOrigin.CROS, + 'Only local printer on Chrome OS requires setup.'); this.destinationInConfiguring_ = destination; - this.destinationStore_.resolveCrosDestination(destination).then( - /** - * @param {!print_preview.PrinterSetupResponse} response - */ - function(response) { - this.destinationInConfiguring_ = null; - this.localList_.getDestinationItem(destination.id) - .onConfigureResolved(response); - }.bind(this), - function() { - this.destinationInConfiguring_ = null; - this.localList_.getDestinationItem(destination.id) - .onConfigureResolved({printerId: destination.id, - success: false}); - }.bind(this)); + this.destinationStore_.resolveCrosDestination(destination) + .then( + /** + * @param {!print_preview.PrinterSetupResponse} response + */ + function(response) { + this.destinationInConfiguring_ = null; + this.localList_.getDestinationItem(destination.id) + .onConfigureResolved(response); + }.bind(this), + function() { + this.destinationInConfiguring_ = null; + this.localList_.getDestinationItem(destination.id) + .onConfigureResolved( + {printerId: destination.id, success: false}); + }.bind(this)); }, /** @@ -655,18 +651,20 @@ */ handleOnDestinationSelect_: function(destination) { if (destination.isProvisional) { - assert(!this.provisionalDestinationResolver_, - 'Provisional destination resolver already exists.'); + assert( + !this.provisionalDestinationResolver_, + 'Provisional destination resolver already exists.'); this.provisionalDestinationResolver_ = print_preview.ProvisionalDestinationResolver.create( this.destinationStore_, destination); - assert(!!this.provisionalDestinationResolver_, - 'Unable to create provisional destination resolver'); + assert( + !!this.provisionalDestinationResolver_, + 'Unable to create provisional destination resolver'); var lastFocusedElement = document.activeElement; this.addChild(this.provisionalDestinationResolver_); - this.provisionalDestinationResolver_.run(this.getElement()). - then( + this.provisionalDestinationResolver_.run(this.getElement()) + .then( /** * @param {!print_preview.Destination} resolvedDestination * Destination to which the provisional destination was @@ -674,34 +672,31 @@ */ function(resolvedDestination) { this.handleOnDestinationSelect_(resolvedDestination); - }.bind(this)). - catch( - function() { - console.error('Failed to resolve provisional destination: ' + - destination.id); - }). - then( - function() { - this.removeChild( - assert(this.provisionalDestinationResolver_)); - this.provisionalDestinationResolver_ = null; + }.bind(this)) + .catch(function() { + console.error( + 'Failed to resolve provisional destination: ' + + destination.id); + }) + .then(function() { + this.removeChild(assert(this.provisionalDestinationResolver_)); + this.provisionalDestinationResolver_ = null; - // Restore focus to the previosly focused element if it's - // still shown in the search. - if (lastFocusedElement && - this.getIsVisible() && - getIsVisible(lastFocusedElement) && - this.getElement().contains(lastFocusedElement)) { - lastFocusedElement.focus(); - } - }.bind(this)); + // Restore focus to the previosly focused element if it's + // still shown in the search. + if (lastFocusedElement && this.getIsVisible() && + getIsVisible(lastFocusedElement) && + this.getElement().contains(lastFocusedElement)) { + lastFocusedElement.focus(); + } + }.bind(this)); return; } this.setIsVisible(false); this.destinationStore_.selectDestination(destination); - this.metrics_.record(print_preview.Metrics.DestinationSearchBucket. - DESTINATION_CLOSED_CHANGED); + this.metrics_.record(print_preview.Metrics.DestinationSearchBucket + .DESTINATION_CLOSED_CHANGED); }, /** @@ -812,9 +807,11 @@ * @private */ onInvitationProcessButtonClick_: function(accept) { - this.metrics_.record(accept ? - print_preview.Metrics.DestinationSearchBucket.INVITATION_ACCEPTED : - print_preview.Metrics.DestinationSearchBucket.INVITATION_REJECTED); + this.metrics_.record( + accept ? print_preview.Metrics.DestinationSearchBucket + .INVITATION_ACCEPTED : + print_preview.Metrics.DestinationSearchBucket + .INVITATION_REJECTED); this.invitationStore_.processInvitation(assert(this.invitation_), accept); this.updateInvitations_(); }, @@ -839,7 +836,5 @@ }; // Export - return { - DestinationSearch: DestinationSearch - }; + return {DestinationSearch: DestinationSearch}; });
diff --git a/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js b/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js index 9eb9566..29dc741 100644 --- a/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js +++ b/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js
@@ -60,7 +60,7 @@ */ ProvisionalDestinationResolver.create = function(store, destination) { if (destination.provisionalType != - print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION) { + print_preview.DestinationProvisionalType.NEEDS_USB_PERMISSION) { return null; } return new ProvisionalDestinationResolver(store, destination); @@ -74,13 +74,10 @@ print_preview.Overlay.prototype.enterDocument.call(this); this.tracker.add( - this.getChildElement('.usb-permission-ok-button'), - 'click', + this.getChildElement('.usb-permission-ok-button'), 'click', this.startResolveDestination_.bind(this)); this.tracker.add( - this.getChildElement('.cancel'), - 'click', - this.cancel.bind(this)); + this.getChildElement('.cancel'), 'click', this.cancel.bind(this)); this.tracker.add( this.destinationStore_, @@ -92,15 +89,17 @@ /** @override */ onSetVisibleInternal: function(visible) { if (visible) { - assert(this.state_ == print_preview.ResolverState.INITIAL, - 'Showing overlay while not in initial state.'); + assert( + this.state_ == print_preview.ResolverState.INITIAL, + 'Showing overlay while not in initial state.'); assert(!this.promiseResolver_, 'Promise resolver already set.'); this.setState_(print_preview.ResolverState.ACTIVE); this.promiseResolver_ = new PromiseResolver(); this.getChildElement('.default').focus(); } else if (this.state_ != print_preview.ResolverState.DONE) { - assert(this.state_ != print_preview.ResolverState.INITIAL, - 'Hiding in initial state'); + assert( + this.state_ != print_preview.ResolverState.INITIAL, + 'Hiding in initial state'); this.setState_(print_preview.ResolverState.DONE); this.promiseResolver_.reject(); this.promiseResolver_ = null; @@ -109,8 +108,8 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'extension-usb-resolver')); + this.setElementInternal( + this.cloneTemplateInternal('extension-usb-resolver')); var extNameEl = this.getChildElement('.usb-permission-extension-name'); extNameEl.title = this.destination_.extensionName; @@ -118,10 +117,10 @@ var extIconEl = this.getChildElement('.usb-permission-extension-icon'); extIconEl.style.backgroundImage = '-webkit-image-set(' + - 'url(chrome://extension-icon/' + - this.destination_.extensionId + '/24/1) 1x,' + - 'url(chrome://extension-icon/' + - this.destination_.extensionId + '/48/1) 2x)'; + 'url(chrome://extension-icon/' + this.destination_.extensionId + + '/24/1) 1x,' + + 'url(chrome://extension-icon/' + this.destination_.extensionId + + '/48/1) 2x)'; }, /** @@ -129,8 +128,9 @@ * @private */ startResolveDestination_: function() { - assert(this.state_ == print_preview.ResolverState.ACTIVE, - 'Invalid state in request grant permission'); + assert( + this.state_ == print_preview.ResolverState.ACTIVE, + 'Invalid state in request grant permission'); this.setState_(print_preview.ResolverState.GRANTING_PERMISSION); this.destinationStore_.resolveProvisionalDestination(this.destination_); @@ -187,18 +187,20 @@ if (this.state_ != print_preview.ResolverState.ACTIVE) this.getChildElement('.cancel').focus(); - this.getChildElement('.throbber-placeholder').classList.toggle( - 'throbber', - this.state_ == print_preview.ResolverState.GRANTING_PERMISSION); + this.getChildElement('.throbber-placeholder') + .classList.toggle( + 'throbber', + this.state_ == print_preview.ResolverState.GRANTING_PERMISSION); this.getChildElement('.usb-permission-extension-desc').hidden = this.state_ == print_preview.ResolverState.ERROR; this.getChildElement('.usb-permission-message').textContent = this.state_ == print_preview.ResolverState.ERROR ? - loadTimeData.getStringF('resolveExtensionUSBErrorMessage', - this.destination_.extensionName) : - loadTimeData.getString('resolveExtensionUSBPermissionMessage'); + loadTimeData.getStringF( + 'resolveExtensionUSBErrorMessage', + this.destination_.extensionName) : + loadTimeData.getString('resolveExtensionUSBPermissionMessage'); }, /** @@ -217,7 +219,5 @@ } }; - return { - ProvisionalDestinationResolver: ProvisionalDestinationResolver - }; + return {ProvisionalDestinationResolver: ProvisionalDestinationResolver}; });
diff --git a/chrome/browser/resources/print_preview/search/recent_destination_list.js b/chrome/browser/resources/print_preview/search/recent_destination_list.js index 47aff4e..57f7d97e 100644 --- a/chrome/browser/resources/print_preview/search/recent_destination_list.js +++ b/chrome/browser/resources/print_preview/search/recent_destination_list.js
@@ -15,11 +15,8 @@ */ function RecentDestinationList(eventTarget) { print_preview.DestinationList.call( - this, - eventTarget, - loadTimeData.getString('recentDestinationsTitle'), - null /*actionLinkLabel*/, - true /*opt_showAll*/); + this, eventTarget, loadTimeData.getString('recentDestinationsTitle'), + null /*actionLinkLabel*/, true /*opt_showAll*/); } RecentDestinationList.prototype = { @@ -32,7 +29,5 @@ } }; - return { - RecentDestinationList: RecentDestinationList - }; + return {RecentDestinationList: RecentDestinationList}; });
diff --git a/chrome/browser/resources/print_preview/settings/advanced_options_settings.js b/chrome/browser/resources/print_preview/settings/advanced_options_settings.js index 62e735b..2469dbe 100644 --- a/chrome/browser/resources/print_preview/settings/advanced_options_settings.js +++ b/chrome/browser/resources/print_preview/settings/advanced_options_settings.js
@@ -60,19 +60,18 @@ enterDocument: function() { print_preview.SettingsSection.prototype.enterDocument.call(this); - this.tracker.add( - this.getButton_(), 'click', function() { - cr.dispatchSimpleEvent( - this, AdvancedOptionsSettings.EventType.BUTTON_ACTIVATED); - }.bind(this)); + this.tracker.add(this.getButton_(), 'click', function() { + cr.dispatchSimpleEvent( + this, AdvancedOptionsSettings.EventType.BUTTON_ACTIVATED); + }.bind(this)); this.tracker.add( this.destinationStore_, print_preview.DestinationStore.EventType.DESTINATION_SELECT, this.onDestinationChanged_.bind(this)); this.tracker.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - SELECTED_DESTINATION_CAPABILITIES_READY, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, this.onDestinationChanged_.bind(this)); }, @@ -94,7 +93,5 @@ }; // Export - return { - AdvancedOptionsSettings: AdvancedOptionsSettings - }; + return {AdvancedOptionsSettings: AdvancedOptionsSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js b/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js index afc4125b..42edd3a9 100644 --- a/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js +++ b/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings.js
@@ -59,8 +59,8 @@ assert(!this.destination_); this.destination_ = destination; this.getChildElement('.advanced-settings-title').textContent = - loadTimeData.getStringF('advancedSettingsDialogTitle', - this.destination_.displayName); + loadTimeData.getStringF( + 'advancedSettingsDialogTitle', this.destination_.displayName); this.setIsVisible(true); this.renderSettings_(); }, @@ -70,18 +70,15 @@ print_preview.Overlay.prototype.enterDocument.call(this); this.tracker.add( - this.getChildElement('.button-strip .cancel-button'), - 'click', + this.getChildElement('.button-strip .cancel-button'), 'click', this.cancel.bind(this)); this.tracker.add( - this.getChildElement('.button-strip .done-button'), - 'click', + this.getChildElement('.button-strip .done-button'), 'click', this.onApplySettings_.bind(this)); this.tracker.add( - assert(this.searchBox_), - print_preview.SearchBox.EventType.SEARCH, + assert(this.searchBox_), print_preview.SearchBox.EventType.SEARCH, this.onSearch_.bind(this)); }, @@ -94,8 +91,8 @@ onSetVisibleInternal: function(isVisible) { if (isVisible) { this.searchBox_.focus(); - this.metrics_.record(print_preview.Metrics.PrintSettingsUiBucket. - ADVANCED_SETTINGS_DIALOG_SHOWN); + this.metrics_.record(print_preview.Metrics.PrintSettingsUiBucket + .ADVANCED_SETTINGS_DIALOG_SHOWN); } else { this.resetSearch_(); this.destination_ = null; @@ -104,8 +101,8 @@ /** @override */ onCancelInternal: function() { - this.metrics_.record(print_preview.Metrics.PrintSettingsUiBucket. - ADVANCED_SETTINGS_DIALOG_CANCELED); + this.metrics_.record(print_preview.Metrics.PrintSettingsUiBucket + .ADVANCED_SETTINGS_DIALOG_CANCELED); }, /** @override */ @@ -145,8 +142,7 @@ lastVisibleItemWithBubble = item; }); setIsVisible( - this.getChildElement('.no-settings-match-hint'), - !atLeastOneMatch); + this.getChildElement('.no-settings-match-hint'), !atLeastOneMatch); setIsVisible( this.getChildElement('.' + AdvancedSettings.Classes_.EXTRA_PADDING), !!lastVisibleItemWithBubble); @@ -236,7 +232,5 @@ }; // Export - return { - AdvancedSettings: AdvancedSettings - }; + return {AdvancedSettings: AdvancedSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.js b/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.js index bbba5593..40e4be31 100644 --- a/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.js +++ b/chrome/browser/resources/print_preview/settings/advanced_settings/advanced_settings_item.js
@@ -75,8 +75,8 @@ /** @override */ createDom: function() { - this.setElementInternal(this.cloneTemplateInternal( - 'advanced-settings-item-template')); + this.setElementInternal( + this.cloneTemplateInternal('advanced-settings-item-template')); this.tracker_.add( this.select_, 'change', this.onSelectChange_.bind(this)); @@ -135,7 +135,7 @@ * @private */ get text_() { - return /** @type {!HTMLSelectElement} */( + return /** @type {!HTMLSelectElement} */ ( this.getChildElement('.advanced-settings-item-value-text-control')); }, @@ -195,8 +195,8 @@ for (var i = 0; i < this.select_.length && !optionMatches; i++) optionMatches = this.select_.options[i].text.match(this.query_); } else { - optionMatches = (this.text_.value || this.text_.placeholder || '') - .match(this.query_); + optionMatches = (this.text_.value || this.text_.placeholder || + '').match(this.query_); } } var matches = nameMatches || !!optionMatches; @@ -267,8 +267,9 @@ * @private */ initializeSelectValue_: function() { - setIsVisible(assert(this.getChildElement( - '.advanced-settings-item-value-select')), true); + setIsVisible( + assert(this.getChildElement('.advanced-settings-item-value-select')), + true); var selectEl = this.select_; var indexToSelect = 0; this.capability_.select_cap.option.forEach(function(option, index) { @@ -293,15 +294,16 @@ * @private */ initializeTextValue_: function() { - setIsVisible(assert(this.getChildElement( - '.advanced-settings-item-value-text')), true); + setIsVisible( + assert(this.getChildElement('.advanced-settings-item-value-text')), + true); var defaultValue = null; if (this.capability_.type == 'TYPED_VALUE' && this.capability_.typed_value_cap) { defaultValue = this.capability_.typed_value_cap.default || null; - } else if (this.capability_.type == 'RANGE' && - this.capability_.range_cap) { + } else if ( + this.capability_.type == 'RANGE' && this.capability_.range_cap) { defaultValue = this.capability_.range_cap.default || null; } @@ -332,7 +334,5 @@ }; // Export - return { - AdvancedSettingsItem: AdvancedSettingsItem - }; + return {AdvancedSettingsItem: AdvancedSettingsItem}; });
diff --git a/chrome/browser/resources/print_preview/settings/color_settings.js b/chrome/browser/resources/print_preview/settings/color_settings.js index 24d9cce..c2df674d 100644 --- a/chrome/browser/resources/print_preview/settings/color_settings.js +++ b/chrome/browser/resources/print_preview/settings/color_settings.js
@@ -45,8 +45,7 @@ /** @override */ enterDocument: function() { print_preview.SettingsSection.prototype.enterDocument.call(this); - this.tracker.add( - this.select_, 'change', this.onSelectChange_.bind(this)); + this.tracker.add(this.select_, 'change', this.onSelectChange_.bind(this)); this.tracker.add( this.colorTicketItem_, print_preview.ticket_items.TicketItem.EventType.CHANGE, @@ -69,7 +68,7 @@ * @private */ get select_() { - return /** @type {!HTMLSelectElement} */( + return /** @type {!HTMLSelectElement} */ ( this.getChildElement('.color-settings-select')); }, @@ -93,7 +92,5 @@ }; // Export - return { - ColorSettings: ColorSettings - }; + return {ColorSettings: ColorSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/copies_settings.js b/chrome/browser/resources/print_preview/settings/copies_settings.js index 369d4005..6aaab6ed 100644 --- a/chrome/browser/resources/print_preview/settings/copies_settings.js +++ b/chrome/browser/resources/print_preview/settings/copies_settings.js
@@ -88,20 +88,13 @@ this.inputField_ = this.getChildElement('input.user-value'); print_preview.SettingsSection.prototype.enterDocument.call(this); this.tracker.add( - this.inputField_, - 'keydown', - this.onTextfieldKeyDown_.bind(this)); + this.inputField_, 'keydown', this.onTextfieldKeyDown_.bind(this)); this.tracker.add( - this.inputField_, - 'input', - this.onTextfieldInput_.bind(this)); + this.inputField_, 'input', this.onTextfieldInput_.bind(this)); this.tracker.add( - this.inputField_, - 'blur', - this.onTextfieldBlur_.bind(this)); + this.inputField_, 'blur', this.onTextfieldBlur_.bind(this)); this.tracker.add( - this.getChildElement('input.collate'), - 'click', + this.getChildElement('input.collate'), 'click', this.onCollateCheckboxClick_.bind(this)); this.tracker.add( this.copiesTicketItem_, @@ -131,8 +124,8 @@ this.inputField_.classList.remove('invalid'); fadeOutElement(this.getChildElement('.hint')); if (!(this.getChildElement('.collate-container').hidden = - !this.collateTicketItem_.isCapabilityAvailable() || - this.copiesTicketItem_.getValueAsNumber() <= 1)) { + !this.collateTicketItem_.isCapabilityAvailable() || + this.copiesTicketItem_.getValueAsNumber() <= 1)) { this.getChildElement('input.collate').checked = this.collateTicketItem_.getValue(); } @@ -146,9 +139,10 @@ */ onTextfieldTimeout_: function() { this.textfieldTimeout_ = null; - var newValue = (this.inputField_.validity.valid && - this.inputField_.value != '') ? - this.inputField_.valueAsNumber.toString() : ''; + var newValue = + (this.inputField_.validity.valid && this.inputField_.value != '') ? + this.inputField_.valueAsNumber.toString() : + ''; if (this.copiesTicketItem_.getValue() === newValue) { this.updateState_(); return; @@ -195,9 +189,11 @@ // No need to update the ticket, but change the display to match. this.inputField_.value = '1'; } else { - setTimeout((function() { - this.copiesTicketItem_.updateValue('1'); - }).bind(this), 0); + setTimeout( + (function() { + this.copiesTicketItem_.updateValue('1'); + }).bind(this), + 0); } } }, @@ -213,7 +209,5 @@ }; // Export - return { - CopiesSettings: CopiesSettings - }; + return {CopiesSettings: CopiesSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/destination_settings.js b/chrome/browser/resources/print_preview/settings/destination_settings.js index bad6fd49..f9941182 100644 --- a/chrome/browser/resources/print_preview/settings/destination_settings.js +++ b/chrome/browser/resources/print_preview/settings/destination_settings.js
@@ -98,8 +98,8 @@ this.onDestinationSelect_.bind(this)); this.tracker_.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - CACHED_SELECTED_DESTINATION_INFO_READY, + print_preview.DestinationStore.EventType + .CACHED_SELECTED_DESTINATION_INFO_READY, this.onSelectedDestinationNameSet_.bind(this)); }, @@ -168,7 +168,5 @@ }; // Export - return { - DestinationSettings: DestinationSettings - }; + return {DestinationSettings: DestinationSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/dpi_settings.js b/chrome/browser/resources/print_preview/settings/dpi_settings.js index 00c01b3..4e44a501 100644 --- a/chrome/browser/resources/print_preview/settings/dpi_settings.js +++ b/chrome/browser/resources/print_preview/settings/dpi_settings.js
@@ -24,17 +24,15 @@ var hDpi = option.horizontal_dpi || 0; var vDpi = option.vertical_dpi || 0; if (hDpi > 0 && vDpi > 0 && hDpi != vDpi) { - return loadTimeData.getStringF('nonIsotropicDpiItemLabel', - hDpi.toLocaleString(), - vDpi.toLocaleString()); + return loadTimeData.getStringF( + 'nonIsotropicDpiItemLabel', hDpi.toLocaleString(), + vDpi.toLocaleString()); } - return loadTimeData.getStringF('dpiItemLabel', - (hDpi || vDpi).toLocaleString()); + return loadTimeData.getStringF( + 'dpiItemLabel', (hDpi || vDpi).toLocaleString()); } }; // Export - return { - DpiSettings: DpiSettings - }; + return {DpiSettings: DpiSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/layout_settings.js b/chrome/browser/resources/print_preview/settings/layout_settings.js index cd1aeed..acb018e 100644 --- a/chrome/browser/resources/print_preview/settings/layout_settings.js +++ b/chrome/browser/resources/print_preview/settings/layout_settings.js
@@ -45,8 +45,7 @@ /** @override */ enterDocument: function() { print_preview.SettingsSection.prototype.enterDocument.call(this); - this.tracker.add( - this.select_, 'change', this.onSelectChange_.bind(this)); + this.tracker.add(this.select_, 'change', this.onSelectChange_.bind(this)); this.tracker.add( this.landscapeTicketItem_, print_preview.ticket_items.TicketItem.EventType.CHANGE, @@ -71,7 +70,7 @@ * @private */ get select_() { - return /** @type {!HTMLSelectElement} */( + return /** @type {!HTMLSelectElement} */ ( this.getChildElement('.layout-settings-select')); }, @@ -97,7 +96,5 @@ }; // Export - return { - LayoutSettings: LayoutSettings - }; + return {LayoutSettings: LayoutSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/margin_settings.js b/chrome/browser/resources/print_preview/settings/margin_settings.js index 2d86be50..f99b3de 100644 --- a/chrome/browser/resources/print_preview/settings/margin_settings.js +++ b/chrome/browser/resources/print_preview/settings/margin_settings.js
@@ -29,9 +29,7 @@ * @enum {string} * @private */ - MarginSettings.Classes_ = { - SELECT: 'margin-settings-select' - }; + MarginSettings.Classes_ = {SELECT: 'margin-settings-select'}; MarginSettings.prototype = { __proto__: print_preview.SettingsSection.prototype, @@ -108,7 +106,5 @@ }; // Export - return { - MarginSettings: MarginSettings - }; + return {MarginSettings: MarginSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/media_size_settings.js b/chrome/browser/resources/print_preview/settings/media_size_settings.js index c7a4319..ca63b57e 100644 --- a/chrome/browser/resources/print_preview/settings/media_size_settings.js +++ b/chrome/browser/resources/print_preview/settings/media_size_settings.js
@@ -26,7 +26,5 @@ }; // Export - return { - MediaSizeSettings: MediaSizeSettings - }; + return {MediaSizeSettings: MediaSizeSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/more_settings.js b/chrome/browser/resources/print_preview/settings/more_settings.js index ebdc78f..25bb73933 100644 --- a/chrome/browser/resources/print_preview/settings/more_settings.js +++ b/chrome/browser/resources/print_preview/settings/more_settings.js
@@ -58,8 +58,8 @@ this.onDestinationChanged_.bind(this)); this.tracker.add( this.destinationStore_, - print_preview.DestinationStore.EventType. - SELECTED_DESTINATION_CAPABILITIES_READY, + print_preview.DestinationStore.EventType + .SELECTED_DESTINATION_CAPABILITIES_READY, this.onDestinationCapabilitiesReady_.bind(this)); this.settingsSections_.forEach(function(section) { this.tracker.add( @@ -79,9 +79,11 @@ onClick_: function() { this.showAll_ = !this.showAll_; this.updateState_(false); - this.metrics_.record(this.isExpanded ? - print_preview.Metrics.PrintSettingsUiBucket.MORE_SETTINGS_CLICKED : - print_preview.Metrics.PrintSettingsUiBucket.LESS_SETTINGS_CLICKED); + this.metrics_.record( + this.isExpanded ? print_preview.Metrics.PrintSettingsUiBucket + .MORE_SETTINGS_CLICKED : + print_preview.Metrics.PrintSettingsUiBucket + .LESS_SETTINGS_CLICKED); }, /** @@ -120,21 +122,20 @@ return; this.getChildElement('.more-settings-label').textContent = - loadTimeData.getString(this.isExpanded ? 'lessOptionsLabel' : - 'moreOptionsLabel'); + loadTimeData.getString( + this.isExpanded ? 'lessOptionsLabel' : 'moreOptionsLabel'); var iconEl = this.getChildElement('.more-settings-icon'); iconEl.classList.toggle('more-settings-icon-plus', !this.isExpanded); iconEl.classList.toggle('more-settings-icon-minus', this.isExpanded); - var availableSections = this.settingsSections_.reduce( - function(count, section) { + var availableSections = + this.settingsSections_.reduce(function(count, section) { return count + (section.isAvailable() ? 1 : 0); }, 0); // Magic 6 is chosen as the number of sections when it still feels like // manageable and not too crowded. - var hasSectionsToToggle = - availableSections > 6 && + var hasSectionsToToggle = availableSections > 6 && this.settingsSections_.some(function(section) { return section.hasCollapsibleContent(); }); @@ -152,7 +153,5 @@ }; // Export - return { - MoreSettings: MoreSettings - }; + return {MoreSettings: MoreSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/other_options_settings.js b/chrome/browser/resources/print_preview/settings/other_options_settings.js index 7b57127..24e04b2 100644 --- a/chrome/browser/resources/print_preview/settings/other_options_settings.js +++ b/chrome/browser/resources/print_preview/settings/other_options_settings.js
@@ -70,7 +70,7 @@ /** Initializes container and checkbox */ decorate: function() { this.container_ = $(this.cssId_); - this.checkbox_ = /** @type {HTMLElement} */( + this.checkbox_ = /** @type {HTMLElement} */ ( this.container_.querySelector('.checkbox')); }, @@ -103,7 +103,7 @@ */ isVisible: function(collapseContent) { return this.ticketItem_.isCapabilityAvailable() && - (!this.collapsible_ || !collapseContent); + (!this.collapsible_ || !collapseContent); }, /** @@ -142,7 +142,7 @@ * enabled. */ this.rasterizeEnabled_ = (!cr.isWindows && !cr.isMac) && - loadTimeData.getBoolean('printPdfAsImageEnabled'); + loadTimeData.getBoolean('printPdfAsImageEnabled'); /** * @private {!Array<!CheckboxTicketItemElement>} checkbox ticket item @@ -150,20 +150,20 @@ * Selection only must always be the last element in the array. */ this.elements_ = [ - new CheckboxTicketItemElement(headerFooter, true, - 'header-footer-container'), - new CheckboxTicketItemElement(fitToPage, false, - 'fit-to-page-container'), + new CheckboxTicketItemElement( + headerFooter, true, 'header-footer-container'), + new CheckboxTicketItemElement(fitToPage, false, 'fit-to-page-container'), new CheckboxTicketItemElement(duplex, false, 'duplex-container'), - new CheckboxTicketItemElement(cssBackground, true, - 'css-background-container'), - new CheckboxTicketItemElement(selectionOnly, true, - 'selection-only-container') + new CheckboxTicketItemElement( + cssBackground, true, 'css-background-container'), + new CheckboxTicketItemElement( + selectionOnly, true, 'selection-only-container') ]; if (this.rasterizeEnabled_) { - this.elements_.splice(4, 0, - new CheckboxTicketItemElement(rasterize, true, - 'rasterize-container')); + this.elements_.splice( + 4, 0, + new CheckboxTicketItemElement( + rasterize, true, 'rasterize-container')); } } @@ -199,8 +199,7 @@ print_preview.SettingsSection.prototype.enterDocument.call(this); this.elements_.forEach(function(element) { this.tracker.add( - assert(element.checkbox), - 'click', + assert(element.checkbox), 'click', element.onCheckboxClick.bind(element)); this.tracker.add( element.ticketItem, @@ -242,7 +241,5 @@ }; // Export - return { - OtherOptionsSettings: OtherOptionsSettings - }; + return {OtherOptionsSettings: OtherOptionsSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/page_settings.js b/chrome/browser/resources/print_preview/settings/page_settings.js index e5ddd6a4..4002ca61 100644 --- a/chrome/browser/resources/print_preview/settings/page_settings.js +++ b/chrome/browser/resources/print_preview/settings/page_settings.js
@@ -105,25 +105,15 @@ this.tracker.add( assert(this.allRadio_), 'click', this.onAllRadioClick_.bind(this)); this.tracker.add( - assert(this.customRadio_), - 'click', + assert(this.customRadio_), 'click', this.onCustomRadioClick_.bind(this)); + this.tracker.add(customInput, 'blur', this.onCustomInputBlur_.bind(this)); this.tracker.add( - customInput, - 'blur', - this.onCustomInputBlur_.bind(this)); + customInput, 'focus', this.onCustomInputFocus_.bind(this)); this.tracker.add( - customInput, - 'focus', - this.onCustomInputFocus_.bind(this)); + customInput, 'keydown', this.onCustomInputKeyDown_.bind(this)); this.tracker.add( - customInput, - 'keydown', - this.onCustomInputKeyDown_.bind(this)); - this.tracker.add( - customInput, - 'input', - this.onCustomInputChange_.bind(this)); + customInput, 'input', this.onCustomInputChange_.bind(this)); this.tracker.add( this.pageRangeTicketItem_, print_preview.ticket_items.TicketItem.EventType.CHANGE, @@ -164,8 +154,7 @@ 'pageRangeLimitInstructionWithValue', this.pageRangeTicketItem_.getDocumentNumPages()); } else { - message = loadTimeData.getString( - 'pageRangeLimitInstruction'); + message = loadTimeData.getString('pageRangeLimitInstruction'); } } else { message = loadTimeData.getStringF( @@ -283,7 +272,5 @@ }; // Export - return { - PageSettings: PageSettings - }; + return {PageSettings: PageSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/scaling_settings.js b/chrome/browser/resources/print_preview/settings/scaling_settings.js index 40ce29a7..99d752c 100644 --- a/chrome/browser/resources/print_preview/settings/scaling_settings.js +++ b/chrome/browser/resources/print_preview/settings/scaling_settings.js
@@ -52,7 +52,6 @@ * @private {HTMLElement} */ this.inputField_ = null; - } /** @@ -88,17 +87,11 @@ this.inputField_ = assert(this.getChildElement('input.user-value')); print_preview.SettingsSection.prototype.enterDocument.call(this); this.tracker.add( - this.inputField_, - 'keydown', - this.onTextfieldKeyDown_.bind(this)); + this.inputField_, 'keydown', this.onTextfieldKeyDown_.bind(this)); this.tracker.add( - this.inputField_, - 'input', - this.onTextfieldInput_.bind(this)); + this.inputField_, 'input', this.onTextfieldInput_.bind(this)); this.tracker.add( - this.inputField_, - 'blur', - this.onTextfieldBlur_.bind(this)); + this.inputField_, 'blur', this.onTextfieldBlur_.bind(this)); this.tracker.add( this.scalingTicketItem_, print_preview.ticket_items.TicketItem.EventType.CHANGE, @@ -115,7 +108,7 @@ */ isFitToPageSelected: function() { return this.fitToPageTicketItem_.isCapabilityAvailable() && - !!this.fitToPageTicketItem_.getValue(); + !!this.fitToPageTicketItem_.getValue(); }, /** @@ -140,8 +133,9 @@ * @private */ displayMatchesFitToPage: function() { - return (this.getInputAsNumber() == this.fitToPageScaling_ || - (this.inputField_.value == '' && !this.fitToPageScaling_)); + return ( + this.getInputAsNumber() == this.fitToPageScaling_ || + (this.inputField_.value == '' && !this.fitToPageScaling_)); }, /** @@ -195,8 +189,9 @@ if (this.isFitToPageSelected()) { // Fit to page was checked. Set scaling to the fit to page scaling. this.displayFitToPageScaling(); - } else if (this.fitToPageTicketItem_.isCapabilityAvailable() && - this.displayMatchesFitToPage()) { + } else if ( + this.fitToPageTicketItem_.isCapabilityAvailable() && + this.displayMatchesFitToPage()) { // Fit to page unchecked. Return to last scaling. this.inputField_.value = this.scalingTicketItem_.getValue(); } @@ -208,7 +203,7 @@ */ onTextfieldTimeout_: function() { this.textfieldTimeout_ = null; - if (!this.inputField_.validity.valid){ + if (!this.inputField_.validity.valid) { this.updateState_(); return; } @@ -226,7 +221,7 @@ if (this.inputField_.value == '') return; this.scalingTicketItem_.updateValue( - this.inputField_.valueAsNumber.toString()); + this.inputField_.valueAsNumber.toString()); }, /** @@ -280,7 +275,5 @@ }; // Export - return { - ScalingSettings: ScalingSettings - }; + return {ScalingSettings: ScalingSettings}; });
diff --git a/chrome/browser/resources/print_preview/settings/settings_section.js b/chrome/browser/resources/print_preview/settings/settings_section.js index 4be8250..6deb0aa 100644 --- a/chrome/browser/resources/print_preview/settings/settings_section.js +++ b/chrome/browser/resources/print_preview/settings/settings_section.js
@@ -116,7 +116,5 @@ }; // Export - return { - SettingsSection: SettingsSection - }; + return {SettingsSection: SettingsSection}; });
diff --git a/chrome/browser/resources/print_preview/settings/settings_section_select.js b/chrome/browser/resources/print_preview/settings/settings_section_select.js index 713c950..62ec25c 100644 --- a/chrome/browser/resources/print_preview/settings/settings_section_select.js +++ b/chrome/browser/resources/print_preview/settings/settings_section_select.js
@@ -41,12 +41,12 @@ /** @override */ enterDocument: function() { print_preview.SettingsSection.prototype.enterDocument.call(this); - this.tracker.add(assert(this.select_), - 'change', - this.onSelectChange_.bind(this)); - this.tracker.add(this.ticketItem_, - print_preview.ticket_items.TicketItem.EventType.CHANGE, - this.onTicketItemChange_.bind(this)); + this.tracker.add( + assert(this.select_), 'change', this.onSelectChange_.bind(this)); + this.tracker.add( + this.ticketItem_, + print_preview.ticket_items.TicketItem.EventType.CHANGE, + this.onTicketItemChange_.bind(this)); }, /** @@ -80,7 +80,7 @@ this.ticketItem_.capability.option.forEach(function(option, index) { var selectOption = document.createElement('option'); selectOption.text = this.getCustomDisplayName_(option) || - this.getDefaultDisplayName_(option); + this.getDefaultDisplayName_(option); selectOption.value = JSON.stringify(option); select.appendChild(selectOption); if (option.is_default) @@ -144,7 +144,5 @@ }; // Export - return { - SettingsSectionSelect: SettingsSectionSelect - }; + return {SettingsSectionSelect: SettingsSectionSelect}; });
diff --git a/chrome/browser/resources/settings/a11y_page/a11y_page.js b/chrome/browser/resources/settings/a11y_page/a11y_page.js index 5f236ee..99ecf4da 100644 --- a/chrome/browser/resources/settings/a11y_page/a11y_page.js +++ b/chrome/browser/resources/settings/a11y_page/a11y_page.js
@@ -33,20 +33,20 @@ type: Object, value: function() { var map = new Map(); -// <if expr="chromeos"> + // <if expr="chromeos"> map.set( settings.Route.MANAGE_ACCESSIBILITY.path, '#subpage-trigger .subpage-arrow'); -// </if> + // </if> return map; }, }, }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ onManageAccessibilityFeaturesTap_: function() { settings.navigateTo(settings.Route.MANAGE_ACCESSIBILITY); }, -// </if> + // </if> });
diff --git a/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js b/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js index 848bd57..3b711a0 100644 --- a/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js +++ b/chrome/browser/resources/settings/a11y_page/manage_a11y_page.js
@@ -27,16 +27,20 @@ // If these values get changed then those strings need to be changed as // well. return [ - {value: 600, - name: loadTimeData.getString('delayBeforeClickExtremelyShort')}, - {value: 800, - name: loadTimeData.getString('delayBeforeClickVeryShort')}, - {value: 1000, - name: loadTimeData.getString('delayBeforeClickShort')}, - {value: 2000, - name: loadTimeData.getString('delayBeforeClickLong')}, - {value: 4000, - name: loadTimeData.getString('delayBeforeClickVeryLong')}, + { + value: 600, + name: loadTimeData.getString('delayBeforeClickExtremelyShort') + }, + { + value: 800, + name: loadTimeData.getString('delayBeforeClickVeryShort') + }, + {value: 1000, name: loadTimeData.getString('delayBeforeClickShort')}, + {value: 2000, name: loadTimeData.getString('delayBeforeClickLong')}, + { + value: 4000, + name: loadTimeData.getString('delayBeforeClickVeryLong') + }, ]; }, }, @@ -55,7 +59,9 @@ /** @private */ isGuest_: { type: Boolean, - value: function() { return loadTimeData.getBoolean('isGuest'); } + value: function() { + return loadTimeData.getBoolean('isGuest'); + } }, },
diff --git a/chrome/browser/resources/settings/about_page/about_page.js b/chrome/browser/resources/settings/about_page/about_page.js index 639345d1..2f61de74 100644 --- a/chrome/browser/resources/settings/about_page/about_page.js +++ b/chrome/browser/resources/settings/about_page/about_page.js
@@ -19,7 +19,7 @@ value: {message: '', progress: 0, status: UpdateStatus.DISABLED}, }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ hasCheckedForUpdates_: { type: Boolean, @@ -34,12 +34,12 @@ /** @private {?RegulatoryInfo} */ regulatoryInfo_: Object, -// </if> + // </if> -// <if expr="_google_chrome and is_macosx"> + // <if expr="_google_chrome and is_macosx"> /** @private {!PromoteUpdaterStatus} */ promoteUpdaterStatus_: Object, -// </if> + // </if> /** @private {!{obsolete: boolean, endOfLine: boolean}} */ obsoleteSystemInfo_: { @@ -61,7 +61,7 @@ /** @private */ showRelaunch_: Boolean, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ showRelaunchAndPowerwash_: { type: Boolean, @@ -96,18 +96,18 @@ /** @private {!AboutPageUpdateInfo|undefined} */ updateInfo_: Object, -// </if> + // </if> }, observers: [ -// <if expr="not chromeos"> + // <if expr="not chromeos"> 'updateShowUpdateStatus_(' + 'obsoleteSystemInfo_, currentUpdateStatusEvent_)', 'updateShowRelaunch_(currentUpdateStatusEvent_)', 'updateShowButtonContainer_(showRelaunch_)', -// </if> + // </if> -// <if expr="chromeos"> + // <if expr="chromeos"> 'updateShowUpdateStatus_(' + 'obsoleteSystemInfo_, currentUpdateStatusEvent_,' + 'hasCheckedForUpdates_)', @@ -115,7 +115,7 @@ 'currentChannel_)', 'updateShowButtonContainer_(' + 'showRelaunch_, showRelaunchAndPowerwash_, showCheckUpdates_)', -// </if> + // </if> ], @@ -133,7 +133,7 @@ this.lifetimeBrowserProxy_ = settings.LifetimeBrowserProxyImpl.getInstance(); -// <if expr="chromeos"> + // <if expr="chromeos"> this.addEventListener('target-channel-changed', function(e) { this.targetChannel_ = e.detail; }.bind(this)); @@ -147,10 +147,10 @@ this.aboutBrowserProxy_.getRegulatoryInfo().then(function(info) { this.regulatoryInfo_ = info; }.bind(this)); -// </if> -// <if expr="not chromeos"> + // </if> + // <if expr="not chromeos"> this.startListening_(); -// </if> + // </if> if (settings.getQueryParameters().get('checkForUpdate') == 'true') { this.onCheckUpdatesTap_(); } @@ -159,13 +159,12 @@ /** @private */ startListening_: function() { this.addWebUIListener( - 'update-status-changed', - this.onUpdateStatusChanged_.bind(this)); -// <if expr="_google_chrome and is_macosx"> + 'update-status-changed', this.onUpdateStatusChanged_.bind(this)); + // <if expr="_google_chrome and is_macosx"> this.addWebUIListener( 'promotion-state-changed', this.onPromoteUpdaterStatusChanged_.bind(this)); -// </if> + // </if> this.aboutBrowserProxy_.refreshUpdateStatus(); }, @@ -174,18 +173,18 @@ * @private */ onUpdateStatusChanged_: function(event) { -// <if expr="chromeos"> + // <if expr="chromeos"> if (event.status == UpdateStatus.CHECKING) { this.hasCheckedForUpdates_ = true; } else if (event.status == UpdateStatus.NEED_PERMISSION_TO_UPDATE) { this.showUpdateWarningDialog_ = true; this.updateInfo_ = {version: event.version, size: event.size}; } -// </if> + // </if> this.currentUpdateStatusEvent_ = event; }, -// <if expr="_google_chrome and is_macosx"> + // <if expr="_google_chrome and is_macosx"> /** * @param {!PromoteUpdaterStatus} status * @private @@ -215,7 +214,7 @@ // actionable items won't trigger action. event.stopPropagation(); }, -// </if> + // </if> /** @private */ onHelpTap_: function() { @@ -229,7 +228,7 @@ /** @private */ updateShowUpdateStatus_: function() { -// <if expr="chromeos"> + // <if expr="chromeos"> // Do not show the "updated" status if we haven't checked yet or the update // warning dialog is shown to user. if (this.currentUpdateStatusEvent_.status == UpdateStatus.UPDATED && @@ -237,7 +236,7 @@ this.showUpdateStatus_ = false; return; } -// </if> + // </if> this.showUpdateStatus_ = this.currentUpdateStatusEvent_.status != UpdateStatus.DISABLED && !this.obsoleteSystemInfo_.endOfLine; @@ -249,24 +248,24 @@ * @private */ updateShowButtonContainer_: function() { -// <if expr="not chromeos"> + // <if expr="not chromeos"> this.showButtonContainer_ = this.showRelaunch_; -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> this.showButtonContainer_ = this.showRelaunch_ || this.showRelaunchAndPowerwash_ || this.showCheckUpdates_; -// </if> + // </if> }, /** @private */ updateShowRelaunch_: function() { -// <if expr="not chromeos"> + // <if expr="not chromeos"> this.showRelaunch_ = this.checkStatus_(UpdateStatus.NEARLY_UPDATED); -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> this.showRelaunch_ = this.checkStatus_(UpdateStatus.NEARLY_UPDATED) && !this.isTargetChannelMoreStable_(); -// </if> + // </if> }, /** @@ -279,10 +278,10 @@ case UpdateStatus.NEED_PERMISSION_TO_UPDATE: return this.i18nAdvanced('aboutUpgradeCheckStarted'); case UpdateStatus.NEARLY_UPDATED: -// <if expr="chromeos"> + // <if expr="chromeos"> if (this.currentChannel_ != this.targetChannel_) return this.i18nAdvanced('aboutUpgradeSuccessChannelSwitch'); -// </if> + // </if> return this.i18nAdvanced('aboutUpgradeRelaunch'); case UpdateStatus.UPDATED: return this.i18nAdvanced('aboutUpgradeUpToDate'); @@ -290,7 +289,7 @@ assert(typeof this.currentUpdateStatusEvent_.progress == 'number'); var progressPercent = this.currentUpdateStatusEvent_.progress + '%'; -// <if expr="chromeos"> + // <if expr="chromeos"> if (this.currentChannel_ != this.targetChannel_) { return this.i18nAdvanced('aboutUpgradeUpdatingChannelSwitch', { substitutions: [ @@ -300,7 +299,7 @@ ] }); } -// </if> + // </if> if (this.currentUpdateStatusEvent_.progress > 0) { // NOTE(dbeam): some platforms (i.e. Mac) always send 0% while // updating (they don't support incremental upgrade progress). Though @@ -314,8 +313,8 @@ return this.i18nAdvanced('aboutUpgradeUpdating'); default: function formatMessage(msg) { - return parseHtmlSubset( - '<b>' + msg + '</b>', ['br', 'pre']).firstChild.innerHTML; + return parseHtmlSubset('<b>' + msg + '</b>', ['br', 'pre']) + .firstChild.innerHTML; } var result = ''; var message = this.currentUpdateStatusEvent_.message; @@ -377,7 +376,7 @@ return this.currentUpdateStatusEvent_.status == status; }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @return {boolean} * @private @@ -421,8 +420,8 @@ computeShowCheckUpdates_: function() { // Enable the update button if we are in a stale 'updated' status or // update has failed. Disable it otherwise. - var staleUpdatedStatus = !this.hasCheckedForUpdates_ && - this.checkStatus_(UpdateStatus.UPDATED); + var staleUpdatedStatus = + !this.hasCheckedForUpdates_ && this.checkStatus_(UpdateStatus.UPDATED); return staleUpdatedStatus || this.checkStatus_(UpdateStatus.FAILED); }, @@ -442,22 +441,24 @@ // dialog and then intends to check for update again. this.hasCheckedForUpdates_ = false; }, -// </if> + // </if> /** @private */ onProductLogoTap_: function() { - this.$['product-logo'].animate({ - transform: ['none', 'rotate(-10turn)'], - }, { - duration: 500, - easing: 'cubic-bezier(1, 0, 0, 1)', - }); + this.$['product-logo'].animate( + { + transform: ['none', 'rotate(-10turn)'], + }, + { + duration: 500, + easing: 'cubic-bezier(1, 0, 0, 1)', + }); }, -// <if expr="_google_chrome"> + // <if expr="_google_chrome"> /** @private */ onReportIssueTap_: function() { this.aboutBrowserProxy_.openFeedbackDialog(); }, -// </if> + // </if> });
diff --git a/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js b/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js index 892ceca5..52f3ced 100644 --- a/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js +++ b/chrome/browser/resources/settings/about_page/about_page_browser_proxy.js
@@ -100,9 +100,12 @@ */ function browserChannelToI18nId(channel) { switch (channel) { - case BrowserChannel.BETA: return 'aboutChannelBeta'; - case BrowserChannel.DEV: return 'aboutChannelDev'; - case BrowserChannel.STABLE: return 'aboutChannelStable'; + case BrowserChannel.BETA: + return 'aboutChannelBeta'; + case BrowserChannel.DEV: + return 'aboutChannelDev'; + case BrowserChannel.STABLE: + return 'aboutChannelStable'; } assertNotReached(); @@ -144,14 +147,14 @@ /** Opens the help page. */ openHelpPage: function() {}, -// <if expr="_google_chrome"> + // <if expr="_google_chrome"> /** * Opens the feedback dialog. */ openFeedbackDialog: function() {}, -// </if> + // </if> -// <if expr="chromeos"> + // <if expr="chromeos"> /** * Checks for available update and applies if it exists. */ @@ -183,14 +186,14 @@ /** @return {!Promise<?RegulatoryInfo>} */ getRegulatoryInfo: function() {}, -// </if> + // </if> -// <if expr="_google_chrome and is_macosx"> + // <if expr="_google_chrome and is_macosx"> /** * Triggers setting up auto-updates for all users. */ promoteUpdater: function() {}, -// </if> + // </if> }; /** @@ -211,26 +214,26 @@ chrome.send('refreshUpdateStatus'); }, -// <if expr="_google_chrome and is_macosx"> + // <if expr="_google_chrome and is_macosx"> /** @override */ promoteUpdater: function() { chrome.send('promoteUpdater'); }, -// </if> + // </if> /** @override */ openHelpPage: function() { chrome.send('openHelpPage'); }, -// <if expr="_google_chrome"> + // <if expr="_google_chrome"> /** @override */ openFeedbackDialog: function() { chrome.send('openFeedbackDialog'); }, -// </if> + // </if> -// <if expr="chromeos"> + // <if expr="chromeos"> /** @override */ requestUpdate: function() { chrome.send('requestUpdate'); @@ -260,7 +263,7 @@ getRegulatoryInfo: function() { return cr.sendWithPromise('getRegulatoryInfo'); } -// </if> + // </if> }; return {
diff --git a/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js b/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js index b98a22d..ceb0322 100644 --- a/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js +++ b/chrome/browser/resources/settings/about_page/channel_switcher_dialog.js
@@ -139,7 +139,7 @@ } if (settings.isTargetChannelMoreStable( - this.currentChannel_, selectedChannel)) { + this.currentChannel_, selectedChannel)) { // More stable channel selected. For non managed devices, notify the user // about powerwash. if (loadTimeData.getBoolean('aboutEnterpriseManaged')) {
diff --git a/chrome/browser/resources/settings/about_page/detailed_build_info.js b/chrome/browser/resources/settings/about_page/detailed_build_info.js index 654ac5dd..8a5842bf 100644 --- a/chrome/browser/resources/settings/about_page/detailed_build_info.js +++ b/chrome/browser/resources/settings/about_page/detailed_build_info.js
@@ -65,7 +65,8 @@ * @private */ getChangeChannelIndicatorSourceName_: function(canChangeChannel) { - return loadTimeData.getBoolean('aboutEnterpriseManaged') ? '' : + return loadTimeData.getBoolean('aboutEnterpriseManaged') ? + '' : loadTimeData.getString('ownerEmail'); },
diff --git a/chrome/browser/resources/settings/about_page/update_warning_dialog.js b/chrome/browser/resources/settings/about_page/update_warning_dialog.js index d938891..4e62fc8 100644 --- a/chrome/browser/resources/settings/about_page/update_warning_dialog.js +++ b/chrome/browser/resources/settings/about_page/update_warning_dialog.js
@@ -40,16 +40,16 @@ /** @private */ onContinueTap_: function() { - this.browserProxy_.requestUpdateOverCellular(this.updateInfo.version, - this.updateInfo.size); + this.browserProxy_.requestUpdateOverCellular( + this.updateInfo.version, this.updateInfo.size); this.$.dialog.close(); }, /** @private */ updateInfoChanged_: function() { - this.$$("#update-warning-message").innerHTML = - this.i18n("aboutUpdateWarningMessage", - // Convert bytes to megabytes - Math.floor(Number(this.updateInfo.size) / (1024 * 1024))); + this.$$('#update-warning-message').innerHTML = this.i18n( + 'aboutUpdateWarningMessage', + // Convert bytes to megabytes + Math.floor(Number(this.updateInfo.size) / (1024 * 1024))); }, });
diff --git a/chrome/browser/resources/settings/android_apps_page/android_apps_browser_proxy.js b/chrome/browser/resources/settings/android_apps_page/android_apps_browser_proxy.js index 0c5c3d5..c5b32bd 100644 --- a/chrome/browser/resources/settings/android_apps_page/android_apps_browser_proxy.js +++ b/chrome/browser/resources/settings/android_apps_page/android_apps_browser_proxy.js
@@ -21,8 +21,7 @@ cr.define('settings', function() { /** @interface */ - function AndroidAppsBrowserProxy() { - } + function AndroidAppsBrowserProxy() {} AndroidAppsBrowserProxy.prototype = { requestAndroidAppsInfo: function() {}, @@ -38,8 +37,7 @@ * @constructor * @implements {settings.AndroidAppsBrowserProxy} */ - function AndroidAppsBrowserProxyImpl() { - } + function AndroidAppsBrowserProxyImpl() {} // The singleton instance_ can be replaced with a test version of this wrapper // during testing.
diff --git a/chrome/browser/resources/settings/animation/animation.js b/chrome/browser/resources/settings/animation/animation.js index 7e07a99..8f369ce 100644 --- a/chrome/browser/resources/settings/animation/animation.js +++ b/chrome/browser/resources/settings/animation/animation.js
@@ -48,6 +48,7 @@ self.queueDispatch_(e); }); self.animation_.addEventListener('cancel', function(e) { + // clang-format off reject(new /** * @see https://heycam.github.io/webidl/#es-DOMException-call @@ -55,6 +56,7 @@ */( DOMException )('', 'AbortError')); + // clang-format on self.queueDispatch_(e); }); });
diff --git a/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js b/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js index 65b76980..5006a3f 100644 --- a/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js +++ b/chrome/browser/resources/settings/appearance_page/appearance_browser_proxy.js
@@ -19,15 +19,15 @@ /** @return {boolean} Whether the current profile is supervised. */ isSupervised: assertNotReached, -// <if expr="chromeos"> + // <if expr="chromeos"> openWallpaperManager: assertNotReached, -// </if> + // </if> useDefaultTheme: assertNotReached, -// <if expr="is_linux and not chromeos"> + // <if expr="is_linux and not chromeos"> useSystemTheme: assertNotReached, -// </if> + // </if> /** * @param {string} url The url of which to check validity. @@ -64,24 +64,24 @@ return loadTimeData.getBoolean('isSupervised'); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @override */ openWallpaperManager: function() { chrome.send('openWallpaperManager'); }, -// </if> + // </if> /** @override */ useDefaultTheme: function() { chrome.send('useDefaultTheme'); }, -// <if expr="is_linux and not chromeos"> + // <if expr="is_linux and not chromeos"> /** @override */ useSystemTheme: function() { chrome.send('useSystemTheme'); }, -// </if> + // </if> /** @override */ validateStartupPage: function(url) {
diff --git a/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js b/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js index f70b9e8..b50fe91 100644 --- a/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js +++ b/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.js
@@ -3,138 +3,137 @@ // found in the LICENSE file. (function() { - 'use strict'; +'use strict'; - /** @const @private {!Array<number>} */ - var FONT_SIZE_RANGE_ = [ - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, - 40, 44, 48, 56, 64, 72, - ]; +/** @const @private {!Array<number>} */ +var FONT_SIZE_RANGE_ = [ + 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, + 26, 28, 30, 32, 34, 36, 40, 44, 48, 56, 64, 72, +]; - /** @const @private {!Array<number>} */ - var MINIMUM_FONT_SIZE_RANGE_ = [ - 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24 - ]; +/** @const @private {!Array<number>} */ +var MINIMUM_FONT_SIZE_RANGE_ = + [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24]; - /** - * 'settings-appearance-fonts-page' is the settings page containing appearance - * settings. - */ - Polymer({ - is: 'settings-appearance-fonts-page', +/** + * 'settings-appearance-fonts-page' is the settings page containing appearance + * settings. + */ +Polymer({ + is: 'settings-appearance-fonts-page', - behaviors: [I18nBehavior, WebUIListenerBehavior], + behaviors: [I18nBehavior, WebUIListenerBehavior], - properties: { - /** @private */ - advancedExtensionSublabel_: String, + properties: { + /** @private */ + advancedExtensionSublabel_: String, - /** @private {!DropdownMenuOptionList} */ - fontOptions_: Object, - - /** @private */ - isGuest_: { - type: Boolean, - value: function() { return loadTimeData.getBoolean('isGuest'); } - }, - - /** - * Common font sizes. - * @private {!Array<number>} - */ - fontSizeRange_: { - readOnly: true, - type: Array, - value: FONT_SIZE_RANGE_, - }, - - /** - * Reasonable, minimum font sizes. - * @private {!Array<number>} - */ - minimumFontSizeRange_: { - readOnly: true, - type: Array, - value: MINIMUM_FONT_SIZE_RANGE_, - }, - - /** - * Preferences state. - */ - prefs: { - type: Object, - notify: true, - }, - }, - - /** @private {?settings.FontsBrowserProxy} */ - browserProxy_: null, - - /** @private {boolean} */ - advancedExtensionInstalled_: false, - - /** @private {?string} */ - advancedExtensionUrl_: null, - - /** @override */ - created: function() { - this.browserProxy_ = settings.FontsBrowserProxyImpl.getInstance(); - }, - - /** @override */ - ready: function() { - this.addWebUIListener('advanced-font-settings-installed', - this.setAdvancedExtensionInstalled_.bind(this)); - this.browserProxy_.observeAdvancedFontExtensionAvailable(); - - this.browserProxy_.fetchFontsData().then( - this.setFontsData_.bind(this)); - }, + /** @private {!DropdownMenuOptionList} */ + fontOptions_: Object, /** @private */ - openAdvancedExtension_: function() { - if (this.advancedExtensionInstalled_) - this.browserProxy_.openAdvancedFontSettings(); - else - window.open(this.advancedExtensionUrl_); - }, - - /** - * @param {boolean} isInstalled Whether the advanced font settings - * extension is installed. - * @private - */ - setAdvancedExtensionInstalled_: function(isInstalled) { - this.advancedExtensionInstalled_ = isInstalled; - this.advancedExtensionSublabel_ = this.i18n(isInstalled ? - 'openAdvancedFontSettings' : 'requiresWebStoreExtension'); - }, - - /** - * @param {!FontsData} response A list of fonts and the advanced - * font settings extension URL. - * @private - */ - setFontsData_: function(response) { - var fontMenuOptions = []; - for (var i = 0; i < response.fontList.length; ++i) { - fontMenuOptions.push({ - value: response.fontList[i][0], - name: response.fontList[i][1] - }); + isGuest_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('isGuest'); } - this.fontOptions_ = fontMenuOptions; - this.advancedExtensionUrl_ = response.extensionUrl; }, /** - * Get the minimum font size, accounting for unset prefs. - * @return {?} - * @private + * Common font sizes. + * @private {!Array<number>} */ - computeMinimumFontSize_: function() { - return this.get('prefs.webkit.webprefs.minimum_font_size.value') || - MINIMUM_FONT_SIZE_RANGE_[0]; + fontSizeRange_: { + readOnly: true, + type: Array, + value: FONT_SIZE_RANGE_, }, - }); + + /** + * Reasonable, minimum font sizes. + * @private {!Array<number>} + */ + minimumFontSizeRange_: { + readOnly: true, + type: Array, + value: MINIMUM_FONT_SIZE_RANGE_, + }, + + /** + * Preferences state. + */ + prefs: { + type: Object, + notify: true, + }, + }, + + /** @private {?settings.FontsBrowserProxy} */ + browserProxy_: null, + + /** @private {boolean} */ + advancedExtensionInstalled_: false, + + /** @private {?string} */ + advancedExtensionUrl_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.FontsBrowserProxyImpl.getInstance(); + }, + + /** @override */ + ready: function() { + this.addWebUIListener( + 'advanced-font-settings-installed', + this.setAdvancedExtensionInstalled_.bind(this)); + this.browserProxy_.observeAdvancedFontExtensionAvailable(); + + this.browserProxy_.fetchFontsData().then(this.setFontsData_.bind(this)); + }, + + /** @private */ + openAdvancedExtension_: function() { + if (this.advancedExtensionInstalled_) + this.browserProxy_.openAdvancedFontSettings(); + else + window.open(this.advancedExtensionUrl_); + }, + + /** + * @param {boolean} isInstalled Whether the advanced font settings + * extension is installed. + * @private + */ + setAdvancedExtensionInstalled_: function(isInstalled) { + this.advancedExtensionInstalled_ = isInstalled; + this.advancedExtensionSublabel_ = this.i18n( + isInstalled ? 'openAdvancedFontSettings' : 'requiresWebStoreExtension'); + }, + + /** + * @param {!FontsData} response A list of fonts and the advanced + * font settings extension URL. + * @private + */ + setFontsData_: function(response) { + var fontMenuOptions = []; + for (var i = 0; i < response.fontList.length; ++i) { + fontMenuOptions.push( + {value: response.fontList[i][0], name: response.fontList[i][1]}); + } + this.fontOptions_ = fontMenuOptions; + this.advancedExtensionUrl_ = response.extensionUrl; + }, + + /** + * Get the minimum font size, accounting for unset prefs. + * @return {?} + * @private + */ + computeMinimumFontSize_: function() { + return this.get('prefs.webkit.webprefs.minimum_font_size.value') || + MINIMUM_FONT_SIZE_RANGE_[0]; + }, +}); })();
diff --git a/chrome/browser/resources/settings/appearance_page/appearance_page.js b/chrome/browser/resources/settings/appearance_page/appearance_page.js index 289e20b..9782c841 100644 --- a/chrome/browser/resources/settings/appearance_page/appearance_page.js +++ b/chrome/browser/resources/settings/appearance_page/appearance_page.js
@@ -122,10 +122,10 @@ 'defaultFontSizeChanged_(prefs.webkit.webprefs.default_font_size.value)', 'themeChanged_(prefs.extensions.theme.id.value, useSystemTheme_)', -// <if expr="is_linux and not chromeos"> + // <if expr="is_linux and not chromeos"> // NOTE: this pref only exists on Linux. 'useSystemThemePrefChanged_(prefs.extensions.theme.use_system.value)', -// </if> + // </if> ], /** @override */ @@ -198,7 +198,7 @@ return this.themeUrl_ || loadTimeData.getString('themesGalleryUrl'); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * ChromeOS only. * @private @@ -206,14 +206,14 @@ openWallpaperManager_: function() { this.browserProxy_.openWallpaperManager(); }, -// </if> + // </if> /** @private */ onUseDefaultTap_: function() { this.browserProxy_.useDefaultTheme(); }, -// <if expr="is_linux and not chromeos"> + // <if expr="is_linux and not chromeos"> /** * @param {boolean} useSystemTheme * @private @@ -251,14 +251,14 @@ */ showThemesSecondary_: function(themeId, useSystemTheme) { return this.showUseClassic_(themeId, useSystemTheme) || - this.showUseSystem_(themeId, useSystemTheme); + this.showUseSystem_(themeId, useSystemTheme); }, /** @private */ onUseSystemTap_: function() { this.browserProxy_.useSystemTheme(); }, -// </if> + // </if> /** * @param {string} themeId @@ -278,12 +278,12 @@ } var i18nId; -// <if expr="is_linux and not chromeos"> + // <if expr="is_linux and not chromeos"> i18nId = useSystemTheme ? 'systemTheme' : 'classicTheme'; -// </if> -// <if expr="not is_linux or chromeos"> + // </if> + // <if expr="not is_linux or chromeos"> i18nId = 'chooseFromWebStore'; -// </if> + // </if> this.themeSublabel_ = this.i18n(i18nId); this.themeUrl_ = ''; },
diff --git a/chrome/browser/resources/settings/basic_page/basic_page.js b/chrome/browser/resources/settings/basic_page/basic_page.js index 9063c8b..9fd3155e 100644 --- a/chrome/browser/resources/settings/basic_page/basic_page.js +++ b/chrome/browser/resources/settings/basic_page/basic_page.js
@@ -140,8 +140,8 @@ ]; if (this.pageVisibility.advancedSettings !== false) { - whenSearchDone.push(this.$$('#advancedPageTemplate').get().then( - function(advancedPage) { + whenSearchDone.push( + this.$$('#advancedPageTemplate').get().then(function(advancedPage) { return settings.getSearchManager().search(query, advancedPage); })); } @@ -149,7 +149,9 @@ return Promise.all(whenSearchDone).then(function(requests) { // Combine the SearchRequests results to a single SearchResult object. return { - canceled: requests.some(function(r) { return r.canceled; }), + canceled: requests.some(function(r) { + return r.canceled; + }), didFindMatches: requests.some(function(r) { return r.didFindMatches(); }), @@ -239,9 +241,8 @@ */ showAdvancedPage_: function( currentRoute, inSearchMode, hasExpandedSection, advancedToggleExpanded) { - return hasExpandedSection ? - settings.Route.ADVANCED.contains(currentRoute) : - advancedToggleExpanded || inSearchMode; + return hasExpandedSection ? settings.Route.ADVANCED.contains(currentRoute) : + advancedToggleExpanded || inSearchMode; }, /**
diff --git a/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js b/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js index 5f0dee2..4c17eaf 100644 --- a/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js +++ b/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.js
@@ -131,8 +131,8 @@ case 'mouse': return 'settings:mouse'; default: - return device.connected ? - 'settings:bluetooth-connected' : 'settings:bluetooth'; + return device.connected ? 'settings:bluetooth-connected' : + 'settings:bluetooth'; } }, });
diff --git a/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js b/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js index 3139be3..92d2f241 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js +++ b/chrome/browser/resources/settings/certificate_manager_page/ca_trust_edit_dialog.js
@@ -33,18 +33,18 @@ /** @override */ attached: function() { this.explanationText_ = loadTimeData.getStringF( - 'certificateManagerCaTrustEditDialogExplanation', - this.model.name); + 'certificateManagerCaTrustEditDialogExplanation', this.model.name); // A non existing |model.id| indicates that a new certificate is being // imported, otherwise an existing certificate is being edited. if (this.model.id) { - this.browserProxy_.getCaCertificateTrust(this.model.id).then( - /** @param {!CaTrustInfo} trustInfo */ - function(trustInfo) { - this.trustInfo_ = trustInfo; - this.$.dialog.showModal(); - }.bind(this)); + this.browserProxy_.getCaCertificateTrust(this.model.id) + .then( + /** @param {!CaTrustInfo} trustInfo */ + function(trustInfo) { + this.trustInfo_ = trustInfo; + this.$.dialog.showModal(); + }.bind(this)); } else { /** @type {!CrDialogElement} */ (this.$.dialog).showModal(); } @@ -61,19 +61,20 @@ var whenDone = this.model.id ? this.browserProxy_.editCaCertificateTrust( - this.model.id, this.$.ssl.checked, - this.$.email.checked, this.$.objSign.checked) : + this.model.id, this.$.ssl.checked, this.$.email.checked, + this.$.objSign.checked) : this.browserProxy_.importCaCertificateTrustSelected( this.$.ssl.checked, this.$.email.checked, this.$.objSign.checked); - whenDone.then(function() { - this.$.spinner.active = false; - /** @type {!CrDialogElement} */ (this.$.dialog).close(); - }.bind(this), - /** @param {!CertificatesError} error */ - function(error) { - /** @type {!CrDialogElement} */ (this.$.dialog).close(); - this.fire('certificates-error', {error: error, anchor: null}); - }.bind(this)); + whenDone.then( + function() { + this.$.spinner.active = false; + /** @type {!CrDialogElement} */ (this.$.dialog).close(); + }.bind(this), + /** @param {!CertificatesError} error */ + function(error) { + /** @type {!CrDialogElement} */ (this.$.dialog).close(); + this.fire('certificates-error', {error: error, anchor: null}); + }.bind(this)); }, });
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js index 0ed71801..6abeece 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_delete_confirmation_dialog.js
@@ -82,14 +82,15 @@ /** @private */ onOkTap_: function() { - this.browserProxy_.deleteCertificate(this.model.id).then( - function() { - /** @type {!CrDialogElement} */ (this.$.dialog).close(); - }.bind(this), - /** @param {!CertificatesError} error */ - function(error) { - /** @type {!CrDialogElement} */ (this.$.dialog).close(); - this.fire('certificates-error', {error: error, anchor: null}); - }.bind(this)); + this.browserProxy_.deleteCertificate(this.model.id) + .then( + function() { + /** @type {!CrDialogElement} */ (this.$.dialog).close(); + }.bind(this), + /** @param {!CertificatesError} error */ + function(error) { + /** @type {!CrDialogElement} */ (this.$.dialog).close(); + this.fire('certificates-error', {error: error, anchor: null}); + }.bind(this)); }, });
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js index 33e9e466..83cedff 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_list.js
@@ -13,13 +13,15 @@ /** @type {!Array<!Certificate>} */ certificates: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @type {!CertificateType} */ certificateType: String, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ isGuest_: { type: Boolean, @@ -27,7 +29,7 @@ return loadTimeData.getBoolean('isGuest'); } }, -// </if> + // </if> }, behaviors: [I18nBehavior], @@ -62,7 +64,7 @@ return this.certificateType != CertificateType.OTHER; }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @return {boolean} * @private @@ -70,7 +72,7 @@ canImportAndBind_: function() { return !this.isGuest_ && this.certificateType == CertificateType.PERSONAL; }, -// </if> + // </if> /** * Handles a rejected Promise returned from |browserProxy_|. @@ -112,20 +114,20 @@ * @private */ onImportTap_: function(e) { - this.handleImport_(false, /** @type {!HTMLElement} */ ( - Polymer.dom(e).localTarget)); + this.handleImport_( + false, /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget)); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @private * @param {!Event} e */ onImportAndBindTap_: function(e) { - this.handleImport_(true, /** @type {!HTMLElement} */ ( - Polymer.dom(e).localTarget)); + this.handleImport_( + true, /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget)); }, -// </if> + // </if> /** * @param {boolean} useHardwareBacked @@ -135,18 +137,15 @@ handleImport_: function(useHardwareBacked, anchor) { var browserProxy = settings.CertificatesBrowserProxyImpl.getInstance(); if (this.certificateType == CertificateType.PERSONAL) { - browserProxy.importPersonalCertificate(useHardwareBacked).then( - function(showPasswordPrompt) { + browserProxy.importPersonalCertificate(useHardwareBacked) + .then(function(showPasswordPrompt) { if (showPasswordPrompt) this.dispatchImportActionEvent_(null, anchor); - }.bind(this), - this.onRejected_.bind(this, anchor)); + }.bind(this), this.onRejected_.bind(this, anchor)); } else if (this.certificateType == CertificateType.CA) { - browserProxy.importCaCertificate().then( - function(certificateName) { - this.dispatchImportActionEvent_({name: certificateName}, anchor); - }.bind(this), - this.onRejected_.bind(this, anchor)); + browserProxy.importCaCertificate().then(function(certificateName) { + this.dispatchImportActionEvent_({name: certificateName}, anchor); + }.bind(this), this.onRejected_.bind(this, anchor)); } else if (this.certificateType == CertificateType.SERVER) { browserProxy.importServerCertificate().catch( this.onRejected_.bind(this, anchor));
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js index 3d28a88..9433f7c 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_manager_page.js
@@ -21,25 +21,33 @@ /** @type {!Array<!Certificate>} */ personalCerts: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @type {!Array<!Certificate>} */ serverCerts: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @type {!Array<!Certificate>} */ caCerts: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @type {!Array<!Certificate>} */ otherCerts: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @private */ @@ -117,10 +125,8 @@ if (event.detail.certificateType == CertificateType.PERSONAL) { this.openDialog_( 'settings-certificate-password-decryption-dialog', - 'showPasswordDecryptionDialog_', - event.detail.anchor); - } else if (event.detail.certificateType == - CertificateType.CA) { + 'showPasswordDecryptionDialog_', event.detail.anchor); + } else if (event.detail.certificateType == CertificateType.CA) { this.openDialog_( 'settings-ca-trust-edit-dialog', 'showCaTrustEditDialog_', event.detail.anchor); @@ -134,8 +140,7 @@ this.openDialog_( 'settings-certificate-delete-confirmation-dialog', 'showDeleteConfirmationDialog_', event.detail.anchor); - } else if (event.detail.action == - CertificateAction.EXPORT_PERSONAL) { + } else if (event.detail.action == CertificateAction.EXPORT_PERSONAL) { this.openDialog_( 'settings-certificate-password-encryption-dialog', 'showPasswordEncryptionDialog_', event.detail.anchor); @@ -149,8 +154,7 @@ var detail = /** @type {!CertificatesErrorEventDetail} */ (event.detail); this.errorDialogModel_ = detail.error; this.openDialog_( - 'settings-certificates-error-dialog', - 'showErrorDialog_', + 'settings-certificates-error-dialog', 'showErrorDialog_', detail.anchor); event.stopPropagation(); }.bind(this));
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js index 3ecc2f0..cdc846e 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_password_decryption_dialog.js
@@ -37,8 +37,8 @@ /** @private */ onOkTap_: function() { - this.browserProxy_.importPersonalCertificatePasswordSelected( - this.password_).then( + this.browserProxy_.importPersonalCertificatePasswordSelected(this.password_) + .then( function() { /** @type {!CrDialogElement} */ (this.$.dialog).close(); }.bind(this),
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js index a768879..ed74927 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_password_encryption_dialog.js
@@ -46,8 +46,8 @@ /** @private */ onOkTap_: function() { - this.browserProxy_.exportPersonalCertificatePasswordSelected( - this.password_).then( + this.browserProxy_.exportPersonalCertificatePasswordSelected(this.password_) + .then( function() { this.$.dialog.close(); }.bind(this), @@ -60,8 +60,8 @@ /** @private */ validate_: function() { - var isValid = this.password_ != '' && - this.password_ == this.confirmPassword_; + var isValid = + this.password_ != '' && this.password_ == this.confirmPassword_; this.$.ok.disabled = !isValid; }, });
diff --git a/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js b/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js index cd76f4b..9c858be8 100644 --- a/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js +++ b/chrome/browser/resources/settings/certificate_manager_page/certificate_subentry.js
@@ -107,12 +107,11 @@ onExportTap_: function(event) { this.closePopupMenu_(); if (this.certificateType == CertificateType.PERSONAL) { - this.browserProxy_.exportPersonalCertificate(this.model.id).then( - function() { + this.browserProxy_.exportPersonalCertificate(this.model.id) + .then(function() { this.dispatchCertificateActionEvent_( CertificateAction.EXPORT_PERSONAL); - }.bind(this), - this.onRejected_.bind(this)); + }.bind(this), this.onRejected_.bind(this)); } else { this.browserProxy_.exportCertificate(this.model.id); } @@ -157,8 +156,7 @@ /** @private */ onDotsTap_: function() { - var actionMenu = /** @type {!CrActionMenuElement} */( - this.$.menu.get()); + var actionMenu = /** @type {!CrActionMenuElement} */ (this.$.menu.get()); actionMenu.showAt(this.$.dots); }, });
diff --git a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js index 77d18fd1..89dd30b 100644 --- a/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js +++ b/chrome/browser/resources/settings/chrome_cleanup_page/chrome_cleanup_page.js
@@ -237,9 +237,9 @@ * Hides the Cleanup card. * @private */ - onDismiss_: function() { - this.fire('chrome-cleanup-dismissed'); - }, + onDismiss_: function() { + this.fire('chrome-cleanup-dismissed'); + }, /** * Dismiss the card.
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js index d4385d12..f3a23a0 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.js
@@ -87,10 +87,7 @@ }, /** @private */ - showImportantSitesDialog_: { - type: Boolean, - value: false - }, + showImportantSitesDialog_: {type: Boolean, value: false}, }, /** @private {settings.ClearBrowsingDataBrowserProxy} */ @@ -99,12 +96,9 @@ /** @override */ ready: function() { this.$.clearFrom.menuOptions = this.clearFromOptions_; + this.addWebUIListener('update-footer', this.updateFooter_.bind(this)); this.addWebUIListener( - 'update-footer', - this.updateFooter_.bind(this)); - this.addWebUIListener( - 'update-counter-text', - this.updateCounterText_.bind(this)); + 'update-counter-text', this.updateCounterText_.bind(this)); }, /** @override */
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.js b/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.js index 3c111d7..5cf45a4 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.js +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/history_deletion_dialog.js
@@ -24,4 +24,3 @@ this.$.dialog.close(); }, }); -
diff --git a/chrome/browser/resources/settings/controls/pref_control_behavior.js b/chrome/browser/resources/settings/controls/pref_control_behavior.js index 29da24c6..dd3e55b 100644 --- a/chrome/browser/resources/settings/controls/pref_control_behavior.js +++ b/chrome/browser/resources/settings/controls/pref_control_behavior.js
@@ -40,4 +40,3 @@ }.bind(this)); }, }; -
diff --git a/chrome/browser/resources/settings/controls/settings_dropdown_menu.js b/chrome/browser/resources/settings/controls/settings_dropdown_menu.js index 4bc6c655..e3fddcf 100644 --- a/chrome/browser/resources/settings/controls/settings_dropdown_menu.js +++ b/chrome/browser/resources/settings/controls/settings_dropdown_menu.js
@@ -76,8 +76,8 @@ if (selected == this.notFoundValue_) return; - var prefValue = Settings.PrefUtil.stringToPrefValue( - selected, assert(this.pref)); + var prefValue = + Settings.PrefUtil.stringToPrefValue(selected, assert(this.pref)); if (prefValue !== undefined) this.set('pref.value', prefValue); },
diff --git a/chrome/browser/resources/settings/controls/settings_radio_group.js b/chrome/browser/resources/settings/controls/settings_radio_group.js index c56d803..07549b3 100644 --- a/chrome/browser/resources/settings/controls/settings_radio_group.js +++ b/chrome/browser/resources/settings/controls/settings_radio_group.js
@@ -21,11 +21,7 @@ /** * IronSelectableBehavior selected attribute. */ - selected: { - type: String, - notify: true, - observer: 'selectedChanged_' - }, + selected: {type: String, notify: true, observer: 'selectedChanged_'}, }, hostAttributes: { @@ -38,7 +34,7 @@ /** @private */ prefChanged_: function() { - var pref = /** @type {!chrome.settingsPrivate.PrefObject} */(this.pref); + var pref = /** @type {!chrome.settingsPrivate.PrefObject} */ (this.pref); this.selected = Settings.PrefUtil.prefToString(pref); }, @@ -46,7 +42,7 @@ selectedChanged_: function(selected) { if (!this.pref) return; - this.set('pref.value', - Settings.PrefUtil.stringToPrefValue(selected, this.pref)); + this.set( + 'pref.value', Settings.PrefUtil.stringToPrefValue(selected, this.pref)); }, });
diff --git a/chrome/browser/resources/settings/controls/settings_slider.js b/chrome/browser/resources/settings/controls/settings_slider.js index d187a7c4..aa66151 100644 --- a/chrome/browser/resources/settings/controls/settings_slider.js +++ b/chrome/browser/resources/settings/controls/settings_slider.js
@@ -60,9 +60,9 @@ * @private */ onSliderChanged_: function() { - var sliderValue = isNaN(this.$.slider.immediateValue) - ? this.$.slider.value - : this.$.slider.immediateValue; + var sliderValue = isNaN(this.$.slider.immediateValue) ? + this.$.slider.value : + this.$.slider.immediateValue; var newValue; if (this.tickValues && this.tickValues.length > 0)
diff --git a/chrome/browser/resources/settings/default_browser_page/default_browser_page.js b/chrome/browser/resources/settings/default_browser_page/default_browser_page.js index cced69f..752fb89a 100644 --- a/chrome/browser/resources/settings/default_browser_page/default_browser_page.js +++ b/chrome/browser/resources/settings/default_browser_page/default_browser_page.js
@@ -36,7 +36,8 @@ /** @override */ ready: function() { - this.addWebUIListener('settings.updateDefaultBrowserState', + this.addWebUIListener( + 'settings.updateDefaultBrowserState', this.updateDefaultBrowserState_.bind(this)); this.browserProxy_.requestDefaultBrowserState().then( @@ -57,7 +58,8 @@ this.isDefault_ = true; else if (!defaultBrowserState.canBeDefault) this.isSecondaryInstall_ = true; - else if (!defaultBrowserState.isDisabledByPolicy && + else if ( + !defaultBrowserState.isDisabledByPolicy && !defaultBrowserState.isUnknownError) this.maySetDefaultBrowser_ = true; else
diff --git a/chrome/browser/resources/settings/device_page/device_page.js b/chrome/browser/resources/settings/device_page/device_page.js index dc714a0..44d61a6 100644 --- a/chrome/browser/resources/settings/device_page/device_page.js +++ b/chrome/browser/resources/settings/device_page/device_page.js
@@ -57,18 +57,12 @@ type: Object, value: function() { var map = new Map(); - map.set( - settings.Route.POINTERS.path, '#pointersRow .subpage-arrow'); - map.set( - settings.Route.KEYBOARD.path, '#keyboardRow .subpage-arrow'); - map.set( - settings.Route.STYLUS.path, '#stylusRow .subpage-arrow'); - map.set( - settings.Route.DISPLAY.path, '#displayRow .subpage-arrow'); - map.set( - settings.Route.STORAGE.path, '#storageRow .subpage-arrow'); - map.set( - settings.Route.POWER.path, '#powerRow .subpage-arrow'); + map.set(settings.Route.POINTERS.path, '#pointersRow .subpage-arrow'); + map.set(settings.Route.KEYBOARD.path, '#keyboardRow .subpage-arrow'); + map.set(settings.Route.STYLUS.path, '#stylusRow .subpage-arrow'); + map.set(settings.Route.DISPLAY.path, '#displayRow .subpage-arrow'); + map.set(settings.Route.STORAGE.path, '#storageRow .subpage-arrow'); + map.set(settings.Route.POWER.path, '#powerRow .subpage-arrow'); return map; }, },
diff --git a/chrome/browser/resources/settings/device_page/display.js b/chrome/browser/resources/settings/device_page/display.js index 14cb651..d5eea936 100644 --- a/chrome/browser/resources/settings/device_page/display.js +++ b/chrome/browser/resources/settings/device_page/display.js
@@ -109,14 +109,21 @@ scheduleTypesList_: { type: Array, value: function() { - return [{ - name: loadTimeData.getString('displayNightLightScheduleNever'), - value: NightLightScheduleType.NEVER }, { - name: loadTimeData.getString( - 'displayNightLightScheduleSunsetToSunRise'), - value: NightLightScheduleType.SUNSET_TO_SUNRISE }, { - name: loadTimeData.getString('displayNightLightScheduleCustom'), - value: NightLightScheduleType.CUSTOM }]; + return [ + { + name: loadTimeData.getString('displayNightLightScheduleNever'), + value: NightLightScheduleType.NEVER + }, + { + name: loadTimeData.getString( + 'displayNightLightScheduleSunsetToSunRise'), + value: NightLightScheduleType.SUNSET_TO_SUNRISE + }, + { + name: loadTimeData.getString('displayNightLightScheduleCustom'), + value: NightLightScheduleType.CUSTOM + } + ]; }, }, @@ -239,8 +246,8 @@ this.currentSelectedModeIndex_ = 0; } else { this.modeValues_ = Array.from(Array(numModes).keys()); - this.currentSelectedModeIndex_ = this.getSelectedModeIndex_( - selectedDisplay); + this.currentSelectedModeIndex_ = + this.getSelectedModeIndex_(selectedDisplay); } // Set |selectedDisplay| first since only the resolution slider depends // on |selectedModePref_|. @@ -382,7 +389,7 @@ this.selectedDisplay.bounds.height.toString()); } var mode = this.selectedDisplay.modes[ - /** @type {number} */(this.selectedModePref_.value)]; + /** @type {number} */ (this.selectedModePref_.value)]; assert(mode); var best = this.selectedDisplay.isInternal ? mode.uiScale == 1.0 : mode.isNative; @@ -467,7 +474,7 @@ } /** @type {!chrome.system.display.DisplayProperties} */ var properties = { displayMode: this.selectedDisplay.modes[ - /** @type {number} */(this.selectedModePref_.value)] + /** @type {number} */ (this.selectedModePref_.value)] }; settings.display.systemDisplayApi.setDisplayProperties( this.selectedDisplay.id, properties, @@ -573,6 +580,6 @@ onScheduleTypeChanged_: function() { this.shouldOpenCustomScheduleCollapse_ = this.getPref('ash.night_light.schedule_type').value == - NightLightScheduleType.CUSTOM; + NightLightScheduleType.CUSTOM; }, });
diff --git a/chrome/browser/resources/settings/device_page/display_layout.js b/chrome/browser/resources/settings/device_page/display_layout.js index 76aac19..7063a7c0 100644 --- a/chrome/browser/resources/settings/device_page/display_layout.js +++ b/chrome/browser/resources/settings/device_page/display_layout.js
@@ -42,7 +42,9 @@ visualOffset_: {left: 0, top: 0}, /** @override */ - detached: function() { this.initializeDrag(false); }, + detached: function() { + this.initializeDrag(false); + }, /** * Called explicitly when |this.displays| and their associated |this.layouts|
diff --git a/chrome/browser/resources/settings/device_page/keyboard.js b/chrome/browser/resources/settings/device_page/keyboard.js index f4a4534e..ed49f142 100644 --- a/chrome/browser/resources/settings/device_page/keyboard.js +++ b/chrome/browser/resources/settings/device_page/keyboard.js
@@ -80,28 +80,36 @@ */ setUpKeyMapTargets_: function() { // Ordering is according to UX, but values match settings.ModifierKey. - this.keyMapTargets_ = [{ - value: settings.ModifierKey.SEARCH_KEY, - name: loadTimeData.getString('keyboardKeySearch'), - }, { - value: settings.ModifierKey.CONTROL_KEY, - name: loadTimeData.getString('keyboardKeyCtrl') - }, { - value: settings.ModifierKey.ALT_KEY, - name: loadTimeData.getString('keyboardKeyAlt') - }, { - value: settings.ModifierKey.CAPS_LOCK_KEY, - name: loadTimeData.getString('keyboardKeyCapsLock') - }, { - value: settings.ModifierKey.ESCAPE_KEY, - name: loadTimeData.getString('keyboardKeyEscape') - }, { - value: settings.ModifierKey.BACKSPACE_KEY, - name: loadTimeData.getString('keyboardKeyBackspace') - }, { - value: settings.ModifierKey.VOID_KEY, - name: loadTimeData.getString('keyboardKeyDisabled') - }]; + this.keyMapTargets_ = [ + { + value: settings.ModifierKey.SEARCH_KEY, + name: loadTimeData.getString('keyboardKeySearch'), + }, + { + value: settings.ModifierKey.CONTROL_KEY, + name: loadTimeData.getString('keyboardKeyCtrl') + }, + { + value: settings.ModifierKey.ALT_KEY, + name: loadTimeData.getString('keyboardKeyAlt') + }, + { + value: settings.ModifierKey.CAPS_LOCK_KEY, + name: loadTimeData.getString('keyboardKeyCapsLock') + }, + { + value: settings.ModifierKey.ESCAPE_KEY, + name: loadTimeData.getString('keyboardKeyEscape') + }, + { + value: settings.ModifierKey.BACKSPACE_KEY, + name: loadTimeData.getString('keyboardKeyBackspace') + }, + { + value: settings.ModifierKey.VOID_KEY, + name: loadTimeData.getString('keyboardKeyDisabled') + } + ]; }, /**
diff --git a/chrome/browser/resources/settings/device_page/layout_behavior.js b/chrome/browser/resources/settings/device_page/layout_behavior.js index 77a56a3..d1665050 100644 --- a/chrome/browser/resources/settings/device_page/layout_behavior.js +++ b/chrome/browser/resources/settings/device_page/layout_behavior.js
@@ -208,8 +208,8 @@ assert(bounds); this.calculatedBoundsMap_.set( displayId, - /** @type {!chrome.system.display.Bounds} */ ( - Object.assign({}, bounds))); + /** @type {!chrome.system.display.Bounds} */ + (Object.assign({}, bounds))); }, /**
diff --git a/chrome/browser/resources/settings/device_page/night_light_slider.js b/chrome/browser/resources/settings/device_page/night_light_slider.js index 64e3aa5..c83f8ca 100644 --- a/chrome/browser/resources/settings/device_page/night_light_slider.js +++ b/chrome/browser/resources/settings/device_page/night_light_slider.js
@@ -53,7 +53,7 @@ observers: [ 'customTimesChanged_(prefs.ash.night_light.custom_start_time.*, ' + - 'prefs.ash.night_light.custom_end_time.*)', + 'prefs.ash.night_light.custom_end_time.*)', ], keyBindings: { @@ -158,7 +158,8 @@ return; var knobPref = this.dragObject_ == this.$.startKnob ? - 'ash.night_light.custom_start_time' : 'ash.night_light.custom_end_time'; + 'ash.night_light.custom_start_time' : + 'ash.night_light.custom_end_time'; if (event.detail.ddx > 0) { // Increment the knob's pref by the amount of deltaMinutes. @@ -228,11 +229,11 @@ * @private */ customTimesChanged_: function() { - var startOffsetMinutes = /** @type {number} */( + var startOffsetMinutes = /** @type {number} */ ( this.getPref('ash.night_light.custom_start_time').value); this.startTime_ = this.offsetMinutesToTimeString_(startOffsetMinutes); this.updateKnobLeft_(this.$.startKnob, startOffsetMinutes); - var endOffsetMinutes = /** @type {number} */( + var endOffsetMinutes = /** @type {number} */ ( this.getPref('ash.night_light.custom_end_time').value); this.endTime_ = this.offsetMinutesToTimeString_(endOffsetMinutes); this.updateKnobLeft_(this.$.endKnob, endOffsetMinutes); @@ -249,7 +250,7 @@ updateKnobLeft_: function(knob, offsetMinutes) { var offsetAfter6pm = (offsetMinutes + TOTAL_MINUTES_PER_DAY - OFFSET_MINUTES_6PM) % - TOTAL_MINUTES_PER_DAY; + TOTAL_MINUTES_PER_DAY; var ratio = offsetAfter6pm / TOTAL_MINUTES_PER_DAY; if (ratio == 0) { @@ -285,17 +286,18 @@ // The end progress bar starts from either the start knob or the start of // the slider (whichever is to its left) and ends at the end knob. - var endProgressLeft = startKnob.offsetLeft >= endKnob.offsetLeft - ? '0px' : startKnob.style.left; + var endProgressLeft = startKnob.offsetLeft >= endKnob.offsetLeft ? + '0px' : + startKnob.style.left; endProgress.style.left = endProgressLeft; endProgress.style.width = (parseFloat(endKnob.style.left) - parseFloat(endProgressLeft)) + 'px'; // The start progress bar starts at the start knob, and ends at either the // end knob or the end of the slider (whichever is to its right). - var startProgressRight = endKnob.offsetLeft < startKnob.offsetLeft - ? this.$.sliderBar.offsetWidth - : endKnob.style.left; + var startProgressRight = endKnob.offsetLeft < startKnob.offsetLeft ? + this.$.sliderBar.offsetWidth : + endKnob.style.left; startProgress.style.left = startKnob.style.left; startProgress.style.width = (parseFloat(startProgressRight) - parseFloat(startKnob.style.left)) + @@ -312,8 +314,8 @@ fixLabelsOverlapIfAny_: function() { var startLabel = this.$.startLabel; var endLabel = this.$.endLabel; - var distance = Math.abs(parseFloat(startLabel.style.left) - - parseFloat(endLabel.style.left)); + var distance = Math.abs( + parseFloat(startLabel.style.left) - parseFloat(endLabel.style.left)); if (distance <= startLabel.offsetWidth) { // Shift the end label up so that it doesn't overlap with the start label. endLabel.classList.add('end-label-overlap'); @@ -378,7 +380,8 @@ * @private */ decrementPref_: function(prefPath, decrement) { - var value = /** @type {number} */(this.getPref(prefPath).value) - decrement; + var value = + /** @type {number} */ (this.getPref(prefPath).value) - decrement; var otherValue = this.getOtherKnobPrefValue_(prefPath); if (value > otherValue &&
diff --git a/chrome/browser/resources/settings/device_page/storage.js b/chrome/browser/resources/settings/device_page/storage.js index 07c2fd0..47c52115d 100644 --- a/chrome/browser/resources/settings/device_page/storage.js +++ b/chrome/browser/resources/settings/device_page/storage.js
@@ -76,8 +76,7 @@ /** @override */ ready: function() { cr.addWebUIListener( - 'storage-size-stat-changed', - this.handleSizeStatChanged_.bind(this)); + 'storage-size-stat-changed', this.handleSizeStatChanged_.bind(this)); cr.addWebUIListener( 'storage-downloads-size-changed', this.handleDownloadsSizeChanged_.bind(this));
diff --git a/chrome/browser/resources/settings/device_page/stylus.js b/chrome/browser/resources/settings/device_page/stylus.js index fc55d8e..d80f250 100644 --- a/chrome/browser/resources/settings/device_page/stylus.js +++ b/chrome/browser/resources/settings/device_page/stylus.js
@@ -78,7 +78,8 @@ findApp_: function(id) { return this.appChoices_.find(function(app) { return app.value == id; - }) || null; + }) || + null; }, /** @private */
diff --git a/chrome/browser/resources/settings/internet_page/internet_detail_page.js b/chrome/browser/resources/settings/internet_page/internet_detail_page.js index f696cb5..ce8553d 100644 --- a/chrome/browser/resources/settings/internet_page/internet_detail_page.js +++ b/chrome/browser/resources/settings/internet_page/internet_detail_page.js
@@ -242,8 +242,8 @@ button.focus(); } - if (this.shoudlShowConfigureWhenNetworkLoaded_ - && this.networkProperties.Tether) { + if (this.shoudlShowConfigureWhenNetworkLoaded_ && + this.networkProperties.Tether) { this.showTetherDialog_(); } }, @@ -567,9 +567,10 @@ /** @private */ onTetherConnect_: function() { this.getTetherDialog_().close(); - this.fire('network-connect', - {networkProperties: this.networkProperties, - bypassConnectionDialog: true}); + this.fire('network-connect', { + networkProperties: this.networkProperties, + bypassConnectionDialog: true + }); }, /** @private */ @@ -974,8 +975,7 @@ * @private */ showCellularSim_: function(networkProperties) { - if (networkProperties.Type != 'Cellular' || - !networkProperties.Cellular) { + if (networkProperties.Type != 'Cellular' || !networkProperties.Cellular) { return false; } return networkProperties.Cellular.Family == 'GSM';
diff --git a/chrome/browser/resources/settings/internet_page/internet_subpage.js b/chrome/browser/resources/settings/internet_page/internet_subpage.js index 7735898..5086195 100644 --- a/chrome/browser/resources/settings/internet_page/internet_subpage.js +++ b/chrome/browser/resources/settings/internet_page/internet_subpage.js
@@ -452,8 +452,8 @@ */ tetherToggleIsEnabled_: function(deviceState, tetherDeviceState) { return this.tetherToggleIsVisible_(deviceState, tetherDeviceState) && - this.enableToggleIsEnabled_(tetherDeviceState) && - tetherDeviceState.State != CrOnc.DeviceState.UNINITIALIZED; + this.enableToggleIsEnabled_(tetherDeviceState) && + tetherDeviceState.State != CrOnc.DeviceState.UNINITIALIZED; }, /**
diff --git a/chrome/browser/resources/settings/internet_page/network_apnlist.js b/chrome/browser/resources/settings/internet_page/network_apnlist.js index 629e27c2..2ecd5f3 100644 --- a/chrome/browser/resources/settings/internet_page/network_apnlist.js +++ b/chrome/browser/resources/settings/internet_page/network_apnlist.js
@@ -181,7 +181,7 @@ * @private */ onSelectApnChange_: function(event) { - var target = /** @type {!HTMLSelectElement} */(event.target); + var target = /** @type {!HTMLSelectElement} */ (event.target); var accessPointName = target.value; // When selecting 'Other', don't set a change event unless a valid // non-default value has been set for Other.
diff --git a/chrome/browser/resources/settings/internet_page/network_ip_config.js b/chrome/browser/resources/settings/internet_page/network_ip_config.js index 695ba50..da9aefaf 100644 --- a/chrome/browser/resources/settings/internet_page/network_ip_config.js +++ b/chrome/browser/resources/settings/internet_page/network_ip_config.js
@@ -87,7 +87,7 @@ this.savedStaticIp_ = undefined; // Update the 'automatic' property. - if (this.networkProperties.IPAddressConfigType ) { + if (this.networkProperties.IPAddressConfigType) { var ipConfigType = CrOnc.getActiveValue(this.networkProperties.IPAddressConfigType); this.automatic_ = (ipConfigType != CrOnc.IPConfigType.STATIC);
diff --git a/chrome/browser/resources/settings/internet_page/network_property_list.js b/chrome/browser/resources/settings/internet_page/network_property_list.js index fd43456..b50a756 100644 --- a/chrome/browser/resources/settings/internet_page/network_property_list.js +++ b/chrome/browser/resources/settings/internet_page/network_property_list.js
@@ -204,9 +204,9 @@ if (key == 'Tether.Carrier') { assert(typeof value == 'string'); - return (!value || value == 'unknown-carrier') - ? this.i18n('tetherUnknownCarrier') - : value; + return (!value || value == 'unknown-carrier') ? + this.i18n('tetherUnknownCarrier') : + value; } return '';
diff --git a/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js b/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js index 83dbb2ce..347b229 100644 --- a/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js +++ b/chrome/browser/resources/settings/internet_page/network_proxy_exclusions.js
@@ -25,7 +25,9 @@ */ exclusions: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, notify: true } },
diff --git a/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js b/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js index a5e2df2..6bae7d7 100644 --- a/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js +++ b/chrome/browser/resources/settings/internet_page/tether_connection_dialog.js
@@ -103,8 +103,9 @@ * @private */ getBatteryPercentageString_: function(networkProperties) { - return this.i18n('tetherConnectionBatteryPercentage', - this.getBatteryPercentageAsString_(networkProperties)); + return this.i18n( + 'tetherConnectionBatteryPercentage', + this.getBatteryPercentageAsString_(networkProperties)); }, /** @@ -113,8 +114,8 @@ * @private */ getExplanation_: function(networkProperties) { - return this.i18n('tetherConnectionExplanation', - CrOnc.getNetworkName(networkProperties)); + return this.i18n( + 'tetherConnectionExplanation', CrOnc.getNetworkName(networkProperties)); }, /** @@ -123,8 +124,9 @@ * @private */ getDescriptionTitle_: function(networkProperties) { - return this.i18n('tetherConnectionDescriptionTitle', - CrOnc.getNetworkName(networkProperties)); + return this.i18n( + 'tetherConnectionDescriptionTitle', + CrOnc.getNetworkName(networkProperties)); }, /** @@ -133,7 +135,8 @@ * @private */ getBatteryDescription_: function(networkProperties) { - return this.i18n('tetherConnectionDescriptionBattery', - this.getBatteryPercentageAsString_(networkProperties)); + return this.i18n( + 'tetherConnectionDescriptionBattery', + this.getBatteryPercentageAsString_(networkProperties)); }, });
diff --git a/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js b/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js index ef287e8..592ff28 100644 --- a/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js +++ b/chrome/browser/resources/settings/languages_page/edit_dictionary_page.js
@@ -38,9 +38,9 @@ /** @override */ ready: function() { - this.languageSettingsPrivate = - settings.languageSettingsPrivateApiForTest || - /** @type {!LanguageSettingsPrivate} */(chrome.languageSettingsPrivate); + this.languageSettingsPrivate = settings.languageSettingsPrivateApiForTest || + /** @type {!LanguageSettingsPrivate} */ + (chrome.languageSettingsPrivate); this.languageSettingsPrivate.getSpellcheckWords(function(words) { this.words_ = words;
diff --git a/chrome/browser/resources/settings/languages_page/languages.js b/chrome/browser/resources/settings/languages_page/languages.js index dc26a82..e7bf2473 100644 --- a/chrome/browser/resources/settings/languages_page/languages.js +++ b/chrome/browser/resources/settings/languages_page/languages.js
@@ -34,7 +34,8 @@ }; var preferredLanguagesPrefName = cr.isChromeOS ? - 'settings.language.preferred_languages' : 'intl.accept_languages'; + 'settings.language.preferred_languages' : + 'intl.accept_languages'; /** * Singleton element that generates the languages model on start-up and @@ -64,7 +65,9 @@ type: Object, notify: true, readOnly: true, - value: function() { return /** @type {!LanguageHelper} */(this); }, + value: function() { + return /** @type {!LanguageHelper} */ (this); + }, }, /** @@ -84,7 +87,9 @@ */ supportedLanguageMap_: { type: Object, - value: function() { return new Map(); }, + value: function() { + return new Map(); + }, }, /** @@ -93,7 +98,9 @@ */ enabledLanguageSet_: { type: Object, - value: function() { return new Set(); }, + value: function() { + return new Set(); + }, }, /** @@ -102,7 +109,9 @@ */ supportedInputMethodMap_: { type: Object, - value: function() { return new Map(); }, + value: function() { + return new Map(); + }, }, /** @@ -113,7 +122,9 @@ */ languageInputMethods_: { type: Object, - value: function() { return new Map(); }, + value: function() { + return new Map(); + }, }, /** @private Prospective UI language when the page was loaded. */ @@ -148,19 +159,19 @@ /** @private {?LanguageSettingsPrivate} */ languageSettingsPrivate_: null, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private {?InputMethodPrivate} */ inputMethodPrivate_: null, -// </if> + // </if> /** @override */ attached: function() { this.browserProxy_ = settings.LanguagesBrowserProxyImpl.getInstance(); this.languageSettingsPrivate_ = this.browserProxy_.getLanguageSettingsPrivate(); -// <if expr="chromeos"> + // <if expr="chromeos"> this.inputMethodPrivate_ = this.browserProxy_.getInputMethodPrivate(); -// </if> + // </if> var promises = []; @@ -236,7 +247,8 @@ * @private */ prospectiveUILanguageChanged_: function(prospectiveUILanguage) { - this.set('languages.prospectiveUILanguage', + this.set( + 'languages.prospectiveUILanguage', prospectiveUILanguage || this.originalProspectiveUILanguage_); }, @@ -261,12 +273,13 @@ * @private */ spellCheckDictionariesPrefChanged_: function() { - var spellCheckSet = this.makeSetFromArray_(/** @type {!Array<string>} */( + var spellCheckSet = this.makeSetFromArray_(/** @type {!Array<string>} */ ( this.getPref('spellcheck.dictionaries').value)); for (var i = 0; i < this.languages.enabled.length; i++) { var languageState = this.languages.enabled[i]; - this.set('languages.enabled.' + i + '.spellCheckEnabled', - !!spellCheckSet.has(languageState.language.code)); + this.set( + 'languages.enabled.' + i + '.spellCheckEnabled', + !!spellCheckSet.has(languageState.language.code)); } }, @@ -274,7 +287,7 @@ translateLanguagesPrefChanged_: function() { var translateBlockedPref = this.getPref('translate_blocked_languages'); var translateBlockedSet = this.makeSetFromArray_( - /** @type {!Array<string>} */(translateBlockedPref.value)); + /** @type {!Array<string>} */ (translateBlockedPref.value)); for (var i = 0; i < this.languages.enabled.length; i++) { if (this.languages.enabled[i].language.code == @@ -301,8 +314,9 @@ * input method (Chrome OS only). * @private */ - createModel_: function(supportedLanguages, translateTarget, - supportedInputMethods, currentInputMethodId) { + createModel_: function( + supportedLanguages, translateTarget, supportedInputMethods, + currentInputMethodId) { // Populate the hash map of supported languages. for (var i = 0; i < supportedLanguages.length; i++) { var language = supportedLanguages[i]; @@ -336,7 +350,7 @@ var prospectiveUILanguage; if (cr.isChromeOS || cr.isWindows) { prospectiveUILanguage = - /** @type {string} */(this.getPref('intl.app_locale').value) || + /** @type {string} */ (this.getPref('intl.app_locale').value) || this.originalProspectiveUILanguage_; } @@ -347,7 +361,7 @@ for (var l = 0; l < enabledLanguageStates.length; l++) this.enabledLanguageSet_.add(enabledLanguageStates[l].language.code); - var model = /** @type {!LanguagesModel} */({ + var model = /** @type {!LanguagesModel} */ ({ supported: supportedLanguages, enabled: enabledLanguageStates, translateTarget: translateTarget, @@ -357,7 +371,7 @@ model.prospectiveUILanguage = prospectiveUILanguage; if (cr.isChromeOS) { - model.inputMethods = /** @type {!InputMethodsModel} */({ + model.inputMethods = /** @type {!InputMethodsModel} */ ({ supported: supportedInputMethods, enabled: this.getEnabledInputMethods_(), currentId: currentInputMethodId, @@ -384,12 +398,12 @@ var pref = this.getPref(preferredLanguagesPrefName); var enabledLanguageCodes = pref.value.split(','); var spellCheckPref = this.getPref('spellcheck.dictionaries'); - var spellCheckSet = this.makeSetFromArray_(/** @type {!Array<string>} */( - spellCheckPref.value)); + var spellCheckSet = this.makeSetFromArray_( + /** @type {!Array<string>} */ (spellCheckPref.value)); var translateBlockedPref = this.getPref('translate_blocked_languages'); var translateBlockedSet = this.makeSetFromArray_( - /** @type {!Array<string>} */(translateBlockedPref.value)); + /** @type {!Array<string>} */ (translateBlockedPref.value)); var enabledLanguageStates = []; for (var i = 0; i < enabledLanguageCodes.length; i++) { @@ -398,14 +412,13 @@ // Skip unsupported languages. if (!language) continue; - var languageState = /** @type {LanguageState} */({}); + var languageState = /** @type {LanguageState} */ ({}); languageState.language = language; languageState.spellCheckEnabled = !!spellCheckSet.has(code); // Translate is considered disabled if this language maps to any translate // language that is blocked. var translateCode = this.convertLanguageCodeForTranslate(code); - languageState.translateEnabled = - !!language.supportsTranslate && + languageState.translateEnabled = !!language.supportsTranslate && !translateBlockedSet.has(translateCode) && translateCode != translateTarget && (!prospectiveUILanguage || code != prospectiveUILanguage); @@ -425,15 +438,18 @@ var enabledInputMethodIds = this.getPref('settings.language.preload_engines').value.split(','); - enabledInputMethodIds = enabledInputMethodIds.concat(this.getPref( - 'settings.language.enabled_extension_imes').value.split(',')); + enabledInputMethodIds = enabledInputMethodIds.concat( + this.getPref('settings.language.enabled_extension_imes') + .value.split(',')); // Return only supported input methods. - return enabledInputMethodIds.map(function(id) { - return this.supportedInputMethodMap_.get(id); - }.bind(this)).filter(function(inputMethod) { - return !!inputMethod; - }); + return enabledInputMethodIds + .map(function(id) { + return this.supportedInputMethodMap_.get(id); + }.bind(this)) + .filter(function(inputMethod) { + return !!inputMethod; + }); }, /** @private */ @@ -443,7 +459,8 @@ var enabledInputMethodSet = this.makeSetFromArray_(enabledInputMethods); for (var i = 0; i < this.languages.inputMethods.supported.length; i++) { - this.set('languages.inputMethods.supported.' + i + '.enabled', + this.set( + 'languages.inputMethods.supported.' + i + '.enabled', enabledInputMethodSet.has(this.languages.inputMethods.supported[i])); } this.set('languages.inputMethods.enabled', enabledInputMethods); @@ -464,7 +481,8 @@ for (var i = 0; i < this.languages.enabled.length; i++) { var languageState = this.languages.enabled[i]; - this.set('languages.enabled.' + i + '.removable', + this.set( + 'languages.enabled.' + i + '.removable', this.canDisableLanguage(languageState.language.code)); } }, @@ -489,7 +507,7 @@ return this.resolver_.promise; }, -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't affect * the actual UI language until a restart. @@ -507,7 +525,7 @@ return this.originalProspectiveUILanguage_ != this.languages.prospectiveUILanguage; }, -// </if> + // </if> /** * @param {string} languageCode @@ -547,8 +565,8 @@ var inputMethods = this.languageInputMethods_.get(languageCode) || []; for (var i = 0; i < inputMethods.length; i++) { var inputMethod = inputMethods[i]; - var supportsOtherEnabledLanguages = inputMethod.languageCodes.some( - function(otherLanguageCode) { + var supportsOtherEnabledLanguages = + inputMethod.languageCodes.some(function(otherLanguageCode) { return otherLanguageCode != languageCode && this.isLanguageEnabled(otherLanguageCode); }.bind(this)); @@ -580,8 +598,8 @@ // If this is the only enabled language that is supported by all enabled // component IMEs, it cannot be disabled because we need those IMEs. - var otherInputMethodsEnabled = this.languages.enabled.some( - function(languageState) { + var otherInputMethodsEnabled = + this.languages.enabled.some(function(languageState) { var otherLanguageCode = languageState.language.code; if (otherLanguageCode == languageCode) return false; @@ -664,7 +682,8 @@ * @param {string} languageCode */ disableTranslateLanguage: function(languageCode) { - this.appendPrefListItem('translate_blocked_languages', + this.appendPrefListItem( + 'translate_blocked_languages', this.convertLanguageCodeForTranslate(languageCode)); }, @@ -733,7 +752,7 @@ return this.supportedLanguageMap_.get(languageCode); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @param {string} id */ addInputMethod: function(id) { if (!this.supportedInputMethodMap_.has(id)) @@ -788,6 +807,6 @@ onInputMethodRemoved_: function(id) { this.updateEnabledInputMethods_(); }, -// </if> + // </if> }); })();
diff --git a/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js b/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js index a36bb2e5..5edc03f 100644 --- a/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js +++ b/chrome/browser/resources/settings/languages_page/languages_browser_proxy.js
@@ -12,7 +12,7 @@ function LanguagesBrowserProxy() {} LanguagesBrowserProxy.prototype = { -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't * affect the actual UI language until a restart. @@ -22,15 +22,15 @@ /** @return {!Promise<string>} */ getProspectiveUILanguage: function() {}, -// </if> + // </if> /** @return {!LanguageSettingsPrivate} */ getLanguageSettingsPrivate: function() {}, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @return {!InputMethodPrivate} */ getInputMethodPrivate: function() {}, -// </if> + // </if> }; /** @@ -43,7 +43,7 @@ cr.addSingletonGetter(LanguagesBrowserProxyImpl); LanguagesBrowserProxyImpl.prototype = { -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** @override */ setProspectiveUILanguage: function(languageCode) { chrome.send('setProspectiveUILanguage', [languageCode]); @@ -53,7 +53,7 @@ getProspectiveUILanguage: function() { return cr.sendWithPromise('getProspectiveUILanguage'); }, -// </if> + // </if> /** @override */ getLanguageSettingsPrivate: function() { @@ -61,12 +61,12 @@ chrome.languageSettingsPrivate); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @override */ getInputMethodPrivate: function() { return /** @type {!InputMethodPrivate} */ (chrome.inputMethodPrivate); }, -// </if> + // </if> }; return {
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.js b/chrome/browser/resources/settings/languages_page/languages_page.js index c321be82..0678644 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.js +++ b/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -42,14 +42,14 @@ /** @type {!LanguageHelper} */ languageHelper: Object, -// <if expr="not is_macosx"> + // <if expr="not is_macosx"> /** @private */ spellCheckSecondaryText_: { type: String, value: '', computed: 'getSpellCheckSecondaryText_(languages.enabled.*)', }, -// </if> + // </if> /** * The language to display the details for. @@ -66,16 +66,16 @@ type: Object, value: function() { var map = new Map(); -// <if expr="not is_macosx"> + // <if expr="not is_macosx"> map.set( settings.Route.EDIT_DICTIONARY.path, '#spellCheckCollapse .subpage-arrow'); -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> map.set( settings.Route.INPUT_METHODS.path, '#inputMethodsCollapse .subpage-arrow'); -// </if> + // </if> return map; }, }, @@ -123,7 +123,7 @@ // "Move up" is a no-op for the top language, and redundant with // "Move to top" for the 2nd language. return !this.isNthLanguage_(0, language) && - !this.isNthLanguage_(1, language); + !this.isNthLanguage_(1, language); }, /** @@ -144,7 +144,7 @@ return this.languages.enabled.length <= 1; }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * Applies Chrome OS session tweaks to the menu. * @param {!CrActionMenuElement} menu @@ -202,9 +202,9 @@ onInputMethodOptionsTap_: function(e) { this.languageHelper.openInputMethodOptions(e.model.item.id); }, -// </if> + // </if> -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * @return {boolean} True for a secondary user in a multi-profile session. * @private @@ -264,7 +264,7 @@ this.closeMenuSoon_(); }, -// </if> + // </if> /** * @param {!chrome.languageSettingsPrivate.Language} language @@ -313,7 +313,7 @@ * @private */ onMoveToTopTap_: function() { - /** @type {!CrActionMenuElement} */(this.$.menu.get()).close(); + /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close(); this.languageHelper.moveLanguageToFront(this.detailLanguage_.language.code); }, @@ -322,7 +322,7 @@ * @private */ onMoveUpTap_: function() { - /** @type {!CrActionMenuElement} */(this.$.menu.get()).close(); + /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close(); this.languageHelper.moveLanguage(this.detailLanguage_.language.code, -1); }, @@ -331,7 +331,7 @@ * @private */ onMoveDownTap_: function() { - /** @type {!CrActionMenuElement} */(this.$.menu.get()).close(); + /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close(); this.languageHelper.moveLanguage(this.detailLanguage_.language.code, 1); }, @@ -340,11 +340,11 @@ * @private */ onRemoveLanguageTap_: function() { - /** @type {!CrActionMenuElement} */(this.$.menu.get()).close(); + /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close(); this.languageHelper.disableLanguage(this.detailLanguage_.language.code); }, -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * Checks whether the prospective UI language (the pref that indicates what * language to use in Chrome) matches the current language. This pref is used @@ -359,15 +359,15 @@ return languageCode == prospectiveUILanguage; }, - /** - * @param {string} prospectiveUILanguage - * @return {string} - * @private - */ + /** + * @param {string} prospectiveUILanguage + * @return {string} + * @private + */ getProspectiveUILanguageName_: function(prospectiveUILanguage) { return this.languageHelper.getLanguage(prospectiveUILanguage).displayName; }, -// </if> + // </if> /** * @return {string} @@ -377,7 +377,7 @@ return cr.isChromeOS || cr.isWindows ? 'two-line' : ''; }, -// <if expr="not is_macosx"> + // <if expr="not is_macosx"> /** * Returns the secondary text for the spell check subsection based on the * enabled spell check languages, listing at most 2 languages. @@ -388,7 +388,7 @@ var enabledSpellCheckLanguages = this.languages.enabled.filter(function(languageState) { return languageState.spellCheckEnabled && - languageState.language.supportsSpellcheck; + languageState.language.supportsSpellcheck; }); switch (enabledSpellCheckLanguages.length) { case 0: @@ -433,8 +433,8 @@ if (!item.language.supportsSpellcheck) return; - this.languageHelper.toggleSpellCheck(item.language.code, - !item.spellCheckEnabled); + this.languageHelper.toggleSpellCheck( + item.language.code, !item.spellCheckEnabled); }, /** @@ -444,7 +444,7 @@ getSpellCheckListTwoLine_: function() { return this.spellCheckSecondaryText_.length ? 'two-line' : ''; }, -// </if> + // </if> /** * Returns either the "selected" class, if the language matches the @@ -463,7 +463,7 @@ return ''; }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @param {string} id The input method ID. * @param {string} currentId The ID of the currently enabled input method. @@ -488,13 +488,13 @@ getInputMethodName_: function(id) { assert(cr.isChromeOS); - var inputMethod = this.languages.inputMethods.enabled.find( - function(inputMethod) { + var inputMethod = + this.languages.inputMethods.enabled.find(function(inputMethod) { return inputMethod.id == id; }); return inputMethod ? inputMethod.displayName : ''; }, -// </if> + // </if> /** * @param {!Event} e @@ -503,18 +503,17 @@ onDotsTap_: function(e) { // Set a copy of the LanguageState object since it is not data-bound to the // languages model directly. - this.detailLanguage_ = /** @type {!LanguageState} */(Object.assign( + this.detailLanguage_ = /** @type {!LanguageState} */ (Object.assign( {}, - /** @type {!{model: !{item: !LanguageState}}} */(e).model.item)); + /** @type {!{model: !{item: !LanguageState}}} */ (e).model.item)); // Ensure the template has been stamped. - var menu = /** @type {?CrActionMenuElement} */( - this.$.menu.getIfExists()); + var menu = /** @type {?CrActionMenuElement} */ (this.$.menu.getIfExists()); if (!menu) { - menu = /** @type {!CrActionMenuElement} */(this.$.menu.get()); -// <if expr="chromeos"> + menu = /** @type {!CrActionMenuElement} */ (this.$.menu.get()); + // <if expr="chromeos"> this.tweakMenuForCrOS_(menu); -// </if> + // </if> } menu.showAt(/** @type {!Element} */ (e.target)); @@ -526,27 +525,27 @@ * @private */ closeMenuSoon_: function() { - var menu = /** @type {!CrActionMenuElement} */(this.$.menu.get()); + var menu = /** @type {!CrActionMenuElement} */ (this.$.menu.get()); setTimeout(function() { if (menu.open) menu.close(); }, settings.kMenuCloseDelay); }, -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * Handler for the restart button. * @private */ onRestartTap_: function() { -// <if expr="chromeos"> + // <if expr="chromeos"> settings.LifetimeBrowserProxyImpl.getInstance().signOutAndRestart(); -// </if> -// <if expr="is_win"> + // </if> + // <if expr="is_win"> settings.LifetimeBrowserProxyImpl.getInstance().restart(); -// </if> + // </if> }, -// </if> + // </if> /** * Toggles the expand button within the element being listened to.
diff --git a/chrome/browser/resources/settings/languages_page/languages_types.js b/chrome/browser/resources/settings/languages_page/languages_types.js index 36d446f..af76c64 100644 --- a/chrome/browser/resources/settings/languages_page/languages_types.js +++ b/chrome/browser/resources/settings/languages_page/languages_types.js
@@ -64,7 +64,7 @@ /** @return {!Promise} */ whenReady: assertNotReached, -// <if expr="chromeos or is_win"> + // <if expr="chromeos or is_win"> /** * Sets the prospective UI language to the chosen language. This won't affect * the actual UI language until a restart. @@ -77,7 +77,7 @@ * @return {boolean} */ requiresRestart: assertNotReached, -// </if> + // </if> /** * @param {string} languageCode @@ -161,7 +161,7 @@ */ getLanguage: assertNotReached, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @param {string} id */ addInputMethod: assertNotReached, @@ -185,5 +185,5 @@ /** @param {string} id Input method ID. */ openInputMethodOptions: assertNotReached, -// </if> + // </if> };
diff --git a/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js b/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js index 92d1223..8e86803 100644 --- a/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js +++ b/chrome/browser/resources/settings/languages_page/manage_input_methods_page.js
@@ -32,7 +32,9 @@ */ languageList_: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, }, @@ -164,8 +166,8 @@ /** @type {!Array<chrome.languageSettingsPrivate.InputMethod>} */ var combinedInputMethods = []; for (var i = 0; i < languageCodes.length; i++) { - var inputMethods = this.languageHelper.getInputMethodsForLanguage( - languageCodes[i]); + var inputMethods = + this.languageHelper.getInputMethodsForLanguage(languageCodes[i]); // Get the language's unused input methods and mark them as used. var newInputMethods = inputMethods.filter(function(inputMethod) { if (usedInputMethods.has(inputMethod.id))
diff --git a/chrome/browser/resources/settings/lifetime_browser_proxy.js b/chrome/browser/resources/settings/lifetime_browser_proxy.js index 0e7750f..b9915c0 100644 --- a/chrome/browser/resources/settings/lifetime_browser_proxy.js +++ b/chrome/browser/resources/settings/lifetime_browser_proxy.js
@@ -13,13 +13,13 @@ // Triggers a browser relaunch. relaunch: function() {}, -// <if expr="chromeos"> + // <if expr="chromeos"> // First signs out current user and then performs a restart. signOutAndRestart: function() {}, // Triggers a factory reset. factoryReset: function() {}, -// </if> + // </if> }; /** @@ -40,7 +40,7 @@ chrome.send('relaunch'); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @override */ signOutAndRestart: function() { chrome.send('signOutAndRestart'); @@ -50,7 +50,7 @@ factoryReset: function() { chrome.send('factoryReset'); }, -// </if> + // </if> }; return {
diff --git a/chrome/browser/resources/settings/on_startup_page/on_startup_page.js b/chrome/browser/resources/settings/on_startup_page/on_startup_page.js index 313c415..c02d05c 100644 --- a/chrome/browser/resources/settings/on_startup_page/on_startup_page.js +++ b/chrome/browser/resources/settings/on_startup_page/on_startup_page.js
@@ -65,11 +65,11 @@ }, /** - * Determine whether to show the user defined startup pages. - * @param {number} restoreOnStartup Enum value from prefValues_. - * @return {boolean} Whether the open specific pages is selected. - * @private - */ + * Determine whether to show the user defined startup pages. + * @param {number} restoreOnStartup Enum value from prefValues_. + * @return {boolean} Whether the open specific pages is selected. + * @private + */ showStartupUrls_: function(restoreOnStartup) { return restoreOnStartup == this.prefValues_.OPEN_SPECIFIC; },
diff --git a/chrome/browser/resources/settings/on_startup_page/startup_url_entry.js b/chrome/browser/resources/settings/on_startup_page/startup_url_entry.js index 2c58202..e5bd08b 100644 --- a/chrome/browser/resources/settings/on_startup_page/startup_url_entry.js +++ b/chrome/browser/resources/settings/on_startup_page/startup_url_entry.js
@@ -63,8 +63,8 @@ /** @private */ onDotsTap_: function() { - var actionMenu = /** @type {!CrActionMenuElement} */( - this.$$('#menu').get()); + var actionMenu = + /** @type {!CrActionMenuElement} */ (this.$$('#menu').get()); actionMenu.showAt(assert(this.$$('#dots'))); }, });
diff --git a/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js b/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js index 1a0b376..fbc43d3 100644 --- a/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js +++ b/chrome/browser/resources/settings/on_startup_page/startup_urls_page.js
@@ -68,8 +68,8 @@ onAddPageTap_: function(e) { e.preventDefault(); this.showStartupUrlDialog_ = true; - this.startupUrlDialogAnchor_ = /** @type {!HTMLElement} */ ( - this.$$('#addPage a[is=action-link]')); + this.startupUrlDialogAnchor_ = + /** @type {!HTMLElement} */ (this.$$('#addPage a[is=action-link]')); }, /** @private */
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js b/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js index 06e84498..ca28ebf 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js
@@ -50,8 +50,7 @@ /** @override */ attached: function() { - this.countryInfo = - settings.address.CountryDetailManagerImpl.getInstance(); + this.countryInfo = settings.address.CountryDetailManagerImpl.getInstance(); this.countryInfo.getCountryList().then(function(countryList) { this.countries_ = countryList; @@ -106,7 +105,7 @@ this.fire('on-update-address-wrapper'); // For easier testing. - var dialog = /** @type {HTMLDialogElement} */(this.$.dialog); + var dialog = /** @type {HTMLDialogElement} */ (this.$.dialog); if (!dialog.open) dialog.showModal(); }.bind(this));
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js index 3cfa710..0a7dff7 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js
@@ -146,325 +146,325 @@ }; (function() { - 'use strict'; +'use strict'; - Polymer({ - is: 'settings-autofill-section', +Polymer({ + is: 'settings-autofill-section', - behaviors: [I18nBehavior], + behaviors: [I18nBehavior], - properties: { - /** - * An array of saved addresses. - * @type {!Array<!AutofillManager.AddressEntry>} - */ - addresses: Array, - - /** - * The model for any address related action menus or dialogs. - * @private {?chrome.autofillPrivate.AddressEntry} - */ - activeAddress: Object, - - /** @private */ - showAddressDialog_: Boolean, - - /** - * An array of saved credit cards. - * @type {!Array<!AutofillManager.CreditCardEntry>} - */ - creditCards: Array, - - /** - * The model for any credit card related action menus or dialogs. - * @private {?chrome.autofillPrivate.CreditCardEntry} - */ - activeCreditCard: Object, - - /** @private */ - showCreditCardDialog_: Boolean, - }, - - listeners: { - 'save-address': 'saveAddress_', - 'save-credit-card': 'saveCreditCard_', - }, + properties: { + /** + * An array of saved addresses. + * @type {!Array<!AutofillManager.AddressEntry>} + */ + addresses: Array, /** - * The element to return focus to, when the currently active dialog is - * closed. - * @private {?HTMLElement} + * The model for any address related action menus or dialogs. + * @private {?chrome.autofillPrivate.AddressEntry} */ - activeDialogAnchor_: null, - - /** - * @type {AutofillManager} - * @private - */ - autofillManager_: null, - - /** - * @type {?function(!Array<!AutofillManager.AddressEntry>)} - * @private - */ - setAddressesListener_: null, - - /** - * @type {?function(!Array<!AutofillManager.CreditCardEntry>)} - * @private - */ - setCreditCardsListener_: null, - - /** @override */ - attached: function() { - // Create listener functions. - /** @type {function(!Array<!AutofillManager.AddressEntry>)} */ - var setAddressesListener = function(list) { - this.addresses = list; - }.bind(this); - - /** @type {function(!Array<!AutofillManager.CreditCardEntry>)} */ - var setCreditCardsListener = function(list) { - this.creditCards = list; - }.bind(this); - - // Remember the bound reference in order to detach. - this.setAddressesListener_ = setAddressesListener; - this.setCreditCardsListener_ = setCreditCardsListener; - - // Set the managers. These can be overridden by tests. - this.autofillManager_ = AutofillManagerImpl.getInstance(); - - // Request initial data. - this.autofillManager_.getAddressList(setAddressesListener); - this.autofillManager_.getCreditCardList(setCreditCardsListener); - - // Listen for changes. - this.autofillManager_.addAddressListChangedListener(setAddressesListener); - this.autofillManager_.addCreditCardListChangedListener( - setCreditCardsListener); - }, - - /** @override */ - detached: function() { - this.autofillManager_.removeAddressListChangedListener( - /** @type {function(!Array<!AutofillManager.AddressEntry>)} */( - this.setAddressesListener_)); - this.autofillManager_.removeCreditCardListChangedListener( - /** @type {function(!Array<!AutofillManager.CreditCardEntry>)} */( - this.setCreditCardsListener_)); - }, - - /** - * Formats the expiration date so it's displayed as MM/YYYY. - * @param {!chrome.autofillPrivate.CreditCardEntry} item - * @return {string} - * @private - */ - expiration_: function(item) { - return item.expirationMonth + '/' + item.expirationYear; - }, - - /** - * Open the address action menu. - * @param {!Event} e The polymer event. - * @private - */ - onAddressMenuTap_: function(e) { - var menuEvent = /** @type {!{model: !{item: !Object}}} */(e); - - /* TODO(scottchen): drop the [dataHost][dataHost] once this bug is fixed: - https://github.com/Polymer/polymer/issues/2574 */ - var item = menuEvent.model['dataHost']['dataHost'].item; - - // Copy item so dialog won't update model on cancel. - this.activeAddress = /** @type {!chrome.autofillPrivate.AddressEntry} */( - Object.assign({}, item)); - - var dotsButton = /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget); - /** @type {!CrActionMenuElement} */ ( - this.$.addressSharedMenu).showAt(dotsButton); - this.activeDialogAnchor_ = dotsButton; - }, - - /** - * Handles tapping on the "Add address" button. - * @param {!Event} e The polymer event. - * @private - */ - onAddAddressTap_: function(e) { - e.preventDefault(); - this.activeAddress = {}; - this.showAddressDialog_ = true; - this.activeDialogAnchor_ = this.$.addAddress; - }, + activeAddress: Object, /** @private */ - onAddressDialogClosed_: function() { - this.showAddressDialog_ = false; - cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); - this.activeDialogAnchor_ = null; - }, + showAddressDialog_: Boolean, /** - * Handles tapping on the "Edit" address button. - * @param {!Event} e The polymer event. - * @private + * An array of saved credit cards. + * @type {!Array<!AutofillManager.CreditCardEntry>} */ - onMenuEditAddressTap_: function(e) { - e.preventDefault(); - this.showAddressDialog_ = true; - this.$.addressSharedMenu.close(); - }, + creditCards: Array, + + /** + * The model for any credit card related action menus or dialogs. + * @private {?chrome.autofillPrivate.CreditCardEntry} + */ + activeCreditCard: Object, /** @private */ - onRemoteEditAddressTap_: function() { - window.open(this.i18n('manageAddressesUrl')); - }, + showCreditCardDialog_: Boolean, + }, - /** - * Handles tapping on the "Remove" address button. - * @private - */ - onMenuRemoveAddressTap_: function() { - this.autofillManager_.removeAddress( - /** @type {string} */(this.activeAddress.guid)); - this.$.addressSharedMenu.close(); - }, + listeners: { + 'save-address': 'saveAddress_', + 'save-credit-card': 'saveCreditCard_', + }, - /** - * Opens the credit card action menu. - * @param {!Event} e The polymer event. - * @private - */ - onCreditCardMenuTap_: function(e) { - var menuEvent = /** @type {!{model: !{item: !Object}}} */(e); + /** + * The element to return focus to, when the currently active dialog is + * closed. + * @private {?HTMLElement} + */ + activeDialogAnchor_: null, - /* TODO(scottchen): drop the [dataHost][dataHost] once this bug is fixed: - https://github.com/Polymer/polymer/issues/2574 */ - var item = menuEvent.model['dataHost']['dataHost'].item; + /** + * @type {AutofillManager} + * @private + */ + autofillManager_: null, - // Copy item so dialog won't update model on cancel. - this.activeCreditCard = - /** @type {!chrome.autofillPrivate.CreditCardEntry} */( - Object.assign({}, item)); + /** + * @type {?function(!Array<!AutofillManager.AddressEntry>)} + * @private + */ + setAddressesListener_: null, - var dotsButton = /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget); - /** @type {!CrActionMenuElement} */ ( - this.$.creditCardSharedMenu).showAt(dotsButton); - this.activeDialogAnchor_ = dotsButton; - }, + /** + * @type {?function(!Array<!AutofillManager.CreditCardEntry>)} + * @private + */ + setCreditCardsListener_: null, - /** - * Handles tapping on the "Add credit card" button. - * @param {!Event} e - * @private - */ - onAddCreditCardTap_: function(e) { - e.preventDefault(); - var date = new Date(); // Default to current month/year. - var expirationMonth = date.getMonth() + 1; // Months are 0 based. - this.activeCreditCard = { - expirationMonth: expirationMonth.toString(), - expirationYear: date.getFullYear().toString(), - }; + /** @override */ + attached: function() { + // Create listener functions. + /** @type {function(!Array<!AutofillManager.AddressEntry>)} */ + var setAddressesListener = function(list) { + this.addresses = list; + }.bind(this); + + /** @type {function(!Array<!AutofillManager.CreditCardEntry>)} */ + var setCreditCardsListener = function(list) { + this.creditCards = list; + }.bind(this); + + // Remember the bound reference in order to detach. + this.setAddressesListener_ = setAddressesListener; + this.setCreditCardsListener_ = setCreditCardsListener; + + // Set the managers. These can be overridden by tests. + this.autofillManager_ = AutofillManagerImpl.getInstance(); + + // Request initial data. + this.autofillManager_.getAddressList(setAddressesListener); + this.autofillManager_.getCreditCardList(setCreditCardsListener); + + // Listen for changes. + this.autofillManager_.addAddressListChangedListener(setAddressesListener); + this.autofillManager_.addCreditCardListChangedListener( + setCreditCardsListener); + }, + + /** @override */ + detached: function() { + this.autofillManager_.removeAddressListChangedListener( + /** @type {function(!Array<!AutofillManager.AddressEntry>)} */ ( + this.setAddressesListener_)); + this.autofillManager_.removeCreditCardListChangedListener( + /** @type {function(!Array<!AutofillManager.CreditCardEntry>)} */ ( + this.setCreditCardsListener_)); + }, + + /** + * Formats the expiration date so it's displayed as MM/YYYY. + * @param {!chrome.autofillPrivate.CreditCardEntry} item + * @return {string} + * @private + */ + expiration_: function(item) { + return item.expirationMonth + '/' + item.expirationYear; + }, + + /** + * Open the address action menu. + * @param {!Event} e The polymer event. + * @private + */ + onAddressMenuTap_: function(e) { + var menuEvent = /** @type {!{model: !{item: !Object}}} */ (e); + + /* TODO(scottchen): drop the [dataHost][dataHost] once this bug is fixed: + https://github.com/Polymer/polymer/issues/2574 */ + var item = menuEvent.model['dataHost']['dataHost'].item; + + // Copy item so dialog won't update model on cancel. + this.activeAddress = /** @type {!chrome.autofillPrivate.AddressEntry} */ ( + Object.assign({}, item)); + + var dotsButton = /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget); + /** @type {!CrActionMenuElement} */ (this.$.addressSharedMenu) + .showAt(dotsButton); + this.activeDialogAnchor_ = dotsButton; + }, + + /** + * Handles tapping on the "Add address" button. + * @param {!Event} e The polymer event. + * @private + */ + onAddAddressTap_: function(e) { + e.preventDefault(); + this.activeAddress = {}; + this.showAddressDialog_ = true; + this.activeDialogAnchor_ = this.$.addAddress; + }, + + /** @private */ + onAddressDialogClosed_: function() { + this.showAddressDialog_ = false; + cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); + this.activeDialogAnchor_ = null; + }, + + /** + * Handles tapping on the "Edit" address button. + * @param {!Event} e The polymer event. + * @private + */ + onMenuEditAddressTap_: function(e) { + e.preventDefault(); + this.showAddressDialog_ = true; + this.$.addressSharedMenu.close(); + }, + + /** @private */ + onRemoteEditAddressTap_: function() { + window.open(this.i18n('manageAddressesUrl')); + }, + + /** + * Handles tapping on the "Remove" address button. + * @private + */ + onMenuRemoveAddressTap_: function() { + this.autofillManager_.removeAddress( + /** @type {string} */ (this.activeAddress.guid)); + this.$.addressSharedMenu.close(); + }, + + /** + * Opens the credit card action menu. + * @param {!Event} e The polymer event. + * @private + */ + onCreditCardMenuTap_: function(e) { + var menuEvent = /** @type {!{model: !{item: !Object}}} */ (e); + + /* TODO(scottchen): drop the [dataHost][dataHost] once this bug is fixed: + https://github.com/Polymer/polymer/issues/2574 */ + var item = menuEvent.model['dataHost']['dataHost'].item; + + // Copy item so dialog won't update model on cancel. + this.activeCreditCard = + /** @type {!chrome.autofillPrivate.CreditCardEntry} */ ( + Object.assign({}, item)); + + var dotsButton = /** @type {!HTMLElement} */ (Polymer.dom(e).localTarget); + /** @type {!CrActionMenuElement} */ (this.$.creditCardSharedMenu) + .showAt(dotsButton); + this.activeDialogAnchor_ = dotsButton; + }, + + /** + * Handles tapping on the "Add credit card" button. + * @param {!Event} e + * @private + */ + onAddCreditCardTap_: function(e) { + e.preventDefault(); + var date = new Date(); // Default to current month/year. + var expirationMonth = date.getMonth() + 1; // Months are 0 based. + this.activeCreditCard = { + expirationMonth: expirationMonth.toString(), + expirationYear: date.getFullYear().toString(), + }; + this.showCreditCardDialog_ = true; + this.activeDialogAnchor_ = this.$.addCreditCard; + }, + + /** @private */ + onCreditCardDialogClosed_: function() { + this.showCreditCardDialog_ = false; + cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); + this.activeDialogAnchor_ = null; + }, + + /** + * Handles tapping on the "Edit" credit card button. + * @param {!Event} e The polymer event. + * @private + */ + onMenuEditCreditCardTap_: function(e) { + e.preventDefault(); + + if (this.activeCreditCard.metadata.isLocal) this.showCreditCardDialog_ = true; - this.activeDialogAnchor_ = this.$.addCreditCard; - }, + else + this.onRemoteEditCreditCardTap_(); - /** @private */ - onCreditCardDialogClosed_: function() { - this.showCreditCardDialog_ = false; - cr.ui.focusWithoutInk(assert(this.activeDialogAnchor_)); - this.activeDialogAnchor_ = null; - }, + this.$.creditCardSharedMenu.close(); + }, - /** - * Handles tapping on the "Edit" credit card button. - * @param {!Event} e The polymer event. - * @private - */ - onMenuEditCreditCardTap_: function(e) { - e.preventDefault(); + /** @private */ + onRemoteEditCreditCardTap_: function() { + window.open(this.i18n('manageCreditCardsUrl')); + }, - if (this.activeCreditCard.metadata.isLocal) - this.showCreditCardDialog_ = true; - else - this.onRemoteEditCreditCardTap_(); + /** + * Handles tapping on the "Remove" credit card button. + * @private + */ + onMenuRemoveCreditCardTap_: function() { + this.autofillManager_.removeCreditCard( + /** @type {string} */ (this.activeCreditCard.guid)); + this.$.creditCardSharedMenu.close(); + }, - this.$.creditCardSharedMenu.close(); - }, + /** + * Handles tapping on the "Clear copy" button for cached credit cards. + * @private + */ + onMenuClearCreditCardTap_: function() { + this.autofillManager_.clearCachedCreditCard( + /** @type {string} */ (this.activeCreditCard.guid)); + this.$.creditCardSharedMenu.close(); + }, - /** @private */ - onRemoteEditCreditCardTap_: function() { - window.open(this.i18n('manageCreditCardsUrl')); - }, + /** + * The 3-dot menu should not be shown if the card is entirely remote. + * @param {!chrome.autofillPrivate.AutofillMetadata} metadata + * @return {boolean} + * @private + */ + showDots_: function(metadata) { + return !!(metadata.isLocal || metadata.isCached); + }, - /** - * Handles tapping on the "Remove" credit card button. - * @private - */ - onMenuRemoveCreditCardTap_: function() { - this.autofillManager_.removeCreditCard( - /** @type {string} */(this.activeCreditCard.guid)); - this.$.creditCardSharedMenu.close(); - }, + /** + * Returns true if the list exists and has items. + * @param {Array<Object>} list + * @return {boolean} + * @private + */ + hasSome_: function(list) { + return !!(list && list.length); + }, - /** - * Handles tapping on the "Clear copy" button for cached credit cards. - * @private - */ - onMenuClearCreditCardTap_: function() { - this.autofillManager_.clearCachedCreditCard( - /** @type {string} */(this.activeCreditCard.guid)); - this.$.creditCardSharedMenu.close(); - }, + /** + * Listens for the save-address event, and calls the private API. + * @param {!Event} event + * @private + */ + saveAddress_: function(event) { + this.autofillManager_.saveAddress(event.detail); + }, - /** - * The 3-dot menu should not be shown if the card is entirely remote. - * @param {!chrome.autofillPrivate.AutofillMetadata} metadata - * @return {boolean} - * @private - */ - showDots_: function(metadata) { - return !!(metadata.isLocal || metadata.isCached); - }, + /** + * Listens for the save-credit-card event, and calls the private API. + * @param {!Event} event + * @private + */ + saveCreditCard_: function(event) { + this.autofillManager_.saveCreditCard(event.detail); + }, - /** - * Returns true if the list exists and has items. - * @param {Array<Object>} list - * @return {boolean} - * @private - */ - hasSome_: function(list) { - return !!(list && list.length); - }, - - /** - * Listens for the save-address event, and calls the private API. - * @param {!Event} event - * @private - */ - saveAddress_: function(event) { - this.autofillManager_.saveAddress(event.detail); - }, - - /** - * Listens for the save-credit-card event, and calls the private API. - * @param {!Event} event - * @private - */ - saveCreditCard_: function(event) { - this.autofillManager_.saveCreditCard(event.detail); - }, - - /** - * @private - * @param {boolean} toggleValue - * @return {string} - */ - getOnOffLabel_: function(toggleValue) { - return toggleValue ? this.i18n('toggleOn') : this.i18n('toggleOff'); - } - }); + /** + * @private + * @param {boolean} toggleValue + * @return {string} + */ + getOnOffLabel_: function(toggleValue) { + return toggleValue ? this.i18n('toggleOn') : this.i18n('toggleOff'); + } +}); })();
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js b/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js index 9ee7c53e..922c08e 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.js
@@ -34,7 +34,7 @@ monthList_: { type: Array, value: [ - '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', + '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ], }, @@ -61,9 +61,10 @@ */ checkIfCardExpired_: function(expirationMonth_, expirationYear_) { var now = new Date(); - return (expirationYear_ < now.getFullYear() || - (expirationYear_ == now.getFullYear() && - expirationMonth_ <= now.getMonth())); + return ( + expirationYear_ < now.getFullYear() || + (expirationYear_ == now.getFullYear() && + expirationMonth_ <= now.getMonth())); }, /** @override */ @@ -127,8 +128,8 @@ // If the card is expired, reflect the error to the user. // Otherwise, update the card, save and close the dialog. - if (!this.checkIfCardExpired_(this.expirationMonth_, - this.expirationYear_)) { + if (!this.checkIfCardExpired_( + this.expirationMonth_, this.expirationYear_)) { this.creditCard.expirationYear = this.expirationYear_; this.creditCard.expirationMonth = this.expirationMonth_; this.fire('save-credit-card', this.creditCard);
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js index fcbd49b..2cf10b1 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js
@@ -275,11 +275,11 @@ /** @override */ detached: function() { this.passwordManager_.removeSavedPasswordListChangedListener( - /** @type {function(!Array<PasswordManager.PasswordUiEntry>):void} */( - this.setSavedPasswordsListener_)); + /** @type {function(!Array<PasswordManager.PasswordUiEntry>):void} */ ( + this.setSavedPasswordsListener_)); this.passwordManager_.removeExceptionListChangedListener( - /** @type {function(!Array<PasswordManager.ExceptionEntry>):void} */( - this.setPasswordExceptionsListener_)); + /** @type {function(!Array<PasswordManager.ExceptionEntry>):void} */ ( + this.setPasswordExceptionsListener_)); }, /** @@ -302,7 +302,7 @@ */ onMenuEditPasswordTap_: function(e) { e.preventDefault(); - /** @type {CrActionMenuElement} */(this.$.menu).close(); + /** @type {CrActionMenuElement} */ (this.$.menu).close(); this.showPasswordEditDialog_ = true; }, @@ -325,7 +325,7 @@ return savedPasswords.filter(function(password) { return password.loginPair.urls.shown.includes(filter) || - password.loginPair.username.includes(filter); + password.loginPair.username.includes(filter); }); }, @@ -346,7 +346,7 @@ */ onMenuRemovePasswordTap_: function() { this.passwordManager_.removeSavedPassword(this.activePassword.loginPair); - /** @type {CrActionMenuElement} */(this.$.menu).close(); + /** @type {CrActionMenuElement} */ (this.$.menu).close(); }, /** @@ -364,7 +364,7 @@ * @private */ onPasswordMenuTap_: function(event) { - var menu = /** @type {!CrActionMenuElement} */(this.$.menu); + var menu = /** @type {!CrActionMenuElement} */ (this.$.menu); var target = /** @type {!HTMLElement} */ (event.detail.target); this.activePassword = @@ -391,7 +391,7 @@ */ showPassword_: function(event) { this.passwordManager_.getPlaintextPassword( - /** @type {!PasswordManager.LoginPair} */(event.detail), + /** @type {!PasswordManager.LoginPair} */ (event.detail), function(item) { this.setPassword(item.loginPair, item.plaintextPassword); }.bind(this));
diff --git a/chrome/browser/resources/settings/people_page/camera.js b/chrome/browser/resources/settings/people_page/camera.js index ce25918..f8a53b45e 100644 --- a/chrome/browser/resources/settings/people_page/camera.js +++ b/chrome/browser/resources/settings/people_page/camera.js
@@ -13,10 +13,7 @@ * Dimensions for camera capture. * @const */ -var CAPTURE_SIZE = { - height: 480, - width: 480 -}; +var CAPTURE_SIZE = {height: 480, width: 480}; Polymer({ is: 'settings-camera', @@ -153,8 +150,8 @@ this.isFlipped_ = !this.isFlipped_; this.$.userImageStreamCrop.classList.toggle('flip-x', this.isFlipped_); - var flipMessageId = this.isFlipped_ ? - 'photoFlippedAccessibleText' : 'photoFlippedBackAccessibleText'; + var flipMessageId = this.isFlipped_ ? 'photoFlippedAccessibleText' : + 'photoFlippedBackAccessibleText'; announceAccessibleMessage(loadTimeData.getString(flipMessageId)); }, @@ -169,8 +166,8 @@ var width = video.videoWidth; var height = video.videoHeight; if (width < CAPTURE_SIZE.width || height < CAPTURE_SIZE.height) { - console.error('Video capture size too small: ' + - width + 'x' + height + '!'); + console.error( + 'Video capture size too small: ' + width + 'x' + height + '!'); } var src = {}; if (width / CAPTURE_SIZE.width > height / CAPTURE_SIZE.height) { @@ -184,8 +181,9 @@ } src.x = (width - src.width) / 2; src.y = (height - src.height) / 2; - ctx.drawImage(video, src.x, src.y, src.width, src.height, - 0, 0, CAPTURE_SIZE.width, CAPTURE_SIZE.height); + ctx.drawImage( + video, src.x, src.y, src.width, src.height, 0, 0, CAPTURE_SIZE.width, + CAPTURE_SIZE.height); }, /**
diff --git a/chrome/browser/resources/settings/people_page/change_picture.js b/chrome/browser/resources/settings/people_page/change_picture.js index 62c5b9da..f210cbc6a 100644 --- a/chrome/browser/resources/settings/people_page/change_picture.js +++ b/chrome/browser/resources/settings/people_page/change_picture.js
@@ -85,7 +85,9 @@ */ defaultImages_: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @private */ @@ -120,16 +122,16 @@ /** @override */ attached: function() { - this.addWebUIListener('default-images-changed', - this.receiveDefaultImages_.bind(this)); - this.addWebUIListener('selected-image-changed', - this.receiveSelectedImage_.bind(this)); - this.addWebUIListener('old-image-changed', - this.receiveOldImage_.bind(this)); - this.addWebUIListener('profile-image-changed', - this.receiveProfileImage_.bind(this)); - this.addWebUIListener('camera-presence-changed', - this.receiveCameraPresence_.bind(this)); + this.addWebUIListener( + 'default-images-changed', this.receiveDefaultImages_.bind(this)); + this.addWebUIListener( + 'selected-image-changed', this.receiveSelectedImage_.bind(this)); + this.addWebUIListener( + 'old-image-changed', this.receiveOldImage_.bind(this)); + this.addWebUIListener( + 'profile-image-changed', this.receiveProfileImage_.bind(this)); + this.addWebUIListener( + 'camera-presence-changed', this.receiveCameraPresence_.bind(this)); }, @@ -310,11 +312,13 @@ ChangePictureSelectionTypes.CAMERA) { var /** SettingsCameraElement */ camera = this.$.camera; camera.takePhoto(); - } else if (this.selectedItem_.dataset.type == - ChangePictureSelectionTypes.FILE) { + } else if ( + this.selectedItem_.dataset.type == + ChangePictureSelectionTypes.FILE) { this.browserProxy_.chooseFile(); - } else if (this.selectedItem_.dataset.type == - ChangePictureSelectionTypes.OLD) { + } else if ( + this.selectedItem_.dataset.type == + ChangePictureSelectionTypes.OLD) { this.onTapDiscardOldImage_(); } break; @@ -372,7 +376,9 @@ * should be hidden. * @private */ - isOldImageHidden_: function(oldImageUrl) { return oldImageUrl.length == 0; }, + isOldImageHidden_: function(oldImageUrl) { + return oldImageUrl.length == 0; + }, /** * @param {ChangePictureImageElement} selectedItem @@ -431,8 +437,9 @@ if (!this.isAuthorCreditShown_(selectedItem)) return ''; - assert(selectedItem.dataset.defaultImageIndex !== null && - selectedItem.dataset.defaultImageIndex < defaultImages.length); + assert( + selectedItem.dataset.defaultImageIndex !== null && + selectedItem.dataset.defaultImageIndex < defaultImages.length); return defaultImages[selectedItem.dataset.defaultImageIndex].author; }, @@ -447,8 +454,9 @@ if (!this.isAuthorCreditShown_(selectedItem)) return ''; - assert(selectedItem.dataset.defaultImageIndex !== null && - selectedItem.dataset.defaultImageIndex < defaultImages.length); + assert( + selectedItem.dataset.defaultImageIndex !== null && + selectedItem.dataset.defaultImageIndex < defaultImages.length); return defaultImages[selectedItem.dataset.defaultImageIndex].website; }, });
diff --git a/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js b/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js index f63503e8..76d2d69 100644 --- a/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js +++ b/chrome/browser/resources/settings/people_page/easy_unlock_turn_off_dialog.js
@@ -47,9 +47,9 @@ 'easy-unlock-enabled-status', this.handleEasyUnlockEnabledStatusChanged_.bind(this)); - this.addWebUIListener( - 'easy-unlock-turn-off-flow-status', - function(status) { this.status_ = status; }.bind(this)); + this.addWebUIListener('easy-unlock-turn-off-flow-status', function(status) { + this.status_ = status; + }.bind(this)); // Since the dialog text depends on the status, defer opening until we have // retrieved the turn off status to prevent UI flicker.
diff --git a/chrome/browser/resources/settings/people_page/fingerprint_browser_proxy.js b/chrome/browser/resources/settings/people_page/fingerprint_browser_proxy.js index f353f09..09e2f8c0 100644 --- a/chrome/browser/resources/settings/people_page/fingerprint_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/fingerprint_browser_proxy.js
@@ -58,14 +58,14 @@ /** * @return {!Promise<!settings.FingerprintInfo>} */ - getFingerprintsList: function () {}, + getFingerprintsList: function() {}, /** * @return {!Promise<number>} */ - getNumFingerprints: function () {}, + getNumFingerprints: function() {}, - startEnroll: function () {}, + startEnroll: function() {}, cancelCurrentEnroll: function() {}, @@ -109,17 +109,17 @@ FingerprintBrowserProxyImpl.prototype = { /** @override */ - getFingerprintsList: function () { + getFingerprintsList: function() { return cr.sendWithPromise('getFingerprintsList'); }, /** @override */ - getNumFingerprints: function () { + getNumFingerprints: function() { return cr.sendWithPromise('getNumFingerprints'); }, /** @override */ - startEnroll: function () { + startEnroll: function() { chrome.send('startEnroll'); }, @@ -160,7 +160,7 @@ }; return { - FingerprintBrowserProxy : FingerprintBrowserProxy, - FingerprintBrowserProxyImpl : FingerprintBrowserProxyImpl, + FingerprintBrowserProxy: FingerprintBrowserProxy, + FingerprintBrowserProxyImpl: FingerprintBrowserProxyImpl, }; });
diff --git a/chrome/browser/resources/settings/people_page/fingerprint_list.js b/chrome/browser/resources/settings/people_page/fingerprint_list.js index 474bb6c..2fbc3d8 100644 --- a/chrome/browser/resources/settings/people_page/fingerprint_list.js +++ b/chrome/browser/resources/settings/people_page/fingerprint_list.js
@@ -96,9 +96,11 @@ ripple.simulatedRipple(); // Flash the background. - listItem.animate({ - backgroundColor: ['var(--google-grey-300)', 'white'], - }, FLASH_DURATION_MS); + listItem.animate( + { + backgroundColor: ['var(--google-grey-300)', 'white'], + }, + FLASH_DURATION_MS); }); }, @@ -124,11 +126,10 @@ * @private */ onFingerprintDeleteTapped_: function(e) { - this.browserProxy_.removeEnrollment(e.model.index).then( - function(success) { - if (success) - this.updateFingerprintsList_(); - }.bind(this)); + this.browserProxy_.removeEnrollment(e.model.index).then(function(success) { + if (success) + this.updateFingerprintsList_(); + }.bind(this)); }, /** @@ -136,8 +137,8 @@ * @private */ onFingerprintLabelChanged_: function(e) { - this.browserProxy_.changeEnrollmentLabel(e.model.index, e.model.item).then( - function(success) { + this.browserProxy_.changeEnrollmentLabel(e.model.index, e.model.item) + .then(function(success) { if (success) this.updateFingerprintsList_(); }.bind(this));
diff --git a/chrome/browser/resources/settings/people_page/fingerprint_progress_arc.js b/chrome/browser/resources/settings/people_page/fingerprint_progress_arc.js index 0bbf430..a156940 100644 --- a/chrome/browser/resources/settings/people_page/fingerprint_progress_arc.js +++ b/chrome/browser/resources/settings/people_page/fingerprint_progress_arc.js
@@ -77,7 +77,8 @@ var ctx = c.getContext('2d'); ctx.beginPath(); - ctx.arc(c.width / 2, c.height / 2, this.canvasCircleRadius_, startAngle, + ctx.arc( + c.width / 2, c.height / 2, this.canvasCircleRadius_, startAngle, endAngle); ctx.lineWidth = this.canvasCircleStrokeWidth_; ctx.strokeStyle = color; @@ -109,9 +110,10 @@ ctx.shadowOffsetY = 0; ctx.shadowColor = this.canvasCircleShadowColor_; ctx.shadowBlur = blur; - ctx.arc(c.width / 2, c.height / 2, + ctx.arc( + c.width / 2, c.height / 2, this.canvasCircleRadius_ - this.canvasCircleStrokeWidth_ / 2 + blur / 2, - 0, 2*Math.PI); + 0, 2 * Math.PI); ctx.stroke(); ctx.translate(c.width, 0); }, @@ -126,8 +128,8 @@ animate: function(startAngle, endAngle) { var currentAngle = startAngle; // The value to update the angle by each tick. - var step = (endAngle - startAngle) / - (ANIMATE_DURATION_MS / ANIMATE_TICKS_MS); + var step = + (endAngle - startAngle) / (ANIMATE_DURATION_MS / ANIMATE_TICKS_MS); var id = setInterval(doAnimate.bind(this), ANIMATE_TICKS_MS); // Circles on html canvas have 0 radians on the positive x-axis and go in // clockwise direction. We want to start at the top of the circle which is @@ -148,10 +150,10 @@ // |currentAngle| to 7 * Math.PI / 2 (start is 3 * Math.PI / 2) otherwise // the regular draw from |start| to |currentAngle| will draw nothing which // will cause a flicker for one frame. - this.drawArc(start, start + currentAngle, - this.canvasCircleProgressColor_); - this.drawArc(start + currentAngle, - currentAngle <= 0 ? 7 * Math.PI / 2 : start, + this.drawArc( + start, start + currentAngle, this.canvasCircleProgressColor_); + this.drawArc( + start + currentAngle, currentAngle <= 0 ? 7 * Math.PI / 2 : start, this.canvasCircleBackgroundColor_); currentAngle += step; }
diff --git a/chrome/browser/resources/settings/people_page/import_data_dialog.js b/chrome/browser/resources/settings/people_page/import_data_dialog.js index d98afd2b..83099cd0 100644 --- a/chrome/browser/resources/settings/people_page/import_data_dialog.js +++ b/chrome/browser/resources/settings/people_page/import_data_dialog.js
@@ -110,8 +110,8 @@ * @private */ getActionButtonText_: function() { - return this.i18n(this.isImportFromFileSelected_() ? - 'importChooseFile' : 'importCommit'); + return this.i18n( + this.isImportFromFileSelected_() ? 'importChooseFile' : 'importCommit'); }, /** @private */
diff --git a/chrome/browser/resources/settings/people_page/lock_screen.js b/chrome/browser/resources/settings/people_page/lock_screen.js index ac2759d..f5b62a7 100644 --- a/chrome/browser/resources/settings/people_page/lock_screen.js +++ b/chrome/browser/resources/settings/people_page/lock_screen.js
@@ -176,7 +176,8 @@ if (this.shouldAskForPassword_(newRoute)) { this.openPasswordPromptDialog_(); - } else if (newRoute != settings.Route.FINGERPRINT && + } else if ( + newRoute != settings.Route.FINGERPRINT && oldRoute != settings.Route.FINGERPRINT) { // If the user navigated away from the lock screen settings page they will // have to re-enter their password. An exception is if they are navigating @@ -262,8 +263,8 @@ /** @private */ getDescriptionText_: function() { if (this.numFingerprints_ > 0) { - return this.i18n('lockScreenNumberFingerprints', - this.numFingerprints_.toString()); + return this.i18n( + 'lockScreenNumberFingerprints', this.numFingerprints_.toString()); } return this.i18n('lockScreenEditFingerprintsDescription');
diff --git a/chrome/browser/resources/settings/people_page/lock_screen_constants.js b/chrome/browser/resources/settings/people_page/lock_screen_constants.js index 2fc1ad4c..4b33805 100644 --- a/chrome/browser/resources/settings/people_page/lock_screen_constants.js +++ b/chrome/browser/resources/settings/people_page/lock_screen_constants.js
@@ -26,24 +26,22 @@ }; cr.define('settings', function() { -/** - * Helper function to send the progress of the pin setup to be recorded in the - * histogram. - * @param {LockScreenProgress} currentProgress - */ -var recordLockScreenProgress = function(currentProgress) { - if (currentProgress >= LockScreenProgress.MAX_BUCKET) { - console.error('Expected a enumeration value of ' + - LockScreenProgress.MAX_BUCKET + ' or lower: Received ' + - currentProgress + '.'); - return; - } - chrome.send('metricsHandler:recordInHistogram', - [PinUnlockUmaHistogramName, currentProgress, - LockScreenProgress.MAX_BUCKET]); -}; - - return { - recordLockScreenProgress: recordLockScreenProgress + /** + * Helper function to send the progress of the pin setup to be recorded in the + * histogram. + * @param {LockScreenProgress} currentProgress + */ + var recordLockScreenProgress = function(currentProgress) { + if (currentProgress >= LockScreenProgress.MAX_BUCKET) { + console.error( + 'Expected a enumeration value of ' + LockScreenProgress.MAX_BUCKET + + ' or lower: Received ' + currentProgress + '.'); + return; + } + chrome.send('metricsHandler:recordInHistogram', [ + PinUnlockUmaHistogramName, currentProgress, LockScreenProgress.MAX_BUCKET + ]); }; + + return {recordLockScreenProgress: recordLockScreenProgress}; });
diff --git a/chrome/browser/resources/settings/people_page/lock_state_behavior.js b/chrome/browser/resources/settings/people_page/lock_state_behavior.js index 3e5a90c..ac6762b 100644 --- a/chrome/browser/resources/settings/people_page/lock_state_behavior.js +++ b/chrome/browser/resources/settings/people_page/lock_state_behavior.js
@@ -22,11 +22,8 @@ * The currently selected unlock type. * @type {!LockScreenUnlockType} */ - selectedUnlockType: { - type: String, - notify: true, - value: LockScreenUnlockType.VALUE_PENDING - }, + selectedUnlockType: + {type: String, notify: true, value: LockScreenUnlockType.VALUE_PENDING}, /** * True/false if there is a PIN set; undefined if the computation is still @@ -34,19 +31,13 @@ * can change the selectedUnlockType before setting up a PIN. * @type {boolean|undefined} */ - hasPin: { - type: Boolean, - notify: true - }, + hasPin: {type: Boolean, notify: true}, /** * Interface for chrome.quickUnlockPrivate calls. May be overriden by tests. * @private */ - quickUnlockPrivate_: { - type: Object, - value: chrome.quickUnlockPrivate - }, + quickUnlockPrivate_: {type: Object, value: chrome.quickUnlockPrivate}, }, /** @override */
diff --git a/chrome/browser/resources/settings/people_page/password_prompt_dialog.js b/chrome/browser/resources/settings/people_page/password_prompt_dialog.js index 7bbb914f..c9ee712 100644 --- a/chrome/browser/resources/settings/people_page/password_prompt_dialog.js +++ b/chrome/browser/resources/settings/people_page/password_prompt_dialog.js
@@ -27,7 +27,7 @@ (function() { 'use strict'; -/** @const */ var PASSWORD_ACTIVE_DURATION_MS = 10 * 60 * 1000; // Ten minutes. +/** @const */ var PASSWORD_ACTIVE_DURATION_MS = 10 * 60 * 1000; // Ten minutes. Polymer({ is: 'settings-password-prompt-dialog', @@ -156,7 +156,7 @@ } this.clearAccountPasswordTimeout_ = setTimeout( - clearSetModes.bind(this), this.passwordActiveDurationMs_); + clearSetModes.bind(this), this.passwordActiveDurationMs_); // Clear stored password state and close the dialog. this.password_ = '';
diff --git a/chrome/browser/resources/settings/people_page/people_page.js b/chrome/browser/resources/settings/people_page/people_page.js index f08e7c6..88890ad32 100644 --- a/chrome/browser/resources/settings/people_page/people_page.js +++ b/chrome/browser/resources/settings/people_page/people_page.js
@@ -10,12 +10,10 @@ is: 'settings-people-page', behaviors: [ - settings.RouteObserverBehavior, - I18nBehavior, - WebUIListenerBehavior, -// <if expr="chromeos"> + settings.RouteObserverBehavior, I18nBehavior, WebUIListenerBehavior, + // <if expr="chromeos"> LockStateBehavior, -// </if> + // </if> ], properties: { @@ -65,18 +63,18 @@ */ deleteProfile_: Boolean, -// <if expr="not chromeos"> + // <if expr="not chromeos"> /** @private */ showImportDataDialog_: { type: Boolean, value: false, }, -// </if> + // </if> /** @private */ showDisconnectDialog_: Boolean, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * True if fingerprint settings should be displayed on this machine. * @private @@ -88,21 +86,20 @@ }, readOnly: true, }, -// </if> + // </if> /** @private {!Map<string, string>} */ focusConfig_: { type: Object, value: function() { var map = new Map(); - map.set( - settings.Route.SYNC.path, '#sync-status .subpage-arrow'); -// <if expr="not chromeos"> + map.set(settings.Route.SYNC.path, '#sync-status .subpage-arrow'); + // <if expr="not chromeos"> map.set( settings.Route.MANAGE_PROFILE.path, '#picture-subpage-trigger .subpage-arrow'); -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> map.set( settings.Route.CHANGE_PICTURE.path, '#picture-subpage-trigger .subpage-arrow'); @@ -112,7 +109,7 @@ map.set( settings.Route.ACCOUNTS.path, '#manage-other-people-subpage-trigger .subpage-arrow'); -// </if> + // </if> return map; }, }, @@ -125,22 +122,23 @@ attached: function() { var profileInfoProxy = settings.ProfileInfoBrowserProxyImpl.getInstance(); profileInfoProxy.getProfileInfo().then(this.handleProfileInfo_.bind(this)); - this.addWebUIListener('profile-info-changed', - this.handleProfileInfo_.bind(this)); + this.addWebUIListener( + 'profile-info-changed', this.handleProfileInfo_.bind(this)); profileInfoProxy.getProfileManagesSupervisedUsers().then( this.handleProfileManagesSupervisedUsers_.bind(this)); - this.addWebUIListener('profile-manages-supervised-users-changed', - this.handleProfileManagesSupervisedUsers_.bind(this)); + this.addWebUIListener( + 'profile-manages-supervised-users-changed', + this.handleProfileManagesSupervisedUsers_.bind(this)); - this.addWebUIListener('profile-stats-count-ready', - this.handleProfileStatsCount_.bind(this)); + this.addWebUIListener( + 'profile-stats-count-ready', this.handleProfileStatsCount_.bind(this)); this.syncBrowserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); this.syncBrowserProxy_.getSyncStatus().then( this.handleSyncStatus_.bind(this)); - this.addWebUIListener('sync-status-changed', - this.handleSyncStatus_.bind(this)); + this.addWebUIListener( + 'sync-status-changed', this.handleSyncStatus_.bind(this)); }, /** @protected */ @@ -165,7 +163,7 @@ } }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ getPasswordState_: function(hasPin, enableScreenLock) { if (!enableScreenLock) @@ -174,7 +172,7 @@ return this.i18n('lockScreenPinOrPassword'); return this.i18n('lockScreenPasswordOnly'); }, -// </if> + // </if> /** * Handler for when the profile's icon and name is updated. @@ -202,13 +200,15 @@ */ handleProfileStatsCount_: function(count) { this.deleteProfileWarning_ = (count > 0) ? - (count == 1) ? - loadTimeData.getStringF('deleteProfileWarningWithCountsSingular', - this.syncStatus.signedInUsername) : - loadTimeData.getStringF('deleteProfileWarningWithCountsPlural', - count, this.syncStatus.signedInUsername) : - loadTimeData.getStringF('deleteProfileWarningWithoutCounts', - this.syncStatus.signedInUsername); + (count == 1) ? loadTimeData.getStringF( + 'deleteProfileWarningWithCountsSingular', + this.syncStatus.signedInUsername) : + loadTimeData.getStringF( + 'deleteProfileWarningWithCountsPlural', count, + this.syncStatus.signedInUsername) : + loadTimeData.getStringF( + 'deleteProfileWarningWithoutCounts', + this.syncStatus.signedInUsername); }, /** @@ -220,10 +220,10 @@ if (!this.syncStatus && syncStatus && !syncStatus.signedIn) chrome.metricsPrivate.recordUserAction('Signin_Impression_FromSettings'); -// <if expr="not chromeos"> + // <if expr="not chromeos"> if (syncStatus.signedIn) settings.ProfileInfoBrowserProxyImpl.getInstance().getProfileStatsCount(); -// </if> + // </if> if (!syncStatus.signedIn && this.showDisconnectDialog_) this.$$('#disconnectDialog').close(); @@ -233,20 +233,20 @@ /** @private */ onPictureTap_: function() { -// <if expr="chromeos"> + // <if expr="chromeos"> settings.navigateTo(settings.Route.CHANGE_PICTURE); -// </if> -// <if expr="not chromeos"> + // </if> + // <if expr="not chromeos"> settings.navigateTo(settings.Route.MANAGE_PROFILE); -// </if> + // </if> }, -// <if expr="not chromeos"> + // <if expr="not chromeos"> /** @private */ onProfileNameTap_: function() { settings.navigateTo(settings.Route.MANAGE_PROFILE); }, -// </if> + // </if> /** @private */ onSigninTap_: function() { @@ -302,10 +302,10 @@ this.syncBrowserProxy_.startSignIn(); break; case settings.StatusAction.SIGNOUT_AND_SIGNIN: -// <if expr="chromeos"> + // <if expr="chromeos"> this.syncBrowserProxy_.attemptUserExit(); -// </if> -// <if expr="not chromeos"> + // </if> + // <if expr="not chromeos"> if (this.syncStatus.domain) settings.navigateTo(settings.Route.SIGN_OUT); else { @@ -314,7 +314,7 @@ this.syncBrowserProxy_.signOut(false); this.syncBrowserProxy_.startSignIn(); } -// </if> + // </if> break; case settings.StatusAction.UPGRADE_CLIENT: settings.navigateTo(settings.Route.ABOUT); @@ -327,7 +327,7 @@ } }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @param {!Event} e * @private @@ -339,27 +339,26 @@ e.preventDefault(); settings.navigateTo(settings.Route.LOCK_SCREEN); }, -// </if> + // </if> /** @private */ onManageOtherPeople_: function() { -// <if expr="not chromeos"> + // <if expr="not chromeos"> this.syncBrowserProxy_.manageOtherPeople(); -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> settings.navigateTo(settings.Route.ACCOUNTS); -// </if> + // </if> }, -// <if expr="not chromeos"> + // <if expr="not chromeos"> /** * @private * @param {string} domain * @return {string} */ getDomainHtml_: function(domain) { - var innerSpan = - '<span id="managed-by-domain-name">' + domain + '</span>'; + var innerSpan = '<span id="managed-by-domain-name">' + domain + '</span>'; return loadTimeData.getStringF('domainManagedProfile', innerSpan); }, @@ -373,7 +372,7 @@ settings.navigateToPreviousRoute(); cr.ui.focusWithoutInk(assert(this.$.importDataDialogTrigger)); }, -// </if> + // </if> /** * @private @@ -381,13 +380,13 @@ * @return {string} */ getDisconnectExplanationHtml_: function(domain) { -// <if expr="not chromeos"> + // <if expr="not chromeos"> if (domain) { return loadTimeData.getStringF( 'syncDisconnectManagedProfileExplanation', '<span id="managed-by-domain-name">' + domain + '</span>'); } -// </if> + // </if> return loadTimeData.getString('syncDisconnectExplanation'); }, @@ -409,8 +408,9 @@ * error, there is an action associated with it. */ isSyncStatusActionable_: function(syncStatus) { - return !!syncStatus && !syncStatus.managed && (!syncStatus.hasError || - syncStatus.statusAction != settings.StatusAction.NO_ACTION); + return !!syncStatus && !syncStatus.managed && + (!syncStatus.hasError || + syncStatus.statusAction != settings.StatusAction.NO_ACTION); }, /**
diff --git a/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js b/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js index cc58a62..e192289 100644 --- a/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js +++ b/chrome/browser/resources/settings/people_page/setup_fingerprint_dialog.js
@@ -9,9 +9,9 @@ * @enum {number} */ settings.FingerprintSetupStep = { - LOCATE_SCANNER: 1, // The user needs to locate the scanner. - MOVE_FINGER: 2, // The user needs to move finger around the scanner. - READY: 3 // The scanner has read the fingerprint successfully. + LOCATE_SCANNER: 1, // The user needs to locate the scanner. + MOVE_FINGER: 2, // The user needs to move finger around the scanner. + READY: 3 // The scanner has read the fingerprint successfully. }; (function() { @@ -103,7 +103,7 @@ // Note: Reset resets |step_| back to the default, so handle anything that // checks |step_| before resetting. - if(this.step_ == settings.FingerprintSetupStep.READY) + if (this.step_ == settings.FingerprintSetupStep.READY) this.fire('add-fingerprint'); else this.browserProxy_.cancelCurrentEnroll(); @@ -176,7 +176,8 @@ opacity: [0.7, 1.0], }, FLASH_DURATION_MS); - this.$.arc.animate(this.receivedScanCount_ * slice, + this.$.arc.animate( + this.receivedScanCount_ * slice, (this.receivedScanCount_ + 1) * slice); this.receivedScanCount_++; }
diff --git a/chrome/browser/resources/settings/people_page/setup_pin_dialog.js b/chrome/browser/resources/settings/people_page/setup_pin_dialog.js index a2796622..fe2e60e 100644 --- a/chrome/browser/resources/settings/people_page/setup_pin_dialog.js +++ b/chrome/browser/resources/settings/people_page/setup_pin_dialog.js
@@ -26,10 +26,7 @@ }; /** @enum {string} */ -var ProblemType = { - WARNING: 'warning', - ERROR: 'error' -}; +var ProblemType = {WARNING: 'warning', ERROR: 'error'}; Polymer({ is: 'settings-setup-pin-dialog', @@ -75,26 +72,22 @@ */ writeUma_: { type: Object, - value: function() { return settings.recordLockScreenProgress; } + value: function() { + return settings.recordLockScreenProgress; + } }, /** * The current step/subpage we are on. * @private */ - isConfirmStep_: { - type: Boolean, - value: false - }, + isConfirmStep_: {type: Boolean, value: false}, /** * Interface for chrome.quickUnlockPrivate calls. May be overriden by tests. * @private */ - quickUnlockPrivate_: { - type: Object, - value: chrome.quickUnlockPrivate - }, + quickUnlockPrivate_: {type: Object, value: chrome.quickUnlockPrivate}, }, /** @override */ @@ -176,8 +169,8 @@ this.processPinRequirements_.bind(this, messageId)); this.problemClass_ = problemClass; this.updateStyles(); - this.enableSubmit_ = problemClass != ProblemType.ERROR && - messageId != MessageType.MISMATCH; + this.enableSubmit_ = + problemClass != ProblemType.ERROR && messageId != MessageType.MISMATCH; }, /** @private */ @@ -201,7 +194,8 @@ } if (message.warnings.length) { - assert(message.warnings[0] == + assert( + message.warnings[0] == chrome.quickUnlockPrivate.CredentialProblem.TOO_WEAK); this.showProblem_(MessageType.TOO_WEAK, ProblemType.WARNING); } @@ -231,8 +225,7 @@ if (this.pinKeyboardValue_) { this.quickUnlockPrivate_.checkCredential( chrome.quickUnlockPrivate.QuickUnlockMode.PIN, - this.pinKeyboardValue_, - this.processPinProblems_.bind(this)); + this.pinKeyboardValue_, this.processPinProblems_.bind(this)); } return; } @@ -276,10 +269,8 @@ } this.setModes.call( - null, - [chrome.quickUnlockPrivate.QuickUnlockMode.PIN], - [this.pinKeyboardValue_], - onSetModesCompleted.bind(this)); + null, [chrome.quickUnlockPrivate.QuickUnlockMode.PIN], + [this.pinKeyboardValue_], onSetModesCompleted.bind(this)); this.writeUma_(LockScreenProgress.CONFIRM_PIN); }, @@ -299,8 +290,9 @@ * @return {string} */ getTitleMessage_: function(isConfirmStep) { - return this.i18n(isConfirmStep ? 'configurePinConfirmPinTitle' : - 'configurePinChoosePinTitle'); + return this.i18n( + isConfirmStep ? 'configurePinConfirmPinTitle' : + 'configurePinChoosePinTitle'); }, /**
diff --git a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js index 252ed1d2..648d22f 100644 --- a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js
@@ -108,7 +108,7 @@ function SyncBrowserProxy() {} SyncBrowserProxy.prototype = { -// <if expr="not chromeos"> + // <if expr="not chromeos"> /** * Starts the signin process for the user. Does nothing if the user is * already signed in. @@ -125,14 +125,14 @@ * Opens the multi-profile user manager. */ manageOtherPeople: function() {}, -// </if> + // </if> -// <if expr="chromeos"> + // <if expr="chromeos"> /** * Signs the user out. */ attemptUserExit: function() {}, -// </if> + // </if> /** * Gets the current sync status. @@ -181,7 +181,7 @@ cr.addSingletonGetter(SyncBrowserProxyImpl); SyncBrowserProxyImpl.prototype = { -// <if expr="not chromeos"> + // <if expr="not chromeos"> /** @override */ startSignIn: function() { chrome.send('SyncSetupStartSignIn'); @@ -196,13 +196,13 @@ manageOtherPeople: function() { chrome.send('SyncSetupManageOtherPeople'); }, -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> /** @override */ attemptUserExit: function() { return chrome.send('AttemptUserExit'); }, -// </if> + // </if> /** @override */ getSyncStatus: function() { @@ -221,14 +221,14 @@ /** @override */ setSyncDatatypes: function(syncPrefs) { - return cr.sendWithPromise('SyncSetupSetDatatypes', - JSON.stringify(syncPrefs)); + return cr.sendWithPromise( + 'SyncSetupSetDatatypes', JSON.stringify(syncPrefs)); }, /** @override */ setSyncEncryption: function(syncPrefs) { - return cr.sendWithPromise('SyncSetupSetEncryption', - JSON.stringify(syncPrefs)); + return cr.sendWithPromise( + 'SyncSetupSetEncryption', JSON.stringify(syncPrefs)); }, /** @override */
diff --git a/chrome/browser/resources/settings/people_page/sync_page.js b/chrome/browser/resources/settings/people_page/sync_page.js index f404436..35c3b47 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.js +++ b/chrome/browser/resources/settings/people_page/sync_page.js
@@ -135,10 +135,10 @@ /** @override */ attached: function() { - this.addWebUIListener('page-status-changed', - this.handlePageStatusChanged_.bind(this)); - this.addWebUIListener('sync-prefs-changed', - this.handleSyncPrefsChanged_.bind(this)); + this.addWebUIListener( + 'page-status-changed', this.handlePageStatusChanged_.bind(this)); + this.addWebUIListener( + 'sync-prefs-changed', this.handleSyncPrefsChanged_.bind(this)); if (settings.getCurrentRoute() == settings.Route.SYNC) this.onNavigateToPage_(); @@ -260,8 +260,8 @@ */ onSingleSyncDataTypeChanged_: function() { assert(this.syncPrefs); - this.browserProxy_.setSyncDatatypes(this.syncPrefs).then( - this.handlePageStatusChanged_.bind(this)); + this.browserProxy_.setSyncDatatypes(this.syncPrefs) + .then(this.handlePageStatusChanged_.bind(this)); }, /** @private */ @@ -274,8 +274,8 @@ * @private */ onAutofillDataTypeChanged_: function() { - this.set('syncPrefs.paymentsIntegrationEnabled', - this.syncPrefs.autofillSynced); + this.set( + 'syncPrefs.paymentsIntegrationEnabled', this.syncPrefs.autofillSynced); this.onSingleSyncDataTypeChanged_(); }, @@ -313,8 +313,8 @@ this.syncPrefs.setNewPassphrase = true; this.syncPrefs.passphrase = this.passphrase_; - this.browserProxy_.setSyncEncryption(this.syncPrefs).then( - this.handlePageStatusChanged_.bind(this)); + this.browserProxy_.setSyncEncryption(this.syncPrefs) + .then(this.handlePageStatusChanged_.bind(this)); }, /** @@ -333,8 +333,8 @@ this.syncPrefs.passphrase = this.existingPassphrase_; this.existingPassphrase_ = ''; - this.browserProxy_.setSyncEncryption(this.syncPrefs).then( - this.handlePageStatusChanged_.bind(this)); + this.browserProxy_.setSyncEncryption(this.syncPrefs) + .then(this.handlePageStatusChanged_.bind(this)); }, /** @@ -354,8 +354,8 @@ settings.navigateTo(settings.Route.PEOPLE); return; case settings.PageStatus.PASSPHRASE_FAILED: - if (this.pageStatus_ == this.pages_.CONFIGURE && - this.syncPrefs && this.syncPrefs.passphraseRequired) { + if (this.pageStatus_ == this.pages_.CONFIGURE && this.syncPrefs && + this.syncPrefs.passphraseRequired) { this.$$('#existingPassphraseInput').invalid = true; } return;
diff --git a/chrome/browser/resources/settings/people_page/users_add_user_dialog.js b/chrome/browser/resources/settings/people_page/users_add_user_dialog.js index 99b27488..0c0dd69 100644 --- a/chrome/browser/resources/settings/people_page/users_add_user_dialog.js +++ b/chrome/browser/resources/settings/people_page/users_add_user_dialog.js
@@ -16,8 +16,8 @@ * e.g. 'john' * @const {!RegExp} */ -var NAME_ONLY_REGEX = new RegExp( - '^\\s*([\\w\\.!#\\$%&\'\\*\\+-\\/=\\?\\^`\\{\\|\\}~]+)\\s*$'); +var NAME_ONLY_REGEX = + new RegExp('^\\s*([\\w\\.!#\\$%&\'\\*\\+-\\/=\\?\\^`\\{\\|\\}~]+)\\s*$'); /** * Regular expression for adding a user where the string provided is a full
diff --git a/chrome/browser/resources/settings/prefs/pref_util.js b/chrome/browser/resources/settings/prefs/pref_util.js index d18395e..790f38b 100644 --- a/chrome/browser/resources/settings/prefs/pref_util.js +++ b/chrome/browser/resources/settings/prefs/pref_util.js
@@ -20,8 +20,9 @@ case chrome.settingsPrivate.PrefType.NUMBER: var n = parseInt(value, 10); if (isNaN(n)) { - console.error('Argument to stringToPrefValue for number pref ' + - 'was unparsable: ' + value); + console.error( + 'Argument to stringToPrefValue for number pref ' + + 'was unparsable: ' + value); return undefined; } return n; @@ -45,7 +46,7 @@ return pref.value.toString(); case chrome.settingsPrivate.PrefType.STRING: case chrome.settingsPrivate.PrefType.URL: - return /** @type {string} */(pref.value); + return /** @type {string} */ (pref.value); default: assertNotReached('No conversion from ' + pref.type + ' pref to string'); }
diff --git a/chrome/browser/resources/settings/prefs/prefs.js b/chrome/browser/resources/settings/prefs/prefs.js index 7e96f79..537da2e7 100644 --- a/chrome/browser/resources/settings/prefs/prefs.js +++ b/chrome/browser/resources/settings/prefs/prefs.js
@@ -13,302 +13,304 @@ */ (function() { - 'use strict'; +'use strict'; - /** - * Checks whether two values are recursively equal. Only compares serializable - * data (primitives, serializable arrays and serializable objects). - * @param {*} val1 Value to compare. - * @param {*} val2 Value to compare with val1. - * @return {boolean} True if the values are recursively equal. - */ - function deepEqual(val1, val2) { - if (val1 === val2) - return true; +/** + * Checks whether two values are recursively equal. Only compares serializable + * data (primitives, serializable arrays and serializable objects). + * @param {*} val1 Value to compare. + * @param {*} val2 Value to compare with val1. + * @return {boolean} True if the values are recursively equal. + */ +function deepEqual(val1, val2) { + if (val1 === val2) + return true; - if (Array.isArray(val1) || Array.isArray(val2)) { - if (!Array.isArray(val1) || !Array.isArray(val2)) - return false; - return arraysEqual(/** @type {!Array} */(val1), - /** @type {!Array} */(val2)); - } + if (Array.isArray(val1) || Array.isArray(val2)) { + if (!Array.isArray(val1) || !Array.isArray(val2)) + return false; + return arraysEqual( + /** @type {!Array} */ (val1), + /** @type {!Array} */ (val2)); + } - if (val1 instanceof Object && val2 instanceof Object) - return objectsEqual(val1, val2); + if (val1 instanceof Object && val2 instanceof Object) + return objectsEqual(val1, val2); + return false; +} + +/** + * @param {!Array} arr1 + * @param {!Array} arr2 + * @return {boolean} True if the arrays are recursively equal. + */ +function arraysEqual(arr1, arr2) { + if (arr1.length != arr2.length) return false; - } - /** - * @param {!Array} arr1 - * @param {!Array} arr2 - * @return {boolean} True if the arrays are recursively equal. - */ - function arraysEqual(arr1, arr2) { - if (arr1.length != arr2.length) + for (var i = 0; i < arr1.length; i++) { + if (!deepEqual(arr1[i], arr2[i])) return false; - - for (var i = 0; i < arr1.length; i++) { - if (!deepEqual(arr1[i], arr2[i])) - return false; - } - - return true; } - /** - * @param {!Object} obj1 - * @param {!Object} obj2 - * @return {boolean} True if the objects are recursively equal. - */ - function objectsEqual(obj1, obj2) { - var keys1 = Object.keys(obj1); - var keys2 = Object.keys(obj2); - if (keys1.length != keys2.length) + return true; +} + +/** + * @param {!Object} obj1 + * @param {!Object} obj2 + * @return {boolean} True if the objects are recursively equal. + */ +function objectsEqual(obj1, obj2) { + var keys1 = Object.keys(obj1); + var keys2 = Object.keys(obj2); + if (keys1.length != keys2.length) + return false; + + for (var i = 0; i < keys1.length; i++) { + var key = keys1[i]; + if (!deepEqual(obj1[key], obj2[key])) return false; - - for (var i = 0; i < keys1.length; i++) { - var key = keys1[i]; - if (!deepEqual(obj1[key], obj2[key])) - return false; - } - - return true; } - /** - * Returns a recursive copy of the value. - * @param {*} val Value to copy. Should be a primitive or only contain - * serializable data (primitives, serializable arrays and - * serializable objects). - * @return {*} A deep copy of the value. - */ - function deepCopy(val) { - if (!(val instanceof Object)) - return val; - return Array.isArray(val) ? deepCopyArray(/** @type {!Array} */(val)) : - deepCopyObject(val); + return true; +} + +/** + * Returns a recursive copy of the value. + * @param {*} val Value to copy. Should be a primitive or only contain + * serializable data (primitives, serializable arrays and + * serializable objects). + * @return {*} A deep copy of the value. + */ +function deepCopy(val) { + if (!(val instanceof Object)) + return val; + return Array.isArray(val) ? deepCopyArray(/** @type {!Array} */ (val)) : + deepCopyObject(val); +} + +/** + * @param {!Array} arr + * @return {!Array} Deep copy of the array. + */ +function deepCopyArray(arr) { + var copy = []; + for (var i = 0; i < arr.length; i++) + copy.push(deepCopy(arr[i])); + return copy; +} + +/** + * @param {!Object} obj + * @return {!Object} Deep copy of the object. + */ +function deepCopyObject(obj) { + var copy = {}; + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + copy[key] = deepCopy(obj[key]); } + return copy; +} - /** - * @param {!Array} arr - * @return {!Array} Deep copy of the array. - */ - function deepCopyArray(arr) { - var copy = []; - for (var i = 0; i < arr.length; i++) - copy.push(deepCopy(arr[i])); - return copy; - } +Polymer({ + is: 'settings-prefs', - /** - * @param {!Object} obj - * @return {!Object} Deep copy of the object. - */ - function deepCopyObject(obj) { - var copy = {}; - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - copy[key] = deepCopy(obj[key]); - } - return copy; - } + properties: { + /** + * Object containing all preferences, for use by Polymer controls. + * @type {Object|undefined} + */ + prefs: { + type: Object, + notify: true, + }, - Polymer({ - is: 'settings-prefs', - - properties: { - /** - * Object containing all preferences, for use by Polymer controls. - * @type {Object|undefined} - */ - prefs: { - type: Object, - notify: true, - }, - - /** - * Map of pref keys to values representing the state of the Chrome - * pref store as of the last update from the API. - * @type {Object<*>} - * @private - */ - lastPrefValues_: { - type: Object, - value: function() { return {}; }, + /** + * Map of pref keys to values representing the state of the Chrome + * pref store as of the last update from the API. + * @type {Object<*>} + * @private + */ + lastPrefValues_: { + type: Object, + value: function() { + return {}; }, }, + }, - observers: [ - 'prefsChanged_(prefs.*)', - ], + observers: [ + 'prefsChanged_(prefs.*)', + ], - /** @type {SettingsPrivate} */ - settingsApi_: /** @type {SettingsPrivate} */(chrome.settingsPrivate), + /** @type {SettingsPrivate} */ + settingsApi_: /** @type {SettingsPrivate} */ (chrome.settingsPrivate), - /** @override */ - created: function() { - if (!CrSettingsPrefs.deferInitialization) - this.initialize(); - }, + /** @override */ + created: function() { + if (!CrSettingsPrefs.deferInitialization) + this.initialize(); + }, - /** @override */ - detached: function() { - CrSettingsPrefs.resetForTesting(); - }, + /** @override */ + detached: function() { + CrSettingsPrefs.resetForTesting(); + }, - /** - * @param {SettingsPrivate=} opt_settingsApi SettingsPrivate implementation - * to use (chrome.settingsPrivate by default). - */ - initialize: function(opt_settingsApi) { - // Only initialize once (or after resetForTesting() is called). - if (this.initialized_) - return; - this.initialized_ = true; + /** + * @param {SettingsPrivate=} opt_settingsApi SettingsPrivate implementation + * to use (chrome.settingsPrivate by default). + */ + initialize: function(opt_settingsApi) { + // Only initialize once (or after resetForTesting() is called). + if (this.initialized_) + return; + this.initialized_ = true; - if (opt_settingsApi) - this.settingsApi_ = opt_settingsApi; + if (opt_settingsApi) + this.settingsApi_ = opt_settingsApi; - /** @private {function(!Array<!chrome.settingsPrivate.PrefObject>)} */ - this.boundPrefsChanged_ = this.onSettingsPrivatePrefsChanged_.bind(this); - this.settingsApi_.onPrefsChanged.addListener(this.boundPrefsChanged_); - this.settingsApi_.getAllPrefs( - this.onSettingsPrivatePrefsFetched_.bind(this)); - }, + /** @private {function(!Array<!chrome.settingsPrivate.PrefObject>)} */ + this.boundPrefsChanged_ = this.onSettingsPrivatePrefsChanged_.bind(this); + this.settingsApi_.onPrefsChanged.addListener(this.boundPrefsChanged_); + this.settingsApi_.getAllPrefs( + this.onSettingsPrivatePrefsFetched_.bind(this)); + }, - /** - * @param {!{path: string}} e - * @private - */ - prefsChanged_: function(e) { - // |prefs| can be directly set or unset in tests. - if (!CrSettingsPrefs.isInitialized || e.path == 'prefs') - return; + /** + * @param {!{path: string}} e + * @private + */ + prefsChanged_: function(e) { + // |prefs| can be directly set or unset in tests. + if (!CrSettingsPrefs.isInitialized || e.path == 'prefs') + return; - var key = this.getPrefKeyFromPath_(e.path); - var prefStoreValue = this.lastPrefValues_[key]; + var key = this.getPrefKeyFromPath_(e.path); + var prefStoreValue = this.lastPrefValues_[key]; - var prefObj = /** @type {chrome.settingsPrivate.PrefObject} */( - this.get(key, this.prefs)); + var prefObj = /** @type {chrome.settingsPrivate.PrefObject} */ ( + this.get(key, this.prefs)); - // If settingsPrivate already has this value, ignore it. (Otherwise, - // a change event from settingsPrivate could make us call - // settingsPrivate.setPref and potentially trigger an IPC loop.) - if (!deepEqual(prefStoreValue, prefObj.value)) { - this.settingsApi_.setPref( - key, - prefObj.value, - /* pageId */ '', - /* callback */ this.setPrefCallback_.bind(this, key)); - } - }, + // If settingsPrivate already has this value, ignore it. (Otherwise, + // a change event from settingsPrivate could make us call + // settingsPrivate.setPref and potentially trigger an IPC loop.) + if (!deepEqual(prefStoreValue, prefObj.value)) { + this.settingsApi_.setPref( + key, prefObj.value, + /* pageId */ '', + /* callback */ this.setPrefCallback_.bind(this, key)); + } + }, - /** - * Called when prefs in the underlying Chrome pref store are changed. - * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs - * The prefs that changed. - * @private - */ - onSettingsPrivatePrefsChanged_: function(prefs) { - if (CrSettingsPrefs.isInitialized) - this.updatePrefs_(prefs); - }, - - /** - * Called when prefs are fetched from settingsPrivate. - * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs - * @private - */ - onSettingsPrivatePrefsFetched_: function(prefs) { + /** + * Called when prefs in the underlying Chrome pref store are changed. + * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs + * The prefs that changed. + * @private + */ + onSettingsPrivatePrefsChanged_: function(prefs) { + if (CrSettingsPrefs.isInitialized) this.updatePrefs_(prefs); - CrSettingsPrefs.setInitialized(); - }, + }, - /** - * Checks the result of calling settingsPrivate.setPref. - * @param {string} key The key used in the call to setPref. - * @param {boolean} success True if setting the pref succeeded. - * @private - */ - setPrefCallback_: function(key, success) { - if (!success) - this.refresh(key); - }, + /** + * Called when prefs are fetched from settingsPrivate. + * @param {!Array<!chrome.settingsPrivate.PrefObject>} prefs + * @private + */ + onSettingsPrivatePrefsFetched_: function(prefs) { + this.updatePrefs_(prefs); + CrSettingsPrefs.setInitialized(); + }, - /** - * Get the current pref value from chrome.settingsPrivate to ensure the UI - * stays up to date. - * @param {string} key - */ - refresh: function(key) { - this.settingsApi_.getPref(key, function(pref) { - this.updatePrefs_([pref]); - }.bind(this)); - }, + /** + * Checks the result of calling settingsPrivate.setPref. + * @param {string} key The key used in the call to setPref. + * @param {boolean} success True if setting the pref succeeded. + * @private + */ + setPrefCallback_: function(key, success) { + if (!success) + this.refresh(key); + }, - /** - * Updates the prefs model with the given prefs. - * @param {!Array<!chrome.settingsPrivate.PrefObject>} newPrefs - * @private - */ - updatePrefs_: function(newPrefs) { - // Use the existing prefs object or create it. - var prefs = this.prefs || {}; - newPrefs.forEach(function(newPrefObj) { - // Use the PrefObject from settingsPrivate to create a copy in - // lastPrefValues_ at the pref's key. - this.lastPrefValues_[newPrefObj.key] = deepCopy(newPrefObj.value); + /** + * Get the current pref value from chrome.settingsPrivate to ensure the UI + * stays up to date. + * @param {string} key + */ + refresh: function(key) { + this.settingsApi_.getPref(key, function(pref) { + this.updatePrefs_([pref]); + }.bind(this)); + }, - if (!deepEqual(this.get(newPrefObj.key, prefs), newPrefObj)) { - // Add the pref to |prefs|. - cr.exportPath(newPrefObj.key, newPrefObj, prefs); - // If this.prefs already exists, notify listeners of the change. - if (prefs == this.prefs) - this.notifyPath('prefs.' + newPrefObj.key, newPrefObj); - } - }, this); - if (!this.prefs) - this.prefs = prefs; - }, + /** + * Updates the prefs model with the given prefs. + * @param {!Array<!chrome.settingsPrivate.PrefObject>} newPrefs + * @private + */ + updatePrefs_: function(newPrefs) { + // Use the existing prefs object or create it. + var prefs = this.prefs || {}; + newPrefs.forEach(function(newPrefObj) { + // Use the PrefObject from settingsPrivate to create a copy in + // lastPrefValues_ at the pref's key. + this.lastPrefValues_[newPrefObj.key] = deepCopy(newPrefObj.value); - /** - * Given a 'property-changed' path, returns the key of the preference the - * path refers to. E.g., if the path of the changed property is - * 'prefs.search.suggest_enabled.value', the key of the pref that changed is - * 'search.suggest_enabled'. - * @param {string} path - * @return {string} - * @private - */ - getPrefKeyFromPath_: function(path) { - // Skip the first token, which refers to the member variable (this.prefs). - var parts = path.split('.'); - assert(parts.shift() == 'prefs', "Path doesn't begin with 'prefs'"); - - for (var i = 1; i <= parts.length; i++) { - var key = parts.slice(0, i).join('.'); - // The lastPrefValues_ keys match the pref keys. - if (this.lastPrefValues_.hasOwnProperty(key)) - return key; + if (!deepEqual(this.get(newPrefObj.key, prefs), newPrefObj)) { + // Add the pref to |prefs|. + cr.exportPath(newPrefObj.key, newPrefObj, prefs); + // If this.prefs already exists, notify listeners of the change. + if (prefs == this.prefs) + this.notifyPath('prefs.' + newPrefObj.key, newPrefObj); } - return ''; - }, + }, this); + if (!this.prefs) + this.prefs = prefs; + }, - /** - * Resets the element so it can be re-initialized with a new prefs state. - */ - resetForTesting: function() { - if (!this.initialized_) - return; - this.prefs = undefined; - this.lastPrefValues_ = {}; - this.initialized_ = false; - // Remove the listener added in initialize(). - this.settingsApi_.onPrefsChanged.removeListener(this.boundPrefsChanged_); - this.settingsApi_ = - /** @type {SettingsPrivate} */(chrome.settingsPrivate); - }, - }); + /** + * Given a 'property-changed' path, returns the key of the preference the + * path refers to. E.g., if the path of the changed property is + * 'prefs.search.suggest_enabled.value', the key of the pref that changed is + * 'search.suggest_enabled'. + * @param {string} path + * @return {string} + * @private + */ + getPrefKeyFromPath_: function(path) { + // Skip the first token, which refers to the member variable (this.prefs). + var parts = path.split('.'); + assert(parts.shift() == 'prefs', 'Path doesn\'t begin with \'prefs\''); + + for (var i = 1; i <= parts.length; i++) { + var key = parts.slice(0, i).join('.'); + // The lastPrefValues_ keys match the pref keys. + if (this.lastPrefValues_.hasOwnProperty(key)) + return key; + } + return ''; + }, + + /** + * Resets the element so it can be re-initialized with a new prefs state. + */ + resetForTesting: function() { + if (!this.initialized_) + return; + this.prefs = undefined; + this.lastPrefValues_ = {}; + this.initialized_ = false; + // Remove the listener added in initialize(). + this.settingsApi_.onPrefsChanged.removeListener(this.boundPrefsChanged_); + this.settingsApi_ = + /** @type {SettingsPrivate} */ (chrome.settingsPrivate); + }, +}); })();
diff --git a/chrome/browser/resources/settings/prefs/prefs_behavior.js b/chrome/browser/resources/settings/prefs/prefs_behavior.js index 76a4399..03a1bad 100644 --- a/chrome/browser/resources/settings/prefs/prefs_behavior.js +++ b/chrome/browser/resources/settings/prefs/prefs_behavior.js
@@ -23,7 +23,7 @@ * @protected */ getPref: function(prefPath) { - var pref = /** @type {!chrome.settingsPrivate.PrefObject} */( + var pref = /** @type {!chrome.settingsPrivate.PrefObject} */ ( this.get(prefPath, this.prefs)); assert(typeof pref != 'undefined', 'Pref is missing: ' + prefPath); return pref;
diff --git a/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js b/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js index 52099fa..28c5886 100644 --- a/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js +++ b/chrome/browser/resources/settings/printing_page/cups_add_printer_dialog.js
@@ -78,14 +78,14 @@ /** @override */ ready: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - startDiscoveringPrinters(); - this.addWebUIListener('on-printer-discovered', - this.onPrinterDiscovered_.bind(this)); - this.addWebUIListener('on-printer-discovery-done', - this.onPrinterDiscoveryDone_.bind(this)); - this.addWebUIListener('on-printer-discovery-failed', - this.onPrinterDiscoveryDone_.bind(this)); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .startDiscoveringPrinters(); + this.addWebUIListener( + 'on-printer-discovered', this.onPrinterDiscovered_.bind(this)); + this.addWebUIListener( + 'on-printer-discovery-done', this.onPrinterDiscoveryDone_.bind(this)); + this.addWebUIListener( + 'on-printer-discovery-failed', this.onPrinterDiscoveryDone_.bind(this)); }, /** @@ -111,8 +111,8 @@ /** @private */ stopDiscoveringPrinters_: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - stopDiscoveringPrinters(); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .stopDiscoveringPrinters(); this.discovering_ = false; }, @@ -151,11 +151,7 @@ properties: { /** @type {!CupsPrinterInfo} */ - newPrinter: { - type: Object, - notify: true, - value: getEmptyPrinter_ - }, + newPrinter: {type: Object, notify: true, value: getEmptyPrinter_}, }, /** @private */ @@ -227,9 +223,9 @@ /** @override */ ready: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - getCupsPrinterManufacturersList().then( - this.manufacturerListChanged_.bind(this)); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .getCupsPrinterManufacturersList() + .then(this.manufacturerListChanged_.bind(this)); }, /** @@ -249,8 +245,9 @@ /** @private */ onBrowseFile_: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - getCupsPrinterPPDPath().then(this.printerPPDPathChanged_.bind(this)); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .getCupsPrinterPPDPath() + .then(this.printerPPDPathChanged_.bind(this)); }, /** @@ -307,9 +304,9 @@ * @return {boolean} Whether we have enough information to set up the printer * @private */ - canAddPrinter_: function(printerManufacturer, printerModel, printerPPDPath) { - return !!((printerManufacturer && printerModel) || printerPPDPath); - }, + canAddPrinter_: function(printerManufacturer, printerModel, printerPPDPath) { + return !!((printerManufacturer && printerModel) || printerPPDPath); + }, }); Polymer({ @@ -322,8 +319,8 @@ /** @override */ attached: function() { - this.$.configuringMessage.textContent = loadTimeData.getStringF( - 'printerConfiguringMessage', this.printerName); + this.$.configuringMessage.textContent = + loadTimeData.getStringF('printerConfiguringMessage', this.printerName); }, /** @private */ @@ -406,20 +403,22 @@ /** @private */ openManuallyAddPrinterDialog_: function() { - this.switchDialog_(this.currentDialog_, AddPrinterDialogs.MANUALLY, - 'showManuallyAddDialog_'); + this.switchDialog_( + this.currentDialog_, AddPrinterDialogs.MANUALLY, + 'showManuallyAddDialog_'); }, /** @private */ openDiscoveryPrintersDialog_: function() { - this.switchDialog_(this.currentDialog_, AddPrinterDialogs.DISCOVERY, - 'showDiscoveryDialog_'); + this.switchDialog_( + this.currentDialog_, AddPrinterDialogs.DISCOVERY, + 'showDiscoveryDialog_'); }, /** @private */ addPrinter_: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - addCupsPrinter(this.newPrinter); + settings.CupsPrintersBrowserProxyImpl.getInstance().addCupsPrinter( + this.newPrinter); }, /** @private */ @@ -465,8 +464,7 @@ this.configuringDialogTitle = loadTimeData.getString('addPrintersNearbyTitle'); this.addPrinter_(); - } else if ( - this.previousDialog_ == AddPrinterDialogs.MANUFACTURER) { + } else if (this.previousDialog_ == AddPrinterDialogs.MANUFACTURER) { this.configuringDialogTitle = loadTimeData.getString('addPrintersManuallyTitle'); this.addPrinter_(); @@ -475,10 +473,9 @@ loadTimeData.getString('addPrintersManuallyTitle'); if (this.newPrinter.printerProtocol == 'ipp' || this.newPrinter.printerProtocol == 'ipps') { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - getPrinterInfo(this.newPrinter). - then( - this.onPrinterFound_.bind(this), this.infoFailed_.bind(this)); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .getPrinterInfo(this.newPrinter) + .then(this.onPrinterFound_.bind(this), this.infoFailed_.bind(this)); } else { // Defer the switch until all the elements are drawn. this.async(this.switchToManufacturerDialog_.bind(this)); @@ -488,8 +485,9 @@ /** @private */ openManufacturerModelDialog_: function() { - this.switchDialog_(this.currentDialog_, AddPrinterDialogs.MANUFACTURER, - 'showManufacturerDialog_'); + this.switchDialog_( + this.currentDialog_, AddPrinterDialogs.MANUFACTURER, + 'showManufacturerDialog_'); }, /** @private */
diff --git a/chrome/browser/resources/settings/printing_page/cups_printer_details_page.js b/chrome/browser/resources/settings/printing_page/cups_printer_details_page.js index 5fc53e4..5739857 100644 --- a/chrome/browser/resources/settings/printing_page/cups_printer_details_page.js +++ b/chrome/browser/resources/settings/printing_page/cups_printer_details_page.js
@@ -35,8 +35,8 @@ * @private */ onValueChange_: function() { - this.browserProxy_.updateCupsPrinter(this.printer.printerId, - this.printer.printerName); + this.browserProxy_.updateCupsPrinter( + this.printer.printerId, this.printer.printerName); }, /** @@ -82,12 +82,11 @@ getPrinterURI_: function(printer) { if (!printer) { return ''; - } else if (printer.printerProtocol && - printer.printerAddress && - printer.printerQueue) { - return printer.printerProtocol + '://' + - printer.printerAddress + '/' + - printer.printerQueue; + } else if ( + printer.printerProtocol && printer.printerAddress && + printer.printerQueue) { + return printer.printerProtocol + '://' + printer.printerAddress + '/' + + printer.printerQueue; } else if (printer.printerProtocol && printer.printerAddress) { return printer.printerProtocol + '://' + printer.printerAddress; } else {
diff --git a/chrome/browser/resources/settings/printing_page/cups_printers.js b/chrome/browser/resources/settings/printing_page/cups_printers.js index 95def65..6c114373 100644 --- a/chrome/browser/resources/settings/printing_page/cups_printers.js +++ b/chrome/browser/resources/settings/printing_page/cups_printers.js
@@ -61,8 +61,10 @@ */ refreshNetworks_: function() { chrome.networkingPrivate.getNetworks( - {'networkType': chrome.networkingPrivate.NetworkType.ALL, - 'configured': true}, + { + 'networkType': chrome.networkingPrivate.NetworkType.ALL, + 'configured': true + }, this.onNetworksReceived_.bind(this)); }, @@ -75,7 +77,7 @@ onNetworksReceived_: function(states) { this.canAddPrinter_ = states.some(function(entry) { return entry.hasOwnProperty('ConnectionState') && - entry.ConnectionState == 'Connected'; + entry.ConnectionState == 'Connected'; }); }, @@ -88,8 +90,8 @@ if (success) { this.updateCupsPrintersList_(); var message = this.$.addPrinterDoneMessage; - message.textContent = loadTimeData.getStringF( - 'printerAddedSuccessfulMessage', printerName); + message.textContent = + loadTimeData.getStringF('printerAddedSuccessfulMessage', printerName); } else { var message = this.$.addPrinterErrorMessage; } @@ -101,8 +103,9 @@ /** @private */ updateCupsPrintersList_: function() { - settings.CupsPrintersBrowserProxyImpl.getInstance(). - getCupsPrintersList().then(this.printersChanged_.bind(this)); + settings.CupsPrintersBrowserProxyImpl.getInstance() + .getCupsPrintersList() + .then(this.printersChanged_.bind(this)); }, /**
diff --git a/chrome/browser/resources/settings/printing_page/cups_printers_list.js b/chrome/browser/resources/settings/printing_page/cups_printers_list.js index 7ce3f04..06aa208 100644 --- a/chrome/browser/resources/settings/printing_page/cups_printers_list.js +++ b/chrome/browser/resources/settings/printing_page/cups_printers_list.js
@@ -64,8 +64,8 @@ onRemoveTap_: function(event) { var index = this.printers.indexOf(assert(this.activePrinter_)); this.splice('printers', index, 1); - this.browserProxy_.removeCupsPrinter(this.activePrinter_.printerId, - this.activePrinter_.printerName); + this.browserProxy_.removeCupsPrinter( + this.activePrinter_.printerId, this.activePrinter_.printerName); this.closeDropdownMenu_(); },
diff --git a/chrome/browser/resources/settings/printing_page/printing_page.js b/chrome/browser/resources/settings/printing_page/printing_page.js index eb1bb21..2a783f10 100644 --- a/chrome/browser/resources/settings/printing_page/printing_page.js +++ b/chrome/browser/resources/settings/printing_page/printing_page.js
@@ -12,7 +12,7 @@ notify: true, }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * Whether to show CUPS printers settings. * @private {boolean} @@ -23,7 +23,7 @@ return loadTimeData.getBoolean('showCupsPrintingFeatures'); }, }, -// </if> + // </if> /** @type {!Array<!CupsPrinterInfo>} */ cupsPrinters: { @@ -43,10 +43,10 @@ map.set( settings.Route.CLOUD_PRINTERS.path, '#cloudPrinters .subpage-arrow'); -// <if expr="chromeos"> + // <if expr="chromeos"> map.set( settings.Route.CUPS_PRINTERS.path, '#cupsPrinters .subpage-arrow'); -// </if> + // </if> return map; }, }, @@ -56,7 +56,7 @@ 'show-cups-printer-details': 'onShowCupsPrinterDetailsPage_', }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ onTapCupsPrinters_: function() { settings.navigateTo(settings.Route.CUPS_PRINTERS); @@ -67,7 +67,7 @@ settings.navigateTo(settings.Route.CUPS_PRINTER_DETAIL); this.$.arraySelector.select(event.detail); }, -// </if> + // </if> /** @private */ onTapCloudPrinters_: function() {
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chrome/browser/resources/settings/privacy_page/privacy_page.js index cc7d8822..8f00696 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.js +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -13,12 +13,7 @@ * Must be kept in sync with the C++ enum of the same name. * @enum {number} */ -var NetworkPredictionOptions = { - ALWAYS: 0, - WIFI_ONLY: 1, - NEVER: 2, - DEFAULT: 1 -}; +var NetworkPredictionOptions = {ALWAYS: 0, WIFI_ONLY: 1, NEVER: 2, DEFAULT: 1}; Polymer({ is: 'settings-privacy-page', @@ -52,7 +47,7 @@ } }, -// <if expr="_google_chrome and not chromeos"> + // <if expr="_google_chrome and not chromeos"> // TODO(dbeam): make a virtual.* pref namespace and set/get this normally // (but handled differently in C++). /** @private {chrome.settingsPrivate.PrefObject} */ @@ -61,18 +56,18 @@ value: function() { // TODO(dbeam): this is basically only to appease PrefControlBehavior. // Maybe add a no-validate attribute instead? This makes little sense. - return /** @type {chrome.settingsPrivate.PrefObject} */({}); + return /** @type {chrome.settingsPrivate.PrefObject} */ ({}); }, }, showRestart_: Boolean, -// </if> + // </if> /** @private {chrome.settingsPrivate.PrefObject} */ safeBrowsingExtendedReportingPref_: { type: Object, value: function() { - return /** @type {chrome.settingsPrivate.PrefObject} */({}); + return /** @type {chrome.settingsPrivate.PrefObject} */ ({}); }, }, @@ -109,11 +104,11 @@ type: Object, value: function() { var map = new Map(); -// <if expr="use_nss_certs"> + // <if expr="use_nss_certs"> map.set( settings.Route.CERTIFICATES.path, '#manageCertificates .subpage-arrow'); -// </if> + // </if> map.set( settings.Route.SITE_SETTINGS.path, '#site-settings-subpage-trigger .subpage-arrow'); @@ -132,11 +127,11 @@ this.browserProxy_ = settings.PrivacyPageBrowserProxyImpl.getInstance(); -// <if expr="_google_chrome and not chromeos"> + // <if expr="_google_chrome and not chromeos"> var setMetricsReportingPref = this.setMetricsReportingPref_.bind(this); this.addWebUIListener('metrics-reporting-change', setMetricsReportingPref); this.browserProxy_.getMetricsReporting().then(setMetricsReportingPref); -// </if> + // </if> var setSber = this.setSafeBrowsingExtendedReporting_.bind(this); this.addWebUIListener('safe-browsing-extended-reporting-change', setSber); @@ -165,7 +160,7 @@ * @private */ onDoNotTrackChange_: function(event) { - var target = /** @type {!SettingsToggleButtonElement} */(event.target); + var target = /** @type {!SettingsToggleButtonElement} */ (event.target); if (!target.checked) { // Always allow disabling the pref. target.sendPrefChange(); @@ -218,12 +213,12 @@ /** @private */ onManageCertificatesTap_: function() { -// <if expr="use_nss_certs"> + // <if expr="use_nss_certs"> settings.navigateTo(settings.Route.CERTIFICATES); -// </if> -// <if expr="is_win or is_macosx"> + // </if> + // <if expr="is_win or is_macosx"> this.browserProxy_.showManageSSLCertificates(); -// </if> + // </if> }, /** @@ -231,8 +226,8 @@ * @private */ onRemoveAllCookiesFromSite_: function() { - var node = /** @type {?SiteDataDetailsSubpageElement} */(this.$$( - 'site-data-details-subpage')); + var node = /** @type {?SiteDataDetailsSubpageElement} */ ( + this.$$('site-data-details-subpage')); if (node) node.removeAll(); }, @@ -259,7 +254,7 @@ this.browserProxy_.setSafeBrowsingExtendedReportingEnabled(enabled); }, -// <if expr="_google_chrome and not chromeos"> + // <if expr="_google_chrome and not chromeos"> /** @private */ onMetricsReportingChange_: function() { var enabled = this.$.metricsReportingControl.checked; @@ -301,7 +296,7 @@ e.stopPropagation(); settings.LifetimeBrowserProxyImpl.getInstance().restart(); }, -// </if> + // </if> /** * @param {boolean} enabled Whether reporting is enabled or not. @@ -329,14 +324,14 @@ /** @private */ getProtectedContentLabel_: function(value) { - return value ? this.i18n('siteSettingsProtectedContentEnable') - : this.i18n('siteSettingsBlocked'); + return value ? this.i18n('siteSettingsProtectedContentEnable') : + this.i18n('siteSettingsBlocked'); }, /** @private */ getProtectedContentIdentifiersLabel_: function(value) { - return value ? this.i18n('siteSettingsProtectedContentEnableIdentifiers') - : this.i18n('siteSettingsBlocked'); + return value ? this.i18n('siteSettingsProtectedContentEnableIdentifiers') : + this.i18n('siteSettingsBlocked'); }, }); })();
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page_browser_proxy.js b/chrome/browser/resources/settings/privacy_page/privacy_page_browser_proxy.js index 2c2c472..38f544d 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page_browser_proxy.js +++ b/chrome/browser/resources/settings/privacy_page/privacy_page_browser_proxy.js
@@ -12,18 +12,18 @@ function PrivacyPageBrowserProxy() {} PrivacyPageBrowserProxy.prototype = { -// <if expr="_google_chrome and not chromeos"> + // <if expr="_google_chrome and not chromeos"> /** @return {!Promise<!MetricsReporting>} */ getMetricsReporting: assertNotReached, /** @param {boolean} enabled */ setMetricsReportingEnabled: assertNotReached, -// </if> + // </if> -// <if expr="is_win or is_macosx"> + // <if expr="is_win or is_macosx"> /** Invokes the native certificate manager (used by win and mac). */ showManageSSLCertificates: function() {}, -// </if> + // </if> /** @return {!Promise<boolean>} */ getSafeBrowsingExtendedReporting: assertNotReached, @@ -40,7 +40,7 @@ cr.addSingletonGetter(PrivacyPageBrowserProxyImpl); PrivacyPageBrowserProxyImpl.prototype = { -// <if expr="_google_chrome and not chromeos"> + // <if expr="_google_chrome and not chromeos"> /** @override */ getMetricsReporting: function() { return cr.sendWithPromise('getMetricsReporting'); @@ -50,7 +50,7 @@ setMetricsReportingEnabled: function(enabled) { chrome.send('setMetricsReportingEnabled', [enabled]); }, -// </if> + // </if> /** @override */ getSafeBrowsingExtendedReporting: function() { @@ -62,12 +62,12 @@ chrome.send('setSafeBrowsingExtendedReportingEnabled', [enabled]); }, -// <if expr="is_win or is_macosx"> + // <if expr="is_win or is_macosx"> /** @override */ showManageSSLCertificates: function() { chrome.send('showManageSSLCertificates'); }, -// </if> + // </if> }; return {
diff --git a/chrome/browser/resources/settings/reset_page/reset_browser_proxy.js b/chrome/browser/resources/settings/reset_page/reset_browser_proxy.js index f9b9fb64..ef80889 100644 --- a/chrome/browser/resources/settings/reset_page/reset_browser_proxy.js +++ b/chrome/browser/resources/settings/reset_page/reset_browser_proxy.js
@@ -43,7 +43,7 @@ */ getTriggeredResetToolName: function() {}, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * A method to be called when the reset powerwash dialog is shown. */ @@ -53,7 +53,7 @@ * Initiates a factory reset and restarts ChromeOS. */ requestFactoryResetRestart: function() {}, -// </if> + // </if> }; /** @@ -66,8 +66,8 @@ ResetBrowserProxyImpl.prototype = { /** @override */ performResetProfileSettings: function(sendSettings, requestOrigin) { - return cr.sendWithPromise('performResetProfileSettings', - sendSettings, requestOrigin); + return cr.sendWithPromise( + 'performResetProfileSettings', sendSettings, requestOrigin); }, /** @override */ @@ -104,7 +104,7 @@ return cr.sendWithPromise('getTriggeredResetToolName'); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** @override */ onPowerwashDialogShow: function() { chrome.send('onPowerwashDialogShow'); @@ -114,7 +114,7 @@ requestFactoryResetRestart: function() { chrome.send('requestFactoryResetRestart'); }, -// </if> + // </if> }; return {
diff --git a/chrome/browser/resources/settings/reset_page/reset_page.js b/chrome/browser/resources/settings/reset_page/reset_page.js index a12d5e1..64a36e1 100644 --- a/chrome/browser/resources/settings/reset_page/reset_page.js +++ b/chrome/browser/resources/settings/reset_page/reset_page.js
@@ -21,10 +21,10 @@ behaviors: [settings.RouteObserverBehavior], properties: { -// <if expr="chromeos"> + // <if expr="chromeos"> /** @private */ showPowerwashDialog_: Boolean, -// </if> + // </if> /** @private */ allowPowerwash_: { @@ -52,8 +52,8 @@ /** @private */ onShowResetProfileDialog_: function() { - settings.navigateTo(settings.Route.RESET_DIALOG, - new URLSearchParams('origin=userclick')); + settings.navigateTo( + settings.Route.RESET_DIALOG, new URLSearchParams('origin=userclick')); }, /** @private */ @@ -62,7 +62,7 @@ cr.ui.focusWithoutInk(assert(this.$.resetProfileArrow)); }, -// <if expr="chromeos"> + // <if expr="chromeos"> /** * @param {!Event} e * @private @@ -77,5 +77,5 @@ this.showPowerwashDialog_ = false; cr.ui.focusWithoutInk(assert(this.$.powerwashArrow)); }, -// </if> + // </if> });
diff --git a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js index 5328fe42..0e63dd8b 100644 --- a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js +++ b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js
@@ -50,8 +50,8 @@ */ getExplanationText_: function() { if (this.isTriggered_) { - return loadTimeData.getStringF('triggeredResetPageExplanation', - this.triggeredResetToolName_); + return loadTimeData.getStringF( + 'triggeredResetPageExplanation', this.triggeredResetToolName_); } return loadTimeData.getStringF('resetPageExplanation'); }, @@ -62,8 +62,8 @@ */ getPageTitle_: function() { if (this.isTriggered_) { - return loadTimeData.getStringF('triggeredResetPageTitle', - this.triggeredResetToolName_); + return loadTimeData.getStringF( + 'triggeredResetPageTitle', this.triggeredResetToolName_); } return loadTimeData.getStringF('resetPageTitle'); }, @@ -76,12 +76,13 @@ this.browserProxy_.onHideResetProfileDialog(); }.bind(this)); - this.$$('paper-checkbox a').addEventListener( - 'tap', this.onShowReportedSettingsTap_.bind(this)); + this.$$('paper-checkbox a') + .addEventListener('tap', this.onShowReportedSettingsTap_.bind(this)); // Prevent toggling of the checkbox when hitting the "Enter" key on the // link. - this.$$('paper-checkbox a').addEventListener( - 'keydown', function(e) { e.stopPropagation(); }); + this.$$('paper-checkbox a').addEventListener('keydown', function(e) { + e.stopPropagation(); + }); }, /** @private */ @@ -105,7 +106,8 @@ // reset request came from the Chrome Cleanup Tool by launching Chrome // with the startup URL chrome://settings/resetProfileSettings#cct. var origin = window.location.hash.slice(1).toLowerCase() == 'cct' ? - 'cct' : settings.getQueryParameters().get('origin'); + 'cct' : + settings.getQueryParameters().get('origin'); this.resetRequestOrigin_ = origin || ''; this.showDialog_(); } @@ -119,13 +121,15 @@ /** @private */ onResetTap_: function() { this.clearingInProgress_ = true; - this.browserProxy_.performResetProfileSettings( - this.$.sendSettings.checked, this.resetRequestOrigin_).then(function() { - this.clearingInProgress_ = false; - if (this.$.dialog.open) - this.$.dialog.close(); - this.fire('reset-done'); - }.bind(this)); + this.browserProxy_ + .performResetProfileSettings( + this.$.sendSettings.checked, this.resetRequestOrigin_) + .then(function() { + this.clearingInProgress_ = false; + if (this.$.dialog.open) + this.$.dialog.close(); + this.fire('reset-done'); + }.bind(this)); }, /**
diff --git a/chrome/browser/resources/settings/route.js b/chrome/browser/resources/settings/route.js index 2890223f7..1d3496b 100644 --- a/chrome/browser/resources/settings/route.js +++ b/chrome/browser/resources/settings/route.js
@@ -113,7 +113,7 @@ r.ADVANCED.createChild('/triggeredResetProfileSettings'); r.TRIGGERED_RESET_DIALOG.isNavigableDialog = true; -// <if expr="chromeos"> + // <if expr="chromeos"> r.INTERNET = r.BASIC.createSection('/internet', 'internet'); r.INTERNET_NETWORKS = r.INTERNET.createChild('/networks'); r.NETWORK_CONFIG = r.INTERNET.createChild('/networkConfig'); @@ -121,7 +121,7 @@ r.KNOWN_NETWORKS = r.INTERNET.createChild('/knownNetworks'); r.BLUETOOTH = r.BASIC.createSection('/bluetooth', 'bluetooth'); r.BLUETOOTH_DEVICES = r.BLUETOOTH.createChild('/bluetoothDevices'); -// </if> + // </if> r.APPEARANCE = r.BASIC.createSection('/appearance', 'appearance'); r.FONTS = r.APPEARANCE.createChild('/fonts'); @@ -132,19 +132,19 @@ r.SEARCH = r.BASIC.createSection('/search', 'search'); r.SEARCH_ENGINES = r.SEARCH.createChild('/searchEngines'); -// <if expr="chromeos"> + // <if expr="chromeos"> r.ANDROID_APPS = r.BASIC.createSection('/androidApps', 'androidApps'); r.ANDROID_APPS_DETAILS = r.ANDROID_APPS.createChild('/androidApps/details'); -// </if> + // </if> r.ON_STARTUP = r.BASIC.createSection('/onStartup', 'onStartup'); r.PEOPLE = r.BASIC.createSection('/people', 'people'); r.SYNC = r.PEOPLE.createChild('/syncSetup'); -// <if expr="not chromeos"> + // <if expr="not chromeos"> r.MANAGE_PROFILE = r.PEOPLE.createChild('/manageProfile'); -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> r.CHANGE_PICTURE = r.PEOPLE.createChild('/changePicture'); r.ACCOUNTS = r.PEOPLE.createChild('/accounts'); r.LOCK_SCREEN = r.PEOPLE.createChild('/lockScreen'); @@ -157,7 +157,7 @@ r.DISPLAY = r.DEVICE.createChild('/display'); r.STORAGE = r.DEVICE.createChild('/storage'); r.POWER = r.DEVICE.createChild('/power'); -// </if> + // </if> r.PRIVACY = r.ADVANCED.createSection('/privacy', 'privacy'); r.CERTIFICATES = r.PRIVACY.createChild('/certificates'); @@ -204,9 +204,9 @@ r.SITE_SETTINGS_PROTECTED_CONTENT = r.SITE_SETTINGS.createChild('protectedContent'); -// <if expr="chromeos"> + // <if expr="chromeos"> r.DATETIME = r.ADVANCED.createSection('/dateTime', 'dateTime'); -// </if> + // </if> r.PASSWORDS = r.ADVANCED.createSection('/passwordsAndForms', 'passwordsAndForms'); @@ -214,36 +214,36 @@ r.MANAGE_PASSWORDS = r.PASSWORDS.createChild('/passwords'); r.LANGUAGES = r.ADVANCED.createSection('/languages', 'languages'); -// <if expr="chromeos"> + // <if expr="chromeos"> r.INPUT_METHODS = r.LANGUAGES.createChild('/inputMethods'); -// </if> -// <if expr="not is_macosx"> + // </if> + // <if expr="not is_macosx"> r.EDIT_DICTIONARY = r.LANGUAGES.createChild('/editDictionary'); -// </if> + // </if> r.DOWNLOADS = r.ADVANCED.createSection('/downloads', 'downloads'); r.PRINTING = r.ADVANCED.createSection('/printing', 'printing'); r.CLOUD_PRINTERS = r.PRINTING.createChild('/cloudPrinters'); -// <if expr="chromeos"> + // <if expr="chromeos"> r.CUPS_PRINTERS = r.PRINTING.createChild('/cupsPrinters'); r.CUPS_PRINTER_DETAIL = r.CUPS_PRINTERS.createChild('/cupsPrinterDetails'); -// </if> + // </if> r.ACCESSIBILITY = r.ADVANCED.createSection('/accessibility', 'a11y'); -// <if expr="chromeos"> + // <if expr="chromeos"> r.MANAGE_ACCESSIBILITY = r.ACCESSIBILITY.createChild('/manageAccessibility'); -// </if> + // </if> r.SYSTEM = r.ADVANCED.createSection('/system', 'system'); r.RESET = r.ADVANCED.createSection('/reset', 'reset'); -// <if expr="chromeos"> + // <if expr="chromeos"> // "About" is the only section in About, but we still need to create the route // in order to show the subpage on Chrome OS. r.ABOUT_ABOUT = r.ABOUT.createSection('/help/about', 'about'); r.DETAILED_BUILD_INFO = r.ABOUT_ABOUT.createChild('/help/details'); -// </if> + // </if> var routeObservers = new Set(); @@ -359,7 +359,9 @@ }; /** @return {!settings.Route} */ - var getCurrentRoute = function() { return currentRoute; }; + var getCurrentRoute = function() { + return currentRoute; + }; /** @return {!URLSearchParams} */ var getQueryParameters = function() { @@ -410,8 +412,7 @@ * this navigates to the immediate parent. This will never exit Settings. */ var navigateToPreviousRoute = function() { - var previousRoute = - window.history.state && + var previousRoute = window.history.state && assert(getRouteForPath(/** @type {string} */ (window.history.state))); if (previousRoute && previousRoute.depth <= currentRoute.depth) @@ -422,8 +423,9 @@ window.addEventListener('popstate', function(event) { // On pop state, do not push the state onto the window.history again. - setCurrentRoute(getRouteForPath(window.location.pathname) || Route.BASIC, - new URLSearchParams(window.location.search), true); + setCurrentRoute( + getRouteForPath(window.location.pathname) || Route.BASIC, + new URLSearchParams(window.location.search), true); }); return {
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js index bf275f9..f77d2002 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js
@@ -106,11 +106,12 @@ return; } - this.browserProxy_.validateSearchEngineInput( - inputElement.id, inputElement.value).then(function(isValid) { - inputElement.invalid = !isValid; - this.updateActionButtonState_(); - }.bind(this)); + this.browserProxy_ + .validateSearchEngineInput(inputElement.id, inputElement.value) + .then(function(isValid) { + inputElement.invalid = !isValid; + this.updateActionButtonState_(); + }.bind(this)); }, /** @private */
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js index e4819dd..5423903 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js
@@ -125,7 +125,9 @@ /** @override */ searchEngineEditCompleted: function(searchEngine, keyword, queryUrl) { chrome.send('searchEngineEditCompleted', [ - searchEngine, keyword, queryUrl, + searchEngine, + keyword, + queryUrl, ]); },
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engines_page.js b/chrome/browser/resources/settings/search_engines_page/search_engines_page.js index 526b22ab..f462274 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engines_page.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engines_page.js
@@ -15,19 +15,25 @@ /** @type {!Array<!SearchEngine>} */ defaultEngines: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** @type {!Array<!SearchEngine>} */ otherEngines: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** @type {!Array<!SearchEngine>} */ extensions: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** @@ -58,8 +64,9 @@ /** @override */ ready: function() { - settings.SearchEnginesBrowserProxyImpl.getInstance(). - getSearchEnginesList().then(this.enginesChanged_.bind(this)); + settings.SearchEnginesBrowserProxyImpl.getInstance() + .getSearchEnginesList() + .then(this.enginesChanged_.bind(this)); this.addWebUIListener( 'search-engines-changed', this.enginesChanged_.bind(this));
diff --git a/chrome/browser/resources/settings/search_page/search_page.js b/chrome/browser/resources/settings/search_page/search_page.js index 78e8feb..54c52a0 100644 --- a/chrome/browser/resources/settings/search_page/search_page.js +++ b/chrome/browser/resources/settings/search_page/search_page.js
@@ -71,7 +71,7 @@ 'google-now-availability-changed', this.googleNowAvailabilityUpdate_.bind(this)); this.browserProxy_.getGoogleNowAvailability().then(function(available) { - this.googleNowAvailabilityUpdate_(available); + this.googleNowAvailabilityUpdate_(available); }.bind(this)); this.focusConfig_ = new Map();
diff --git a/chrome/browser/resources/settings/search_settings.js b/chrome/browser/resources/settings/search_settings.js index ad541dd..3a74f28 100644 --- a/chrome/browser/resources/settings/search_settings.js +++ b/chrome/browser/resources/settings/search_settings.js
@@ -67,15 +67,15 @@ function findAndRemoveHighlights_(node) { var wrappers = node.querySelectorAll('* /deep/ .' + WRAPPER_CSS_CLASS); - for (var i = 0; i < wrappers.length; i++ ) { + for (var i = 0; i < wrappers.length; i++) { var wrapper = wrappers[i]; - var originalNode = wrapper.querySelector( - '.' + ORIGINAL_CONTENT_CSS_CLASS); + var originalNode = + wrapper.querySelector('.' + ORIGINAL_CONTENT_CSS_CLASS); wrapper.parentElement.replaceChild(originalNode.firstChild, wrapper); } - var searchBubbles = node.querySelectorAll( - '* /deep/ .' + SEARCH_BUBBLE_CSS_CLASS); + var searchBubbles = + node.querySelectorAll('* /deep/ .' + SEARCH_BUBBLE_CSS_CLASS); for (var j = 0; j < searchBubbles.length; j++) searchBubbles[j].remove(); } @@ -113,7 +113,7 @@ } else { var span = document.createElement('span'); span.classList.add(HIT_CSS_CLASS); - span.style.backgroundColor = '#ffeb3b'; // --var(--paper-yellow-500) + span.style.backgroundColor = '#ffeb3b'; // --var(--paper-yellow-500) span.textContent = tokens[i]; wrapper.appendChild(span); } @@ -143,10 +143,9 @@ return; if (node instanceof HTMLElement) { - var element = /** @type {HTMLElement} */(node); + var element = /** @type {HTMLElement} */ (node); if (element.hasAttribute(SKIP_SEARCH_CSS_ATTRIBUTE) || - element.hasAttribute('hidden') || - element.style.display == 'none') { + element.hasAttribute('hidden') || element.style.display == 'none') { return; } } @@ -242,7 +241,8 @@ var parent = node; while (parent && parent.nodeName !== 'SETTINGS-SECTION') { parent = parent.nodeType == Node.DOCUMENT_FRAGMENT_NODE ? - parent.host : parent.parentNode; + parent.host : + parent.parentNode; if (parent.nodeName == 'SETTINGS-SUBPAGE') { // TODO(dpapad): Cast to SettingsSubpageElement here. associatedControl = assert( @@ -444,8 +444,7 @@ * @private */ popNextTask_: function() { - return this.queues_.high.shift() || - this.queues_.middle.shift() || + return this.queues_.high.shift() || this.queues_.middle.shift() || this.queues_.low.shift(); }, @@ -535,8 +534,8 @@ // Generate search text by escaping any characters that would be // problematic for regular expressions. - var searchText = this.rawQuery_.trim().replace( - SearchRequest.SANITIZE_REGEX_, '\\$&'); + var searchText = + this.rawQuery_.trim().replace(SearchRequest.SANITIZE_REGEX_, '\\$&'); if (searchText.length > 0) regExp = new RegExp('(' + searchText + ')', 'i');
diff --git a/chrome/browser/resources/settings/settings_main/settings_main.js b/chrome/browser/resources/settings/settings_main/settings_main.js index a7c1e8d..e42680c3 100644 --- a/chrome/browser/resources/settings/settings_main/settings_main.js +++ b/chrome/browser/resources/settings/settings_main/settings_main.js
@@ -126,8 +126,8 @@ var visibleBottom = scroller.scrollTop + scroller.clientHeight; var overscrollBottom = overscroll.offsetTop + overscroll.scrollHeight; // How much of the overscroll is visible (may be negative). - var visibleOverscroll = overscroll.scrollHeight - - (overscrollBottom - visibleBottom); + var visibleOverscroll = + overscroll.scrollHeight - (overscrollBottom - visibleBottom); this.overscroll_ = Math.max(opt_minHeight || 0, Math.ceil(visibleOverscroll)); }, @@ -234,12 +234,12 @@ */ getPage_: function(route) { if (settings.Route.ABOUT.contains(route)) { - return /** @type {?SettingsAboutPageElement} */( + return /** @type {?SettingsAboutPageElement} */ ( this.$$('settings-about-page')); } if (settings.Route.BASIC.contains(route) || settings.Route.ADVANCED.contains(route)) { - return /** @type {?SettingsBasicPageElement} */( + return /** @type {?SettingsBasicPageElement} */ ( this.$$('settings-basic-page')); } assertNotReached();
diff --git a/chrome/browser/resources/settings/settings_page/main_page_behavior.js b/chrome/browser/resources/settings/settings_page/main_page_behavior.js index 04b70c97..7e6b9df 100644 --- a/chrome/browser/resources/settings/settings_page/main_page_behavior.js +++ b/chrome/browser/resources/settings/settings_page/main_page_behavior.js
@@ -58,9 +58,8 @@ * @param {settings.Route} oldRoute */ currentRouteChanged: function(newRoute, oldRoute) { - var oldRouteWasSection = - !!oldRoute && !!oldRoute.parent && !!oldRoute.section && - oldRoute.parent.section != oldRoute.section; + var oldRouteWasSection = !!oldRoute && !!oldRoute.parent && + !!oldRoute.section && oldRoute.parent.section != oldRoute.section; if (this.scroller) { // When navigating from a section to the root route, we just need to @@ -141,7 +140,7 @@ } var promise; - var expandedSection = /** @type {?SettingsSectionElement} */( + var expandedSection = /** @type {?SettingsSectionElement} */ ( this.$$('settings-section.expanded')); if (expandedSection) { // If the section shouldn't be expanded, collapse it. @@ -190,7 +189,7 @@ */ maybeStopCurrentAnimation_: function() { var currentRoute = settings.getCurrentRoute(); - var animatingSection = /** @type {?SettingsSectionElement} */( + var animatingSection = /** @type {?SettingsSectionElement} */ ( this.$$('settings-section.expanding, settings-section.collapsing')); assert(animatingSection); @@ -340,19 +339,22 @@ } this.currentAnimation_ = section.animateCollapse( - /** @type {!HTMLElement} */(this.scroller)); + /** @type {!HTMLElement} */ (this.scroller)); - this.currentAnimation_.finished.catch(function() { - // The collapse was canceled, so the page is showing a subpage still. - this.fire('subpage-expand'); - }.bind(this)).then(function() { - // Clean up after the animation succeeds or cancels. - section.setFrozen(false); - section.classList.remove('collapsing'); - this.fire('freeze-scroll', false); - this.currentAnimation_ = null; - resolve(); - }.bind(this)); + this.currentAnimation_.finished + .catch(function() { + // The collapse was canceled, so the page is showing a subpage + // still. + this.fire('subpage-expand'); + }.bind(this)) + .then(function() { + // Clean up after the animation succeeds or cancels. + section.setFrozen(false); + section.classList.remove('collapsing'); + this.fire('freeze-scroll', false); + this.currentAnimation_ = null; + resolve(); + }.bind(this)); }.bind(this)); }.bind(this)); }, @@ -365,8 +367,7 @@ * @private */ toggleOtherSectionsHidden_: function(sectionName, hidden) { - var sections = Polymer.dom(this.root).querySelectorAll( - 'settings-section'); + var sections = Polymer.dom(this.root).querySelectorAll('settings-section'); for (var i = 0; i < sections.length; i++) sections[i].hidden = hidden && (sections[i].section != sectionName); }, @@ -379,7 +380,7 @@ getSection: function(section) { if (!section) return null; - return /** @type {?SettingsSectionElement} */( + return /** @type {?SettingsSectionElement} */ ( this.$$('settings-section[section="' + section + '"]')); }, };
diff --git a/chrome/browser/resources/settings/settings_page/settings_animated_pages.js b/chrome/browser/resources/settings/settings_page/settings_animated_pages.js index 9fa356d..b2c80e50 100644 --- a/chrome/browser/resources/settings/settings_page/settings_animated_pages.js +++ b/chrome/browser/resources/settings/settings_page/settings_animated_pages.js
@@ -70,10 +70,10 @@ 'settings-subpage[route-path=\"' + settings.Route.SITE_SETTINGS_COOKIES.path + '\"]'; -// <if expr="chromeos"> + // <if expr="chromeos"> whitelist += ', settings-subpage[route-path=\"' + settings.Route.INTERNET_NETWORKS.path + '\"]'; -// </if> + // </if> if (!e.detail.item.matches('neon-animatable, ' + whitelist)) return;
diff --git a/chrome/browser/resources/settings/settings_page/settings_section.js b/chrome/browser/resources/settings/settings_page/settings_section.js index a291461..0265b83 100644 --- a/chrome/browser/resources/settings/settings_page/settings_section.js +++ b/chrome/browser/resources/settings/settings_page/settings_section.js
@@ -140,13 +140,17 @@ var animation = this.animateCard_('fixed', startTop, endTop, startHeight, endHeight); - animation.finished.then(function() { - this.classList.add('expanded'); - }.bind(this), function() {}).then(function() { - // Unset these changes whether the animation finished or canceled. - this.classList.remove('expanding'); - this.style.height = ''; - }.bind(this)); + animation.finished + .then( + function() { + this.classList.add('expanded'); + }.bind(this), + function() {}) + .then(function() { + // Unset these changes whether the animation finished or canceled. + this.classList.remove('expanding'); + this.style.height = ''; + }.bind(this)); return animation; }, @@ -217,13 +221,17 @@ this.$.card.style.height = ''; this.$.card.style.top = ''; - animation.finished.then(function() { - this.classList.remove('expanded'); - }.bind(this), function() {}).then(function() { - // The card now determines the section's height automatically. - this.style.height = ''; - this.classList.remove('collapsing'); - }.bind(this)); + animation.finished + .then( + function() { + this.classList.remove('expanded'); + }.bind(this), + function() {}) + .then(function() { + // The card now determines the section's height automatically. + this.style.height = ''; + this.classList.remove('collapsing'); + }.bind(this)); return animation; }, @@ -255,7 +263,7 @@ height: endHeight, }; - var options = /** @type {!KeyframeEffectOptions} */({ + var options = /** @type {!KeyframeEffectOptions} */ ({ duration: settings.animation.Timing.DURATION, easing: settings.animation.Timing.EASING, });
diff --git a/chrome/browser/resources/settings/settings_ui/settings_ui.js b/chrome/browser/resources/settings/settings_ui/settings_ui.js index de88756f..279ebc7b 100644 --- a/chrome/browser/resources/settings/settings_ui/settings_ui.js +++ b/chrome/browser/resources/settings/settings_ui/settings_ui.js
@@ -11,8 +11,9 @@ * <settings-ui prefs="{{prefs}}"></settings-ui> */ cr.exportPath('settings'); -assert(!settings.defaultResourceLoaded, - 'settings_ui.js run twice. You probably have an invalid import.'); +assert( + !settings.defaultResourceLoaded, + 'settings_ui.js run twice. You probably have an invalid import.'); /** Global defined when the main Settings script runs. */ settings.defaultResourceLoaded = true; @@ -98,14 +99,14 @@ loadTimeData.getString('controlledSettingRecommendedMatches'), controlledSettingRecommendedDiffers: loadTimeData.getString('controlledSettingRecommendedDiffers'), -// <if expr="chromeos"> + // <if expr="chromeos"> controlledSettingShared: loadTimeData.getString('controlledSettingShared'), controlledSettingOwner: loadTimeData.getString('controlledSettingOwner'), -// </if> + // </if> }; -// <if expr="chromeos"> + // <if expr="chromeos"> CrOncStrings = { OncTypeCellular: loadTimeData.getString('OncTypeCellular'), OncTypeEthernet: loadTimeData.getString('OncTypeEthernet'), @@ -123,7 +124,7 @@ loadTimeData.getString('networkListItemNotConnected'), vpnNameTemplate: loadTimeData.getString('vpnNameTemplate'), }; -// </if> + // </if> if (loadTimeData.getBoolean('isGuest')) { this.pageVisibility_ = { @@ -131,12 +132,12 @@ people: false, onStartup: false, reset: false, -// <if expr="not chromeos"> + // <if expr="not chromeos"> appearance: false, defaultBrowser: false, advancedSettings: false, -// </if> -// <if expr="chromeos"> + // </if> + // <if expr="chromeos"> appearance: { setWallpaper: false, setTheme: false, @@ -152,7 +153,7 @@ downloads: { googleDrive: false, }, -// </if> + // </if> }; } @@ -217,8 +218,8 @@ this.lastSearchQuery_ = urlSearchQuery; var toolbar = /** @type {!CrToolbarElement} */ (this.$$('cr-toolbar')); - var searchField = /** @type {CrToolbarSearchFieldElement} */ ( - toolbar.getSearchField()); + var searchField = + /** @type {CrToolbarSearchFieldElement} */ (toolbar.getSearchField()); // If the search was initiated by directly entering a search URL, need to // sync the URL parameter to the textbox. @@ -236,8 +237,8 @@ * @private */ onRefreshPref_: function(e) { - var prefName = /** @type {string} */(e.detail); - return /** @type {SettingsPrefsElement} */(this.$.prefs).refresh(prefName); + var prefName = /** @type {string} */ (e.detail); + return /** @type {SettingsPrefsElement} */ (this.$.prefs).refresh(prefName); }, /** @@ -289,7 +290,6 @@ /** @private */ directionDelegateChanged_: function() { - this.$.drawer.align = this.directionDelegate.isRtl() ? - 'right' : 'left'; + this.$.drawer.align = this.directionDelegate.isRtl() ? 'right' : 'left'; }, });
diff --git a/chrome/browser/resources/settings/site_settings/category_default_setting.js b/chrome/browser/resources/settings/site_settings/category_default_setting.js index fdc483e..a150324 100644 --- a/chrome/browser/resources/settings/site_settings/category_default_setting.js +++ b/chrome/browser/resources/settings/site_settings/category_default_setting.js
@@ -31,7 +31,7 @@ controlParams_: { type: Object, value: function() { - return /** @type {chrome.settingsPrivate.PrefObject} */({}); + return /** @type {chrome.settingsPrivate.PrefObject} */ ({}); }, }, @@ -46,7 +46,7 @@ priorDefaultContentSetting_: { type: Object, value: function() { - return /** @type {DefaultContentSetting} */({}); + return /** @type {DefaultContentSetting} */ ({}); }, }, @@ -58,7 +58,7 @@ subControlParams_: { type: Object, value: function() { - return /** @type {chrome.settingsPrivate.PrefObject} */({}); + return /** @type {chrome.settingsPrivate.PrefObject} */ ({}); }, }, }, @@ -71,8 +71,8 @@ /** @override */ ready: function() { - this.addWebUIListener('contentSettingCategoryChanged', - this.onCategoryChanged_.bind(this)); + this.addWebUIListener( + 'contentSettingCategoryChanged', this.onCategoryChanged_.bind(this)); }, /** @return {boolean} */ @@ -96,9 +96,8 @@ // "Allowed" vs "Blocked". this.browserProxy.setDefaultValueForContentType( this.category, - this.categoryEnabled ? - settings.PermissionValues.ALLOW : - settings.PermissionValues.BLOCK); + this.categoryEnabled ? settings.PermissionValues.ALLOW : + settings.PermissionValues.BLOCK); break; case settings.ContentSettingsTypes.AUTOMATIC_DOWNLOADS: case settings.ContentSettingsTypes.CAMERA: @@ -110,9 +109,8 @@ // "Ask" vs "Blocked". this.browserProxy.setDefaultValueForContentType( this.category, - this.categoryEnabled ? - settings.PermissionValues.ASK : - settings.PermissionValues.BLOCK); + this.categoryEnabled ? settings.PermissionValues.ASK : + settings.PermissionValues.BLOCK); break; case settings.ContentSettingsTypes.COOKIES: // This category is tri-state: "Allow", "Block", "Keep data until @@ -169,7 +167,7 @@ var prefValue = this.computeIsSettingEnabled(update.setting); // The controlParams_ must be replaced (rather than just value changes) so // that observers will be notified of the change. - this.controlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */( + this.controlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */ ( Object.assign({'value': prefValue}, basePref)); var subPrefValue = false; @@ -178,14 +176,15 @@ if (this.category == settings.ContentSettingsTypes.PLUGINS && update.setting == settings.PermissionValues.IMPORTANT_CONTENT) { subPrefValue = true; - } else if (this.category == settings.ContentSettingsTypes.COOKIES && + } else if ( + this.category == settings.ContentSettingsTypes.COOKIES && update.setting == settings.PermissionValues.SESSION_ONLY) { subPrefValue = true; } } // The subControlParams_ must be replaced (rather than just value changes) // so that observers will be notified of the change. - this.subControlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */( + this.subControlParams_ = /** @type {chrome.settingsPrivate.PrefObject} */ ( Object.assign({'value': subPrefValue}, basePref)); }, @@ -194,25 +193,24 @@ * @private */ onCategoryChanged_: function() { - this.browserProxy - .getDefaultValueForContentType( - this.category).then(function(defaultValue) { - this.updateControlParams_(defaultValue); + this.browserProxy.getDefaultValueForContentType(this.category) + .then(function(defaultValue) { + this.updateControlParams_(defaultValue); - // Flash only shows ALLOW or BLOCK descriptions on the toggle. - var setting = defaultValue.setting; - if (this.category == settings.ContentSettingsTypes.PLUGINS && - setting == settings.PermissionValues.IMPORTANT_CONTENT) { - setting = settings.PermissionValues.ALLOW; - } else if ( - this.category == settings.ContentSettingsTypes.COOKIES && - setting == settings.PermissionValues.SESSION_ONLY) { - setting = settings.PermissionValues.ALLOW; - } - var categoryEnabled = setting != settings.PermissionValues.BLOCK; - this.optionLabel_ = - categoryEnabled ? this.toggleOnLabel : this.toggleOffLabel; - }.bind(this)); + // Flash only shows ALLOW or BLOCK descriptions on the toggle. + var setting = defaultValue.setting; + if (this.category == settings.ContentSettingsTypes.PLUGINS && + setting == settings.PermissionValues.IMPORTANT_CONTENT) { + setting = settings.PermissionValues.ALLOW; + } else if ( + this.category == settings.ContentSettingsTypes.COOKIES && + setting == settings.PermissionValues.SESSION_ONLY) { + setting = settings.PermissionValues.ALLOW; + } + var categoryEnabled = setting != settings.PermissionValues.BLOCK; + this.optionLabel_ = + categoryEnabled ? this.toggleOnLabel : this.toggleOffLabel; + }.bind(this)); }, /**
diff --git a/chrome/browser/resources/settings/site_settings/constants.js b/chrome/browser/resources/settings/site_settings/constants.js index 600325e..46b5ba7 100644 --- a/chrome/browser/resources/settings/site_settings/constants.js +++ b/chrome/browser/resources/settings/site_settings/constants.js
@@ -29,9 +29,9 @@ MIDI_DEVICES: 'midi-sysex', USB_DEVICES: 'usb-chooser-data', ZOOM_LEVELS: 'zoom-levels', -// <if expr="chromeos"> + // <if expr="chromeos"> PROTECTED_CONTENT: 'protectedContent', -// </if> + // </if> ADS: 'ads', };
diff --git a/chrome/browser/resources/settings/site_settings/cookie_info.js b/chrome/browser/resources/settings/site_settings/cookie_info.js index ba05b4a2..43056bb 100644 --- a/chrome/browser/resources/settings/site_settings/cookie_info.js +++ b/chrome/browser/resources/settings/site_settings/cookie_info.js
@@ -26,44 +26,50 @@ // 2) What order to show it in. // 3) What user friendly label to prefix the data with. /** @const */ var cookieInfo = { - 'cookie': [['name', 'cookieName'], - ['content', 'cookieContent'], - ['domain', 'cookieDomain'], - ['path', 'cookiePath'], - ['sendfor', 'cookieSendFor'], - ['accessibleToScript', 'cookieAccessibleToScript'], - ['created', 'cookieCreated'], - ['expires', 'cookieExpires']], - 'app_cache': [['manifest', 'appCacheManifest'], - ['size', 'localStorageSize'], - ['created', 'cookieCreated'], - ['accessed', 'cookieLastAccessed']], - 'database': [['name', 'cookieName'], - ['desc', 'webdbDesc'], - ['size', 'localStorageSize'], - ['modified', 'localStorageLastModified']], - 'local_storage': [['origin', 'localStorageOrigin'], - ['size', 'localStorageSize'], - ['modified', 'localStorageLastModified']], - 'indexed_db': [['origin', 'indexedDbOrigin'], - ['size', 'indexedDbSize'], - ['modified', 'indexedDbLastModified']], - 'file_system': [['origin', 'fileSystemOrigin'], - ['persistent', 'fileSystemPersistentUsage'], - ['temporary', 'fileSystemTemporaryUsage']], - 'channel_id': [['serverId', 'channelIdServerId'], - ['certType', 'channelIdType'], - ['created', 'channelIdCreated']], - 'service_worker': [['origin', 'serviceWorkerOrigin'], - ['size', 'serviceWorkerSize'], - ['scopes', 'serviceWorkerScopes']], - 'cache_storage': [['origin', 'cacheStorageOrigin'], - ['size', 'cacheStorageSize'], - ['modified', 'cacheStorageLastModified']], + 'cookie': [ + ['name', 'cookieName'], ['content', 'cookieContent'], + ['domain', 'cookieDomain'], ['path', 'cookiePath'], + ['sendfor', 'cookieSendFor'], + ['accessibleToScript', 'cookieAccessibleToScript'], + ['created', 'cookieCreated'], ['expires', 'cookieExpires'] + ], + 'app_cache': [ + ['manifest', 'appCacheManifest'], ['size', 'localStorageSize'], + ['created', 'cookieCreated'], ['accessed', 'cookieLastAccessed'] + ], + 'database': [ + ['name', 'cookieName'], ['desc', 'webdbDesc'], ['size', 'localStorageSize'], + ['modified', 'localStorageLastModified'] + ], + 'local_storage': [ + ['origin', 'localStorageOrigin'], ['size', 'localStorageSize'], + ['modified', 'localStorageLastModified'] + ], + 'indexed_db': [ + ['origin', 'indexedDbOrigin'], ['size', 'indexedDbSize'], + ['modified', 'indexedDbLastModified'] + ], + 'file_system': [ + ['origin', 'fileSystemOrigin'], ['persistent', 'fileSystemPersistentUsage'], + ['temporary', 'fileSystemTemporaryUsage'] + ], + 'channel_id': [ + ['serverId', 'channelIdServerId'], ['certType', 'channelIdType'], + ['created', 'channelIdCreated'] + ], + 'service_worker': [ + ['origin', 'serviceWorkerOrigin'], ['size', 'serviceWorkerSize'], + ['scopes', 'serviceWorkerScopes'] + ], + 'cache_storage': [ + ['origin', 'cacheStorageOrigin'], ['size', 'cacheStorageSize'], + ['modified', 'cacheStorageLastModified'] + ], 'flash_lso': [['domain', 'cookieDomain']], - 'media_license': [['origin', 'mediaLicenseOrigin'], - ['size', 'mediaLicenseSize'], - ['modified', 'mediaLicenseLastModified']], + 'media_license': [ + ['origin', 'mediaLicenseOrigin'], ['size', 'mediaLicenseSize'], + ['modified', 'mediaLicenseLastModified'] + ], }; /** @@ -82,7 +88,7 @@ // (in the order determined by |cookieInfo|). var key = field[0]; if (data[key].length > 0) { - var entry = /** @type {CookieDataForDisplay} */({ + var entry = /** @type {CookieDataForDisplay} */ ({ label: loadTimeData.getString(field[1]), content: data[key], });
diff --git a/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js b/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js index 287622c..0b540b9 100644 --- a/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js +++ b/chrome/browser/resources/settings/site_settings/cookie_tree_behavior.js
@@ -26,8 +26,8 @@ /** @override */ ready: function() { - cr.addWebUIListener('onTreeItemRemoved', - this.onTreeItemRemoved_.bind(this)); + cr.addWebUIListener( + 'onTreeItemRemoved', this.onTreeItemRemoved_.bind(this)); this.rootCookieNode = new settings.CookieTreeNode(null); }, @@ -43,16 +43,16 @@ var children = childList.children; var prefix = ''; if (parentId !== null) { - this.rootCookieNode.populateChildNodes(parentId, - this.rootCookieNode, children); + this.rootCookieNode.populateChildNodes( + parentId, this.rootCookieNode, children); prefix = parentId + ', '; } var promises = []; for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.hasChildren) { - promises.push(this.browserProxy.loadCookieChildren( - prefix + child.id).then(loadChildrenRecurse.bind(this))); + promises.push(this.browserProxy.loadCookieChildren(prefix + child.id) + .then(loadChildrenRecurse.bind(this))); } } return Promise.all(promises);
diff --git a/chrome/browser/resources/settings/site_settings/cookie_tree_node.js b/chrome/browser/resources/settings/site_settings/cookie_tree_node.js index 030099b..809ee7f 100644 --- a/chrome/browser/resources/settings/site_settings/cookie_tree_node.js +++ b/chrome/browser/resources/settings/site_settings/cookie_tree_node.js
@@ -109,7 +109,7 @@ } if (this.populateChildNodes( - parentId, startingNode.children_[i], newNodes)) { + parentId, startingNode.children_[i], newNodes)) { return true; } } @@ -138,9 +138,11 @@ var child = this.children_[i]; for (var j = 0; j < child.children_.length; j++) { var cookie = child.children_[j]; - list.push({title: cookie.data.title, - id: cookie.data.id, - data: cookie.data}); + list.push({ + title: cookie.data.title, + id: cookie.data.id, + data: cookie.data + }); } } @@ -186,7 +188,7 @@ dataType, descriptionNode.data.totalUsage); } } - list.push({ site: title, id: id, localData: description }); + list.push({site: title, id: id, localData: description}); } list.sort(function(a, b) { return a.site.localeCompare(b.site);
diff --git a/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js b/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js index bc5cc802..b4d39aa5 100644 --- a/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js +++ b/chrome/browser/resources/settings/site_settings/edit_exception_dialog.js
@@ -50,16 +50,11 @@ if (this.model.origin != this.origin_) { // The way to "edit" an exception is to remove it and and a new one. this.browserProxy_.resetCategoryPermissionForOrigin( - this.model.origin, - this.model.embeddingOrigin, - this.model.category, + this.model.origin, this.model.embeddingOrigin, this.model.category, this.model.incognito); this.browserProxy_.setCategoryPermissionForOrigin( - this.origin_, - this.origin_, - this.model.category, - this.model.setting, + this.origin_, this.origin_, this.model.category, this.model.setting, this.model.incognito); }
diff --git a/chrome/browser/resources/settings/site_settings/media_picker.js b/chrome/browser/resources/settings/site_settings/media_picker.js index 213eea7..f39f5f9a 100644 --- a/chrome/browser/resources/settings/site_settings/media_picker.js +++ b/chrome/browser/resources/settings/site_settings/media_picker.js
@@ -30,8 +30,8 @@ /** @override */ ready: function() { - this.addWebUIListener('updateDevicesMenu', - this.updateDevicesMenu_.bind(this)); + this.addWebUIListener( + 'updateDevicesMenu', this.updateDevicesMenu_.bind(this)); this.browserProxy.getDefaultCaptureDevices(this.type); },
diff --git a/chrome/browser/resources/settings/site_settings/protocol_handlers.js b/chrome/browser/resources/settings/site_settings/protocol_handlers.js index 923bbab..871659b 100644 --- a/chrome/browser/resources/settings/site_settings/protocol_handlers.js +++ b/chrome/browser/resources/settings/site_settings/protocol_handlers.js
@@ -63,11 +63,12 @@ /** @override */ ready: function() { - this.addWebUIListener('setHandlersEnabled', - this.setHandlersEnabled_.bind(this)); - this.addWebUIListener('setProtocolHandlers', - this.setProtocolHandlers_.bind(this)); - this.addWebUIListener('setIgnoredProtocolHandlers', + this.addWebUIListener( + 'setHandlersEnabled', this.setHandlersEnabled_.bind(this)); + this.addWebUIListener( + 'setProtocolHandlers', this.setProtocolHandlers_.bind(this)); + this.addWebUIListener( + 'setIgnoredProtocolHandlers', this.setIgnoredProtocolHandlers_.bind(this)); this.browserProxy.observeProtocolHandlers(); }, @@ -159,8 +160,9 @@ * @return {boolean} if actionMenuModel_ is default handler of its protocol. */ isModelDefault_: function() { - return !!this.actionMenuModel_ && (this.actionMenuModel_.index == - this.actionMenuModel_.protocol.default_handler); + return !!this.actionMenuModel_ && + (this.actionMenuModel_.index == + this.actionMenuModel_.protocol.default_handler); }, /** @@ -171,8 +173,8 @@ */ showMenu_: function(event) { this.actionMenuModel_ = event.model; - /** @type {!CrActionMenuElement} */ ( - this.$$('dialog[is=cr-action-menu]')).showAt( + /** @type {!CrActionMenuElement} */ (this.$$('dialog[is=cr-action-menu]')) + .showAt( /** @type {!Element} */ ( Polymer.dom(/** @type {!Event} */ (event)).localTarget)); }
diff --git a/chrome/browser/resources/settings/site_settings/site_data.js b/chrome/browser/resources/settings/site_settings/site_data.js index 64b8d93..690eaab 100644 --- a/chrome/browser/resources/settings/site_settings/site_data.js +++ b/chrome/browser/resources/settings/site_settings/site_data.js
@@ -119,8 +119,8 @@ */ onRemoveShowingSitesTap_: function(e) { e.preventDefault(); - this.confirmationDeleteMsg_ = loadTimeData.getString( - 'siteSettingsCookieRemoveMultipleConfirmation'); + this.confirmationDeleteMsg_ = + loadTimeData.getString('siteSettingsCookieRemoveMultipleConfirmation'); this.$.confirmDeleteDialog.showModal(); }, @@ -140,7 +140,7 @@ this.browserProxy.removeCookie(items[i].id); } // We just deleted all items found by the filter, let's reset the filter. - /** @type {SettingsSubpageSearchElement} */(this.$.filter).setValue(''); + /** @type {SettingsSubpageSearchElement} */ (this.$.filter).setValue(''); } }, @@ -159,7 +159,8 @@ * @private */ onSiteTap_: function(event) { - settings.navigateTo(settings.Route.SITE_SETTINGS_DATA_DETAILS, + settings.navigateTo( + settings.Route.SITE_SETTINGS_DATA_DETAILS, new URLSearchParams('site=' + event.model.item.site)); }, });
diff --git a/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js b/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js index ed83ad9..e01f9a8 100644 --- a/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js +++ b/chrome/browser/resources/settings/site_settings/site_data_details_subpage.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. (function() { - 'use strict'; +'use strict'; /** * 'site-data-details-subpage' Display cookie contents. @@ -45,8 +45,8 @@ this.browserProxy_ = settings.SiteSettingsPrefsBrowserProxyImpl.getInstance(); - this.addWebUIListener('onTreeItemRemoved', - this.getCookieDetails_.bind(this)); + this.addWebUIListener( + 'onTreeItemRemoved', this.getCookieDetails_.bind(this)); }, /** @@ -69,9 +69,10 @@ getCookieDetails_: function() { if (!this.site_) return; - this.browserProxy_.getCookieDetails(this.site_).then( - this.onCookiesLoaded_.bind(this), - this.onCookiesLoadFailed_.bind(this)); + this.browserProxy_.getCookieDetails(this.site_) + .then( + this.onCookiesLoaded_.bind(this), + this.onCookiesLoadFailed_.bind(this)); }, /** @@ -90,7 +91,9 @@ this.siteId_ = cookies.id; this.entries_ = cookies.children; // Set up flag for expanding cookie details. - this.entries_.forEach(function(e) { e.expanded_ = false; }); + this.entries_.forEach(function(e) { + e.expanded_ = false; + }); }, /** @@ -125,7 +128,7 @@ */ onRemove_: function(event) { this.browserProxy_.removeCookie( - /** @type {!CookieDetails} */(event.currentTarget.dataset).idPath); + /** @type {!CookieDetails} */ (event.currentTarget.dataset).idPath); }, /**
diff --git a/chrome/browser/resources/settings/site_settings/site_details.js b/chrome/browser/resources/settings/site_settings/site_details.js index d1022348..c75cfa7 100644 --- a/chrome/browser/resources/settings/site_settings/site_details.js +++ b/chrome/browser/resources/settings/site_settings/site_details.js
@@ -122,7 +122,9 @@ onClearAndReset_: function() { Array.prototype.forEach.call( this.root.querySelectorAll('site-details-permission'), - function(element) { element.resetPermission(); }); + function(element) { + element.resetPermission(); + }); if (this.storedData_ != '') this.onClearStorage_(); @@ -146,6 +148,8 @@ permissionShowing_: function() { return Array.prototype.some.call( this.root.querySelectorAll('site-details-permission'), - function(element) { return element.offsetHeight > 0; }); + function(element) { + return element.offsetHeight > 0; + }); }, });
diff --git a/chrome/browser/resources/settings/site_settings/site_details_permission.js b/chrome/browser/resources/settings/site_settings/site_details_permission.js index 5cb9947..17ca6c0 100644 --- a/chrome/browser/resources/settings/site_settings/site_details_permission.js +++ b/chrome/browser/resources/settings/site_settings/site_details_permission.js
@@ -24,7 +24,8 @@ /** @override */ attached: function() { - this.addWebUIListener('contentSettingSitePermissionChanged', + this.addWebUIListener( + 'contentSettingSitePermissionChanged', this.sitePermissionChanged_.bind(this)); }, @@ -53,16 +54,16 @@ */ siteChanged_: function(site) { - this.browserProxy.getExceptionList(this.category).then( - function(exceptionList) { - for (var i = 0; i < exceptionList.length; ++i) { - if (exceptionList[i].embeddingOrigin == site.embeddingOrigin && - this.sameOrigin_(exceptionList[i].origin, site.origin)) { - this.$.permission.value = exceptionList[i].setting; - break; - } - } - }.bind(this)); + this.browserProxy.getExceptionList(this.category) + .then(function(exceptionList) { + for (var i = 0; i < exceptionList.length; ++i) { + if (exceptionList[i].embeddingOrigin == site.embeddingOrigin && + this.sameOrigin_(exceptionList[i].origin, site.origin)) { + this.$.permission.value = exceptionList[i].setting; + break; + } + } + }.bind(this)); }, /** @@ -79,8 +80,9 @@ if (category != this.category) return; - if (origin == '' || (origin == this.site.origin && - embeddingOrigin == this.site.embeddingOrigin)) { + if (origin == '' || + (origin == this.site.origin && + embeddingOrigin == this.site.embeddingOrigin)) { this.siteChanged_(this.site); } },
diff --git a/chrome/browser/resources/settings/site_settings/site_list.js b/chrome/browser/resources/settings/site_settings/site_list.js index e95115fe7..eb5290fe 100644 --- a/chrome/browser/resources/settings/site_settings/site_list.js +++ b/chrome/browser/resources/settings/site_settings/site_list.js
@@ -110,10 +110,11 @@ /** @override */ ready: function() { - this.addWebUIListener('contentSettingSitePermissionChanged', + this.addWebUIListener( + 'contentSettingSitePermissionChanged', this.siteWithinCategoryChanged_.bind(this)); - this.addWebUIListener('onIncognitoStatusChanged', - this.onIncognitoStatusChanged_.bind(this)); + this.addWebUIListener( + 'onIncognitoStatusChanged', this.onIncognitoStatusChanged_.bind(this)); }, /** @@ -262,7 +263,7 @@ * @private */ toSiteArray_: function(sites) { - var results = /** @type {!Array<SiteException>} */([]); + var results = /** @type {!Array<SiteException>} */ ([]); var lastOrigin = ''; var lastEmbeddingOrigin = ''; for (var i = 0; i < sites.length; ++i) { @@ -313,7 +314,8 @@ onOriginTap_: function(event) { if (!this.enableSiteSettings_) return; - settings.navigateTo(settings.Route.SITE_SETTINGS_SITE_DETAILS, + settings.navigateTo( + settings.Route.SITE_SETTINGS_SITE_DETAILS, new URLSearchParams('site=' + event.model.item.origin)); }, @@ -361,8 +363,8 @@ onEditTap_: function() { // Close action menu without resetting |this.actionMenuSite_| since it is // bound to the dialog. - /** @type {!CrActionMenuElement} */ ( - this.$$('dialog[is=cr-action-menu]')).close(); + /** @type {!CrActionMenuElement} */ (this.$$('dialog[is=cr-action-menu]')) + .close(); this.showEditExceptionDialog_ = true; }, @@ -389,8 +391,8 @@ */ computeSiteDescription_: function(item) { if (item.incognito && item.embeddingDisplayName.length > 0) { - return loadTimeData.getStringF('embeddedIncognitoSite', - item.embeddingDisplayName); + return loadTimeData.getStringF( + 'embeddedIncognitoSite', item.embeddingDisplayName); } if (item.incognito) @@ -415,8 +417,8 @@ Polymer.dom(/** @type {!Event} */ (e)).localTarget); this.actionMenuSite_ = e.model.item; - /** @type {!CrActionMenuElement} */ ( - this.$$('dialog[is=cr-action-menu]')).showAt(this.activeDialogAnchor_); + /** @type {!CrActionMenuElement} */ (this.$$('dialog[is=cr-action-menu]')) + .showAt(this.activeDialogAnchor_); }, /** @private */
diff --git a/chrome/browser/resources/settings/site_settings/site_settings_behavior.js b/chrome/browser/resources/settings/site_settings/site_settings_behavior.js index 318bbd5..3b8f6442 100644 --- a/chrome/browser/resources/settings/site_settings/site_settings_behavior.js +++ b/chrome/browser/resources/settings/site_settings/site_settings_behavior.js
@@ -72,8 +72,7 @@ urlWithScheme.endsWith(':443')) { return url.slice(0, -4); } - if (urlWithScheme.startsWith('http://') && - urlWithScheme.endsWith(':80')) { + if (urlWithScheme.startsWith('http://') && urlWithScheme.endsWith(':80')) { return url.slice(0, -3); } return url;
diff --git a/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js b/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js index 82954ac..ecbd1c1 100644 --- a/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js +++ b/chrome/browser/resources/settings/site_settings/site_settings_prefs_browser_proxy.js
@@ -68,7 +68,7 @@ * @typedef {{protocol: string, * spec: string}} */ - var ProtocolHandlerEntry; +var ProtocolHandlerEntry; /** * @typedef {{name: string,
diff --git a/chrome/browser/resources/settings/site_settings/usb_devices.js b/chrome/browser/resources/settings/site_settings/usb_devices.js index a80fc6f21..28a4898 100644 --- a/chrome/browser/resources/settings/site_settings/usb_devices.js +++ b/chrome/browser/resources/settings/site_settings/usb_devices.js
@@ -71,8 +71,8 @@ */ showMenu_: function(event) { this.actionMenuModel_ = event.model.item; - /** @type {!CrActionMenuElement} */ ( - this.$$('dialog[is=cr-action-menu]')).showAt( + /** @type {!CrActionMenuElement} */ (this.$$('dialog[is=cr-action-menu]')) + .showAt( /** @type {!Element} */ ( Polymer.dom(/** @type {!Event} */ (event)).localTarget)); }
diff --git a/chrome/browser/resources/settings/site_settings/website_usage_private_api.js b/chrome/browser/resources/settings/site_settings/website_usage_private_api.js index 7be7520f..4540e26 100644 --- a/chrome/browser/resources/settings/site_settings/website_usage_private_api.js +++ b/chrome/browser/resources/settings/site_settings/website_usage_private_api.js
@@ -116,9 +116,11 @@ instance.notifyUsageDeleted(origin); }; - return { websiteUsagePolymerInstance: websiteUsagePolymerInstance, - fetchUsageTotal: fetchUsageTotal, - returnUsageTotal: returnUsageTotal, - clearUsage: clearUsage, - onUsageCleared: onUsageCleared, }; + return { + websiteUsagePolymerInstance: websiteUsagePolymerInstance, + fetchUsageTotal: fetchUsageTotal, + returnUsageTotal: returnUsageTotal, + clearUsage: clearUsage, + onUsageCleared: onUsageCleared, + }; });
diff --git a/chrome/browser/resources/settings/site_settings/zoom_levels.js b/chrome/browser/resources/settings/site_settings/zoom_levels.js index 362223a..850501b8 100644 --- a/chrome/browser/resources/settings/site_settings/zoom_levels.js +++ b/chrome/browser/resources/settings/site_settings/zoom_levels.js
@@ -23,8 +23,8 @@ /** @override */ ready: function() { - this.addWebUIListener('onZoomLevelsChanged', - this.onZoomLevelsChanged_.bind(this)); + this.addWebUIListener( + 'onZoomLevelsChanged', this.onZoomLevelsChanged_.bind(this)); this.browserProxy.fetchZoomLevels(); },
diff --git a/chrome/browser/resources/settings/site_settings_page/site_settings_page.js b/chrome/browser/resources/settings/site_settings_page/site_settings_page.js index 2640045b..ce8e6fd 100644 --- a/chrome/browser/resources/settings/site_settings_page/site_settings_page.js +++ b/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
@@ -38,7 +38,9 @@ /** @private */ isGuest_: { type: Boolean, - value: function() { return loadTimeData.getBoolean('isGuest'); } + value: function() { + return loadTimeData.getBoolean('isGuest'); + } }, /** @private */ @@ -70,31 +72,26 @@ // element, with additional entries that correspond to subpage trigger // elements residing in this element's Shadow DOM. var R = settings.Route; - [ - [R.SITE_SETTINGS_COOKIES, 'cookies'], - [R.SITE_SETTINGS_LOCATION, 'location'], - [R.SITE_SETTINGS_CAMERA, 'camera'], - [R.SITE_SETTINGS_MICROPHONE, 'microphone'], - [R.SITE_SETTINGS_NOTIFICATIONS, 'notifications'], - [R.SITE_SETTINGS_JAVASCRIPT,'javascript'], - [R.SITE_SETTINGS_FLASH,'flash'], - [R.SITE_SETTINGS_IMAGES,'images'], - [R.SITE_SETTINGS_POPUPS,'popups'], - [R.SITE_SETTINGS_BACKGROUND_SYNC,'background-sync'], - [R.SITE_SETTINGS_AUTOMATIC_DOWNLOADS,'automatic-downloads'], - [R.SITE_SETTINGS_UNSANDBOXED_PLUGINS,'unsandboxed-plugins'], - [R.SITE_SETTINGS_HANDLERS,'protocol-handlers'], - [R.SITE_SETTINGS_MIDI_DEVICES,'midi-devices'], - [R.SITE_SETTINGS_ADS,'ads'], - [R.SITE_SETTINGS_ZOOM_LEVELS,'zoom-levels'], - [R.SITE_SETTINGS_USB_DEVICES,'usb-devices'], - [R.SITE_SETTINGS_PDF_DOCUMENTS,'pdf-documents'], - [R.SITE_SETTINGS_PROTECTED_CONTENT,'protected-content'], + [[R.SITE_SETTINGS_COOKIES, 'cookies'], + [R.SITE_SETTINGS_LOCATION, 'location'], [R.SITE_SETTINGS_CAMERA, 'camera'], + [R.SITE_SETTINGS_MICROPHONE, 'microphone'], + [R.SITE_SETTINGS_NOTIFICATIONS, 'notifications'], + [R.SITE_SETTINGS_JAVASCRIPT, 'javascript'], + [R.SITE_SETTINGS_FLASH, 'flash'], [R.SITE_SETTINGS_IMAGES, 'images'], + [R.SITE_SETTINGS_POPUPS, 'popups'], + [R.SITE_SETTINGS_BACKGROUND_SYNC, 'background-sync'], + [R.SITE_SETTINGS_AUTOMATIC_DOWNLOADS, 'automatic-downloads'], + [R.SITE_SETTINGS_UNSANDBOXED_PLUGINS, 'unsandboxed-plugins'], + [R.SITE_SETTINGS_HANDLERS, 'protocol-handlers'], + [R.SITE_SETTINGS_MIDI_DEVICES, 'midi-devices'], + [R.SITE_SETTINGS_ADS, 'ads'], [R.SITE_SETTINGS_ZOOM_LEVELS, 'zoom-levels'], + [R.SITE_SETTINGS_USB_DEVICES, 'usb-devices'], + [R.SITE_SETTINGS_PDF_DOCUMENTS, 'pdf-documents'], + [R.SITE_SETTINGS_PROTECTED_CONTENT, 'protected-content'], ].forEach(function(pair) { var route = pair[0]; var id = pair[1]; - this.focusConfig.set( - route.path, '* /deep/ #' + id + ' .subpage-arrow'); + this.focusConfig.set(route.path, '* /deep/ #' + id + ' .subpage-arrow'); }.bind(this)); }, @@ -122,8 +119,7 @@ 'contentSettingCategoryChanged', this.updateDefaultValueLabel_.bind(this)); this.addWebUIListener( - 'setHandlersEnabled', - this.updateHandlersEnabled_.bind(this)); + 'setHandlersEnabled', this.updateHandlersEnabled_.bind(this)); this.browserProxy.observeProtocolHandlersEnabledState(); }, @@ -149,8 +145,8 @@ * @private */ updateDefaultValueLabel_: function(category) { - this.browserProxy.getDefaultValueForContentType( - category).then(function(defaultValue) { + this.browserProxy.getDefaultValueForContentType(category).then( + function(defaultValue) { this.set( 'default_.' + Polymer.CaseMap.dashToCamelCase(category), defaultValue.setting); @@ -166,9 +162,8 @@ var category = settings.ContentSettingsTypes.PROTOCOL_HANDLERS; this.set( 'default_.' + Polymer.CaseMap.dashToCamelCase(category), - enabled ? - settings.PermissionValues.ALLOW : - settings.PermissionValues.BLOCK); + enabled ? settings.PermissionValues.ALLOW : + settings.PermissionValues.BLOCK); }, /** @@ -177,7 +172,7 @@ * @private */ onTapNavigate_: function(event) { - var dataSet = /** @type {{route: string}} */(event.currentTarget.dataset); + var dataSet = /** @type {{route: string}} */ (event.currentTarget.dataset); settings.navigateTo(settings.Route[dataSet.route]); }, });
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc index 2d20c82..34605c3 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc
@@ -19,12 +19,14 @@ #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task_runner_util.h" #include "base/task_scheduler/post_task.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" -#include "chrome/common/channel_info.h" +#include "chrome/install_static/install_details.h" +#include "chrome/install_static/install_modes.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/version_info/version_info.h" #include "net/base/load_flags.h" @@ -40,21 +42,14 @@ namespace { base::FilePath::StringType CleanerTempDirectoryPrefix() { - base::FilePath::StringType common_prefix = FILE_PATH_LITERAL("ChromeCleaner"); - switch (chrome::GetChannel()) { - case version_info::Channel::UNKNOWN: - return common_prefix + FILE_PATH_LITERAL("_0_"); - case version_info::Channel::CANARY: - return common_prefix + FILE_PATH_LITERAL("_1_"); - case version_info::Channel::DEV: - return common_prefix + FILE_PATH_LITERAL("_2_"); - case version_info::Channel::BETA: - return common_prefix + FILE_PATH_LITERAL("_3_"); - case version_info::Channel::STABLE: - return common_prefix + FILE_PATH_LITERAL("_4_"); - } - NOTREACHED(); - return common_prefix + FILE_PATH_LITERAL("_0_"); + // Create a temporary directory name prefix like "ChromeCleaner_4_", where + // "Chrome" is the product name and the 4 refers to the install mode of the + // browser. + int install_mode = install_static::InstallDetails::Get().install_mode_index(); + return base::StringPrintf( + FILE_PATH_LITERAL("%" PRFilePath "%" PRFilePath "_%d_"), + install_static::kProductPathName, FILE_PATH_LITERAL("Cleaner"), + install_mode); } // Class that will attempt to download the Chrome Cleaner executable and call a
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu.cc b/chrome/browser/ui/ash/launcher/launcher_context_menu.cc index 82b7fdf..8df12d96 100644 --- a/chrome/browser/ui/ash/launcher/launcher_context_menu.cc +++ b/chrome/browser/ui/ash/launcher/launcher_context_menu.cc
@@ -13,6 +13,7 @@ #include "ash/shell_port.h" #include "ash/strings/grit/ash_strings.h" #include "ash/wallpaper/wallpaper_delegate.h" +#include "ash/wm/maximize_mode/maximize_mode_controller.h" #include "build/build_config.h" #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h" #include "chrome/browser/fullscreen.h" @@ -126,6 +127,12 @@ } ash::ShellPort::Get()->RecordUserMetricsAction( ash::UMA_CLOSE_THROUGH_CONTEXT_MENU); + if (ash::Shell::Get() + ->maximize_mode_controller() + ->IsMaximizeModeWindowManagerEnabled()) { + ash::ShellPort::Get()->RecordUserMetricsAction( + ash::UMA_TABLET_WINDOW_CLOSE_THROUGH_CONTXT_MENU); + } break; case MENU_PIN: if (controller_->IsAppPinned(item_.id.app_id))
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_bubble_controller.mm b/chrome/browser/ui/cocoa/bookmarks/bookmark_bubble_controller.mm index c2e0a4fd..7be4bd6 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_bubble_controller.mm +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_bubble_controller.mm
@@ -150,6 +150,11 @@ // We caught a close so we don't need to watch for the parent closing. bookmarkObserver_.reset(); [self notifyBubbleClosed]; + + // Force the field editor to resign the first responder so that it'll + // be removed from the view hierarchy and its delegate be set to nil. + [[self window] endEditingFor:nameTextField_]; + [super windowWillClose:notification]; } @@ -267,7 +272,7 @@ if (!textFieldEditor_) textFieldEditor_.reset([[DialogTextFieldEditor alloc] init]); - return textFieldEditor_.autorelease(); + return textFieldEditor_.get(); } // Shows the bookmark editor sheet for more advanced editing.
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_base_controller.h b/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_base_controller.h index 59145999..0c336eb 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_base_controller.h +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_base_controller.h
@@ -69,6 +69,8 @@ title:(const base::string16&)title configuration:(BookmarkEditor::Configuration)configuration; +- (void)windowWillClose:(NSNotification*)notification; + // Override to customize the touch bar. - (NSTouchBar*)makeTouchBar;
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.mm b/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.mm index f97970d..10b5c8b 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.mm +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.mm
@@ -82,17 +82,25 @@ [self bookmarkModel]->expanded_state_tracker()->GetExpandedNodes()]; } +- (void)windowWillClose:(NSNotification*)notification { + // Force the field editors to resign the first responder so that they'll + // be removed from the view hierarchy and its delegate be set to nil. + [[self window] endEditingFor:urlField_]; + [[self window] endEditingFor:nameTextField_]; + + [super windowWillClose:notification]; +} + - (id)windowWillReturnFieldEditor:(NSWindow*)sender toObject:(id)obj { if (obj == urlField_) { if (!urlFieldEditor_) urlFieldEditor_.reset([[DialogTextFieldEditor alloc] init]); - - return urlFieldEditor_.autorelease(); + return urlFieldEditor_.get(); } else if (obj == nameTextField_) { if (!nameFieldEditor_) nameFieldEditor_.reset([[DialogTextFieldEditor alloc] init]); - return nameFieldEditor_.autorelease(); + return nameFieldEditor_.get(); } return nil;
diff --git a/chrome/browser/ui/cocoa/browser_window_touch_bar.mm b/chrome/browser/ui/cocoa/browser_window_touch_bar.mm index be2cdf3..ca3b4aa 100644 --- a/chrome/browser/ui/cocoa/browser_window_touch_bar.mm +++ b/chrome/browser/ui/cocoa/browser_window_touch_bar.mm
@@ -275,7 +275,7 @@ IDS_TOUCH_BAR_STOP_RELOAD_CUSTOMIZATION_LABEL)]; } else if ([identifier hasSuffix:kHomeTouchId]) { [touchBarItem setView:CreateTouchBarButton(kNavigateHomeIcon, self, - IDC_HOME, IDS_TOOLTIP_HOME)]; + IDC_HOME, IDS_ACCNAME_HOME)]; [touchBarItem setCustomizationLabel:l10n_util::GetNSString( IDS_TOUCH_BAR_HOME_CUSTOMIZATION_LABEL)]; @@ -404,12 +404,11 @@ NSArray* segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute]; NSEnumerator* e = [segments objectEnumerator]; - [[e nextObject] accessibilitySetOverrideValue:l10n_util::GetNSString( - IDS_TOOLTIP_TOUCH_BAR_BACK) - forAttribute:NSAccessibilityTitleAttribute]; [[e nextObject] - accessibilitySetOverrideValue:l10n_util::GetNSString( - IDS_TOOLTIP_TOUCH_BAR_FORWARD) + accessibilitySetOverrideValue:l10n_util::GetNSString(IDS_ACCNAME_BACK) + forAttribute:NSAccessibilityTitleAttribute]; + [[e nextObject] + accessibilitySetOverrideValue:l10n_util::GetNSString(IDS_ACCNAME_FORWARD) forAttribute:NSAccessibilityTitleAttribute]; return control; }
diff --git a/chrome/browser/ui/cocoa/tab_contents/sad_tab_view_cocoa.mm b/chrome/browser/ui/cocoa/tab_contents/sad_tab_view_cocoa.mm index 8c9904a9..d841a098 100644 --- a/chrome/browser/ui/cocoa/tab_contents/sad_tab_view_cocoa.mm +++ b/chrome/browser/ui/cocoa/tab_contents/sad_tab_view_cocoa.mm
@@ -6,7 +6,6 @@ #import "base/mac/foundation_util.h" #include "components/grit/components_scaled_resources.h" -#import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h" #import "ui/base/cocoa/controls/blue_label_button.h" #import "ui/base/cocoa/controls/hyperlink_text_view.h" #include "ui/base/l10n/l10n_util_mac.h" @@ -18,6 +17,8 @@ const CGFloat kMaxContainerWidth = 600; // Padding between icon and title. const CGFloat kIconTitleSpacing = 40; +// Space between lines of the title. +const CGFloat kTitleLineSpacing = 6; // Padding between title and message. const CGFloat kTitleMessageSpacing = 18; // Padding between message and link. @@ -29,16 +30,6 @@ // Maximum margin on top. const CGFloat kMaxTopMargin = 130; -NSTextField* MakeLabelTextField(NSRect frame) { - // Not a scoped_nsobject for easy property access. - NSTextField* ret = [[[NSTextField alloc] initWithFrame:frame] autorelease]; - ret.autoresizingMask = NSViewWidthSizable; - ret.editable = NO; - ret.drawsBackground = NO; - ret.bezeled = NO; - return ret; -} - } // namespace @interface SadTabContainerView : NSView @@ -55,7 +46,7 @@ @implementation SadTabView { NSView* container_; - NSTextField* message_; + NSTextView* message_; HyperlinkTextView* help_; NSButton* button_; chrome::SadTab* sadTab_; @@ -78,34 +69,74 @@ icon.frameSize = iconImage.size; [container_ addSubview:icon]; - NSTextField* title = MakeLabelTextField( - NSMakeRect(0, NSMaxY(icon.frame) + kIconTitleSpacing, 0, 0)); - title.font = [NSFont systemFontOfSize:24]; - title.textColor = - [NSColor colorWithCalibratedWhite:38.0f / 255.0f alpha:1.0]; + message_ = [[[NSTextView alloc] + initWithFrame:NSMakeRect(0, NSMaxY(icon.frame) + kIconTitleSpacing, + NSWidth(container_.bounds), 0)] autorelease]; + message_.editable = NO; + message_.drawsBackground = NO; + message_.autoresizingMask = NSViewWidthSizable; - NSMutableParagraphStyle* titleStyle = - [[NSMutableParagraphStyle new] autorelease]; - titleStyle.lineSpacing = 6; - title.attributedStringValue = [[[NSAttributedString alloc] - initWithString:l10n_util::GetNSString(sadTab->GetTitle()) - attributes:@{NSParagraphStyleAttributeName : titleStyle}] - autorelease]; - - [title sizeToFit]; - [container_ addSubview:title]; + NSMutableParagraphStyle* titleParagraphStyle = + [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; + titleParagraphStyle.lineSpacing = kTitleLineSpacing; + titleParagraphStyle.paragraphSpacing = + kTitleMessageSpacing - kTitleLineSpacing; + [message_.textStorage + appendAttributedString: + [[[NSAttributedString alloc] + initWithString:[NSString + stringWithFormat:@"%@\n", + l10n_util::GetNSString( + sadTab->GetTitle())] + attributes:@{ + NSParagraphStyleAttributeName : titleParagraphStyle, + NSFontAttributeName : [NSFont systemFontOfSize:24], + NSForegroundColorAttributeName : + [NSColor colorWithCalibratedWhite:38.0f / 255.0f + alpha:1.0], + }] autorelease]]; NSFont* messageFont = [NSFont systemFontOfSize:14]; NSColor* messageColor = [NSColor colorWithCalibratedWhite:81.0f / 255.0f alpha:1.0]; + [message_.textStorage + appendAttributedString:[[[NSAttributedString alloc] + initWithString:l10n_util::GetNSString( + sadTab->GetMessage()) + attributes:@{ + NSFontAttributeName : messageFont, + NSForegroundColorAttributeName : + messageColor, + }] autorelease]]; - message_ = MakeLabelTextField(NSMakeRect(0, NSMaxY(title.frame), 0, 0)); - message_.frameOrigin = - NSMakePoint(0, NSMaxY(title.frame) + kTitleMessageSpacing); - base::mac::ObjCCast<NSCell>(message_.cell).wraps = YES; - message_.font = messageFont; - message_.textColor = messageColor; - message_.stringValue = l10n_util::GetNSString(sadTab->GetMessage()); + if (int subMessage = sadTab->GetSubMessage(0)) { + NSTextList* textList = + [[[NSTextList alloc] initWithMarkerFormat:@"{disc}" options:0] + autorelease]; + NSMutableParagraphStyle* paragraphStyle = + [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; + paragraphStyle.textLists = @[ textList ]; + paragraphStyle.paragraphSpacingBefore = messageFont.capHeight; + paragraphStyle.headIndent = + static_cast<NSTextTab*>(paragraphStyle.tabStops[1]).location; + + NSMutableString* subMessageString = [NSMutableString string]; + for (int i = 0; subMessage; subMessage = sadTab->GetSubMessage(++i)) { + [subMessageString appendFormat:@"\n\t%@\t%@", + [textList markerForItemNumber:i], + l10n_util::GetNSString(subMessage)]; + } + [message_.textStorage + appendAttributedString:[[[NSAttributedString alloc] + initWithString:subMessageString + attributes:@{ + NSParagraphStyleAttributeName : + paragraphStyle, + NSFontAttributeName : messageFont, + NSForegroundColorAttributeName : + messageColor, + }] autorelease]]; + } [container_ addSubview:message_]; NSString* helpLinkTitle = @@ -162,9 +193,6 @@ // Set the container's size first because text wrapping depends on its width. container_.frameSize = containerSize; - // |message_| can wrap to variable number of lines. - [GTMUILocalizerAndLayoutTweaker sizeToFitFixedWidthTextField:message_]; - help_.frameOrigin = NSMakePoint(0, NSMaxY(message_.frame) + kMessageLinkSpacing);
diff --git a/chrome/browser/ui/webui/chromeos/login/OWNERS b/chrome/browser/ui/webui/chromeos/login/OWNERS index e7a8a06..675ddd2 100644 --- a/chrome/browser/ui/webui/chromeos/login/OWNERS +++ b/chrome/browser/ui/webui/chromeos/login/OWNERS
@@ -1,2 +1,3 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org
diff --git a/chrome/browser/win/enumerate_modules_model.cc b/chrome/browser/win/enumerate_modules_model.cc index d466e28..84e8df2b 100644 --- a/chrome/browser/win/enumerate_modules_model.cc +++ b/chrome/browser/win/enumerate_modules_model.cc
@@ -35,9 +35,9 @@ #include "base/time/time.h" #include "base/values.h" #include "base/version.h" -#include "base/win/registry.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" +#include "chrome/browser/conflicts/shell_extension_enumerator_win.h" #include "chrome/browser/net/service_providers_win.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/crash_keys.h" @@ -47,10 +47,6 @@ using content::BrowserThread; -// The path to the Shell Extension key in the Windows registry. -static const wchar_t kRegPath[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"; - // A sort method that sorts by bad modules first, then by full name (including // path). static bool ModuleSort(const ModuleEnumerator::Module& a, @@ -310,34 +306,18 @@ } void ModuleEnumerator::EnumerateShellExtensions() { - ReadShellExtensions(HKEY_LOCAL_MACHINE); - ReadShellExtensions(HKEY_CURRENT_USER); + // The callback is executed synchronously, so the use of base::Unretained is + // safe. + ShellExtensionEnumerator::EnumerateShellExtensionPaths(base::Bind( + &ModuleEnumerator::OnShellExtensionEnumerated, base::Unretained(this))); } -void ModuleEnumerator::ReadShellExtensions(HKEY parent) { - base::win::RegistryValueIterator registration(parent, kRegPath); - while (registration.Valid()) { - std::wstring key(std::wstring(L"CLSID\\") + registration.Name() + - L"\\InProcServer32"); - base::win::RegKey clsid; - if (clsid.Open(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) != ERROR_SUCCESS) { - ++registration; - continue; - } - base::string16 dll; - if (clsid.ReadValue(L"", &dll) != ERROR_SUCCESS) { - ++registration; - continue; - } - clsid.Close(); - - Module entry; - entry.type = SHELL_EXTENSION; - entry.location = dll; - AddToListWithoutDuplicating(entry); - - ++registration; - } +void ModuleEnumerator::OnShellExtensionEnumerated( + const base::FilePath& shell_extension) { + Module entry; + entry.type = SHELL_EXTENSION; + entry.location = shell_extension.value(); + AddToListWithoutDuplicating(entry); } void ModuleEnumerator::EnumerateWinsockModules() {
diff --git a/chrome/browser/win/enumerate_modules_model.h b/chrome/browser/win/enumerate_modules_model.h index 7be732e..12a5041 100644 --- a/chrome/browser/win/enumerate_modules_model.h +++ b/chrome/browser/win/enumerate_modules_model.h
@@ -159,15 +159,13 @@ // entries in |enumerated_modules_| with a populated |location| field. void EnumerateShellExtensions(); + // Callback for ShellExtensionEnumerator::EnumerateShellExtensionPaths(). + void OnShellExtensionEnumerated(const base::FilePath& shell_extension); + // Enumerate all registered Winsock LSP modules. Creates empty // entries in |enumerated_modules_| with a populated |location| field. void EnumerateWinsockModules(); - // Reads the registered shell extensions found under |parent| key in the - // registry. Creates empty entries in |enumerated_modules_| with a populated - // |location| field. - void ReadShellExtensions(HKEY parent); - // Given a |module|, initializes the structure and loads additional // information using the location field of the module. void PopulateModuleInformation(Module* module);
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index f7d26ea..82dca27 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3035,6 +3035,7 @@ "../browser/conflicts/module_info_util_win_unittest.cc", "../browser/conflicts/module_info_win_unittest.cc", "../browser/conflicts/module_inspector_win_unittest.cc", + "../browser/conflicts/shell_extension_enumerator_win_unittest.cc", "../browser/content_settings/content_settings_default_provider_unittest.cc", "../browser/content_settings/content_settings_mock_observer.cc", "../browser/content_settings/content_settings_mock_observer.h",
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.cc b/chrome/test/chromedriver/chrome/web_view_impl.cc index d11a7fb6..4ecadf92 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl.cc
@@ -442,7 +442,8 @@ base::DictionaryValue params; std::unique_ptr<base::DictionaryValue> result; - if (browser_info_->build_no >= 3029) { + if (browser_info_->build_no >= 3029 && + browser_info_->browser_name != "webview") { base::ListValue url_list; url_list.AppendString(current_page_url); params.Set("urls", base::MakeUnique<base::Value>(url_list));
diff --git a/chrome/test/chromedriver/test/test_expectations b/chrome/test/chromedriver/test/test_expectations index 8223607..b3f3954c 100644 --- a/chrome/test/chromedriver/test/test_expectations +++ b/chrome/test/chromedriver/test/test_expectations
@@ -273,10 +273,6 @@ # TODO(gmanikpure): re-enable this test when we stop supporting # WebView on KitKat. 'ClickTest.testCanClickAnImageMapArea', - # The WebView shell that we test against (on Kitkat) does not yet - # support Network.getCookies DevTools command. - # TODO(gmanikpure): reenable when it does. - 'ObjectStateAssumptionsTest.testOptionsForUninitializedWebDriver', ] )
diff --git a/chromeos/login/OWNERS b/chromeos/login/OWNERS index 5539f89..8f195fe 100644 --- a/chromeos/login/OWNERS +++ b/chromeos/login/OWNERS
@@ -1,4 +1,5 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org piman@chromium.org xiyuan@chromium.org
diff --git a/components/login/OWNERS b/components/login/OWNERS index 5539f89..8f195fe 100644 --- a/components/login/OWNERS +++ b/components/login/OWNERS
@@ -1,4 +1,5 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org piman@chromium.org xiyuan@chromium.org
diff --git a/components/ntp_tiles/webui/ntp_tiles_internals_message_handler.cc b/components/ntp_tiles/webui/ntp_tiles_internals_message_handler.cc index fb06ccd1..098e715 100644 --- a/components/ntp_tiles/webui/ntp_tiles_internals_message_handler.cc +++ b/components/ntp_tiles/webui/ntp_tiles_internals_message_handler.cc
@@ -256,9 +256,12 @@ FaviconResultMap::key_type(tile.url, entry.type_enum)); if (it != result_map.end()) { + const favicon_base::FaviconRawBitmapResult& result = it->second; auto icon = base::MakeUnique<base::DictionaryValue>(); - icon->SetString("url", it->second.icon_url.spec()); + icon->SetString("url", result.icon_url.spec()); icon->SetString("type", entry.type_name); + icon->SetInteger("width", result.pixel_size.width()); + icon->SetInteger("height", result.pixel_size.height()); icon_list->Append(std::move(icon)); } }
diff --git a/components/ntp_tiles/webui/resources/ntp_tiles_internals.html b/components/ntp_tiles/webui/resources/ntp_tiles_internals.html index 691c43f..d97edb82 100644 --- a/components/ntp_tiles/webui/resources/ntp_tiles_internals.html +++ b/components/ntp_tiles/webui/resources/ntp_tiles_internals.html
@@ -124,7 +124,8 @@ </tr> <tr jsselect="icons"> <td class="detail" jscontent="type"></td> - <td class="value" jscontent="url"></td> + <td class="value"><a jsvalues="href:url" + jscontent="url + ' (' + width + 'x' + height + ')'"></a></td> </tr> </tbody> </table>
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index 773dac1d..e635a07 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -83,6 +83,9 @@ "password_bubble_experiment.h", "password_form_manager.cc", "password_form_manager.h", + "password_form_metrics_recorder.cc", + "password_form_metrics_recorder.h", + "password_form_user_action.h", "password_generation_manager.cc", "password_generation_manager.h", "password_manager.cc", @@ -310,6 +313,7 @@ "password_autofill_manager_unittest.cc", "password_bubble_experiment_unittest.cc", "password_form_manager_unittest.cc", + "password_form_metrics_recorder_unittest.cc", "password_generation_manager_unittest.cc", "password_manager_settings_migration_experiment_unittest.cc", "password_manager_unittest.cc",
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 98100d2..d38e2279 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -215,21 +215,19 @@ ? SplitPathToSegments(observed_form_.origin.path()) : std::vector<std::string>()), is_new_login_(true), + has_autofilled_(false), has_generated_password_(false), is_manual_generation_(false), generation_popup_was_shown_(false), form_classifier_outcome_(kNoOutcome), password_overridden_(false), retry_password_form_password_update_(false), - generation_available_(false), password_manager_(password_manager), preferred_match_(nullptr), is_possible_change_password_form_without_username_( observed_form.IsPossibleChangePasswordFormWithoutUsername()), client_(client), - manager_action_(kManagerActionNone), - user_action_(kUserActionNone), - submit_result_(kSubmitResultNotSubmitted), + user_action_(UserAction::kNone), form_type_(kFormTypeUnspecified), form_saver_(std::move(form_saver)), owned_form_fetcher_( @@ -240,7 +238,8 @@ true /* should_migrate_http_passwords */, true /* should_query_suppressed_https_forms */)), form_fetcher_(form_fetcher ? form_fetcher : owned_form_fetcher_.get()), - is_main_frame_secure_(client->IsMainFrameSecure()) { + is_main_frame_secure_(client->IsMainFrameSecure()), + metrics_recorder_(client->IsMainFrameSecure()) { if (owned_form_fetcher_) owned_form_fetcher_->Fetch(); DCHECK_EQ(observed_form.scheme == PasswordForm::SCHEME_HTML, @@ -253,28 +252,8 @@ PasswordFormManager::~PasswordFormManager() { form_fetcher_->RemoveConsumer(this); - UMA_HISTOGRAM_ENUMERATION("PasswordManager.ActionsTakenV3", GetActionsTaken(), - kMaxNumActionsTaken); - - // Use the visible main frame URL at the time the PasswordFormManager - // is created, in case a navigation has already started and the - // visible URL has changed. - if (!is_main_frame_secure_) { - UMA_HISTOGRAM_ENUMERATION("PasswordManager.ActionsTakenOnNonSecureForm", - GetActionsTaken(), kMaxNumActionsTaken); - } - RecordHistogramsOnSuppressedAccounts(); - if (submit_result_ == kSubmitResultNotSubmitted) { - if (has_generated_password_) - metrics_util::LogPasswordGenerationSubmissionEvent( - metrics_util::PASSWORD_NOT_SUBMITTED); - else if (generation_available_) - metrics_util::LogPasswordGenerationAvailableSubmissionEvent( - metrics_util::PASSWORD_NOT_SUBMITTED); - } - if (form_type_ != kFormTypeUnspecified) { UMA_HISTOGRAM_ENUMERATION("PasswordManager.SubmittedFormType", form_type_, kFormTypeMax); @@ -285,12 +264,6 @@ } } -int PasswordFormManager::GetActionsTaken() const { - return user_action_ + - kUserActionMax * - (manager_action_ + kManagerActionMax * submit_result_); -} - int PasswordFormManager::GetHistogramSampleForSuppressedAccounts( const std::vector<const autofill::PasswordForm*> suppressed_forms, PasswordForm::Type manual_or_generated) const { @@ -314,19 +287,11 @@ best_matching_account = std::max(best_matching_account, current_account); } - // Merge kManagerActionNone and kManagerActionBlacklisted_Obsolete. This - // lowers the number of histogram buckets used by 33%. - ManagerActionNew manager_action_new = - (manager_action_ == kManagerActionAutofilled) - ? kManagerActionNewAutofilled - : kManagerActionNewNone; - // Encoding: most significant digit is the |best_matching_account|. int mixed_base_encoding = 0; mixed_base_encoding += best_matching_account; - (mixed_base_encoding *= kSubmitResultMax) += submit_result_; - (mixed_base_encoding *= kManagerActionNewMax) += manager_action_new; - (mixed_base_encoding *= kUserActionMax) += user_action_; + mixed_base_encoding *= PasswordFormMetricsRecorder::kMaxNumActionsTakenNew; + mixed_base_encoding += metrics_recorder_.GetActionsTakenNew(); DCHECK_LT(mixed_base_encoding, kMaxSuppressedAccountStats); return mixed_base_encoding; } @@ -510,9 +475,9 @@ metrics_util::LogPasswordAcceptedSaveUpdateSubmissionIndicatorEvent( submitted_form_->submission_event); - if ((user_action_ == kUserActionNone) && + if ((user_action_ == UserAction::kNone) && DidPreferenceChange(best_matches_, pending_credentials_.username_value)) { - SetUserAction(kUserActionChoose); + SetUserAction(UserAction::kChoose); } base::Optional<PasswordForm> old_primary_key; if (is_new_login_) { @@ -723,9 +688,12 @@ preferred_match_->is_public_suffix_match || observed_form_.IsPossibleChangePasswordForm(); if (wait_for_username) { - manager_action_ = kManagerActionNone; + metrics_recorder_.SetManagerAction( + PasswordFormMetricsRecorder::kManagerActionNone); } else { - manager_action_ = kManagerActionAutofilled; + has_autofilled_ = true; + metrics_recorder_.SetManagerAction( + PasswordFormMetricsRecorder::kManagerActionAutofilled); base::RecordAction(base::UserMetricsAction("PasswordManager_Autofilled")); } if (ShouldShowInitialPasswordAccountSuggestions()) { @@ -750,7 +718,9 @@ if (!preferred_match_) return; - manager_action_ = kManagerActionAutofilled; + has_autofilled_ = true; + metrics_recorder_.SetManagerAction( + PasswordFormMetricsRecorder::kManagerActionAutofilled); password_manager_->AutofillHttpAuth(best_matches_, *preferred_match_); } @@ -1017,8 +987,8 @@ // from Android apps store a copy with the current origin and signon // realm. This ensures that on the next visit, a precise match is found. is_new_login_ = true; - SetUserAction(password_overridden_ ? kUserActionOverridePassword - : kUserActionChoosePslMatch); + SetUserAction(password_overridden_ ? UserAction::kOverridePassword + : UserAction::kChoosePslMatch); // Since this credential will not overwrite a previously saved credential, // username_value can be updated now. @@ -1068,7 +1038,7 @@ } else { // Not a PSL match. is_new_login_ = false; if (password_overridden_) - SetUserAction(kUserActionOverridePassword); + SetUserAction(UserAction::kOverridePassword); } } else if (other_possible_username_action_ == ALLOW_OTHER_POSSIBLE_USERNAMES && @@ -1135,7 +1105,7 @@ pending_credentials_.signon_realm = submitted_form_->signon_realm; } - if (user_action_ == kUserActionOverridePassword && + if (user_action_ == UserAction::kOverridePassword && pending_credentials_.type == PasswordForm::TYPE_GENERATED && !has_generated_password_) { metrics_util::LogPasswordGenerationSubmissionEvent( @@ -1278,7 +1248,7 @@ void PasswordFormManager::CreatePendingCredentialsForNewCredentials() { // User typed in a new, unknown username. - SetUserAction(kUserActionOverrideUsernameAndPassword); + SetUserAction(UserAction::kOverrideUsernameAndPassword); pending_credentials_ = observed_form_; if (submitted_form_->was_parsed_using_autofill_predictions) pending_credentials_.username_element = submitted_form_->username_element; @@ -1319,30 +1289,21 @@ } } +void PasswordFormManager::SetHasGeneratedPassword(bool generated_password) { + has_generated_password_ = generated_password; + metrics_recorder_.SetHasGeneratedPassword(generated_password); +} + void PasswordFormManager::LogSubmitPassed() { - if (submit_result_ != kSubmitResultFailed) { - if (has_generated_password_) { - metrics_util::LogPasswordGenerationSubmissionEvent( - metrics_util::PASSWORD_SUBMITTED); - } else if (generation_available_) { - metrics_util::LogPasswordGenerationAvailableSubmissionEvent( - metrics_util::PASSWORD_SUBMITTED); - } - } - base::RecordAction(base::UserMetricsAction("PasswordManager_LoginPassed")); - submit_result_ = kSubmitResultPassed; + metrics_recorder_.LogSubmitPassed(); } void PasswordFormManager::LogSubmitFailed() { - if (has_generated_password_) { - metrics_util::LogPasswordGenerationSubmissionEvent( - metrics_util::GENERATED_PASSWORD_FORCE_SAVED); - } else if (generation_available_) { - metrics_util::LogPasswordGenerationAvailableSubmissionEvent( - metrics_util::PASSWORD_SUBMISSION_FAILED); - } - base::RecordAction(base::UserMetricsAction("PasswordManager_LoginFailed")); - submit_result_ = kSubmitResultFailed; + metrics_recorder_.LogSubmitFailed(); +} + +void PasswordFormManager::MarkGenerationAvailable() { + metrics_recorder_.MarkGenerationAvailable(); } void PasswordFormManager::WipeStoreCopyIfOutdated() { @@ -1430,22 +1391,8 @@ } void PasswordFormManager::SetUserAction(UserAction user_action) { - if (user_action == kUserActionChoose) { - base::RecordAction( - base::UserMetricsAction("PasswordManager_UsedNonDefaultUsername")); - } else if (user_action == kUserActionChoosePslMatch) { - base::RecordAction( - base::UserMetricsAction("PasswordManager_ChoseSubdomainPassword")); - } else if (user_action == kUserActionOverridePassword) { - base::RecordAction( - base::UserMetricsAction("PasswordManager_LoggedInWithNewPassword")); - } else if (user_action == kUserActionOverrideUsernameAndPassword) { - base::RecordAction( - base::UserMetricsAction("PasswordManager_LoggedInWithNewUsername")); - } else { - NOTREACHED(); - } user_action_ = user_action; + metrics_recorder_.SetUserAction(user_action); } base::Optional<PasswordForm> PasswordFormManager::UpdatePendingAndGetOldKey(
diff --git a/components/password_manager/core/browser/password_form_manager.h b/components/password_manager/core/browser/password_form_manager.h index 2bc3bb2..0eac86b3 100644 --- a/components/password_manager/core/browser/password_form_manager.h +++ b/components/password_manager/core/browser/password_form_manager.h
@@ -21,6 +21,8 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/form_fetcher.h" +#include "components/password_manager/core/browser/password_form_metrics_recorder.h" +#include "components/password_manager/core/browser/password_form_user_action.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_store.h" @@ -154,9 +156,7 @@ // These functions are used to determine if this form has had it's password // auto generated by the browser. bool has_generated_password() const { return has_generated_password_; } - void set_has_generated_password(bool generated_password) { - has_generated_password_ = generated_password; - } + void SetHasGeneratedPassword(bool generated_password); bool is_manual_generation() { return is_manual_generation_; } void set_is_manual_generation(bool is_manual_generation) { @@ -182,7 +182,7 @@ } // Called if the user could generate a password for this form. - void MarkGenerationAvailable() { generation_available_ = true; } + void MarkGenerationAvailable(); // Returns the provisionally saved form, if it exists, otherwise nullptr. const autofill::PasswordForm* submitted_form() const { @@ -261,50 +261,6 @@ size_t filtered_count) override; private: - // ManagerAction - What does the manager do with this form? Either it - // fills it, or it doesn't. If it doesn't fill it, that's either - // because it has no match or it is disabled via the AUTOCOMPLETE=off - // attribute. Note that if we don't have an exact match, we still provide - // candidates that the user may end up choosing. - enum ManagerAction { - kManagerActionNone = 0, - kManagerActionAutofilled, - kManagerActionBlacklisted_Obsolete, - kManagerActionMax - }; - - // Same as above, without the obsoleted 'Blacklisted' action. - enum ManagerActionNew { - kManagerActionNewNone, - kManagerActionNewAutofilled, - kManagerActionNewMax - }; - - // UserAction - What does the user do with this form? If they do nothing - // (either by accepting what the password manager did, or by simply (not - // typing anything at all), you get None. If there were multiple choices and - // the user selects one other than the default, you get Choose, if user - // selects an entry from matching against the Public Suffix List you get - // ChoosePslMatch, if the user types in a new value for just the password you - // get OverridePassword, and if the user types in a new value for the - // username and password you get OverrideUsernameAndPassword. - enum UserAction { - kUserActionNone = 0, - kUserActionChoose, - kUserActionChoosePslMatch, - kUserActionOverridePassword, - kUserActionOverrideUsernameAndPassword, - kUserActionMax - }; - - // Result - What happens to the form? - enum SubmitResult { - kSubmitResultNotSubmitted = 0, - kSubmitResultFailed, - kSubmitResultPassed, - kSubmitResultMax - }; - // What the form is used for. kFormTypeUnspecified is only set before // the SetSubmittedForm() is called, and should never be actually uploaded. enum FormType { @@ -327,11 +283,6 @@ kFoundGenerationElement }; - // The maximum number of combinations of the three preceding enums. - // This is used when recording the actions taken by the form in UMA. - static const int kMaxNumActionsTaken = - kManagerActionMax * kUserActionMax * kSubmitResultMax; - // Enumerates whether there were `suppressed` credentials. These are stored // credentials that were not filled, even though they might be related to the // |observed_form_|. See FormFetcher::GetSuppressed* for details. @@ -353,8 +304,10 @@ // The maximum number of combinations recorded into histograms in the // PasswordManager.SuppressedAccount.* family. static constexpr int kMaxSuppressedAccountStats = - kSuppressedAccountExistenceMax * kManagerActionNewMax * kUserActionMax * - kSubmitResultMax; + kSuppressedAccountExistenceMax * + PasswordFormMetricsRecorder::kManagerActionNewMax * + static_cast<int>(UserAction::kMax) * + PasswordFormMetricsRecorder::kSubmitResultMax; // Through |driver|, supply the associated frame with appropriate information // (fill data, whether to allow password generation, etc.). @@ -426,10 +379,6 @@ bool UpdatePendingCredentialsIfUsernameChanged( const autofill::PasswordForm& form); - // Converts the "ActionsTaken" fields into an int so they can be logged to - // UMA. - int GetActionsTaken() const; - // When supplied with the list of all |suppressed_forms| that belong to // certain suppressed credential type (see FormFetcher::GetSuppressed*), // filters that list down to forms that are either |manual_or_generated|, and @@ -561,6 +510,9 @@ // to an existing one. bool is_new_login_; + // Whether the form was autofilled with credentials. + bool has_autofilled_; + // Whether this form has an auto generated password. bool has_generated_password_; @@ -590,9 +542,6 @@ // and it was entered on a retry password form. bool retry_password_form_password_update_; - // Whether the user can choose to generate a password for this form. - bool generation_available_; - // Set if the user has selected one of the other possible usernames in // |pending_credentials_|. base::string16 selected_username_; @@ -626,12 +575,9 @@ // the filling information when needed. std::vector<base::WeakPtr<PasswordManagerDriver>> drivers_; - // These three fields record the "ActionsTaken" by the browser and - // the user with this form, and the result. They are combined and - // recorded in UMA when the manager is destroyed. - ManagerAction manager_action_; + // Records the action the user has taken while interacting with the password + // form. UserAction user_action_; - SubmitResult submit_result_; // Form type of the form that |this| is managing. Set after SetSubmittedForm() // as our classification of the form can change depending on what data the @@ -652,6 +598,9 @@ // was created, is secure. bool is_main_frame_secure_ = false; + // Takes care of recording metrics and events for this PasswordFormManager. + PasswordFormMetricsRecorder metrics_recorder_; + DISALLOW_COPY_AND_ASSIGN(PasswordFormManager); };
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index e4ed9f70..51de9de7 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -655,7 +655,7 @@ : form.password_element; form_manager.set_generation_element(generation_element); form_manager.set_generation_popup_was_shown(true); - form_manager.set_has_generated_password(has_generated_password); + form_manager.SetHasGeneratedPassword(has_generated_password); // Figure out expected generation event type. autofill::AutofillUploadContents::Field::PasswordGenerationType @@ -768,7 +768,7 @@ if (manager_action != SimulatedManagerAction::NONE) matches.push_back(&http_stored_form); - // Extra mile: kUserActionChoose is only recorded if there were multiple + // Extra mile: kChoose is only recorded if there were multiple // logins available and the preferred one was changed. PasswordForm http_stored_form2 = http_stored_form; if (manager_action == SimulatedManagerAction::OFFERED) { @@ -2529,7 +2529,7 @@ TEST_F(PasswordFormManagerTest, TestSavingOnChangePasswordFormGenerationNoStoredForms) { fake_form_fetcher()->SetNonFederated(std::vector<const PasswordForm*>(), 0u); - form_manager()->set_has_generated_password(true); + form_manager()->SetHasGeneratedPassword(true); // User submits change password form and there is no stored credentials. PasswordForm credentials = *observed_form(); @@ -2564,7 +2564,7 @@ TEST_F(PasswordFormManagerTest, TestUpdatingOnChangePasswordFormGeneration) { fake_form_fetcher()->SetNonFederated({saved_match()}, 0u); - form_manager()->set_has_generated_password(true); + form_manager()->SetHasGeneratedPassword(true); // User submits credentials for the change password form, and old password is // coincide with password from an existing credentials, so stored credentials @@ -2600,7 +2600,7 @@ TEST_F(PasswordFormManagerTest, TestSavingOnChangePasswordFormGenerationNoMatchedForms) { fake_form_fetcher()->SetNonFederated({saved_match()}, 0u); - form_manager()->set_has_generated_password(true); + form_manager()->SetHasGeneratedPassword(true); // User submits credentials for the change password form, and old password is // not coincide with password from existing credentials, so new credentials
diff --git a/components/password_manager/core/browser/password_form_metrics_recorder.cc b/components/password_manager/core/browser/password_form_metrics_recorder.cc new file mode 100644 index 0000000..0ee2b61 --- /dev/null +++ b/components/password_manager/core/browser/password_form_metrics_recorder.cc
@@ -0,0 +1,119 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/password_manager/core/browser/password_form_metrics_recorder.h" + +#include "base/logging.h" +#include "base/metrics/histogram_macros.h" +#include "base/metrics/user_metrics.h" +#include "components/password_manager/core/browser/password_manager_metrics_util.h" + +namespace password_manager { + +PasswordFormMetricsRecorder::PasswordFormMetricsRecorder( + bool is_main_frame_secure) + : is_main_frame_secure_(is_main_frame_secure) {} + +PasswordFormMetricsRecorder::~PasswordFormMetricsRecorder() { + UMA_HISTOGRAM_ENUMERATION("PasswordManager.ActionsTakenV3", GetActionsTaken(), + kMaxNumActionsTaken); + + // Use the visible main frame URL at the time the PasswordFormManager + // is created, in case a navigation has already started and the + // visible URL has changed. + if (!is_main_frame_secure_) { + UMA_HISTOGRAM_ENUMERATION("PasswordManager.ActionsTakenOnNonSecureForm", + GetActionsTaken(), kMaxNumActionsTaken); + } + + if (submit_result_ == kSubmitResultNotSubmitted) { + if (has_generated_password_) { + metrics_util::LogPasswordGenerationSubmissionEvent( + metrics_util::PASSWORD_NOT_SUBMITTED); + } else if (generation_available_) { + metrics_util::LogPasswordGenerationAvailableSubmissionEvent( + metrics_util::PASSWORD_NOT_SUBMITTED); + } + } +} + +void PasswordFormMetricsRecorder::MarkGenerationAvailable() { + generation_available_ = true; +} + +void PasswordFormMetricsRecorder::SetHasGeneratedPassword( + bool has_generated_password) { + has_generated_password_ = has_generated_password; +} + +void PasswordFormMetricsRecorder::SetManagerAction( + ManagerAction manager_action) { + manager_action_ = manager_action; +} + +void PasswordFormMetricsRecorder::SetUserAction(UserAction user_action) { + if (user_action == UserAction::kChoose) { + base::RecordAction( + base::UserMetricsAction("PasswordManager_UsedNonDefaultUsername")); + } else if (user_action == UserAction::kChoosePslMatch) { + base::RecordAction( + base::UserMetricsAction("PasswordManager_ChoseSubdomainPassword")); + } else if (user_action == UserAction::kOverridePassword) { + base::RecordAction( + base::UserMetricsAction("PasswordManager_LoggedInWithNewPassword")); + } else if (user_action == UserAction::kOverrideUsernameAndPassword) { + base::RecordAction( + base::UserMetricsAction("PasswordManager_LoggedInWithNewUsername")); + } else { + NOTREACHED(); + } + user_action_ = user_action; +} + +void PasswordFormMetricsRecorder::LogSubmitPassed() { + if (submit_result_ != kSubmitResultFailed) { + if (has_generated_password_) { + metrics_util::LogPasswordGenerationSubmissionEvent( + metrics_util::PASSWORD_SUBMITTED); + } else if (generation_available_) { + metrics_util::LogPasswordGenerationAvailableSubmissionEvent( + metrics_util::PASSWORD_SUBMITTED); + } + } + base::RecordAction(base::UserMetricsAction("PasswordManager_LoginPassed")); + submit_result_ = kSubmitResultPassed; +} + +void PasswordFormMetricsRecorder::LogSubmitFailed() { + if (has_generated_password_) { + metrics_util::LogPasswordGenerationSubmissionEvent( + metrics_util::GENERATED_PASSWORD_FORCE_SAVED); + } else if (generation_available_) { + metrics_util::LogPasswordGenerationAvailableSubmissionEvent( + metrics_util::PASSWORD_SUBMISSION_FAILED); + } + base::RecordAction(base::UserMetricsAction("PasswordManager_LoginFailed")); + submit_result_ = kSubmitResultFailed; +} + +int PasswordFormMetricsRecorder::GetActionsTakenNew() const { + // Merge kManagerActionNone and kManagerActionBlacklisted_Obsolete. This + // lowers the number of histogram buckets used by 33%. + ManagerActionNew manager_action_new = + (manager_action_ == kManagerActionAutofilled) + ? kManagerActionNewAutofilled + : kManagerActionNewNone; + + return static_cast<int>(user_action_) + + static_cast<int>(UserAction::kMax) * + (manager_action_new + kManagerActionNewMax * submit_result_); +} + +int PasswordFormMetricsRecorder::GetActionsTaken() const { + return static_cast<int>(user_action_) + + static_cast<int>(UserAction::kMax) * + (manager_action_ + kManagerActionMax * submit_result_); +} + +} // namespace password_manager
diff --git a/components/password_manager/core/browser/password_form_metrics_recorder.h b/components/password_manager/core/browser/password_form_metrics_recorder.h new file mode 100644 index 0000000..cf15972 --- /dev/null +++ b/components/password_manager/core/browser/password_form_metrics_recorder.h
@@ -0,0 +1,107 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_METRICS_RECORDER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_METRICS_RECORDER_H_ + +#include "base/macros.h" + +#include "components/password_manager/core/browser/password_form_user_action.h" + +namespace password_manager { + +// The pupose of this class is to record various types of metrics about the +// behavior of the PasswordFormManager and its interaction with the user and the +// page. +class PasswordFormMetricsRecorder { + public: + explicit PasswordFormMetricsRecorder(bool is_main_frame_secure); + ~PasswordFormMetricsRecorder(); + + // ManagerAction - What does the PasswordFormManager do with this form? Either + // it fills it, or it doesn't. If it doesn't fill it, that's either + // because it has no match or it is disabled via the AUTOCOMPLETE=off + // attribute. Note that if we don't have an exact match, we still provide + // candidates that the user may end up choosing. + enum ManagerAction { + kManagerActionNone = 0, + kManagerActionAutofilled, + kManagerActionBlacklisted_Obsolete, + kManagerActionMax + }; + + // Same as above without the obsoleted 'Blacklisted' action. + enum ManagerActionNew { + kManagerActionNewNone = 0, + kManagerActionNewAutofilled, + kManagerActionNewMax + }; + + // Result - What happens to the form? + enum SubmitResult { + kSubmitResultNotSubmitted = 0, + kSubmitResultFailed, + kSubmitResultPassed, + kSubmitResultMax + }; + + // The maximum number of combinations of the ManagerAction, UserAction and + // SubmitResult enums. + // This is used when recording the actions taken by the form in UMA. + static constexpr int kMaxNumActionsTaken = + kManagerActionMax * static_cast<int>(UserAction::kMax) * kSubmitResultMax; + + // Same as above but for ManagerActionNew instead of ManagerAction. + static constexpr int kMaxNumActionsTakenNew = + kManagerActionNewMax * static_cast<int>(UserAction::kMax) * + kSubmitResultMax; + + // Called if the user could generate a password for this form. + void MarkGenerationAvailable(); + + // Stores whether the form has had its password auto generated by the browser. + void SetHasGeneratedPassword(bool has_generated_password); + + // Stores the password manager and user actions and logs them. + void SetManagerAction(ManagerAction manager_action); + void SetUserAction(UserAction user_action); + + // Call these if/when we know the form submission worked or failed. + // These routines are used to update internal statistics ("ActionsTaken"). + void LogSubmitPassed(); + void LogSubmitFailed(); + + // Converts the "ActionsTaken" fields (using ManagerActionNew) into an int so + // they can be logged to UMA. + // TODO(battre): This should not be public. + int GetActionsTakenNew() const; + + private: + // Converts the "ActionsTaken" fields into an int so they can be logged to + // UMA. + int GetActionsTaken() const; + + // True if the main frame's visible URL, at the time this PasswordFormManager + // was created, is secure. + const bool is_main_frame_secure_; + + // Whether the user can choose to generate a password for this form. + bool generation_available_ = false; + + // Whether this form has an auto generated password. + bool has_generated_password_ = false; + + // These three fields record the "ActionsTaken" by the browser and + // the user with this form, and the result. They are combined and + // recorded in UMA when the PasswordFormMetricsRecorder is destroyed. + ManagerAction manager_action_ = kManagerActionNone; + UserAction user_action_ = UserAction::kNone; + SubmitResult submit_result_ = kSubmitResultNotSubmitted; + + DISALLOW_COPY_AND_ASSIGN(PasswordFormMetricsRecorder); +}; + +} // namespace password_manager + +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_METRICS_RECORDER_H_
diff --git a/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc b/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc new file mode 100644 index 0000000..30da6b4 --- /dev/null +++ b/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc
@@ -0,0 +1,264 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/password_manager/core/browser/password_form_metrics_recorder.h" + +#include "base/logging.h" +#include "base/test/histogram_tester.h" +#include "base/test/user_action_tester.h" +#include "components/password_manager/core/browser/password_manager_metrics_util.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace password_manager { + +// Test the metrics recorded around password generation and the user's +// interaction with the offer to generate passwords. +TEST(PasswordFormMetricsRecorder, Generation) { + static constexpr struct { + bool generation_available; + bool has_generated_password; + PasswordFormMetricsRecorder::SubmitResult submission; + } kTests[] = { + {false, false, PasswordFormMetricsRecorder::kSubmitResultNotSubmitted}, + {true, false, PasswordFormMetricsRecorder::kSubmitResultNotSubmitted}, + {true, true, PasswordFormMetricsRecorder::kSubmitResultNotSubmitted}, + {false, false, PasswordFormMetricsRecorder::kSubmitResultFailed}, + {true, false, PasswordFormMetricsRecorder::kSubmitResultFailed}, + {true, true, PasswordFormMetricsRecorder::kSubmitResultFailed}, + {false, false, PasswordFormMetricsRecorder::kSubmitResultPassed}, + {true, false, PasswordFormMetricsRecorder::kSubmitResultPassed}, + {true, true, PasswordFormMetricsRecorder::kSubmitResultPassed}, + }; + + for (const auto& test : kTests) { + SCOPED_TRACE(testing::Message() + << "generation_available=" << test.generation_available + << ", has_generated_password=" << test.has_generated_password + << ", submission" << test.submission); + + base::HistogramTester histogram_tester; + base::UserActionTester user_action_tester; + + // Use a scoped PasswordFromMetricsRecorder because some metrics are recored + // on destruction. + { + PasswordFormMetricsRecorder recorder(/*is_main_frame_secure*/ true); + if (test.generation_available) + recorder.MarkGenerationAvailable(); + recorder.SetHasGeneratedPassword(test.has_generated_password); + switch (test.submission) { + case PasswordFormMetricsRecorder::kSubmitResultNotSubmitted: + // Do nothing. + break; + case PasswordFormMetricsRecorder::kSubmitResultFailed: + recorder.LogSubmitFailed(); + break; + case PasswordFormMetricsRecorder::kSubmitResultPassed: + recorder.LogSubmitPassed(); + break; + case PasswordFormMetricsRecorder::kSubmitResultMax: + NOTREACHED(); + } + } + + EXPECT_EQ( + test.submission == PasswordFormMetricsRecorder::kSubmitResultFailed ? 1 + : 0, + user_action_tester.GetActionCount("PasswordManager_LoginFailed")); + + EXPECT_EQ( + test.submission == PasswordFormMetricsRecorder::kSubmitResultPassed ? 1 + : 0, + user_action_tester.GetActionCount("PasswordManager_LoginPassed")); + + if (test.has_generated_password) { + switch (test.submission) { + case PasswordFormMetricsRecorder::kSubmitResultNotSubmitted: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionEvent", + metrics_util::PASSWORD_NOT_SUBMITTED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultFailed: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionEvent", + metrics_util::GENERATED_PASSWORD_FORCE_SAVED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultPassed: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionEvent", + metrics_util::PASSWORD_SUBMITTED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultMax: + NOTREACHED(); + } + } + + if (!test.has_generated_password && test.generation_available) { + switch (test.submission) { + case PasswordFormMetricsRecorder::kSubmitResultNotSubmitted: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionAvailableEvent", + metrics_util::PASSWORD_NOT_SUBMITTED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultFailed: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionAvailableEvent", + metrics_util::PASSWORD_SUBMISSION_FAILED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultPassed: + histogram_tester.ExpectBucketCount( + "PasswordGeneration.SubmissionAvailableEvent", + metrics_util::PASSWORD_SUBMITTED, 1); + break; + case PasswordFormMetricsRecorder::kSubmitResultMax: + NOTREACHED(); + } + } + } +} + +// Test the recording of metrics around manager_action, user_action, and +// submit_result. +TEST(PasswordFormMetricsRecorder, Actions) { + static constexpr const struct { + // Stimuli: + bool is_main_frame_secure; + PasswordFormMetricsRecorder::ManagerAction manager_action; + UserAction user_action; + PasswordFormMetricsRecorder::SubmitResult submit_result; + // Expectations: + // Histogram bucket for PasswordManager.ActionsTakenV3 and + // PasswordManager.ActionsTakenOnNonSecureForm. + int32_t actions_taken; + // Result of GetActionsTakenNew. + int32_t actions_taken_new; + } kTests[] = { + // Test values of manager_action. + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kNone /*0*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 0, 0}, + {true, PasswordFormMetricsRecorder::kManagerActionAutofilled /*1*/, + UserAction::kNone /*0*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 5, 5}, + // Test values of user_action. + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kChoose /*1*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 1, 1}, + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kChoosePslMatch /*2*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 2, 2}, + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kOverridePassword /*3*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 3, 3}, + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kOverrideUsernameAndPassword /*4*/, + PasswordFormMetricsRecorder::kSubmitResultNotSubmitted /*0*/, 4, 4}, + // Test values of submit_result. + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kNone /*0*/, + PasswordFormMetricsRecorder::kSubmitResultFailed /*1*/, 15, 10}, + {true, PasswordFormMetricsRecorder::kManagerActionNone /*0*/, + UserAction::kNone /*0*/, + PasswordFormMetricsRecorder::kSubmitResultPassed /*2*/, 30, 20}, + // Test combination. + {true, PasswordFormMetricsRecorder::kManagerActionAutofilled /*1*/, + UserAction::kOverrideUsernameAndPassword /*4*/, + PasswordFormMetricsRecorder::kSubmitResultFailed /*2*/, 24, 19}, + // Test non-secure form. + {false, PasswordFormMetricsRecorder::kManagerActionAutofilled /*1*/, + UserAction::kOverrideUsernameAndPassword /*4*/, + PasswordFormMetricsRecorder::kSubmitResultFailed /*2*/, 24, 19}, + }; + + for (const auto& test : kTests) { + SCOPED_TRACE(testing::Message() + << "is_main_frame_secure=" << test.is_main_frame_secure + << ", manager_action=" << test.manager_action + << ", user_action" << static_cast<int>(test.user_action) + << ", submit_result=" << test.submit_result); + + base::HistogramTester histogram_tester; + base::UserActionTester user_action_tester; + + // Use a scoped PasswordFromMetricsRecorder because some metrics are recored + // on destruction. + { + PasswordFormMetricsRecorder recorder(test.is_main_frame_secure); + + recorder.SetManagerAction(test.manager_action); + if (test.user_action != UserAction::kNone) + recorder.SetUserAction(test.user_action); + if (test.submit_result == + PasswordFormMetricsRecorder::kSubmitResultFailed) { + recorder.LogSubmitFailed(); + } else if (test.submit_result == + PasswordFormMetricsRecorder::kSubmitResultPassed) { + recorder.LogSubmitPassed(); + } + + EXPECT_EQ(test.actions_taken_new, recorder.GetActionsTakenNew()); + } + + EXPECT_THAT( + histogram_tester.GetAllSamples("PasswordManager.ActionsTakenV3"), + ::testing::ElementsAre(base::Bucket(test.actions_taken, 1))); + if (!test.is_main_frame_secure) { + EXPECT_THAT(histogram_tester.GetAllSamples( + "PasswordManager.ActionsTakenOnNonSecureForm"), + ::testing::ElementsAre(base::Bucket(test.actions_taken, 1))); + } + + switch (test.user_action) { + case UserAction::kNone: + break; + case UserAction::kChoose: + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_UsedNonDefaultUsername")); + break; + case UserAction::kChoosePslMatch: + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_ChoseSubdomainPassword")); + break; + case UserAction::kOverridePassword: + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_LoggedInWithNewPassword")); + break; + case UserAction::kOverrideUsernameAndPassword: + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_LoggedInWithNewUsername")); + break; + case UserAction::kMax: + break; + } + } +} + +// Test that in the case of a sequence of user actions, only the last one is +// recorded in ActionsV3 but all are recorded as UMA user actions. +TEST(PasswordFormMetricsRecorder, ActionSequence) { + base::HistogramTester histogram_tester; + base::UserActionTester user_action_tester; + + // Use a scoped PasswordFromMetricsRecorder because some metrics are recored + // on destruction. + { + PasswordFormMetricsRecorder recorder(/*is_main_frame_secure*/ true); + recorder.SetManagerAction( + PasswordFormMetricsRecorder::kManagerActionAutofilled); + recorder.SetUserAction(UserAction::kChoosePslMatch); + recorder.SetUserAction(UserAction::kOverrideUsernameAndPassword); + recorder.LogSubmitPassed(); + } + + EXPECT_THAT(histogram_tester.GetAllSamples("PasswordManager.ActionsTakenV3"), + ::testing::ElementsAre(base::Bucket(39, 1))); + + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_ChoseSubdomainPassword")); + EXPECT_EQ(1, user_action_tester.GetActionCount( + "PasswordManager_LoggedInWithNewUsername")); +} + +} // namespace password_manager
diff --git a/components/password_manager/core/browser/password_form_user_action.h b/components/password_manager/core/browser/password_form_user_action.h new file mode 100644 index 0000000..0665dabf --- /dev/null +++ b/components/password_manager/core/browser/password_form_user_action.h
@@ -0,0 +1,30 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_USER_ACTION_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_USER_ACTION_H_ + +namespace password_manager { + +// UserAction - What does the user do with a form? +enum class UserAction { + // User did nothing, either by accepting what the password manager did, or by + // simply not typing anything at all. + kNone = 0, + // There were multiple choices and the user selected a different one than the + // default. + kChoose, + // The user selected an entry that originated from matching the form against + // the Public Suffix List. + kChoosePslMatch, + // User typed a new value just for the password. + kOverridePassword, + // User typed a new value for the username and the password. + kOverrideUsernameAndPassword, + kMax +}; + +} // namespace password_manager + +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_USER_ACTION_H_
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 804aa5d..1c6d8f7 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -212,7 +212,7 @@ if (form_manager) { if (!password_is_generated) form_manager->form_saver()->RemovePresavedPassword(); - form_manager->set_has_generated_password(password_is_generated); + form_manager->SetHasGeneratedPassword(password_is_generated); return; }
diff --git a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.cc b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.cc index 9235395..f8b3ac67 100644 --- a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.cc +++ b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.cc
@@ -61,6 +61,10 @@ base::OnTaskRunnerDeleter(io_task_runner_)), client_(client) { DCHECK(handle->IsInMainFrame()); + + CheckCurrentUrl(); + // Check added to investigate crbug.com/733099. + CHECK(!database_client_ || !check_results_.empty()); } SubresourceFilterSafeBrowsingActivationThrottle:: @@ -85,22 +89,22 @@ content::NavigationThrottle::ThrottleCheckResult SubresourceFilterSafeBrowsingActivationThrottle::WillStartRequest() { - CheckCurrentUrl(); + will_start_request_called_ = true; return content::NavigationThrottle::ThrottleCheckResult::PROCEED; } content::NavigationThrottle::ThrottleCheckResult SubresourceFilterSafeBrowsingActivationThrottle::WillRedirectRequest() { CheckCurrentUrl(); + // Check added to investigate crbug.com/733099. + CHECK(!database_client_ || !check_results_.empty()); return content::NavigationThrottle::ThrottleCheckResult::PROCEED; } content::NavigationThrottle::ThrottleCheckResult SubresourceFilterSafeBrowsingActivationThrottle::WillProcessResponse() { - // Non-null |database_client_| implies that by this time we have made a - // database request. This is guaranteed because with a valid - // |database_client_|, we always populate |check_results_| in - // WillStartRequest. + // Checks added to investigate crbug.com/733099. + CHECK(will_start_request_called_); CHECK(!database_client_ || !check_results_.empty()); // No need to defer the navigation if the check already happened.
diff --git a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.h b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.h index 885e4e3e..774ec62 100644 --- a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.h +++ b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_activation_throttle.h
@@ -94,6 +94,9 @@ // WillProcessResponse. If deferral was not necessary, will remain null. base::TimeTicks defer_time_; + // Added to investigate crbug.com/733099. + bool will_start_request_called_ = false; + DISALLOW_COPY_AND_ASSIGN(SubresourceFilterSafeBrowsingActivationThrottle); };
diff --git a/content/browser/download/download_stats.cc b/content/browser/download/download_stats.cc index d008996c..1289d61 100644 --- a/content/browser/download/download_stats.cc +++ b/content/browser/download/download_stats.cc
@@ -640,8 +640,8 @@ DOWNLOAD_IMAGE_MAX); } -DownloadContent DownloadContentFromMimeType( - const std::string& mime_type_string) { +DownloadContent DownloadContentFromMimeType(const std::string& mime_type_string, + bool record_image_type) { DownloadContent download_content = DOWNLOAD_CONTENT_UNRECOGNIZED; // Look up exact matches. @@ -661,7 +661,8 @@ } else if (base::StartsWith(mime_type_string, "image/", base::CompareCase::SENSITIVE)) { download_content = DOWNLOAD_CONTENT_IMAGE; - RecordDownloadImageType(mime_type_string); + if (record_image_type) + RecordDownloadImageType(mime_type_string); } else if (base::StartsWith(mime_type_string, "audio/", base::CompareCase::SENSITIVE)) { download_content = DOWNLOAD_CONTENT_AUDIO; @@ -678,15 +679,16 @@ void RecordDownloadMimeType(const std::string& mime_type_string) { UMA_HISTOGRAM_ENUMERATION("Download.Start.ContentType", - DownloadContentFromMimeType(mime_type_string), + DownloadContentFromMimeType(mime_type_string, true), DOWNLOAD_CONTENT_MAX); } void RecordDownloadMimeTypeForNormalProfile( const std::string& mime_type_string) { - UMA_HISTOGRAM_ENUMERATION("Download.Start.ContentType.NormalProfile", - DownloadContentFromMimeType(mime_type_string), - DOWNLOAD_CONTENT_MAX); + UMA_HISTOGRAM_ENUMERATION( + "Download.Start.ContentType.NormalProfile", + DownloadContentFromMimeType(mime_type_string, false), + DOWNLOAD_CONTENT_MAX); } void RecordDownloadContentDisposition(
diff --git a/content/public/common/bindings_policy.h b/content/public/common/bindings_policy.h index 8ae87d2f..f7b2f92 100644 --- a/content/public/common/bindings_policy.h +++ b/content/public/common/bindings_policy.h
@@ -32,12 +32,6 @@ // normal web contents and are intended only for use with WebUI and layout // tests. BINDINGS_POLICY_MOJO = 1 << 3, - // Bindings that allows main world JS content within a HeadlessWebContents to - // access the headless::TabSocket API. - BINDINGS_POLICY_HEADLESS_MAIN_WORLD = 1 << 4, - // Similar to BINDINGS_POLICY_HEADLESS_MAIN_WORLD except it's intended allow - // access only from within DevTools created isolated worlds. - BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD = 1 << 5, }; }
diff --git a/content/public/renderer/render_frame.h b/content/public/renderer/render_frame.h index e9f20c0..2b2c8c8 100644 --- a/content/public/renderer/render_frame.h +++ b/content/public/renderer/render_frame.h
@@ -93,10 +93,7 @@ RECORD_DECISION = 1 }; - // Returns the RenderFrame given a WebFrame. - // TODO(https://crbug.com/416660): Remove this, as RenderFrames only - // correspond to WebLocalFrames. - static RenderFrame* FromWebFrame(blink::WebFrame* web_frame); + // Returns the RenderFrame given a WebLocalFrame. static RenderFrame* FromWebFrame(blink::WebLocalFrame* web_frame); // Returns the RenderFrame given a routing id.
diff --git a/content/renderer/media/media_stream_video_track.cc b/content/renderer/media/media_stream_video_track.cc index cc7fc9af..d23adb2d 100644 --- a/content/renderer/media/media_stream_video_track.cc +++ b/content/renderer/media/media_stream_video_track.cc
@@ -396,6 +396,7 @@ if (width_ && height_) { settings.width = width_; settings.height = height_; + settings.aspect_ratio = static_cast<double>(width_) / height_; } // 0.0 means the track is using the source's frame rate.
diff --git a/content/renderer/media/webmediaplayer_ms.cc b/content/renderer/media/webmediaplayer_ms.cc index e7be5e048..a9471b0 100644 --- a/content/renderer/media/webmediaplayer_ms.cc +++ b/content/renderer/media/webmediaplayer_ms.cc
@@ -36,6 +36,7 @@ #include "third_party/WebKit/public/platform/WebMediaPlayerSource.h" #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/platform/WebSize.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" namespace content { @@ -141,7 +142,7 @@ }; WebMediaPlayerMS::WebMediaPlayerMS( - blink::WebFrame* frame, + blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, media::WebMediaPlayerDelegate* delegate, std::unique_ptr<media::MediaLog> media_log,
diff --git a/content/renderer/media/webmediaplayer_ms.h b/content/renderer/media/webmediaplayer_ms.h index ff31d9ed..8fc8a04e 100644 --- a/content/renderer/media/webmediaplayer_ms.h +++ b/content/renderer/media/webmediaplayer_ms.h
@@ -22,7 +22,7 @@ #include "url/origin.h" namespace blink { -class WebFrame; +class WebLocalFrame; class WebMediaPlayerClient; class WebSecurityOrigin; class WebString; @@ -70,7 +70,7 @@ // a MediaStreamClient which provides MediaStreamVideoRenderer. // |delegate| must not be null. WebMediaPlayerMS( - blink::WebFrame* frame, + blink::WebLocalFrame* frame, blink::WebMediaPlayerClient* client, media::WebMediaPlayerDelegate* delegate, std::unique_ptr<media::MediaLog> media_log, @@ -199,7 +199,7 @@ // Getter method to |client_|. blink::WebMediaPlayerClient* get_client() { return client_; } - blink::WebFrame* const frame_; + blink::WebLocalFrame* const frame_; blink::WebMediaPlayer::NetworkState network_state_; blink::WebMediaPlayer::ReadyState ready_state_;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 5049df8..d4f284f8 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -1090,11 +1090,6 @@ } // static -RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) { - return RenderFrameImpl::FromWebFrame(web_frame); -} - -// static RenderFrame* RenderFrame::FromWebFrame(blink::WebLocalFrame* web_frame) { return RenderFrameImpl::FromWebFrame(web_frame); } @@ -6442,17 +6437,12 @@ } void RenderFrameImpl::MaybeEnableMojoBindings() { - // BINDINGS_POLICY_WEB_UI, BINDINGS_POLICY_MOJO, - // BINDINGS_POLICY_HEADLESS_MAIN_WORLD and - // BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD are mutually exclusive. They - // provide access to Mojo bindings, but do so in incompatible ways. - const int kAllBindingsTypes = BINDINGS_POLICY_WEB_UI | BINDINGS_POLICY_MOJO | - BINDINGS_POLICY_HEADLESS_MAIN_WORLD | - BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD; + // BINDINGS_POLICY_WEB_UI and BINDINGS_POLICY_MOJO are mutually exclusive. + // They provide access to Mojo bindings, but do so in incompatible ways. + const int kAllBindingsTypes = BINDINGS_POLICY_WEB_UI | BINDINGS_POLICY_MOJO; - // Make sure that at most one of BINDINGS_POLICY_WEB_UI, BINDINGS_POLICY_MOJO - // BINDINGS_POLICY_HEADLESS_MAIN_WORLD and - // BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD have been set. + // Make sure that at most one of BINDINGS_POLICY_WEB_UI and + // BINDINGS_POLICY_MOJO have been set. // NOTE x & (x - 1) == 0 is true iff x is zero or a power of two. DCHECK_EQ((enabled_bindings_ & kAllBindingsTypes) & ((enabled_bindings_ & kAllBindingsTypes) - 1),
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 6c6c3133..8e9dc57 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -815,7 +815,7 @@ "<iframe src='data:text/html,frame 2'></iframe>"); WebFrame* web_frame = frame()->GetWebFrame(); TestRenderFrame* child_frame = static_cast<TestRenderFrame*>( - RenderFrame::FromWebFrame(web_frame->FirstChild())); + RenderFrame::FromWebFrame(web_frame->FirstChild()->ToWebLocalFrame())); // Swap the child frame out and pass a replicated origin to be set for // WebRemoteFrame. @@ -836,8 +836,9 @@ // Now, swap out the second frame using a unique origin and verify that it is // replicated correctly. replication_state.origin = url::Origin(); - TestRenderFrame* child_frame2 = static_cast<TestRenderFrame*>( - RenderFrame::FromWebFrame(web_frame->FirstChild()->NextSibling())); + TestRenderFrame* child_frame2 = + static_cast<TestRenderFrame*>(RenderFrame::FromWebFrame( + web_frame->FirstChild()->NextSibling()->ToWebLocalFrame())); child_frame2->SwapOut(kProxyRoutingId + 1, true, replication_state); EXPECT_TRUE(web_frame->FirstChild()->NextSibling()->IsWebRemoteFrame()); EXPECT_TRUE( @@ -856,7 +857,7 @@ LoadHTML("Hello <iframe src='data:text/html,frame 1'></iframe>"); WebFrame* web_frame = frame()->GetWebFrame(); TestRenderFrame* child_frame = static_cast<TestRenderFrame*>( - RenderFrame::FromWebFrame(web_frame->FirstChild())); + RenderFrame::FromWebFrame(web_frame->FirstChild()->ToWebLocalFrame())); // Swap the child frame out. FrameReplicationState replication_state =
diff --git a/content/shell/renderer/layout_test/blink_test_runner.cc b/content/shell/renderer/layout_test/blink_test_runner.cc index 91d0cfab..20585331 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.cc +++ b/content/shell/renderer/layout_test/blink_test_runner.cc
@@ -767,7 +767,7 @@ SchedulerRunIdleTasks(callback); } -void BlinkTestRunner::ForceTextInputStateUpdate(WebFrame* frame) { +void BlinkTestRunner::ForceTextInputStateUpdate(WebLocalFrame* frame) { ForceTextInputStateUpdateForRenderFrame(RenderFrame::FromWebFrame(frame)); }
diff --git a/content/shell/renderer/layout_test/blink_test_runner.h b/content/shell/renderer/layout_test/blink_test_runner.h index 1bcb91a..ee74488 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.h +++ b/content/shell/renderer/layout_test/blink_test_runner.h
@@ -30,7 +30,6 @@ namespace blink { class MotionData; class OrientationData; -class WebFrame; class WebURLRequest; class WebView; } @@ -161,7 +160,7 @@ const blink::WebPluginParams& params) override; float GetDeviceScaleFactor() const override; void RunIdleTasks(const base::Closure& callback) override; - void ForceTextInputStateUpdate(blink::WebFrame* frame) override; + void ForceTextInputStateUpdate(blink::WebLocalFrame* frame) override; bool IsNavigationInitiatedByRenderer( const blink::WebURLRequest& request) override;
diff --git a/content/shell/test_runner/text_input_controller.cc b/content/shell/test_runner/text_input_controller.cc index eb8637b9..672c7e419 100644 --- a/content/shell/test_runner/text_input_controller.cc +++ b/content/shell/test_runner/text_input_controller.cc
@@ -322,8 +322,11 @@ } void TextInputController::ForceTextInputStateUpdate() { + CHECK(view()->MainFrame()->IsWebLocalFrame()) + << "WebView does not have a local main frame and" + " cannot handle input method controller tasks."; web_view_test_proxy_base_->delegate()->ForceTextInputStateUpdate( - view()->MainFrame()); + view()->MainFrame()->ToWebLocalFrame()); } blink::WebView* TextInputController::view() { @@ -335,12 +338,15 @@ if (!view()->MainFrame()) return nullptr; - blink::WebLocalFrame* mainFrame = view()->MainFrame()->ToWebLocalFrame(); - if (!mainFrame) { - CHECK(false) << "WebView does not have a local main frame and" - " cannot handle input method controller tasks."; - } - return mainFrame->FrameWidget()->GetActiveWebInputMethodController(); + CHECK(view()->MainFrame()->IsWebLocalFrame()) + << "WebView does not have a local main frame and" + " cannot handle input method controller tasks."; + + return view() + ->MainFrame() + ->ToWebLocalFrame() + ->FrameWidget() + ->GetActiveWebInputMethodController(); } } // namespace test_runner
diff --git a/content/shell/test_runner/web_test_delegate.h b/content/shell/test_runner/web_test_delegate.h index fdb1606..1bd00de 100644 --- a/content/shell/test_runner/web_test_delegate.h +++ b/content/shell/test_runner/web_test_delegate.h
@@ -23,7 +23,6 @@ } namespace blink { -class WebFrame; class WebInputEvent; class WebLocalFrame; class WebMediaStream; @@ -295,7 +294,7 @@ // Forces a text input state update for the client of WebFrameWidget // associated with |frame|. - virtual void ForceTextInputStateUpdate(blink::WebFrame* frame) = 0; + virtual void ForceTextInputStateUpdate(blink::WebLocalFrame* frame) = 0; // PlzNavigate // Indicates if the navigation was initiated by the browser or renderer.
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index c230f4f..92a3a2d 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -64,8 +64,3 @@ ['mac', ('intel', 0x0a2e)], bug=718183) self.Fail('Pixel_WebGLGreenTriangle_NonChromiumImage_NoAA_NoAlpha', ['mac', ('intel', 0x0a2e)], bug=718183) - - self.Flaky('Pixel_OffscreenCanvasTransferBeforeStyleResize', - ['mac', 'linux', 'win', 'android'], bug=720188) - self.Flaky('Pixel_OffscreenCanvasTransferAfterStyleResize', - ['mac', 'linux', 'win', 'android'], bug=719144)
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index 8748000..ba3e731 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -296,6 +296,13 @@ ['win', 'passthrough', 'd3d11'], bug=602688) self.Fail('conformance2/reading/read-pixels-from-fbo-test.html', ['win', 'passthrough', 'd3d11'], bug=602688) + self.Skip('conformance2/textures/misc/' + + 'copy-texture-image-webgl-specific.html', + ['win', 'passthrough', 'd3d11'], bug=602688) + self.Skip('conformance2/reading/read-pixels-pack-parameters.html', + ['win', 'passthrough', 'd3d11'], bug=602688) + self.Skip('conformance2/reading/read-pixels-into-pixel-pack-buffer.html', + ['win', 'passthrough', 'd3d11'], bug=602688) self.Fail('conformance2/textures/misc/' + 'tex-image-with-bad-args-from-dom-elements.html',
diff --git a/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc b/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc index 191f117..38dd713 100644 --- a/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc +++ b/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc
@@ -265,7 +265,7 @@ params->SetBoolean(guest_view::kElementSizeIsLogical, true); content::RenderFrame* embedder_parent_frame = - content::RenderFrame::FromWebFrame(parent_frame); + content::RenderFrame::FromWebFrame(parent_frame->ToWebLocalFrame()); // Create a GuestViewContainer if it does not exist. // An element instance ID uniquely identifies an IframeGuestViewContainer
diff --git a/headless/BUILD.gn b/headless/BUILD.gn index 4f30755..637b026 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn
@@ -109,6 +109,12 @@ ] } +mojom("headless_render_frame_controller") { + sources = [ + "lib/headless_render_frame_controller.mojom", + ] +} + grit("resources") { source = "lib/resources/headless_lib_resources.grd" outputs = [ @@ -120,6 +126,7 @@ "mojom_root=" + rebase_path(root_gen_dir, root_build_dir), ] deps = [ + ":headless_render_frame_controller__generator", ":tab_socket__generator", ] } @@ -344,6 +351,7 @@ deps = [ ":gen_devtools_client_api", + ":headless_render_frame_controller", ":tab_socket", ":version_header", "//components/security_state/core",
diff --git a/headless/lib/browser/headless_content_browser_client.cc b/headless/lib/browser/headless_content_browser_client.cc index 56e09a6..6f2d431 100644 --- a/headless/lib/browser/headless_content_browser_client.cc +++ b/headless/lib/browser/headless_content_browser_client.cc
@@ -138,8 +138,17 @@ std::unique_ptr<base::Value> HeadlessContentBrowserClient::GetServiceManifestOverlay( base::StringPiece name) { - if (name != content::mojom::kBrowserServiceName || - browser_->options()->mojo_service_names.empty()) + if (name == content::mojom::kBrowserServiceName) + return GetBrowserServiceManifestOverlay(); + else if (name == content::mojom::kRendererServiceName) + return GetRendererServiceManifestOverlay(); + + return nullptr; +} + +std::unique_ptr<base::Value> +HeadlessContentBrowserClient::GetBrowserServiceManifestOverlay() { + if (browser_->options()->mojo_service_names.empty()) return nullptr; base::StringPiece manifest_template = @@ -162,6 +171,14 @@ return manifest; } +std::unique_ptr<base::Value> +HeadlessContentBrowserClient::GetRendererServiceManifestOverlay() { + base::StringPiece manifest_template = + ui::ResourceBundle::GetSharedInstance().GetRawDataResource( + IDR_HEADLESS_RENDERER_MANIFEST_OVERLAY); + return base::JSONReader::Read(manifest_template); +} + void HeadlessContentBrowserClient::GetQuotaSettings( content::BrowserContext* context, content::StoragePartition* partition,
diff --git a/headless/lib/browser/headless_content_browser_client.h b/headless/lib/browser/headless_content_browser_client.h index 1c3f95f..78c14df 100644 --- a/headless/lib/browser/headless_content_browser_client.h +++ b/headless/lib/browser/headless_content_browser_client.h
@@ -53,6 +53,9 @@ void ResourceDispatcherHostCreated() override; private: + std::unique_ptr<base::Value> GetBrowserServiceManifestOverlay(); + std::unique_ptr<base::Value> GetRendererServiceManifestOverlay(); + HeadlessBrowserImpl* browser_; // Not owned. std::unique_ptr<HeadlessResourceDispatcherHostDelegate>
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 3980324..77e94ef5 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -34,6 +34,7 @@ #include "headless/lib/browser/headless_tab_socket_impl.h" #include "printing/features/features.h" #include "services/service_manager/public/cpp/binder_registry.h" +#include "services/service_manager/public/cpp/interface_provider.h" #if BUILDFLAG(ENABLE_BASIC_PRINTING) #include "headless/lib/browser/headless_print_manager.h" @@ -49,27 +50,6 @@ return static_cast<HeadlessWebContentsImpl*>(web_contents); } -class WebContentsObserverAdapter : public content::WebContentsObserver { - public: - WebContentsObserverAdapter(content::WebContents* web_contents, - HeadlessWebContents::Observer* observer) - : content::WebContentsObserver(web_contents), observer_(observer) {} - - ~WebContentsObserverAdapter() override {} - - void RenderViewReady() override { - DCHECK(web_contents()->GetMainFrame()->IsRenderFrameLive()); - observer_->DevToolsTargetReady(); - } - - HeadlessWebContents::Observer* observer() { return observer_; } - - private: - HeadlessWebContents::Observer* observer_; // Not owned. - - DISALLOW_COPY_AND_ASSIGN(WebContentsObserverAdapter); -}; - class HeadlessWebContentsImpl::Delegate : public content::WebContentsDelegate { public: explicit Delegate(HeadlessBrowserContextImpl* browser_context) @@ -213,7 +193,8 @@ agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)), inject_mojo_services_into_isolated_world_(false), browser_context_(browser_context), - render_process_host_(web_contents->GetRenderProcessHost()) { + render_process_host_(web_contents->GetRenderProcessHost()), + weak_ptr_factory_(this) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD) printing::HeadlessPrintManager::CreateForWebContents(web_contents); #endif @@ -230,11 +211,28 @@ void HeadlessWebContentsImpl::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { + render_frame_host->GetRemoteInterfaces()->GetInterface( + &render_frame_controller_); if (!mojo_services_.empty()) { - render_frame_host->AllowBindings( + base::Closure callback; + // We only fire DevToolsTargetReady when the tab socket is set up for the + // main frame. + // TODO(eseckler): To indicate tab socket readiness for child frames, we + // need to send an event via the parent frame's DevTools connection instead. + if (render_frame_host == web_contents()->GetMainFrame()) { + callback = + base::Bind(&HeadlessWebContentsImpl::MainFrameTabSocketSetupComplete, + weak_ptr_factory_.GetWeakPtr()); + } + render_frame_controller_->AllowTabSocketBindings( inject_mojo_services_into_isolated_world_ - ? content::BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD - : content::BINDINGS_POLICY_HEADLESS_MAIN_WORLD); + ? MojoBindingsPolicy::ISOLATED_WORLD + : MojoBindingsPolicy::MAIN_WORLD, + callback); + } else if (render_frame_host == web_contents()->GetMainFrame()) { + // Pretend we set up the TabSocket, which allows the DevToolsTargetReady + // event to fire. + MainFrameTabSocketSetupComplete(); } service_manager::BinderRegistry* interface_registry = @@ -258,6 +256,25 @@ render_frame_host->GetRoutingID()); } +void HeadlessWebContentsImpl::RenderViewReady() { + DCHECK(web_contents()->GetMainFrame()->IsRenderFrameLive()); + render_view_ready_ = true; + MaybeIssueDevToolsTargetReady(); +} + +void HeadlessWebContentsImpl::MainFrameTabSocketSetupComplete() { + main_frame_tab_socket_setup_complete_ = true; + MaybeIssueDevToolsTargetReady(); +} + +void HeadlessWebContentsImpl::MaybeIssueDevToolsTargetReady() { + if (!main_frame_tab_socket_setup_complete_ || !render_view_ready_) + return; + + for (auto& observer : observers_) + observer.DevToolsTargetReady(); +} + std::string HeadlessWebContentsImpl::GetUntrustedDevToolsFrameIdForFrameTreeNodeId( int process_id, @@ -293,29 +310,23 @@ } void HeadlessWebContentsImpl::AddObserver(Observer* observer) { - DCHECK(observer_map_.find(observer) == observer_map_.end()); - observer_map_[observer] = base::MakeUnique<WebContentsObserverAdapter>( - web_contents_.get(), observer); + observers_.AddObserver(observer); } void HeadlessWebContentsImpl::RemoveObserver(Observer* observer) { - ObserverMap::iterator it = observer_map_.find(observer); - DCHECK(it != observer_map_.end()); - observer_map_.erase(it); + observers_.RemoveObserver(observer); } void HeadlessWebContentsImpl::DevToolsAgentHostAttached( content::DevToolsAgentHost* agent_host) { - for (const auto& pair : observer_map_) { - pair.second->observer()->DevToolsClientAttached(); - } + for (auto& observer : observers_) + observer.DevToolsClientAttached(); } void HeadlessWebContentsImpl::DevToolsAgentHostDetached( content::DevToolsAgentHost* agent_host) { - for (const auto& pair : observer_map_) { - pair.second->observer()->DevToolsClientDetached(); - } + for (auto& observer : observers_) + observer.DevToolsClientDetached(); } void HeadlessWebContentsImpl::RenderProcessExited( @@ -323,9 +334,8 @@ base::TerminationStatus status, int exit_code) { DCHECK_EQ(render_process_host_, host); - for (const auto& pair : observer_map_) { - pair.second->observer()->RenderProcessExited(status, exit_code); - } + for (auto& observer : observers_) + observer.RenderProcessExited(status, exit_code); } void HeadlessWebContentsImpl::RenderProcessHostDestroyed(
diff --git a/headless/lib/browser/headless_web_contents_impl.h b/headless/lib/browser/headless_web_contents_impl.h index 59fd571b2..f7eb0fa8 100644 --- a/headless/lib/browser/headless_web_contents_impl.h +++ b/headless/lib/browser/headless_web_contents_impl.h
@@ -10,10 +10,12 @@ #include <string> #include <unordered_map> +#include "base/observer_list.h" #include "content/public/browser/devtools_agent_host_observer.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/web_contents_observer.h" #include "headless/lib/browser/headless_window_tree_host.h" +#include "headless/lib/headless_render_frame_controller.mojom.h" #include "headless/public/headless_devtools_target.h" #include "headless/public/headless_export.h" #include "headless/public/headless_web_contents.h" @@ -30,7 +32,6 @@ namespace headless { class HeadlessBrowserImpl; class HeadlessTabSocketImpl; -class WebContentsObserverAdapter; // Exported for tests. class HEADLESS_EXPORT HeadlessWebContentsImpl @@ -83,6 +84,7 @@ // content::WebContentsObserver implementation: void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; + void RenderViewReady() override; content::WebContents* web_contents() const; bool OpenURL(const GURL& url); @@ -113,6 +115,9 @@ HeadlessWebContentsImpl(content::WebContents* web_contents, HeadlessBrowserContextImpl* browser_context); + void MainFrameTabSocketSetupComplete(); + void MaybeIssueDevToolsTargetReady(); + void InitializeScreen(const gfx::Size& initial_size); using MojoService = HeadlessWebContents::Builder::MojoService; @@ -126,16 +131,19 @@ std::list<MojoService> mojo_services_; bool inject_mojo_services_into_isolated_world_; std::unique_ptr<HeadlessTabSocketImpl> headless_tab_socket_; + bool render_view_ready_ = false; + bool main_frame_tab_socket_setup_complete_ = false; HeadlessBrowserContextImpl* browser_context_; // Not owned. // TODO(alexclarke): With OOPIF there may be more than one renderer, we need // to fix this. See crbug.com/715924 content::RenderProcessHost* render_process_host_; // Not owned. - using ObserverMap = - std::unordered_map<HeadlessWebContents::Observer*, - std::unique_ptr<WebContentsObserverAdapter>>; - ObserverMap observer_map_; + HeadlessRenderFrameControllerPtr render_frame_controller_; + + base::ObserverList<HeadlessWebContents::Observer> observers_; + + base::WeakPtrFactory<HeadlessWebContentsImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(HeadlessWebContentsImpl); };
diff --git a/headless/lib/headless_render_frame_controller.mojom b/headless/lib/headless_render_frame_controller.mojom new file mode 100644 index 0000000..f8ff294 --- /dev/null +++ b/headless/lib/headless_render_frame_controller.mojom
@@ -0,0 +1,20 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module headless; + +enum MojoBindingsPolicy { + // No access to the TabSocket API from within the frame. + NONE, + // Allow main world JS content within the frame to access the TabSocket API. + MAIN_WORLD, + // Allow access to the TabSocket API only from within DevTools-created + // isolated worlds for the frame. + ISOLATED_WORLD +}; + +interface HeadlessRenderFrameController { + // Set the bindings policy for TabSocket mojo services for a frame. + AllowTabSocketBindings(MojoBindingsPolicy policy) => (); +};
diff --git a/headless/lib/renderer/headless_content_renderer_client.cc b/headless/lib/renderer/headless_content_renderer_client.cc index dff2179..b6437e4 100644 --- a/headless/lib/renderer/headless_content_renderer_client.cc +++ b/headless/lib/renderer/headless_content_renderer_client.cc
@@ -13,8 +13,12 @@ #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" +#include "headless/lib/headless_render_frame_controller.mojom.h" #include "headless/lib/tab_socket.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "printing/features/features.h" +#include "services/service_manager/public/cpp/bind_source_info.h" +#include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/WebKit/public/platform/WebIsolatedWorldIds.h" #include "third_party/WebKit/public/web/WebKit.h" @@ -28,56 +32,70 @@ namespace headless { -HeadlessContentRendererClient::HeadlessContentRendererClient() {} - -HeadlessContentRendererClient::~HeadlessContentRendererClient() {} - class HeadlessTabSocketBindings : public gin::Wrappable<HeadlessTabSocketBindings>, - public content::RenderFrameObserver, public blink::WebScriptExecutionCallback { public: explicit HeadlessTabSocketBindings(content::RenderFrame* render_frame) - : content::RenderFrameObserver(render_frame), weak_ptr_factory_(this) {} + : render_frame_(render_frame), weak_ptr_factory_(this) {} ~HeadlessTabSocketBindings() override {} - // content::RenderFrameObserver implementation: - void DidCreateScriptContext(v8::Local<v8::Context> context, - int world_id) override { + void SetBindingsPolicy(MojoBindingsPolicy bindings_policy) { + bindings_policy_ = bindings_policy; + + if (world_id_) + return; + + // Update bindings for pre-existing script contexts. + v8::Isolate* isolate = blink::MainThreadIsolate(); + v8::HandleScope handle_scope(isolate); + if (bindings_policy == MojoBindingsPolicy::MAIN_WORLD) { + InitializeTabSocketBindings( + render_frame_->GetWebFrame()->MainWorldScriptContext(), + content::ISOLATED_WORLD_ID_GLOBAL); + } else if (bindings_policy == MojoBindingsPolicy::ISOLATED_WORLD) { + // TODO(eseckler): We currently only support a single isolated world + // context. InitializeTabSocketBindings will log a warning and ignore any + // but the first isolated world if called multiple times here. + for (const auto& entry : context_map_) { + if (entry.first != content::ISOLATED_WORLD_ID_GLOBAL) + InitializeTabSocketBindings(entry.second.Get(isolate), entry.first); + } + } + } + + void DidCreateScriptContext(v8::Local<v8::Context> context, int world_id) { + bool is_devtools_world = world_id >= blink::kDevToolsFirstIsolatedWorldId && + world_id <= blink::kDevToolsLastIsolatedWorldId; if (world_id == content::ISOLATED_WORLD_ID_GLOBAL) { - // For the main world only inject TabSocket if - // BINDINGS_POLICY_HEADLESS_MAIN_WORLD is set. - if (!(render_frame()->GetEnabledBindings() & - content::BindingsPolicy::BINDINGS_POLICY_HEADLESS_MAIN_WORLD)) { + context_map_[world_id].Reset(blink::MainThreadIsolate(), context); + + // For the main world, only inject TabSocket if MAIN_WORLD policy is set. + if (bindings_policy_ != MojoBindingsPolicy::MAIN_WORLD) return; - } + } else if (is_devtools_world) { + context_map_[world_id].Reset(blink::MainThreadIsolate(), context); + + // For devtools-created isolated worlds, only inject TabSocket if + // ISOLATED_WORLD policy is set. + if (bindings_policy_ != MojoBindingsPolicy::ISOLATED_WORLD) + return; } else { - // For the isolated worlds only inject TabSocket if - // BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD is set and the world id falls - // within the range reserved for DevTools created isolated worlds. - if (!(render_frame()->GetEnabledBindings() & - content::BindingsPolicy::BINDINGS_POLICY_HEADLESS_ISOLATED_WORLD)) { - return; - } - if (world_id < blink::kDevToolsFirstIsolatedWorldId || - world_id > blink::kDevToolsLastIsolatedWorldId) { - return; - } + // Other worlds don't receive TabSocket bindings. + return; } - InitializeTabSocketBindings(context); + InitializeTabSocketBindings(context, world_id); } - void WillReleaseScriptContext(v8::Local<v8::Context> context, - int world_id) override { - if (context_ == context) { + void WillReleaseScriptContext(v8::Local<v8::Context> context, int world_id) { + context_map_.erase(world_id); + if (world_id_ && *world_id_ == world_id) { on_message_callback_.Reset(); - context_.Reset(); + world_id_.reset(); } } - void OnDestruct() override {} - // gin::WrappableBase implementation: gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { @@ -113,7 +131,7 @@ gin::Converter<std::string>::ToV8(isolate, message), }; - render_frame()->GetWebFrame()->RequestExecuteV8Function( + render_frame_->GetWebFrame()->RequestExecuteV8Function( context, GetOnMessageCallback(), context->Global(), arraysize(argv), argv, this); @@ -122,8 +140,18 @@ weak_ptr_factory_.GetWeakPtr())); } - void InitializeTabSocketBindings(v8::Local<v8::Context> context) { - // Add TabSocket bindings to the DevTools created isolated world. + void InitializeTabSocketBindings(v8::Local<v8::Context> context, + int world_id) { + if (world_id_) { + // TODO(eseckler): Support multiple isolated worlds inside the same frame. + LOG(WARNING) << "TabSocket not created for world id " << world_id + << ". TabSocket only supports a single active world."; + return; + } + + DCHECK(context_map_.find(world_id) != context_map_.end()); + + // Add TabSocket bindings to the context. v8::Isolate* isolate = blink::MainThreadIsolate(); v8::HandleScope handle_scope(isolate); if (context.IsEmpty()) @@ -137,19 +165,22 @@ v8::Local<v8::Object> global = context->Global(); global->Set(gin::StringToV8(isolate, "TabSocket"), bindings.ToV8()); - context_.Reset(blink::MainThreadIsolate(), context); + world_id_ = world_id; } headless::TabSocketPtr& EnsureTabSocketPtr() { if (!tab_socket_ptr_.is_bound()) { - render_frame()->GetRemoteInterfaces()->GetInterface( + render_frame_->GetRemoteInterfaces()->GetInterface( mojo::MakeRequest(&tab_socket_ptr_)); } return tab_socket_ptr_; } v8::Local<v8::Context> GetContext() { - return v8::Local<v8::Context>::New(blink::MainThreadIsolate(), context_); + if (!world_id_) + return v8::Local<v8::Context>(); + DCHECK(context_map_.find(*world_id_) != context_map_.end()); + return context_map_[*world_id_].Get(blink::MainThreadIsolate()); } v8::Local<v8::Function> GetOnMessageCallback() { @@ -157,8 +188,11 @@ on_message_callback_); } + content::RenderFrame* render_frame_; + MojoBindingsPolicy bindings_policy_ = MojoBindingsPolicy::NONE; headless::TabSocketPtr tab_socket_ptr_; - v8::UniquePersistent<v8::Context> context_; + base::Optional<int> world_id_; + base::flat_map<int, v8::UniquePersistent<v8::Context>> context_map_; v8::UniquePersistent<v8::Function> on_message_callback_; base::WeakPtrFactory<HeadlessTabSocketBindings> weak_ptr_factory_; }; @@ -166,13 +200,62 @@ gin::WrapperInfo HeadlessTabSocketBindings::kWrapperInfo = { gin::kEmbedderNativeGin}; +class HeadlessRenderFrameControllerImpl : public HeadlessRenderFrameController, + public content::RenderFrameObserver { + public: + HeadlessRenderFrameControllerImpl(content::RenderFrame* render_frame) + : content::RenderFrameObserver(render_frame), + tab_socket_bindings_(render_frame) { + render_frame->GetInterfaceRegistry()->AddInterface(base::Bind( + &HeadlessRenderFrameControllerImpl::OnRenderFrameControllerRequest, + base::Unretained(this))); + } + + void OnRenderFrameControllerRequest( + const service_manager::BindSourceInfo& source_info, + headless::HeadlessRenderFrameControllerRequest request) { + headless_render_frame_controller_bindings_.AddBinding(this, + std::move(request)); + } + + // HeadlessRenderFrameController implementation: + void AllowTabSocketBindings( + MojoBindingsPolicy policy, + AllowTabSocketBindingsCallback callback) override { + tab_socket_bindings_.SetBindingsPolicy(policy); + std::move(callback).Run(); + } + + // content::RenderFrameObserverW implementation: + void DidCreateScriptContext(v8::Local<v8::Context> context, + int world_id) override { + tab_socket_bindings_.DidCreateScriptContext(context, world_id); + } + + void WillReleaseScriptContext(v8::Local<v8::Context> context, + int world_id) override { + tab_socket_bindings_.WillReleaseScriptContext(context, world_id); + } + + void OnDestruct() override { delete this; } + + private: + mojo::BindingSet<headless::HeadlessRenderFrameController> + headless_render_frame_controller_bindings_; + HeadlessTabSocketBindings tab_socket_bindings_; +}; + +HeadlessContentRendererClient::HeadlessContentRendererClient() {} + +HeadlessContentRendererClient::~HeadlessContentRendererClient() {} + void HeadlessContentRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) new printing::PrintWebViewHelper( render_frame, base::MakeUnique<HeadlessPrintWebViewHelperDelegate>()); #endif - new HeadlessTabSocketBindings(render_frame); + new HeadlessRenderFrameControllerImpl(render_frame); } } // namespace headless
diff --git a/headless/lib/renderer/headless_renderer_manifest_overlay.json b/headless/lib/renderer/headless_renderer_manifest_overlay.json new file mode 100644 index 0000000..28fefc2 --- /dev/null +++ b/headless/lib/renderer/headless_renderer_manifest_overlay.json
@@ -0,0 +1,12 @@ +{ + "name": "content_renderer", + "interface_provider_specs": { + "navigation:frame": { + "provides": { + "browser": [ + "headless::HeadlessRenderFrameController" + ] + } + } + } +}
diff --git a/headless/lib/resources/headless_lib_resources.grd b/headless/lib/resources/headless_lib_resources.grd index eb36ef2..78f34cd 100644 --- a/headless/lib/resources/headless_lib_resources.grd +++ b/headless/lib/resources/headless_lib_resources.grd
@@ -11,6 +11,7 @@ <includes> <include name="IDR_HEADLESS_LIB_DEVTOOLS_DISCOVERY_PAGE" file="devtools_discovery_page.html" type="BINDATA" /> <include name="IDR_HEADLESS_BROWSER_MANIFEST_OVERLAY_TEMPLATE" file="../browser/headless_browser_manifest_overlay_template.json" type="BINDATA" /> + <include name="IDR_HEADLESS_RENDERER_MANIFEST_OVERLAY" file="../renderer/headless_renderer_manifest_overlay.json" type="BINDATA" /> <include name="IDR_HEADLESS_TAB_SOCKET_MOJOM_JS" file="${mojom_root}\headless\lib\tab_socket.mojom.js" use_base_dir="false" type="BINDATA" /> </includes> </release>
diff --git a/ios/chrome/browser/ui/autofill/cells/autofill_edit_item.mm b/ios/chrome/browser/ui/autofill/cells/autofill_edit_item.mm index 6b4e19d8..c5941ba 100644 --- a/ios/chrome/browser/ui/autofill/cells/autofill_edit_item.mm +++ b/ios/chrome/browser/ui/autofill/cells/autofill_edit_item.mm
@@ -92,15 +92,16 @@ _textLabel = [[UILabel alloc] init]; _textLabel.translatesAutoresizingMaskIntoConstraints = NO; + _textLabel.font = [[MDCTypography fontLoader] mediumFontOfSize:14]; + _textLabel.textColor = [[MDCPalette greyPalette] tint900]; + [_textLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh + forAxis:UILayoutConstraintAxisHorizontal]; [contentView addSubview:_textLabel]; _textField = [[UITextField alloc] init]; _textField.translatesAutoresizingMaskIntoConstraints = NO; [contentView addSubview:_textField]; - _textLabel.font = [[MDCTypography fontLoader] mediumFontOfSize:14]; - _textLabel.textColor = [[MDCPalette greyPalette] tint900]; - _textField.font = [[MDCTypography fontLoader] lightFontOfSize:16]; _textField.textColor = [[MDCPalette greyPalette] tint500]; _textField.autocapitalizationType = UITextAutocapitalizationTypeWords; @@ -150,8 +151,6 @@ _iconHeightConstraint, _iconWidthConstraint, ]]; - [_textField setContentHuggingPriority:UILayoutPriorityDefaultLow - forAxis:UILayoutConstraintAxisHorizontal]; } return self; }
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator.h b/ios/chrome/browser/ui/payments/payment_request_coordinator.h index e82be40..7bc8165 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator.h +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator.h
@@ -10,7 +10,10 @@ #include "base/ios/block_types.h" #include "base/strings/string16.h" #import "ios/chrome/browser/chrome_coordinator.h" +#import "ios/chrome/browser/ui/payments/address_edit_coordinator.h" +#import "ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/contact_info_selection_coordinator.h" +#import "ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_items_display_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_method_selection_coordinator.h" #include "ios/chrome/browser/ui/payments/payment_request_error_coordinator.h" @@ -70,11 +73,14 @@ // controller. The PR view controller will be presented by the view controller // provided in the initializer. @interface PaymentRequestCoordinator - : ChromeCoordinator<ContactInfoSelectionCoordinatorDelegate, - PaymentRequestViewControllerDelegate, - PaymentRequestErrorCoordinatorDelegate, + : ChromeCoordinator<AddressEditCoordinatorDelegate, + ContactInfoEditCoordinatorDelegate, + ContactInfoSelectionCoordinatorDelegate, + CreditCardEditCoordinatorDelegate, PaymentItemsDisplayCoordinatorDelegate, PaymentMethodSelectionCoordinatorDelegate, + PaymentRequestErrorCoordinatorDelegate, + PaymentRequestViewControllerDelegate, ShippingAddressSelectionCoordinatorDelegate, ShippingOptionSelectionCoordinatorDelegate>
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm index 1ada066..b0ca87fb 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm
@@ -22,10 +22,16 @@ namespace { using ::payments::data_util::GetPaymentAddressFromAutofillProfile; + +// Time interval before updating the Payment Summary item in seconds. +const NSTimeInterval kUpdatePaymentSummaryItemIntervalSeconds = 10.0; } // namespace @implementation PaymentRequestCoordinator { UINavigationController* _navigationController; + AddressEditCoordinator* _addressEditCoordinator; + CreditCardEditCoordinator* _creditCardEditCoordinator; + ContactInfoEditCoordinator* _contactInfoEditCoordinator; ContactInfoSelectionCoordinator* _contactInfoSelectionCoordinator; PaymentRequestViewController* _viewController; PaymentRequestErrorCoordinator* _errorCoordinator; @@ -42,6 +48,9 @@ // The selected shipping address, pending approval from the page. autofill::AutofillProfile* _pendingShippingAddress; + + // Timer used to update the Payment Summary item. + NSTimer* _updatePaymentSummaryItemTimer; } @synthesize paymentRequest = _paymentRequest; @@ -84,6 +93,12 @@ [[_navigationController presentingViewController] dismissViewControllerAnimated:YES completion:nil]; + [_addressEditCoordinator stop]; + _addressEditCoordinator = nil; + [_creditCardEditCoordinator stop]; + _creditCardEditCoordinator = nil; + [_contactInfoEditCoordinator stop]; + _contactInfoEditCoordinator = nil; [_itemsDisplayCoordinator stop]; _itemsDisplayCoordinator = nil; [_contactInfoSelectionCoordinator stop]; @@ -122,43 +137,57 @@ } - (void)updatePaymentDetails:(web::PaymentDetails)paymentDetails { + [_updatePaymentSummaryItemTimer invalidate]; + BOOL totalValueChanged = (_paymentRequest->payment_details().total != paymentDetails.total); [_mediator setTotalValueChanged:totalValueChanged]; + // Update the payment summary item. + [_viewController updatePaymentSummaryItem]; + + if (totalValueChanged) { + // If the total value changed, update the Payment Summary item after a + // certain time interval in order to clear the 'Updated' label on the item. + _updatePaymentSummaryItemTimer = [NSTimer + scheduledTimerWithTimeInterval:kUpdatePaymentSummaryItemIntervalSeconds + target:_viewController + selector:@selector(updatePaymentSummaryItem) + userInfo:nil + repeats:NO]; + } + _paymentRequest->UpdatePaymentDetails(paymentDetails); - if (_paymentRequest->shipping_options().empty()) { - // Display error in the shipping address/option selection view. - if (_shippingAddressSelectionCoordinator) { - _paymentRequest->set_selected_shipping_profile(nil); - [_shippingAddressSelectionCoordinator stopSpinnerAndDisplayError]; - } else if (_shippingOptionSelectionCoordinator) { - [_shippingOptionSelectionCoordinator stopSpinnerAndDisplayError]; - } - // Update the payment request summary view. - [_viewController loadModel]; - [[_viewController collectionView] reloadData]; - } else { - // Update the payment summary item. - [_viewController updatePaymentSummaryItem]; - - if (_shippingAddressSelectionCoordinator) { - // Set the selected shipping address. - _paymentRequest->set_selected_shipping_profile(_pendingShippingAddress); - _pendingShippingAddress = nil; - - // Dismiss the shipping address selection view. - [_shippingAddressSelectionCoordinator stop]; - _shippingAddressSelectionCoordinator = nil; - } else if (_shippingOptionSelectionCoordinator) { - // Dismiss the shipping option selection view. - [_shippingOptionSelectionCoordinator stop]; - _shippingOptionSelectionCoordinator = nil; - } - - // Update the Shipping section in the payment request summary view. - [_viewController updateShippingSection]; + // If a shipping address has been selected and there are available shipping + // options, set it as the selected shipping address. + if (_pendingShippingAddress && !_paymentRequest->shipping_options().empty()) { + _paymentRequest->set_selected_shipping_profile(_pendingShippingAddress); } + _pendingShippingAddress = nil; + + // Update the shipping section. The available shipping addresses/options and + // the selected shipping address/option are already up-to-date. + [_viewController updateShippingSection]; + + if (_paymentRequest->shipping_options().empty()) { + // Display error in the shipping address selection view, if present. + [_shippingAddressSelectionCoordinator stopSpinnerAndDisplayError]; + + // Display error in the shipping option selection view, if present. + [_shippingOptionSelectionCoordinator stopSpinnerAndDisplayError]; + } else { + // Dismiss the shipping address selection view, if present. + [_shippingAddressSelectionCoordinator stop]; + _shippingAddressSelectionCoordinator = nil; + + // Dismiss the shipping option selection view, if present. + [_shippingOptionSelectionCoordinator stop]; + _shippingOptionSelectionCoordinator = nil; + } + + // Dismiss the address edit view, if present. + [_addressEditCoordinator stop]; + _addressEditCoordinator = nil; } - (void)displayErrorWithCallback:(ProceduralBlock)callback { @@ -189,6 +218,10 @@ - (void)paymentRequestViewControllerDidSelectPaymentSummaryItem: (PaymentRequestViewController*)controller { + // Return if there are no display items. + if (_paymentRequest->payment_details().display_items.empty()) + return; + _itemsDisplayCoordinator = [[PaymentItemsDisplayCoordinator alloc] initWithBaseViewController:_viewController]; [_itemsDisplayCoordinator setPaymentRequest:_paymentRequest]; @@ -199,6 +232,16 @@ - (void)paymentRequestViewControllerDidSelectContactInfoItem: (PaymentRequestViewController*)controller { + if (_paymentRequest->contact_profiles().empty()) { + _contactInfoEditCoordinator = [[ContactInfoEditCoordinator alloc] + initWithBaseViewController:_viewController]; + [_contactInfoEditCoordinator setPaymentRequest:_paymentRequest]; + [_contactInfoEditCoordinator setDelegate:self]; + + [_contactInfoEditCoordinator start]; + return; + } + _contactInfoSelectionCoordinator = [[ContactInfoSelectionCoordinator alloc] initWithBaseViewController:_viewController]; [_contactInfoSelectionCoordinator setPaymentRequest:_paymentRequest]; @@ -209,6 +252,16 @@ - (void)paymentRequestViewControllerDidSelectShippingAddressItem: (PaymentRequestViewController*)controller { + if (_paymentRequest->shipping_profiles().empty()) { + _addressEditCoordinator = [[AddressEditCoordinator alloc] + initWithBaseViewController:_viewController]; + [_addressEditCoordinator setPaymentRequest:_paymentRequest]; + [_addressEditCoordinator setDelegate:self]; + + [_addressEditCoordinator start]; + return; + } + _shippingAddressSelectionCoordinator = [[ShippingAddressSelectionCoordinator alloc] initWithBaseViewController:_viewController]; @@ -231,6 +284,16 @@ - (void)paymentRequestViewControllerDidSelectPaymentMethodItem: (PaymentRequestViewController*)controller { + if (_paymentRequest->credit_cards().empty()) { + _creditCardEditCoordinator = [[CreditCardEditCoordinator alloc] + initWithBaseViewController:_viewController]; + [_creditCardEditCoordinator setPaymentRequest:_paymentRequest]; + [_creditCardEditCoordinator setDelegate:self]; + + [_creditCardEditCoordinator start]; + return; + } + _methodSelectionCoordinator = [[PaymentMethodSelectionCoordinator alloc] initWithBaseViewController:_viewController]; [_methodSelectionCoordinator setPaymentRequest:_paymentRequest]; @@ -256,9 +319,6 @@ - (void)paymentItemsDisplayCoordinatorDidReturn: (PaymentItemsDisplayCoordinator*)coordinator { - // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; - [_itemsDisplayCoordinator stop]; _itemsDisplayCoordinator = nil; } @@ -273,8 +333,8 @@ - (void) contactInfoSelectionCoordinator:(ContactInfoSelectionCoordinator*)coordinator didSelectContactProfile:(autofill::AutofillProfile*)contactProfile { + DCHECK(contactProfile); _paymentRequest->set_selected_contact_profile(contactProfile); - [_viewController updateContactInfoSection]; [_contactInfoSelectionCoordinator stop]; @@ -287,6 +347,24 @@ _contactInfoSelectionCoordinator = nil; } +#pragma mark - ContactInfoEditCoordinatorDelegate + +- (void)contactInfoEditCoordinator:(ContactInfoEditCoordinator*)coordinator + didFinishEditingProfile:(autofill::AutofillProfile*)profile { + DCHECK(profile); + _paymentRequest->set_selected_contact_profile(profile); + [_viewController updateContactInfoSection]; + + [_contactInfoEditCoordinator stop]; + _contactInfoEditCoordinator = nil; +} + +- (void)contactInfoEditCoordinatorDidCancel: + (ContactInfoEditCoordinator*)coordinator { + [_contactInfoEditCoordinator stop]; + _contactInfoEditCoordinator = nil; +} + #pragma mark - ShippingAddressSelectionCoordinatorDelegate - (void)shippingAddressSelectionCoordinator: @@ -302,28 +380,42 @@ - (void)shippingAddressSelectionCoordinatorDidReturn: (ShippingAddressSelectionCoordinator*)coordinator { - // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; [_shippingAddressSelectionCoordinator stop]; _shippingAddressSelectionCoordinator = nil; } +#pragma mark - AddressEditCoordinatorDelegate + +- (void)addressEditCoordinator:(AddressEditCoordinator*)coordinator + didFinishEditingAddress:(autofill::AutofillProfile*)address { + _pendingShippingAddress = address; + DCHECK(address); + payments::PaymentAddress shippingAddress = + GetPaymentAddressFromAutofillProfile( + *address, GetApplicationContext()->GetApplicationLocale()); + [_delegate paymentRequestCoordinator:self + didSelectShippingAddress:shippingAddress]; +} + +- (void)addressEditCoordinatorDidCancel:(AddressEditCoordinator*)coordinator { + [_addressEditCoordinator stop]; + _addressEditCoordinator = nil; +} + #pragma mark - ShippingOptionSelectionCoordinatorDelegate - (void)shippingOptionSelectionCoordinator: (ShippingOptionSelectionCoordinator*)coordinator didSelectShippingOption: (web::PaymentShippingOption*)shippingOption { + DCHECK(shippingOption); [_delegate paymentRequestCoordinator:self didSelectShippingOption:*shippingOption]; } - (void)shippingOptionSelectionCoordinatorDidReturn: (ShippingAddressSelectionCoordinator*)coordinator { - // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; - [_shippingOptionSelectionCoordinator stop]; _shippingOptionSelectionCoordinator = nil; } @@ -333,24 +425,36 @@ - (void)paymentMethodSelectionCoordinator: (PaymentMethodSelectionCoordinator*)coordinator didSelectPaymentMethod:(autofill::CreditCard*)creditCard { + DCHECK(creditCard); _paymentRequest->set_selected_credit_card(creditCard); - [_viewController updatePaymentMethodSection]; - // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; - [_methodSelectionCoordinator stop]; _methodSelectionCoordinator = nil; } - (void)paymentMethodSelectionCoordinatorDidReturn: (PaymentMethodSelectionCoordinator*)coordinator { - // Clear the 'Updated' label on the payment summary item, if there is one. - [_viewController updatePaymentSummaryItem]; - [_methodSelectionCoordinator stop]; _methodSelectionCoordinator = nil; } +#pragma mark - CreditCardEditCoordinatorDelegate + +- (void)creditCardEditCoordinator:(CreditCardEditCoordinator*)coordinator + didFinishEditingCreditCard:(autofill::CreditCard*)creditCard { + DCHECK(creditCard); + _paymentRequest->set_selected_credit_card(creditCard); + [_viewController updatePaymentMethodSection]; + + [_creditCardEditCoordinator stop]; + _creditCardEditCoordinator = nil; +} + +- (void)creditCardEditCoordinatorDidCancel: + (CreditCardEditCoordinator*)coordinator { + [_creditCardEditCoordinator stop]; + _creditCardEditCoordinator = nil; +} + @end
diff --git a/ios/clean/chrome/browser/ui/actions/tab_strip_actions.h b/ios/clean/chrome/browser/ui/actions/tab_strip_actions.h index 511a968..f62cf65f 100644 --- a/ios/clean/chrome/browser/ui/actions/tab_strip_actions.h +++ b/ios/clean/chrome/browser/ui/actions/tab_strip_actions.h
@@ -10,8 +10,6 @@ // Target/Action methods relating to the tab strip. @protocol TabStripActions @optional -// Shows the tab strip. -- (void)showTabStrip:(id)sender; // Hides the tab strip. - (void)hideTabStrip:(id)sender; @end
diff --git a/ios/clean/chrome/browser/ui/commands/tab_strip_commands.h b/ios/clean/chrome/browser/ui/commands/tab_strip_commands.h index d9baf28..f352e1d 100644 --- a/ios/clean/chrome/browser/ui/commands/tab_strip_commands.h +++ b/ios/clean/chrome/browser/ui/commands/tab_strip_commands.h
@@ -7,10 +7,13 @@ // Commands relating to tab strip UI. @protocol TabStripCommands +@optional // Display the tab corresponding to |index|. - (void)showTabStripTabAtIndex:(int)index; // Remove tab corresponding to |index|. - (void)closeTabStripTabAtIndex:(int)index; +// Display the tab strip. +- (void)showTabStrip; @end #endif // IOS_CLEAN_CHROME_BROWSER_UI_COMMANDS_TAB_STRIP_COMMANDS_H_
diff --git a/ios/clean/chrome/browser/ui/tab/tab_container_view_controller.mm b/ios/clean/chrome/browser/ui/tab/tab_container_view_controller.mm index 082079e..4f8dd3a 100644 --- a/ios/clean/chrome/browser/ui/tab/tab_container_view_controller.mm +++ b/ios/clean/chrome/browser/ui/tab/tab_container_view_controller.mm
@@ -254,10 +254,6 @@ #pragma mark - Tab Strip actions. -- (void)showTabStrip:(id)sender { - self.tabStripVisible = YES; -} - - (void)hideTabStrip:(id)sender { self.tabStripVisible = NO; }
diff --git a/ios/clean/chrome/browser/ui/tab/tab_coordinator.mm b/ios/clean/chrome/browser/ui/tab/tab_coordinator.mm index bf46bc8..54f9c30 100644 --- a/ios/clean/chrome/browser/ui/tab/tab_coordinator.mm +++ b/ios/clean/chrome/browser/ui/tab/tab_coordinator.mm
@@ -11,6 +11,7 @@ #include "ios/chrome/browser/chrome_url_constants.h" #import "ios/clean/chrome/browser/ui/animators/zoom_transition_animator.h" #import "ios/clean/chrome/browser/ui/commands/tab_commands.h" +#import "ios/clean/chrome/browser/ui/commands/tab_strip_commands.h" #import "ios/clean/chrome/browser/ui/find_in_page/find_in_page_coordinator.h" #import "ios/clean/chrome/browser/ui/ntp/ntp_coordinator.h" #import "ios/clean/chrome/browser/ui/tab/tab_container_view_controller.h" @@ -61,8 +62,10 @@ selector:@selector(broadcastTabStripVisible:)]; CommandDispatcher* dispatcher = self.browser->dispatcher(); - // TabCommands + // Register Commands [dispatcher startDispatchingToTarget:self forSelector:@selector(loadURL:)]; + [dispatcher startDispatchingToTarget:self + forSelector:@selector(showTabStrip)]; WebCoordinator* webCoordinator = [[WebCoordinator alloc] init]; webCoordinator.webState = self.webState; @@ -207,4 +210,10 @@ self.webState->GetNavigationManager()->LoadURLWithParams(params); } +#pragma mark - TabStripCommands + +- (void)showTabStrip { + self.viewController.tabStripVisible = YES; +} + @end
diff --git a/ios/clean/chrome/browser/ui/tab_strip/tab_strip_toolbar.mm b/ios/clean/chrome/browser/ui/tab_strip/tab_strip_toolbar.mm index 0f76625e..1854300e 100644 --- a/ios/clean/chrome/browser/ui/tab_strip/tab_strip_toolbar.mm +++ b/ios/clean/chrome/browser/ui/tab_strip/tab_strip_toolbar.mm
@@ -49,6 +49,7 @@ UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setImage:[ChromeIcon closeIcon] forState:UIControlStateNormal]; [button setTintColor:[UIColor whiteColor]]; + // TODO(crbug.com/733453): Use dispatcher instead of responder chain. [button addTarget:nil action:@selector(hideTabStrip:) forControlEvents:UIControlEventTouchUpInside];
diff --git a/ios/clean/chrome/browser/ui/toolbar/BUILD.gn b/ios/clean/chrome/browser/ui/toolbar/BUILD.gn index 3095a53..af92896 100644 --- a/ios/clean/chrome/browser/ui/toolbar/BUILD.gn +++ b/ios/clean/chrome/browser/ui/toolbar/BUILD.gn
@@ -38,7 +38,6 @@ ":toolbar_components_ui", "//base", "//ios/chrome/browser/ui", - "//ios/clean/chrome/browser/ui/actions", "//ios/clean/chrome/browser/ui/animators", "//ios/clean/chrome/browser/ui/commands", "//ios/clean/chrome/browser/ui/tools",
diff --git a/ios/clean/chrome/browser/ui/toolbar/toolbar_coordinator.mm b/ios/clean/chrome/browser/ui/toolbar/toolbar_coordinator.mm index 8b892dcc..f443d6b 100644 --- a/ios/clean/chrome/browser/ui/toolbar/toolbar_coordinator.mm +++ b/ios/clean/chrome/browser/ui/toolbar/toolbar_coordinator.mm
@@ -48,7 +48,8 @@ } - (void)start { - self.viewController = [[ToolbarViewController alloc] init]; + self.viewController = [[ToolbarViewController alloc] + initWithDispatcher:static_cast<id>(self.browser->dispatcher())]; CommandDispatcher* dispatcher = self.browser->dispatcher(); [dispatcher startDispatchingToTarget:self @@ -61,7 +62,6 @@ [dispatcher startDispatchingToTarget:self forSelector:@selector(stopLoadingPage)]; - self.viewController.dispatcher = static_cast<id>(self.browser->dispatcher()); self.mediator.consumer = self.viewController; self.mediator.webStateList = &self.browser->web_state_list();
diff --git a/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.h b/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.h index 7ddcd6e..13954a22 100644 --- a/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.h +++ b/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.h
@@ -12,6 +12,7 @@ @protocol NavigationCommands; @protocol TabGridCommands; +@protocol TabStripCommands; @protocol ToolsMenuCommands; // View controller for a toolbar, which will show a horizontal row of @@ -22,9 +23,14 @@ @interface ToolbarViewController : UIViewController<ZoomTransitionDelegate, ToolbarConsumer> +- (instancetype)initWithDispatcher:(id<NavigationCommands, + TabGridCommands, + TabStripCommands, + ToolsMenuCommands>)dispatcher; + // The dispatcher for this view controller @property(nonatomic, weak) - id<NavigationCommands, TabGridCommands, ToolsMenuCommands> + id<NavigationCommands, TabGridCommands, TabStripCommands, ToolsMenuCommands> dispatcher; @property(nonatomic, strong) UIViewController* locationBarViewController;
diff --git a/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.mm b/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.mm index 6ab9c7cd..8d967fb1 100644 --- a/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.mm +++ b/ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.mm
@@ -6,9 +6,9 @@ #import "base/mac/foundation_util.h" #import "ios/chrome/browser/ui/uikit_ui_util.h" -#import "ios/clean/chrome/browser/ui/actions/tab_strip_actions.h" #import "ios/clean/chrome/browser/ui/commands/navigation_commands.h" #import "ios/clean/chrome/browser/ui/commands/tab_grid_commands.h" +#import "ios/clean/chrome/browser/ui/commands/tab_strip_commands.h" #import "ios/clean/chrome/browser/ui/commands/tools_menu_commands.h" #import "ios/clean/chrome/browser/ui/toolbar/toolbar_button+factory.h" #import "ios/clean/chrome/browser/ui/toolbar/toolbar_component_options.h" @@ -58,6 +58,14 @@ return self; } +- (instancetype)initWithDispatcher:(id<NavigationCommands, + TabGridCommands, + TabStripCommands, + ToolsMenuCommands>)dispatcher { + _dispatcher = dispatcher; + return [self init]; +} + #pragma mark - View lifecyle - (void)viewDidLoad { @@ -135,8 +143,8 @@ [buttonConstraints addObject:[self.backButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.backButton addTarget:self - action:@selector(goBack:) + [self.backButton addTarget:self.dispatcher + action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside]; // Forward button. @@ -147,8 +155,8 @@ [buttonConstraints addObject:[self.forwardButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.forwardButton addTarget:self - action:@selector(goForward:) + [self.forwardButton addTarget:self.dispatcher + action:@selector(goForward) forControlEvents:UIControlEventTouchUpInside]; // Tab switcher Strip button. @@ -159,8 +167,8 @@ [buttonConstraints addObject:[self.tabSwitchStripButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.tabSwitchStripButton addTarget:nil - action:@selector(showTabStrip:) + [self.tabSwitchStripButton addTarget:self.dispatcher + action:@selector(showTabStrip) forControlEvents:UIControlEventTouchUpInside]; [self.tabSwitchStripButton setTitleColor:UIColorFromRGB(kToolbarButtonTitleNormalColor) @@ -177,8 +185,8 @@ [buttonConstraints addObject:[self.tabSwitchGridButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.tabSwitchGridButton addTarget:self - action:@selector(showTabGrid:) + [self.tabSwitchGridButton addTarget:self.dispatcher + action:@selector(showTabGrid) forControlEvents:UIControlEventTouchUpInside]; self.tabSwitchGridButton.hiddenInCurrentState = YES; @@ -189,8 +197,8 @@ [buttonConstraints addObject:[self.toolsMenuButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.toolsMenuButton addTarget:self - action:@selector(showToolsMenu:) + [self.toolsMenuButton addTarget:self.dispatcher + action:@selector(showToolsMenu) forControlEvents:UIControlEventTouchUpInside]; // Share button. @@ -199,9 +207,7 @@ [buttonConstraints addObject:[self.shareButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.shareButton addTarget:self - action:@selector(showShareMenu:) - forControlEvents:UIControlEventTouchUpInside]; + // TODO(crbug.com/683793):Dispatch command once someone is handling it. // Reload button. self.reloadButton = [ToolbarButton reloadToolbarButton]; @@ -209,8 +215,8 @@ [buttonConstraints addObject:[self.reloadButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.reloadButton addTarget:self - action:@selector(reload:) + [self.reloadButton addTarget:self.dispatcher + action:@selector(reloadPage) forControlEvents:UIControlEventTouchUpInside]; // Stop button. @@ -219,8 +225,8 @@ [buttonConstraints addObject:[self.stopButton.widthAnchor constraintEqualToConstant:kToolbarButtonWidth]]; - [self.stopButton addTarget:self - action:@selector(stop:) + [self.stopButton addTarget:self.dispatcher + action:@selector(stopLoadingPage) forControlEvents:UIControlEventTouchUpInside]; // Set the button constraint priority to UILayoutPriorityDefaultHigh so @@ -375,40 +381,6 @@ fromView:self.toolsMenuButton]; } -#pragma mark - Private Methods - -- (void)showToolsMenu:(id)sender { - [self.dispatcher showToolsMenu]; -} - -- (void)closeToolsMenu:(id)sender { - [self.dispatcher closeToolsMenu]; -} - -- (void)showShareMenu:(id)sender { - [self.dispatcher showShareMenu]; -} - -- (void)goBack:(id)sender { - [self.dispatcher goBack]; -} - -- (void)goForward:(id)sender { - [self.dispatcher goForward]; -} - -- (void)stop:(id)sender { - [self.dispatcher stopLoadingPage]; -} - -- (void)reload:(id)sender { - [self.dispatcher reloadPage]; -} - -- (void)showTabGrid:(id)sender { - [self.dispatcher showTabGrid]; -} - #pragma mark - Helper Methods // Updates all Buttons visibility to match any recent WebState change.
diff --git a/ios/net/BUILD.gn b/ios/net/BUILD.gn index 7132276..6c9ab890 100644 --- a/ios/net/BUILD.gn +++ b/ios/net/BUILD.gn
@@ -75,6 +75,7 @@ } test("ios_net_unittests") { + configs += [ "//build/config/compiler:enable_arc" ] deps = [ ":net", "//base",
diff --git a/ios/net/cookies/cookie_creation_time_manager_unittest.mm b/ios/net/cookies/cookie_creation_time_manager_unittest.mm index 5a3f082..9b1f4577 100644 --- a/ios/net/cookies/cookie_creation_time_manager_unittest.mm +++ b/ios/net/cookies/cookie_creation_time_manager_unittest.mm
@@ -11,6 +11,10 @@ #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { class CookieCreationTimeManagerTest : public testing::Test {
diff --git a/ios/net/cookies/cookie_store_ios_persistent_unittest.mm b/ios/net/cookies/cookie_store_ios_persistent_unittest.mm index 85706f6..9cb9ed7 100644 --- a/ios/net/cookies/cookie_store_ios_persistent_unittest.mm +++ b/ios/net/cookies/cookie_store_ios_persistent_unittest.mm
@@ -17,6 +17,10 @@ #include "net/cookies/cookie_store_unittest.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { struct InactiveCookieStoreIOSTestTraits {
diff --git a/ios/net/cookies/cookie_store_ios_test_util.mm b/ios/net/cookies/cookie_store_ios_test_util.mm index 3e71942..e96e734 100644 --- a/ios/net/cookies/cookie_store_ios_test_util.mm +++ b/ios/net/cookies/cookie_store_ios_test_util.mm
@@ -13,6 +13,10 @@ #include "net/cookies/cookie_options.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { namespace {
diff --git a/ios/net/cookies/cookie_store_ios_unittest.mm b/ios/net/cookies/cookie_store_ios_unittest.mm index 514738b..1280af0 100644 --- a/ios/net/cookies/cookie_store_ios_unittest.mm +++ b/ios/net/cookies/cookie_store_ios_unittest.mm
@@ -19,6 +19,10 @@ #include "net/cookies/cookie_store_unittest.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { struct CookieStoreIOSTestTraits {
diff --git a/ios/net/cookies/system_cookie_util_unittest.mm b/ios/net/cookies/system_cookie_util_unittest.mm index 33fadb0..ab9bf3d 100644 --- a/ios/net/cookies/system_cookie_util_unittest.mm +++ b/ios/net/cookies/system_cookie_util_unittest.mm
@@ -6,7 +6,6 @@ #import <Foundation/Foundation.h> -#include "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #include "base/time/time.h" #include "net/cookies/cookie_constants.h" @@ -14,6 +13,10 @@ #include "testing/gtest_mac.h" #include "url/gurl.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { namespace { @@ -34,8 +37,8 @@ secure, httponly, net::CookieSameSite::DEFAULT_MODE, net::COOKIE_PRIORITY_DEFAULT); // Convert it to system cookie. - base::scoped_nsobject<NSHTTPCookie> system_cookie( - [SystemCookieFromCanonicalCookie(canonical_cookie) retain]); + NSHTTPCookie* system_cookie = + SystemCookieFromCanonicalCookie(canonical_cookie); // Check the attributes. EXPECT_TRUE(system_cookie); @@ -62,15 +65,14 @@ base::Time expire_date = creation_time + base::TimeDelta::FromHours(2); NSDate* system_expire_date = [NSDate dateWithTimeIntervalSince1970:expire_date.ToDoubleT()]; - base::scoped_nsobject<NSHTTPCookie> system_cookie( - [[NSHTTPCookie alloc] initWithProperties:@{ - NSHTTPCookieDomain : @"foo", - NSHTTPCookieName : @"a", - NSHTTPCookiePath : @"/", - NSHTTPCookieValue : @"b", - NSHTTPCookieExpires : system_expire_date, - @"HttpOnly" : @YES, - }]); + NSHTTPCookie* system_cookie = [[NSHTTPCookie alloc] initWithProperties:@{ + NSHTTPCookieDomain : @"foo", + NSHTTPCookieName : @"a", + NSHTTPCookiePath : @"/", + NSHTTPCookieValue : @"b", + NSHTTPCookieExpires : system_expire_date, + @"HttpOnly" : @YES, + }]; ASSERT_TRUE(system_cookie); net::CanonicalCookie chrome_cookie = CanonicalCookieFromSystemCookie(system_cookie, creation_time); @@ -91,13 +93,13 @@ EXPECT_EQ(net::COOKIE_PRIORITY_DEFAULT, chrome_cookie.Priority()); // Test session and secure cookie. - system_cookie.reset([[NSHTTPCookie alloc] initWithProperties:@{ + system_cookie = [[NSHTTPCookie alloc] initWithProperties:@{ NSHTTPCookieDomain : @"foo", NSHTTPCookieName : @"a", NSHTTPCookiePath : @"/", NSHTTPCookieValue : @"b", NSHTTPCookieSecure : @"Y", - }]); + }]; ASSERT_TRUE(system_cookie); chrome_cookie = CanonicalCookieFromSystemCookie(system_cookie, creation_time); EXPECT_FALSE(chrome_cookie.IsPersistent()); @@ -125,8 +127,8 @@ false, // httponly net::CookieSameSite::DEFAULT_MODE, net::COOKIE_PRIORITY_DEFAULT); // Convert it to system cookie. - base::scoped_nsobject<NSHTTPCookie> system_cookie( - [SystemCookieFromCanonicalCookie(bad_canonical_cookie) retain]); + NSHTTPCookie* system_cookie = + SystemCookieFromCanonicalCookie(bad_canonical_cookie); EXPECT_TRUE(system_cookie == nil); }
diff --git a/ios/net/http_response_headers_util_unittest.mm b/ios/net/http_response_headers_util_unittest.mm index 27dfcb89..ae64284 100644 --- a/ios/net/http_response_headers_util_unittest.mm +++ b/ios/net/http_response_headers_util_unittest.mm
@@ -8,11 +8,14 @@ #include <algorithm> -#include "base/mac/scoped_nsobject.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { // Returns true if all the information in |http_response| is present in @@ -39,7 +42,7 @@ // Tests that HttpResponseHeaders created from NSHTTPURLResponses successfully // copy over the status code and the header names and values. TEST(HttpResponseHeadersUtilTest, CreateHeadersFromNSHTTPURLResponse) { - base::scoped_nsobject<NSHTTPURLResponse> http_response( + NSHTTPURLResponse* http_response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"test.com"] statusCode:200 HTTPVersion:@"HTTP/1.1" @@ -47,11 +50,10 @@ @"headerName1" : @"headerValue1", @"headerName2" : @"headerValue2", @"headerName3" : @"headerValue3", - }]); + }]; scoped_refptr<HttpResponseHeaders> http_response_headers = CreateHeadersFromNSHTTPURLResponse(http_response); - EXPECT_TRUE( - AreHeadersEqual(http_response.get(), http_response_headers.get())); + EXPECT_TRUE(AreHeadersEqual(http_response, http_response_headers.get())); } } // namespace net.
diff --git a/ios/net/nsurlrequest_util_unittest.mm b/ios/net/nsurlrequest_util_unittest.mm index 01bd2f7..fcd848ff 100644 --- a/ios/net/nsurlrequest_util_unittest.mm +++ b/ios/net/nsurlrequest_util_unittest.mm
@@ -4,19 +4,20 @@ #include "ios/net/nsurlrequest_util.h" -#include "base/mac/scoped_nsobject.h" #include "testing/gtest/include/gtest/gtest.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace { // Tests that FormatUrlRequestForLogging outputs the string in the form: // request:<url> request.mainDocURL:<mainDocumentURL>. TEST(NSURLRequestUtilTest, FormatUrlRequestForLogging) { - base::scoped_nsobject<NSMutableURLRequest> request( - [[NSMutableURLRequest alloc] init]); - request.get().URL = [NSURL URLWithString:@"http://www.google.com"]; - request.get().mainDocumentURL = - [NSURL URLWithString:@"http://www.google1.com"]; + NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init]; + request.URL = [NSURL URLWithString:@"http://www.google.com"]; + request.mainDocumentURL = [NSURL URLWithString:@"http://www.google1.com"]; std::string actualString, expectedString; actualString = net::FormatUrlRequestForLogging(request); @@ -24,21 +25,20 @@ " request.mainDocURL: http://www.google1.com"; EXPECT_EQ(expectedString, actualString); - request.get().URL = nil; - request.get().mainDocumentURL = - [NSURL URLWithString:@"http://www.google1.com"]; + request.URL = nil; + request.mainDocumentURL = [NSURL URLWithString:@"http://www.google1.com"]; actualString = net::FormatUrlRequestForLogging(request); expectedString = "request: [nil] request.mainDocURL: http://www.google1.com"; EXPECT_EQ(expectedString, actualString); - request.get().URL = [NSURL URLWithString:@"http://www.google.com"]; - request.get().mainDocumentURL = nil; + request.URL = [NSURL URLWithString:@"http://www.google.com"]; + request.mainDocumentURL = nil; actualString = net::FormatUrlRequestForLogging(request); expectedString = "request: http://www.google.com request.mainDocURL: [nil]"; EXPECT_EQ(expectedString, actualString); - request.get().URL = nil; - request.get().mainDocumentURL = nil; + request.URL = nil; + request.mainDocumentURL = nil; actualString = net::FormatUrlRequestForLogging(request); expectedString = "request: [nil] request.mainDocURL: [nil]"; EXPECT_EQ(expectedString, actualString);
diff --git a/ios/net/protocol_handler_util_unittest.mm b/ios/net/protocol_handler_util_unittest.mm index 54a3c1b..ff386ec 100644 --- a/ios/net/protocol_handler_util_unittest.mm +++ b/ios/net/protocol_handler_util_unittest.mm
@@ -7,7 +7,6 @@ #include <memory> #include <utility> -#include "base/mac/scoped_nsobject.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -27,6 +26,10 @@ #include "testing/gtest_mac.h" #include "url/gurl.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + // When C++ exceptions are disabled, the C++ library defines |try| and // |catch| so as to allow exception-expecting C++ code to build properly when // language support for exceptions is not present. These macros interfere @@ -228,8 +231,8 @@ TEST_F(ProtocolHandlerUtilTest, CopyHttpHeaders) { GURL url(std::string("http://url")); - base::scoped_nsobject<NSMutableURLRequest> in_request( - [[NSMutableURLRequest alloc] initWithURL:NSURLWithGURL(url)]); + NSMutableURLRequest* in_request = + [[NSMutableURLRequest alloc] initWithURL:NSURLWithGURL(url)]; [in_request setAllHTTPHeaderFields:@{ @"Referer" : @"referrer", @"User-Agent" : @"secret", @@ -253,8 +256,8 @@ TEST_F(ProtocolHandlerUtilTest, AddMissingHeaders) { GURL url(std::string("http://url")); - base::scoped_nsobject<NSMutableURLRequest> in_request( - [[NSMutableURLRequest alloc] initWithURL:NSURLWithGURL(url)]); + NSMutableURLRequest* in_request = + [[NSMutableURLRequest alloc] initWithURL:NSURLWithGURL(url)]; std::unique_ptr<URLRequest> out_request( request_context_->CreateRequest(url, DEFAULT_PRIORITY, nullptr)); out_request->set_method("POST");
diff --git a/ios/net/url_scheme_util_unittest.mm b/ios/net/url_scheme_util_unittest.mm index ebea8afa..b91a0de 100644 --- a/ios/net/url_scheme_util_unittest.mm +++ b/ios/net/url_scheme_util_unittest.mm
@@ -10,6 +10,10 @@ #import "testing/gtest_mac.h" #include "url/gurl.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace net { const char* kSchemeTestData[] = {
diff --git a/ios/showcase/payments/sc_payments_editor_coordinator.mm b/ios/showcase/payments/sc_payments_editor_coordinator.mm index ba652e23..c1db284 100644 --- a/ios/showcase/payments/sc_payments_editor_coordinator.mm +++ b/ios/showcase/payments/sc_payments_editor_coordinator.mm
@@ -11,6 +11,7 @@ #import "ios/chrome/browser/ui/autofill/cells/autofill_edit_item.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h" #import "ios/chrome/browser/ui/payments/cells/payments_text_item.h" +#import "ios/chrome/browser/ui/payments/payment_request_edit_consumer.h" #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller.h" #import "ios/chrome/browser/ui/payments/payment_request_editor_field.h" #import "ios/showcase/common/protocol_alerter.h" @@ -19,54 +20,34 @@ #error "This file requires ARC support." #endif -@interface SCPaymentsEditorCoordinator ()< - PaymentRequestEditViewControllerDataSource, - PaymentRequestEditViewControllerValidator> +@interface SCPaymentsEditorMediator + : NSObject<PaymentRequestEditViewControllerDataSource, + PaymentRequestEditViewControllerValidator> -@property(nonatomic, strong) - PaymentRequestEditViewController* paymentRequestEditViewController; - -@property(nonatomic, strong) ProtocolAlerter* alerter; - +// The reference to the province field. @property(nonatomic, strong) EditorField* province; +// The consumer for this object. +@property(nonatomic, weak) id<PaymentRequestEditConsumer> consumer; + @end -@implementation SCPaymentsEditorCoordinator +@implementation SCPaymentsEditorMediator @synthesize state = _state; -@synthesize baseViewController = _baseViewController; -@synthesize paymentRequestEditViewController = - _paymentRequestEditViewController; -@synthesize alerter = _alerter; @synthesize province = _province; +@synthesize consumer = _consumer; -- (void)start { - self.alerter = [[ProtocolAlerter alloc] initWithProtocols:@[ - @protocol(PaymentRequestEditViewControllerDelegate) - ]]; - self.alerter.baseViewController = self.baseViewController; +- (void)setConsumer:(id<PaymentRequestEditConsumer>)consumer { + _consumer = consumer; + [self.consumer setEditorFields:[self editorFields]]; +} - self.paymentRequestEditViewController = - [[PaymentRequestEditViewController alloc] - initWithStyle:CollectionViewControllerStyleAppBar]; - [self.paymentRequestEditViewController setTitle:@"Add info"]; - [self.paymentRequestEditViewController setEditorFields:[self editorFields]]; - [self.paymentRequestEditViewController setDataSource:self]; - [self.paymentRequestEditViewController - setDelegate:static_cast<id<PaymentRequestEditViewControllerDelegate>>( - self.alerter)]; - [self.paymentRequestEditViewController setValidatorDelegate:self]; - [self.paymentRequestEditViewController loadModel]; - // Set the options for the province field after the model is loaded. +- (void)loadProvinces { NSArray<NSString*>* options = @[ @"Ontario", @"Quebec" ]; self.province.value = options[1]; self.province.enabled = YES; - [self.paymentRequestEditViewController setOptions:options - forEditorField:self.province]; - [self.baseViewController - pushViewController:self.paymentRequestEditViewController - animated:YES]; + [self.consumer setOptions:options forEditorField:self.province]; } #pragma mark - Helper methods @@ -137,3 +118,51 @@ } @end + +@interface SCPaymentsEditorCoordinator () + +@property(nonatomic, strong) + PaymentRequestEditViewController* paymentRequestEditViewController; + +@property(nonatomic, strong) SCPaymentsEditorMediator* mediator; + +@property(nonatomic, strong) ProtocolAlerter* alerter; + +@end + +@implementation SCPaymentsEditorCoordinator + +@synthesize baseViewController = _baseViewController; +@synthesize paymentRequestEditViewController = + _paymentRequestEditViewController; +@synthesize mediator = _mediator; +@synthesize alerter = _alerter; + +- (void)start { + self.alerter = [[ProtocolAlerter alloc] initWithProtocols:@[ + @protocol(PaymentRequestEditViewControllerDelegate) + ]]; + self.alerter.baseViewController = self.baseViewController; + + self.paymentRequestEditViewController = + [[PaymentRequestEditViewController alloc] + initWithStyle:CollectionViewControllerStyleAppBar]; + [self.paymentRequestEditViewController setTitle:@"Add info"]; + self.mediator = [[SCPaymentsEditorMediator alloc] init]; + [self.mediator setConsumer:self.paymentRequestEditViewController]; + [self.paymentRequestEditViewController setDataSource:self.mediator]; + [self.paymentRequestEditViewController + setDelegate:static_cast<id<PaymentRequestEditViewControllerDelegate>>( + self.alerter)]; + [self.paymentRequestEditViewController setValidatorDelegate:self.mediator]; + [self.paymentRequestEditViewController loadModel]; + + // Set the options for the province field after the model is loaded. + [self.mediator loadProvinces]; + + [self.baseViewController + pushViewController:self.paymentRequestEditViewController + animated:YES]; +} + +@end
diff --git a/ios/showcase/toolbar/sc_toolbar_coordinator.mm b/ios/showcase/toolbar/sc_toolbar_coordinator.mm index 21972f9..20de4f8 100644 --- a/ios/showcase/toolbar/sc_toolbar_coordinator.mm +++ b/ios/showcase/toolbar/sc_toolbar_coordinator.mm
@@ -6,6 +6,7 @@ #import "ios/clean/chrome/browser/ui/commands/navigation_commands.h" #import "ios/clean/chrome/browser/ui/commands/tab_grid_commands.h" +#import "ios/clean/chrome/browser/ui/commands/tab_strip_commands.h" #import "ios/clean/chrome/browser/ui/commands/tools_menu_commands.h" #import "ios/clean/chrome/browser/ui/toolbar/toolbar_view_controller.h" #import "ios/showcase/common/protocol_alerter.h" @@ -30,7 +31,7 @@ - (void)start { self.alerter = [[ProtocolAlerter alloc] initWithProtocols:@[ @protocol(NavigationCommands), @protocol(TabGridCommands), - @protocol(ToolsMenuCommands) + @protocol(TabStripCommands), @protocol(ToolsMenuCommands) ]]; self.alerter.baseViewController = self.baseViewController; @@ -46,8 +47,8 @@ ToolbarViewController* toolbarViewController = [[ToolbarViewController alloc] init]; toolbarViewController.dispatcher = - static_cast<id<NavigationCommands, TabGridCommands, ToolsMenuCommands>>( - self.alerter); + static_cast<id<NavigationCommands, TabGridCommands, TabStripCommands, + ToolsMenuCommands>>(self.alerter); [containerViewController addChildViewController:toolbarViewController]; toolbarViewController.view.frame = containerView.frame; [containerView addSubview:toolbarViewController.view];
diff --git a/net/android/java/src/org/chromium/net/X509Util.java b/net/android/java/src/org/chromium/net/X509Util.java index b6671aa..ffe25d7 100644 --- a/net/android/java/src/org/chromium/net/X509Util.java +++ b/net/android/java/src/org/chromium/net/X509Util.java
@@ -12,11 +12,11 @@ import android.net.http.X509TrustManagerExtensions; import android.os.Build; import android.security.KeyChain; -import android.util.Log; import android.util.Pair; import org.chromium.base.BuildInfo; import org.chromium.base.ContextUtils; +import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.SuppressFBWarnings; @@ -34,6 +34,7 @@ import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -160,24 +161,12 @@ private static final String OID_SERVER_GATED_MICROSOFT = "1.3.6.1.4.1.311.10.3.3"; /** - * Trust manager backed up by the read-only system certificate store. - */ - private static X509TrustManagerImplementation sDefaultTrustManager; - - /** * BroadcastReceiver that listens to change in the system keystore to invalidate certificate * caches. */ private static TrustStorageListener sTrustStorageListener; /** - * Trust manager backed up by a custom certificate store. We need such manager to plant test - * root CA to the trust store in testing. - */ - private static X509TrustManagerImplementation sTestTrustManager; - private static KeyStore sTestKeyStore; - - /** * The system key store. This is used to determine whether a trust anchor is a system trust * anchor or user-installed. */ @@ -192,20 +181,25 @@ private static File sSystemCertificateDirectory; /** - * An in-memory cache of which trust anchors are system trust roots. This avoids reading and - * decoding the root from disk on every verification. Mirrors a similar in-memory cache in - * Conscrypt's X509TrustManager implementation. + * True if ensureInitialized has run successfully. */ - private static Set<Pair<X500Principal, PublicKey>> sSystemTrustAnchorCache; + private static boolean sInitialized; /** - * True if the system key store has been loaded. If the "AndroidCAStore" KeyStore instance - * was not found, sSystemKeyStore may be null while sLoadedSystemKeyStore is true. + * The list of test root certificates to inject via testing. This list is protected by sLock. */ - private static boolean sLoadedSystemKeyStore; + private static List<X509Certificate> sTestRoots = new ArrayList<X509Certificate>(); /** - * Lock object used to synchronize all calls that modify or depend on the trust managers. + * Wraps all reloadable state in the verifier. When the backing KeyStores change, this field + * should be reset to null. Any verifications currently using the old instance will run to + * completion, but new ones use fresh state. + */ + private static CertificateVerifier sVerifier; + + /** + * Lock object used to synchronize all calls that modify or depend on the above globals. All + * fields except sVerifier are final once ensureInitialized completes successfully. */ private static final Object sLock = new Object(); @@ -216,6 +210,225 @@ */ private static boolean sDisableNativeCodeForTest; + private static final class CertificateVerifier { + /** + * X509TrustManager wrapping the default KeyStore. + */ + private X509TrustManagerImplementation mDefaultTrustManager; + + /** + * X509TrustManager wrapping any test roots which were configured when the + * CertificateVerifier was created. + */ + private X509TrustManagerImplementation mTestTrustManager; + + /** + * An in-memory cache of which trust anchors are system trust roots. This avoids reading and + * decoding the root from disk on every verification and mirrors a similar in-memory cache + * in Conscrypt's X509TrustManager implementation. + */ + private Set<Pair<X500Principal, PublicKey>> mSystemTrustAnchorCache; + + /** + * Lock object used to synchronize mSystemTrustAnchorCache. + */ + private Object mSystemTrustAnchorCacheLock; + + public CertificateVerifier() + throws CertificateException, KeyStoreException, NoSuchAlgorithmException { + assert Thread.holdsLock(sLock); + ensureInitializedLocked(); + + mDefaultTrustManager = createTrustManager(null); + if (!sTestRoots.isEmpty()) { + KeyStore testKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + try { + testKeyStore.load(null); + } catch (IOException e) { + // No IO operation is attempted + } + for (int i = 0; i < sTestRoots.size(); i++) { + testKeyStore.setCertificateEntry( + "root_cert_" + Integer.toString(i), sTestRoots.get(i)); + } + mTestTrustManager = createTrustManager(testKeyStore); + } + mSystemTrustAnchorCache = new HashSet<Pair<X500Principal, PublicKey>>(); + mSystemTrustAnchorCacheLock = new Object(); + } + + /** + * Creates a X509TrustManagerImplementation backed up by the given key store. When null is + * passed as a key store, system default trust store is used. Returns null if no created + * TrustManager was suitable. + * @throws KeyStoreException, NoSuchAlgorithmException on error initializing the + * TrustManager. + */ + private static X509TrustManagerImplementation createTrustManager(KeyStore keyStore) + throws KeyStoreException, NoSuchAlgorithmException { + String algorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); + tmf.init(keyStore); + + for (TrustManager tm : tmf.getTrustManagers()) { + if (tm instanceof X509TrustManager) { + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + return new X509TrustManagerJellyBean((X509TrustManager) tm); + } else { + return new X509TrustManagerIceCreamSandwich((X509TrustManager) tm); + } + } catch (IllegalArgumentException e) { + String className = tm.getClass().getName(); + Log.e(TAG, "Error creating trust manager (" + className + "): " + e); + } + } + } + Log.e(TAG, "Could not find suitable trust manager"); + return null; + } + + private static final char[] HEX_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', + }; + + private static String hashPrincipal(X500Principal principal) + throws NoSuchAlgorithmException { + // Android hashes a principal as the first four bytes of its MD5 digest, encoded in + // lowercase hex and reversed. Verified in 4.2, 4.3, and 4.4. + byte[] digest = MessageDigest.getInstance("MD5").digest(principal.getEncoded()); + char[] hexChars = new char[8]; + for (int i = 0; i < 4; i++) { + hexChars[2 * i] = HEX_DIGITS[(digest[3 - i] >> 4) & 0xf]; + hexChars[2 * i + 1] = HEX_DIGITS[digest[3 - i] & 0xf]; + } + return new String(hexChars); + } + + private boolean isKnownRoot(X509Certificate root) + throws NoSuchAlgorithmException, KeyStoreException { + // Could not find the system key store. Conservatively report false. + if (sSystemKeyStore == null) return false; + + // Check the in-memory cache first; avoid decoding the anchor from disk + // if it has been seen before. + Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>( + root.getSubjectX500Principal(), root.getPublicKey()); + + synchronized (mSystemTrustAnchorCacheLock) { + if (mSystemTrustAnchorCache.contains(key)) return true; + } + + // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the + // server supplies a copy of a trust anchor, X509TrustManagerExtensions returns the + // server's version rather than the system one. getCertificiateAlias will then fail to + // find an anchor name. This is fixed upstream in + // https://android-review.googlesource.com/#/c/91605/ + // + // TODO(davidben): When the change trickles into an Android release, query + // sSystemKeyStore directly. + + // System trust anchors are stored under a hash of the principal. In case of collisions, + // a number is appended. + String hash = hashPrincipal(root.getSubjectX500Principal()); + for (int i = 0; true; i++) { + String alias = hash + '.' + i; + if (!new File(sSystemCertificateDirectory, alias).exists()) break; + + Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias); + // It is possible for this to return null if the user deleted a trust anchor. In + // that case, the certificate remains in the system directory but is also added to + // another file. Continue iterating as there may be further collisions after the + // deleted anchor. + if (anchor == null) continue; + + if (!(anchor instanceof X509Certificate)) { + // This should never happen. + String className = anchor.getClass().getName(); + Log.e(TAG, "Anchor " + alias + " not an X509Certificate: " + className); + continue; + } + + // If the subject and public key match, this is a system root. + X509Certificate anchorX509 = (X509Certificate) anchor; + if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal()) + && root.getPublicKey().equals(anchorX509.getPublicKey())) { + synchronized (mSystemTrustAnchorCacheLock) { + mSystemTrustAnchorCache.add(key); + } + return true; + } + } + + return false; + } + + public AndroidCertVerifyResult verifyServerCertificates(byte[][] certChain, String authType, + String host) throws KeyStoreException, NoSuchAlgorithmException { + if (certChain == null || certChain.length == 0 || certChain[0] == null) { + throw new IllegalArgumentException("Expected non-null and non-empty certificate " + + "chain passed as |certChain|. |certChain|=" + + Arrays.deepToString(certChain)); + } + + X509Certificate[] serverCertificates = new X509Certificate[certChain.length]; + try { + for (int i = 0; i < certChain.length; ++i) { + serverCertificates[i] = createCertificateFromBytes(certChain[i]); + } + } catch (CertificateException e) { + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.UNABLE_TO_PARSE); + } + + // Expired and not yet valid certificates would be rejected by the trust managers, but + // the trust managers report all certificate errors using the general + // CertificateException. In order to get more granular error information, cert validity + // time range is being checked separately. + try { + serverCertificates[0].checkValidity(); + if (!verifyKeyUsage(serverCertificates[0])) { + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.INCORRECT_KEY_USAGE); + } + } catch (CertificateExpiredException e) { + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.EXPIRED); + } catch (CertificateNotYetValidException e) { + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.NOT_YET_VALID); + } catch (CertificateException e) { + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.FAILED); + } + + List<X509Certificate> verifiedChain; + try { + verifiedChain = + mDefaultTrustManager.checkServerTrusted(serverCertificates, authType, host); + } catch (CertificateException eDefaultManager) { + try { + if (mTestTrustManager == null) { + throw new CertificateException(); + } + verifiedChain = mTestTrustManager.checkServerTrusted( + serverCertificates, authType, host); + } catch (CertificateException eTestManager) { + // Neither of the trust managers confirms the validity of the certificate chain, + // log the error message returned by the system trust manager. + Log.i(TAG, + "Failed to validate the certificate chain, error: " + + eDefaultManager.getMessage()); + return new AndroidCertVerifyResult(CertVerifyStatusAndroid.NO_TRUSTED_ROOT); + } + } + + boolean isIssuedByKnownRoot = false; + if (verifiedChain.size() > 0) { + X509Certificate root = verifiedChain.get(verifiedChain.size() - 1); + isIssuedByKnownRoot = isKnownRoot(root); + } + + return new AndroidCertVerifyResult( + CertVerifyStatusAndroid.OK, isIssuedByKnownRoot, verifiedChain); + } + } + /** * Ensures that the trust managers and certificate factory are initialized. */ @@ -237,45 +450,27 @@ throws CertificateException, KeyStoreException, NoSuchAlgorithmException { assert Thread.holdsLock(sLock); - if (sCertificateFactory == null) { - sCertificateFactory = CertificateFactory.getInstance("X.509"); - } - if (sDefaultTrustManager == null) { - sDefaultTrustManager = X509Util.createTrustManager(null); - } - if (!sLoadedSystemKeyStore) { + if (sInitialized) return; + + sCertificateFactory = CertificateFactory.getInstance("X.509"); + + try { + sSystemKeyStore = KeyStore.getInstance("AndroidCAStore"); try { - sSystemKeyStore = KeyStore.getInstance("AndroidCAStore"); - try { - sSystemKeyStore.load(null); - } catch (IOException e) { - // No IO operation is attempted. - } - sSystemCertificateDirectory = - new File(System.getenv("ANDROID_ROOT") + "/etc/security/cacerts"); - } catch (KeyStoreException e) { - // Could not load AndroidCAStore. Continue anyway; isKnownRoot will always - // return false. - } - if (!sDisableNativeCodeForTest) { - nativeRecordCertVerifyCapabilitiesHistogram(sSystemKeyStore != null); - } - sLoadedSystemKeyStore = true; - } - if (sSystemTrustAnchorCache == null) { - sSystemTrustAnchorCache = new HashSet<Pair<X500Principal, PublicKey>>(); - } - if (sTestKeyStore == null) { - sTestKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - try { - sTestKeyStore.load(null); + sSystemKeyStore.load(null); } catch (IOException e) { // No IO operation is attempted. } + sSystemCertificateDirectory = + new File(System.getenv("ANDROID_ROOT") + "/etc/security/cacerts"); + } catch (KeyStoreException e) { + // Could not load AndroidCAStore. Continue anyway; isKnownRoot will always + // return false. } - if (sTestTrustManager == null) { - sTestTrustManager = X509Util.createTrustManager(sTestKeyStore); + if (!sDisableNativeCodeForTest) { + nativeRecordCertVerifyCapabilitiesHistogram(sSystemKeyStore != null); } + if (!sDisableNativeCodeForTest && sTrustStorageListener == null) { sTrustStorageListener = new TrustStorageListener(); IntentFilter filter = new IntentFilter(); @@ -288,57 +483,32 @@ } ContextUtils.getApplicationContext().registerReceiver(sTrustStorageListener, filter); } + + sInitialized = true; } /** - * Creates a X509TrustManagerImplementation backed up by the given key - * store. When null is passed as a key store, system default trust store is - * used. Returns null if no created TrustManager was suitable. - * @throws KeyStoreException, NoSuchAlgorithmException on error initializing the TrustManager. + * Returns the current CertificateVerifier instance. */ - private static X509TrustManagerImplementation createTrustManager(KeyStore keyStore) throws - KeyStoreException, NoSuchAlgorithmException { - String algorithm = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); - tmf.init(keyStore); - - for (TrustManager tm : tmf.getTrustManagers()) { - if (tm instanceof X509TrustManager) { - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - return new X509TrustManagerJellyBean((X509TrustManager) tm); - } else { - return new X509TrustManagerIceCreamSandwich((X509TrustManager) tm); - } - } catch (IllegalArgumentException e) { - String className = tm.getClass().getName(); - Log.e(TAG, "Error creating trust manager (" + className + "): " + e); - } + private static CertificateVerifier getVerifier() + throws CertificateException, KeyStoreException, NoSuchAlgorithmException { + synchronized (sLock) { + if (sVerifier == null) { + sVerifier = new CertificateVerifier(); } + return sVerifier; } - Log.e(TAG, "Could not find suitable trust manager"); - return null; - } - - /** - * After each modification of test key store, trust manager has to be generated again. - */ - private static void reloadTestTrustManager() throws KeyStoreException, - NoSuchAlgorithmException { - assert Thread.holdsLock(sLock); - - sTestTrustManager = X509Util.createTrustManager(sTestKeyStore); } /** * After each modification by the system of the key store, trust manager has to be regenerated. */ - private static void reloadDefaultTrustManager() throws KeyStoreException, - NoSuchAlgorithmException, CertificateException { + private static void reloadDefaultTrustManager() + throws KeyStoreException, NoSuchAlgorithmException, CertificateException { synchronized (sLock) { - sDefaultTrustManager = null; - sSystemTrustAnchorCache = null; - ensureInitializedLocked(); + // Invalidate the current verifier. Future certificate requests will + // use fresh state. + sVerifier = null; } nativeNotifyKeyChainChanged(); } @@ -355,100 +525,21 @@ public static void addTestRootCertificate(byte[] rootCertBytes) throws CertificateException, KeyStoreException, NoSuchAlgorithmException { - ensureInitialized(); X509Certificate rootCert = createCertificateFromBytes(rootCertBytes); synchronized (sLock) { - sTestKeyStore.setCertificateEntry( - "root_cert_" + Integer.toString(sTestKeyStore.size()), rootCert); - reloadTestTrustManager(); + sTestRoots.add(rootCert); + sVerifier = null; } } - public static void clearTestRootCertificates() throws NoSuchAlgorithmException, - CertificateException, KeyStoreException { - ensureInitialized(); + public static void clearTestRootCertificates() + throws NoSuchAlgorithmException, CertificateException, KeyStoreException { synchronized (sLock) { - try { - sTestKeyStore.load(null); - reloadTestTrustManager(); - } catch (IOException e) { - // No IO operation is attempted. - } + sTestRoots.clear(); + sVerifier = null; } } - private static final char[] HEX_DIGITS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', - }; - - private static String hashPrincipal(X500Principal principal) throws NoSuchAlgorithmException { - // Android hashes a principal as the first four bytes of its MD5 digest, encoded in - // lowercase hex and reversed. Verified in 4.2, 4.3, and 4.4. - byte[] digest = MessageDigest.getInstance("MD5").digest(principal.getEncoded()); - char[] hexChars = new char[8]; - for (int i = 0; i < 4; i++) { - hexChars[2 * i] = HEX_DIGITS[(digest[3 - i] >> 4) & 0xf]; - hexChars[2 * i + 1] = HEX_DIGITS[digest[3 - i] & 0xf]; - } - return new String(hexChars); - } - - private static boolean isKnownRoot(X509Certificate root) - throws NoSuchAlgorithmException, KeyStoreException { - assert Thread.holdsLock(sLock); - - // Could not find the system key store. Conservatively report false. - if (sSystemKeyStore == null) return false; - - // Check the in-memory cache first; avoid decoding the anchor from disk - // if it has been seen before. - Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>( - root.getSubjectX500Principal(), root.getPublicKey()); - - if (sSystemTrustAnchorCache.contains(key)) return true; - - // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the server - // supplies a copy of a trust anchor, X509TrustManagerExtensions returns the server's - // version rather than the system one. getCertificiateAlias will then fail to find an anchor - // name. This is fixed upstream in https://android-review.googlesource.com/#/c/91605/ - // - // TODO(davidben): When the change trickles into an Android release, query sSystemKeyStore - // directly. - - // System trust anchors are stored under a hash of the principal. In case of collisions, - // a number is appended. - String hash = hashPrincipal(root.getSubjectX500Principal()); - for (int i = 0; true; i++) { - String alias = hash + '.' + i; - if (!new File(sSystemCertificateDirectory, alias).exists()) break; - - Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias); - // It is possible for this to return null if the user deleted a trust anchor. In - // that case, the certificate remains in the system directory but is also added to - // another file. Continue iterating as there may be further collisions after the - // deleted anchor. - if (anchor == null) continue; - - if (!(anchor instanceof X509Certificate)) { - // This should never happen. - String className = anchor.getClass().getName(); - Log.e(TAG, "Anchor " + alias + " not an X509Certificate: " + className); - continue; - } - - // If the subject and public key match, this is a system root. - X509Certificate anchorX509 = (X509Certificate) anchor; - if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal()) - && root.getPublicKey().equals(anchorX509.getPublicKey())) { - sSystemTrustAnchorCache.add(key); - return true; - } - } - - return false; - } - /** * If an EKU extension is present in the end-entity certificate, it MUST contain either the * anyEKU or serverAuth or netscapeSGC or Microsoft SGC EKUs. @@ -487,78 +578,14 @@ String authType, String host) throws KeyStoreException, NoSuchAlgorithmException { - if (certChain == null || certChain.length == 0 || certChain[0] == null) { - throw new IllegalArgumentException("Expected non-null and non-empty certificate " - + "chain passed as |certChain|. |certChain|=" + Arrays.deepToString(certChain)); - } - - + CertificateVerifier verifier; try { - ensureInitialized(); + verifier = getVerifier(); } catch (CertificateException e) { return new AndroidCertVerifyResult(CertVerifyStatusAndroid.FAILED); } - X509Certificate[] serverCertificates = new X509Certificate[certChain.length]; - try { - for (int i = 0; i < certChain.length; ++i) { - serverCertificates[i] = createCertificateFromBytes(certChain[i]); - } - } catch (CertificateException e) { - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.UNABLE_TO_PARSE); - } - - // Expired and not yet valid certificates would be rejected by the trust managers, but the - // trust managers report all certificate errors using the general CertificateException. In - // order to get more granular error information, cert validity time range is being checked - // separately. - try { - serverCertificates[0].checkValidity(); - if (!verifyKeyUsage(serverCertificates[0])) { - return new AndroidCertVerifyResult( - CertVerifyStatusAndroid.INCORRECT_KEY_USAGE); - } - } catch (CertificateExpiredException e) { - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.EXPIRED); - } catch (CertificateNotYetValidException e) { - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.NOT_YET_VALID); - } catch (CertificateException e) { - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.FAILED); - } - - synchronized (sLock) { - // If no trust manager was found, fail without crashing on the null pointer. - if (sDefaultTrustManager == null) { - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.FAILED); - } - - List<X509Certificate> verifiedChain; - try { - verifiedChain = sDefaultTrustManager.checkServerTrusted(serverCertificates, - authType, host); - } catch (CertificateException eDefaultManager) { - try { - verifiedChain = sTestTrustManager.checkServerTrusted(serverCertificates, - authType, host); - } catch (CertificateException eTestManager) { - // Neither of the trust managers confirms the validity of the certificate chain, - // log the error message returned by the system trust manager. - Log.i(TAG, "Failed to validate the certificate chain, error: " - + eDefaultManager.getMessage()); - return new AndroidCertVerifyResult( - CertVerifyStatusAndroid.NO_TRUSTED_ROOT); - } - } - - boolean isIssuedByKnownRoot = false; - if (verifiedChain.size() > 0) { - X509Certificate root = verifiedChain.get(verifiedChain.size() - 1); - isIssuedByKnownRoot = isKnownRoot(root); - } - - return new AndroidCertVerifyResult(CertVerifyStatusAndroid.OK, - isIssuedByKnownRoot, verifiedChain); - } + return verifier.verifyServerCertificates(certChain, authType, host); } public static void setDisableNativeCodeForTest(boolean disabled) {
diff --git a/net/http/http_stream_factory_impl_job.cc b/net/http/http_stream_factory_impl_job.cc index 37b29b7e..9575055 100644 --- a/net/http/http_stream_factory_impl_job.cc +++ b/net/http/http_stream_factory_impl_job.cc
@@ -199,10 +199,12 @@ num_streams_(0), spdy_session_direct_( !(proxy_info.is_https() && origin_url_.SchemeIs(url::kHttpScheme))), - spdy_session_key_(GetSpdySessionKey(spdy_session_direct_, - proxy_info_.proxy_server(), - origin_url_, - request_info_.privacy_mode)), + spdy_session_key_(using_quic_ + ? SpdySessionKey() + : GetSpdySessionKey(spdy_session_direct_, + proxy_info_.proxy_server(), + origin_url_, + request_info_.privacy_mode)), stream_type_(HttpStreamRequest::BIDIRECTIONAL_STREAM), init_connection_already_resumed_(false), ptr_factory_(this) { @@ -409,6 +411,8 @@ } bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const { + DCHECK(!using_quic_); + // We need to make sure that if a spdy session was created for // https://somehost/ that we don't use that session for http://somehost:443/. // The only time we can use an existing session is if the request URL is @@ -555,9 +559,11 @@ if (result == ERR_IO_PENDING) return; - // Resume all throttled Jobs with the same SpdySessionKey if there are any, - // now that this job is done. - session_->spdy_session_pool()->ResumePendingRequests(spdy_session_key_); + if (!using_quic_) { + // Resume all throttled Jobs with the same SpdySessionKey if there are any, + // now that this job is done. + session_->spdy_session_pool()->ResumePendingRequests(spdy_session_key_); + } if (job_type_ == PRECONNECT) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -779,6 +785,8 @@ next_state_ = STATE_INIT_CONNECTION; if (!using_ssl_) return OK; + if (using_quic_) + return OK; // Ask |delegate_delegate_| to update the spdy session key for the request // that launched this job. delegate_->SetSpdySessionKey(this, spdy_session_key_); @@ -1279,7 +1287,8 @@ connection_->socket()->Disconnect(); connection_->Reset(); - delegate_->RemoveRequestFromSpdySessionRequestMapForJob(this); + if (!using_quic_) + delegate_->RemoveRequestFromSpdySessionRequestMapForJob(this); next_state_ = STATE_INIT_CONNECTION; }
diff --git a/net/http/http_stream_factory_impl_job.h b/net/http/http_stream_factory_impl_job.h index 0c5b61bb..ab7ddee 100644 --- a/net/http/http_stream_factory_impl_job.h +++ b/net/http/http_stream_factory_impl_job.h
@@ -243,6 +243,8 @@ return using_existing_quic_session_; } + bool using_quic() const { return using_quic_; } + bool should_reconsider_proxy() const { return should_reconsider_proxy_; } // TODO(xunjieli): Added to investigate crbug.com/711721. Remove when no
diff --git a/net/http/http_stream_factory_impl_job_controller.cc b/net/http/http_stream_factory_impl_job_controller.cc index 3e46fa94..9a21423 100644 --- a/net/http/http_stream_factory_impl_job_controller.cc +++ b/net/http/http_stream_factory_impl_job_controller.cc
@@ -174,8 +174,10 @@ } void HttpStreamFactoryImpl::JobController::OnRequestComplete() { - CancelJobs(); DCHECK(request_); + + RemoveRequestFromSpdySessionRequestMap(); + CancelJobs(); request_ = nullptr; if (bound_job_) { if (bound_job_->job_type() == MAIN) { @@ -329,8 +331,7 @@ if (next_state_ == STATE_RESOLVE_PROXY_COMPLETE) { if (status == ERR_IO_PENDING) return; - // TODO(xunjieli): Use DCHECK once https://crbug.com/723589 is fixed. - CHECK_EQ(OK, status); + DCHECK_EQ(OK, status); RunLoop(status); return; } @@ -600,6 +601,8 @@ void HttpStreamFactoryImpl::JobController::SetSpdySessionKey( Job* job, const SpdySessionKey& spdy_session_key) { + DCHECK(!job->using_quic()); + if (is_preconnect_ || IsJobOrphaned(job)) return; @@ -609,6 +612,8 @@ void HttpStreamFactoryImpl::JobController:: RemoveRequestFromSpdySessionRequestMapForJob(Job* job) { + DCHECK(!job->using_quic()); + if (is_preconnect_ || IsJobOrphaned(job)) return; @@ -867,7 +872,6 @@ void HttpStreamFactoryImpl::JobController::CancelJobs() { DCHECK(request_); - RemoveRequestFromSpdySessionRequestMap(); if (job_bound_) return; if (alternative_job_) @@ -905,6 +909,8 @@ // |job| should only be nullptr if we're being serviced by a late bound // SpdySession (one that was not created by a job in our |jobs_| set). if (!job) { + // TODO(xunjieli): This seems to be dead code. Remove it. crbug.com/475060. + CHECK(false); DCHECK(!bound_job_); // NOTE(willchan): We do *NOT* call OrphanUnboundJob() here. The reason is // because we *WANT* to cancel the unnecessary Jobs from other requests if @@ -1268,7 +1274,8 @@ origin_url, request_info_.method, error, &proxy_info_, io_callback_, &pac_request_, session_->context().proxy_delegate, net_log_); if (rv == OK || rv == ERR_IO_PENDING) { - RemoveRequestFromSpdySessionRequestMap(); + if (!job->using_quic()) + RemoveRequestFromSpdySessionRequestMap(); // Abandon all Jobs and start over. job_bound_ = false; bound_job_ = nullptr;
diff --git a/net/http/http_stream_factory_impl_job_controller_unittest.cc b/net/http/http_stream_factory_impl_job_controller_unittest.cc index b973347db..886f739 100644 --- a/net/http/http_stream_factory_impl_job_controller_unittest.cc +++ b/net/http/http_stream_factory_impl_job_controller_unittest.cc
@@ -23,6 +23,9 @@ #include "net/http/http_stream_factory_impl_request.h" #include "net/http/http_stream_factory_test_util.h" #include "net/log/net_log_with_source.h" +#include "net/log/test_net_log.h" +#include "net/log/test_net_log_entry.h" +#include "net/log/test_net_log_util.h" #include "net/proxy/mock_proxy_resolver.h" #include "net/proxy/proxy_config_service_fixed.h" #include "net/proxy/proxy_info.h" @@ -207,6 +210,7 @@ ProxyService::CreateFixedFromPacResult("HTTPS myproxy.org:443"); session_deps_.proxy_service = std::move(proxy_service); } + session_deps_.net_log = net_log_.bound().net_log(); HttpNetworkSession::Params params = SpdySessionDependencies::CreateSessionParams(&session_deps_); HttpNetworkSession::Context session_context = @@ -279,6 +283,7 @@ kServerHostname, Perspective::IS_CLIENT}; protected: + BoundTestNetLog net_log_; bool use_alternative_proxy_ = false; bool is_preconnect_ = false; bool enable_ip_based_pooling_ = true; @@ -309,7 +314,7 @@ OnStreamFailed(ERR_MANDATORY_PROXY_CONFIGURATION_FAILED, _)) .Times(1); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_FALSE(job_controller_->main_job()); @@ -341,7 +346,7 @@ Initialize(request_info); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_FALSE(job_controller_->main_job()); @@ -373,7 +378,7 @@ EXPECT_CALL(request_delegate_, OnStreamFailed(ERR_NO_SUPPORTED_PROXIES, _)) .Times(1); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_FALSE(job_controller_->main_job()); @@ -407,9 +412,9 @@ request_info, is_preconnect_, enable_ip_based_pooling_, enable_alternative_services_, SSLConfig(), SSLConfig()); HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); - return job_controller->Start( - &request_delegate_, nullptr, NetLogWithSource(), - HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); + return job_controller->Start(&request_delegate_, nullptr, net_log_.bound(), + HttpStreamRequest::HTTP_STREAM, + DEFAULT_PRIORITY); } private: @@ -615,7 +620,7 @@ Initialize(request_info); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); @@ -639,7 +644,7 @@ Initialize(request_info); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); // There's no other alternative job. Thus when a stream is ready, it should @@ -671,7 +676,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -700,7 +705,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -736,7 +741,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -776,7 +781,7 @@ AlternativeService alternative_service(kProtoQUIC, server.host(), 443); SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -819,7 +824,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); HostPortPair main_host_port_pair = @@ -863,7 +868,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -918,7 +923,7 @@ EXPECT_CALL(request_delegate_, OnStreamFailed(_, _)).Times(0); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -962,7 +967,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1005,7 +1010,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1046,7 +1051,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1093,7 +1098,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1118,7 +1123,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_factory_.main_job()->is_waiting()); @@ -1154,7 +1159,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1221,7 +1226,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1280,7 +1285,7 @@ // request and controller should resume the main job with delay. // OnStreamFailed should resume the main job immediately. request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1324,7 +1329,7 @@ EXPECT_TRUE(test_proxy_delegate()->alternative_proxy_server().is_quic()); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_FALSE(job_controller_->main_job()->is_waiting()); @@ -1349,7 +1354,7 @@ EXPECT_TRUE(test_proxy_delegate()->alternative_proxy_server().is_quic()); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_FALSE(job_controller_->main_job()->is_waiting()); @@ -1391,7 +1396,7 @@ url::SchemeHostPort(GURL("https://myproxy.org")), stats1); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->main_job()->is_waiting()); @@ -1447,7 +1452,7 @@ url::SchemeHostPort(GURL("https://myproxy.org")), stats1); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1490,7 +1495,7 @@ url::SchemeHostPort server(request_info.url); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); EXPECT_TRUE(job_controller_->alternative_job()); @@ -1616,7 +1621,7 @@ enable_alternative_services_, SSLConfig(), SSLConfig()); HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); auto request = job_controller->Start( - request_delegates[i].get(), nullptr, NetLogWithSource(), + request_delegates[i].get(), nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller->main_job()); EXPECT_FALSE(job_controller->alternative_job()); @@ -1634,6 +1639,14 @@ base::RunLoop().RunUntilIdle(); requests.clear(); EXPECT_TRUE(HttpStreamFactoryImplPeer::IsJobControllerDeleted(factory_)); + TestNetLogEntry::List entries; + size_t log_position = 0; + for (int i = 0; i < kNumRequests - 1; ++i) { + net_log_.GetEntries(&entries); + log_position = ExpectLogContainsSomewhereAfter( + entries, log_position, NetLogEventType::HTTP_STREAM_JOB_THROTTLED, + NetLogEventPhase::NONE); + } } TEST_F(JobControllerLimitMultipleH2Requests, MultipleRequestsFirstRequestHang) { @@ -1685,7 +1698,7 @@ enable_alternative_services_, SSLConfig(), SSLConfig()); HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); auto request = job_controller->Start( - request_delegates[i].get(), nullptr, NetLogWithSource(), + request_delegates[i].get(), nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller->main_job()); EXPECT_FALSE(job_controller->alternative_job()); @@ -1761,7 +1774,7 @@ enable_alternative_services_, SSLConfig(), SSLConfig()); HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); auto request = job_controller->Start( - request_delegates[i].get(), nullptr, NetLogWithSource(), + request_delegates[i].get(), nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller->main_job()); EXPECT_FALSE(job_controller->alternative_job()); @@ -1862,7 +1875,7 @@ enable_alternative_services_, SSLConfig(), SSLConfig()); HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); auto request = job_controller->Start( - request_delegates[i].get(), nullptr, NetLogWithSource(), + request_delegates[i].get(), nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller->main_job()); EXPECT_FALSE(job_controller->alternative_job()); @@ -1882,6 +1895,60 @@ EXPECT_FALSE(second_socket->AllReadDataConsumed()); } +// Tests that HTTP/2 throttling logic only applies to non-QUIC jobs. +TEST_F(JobControllerLimitMultipleH2Requests, QuicJobNotThrottled) { + crypto_client_stream_factory_.set_handshake_mode( + MockCryptoClientStream::COLD_START); + quic_data_ = base::MakeUnique<test::MockQuicData>(); + quic_data_->AddRead(SYNCHRONOUS, ERR_IO_PENDING); + MockRead reads[] = {MockRead(SYNCHRONOUS, ERR_IO_PENDING)}; + tcp_data_ = base::MakeUnique<SequencedSocketData>(reads, arraysize(reads), + nullptr, 0); + + tcp_data_->set_connect_data(MockConnect(ASYNC, OK)); + auto ssl_data = base::MakeUnique<SSLSocketDataProvider>(ASYNC, OK); + ssl_data->next_proto = kProtoHTTP2; + session_deps_.socket_factory->AddSSLSocketDataProvider(ssl_data.get()); + + HttpRequestInfo request_info; + request_info.method = "GET"; + request_info.url = GURL("https://www.google.com"); + + Initialize(request_info); + SpdySessionPoolPeer pool_peer(session_->spdy_session_pool()); + pool_peer.SetEnableSendingInitialData(false); + + url::SchemeHostPort server(request_info.url); + // Sets server supports QUIC. + AlternativeService alternative_service(kProtoQUIC, server.host(), 443); + SetAlternativeService(request_info, alternative_service); + + // Sets server support HTTP/2. + session_->http_server_properties()->SetSupportsSpdy(server, true); + + // Use default job factory so that Resume() is not mocked out. + HttpStreamFactoryImpl::JobFactory default_job_factory; + HttpStreamFactoryImpl::JobController* job_controller = + new HttpStreamFactoryImpl::JobController( + factory_, &request_delegate_, session_.get(), &default_job_factory, + request_info, is_preconnect_, enable_ip_based_pooling_, + enable_alternative_services_, SSLConfig(), SSLConfig()); + HttpStreamFactoryImplPeer::AddJobController(factory_, job_controller); + request_ = + job_controller->Start(&request_delegate_, nullptr, net_log_.bound(), + HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); + + EXPECT_TRUE(job_controller->main_job()); + EXPECT_TRUE(job_controller->alternative_job()); + EXPECT_CALL(request_delegate_, OnStreamReadyImpl(_, _, _)); + base::RunLoop().RunUntilIdle(); + TestNetLogEntry::List entries; + net_log_.GetEntries(&entries); + for (auto entry : entries) { + ASSERT_NE(NetLogEventType::HTTP_STREAM_JOB_THROTTLED, entry.type); + } +} + class HttpStreamFactoryImplJobControllerMisdirectedRequestRetry : public HttpStreamFactoryImplJobControllerTest, public ::testing::WithParamInterface<::testing::tuple<bool, bool>> {}; @@ -1922,7 +1989,7 @@ SetAlternativeService(request_info, alternative_service); request_ = - job_controller_->Start(&request_delegate_, nullptr, NetLogWithSource(), + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); EXPECT_TRUE(job_controller_->main_job()); if (enable_alternative_services) {
diff --git a/net/http/http_stream_factory_test_util.cc b/net/http/http_stream_factory_test_util.cc index 0f5371d..4d05c408d 100644 --- a/net/http/http_stream_factory_test_util.cc +++ b/net/http/http_stream_factory_test_util.cc
@@ -75,7 +75,7 @@ auto main_job = base::MakeUnique<MockHttpStreamFactoryImplJob>( delegate, job_type, session, request_info, priority, proxy_info, SSLConfig(), SSLConfig(), destination, origin_url, kProtoUnknown, - ProxyServer(), enable_ip_based_pooling, nullptr); + ProxyServer(), enable_ip_based_pooling, net_log); // Keep raw pointer to Job but pass ownership. main_job_ = main_job.get(); @@ -100,7 +100,7 @@ auto alternative_job = base::MakeUnique<MockHttpStreamFactoryImplJob>( delegate, job_type, session, request_info, priority, proxy_info, SSLConfig(), SSLConfig(), destination, origin_url, alternative_protocol, - ProxyServer(), enable_ip_based_pooling, nullptr); + ProxyServer(), enable_ip_based_pooling, net_log); // Keep raw pointer to Job but pass ownership. alternative_job_ = alternative_job.get(); @@ -125,7 +125,7 @@ auto alternative_job = base::MakeUnique<MockHttpStreamFactoryImplJob>( delegate, job_type, session, request_info, priority, proxy_info, SSLConfig(), SSLConfig(), destination, origin_url, kProtoUnknown, - alternative_proxy_server, enable_ip_based_pooling, nullptr); + alternative_proxy_server, enable_ip_based_pooling, net_log); // Keep raw pointer to Job but pass ownership. alternative_job_ = alternative_job.get();
diff --git a/net/quic/core/quic_flags_list.h b/net/quic/core/quic_flags_list.h index ef6cf445..d8c39b4 100644 --- a/net/quic/core/quic_flags_list.h +++ b/net/quic/core/quic_flags_list.h
@@ -211,9 +211,9 @@ // If true, use the more CPU efficient bandwidth sampler datastructure. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_faster_bandwidth_sampler, false) -// In QUIC, notify StreamNotifier instead of per-packet AckNotifier on -// every ack or retransmitted. -QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_use_stream_notifier, false) +// In QUIC, QuicSession gets notified when stream frames are acked, discarded or +// retransmitted. +QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_use_stream_notifier2, false) // When true, defaults to BBR congestion control instead of Cubic. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_default_to_bbr, false)
diff --git a/net/quic/core/quic_session.cc b/net/quic/core/quic_session.cc index 7c1bf263..5aa0de73 100644 --- a/net/quic/core/quic_session.cc +++ b/net/quic/core/quic_session.cc
@@ -47,7 +47,7 @@ currently_writing_stream_id_(0), respect_goaway_(true), use_stream_notifier_( - FLAGS_quic_reloadable_flag_quic_use_stream_notifier) {} + FLAGS_quic_reloadable_flag_quic_use_stream_notifier2) {} void QuicSession::Initialize() { connection_->set_visitor(this); @@ -382,7 +382,7 @@ stream->set_rst_sent(true); } - if (stream->IsWaitingForAcks()) { + if (use_stream_notifier_ && stream->IsWaitingForAcks()) { zombie_streams_[stream->id()] = std::move(it->second); } else { closed_streams_.push_back(std::move(it->second)); @@ -990,6 +990,7 @@ void QuicSession::OnStreamFrameAcked(const QuicStreamFrame& frame, QuicTime::Delta ack_delay_time) { QuicStream* stream = GetStream(frame.stream_id); + // Stream can already be reset when sent frame gets acked. if (stream != nullptr) { stream->OnStreamFrameAcked(frame, ack_delay_time); } @@ -997,9 +998,28 @@ void QuicSession::OnStreamFrameRetransmitted(const QuicStreamFrame& frame) { QuicStream* stream = GetStream(frame.stream_id); - if (stream != nullptr) { - stream->OnStreamFrameRetransmitted(frame); + if (stream == nullptr) { + QUIC_BUG << "Stream: " << frame.stream_id << " is closed when " << frame + << " is retransmitted."; + connection()->CloseConnection( + QUIC_INTERNAL_ERROR, "Attempt to retransmit frame of a closed stream", + ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); + return; } + stream->OnStreamFrameRetransmitted(frame); +} + +void QuicSession::OnStreamFrameDiscarded(const QuicStreamFrame& frame) { + QuicStream* stream = GetStream(frame.stream_id); + if (stream == nullptr) { + QUIC_BUG << "Stream: " << frame.stream_id << " is closed when " << frame + << " is discarded."; + connection()->CloseConnection( + QUIC_INTERNAL_ERROR, "Attempt to discard frame of a closed stream", + ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); + return; + } + stream->OnStreamFrameDiscarded(frame); } } // namespace net
diff --git a/net/quic/core/quic_session.h b/net/quic/core/quic_session.h index d70e4bdf..bad3a73 100644 --- a/net/quic/core/quic_session.h +++ b/net/quic/core/quic_session.h
@@ -113,6 +113,7 @@ void OnStreamFrameAcked(const QuicStreamFrame& frame, QuicTime::Delta ack_delay_time) override; void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override; + void OnStreamFrameDiscarded(const QuicStreamFrame& frame) override; // Called on every incoming packet. Passes |packet| through to |connection_|. virtual void ProcessUdpPacket(const QuicSocketAddress& self_address,
diff --git a/net/quic/core/quic_session_test.cc b/net/quic/core/quic_session_test.cc index 8a251a7..8877be8 100644 --- a/net/quic/core/quic_session_test.cc +++ b/net/quic/core/quic_session_test.cc
@@ -1349,15 +1349,17 @@ } TEST_P(QuicSessionTestServer, ZombieStreams) { - if (!session_.use_stream_notifier()) { - return; - } TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority); QuicStreamPeer::SetStreamBytesWritten(3, stream2); EXPECT_TRUE(stream2->IsWaitingForAcks()); EXPECT_CALL(*connection_, SendRstStream(2, _, _)); session_.CloseStream(2); + if (!session_.use_stream_notifier()) { + EXPECT_TRUE(session_.zombie_streams().empty()); + EXPECT_FALSE(session_.closed_streams()->empty()); + return; + } EXPECT_TRUE(QuicContainsKey(session_.zombie_streams(), 2)); EXPECT_TRUE(session_.closed_streams()->empty()); session_.OnStreamDoneWaitingForAcks(2);
diff --git a/net/quic/core/quic_spdy_stream_test.cc b/net/quic/core/quic_spdy_stream_test.cc index 2a87a4d..2ebc374 100644 --- a/net/quic/core/quic_spdy_stream_test.cc +++ b/net/quic/core/quic_spdy_stream_test.cc
@@ -971,7 +971,6 @@ if (!session_->use_stream_notifier()) { return; } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); @@ -1011,20 +1010,21 @@ TEST_P(QuicSpdyStreamTest, StreamBecomesZombieWithWriteThatCloses) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); QuicStreamPeer::CloseReadSide(stream_); // This write causes stream to be closed. stream_->WriteOrBufferData("Test1", true, nullptr); - // stream_ has unacked data and should become zombie. - EXPECT_TRUE(QuicContainsKey(QuicSessionPeer::zombie_streams(session_.get()), - stream_->id())); - EXPECT_TRUE(QuicSessionPeer::closed_streams(session_.get()).empty()); + if (!session_->use_stream_notifier()) { + EXPECT_TRUE(QuicSessionPeer::zombie_streams(session_.get()).empty()); + EXPECT_FALSE(QuicSessionPeer::closed_streams(session_.get()).empty()); + } else { + // stream_ has unacked data and should become zombie. + EXPECT_TRUE(QuicContainsKey(QuicSessionPeer::zombie_streams(session_.get()), + stream_->id())); + EXPECT_TRUE(QuicSessionPeer::closed_streams(session_.get()).empty()); + } } } // namespace
diff --git a/net/quic/core/quic_stream.cc b/net/quic/core/quic_stream.cc index cf8e15f..94194f4 100644 --- a/net/quic/core/quic_stream.cc +++ b/net/quic/core/quic_stream.cc
@@ -54,14 +54,14 @@ session_(session), stream_bytes_read_(0), stream_bytes_written_(0), - stream_bytes_acked_(0), + stream_bytes_outstanding_(0), stream_error_(QUIC_STREAM_NO_ERROR), connection_error_(QUIC_NO_ERROR), read_side_closed_(false), write_side_closed_(false), fin_buffered_(false), fin_sent_(false), - fin_acked_(false), + fin_outstanding_(false), fin_received_(false), rst_sent_(false), rst_received_(false), @@ -178,9 +178,6 @@ // Sending a RstStream results in calling CloseStream. session()->SendRstStream(id(), error, stream_bytes_written_); rst_sent_ = true; - if (session()->use_stream_notifier() && !IsWaitingForAcks()) { - session_->OnStreamDoneWaitingForAcks(id_); - } } void QuicStream::CloseConnectionWithDetails(QuicErrorCode error, @@ -331,6 +328,7 @@ WritevDataInner(QuicIOVector(iov, iov_count, write_length), stream_bytes_written_, fin, std::move(ack_listener)); stream_bytes_written_ += consumed_data.bytes_consumed; + stream_bytes_outstanding_ += consumed_data.bytes_consumed; AddBytesSent(consumed_data.bytes_consumed); @@ -346,6 +344,7 @@ } if (fin && consumed_data.fin_consumed) { fin_sent_ = true; + fin_outstanding_ = true; if (fin_received_) { session_->StreamDraining(id_); } @@ -504,22 +503,10 @@ void QuicStream::OnStreamFrameAcked(const QuicStreamFrame& frame, QuicTime::Delta ack_delay_time) { - DCHECK_EQ(frame.stream_id, id()); - stream_bytes_acked_ += frame.data_length; - if (stream_bytes_acked_ > stream_bytes_written_) { - CloseConnectionWithDetails(QUIC_INTERNAL_ERROR, - "Unsent stream data is acked"); - return; - } - if (frame.fin) { - fin_acked_ = true; - } + OnStreamFrameDiscarded(frame); if (ack_listener_ != nullptr) { ack_listener_->OnPacketAcked(frame.data_length, ack_delay_time); } - if (!IsWaitingForAcks()) { - session_->OnStreamDoneWaitingForAcks(id_); - } } void QuicStream::OnStreamFrameRetransmitted(const QuicStreamFrame& frame) { @@ -528,22 +515,25 @@ } } -bool QuicStream::IsWaitingForAcks() const { - if (rst_sent_ && stream_error_ != QUIC_STREAM_NO_ERROR) { - // RST_STREAM sent because of error. - return false; +void QuicStream::OnStreamFrameDiscarded(const QuicStreamFrame& frame) { + DCHECK_EQ(id_, frame.stream_id); + if (stream_bytes_outstanding_ < frame.data_length || + (!fin_outstanding_ && frame.fin)) { + CloseConnectionWithDetails(QUIC_INTERNAL_ERROR, + "Trying to discard unsent data."); + return; } - if (connection_error_ != QUIC_NO_ERROR) { - // Connection encounters error and is going to close. - return false; + stream_bytes_outstanding_ -= frame.data_length; + if (frame.fin) { + fin_outstanding_ = false; } - if (stream_bytes_acked_ == stream_bytes_written_ && - ((fin_sent_ && fin_acked_) || !fin_sent_)) { - // All sent data has been acked. - return false; + if (!IsWaitingForAcks()) { + session_->OnStreamDoneWaitingForAcks(id_); } +} - return true; +bool QuicStream::IsWaitingForAcks() const { + return stream_bytes_outstanding_ || fin_outstanding_; } } // namespace net
diff --git a/net/quic/core/quic_stream.h b/net/quic/core/quic_stream.h index e88c684b..6c4d831 100644 --- a/net/quic/core/quic_stream.h +++ b/net/quic/core/quic_stream.h
@@ -200,6 +200,7 @@ void OnStreamFrameAcked(const QuicStreamFrame& frame, QuicTime::Delta ack_delay_time) override; void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override; + void OnStreamFrameDiscarded(const QuicStreamFrame& frame) override; protected: // Sends as many bytes in the first |count| buffers of |iov| to the connection @@ -287,8 +288,8 @@ // framing, encryption overhead etc. uint64_t stream_bytes_read_; uint64_t stream_bytes_written_; - // Written bytes which have been acked. - uint64_t stream_bytes_acked_; + // Written bytes which are waiting to be acked. + uint64_t stream_bytes_outstanding_; // Stream error code received from a RstStreamFrame or error code sent by the // visitor or sequencer in the RstStreamFrame. @@ -308,8 +309,8 @@ bool fin_buffered_; // True if a FIN has been sent to the session. bool fin_sent_; - // True if a FIN has been acked. - bool fin_acked_; + // True if a FIN is waiting to be acked. + bool fin_outstanding_; // True if this stream has received (and the sequencer has accepted) a // StreamFrame with the FIN set.
diff --git a/net/quic/core/quic_stream_test.cc b/net/quic/core/quic_stream_test.cc index a2aebf5..c08eba40 100644 --- a/net/quic/core/quic_stream_test.cc +++ b/net/quic/core/quic_stream_test.cc
@@ -716,9 +716,6 @@ TEST_F(QuicStreamTest, StreamWaitsForAcks) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); // Stream is not waiting for acks initially. @@ -752,53 +749,53 @@ TEST_F(QuicStreamTest, CancelStream) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); stream_->WriteOrBufferData(kData1, false, nullptr); + QuicStreamFrame frame(stream_->id(), 0, false, kData1); EXPECT_TRUE(stream_->IsWaitingForAcks()); // Cancel stream. stream_->Reset(QUIC_STREAM_NO_ERROR); // stream still waits for acks as the error code is QUIC_STREAM_NO_ERROR, and // data is going to be retransmitted. EXPECT_TRUE(stream_->IsWaitingForAcks()); + EXPECT_CALL(*session_, + SendRstStream(stream_->id(), QUIC_STREAM_CANCELLED, 9)); stream_->Reset(QUIC_STREAM_CANCELLED); - // Stream stops waiting for acks as data is not going to be retransmitted. - EXPECT_FALSE(stream_->IsWaitingForAcks()); + if (session_->use_stream_notifier()) { + stream_->OnStreamFrameDiscarded(frame); + // Stream stops waiting for acks as data is not going to be retransmitted. + EXPECT_FALSE(stream_->IsWaitingForAcks()); + } } TEST_F(QuicStreamTest, RstFrameReceivedStreamNotFinishSending) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); stream_->WriteOrBufferData(kData1, false, nullptr); + QuicStreamFrame frame(stream_->id(), 0, false, kData1); EXPECT_TRUE(stream_->IsWaitingForAcks()); // RST_STREAM received. - QuicRstStreamFrame rst_frame(stream_->id(), QUIC_STREAM_CANCELLED, 1234); + QuicRstStreamFrame rst_frame(stream_->id(), QUIC_STREAM_CANCELLED, 9); + EXPECT_CALL(*session_, + SendRstStream(stream_->id(), QUIC_RST_ACKNOWLEDGEMENT, 9)); stream_->OnStreamReset(rst_frame); - // Stream stops waiting for acks as it does not finish sending and rst is - // sent. - EXPECT_FALSE(stream_->IsWaitingForAcks()); + if (session_->use_stream_notifier()) { + stream_->OnStreamFrameDiscarded(frame); + // Stream stops waiting for acks as it does not finish sending and rst is + // sent. + EXPECT_FALSE(stream_->IsWaitingForAcks()); + } } TEST_F(QuicStreamTest, RstFrameReceivedStreamFinishSending) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); @@ -807,6 +804,7 @@ EXPECT_TRUE(stream_->IsWaitingForAcks()); // RST_STREAM received. + EXPECT_CALL(*session_, SendRstStream(_, _, _)).Times(0); QuicRstStreamFrame rst_frame(stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); // Stream stops waiting for acks as it has unacked data. @@ -815,21 +813,23 @@ TEST_F(QuicStreamTest, ConnectionClosed) { Initialize(kShouldProcessData); - if (!session_->use_stream_notifier()) { - return; - } - EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(MockQuicSession::ConsumeAllData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); stream_->WriteOrBufferData(kData1, false, nullptr); + QuicStreamFrame frame(stream_->id(), 0, false, kData1); EXPECT_TRUE(stream_->IsWaitingForAcks()); + EXPECT_CALL(*session_, + SendRstStream(stream_->id(), QUIC_RST_ACKNOWLEDGEMENT, 9)); stream_->OnConnectionClosed(QUIC_INTERNAL_ERROR, ConnectionCloseSource::FROM_SELF); - // Stream stops waiting for acks as connection is going to close. - EXPECT_FALSE(stream_->IsWaitingForAcks()); + if (session_->use_stream_notifier()) { + stream_->OnStreamFrameDiscarded(frame); + // Stream stops waiting for acks as connection is going to close. + EXPECT_FALSE(stream_->IsWaitingForAcks()); + } } } // namespace
diff --git a/net/quic/core/quic_unacked_packet_map.cc b/net/quic/core/quic_unacked_packet_map.cc index 4c5f8b2d..d4eed3b 100644 --- a/net/quic/core/quic_unacked_packet_map.cc +++ b/net/quic/core/quic_unacked_packet_map.cc
@@ -272,6 +272,15 @@ if (frames->empty()) { continue; } + if (stream_notifier_ != nullptr) { + for (const QuicFrame& frame : *frames) { + if (frame.type != STREAM_FRAME || + frame.stream_frame->stream_id != stream_id) { + continue; + } + stream_notifier_->OnStreamFrameDiscarded(*frame.stream_frame); + } + } RemoveFramesForStream(frames, stream_id); if (frames->empty()) { RemoveRetransmittability(packet_number);
diff --git a/net/quic/core/quic_unacked_packet_map_test.cc b/net/quic/core/quic_unacked_packet_map_test.cc index 7fc9fc8..69e3315 100644 --- a/net/quic/core/quic_unacked_packet_map_test.cc +++ b/net/quic/core/quic_unacked_packet_map_test.cc
@@ -7,6 +7,8 @@ #include "net/quic/platform/api/quic_test.h" #include "net/quic/test_tools/quic_test_utils.h" +using testing::_; + namespace net { namespace test { namespace { @@ -14,11 +16,21 @@ // Default packet length. const uint32_t kDefaultLength = 1000; +class MockStreamNotifier : public StreamNotifierInterface { + public: + MOCK_METHOD2(OnStreamFrameAcked, + void(const QuicStreamFrame&, QuicTime::Delta)); + MOCK_METHOD1(OnStreamFrameRetransmitted, void(const QuicStreamFrame&)); + MOCK_METHOD1(OnStreamFrameDiscarded, void(const QuicStreamFrame&)); +}; + class QuicUnackedPacketMapTest : public QuicTest { protected: QuicUnackedPacketMapTest() : unacked_packets_(), - now_(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1000)) {} + now_(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1000)) { + unacked_packets_.SetStreamNotifier(¬ifier_); + } ~QuicUnackedPacketMapTest() override {} @@ -103,6 +115,7 @@ } QuicUnackedPacketMap unacked_packets_; QuicTime now_; + MockStreamNotifier notifier_; }; TEST_F(QuicUnackedPacketMapTest, RttOnly) { @@ -158,6 +171,7 @@ QuicPacketNumber retransmittable[] = {1}; VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); + EXPECT_CALL(notifier_, OnStreamFrameDiscarded(_)).Times(1); unacked_packets_.CancelRetransmissionsForStream(stream_id); VerifyUnackedPackets(unacked, arraysize(unacked)); VerifyInFlightPackets(unacked, arraysize(unacked)); @@ -176,6 +190,7 @@ VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); // Stop retransmissions on another stream and verify the packet is unchanged. + EXPECT_CALL(notifier_, OnStreamFrameDiscarded(_)).Times(0); unacked_packets_.CancelRetransmissionsForStream(stream_id + 2); VerifyUnackedPackets(unacked, arraysize(unacked)); VerifyInFlightPackets(unacked, arraysize(unacked)); @@ -195,6 +210,7 @@ QuicPacketNumber retransmittable[] = {2}; VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); + EXPECT_CALL(notifier_, OnStreamFrameDiscarded(_)).Times(1); unacked_packets_.CancelRetransmissionsForStream(stream_id); VerifyUnackedPackets(unacked, arraysize(unacked)); VerifyInFlightPackets(unacked, arraysize(unacked));
diff --git a/net/quic/core/stream_notifier_interface.h b/net/quic/core/stream_notifier_interface.h index 34d90be9..1237e5c5 100644 --- a/net/quic/core/stream_notifier_interface.h +++ b/net/quic/core/stream_notifier_interface.h
@@ -22,6 +22,10 @@ // Called when |frame| is retransmitted. virtual void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) = 0; + + // Called when |frame| is discarded from unacked packet map because stream is + // reset. + virtual void OnStreamFrameDiscarded(const QuicStreamFrame& frame) = 0; }; } // namespace net
diff --git a/net/quic/test_tools/quic_stream_peer.cc b/net/quic/test_tools/quic_stream_peer.cc index 7b79cb3c..4dfbea7e 100644 --- a/net/quic/test_tools/quic_stream_peer.cc +++ b/net/quic/test_tools/quic_stream_peer.cc
@@ -21,6 +21,7 @@ QuicStreamOffset stream_bytes_written, QuicStream* stream) { stream->stream_bytes_written_ = stream_bytes_written; + stream->stream_bytes_outstanding_ = stream_bytes_written; } // static
diff --git a/net/tools/quic/end_to_end_test.cc b/net/tools/quic/end_to_end_test.cc index 1b7e412..2278c61d 100644 --- a/net/tools/quic/end_to_end_test.cc +++ b/net/tools/quic/end_to_end_test.cc
@@ -2253,18 +2253,21 @@ TEST_P(EndToEndTest, CanceledStreamDoesNotBecomeZombie) { ASSERT_TRUE(Initialize()); - if (!FLAGS_quic_reloadable_flag_quic_use_stream_notifier) { + if (GetParam().force_hol_blocking) { return; } - EXPECT_TRUE(client_->client()->WaitForCryptoHandshakeConfirmed()); // Lose the request. SetPacketLossPercentage(100); - client_->SendRequest("/small_response"); - // Cancel the stream, and let the RST_STREAM go through. - SetPacketLossPercentage(0); + SpdyHeaderBlock headers; + headers[":method"] = "POST"; + headers[":path"] = "/foo"; + headers[":scheme"] = "https"; + headers[":authority"] = server_hostname_; + client_->SendMessage(headers, "test_body", /*fin=*/false); QuicSpdyClientStream* stream = client_->GetOrCreateStream(); - // Reset stream. + + // Cancel the stream. stream->Reset(QUIC_STREAM_CANCELLED); QuicSession* session = client_->client()->session(); // Verify canceled stream does not become zombie.
diff --git a/third_party/WebKit/API_OWNERS b/third_party/WebKit/API_OWNERS index f503683..e704dd9 100644 --- a/third_party/WebKit/API_OWNERS +++ b/third_party/WebKit/API_OWNERS
@@ -9,3 +9,4 @@ jochen@chromium.org rbyers@chromium.org tkent@chromium.org +mkwst@chromium.org
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-network-service b/third_party/WebKit/LayoutTests/FlagExpectations/enable-network-service index f3c1c55..ac84c2b 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-network-service +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-network-service
@@ -71,10 +71,18 @@ Bug(none) bluetooth/server/getPrimaryServices/services-not-found.html [ Failure Timeout ] Bug(none) bluetooth/service/device-same-from-2-services.html [ Timeout ] Bug(none) bluetooth/service/device-same-object.html [ Timeout ] +Bug(none) compositing/color-matching/image-color-matching.html [ Failure ] +Bug(none) compositing/geometry/video-fixed-scrolling.html [ Failure ] +Bug(none) compositing/geometry/video-opacity-overlay.html [ Failure ] Bug(none) compositing/iframes/iframe-in-composited-layer.html [ Failure ] -Bug(none) compositing/layers-inside-overflow-scroll.html [ Timeout ] +Bug(none) compositing/layers-inside-overflow-scroll.html [ Failure Timeout ] +Bug(none) compositing/overflow/overflow-compositing-descendant.html [ Failure ] +Bug(none) compositing/overflow/scroll-ancestor-update.html [ Failure ] +Bug(none) compositing/reflections/load-video-in-reflection.html [ Failure ] +Bug(none) compositing/self-painting-layers.html [ Failure ] Bug(none) compositing/self-painting-layers2.html [ Timeout ] Bug(none) compositing/video/video-reflection.html [ Timeout ] +Bug(none) compositing/visibility/visibility-simple-video-layer.html [ Failure ] Bug(none) crypto/gc.html [ Timeout ] Bug(none) css-parser/color3.html [ Failure ] Bug(none) css-parser/color3_hsl.html [ Failure ] @@ -345,7 +353,8 @@ Bug(none) external/wpt/hr-time/test_cross_frame_start.html [ Failure Timeout ] Bug(none) external/wpt/hr-time/window-worker-time-origin.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/browsing-the-web/navigating-across-documents/012.html [ Failure Timeout ] -Bug(none) external/wpt/html/browsers/browsing-the-web/read-media/pageload-video.html [ Failure Timeout ] +Bug(none) external/wpt/html/browsers/browsing-the-web/read-media/pageload-video.html [ Crash Pass Failure Timeout ] +Bug(none) external/wpt/html/browsers/browsing-the-web/unloading-documents/005.html [ Crash ] Bug(none) external/wpt/html/browsers/history/the-location-interface/location-pathname-setter-question-mark.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/history/the-location-interface/location-protocol-setter-non-broken-weird.html [ Failure Timeout Failure ] Bug(none) external/wpt/html/browsers/history/the-location-interface/location-protocol-setter-non-broken.html [ Failure Timeout ] @@ -1536,6 +1545,8 @@ Bug(none) fast/canvas/webgl/texImage-imageBitmap-from-imageBitmap-from-blob.html [ Failure ] Bug(none) fast/css/counters/counter-traverse-table-cell.html [ Failure ] Bug(none) fast/css/font-face-attribute-remove.html [ Timeout ] +Bug(none) fast/css/object-fit-grow-landscape.html [ Failure ] +Bug(none) fast/css/object-fit-grow-portrait.html [ Failure ] Bug(none) fast/dnd/file-drag-drop-on-page.html [ Failure ] Bug(none) fast/dom/Document/xml-document-focus.xml [ Failure ] Bug(none) fast/dom/Element/offsetLeft-offsetTop-body-quirk.html [ Failure ] @@ -1572,12 +1583,13 @@ Bug(none) fast/events/drag-and-drop-autoscroll-inner-frame.html [ Failure ] Bug(none) fast/events/event-on-xhr-document.html [ Failure ] Bug(none) fast/events/event-properties-gc.html [ Timeout ] -Bug(none) fast/events/media-focus-in-standalone-media-document.html [ Timeout ] +Bug(none) fast/events/media-focus-in-standalone-media-document.html [ Crash Timeout ] Bug(none) fast/events/message-port-gc-closed-cloned.html [ Timeout ] Bug(none) fast/events/message-port-gc-closed.html [ Timeout ] Bug(none) fast/events/message-port-transferables.html [ Timeout ] Bug(none) fast/events/resize-subframe.html [ Failure ] Bug(none) fast/events/touch/gesture/long-press-focuses-frame.html [ Failure ] +Bug(none) fast/events/wheel/mouse-wheel-scroll-latching.html [ Timeout Pass ] Bug(none) fast/files/apply-blob-url-to-img.html [ Timeout ] Bug(none) fast/files/apply-blob-url-to-xhr.html [ Timeout ] Bug(none) fast/files/blob-close-read.html [ Failure ] @@ -1624,6 +1636,7 @@ Bug(none) fast/frames/frameset-style-recalc.html [ Failure ] Bug(none) fast/frames/negative-remaining-length-crash.html [ Failure ] Bug(none) fast/frames/sandboxed-iframe-plugins.html [ Failure ] +Bug(none) fast/frames/set-parent-src-synchronously-xhtml.xhtml [ Crash ] Bug(none) fast/harness/internals-observe-gc.html [ Timeout ] Bug(none) fast/harness/perftests/measure-time.html [ Timeout ] Bug(none) fast/harness/perftests/runs-per-second-iterations.html [ Timeout ] @@ -1632,6 +1645,7 @@ Bug(none) fast/html/imports/import-expando-gc.html [ Timeout ] Bug(none) fast/js/nested-object-gc.html [ Timeout ] Bug(none) fast/js/with-scope-gc.html [ Timeout ] +Bug(none) fast/loader/document-destruction-within-unload.html [ Crash ] Bug(none) fast/loader/local-svg-parsed-as-svg.svg [ Timeout ] Bug(none) fast/loader/main-document-url-for-non-http-loads.html [ Failure ] Bug(none) fast/loader/reload-zero-byte-plugin.html [ Timeout ] @@ -1639,6 +1653,7 @@ Bug(none) fast/loader/simultaneous-reloads-assert.html [ Failure ] Bug(none) fast/loader/stateobjects/pushstate-in-data-url-denied.html [ Failure ] Bug(none) fast/loader/url-strip-cr-lf-tab.html [ Failure ] +Bug(none) fast/media/mq-color-gamut-picture.html [ Failure ] Bug(none) fast/mediacapturefromelement/HTMLMediaElementCapture-capture.html [ Timeout ] Bug(none) fast/mediacapturefromelement/HTMLMediaElementCapture-creation.html [ Timeout ] Bug(none) fast/mediacapturefromelement/HTMLMediaElementCapture-ended.html [ Timeout ] @@ -1647,7 +1662,10 @@ Bug(none) fast/mediastream/MediaStreamTrack-contentHint.html [ Timeout ] Bug(none) fast/parser/compatMode-in-xhtml.xhtml [ Timeout ] Bug(none) fast/parser/external-entities-in-xslt.xml [ Failure ] +Bug(none) fast/parser/xhtml-close-while-parsing.xhtml [ Crash ] Bug(none) fast/parser/xhtml-document-with-html-object.xhtml [ Timeout ] +Bug(none) fast/parser/xhtml-dom-character-data-modified-crash.html [ Crash ] +Bug(none) fast/parser/xhtml-synchronous-detach-crash.html [ Crash ] Bug(none) fast/peerconnection/RTCPeerConnection-lifetime.html [ Timeout ] Bug(none) fast/replaced/frame-removed-during-resize-smaller.html [ Timeout ] Bug(none) fast/replaced/frame-removed-during-resize.html [ Timeout ] @@ -2166,6 +2184,7 @@ Bug(none) http/tests/media/controls/video-controls-overflow-menu-updates-appropriately.html [ Timeout ] Bug(none) http/tests/media/encrypted-media/encrypted-media-encrypted-event-same-origin.html [ Timeout ] Bug(none) http/tests/media/gc-while-network-loading.html [ Timeout ] +Bug(none) http/tests/media/media-document.html [ Crash ] Bug(none) http/tests/media/media-source/mediasource-addsourcebuffer.html [ Timeout ] Bug(none) http/tests/media/media-source/mediasource-append-buffer.html [ Timeout ] Bug(none) http/tests/media/media-source/mediasource-appendwindow.html [ Timeout ] @@ -2553,11 +2572,55 @@ Bug(none) imagecapture/MediaStreamTrack-getCapabilities.html [ Timeout ] Bug(none) imagecapture/MediaStreamTrack-getSettings.html [ Timeout ] Bug(none) imagecapture/getPhotoCapabilities.html [ Timeout ] +Bug(none) imagecapture/getPhotoSettings.html [ Timeout ] Bug(none) imagecapture/setOptions-reject.html [ Timeout ] Bug(none) imagecapture/setOptions.html [ Timeout ] Bug(none) imagecapture/takePhoto-with-PhotoSettings.html [ Timeout ] Bug(none) imagecapture/takePhoto.html [ Timeout ] +Bug(none) images/cHRM_color_spin.html [ Failure ] +Bug(none) images/color-jpeg-with-color-profile.html [ Failure ] +Bug(none) images/color-profile-animate-rotate.html [ Failure ] +Bug(none) images/color-profile-animate.html [ Failure ] +Bug(none) images/color-profile-background-clip-text.html [ Failure ] +Bug(none) images/color-profile-background-image-cover.html [ Failure ] +Bug(none) images/color-profile-background-image-cross-fade-png.html [ Failure ] +Bug(none) images/color-profile-background-image-cross-fade.html [ Failure ] +Bug(none) images/color-profile-background-image-repeat.html [ Failure ] +Bug(none) images/color-profile-background-image-space.html [ Failure ] +Bug(none) images/color-profile-border-fade.html [ Failure ] +Bug(none) images/color-profile-border-image.html [ Failure ] +Bug(none) images/color-profile-border-radius.html [ Failure ] +Bug(none) images/color-profile-clip.html [ Failure ] +Bug(none) images/color-profile-drag-image.html [ Failure ] +Bug(none) images/color-profile-filter.html [ Failure ] +Bug(none) images/color-profile-group.html [ Failure ] +Bug(none) images/color-profile-iframe.html [ Failure ] +Bug(none) images/color-profile-image-canvas-pattern.html [ Failure ] +Bug(none) images/color-profile-image-canvas-svg.html [ Failure ] +Bug(none) images/color-profile-image-canvas.html [ Failure ] +Bug(none) images/color-profile-image-filter-all.html [ Failure ] +Bug(none) images/color-profile-image-object-fit.html [ Failure ] +Bug(none) images/color-profile-image-pseudo-content.html [ Failure ] +Bug(none) images/color-profile-image-shape.html [ Failure ] +Bug(none) images/color-profile-image-svg-resource-url.html [ Failure ] +Bug(none) images/color-profile-image.html [ Failure ] +Bug(none) images/color-profile-layer-filter.html [ Failure ] +Bug(none) images/color-profile-layer.html [ Failure ] +Bug(none) images/color-profile-mask-image-svg.html [ Failure ] +Bug(none) images/color-profile-munsell-adobe-to-srgb.html [ Failure ] +Bug(none) images/color-profile-object.html [ Failure ] +Bug(none) images/color-profile-svg-fill-text.html [ Failure ] +Bug(none) images/color-profile-svg-foreign-object.html [ Failure ] +Bug(none) images/color-profile-svg.html [ Failure ] +Bug(none) images/cross-fade-background-size.html [ Failure ] Bug(none) images/destroyed-image-load-event.html [ Timeout ] +Bug(none) images/jpeg-with-color-profile.html [ Failure ] +Bug(none) images/paletted-png-with-color-profile.html [ Failure ] +Bug(none) images/png-suite/test.html [ Failure ] +Bug(none) images/png-with-color-profile.html [ Failure ] +Bug(none) images/webp-color-profile-lossless.html [ Failure ] +Bug(none) images/webp-color-profile-lossy-alpha.html [ Failure ] +Bug(none) images/webp-color-profile-lossy.html [ Failure ] Bug(none) inspector-enabled/console/console-uncaught-promise-no-inspector.html [ Timeout ] Bug(none) inspector-protocol/accessibility/accessibility-nameSources-buttons.html [ Timeout ] Bug(none) inspector-protocol/css/css-get-background-colors.html [ Timeout ] @@ -2833,6 +2896,9 @@ Bug(none) media/avtrack/track-switching.html [ Timeout ] Bug(none) media/avtrack/video-track-properties.html [ Timeout ] Bug(none) media/avtrack/video-track-selected.html [ Timeout ] +Bug(none) media/color-profile-munsell-bt601-smpte-to-srgb.html [ Failure ] +Bug(none) media/color-profile-munsell-bt709-to-srgb.html [ Failure ] +Bug(none) media/color-profile-video-poster-image.html [ Failure ] Bug(none) media/color-profile-video-seek-filter.html [ Timeout ] Bug(none) media/color-profile-video-seek-object-fit.html [ Timeout ] Bug(none) media/color-profile-video-seek.html [ Timeout ] @@ -2870,6 +2936,7 @@ Bug(none) media/controls/video-enter-exit-fullscreen-while-hovering-shows-controls.html [ Timeout ] Bug(none) media/controls/video-overlay-cast-covering.html [ Timeout ] Bug(none) media/controls/video-overlay-cast-dark-rendering.html [ Timeout ] +Bug(none) media/controls/video-overlay-cast-light-rendering.html [ Failure ] Bug(none) media/controls/video-overlay-play-button.html [ Timeout ] Bug(none) media/controls/volumechange-muted-attribute.html [ Timeout ] Bug(none) media/controls/volumechange-stopimmediatepropagation.html [ Timeout ] @@ -2908,8 +2975,8 @@ Bug(none) media/media-controls-overflow-hidden.html [ Timeout ] Bug(none) media/media-controls-overflow-visible.html [ Timeout ] Bug(none) media/media-controls-tap-show-controls-without-activating.html [ Timeout ] -Bug(none) media/media-document-audio-repaint.html [ Timeout ] -Bug(none) media/media-document-audio-size.html [ Timeout ] +Bug(none) media/media-document-audio-repaint.html [ Crash Timeout ] +Bug(none) media/media-document-audio-size.html [ Crash Timeout ] Bug(none) media/media-element-play-after-eos.html [ Timeout ] Bug(none) media/media-ended.html [ Timeout ] Bug(none) media/media-extension-with-fragment.html [ Timeout ] @@ -2935,10 +3002,13 @@ Bug(none) media/video-append-source.html [ Timeout ] Bug(none) media/video-aspect-ratio.html [ Timeout ] Bug(none) media/video-autoplay.html [ Timeout ] +Bug(none) media/video-black-bg-in-media-document.html [ Crash ] Bug(none) media/video-buffered-unknown-duration.html [ Timeout ] Bug(none) media/video-buffered.html [ Timeout ] Bug(none) media/video-canvas-alpha.html [ Timeout ] Bug(none) media/video-canvas-draw.html [ Timeout ] +Bug(none) media/video-colorspace-yuv420.html [ Failure ] +Bug(none) media/video-colorspace-yuv422.html [ Failure ] Bug(none) media/video-controls-always-visible-when-control-hovered.html [ Timeout ] Bug(none) media/video-controls-attribute-fullscreen.html [ Timeout ] Bug(none) media/video-controls-auto-hide-after-play-by-touch.html [ Timeout ] @@ -2952,7 +3022,7 @@ Bug(none) media/video-controls-hidden-audio.html [ Timeout ] Bug(none) media/video-controls-hide-after-touch-on-control.html [ Timeout ] Bug(none) media/video-controls-hide-on-move-outside-controls.html [ Timeout ] -Bug(none) media/video-controls-in-media-document.html [ Timeout ] +Bug(none) media/video-controls-in-media-document.html [ Crash Timeout ] Bug(none) media/video-controls-mouse-events-captured.html [ Timeout ] Bug(none) media/video-controls-muted-video-can-unmute.html [ Timeout ] Bug(none) media/video-controls-overflow-menu-closed-captions-button.html [ Timeout ] @@ -3024,6 +3094,7 @@ Bug(none) media/video-preload.html [ Timeout ] Bug(none) media/video-remove-insert-repaints.html [ Timeout ] Bug(none) media/video-replaces-poster.html [ Timeout ] +Bug(none) media/video-scales-in-media-document.html [ Crash ] Bug(none) media/video-seek-by-small-increment.html [ Timeout ] Bug(none) media/video-seek-past-end-paused.html [ Timeout ] Bug(none) media/video-seek-past-end-playing.html [ Timeout ] @@ -3053,6 +3124,7 @@ Bug(none) media/video-webkit-appearance.html [ Timeout ] Bug(none) media/video-zoom-controls.html [ Failure Timeout ] Bug(none) media/video-zoom.html [ Failure Timeout ] +Bug(none) media/viewport-in-standalone-media-document.html [ Crash ] Bug(none) mhtml/invalid-bad-boundary.mht [ Timeout ] Bug(none) netinfo/gc-frame-listeners.html [ Timeout ] Bug(none) nfc/mock-nfc.html [ Timeout ] @@ -3060,6 +3132,8 @@ Bug(none) nfc/push.html [ Timeout ] Bug(none) nfc/watch.html [ Timeout ] Bug(none) paint/invalidation/media-audio-no-spurious-repaints.html [ Timeout ] +Bug(none) paint/invalidation/svg/relative-sized-image.xhtml [ Failure ] +Bug(none) paint/invalidation/svg/scrolling-embedded-svg-file-image-repaint-problem.html [ Failure ] Bug(none) paint/invalidation/video-mute-repaint.html [ Timeout ] Bug(none) paint/invalidation/video-paint-invalidation.html [ Timeout ] Bug(none) paint/invalidation/video-unmute-repaint.html [ Timeout ] @@ -3085,6 +3159,7 @@ Bug(none) presentation/presentation-start.html [ Timeout ] Bug(none) presentation/presentationconnectionavailableevent-ctor-mock.html [ Timeout ] Bug(none) printing/subframes-percentage-height.html [ Failure ] +Bug(none) scrollbars/listbox-scrollbar-combinations.html [ Failure ] Bug(none) sensor/accelerometer.html [ Timeout ] Bug(none) sensor/ambient-light-sensor.html [ Timeout ] Bug(none) sensor/gyroscope.html [ Timeout ] @@ -3116,12 +3191,28 @@ Bug(none) storage/websql/multiple-transactions.html [ Timeout ] Bug(none) storage/websql/transaction-error-callback-isolated-world.html [ Timeout ] Bug(none) storage/websql/transaction-success-callback-isolated-world.html [ Timeout ] +Bug(none) svg/W3C-SVG-1.1-SE/filters-image-03-f.svg [ Failure ] +Bug(none) svg/W3C-SVG-1.1-SE/filters-image-05-f.svg [ Failure ] +Bug(none) svg/W3C-SVG-1.1/render-groups-01-b.svg [ Failure ] +Bug(none) svg/W3C-SVG-1.1/render-groups-03-t.svg [ Failure ] +Bug(none) svg/W3C-SVG-1.1/struct-image-06-t.svg [ Failure ] +Bug(none) svg/W3C-SVG-1.1/struct-use-01-t.svg [ Failure ] Bug(none) svg/animations/mpath-remove-from-dependents-on-delete-crash.html [ Timeout ] Bug(none) svg/animations/target-condition-crash.html [ Timeout ] +Bug(none) svg/as-border-image/svg-as-border-image.html [ Failure ] +Bug(none) svg/as-image/image-preserveAspectRatio-all.svg [ Failure ] Bug(none) svg/custom/g-outside-svg.html [ Failure ] +Bug(none) svg/custom/group-opacity.svg [ Failure ] Bug(none) svg/dom/SVGAnimatedListPropertyTearOff-crash.html [ Timeout ] Bug(none) svg/dom/SVGMatrixTearOff-crash.html [ Timeout ] Bug(none) svg/dom/getScreenCTM-ancestor-transform.html [ Failure ] +Bug(none) svg/filters/feImage-preserveAspectRatio-all.svg [ Failure ] +Bug(none) svg/filters/feImage-preserveAspectratio.svg [ Failure ] +Bug(none) svg/filters/filter-source-position.svg [ Failure ] +Bug(none) svg/filters/filteredImage.svg [ Failure ] +Bug(none) svg/zoom/page/zoom-svg-through-object-with-absolute-size-2.xhtml [ Failure ] +Bug(none) svg/zoom/page/zoom-svg-through-object-with-absolute-size.xhtml [ Failure ] +Bug(none) svg/zoom/page/zoom-svg-through-object-with-percentage-size.xhtml [ Failure ] Bug(none) tables/mozilla/core/col_widths_fix_autoFixPer.html [ Timeout ] Bug(none) tables/mozilla_expected_failures/marvin/backgr_fixed-bg.html [ Failure ] Bug(none) traversal/node-iterator-009.html [ Failure ] @@ -3211,7 +3302,7 @@ Bug(none) webaudio/codec-tests/webm/webm-decode.html [ Timeout ] Bug(none) webaudio/constructor/mediastreamaudiodestination.html [ Timeout ] Bug(none) webaudio/constructor/mediastreamaudiosource.html [ Timeout ] -Bug(none) webaudio/decodeAudioData/decode-audio-data-basic.html [ Timeout ] +Bug(none) webaudio/decodeAudioData/decode-audio-data-basic.html [ Failure Pass Timeout ] Bug(none) webaudio/dom-exceptions.html [ Timeout ] Bug(none) webaudio/internals/audiocontext-close.html [ Timeout ] Bug(none) webaudio/internals/audiocontext-lock-threading-race.html [ Timeout ]
diff --git a/third_party/WebKit/LayoutTests/W3CImportExpectations b/third_party/WebKit/LayoutTests/W3CImportExpectations index 53d73ef..fdaf7fcb 100644 --- a/third_party/WebKit/LayoutTests/W3CImportExpectations +++ b/third_party/WebKit/LayoutTests/W3CImportExpectations
@@ -120,7 +120,8 @@ external/wpt/css/CSS2/selectors [ Skip ] external/wpt/css/CSS2/syntax [ Skip ] external/wpt/css/CSS2/tables [ Skip ] -external/wpt/css/CSS2/text [ Skip ] +## Owners: kojii@chromium.org +# external/wpt/css/CSS2/text [ Pass ] external/wpt/css/CSS2/ui [ Skip ] external/wpt/css/CSS2/values [ Skip ] external/wpt/css/CSS2/visudet [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-shadow.html b/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-shadow.html index f272924..6d44df6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-shadow.html +++ b/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-shadow.html
@@ -26,7 +26,7 @@ var expected_y = shadowDiv.offsetTop; assert_not_equals(window.scrollX, expected_x); assert_not_equals(window.scrollY, expected_y); - shadowDiv.scrollIntoView({block: "start", inlinePosition: "start"}); + shadowDiv.scrollIntoView({block: "start", inline: "start"}); assert_approx_equals(window.scrollX, expected_x, 1); assert_approx_equals(window.scrollY, expected_y, 1); }, "scrollIntoView should behave correctly if applies to shadow dom elements");
diff --git a/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-smooth.html b/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-smooth.html index 7a8b6a78..8799b8b 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-smooth.html +++ b/third_party/WebKit/LayoutTests/external/wpt/cssom-view/scrollIntoView-smooth.html
@@ -47,7 +47,7 @@ var expected_y = content.offsetTop + content_height - window_height; assert_not_equals(window.scrollX, expected_x); assert_not_equals(window.scrollY, expected_y); - content.scrollIntoView({behavior: "smooth", block: "nearest", inlinePosition: + content.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"}); return waitForScrollEnd().then(() => { assert_approx_equals(window.scrollX, expected_x, 1); @@ -61,7 +61,7 @@ var expected_y = content.offsetTop; assert_not_equals(window.scrollX, expected_x); assert_not_equals(window.scrollY, expected_y); - content.scrollIntoView({behavior: "smooth", block: "start", inlinePosition: + content.scrollIntoView({behavior: "smooth", block: "start", inline: "start"}); return waitForScrollEnd().then(() => { assert_approx_equals(window.scrollX, expected_x, 1); @@ -75,7 +75,7 @@ var expected_y = content.offsetTop + (content_height - window_height) / 2; assert_not_equals(window.scrollX, expected_x); assert_not_equals(window.scrollY, expected_y); - content.scrollIntoView({behavior: "smooth", block: "center", inlinePosition: + content.scrollIntoView({behavior: "smooth", block: "center", inline: "center"}); return waitForScrollEnd().then(() => { assert_approx_equals(window.scrollX, expected_x, 1); @@ -89,7 +89,7 @@ var expected_y = content.offsetTop + content_height - window_height; assert_not_equals(window.scrollX, expected_x); assert_not_equals(window.scrollY, expected_y); - content.scrollIntoView({behavior: "smooth", block: "end", inlinePosition: + content.scrollIntoView({behavior: "smooth", block: "end", inline: "end"}); return waitForScrollEnd().then(() => { assert_approx_equals(window.scrollX, expected_x, 1);
diff --git a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-no-resize-event-on-overflow-recalc.html b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-no-resize-event-on-overflow-recalc.html new file mode 100644 index 0000000..eb5eeca --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-no-resize-event-on-overflow-recalc.html
@@ -0,0 +1,49 @@ +<!doctype html> +<html> + <head> + <title>Viewport: No Resize Event Fired on Overflow Recalc</title> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, minimum-scale=1"> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="viewport_support.js"></script> + <style> + html { + height: 100%; + } + body { + /* Ensure overflow to start */ + height: 200%; + } + </style> + </head> + <body> + <h1>No Resize Event Fired on Overflow Recalc</h1> + <h4> + Test Description: This test ensures we don't fire spurrious resize + events when overflow is recalculated. + </h4> + <script> + function runTest() { + var t = async_test( + "Resize event not fired at window.view when content is added"); + var viewResized = false; + window.view.addEventListener('resize', function() { + viewResized = true; + }); + + requestAnimationFrame(t.step_func_done(function() { + assert_equals(viewResized, false); + })); + + document.body.style.height = "400%"; + } + + // Run the test after load to make sure any resize from load doesn't + // interfere. + window.onload = requestAnimationFrame(runTest); + </script> + <div id="log"></div> + </body> +</html> +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-causes-layout.html b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-causes-layout.html index 21d9a910..f282314 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-causes-layout.html +++ b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-causes-layout.html
@@ -1,4 +1,5 @@ <!DOCTYPE html> +<meta name="viewport" content="width=device-width, minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-in-iframe-causes-layout.html b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-in-iframe-causes-layout.html index 63cb005..2f4b734 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-in-iframe-causes-layout.html +++ b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-read-size-in-iframe-causes-layout.html
@@ -1,4 +1,5 @@ <!DOCTYPE html> +<meta name="viewport" content="width=device-width, minimum-scale=1"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <style>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-resize-event-on-load-overflowing-page.html b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-resize-event-on-load-overflowing-page.html new file mode 100644 index 0000000..4f08b66 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/viewport/viewport-resize-event-on-load-overflowing-page.html
@@ -0,0 +1,60 @@ +<!doctype html> +<html> + <head> + <title>Viewport: Resize Event On Load Overflowing Page</title> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, minimum-scale=1"> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="viewport_support.js"></script> + <script> + // This first case ensures that we load into the same kind of + // viewport. If the previous test had a page-scale factor set or a + // different viewport <meta> we might get a resize because of that. + if (location.search === "") { + window.addEventListener('load', function() { + var url = window.location.href + "?reloaded"; + window.location.href = url; + }); + } else { + var t = async_test( + "Resize event fired exactly once against window.view if " + + "scrollbars affect layout."); + var numViewResizes = 0; + window.view.addEventListener('resize', function() { + numViewResizes++; + }); + + window.addEventListener('load', function() { + requestAnimationFrame( + t.step_func_done(function() { + var isOverlay = calculateScrollbarThickness() == 0; + assert_equals(numViewResizes, isOverlay ? 0 : 1); + })); + }); + } + </script> + <style> + html { + height: 100%; + } + body { + /* Ensure overflow */ + height: 200%; + } + #log { + overflow: auto; + } + </style> + </head> + <body> + <h1>Viewport: Resize Event On Load Overflowing Page</h1> + <h4> + Test Description: This test ensures that we fire a resize event against + window.view if the page has overflow (since this creates a scrollbar + and thus changes the viewport size). + </h4> + <div id="log"></div> + </body> +</html> +
diff --git a/third_party/WebKit/LayoutTests/fast/mediastream/MediaStreamTrack-getSettings.html b/third_party/WebKit/LayoutTests/fast/mediastream/MediaStreamTrack-getSettings.html index e0cf760..720126d 100644 --- a/third_party/WebKit/LayoutTests/fast/mediastream/MediaStreamTrack-getSettings.html +++ b/third_party/WebKit/LayoutTests/fast/mediastream/MediaStreamTrack-getSettings.html
@@ -42,6 +42,9 @@ 'Width missing: ' + JSON.stringify(settings)); assert_true('height' in settings, 'Height missing: ' + JSON.stringify(settings)); + assert_true('aspectRatio' in settings, + 'Aspect ratio missing: ' + JSON.stringify(settings)); + assert_equals(settings.width / settings.height, settings.aspectRatio); }); }, 'A video track returns the expected variables');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-getSettings.html b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-getSettings.html index f8a79852..dac1d8ca 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-getSettings.html +++ b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-getSettings.html
@@ -14,13 +14,13 @@ async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); - const constraints = { advanced : [{ whiteBalanceMode : "single-shot", - exposureMode : "continuous", - focusMode : "single-shot", + const constraints = { advanced : [{ whiteBalanceMode : 'single-shot', + exposureMode : 'continuous', + focusMode : 'single-shot', pointsOfInterest : [{x : 0.1, y : 0.2}, {x : 0.3, y : 0.4}], @@ -45,7 +45,7 @@ theMock = mock; }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(() => { // |stream| must be created _after_ |mock| is constructed to give the @@ -99,7 +99,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error applying constraints: " + error.message); + assert_unreached('Error applying constraints: ' + error.message); }); }, 'exercises an applyConstraints() - getSettings() cycle');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-reject.html b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-reject.html index dc6bf81..b54385c 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-reject.html +++ b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints-reject.html
@@ -9,8 +9,8 @@ <script> var canvas = document.getElementById('canvas'); -var context = canvas.getContext("2d"); -context.fillStyle = "red"; +var context = canvas.getContext('2d'); +context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); // This test verifies that MediaStreamTrack.applyConstraints() rejects if any @@ -35,22 +35,22 @@ return new Promise(resolve => setTimeout(resolve, 100)); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(function() { const constraints = { advanced : [ getConstraint(theMock.state()) ] }; - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, 'NotSupportedError', videoTrack.applyConstraints(constraints)); }); }); }; const constraintGenerators = [ - capabilities => ({ whiteBalanceMode: "manual" }), - capabilities => ({ exposureMode: "manual" }), - capabilities => ({ focusMode: "continuous" }), + capabilities => ({ whiteBalanceMode: 'manual' }), + capabilities => ({ exposureMode: 'manual' }), + capabilities => ({ focusMode: 'continuous' }), capabilities => ({ exposureCompensation: capabilities.exposure_compensation.max + 1 }),
diff --git a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints.html b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints.html index 25013a4..6e8884cb 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints.html +++ b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-applyConstraints.html
@@ -9,20 +9,20 @@ </body> <script> -const meteringModeNames = ["none", "manual", "single-shot", "continuous"]; +const meteringModeNames = ['none', 'manual', 'single-shot', 'continuous']; // This test verifies that we can all MediaStreamTrack.applyConstraints(), with // a mock Mojo service implementation. async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); - const constraints = { advanced : [{ whiteBalanceMode : "single-shot", - exposureMode : "continuous", - focusMode : "single-shot", + const constraints = { advanced : [{ whiteBalanceMode : 'single-shot', + exposureMode : 'continuous', + focusMode : 'single-shot', pointsOfInterest : [{x : 0.1, y : 0.2}, {x : 0.3, y : 0.4}], @@ -57,7 +57,7 @@ return new Promise(resolve => setTimeout(resolve, 100)); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(() => videoTrack.applyConstraints(constraints)) .then(appliedConstraints => { @@ -69,7 +69,7 @@ assert_equals(constraintsDict.length, appliedConstraintsDict.length); Object.keys(appliedConstraintsDict).forEach((key, value) => { assert_not_equals(constraintsDict[key], undefined, 'key ' + key); - if (key != "pointsOfInterest") { + if (key != 'pointsOfInterest') { assert_equals(constraintsDict[key], appliedConstraintsDict[key], key); } else { assert_point2d_array_approx_equals(constraintsDict[key], @@ -112,7 +112,7 @@ t.done(); }) .catch(error => { - assert_unreached("applyConstraints(): " + error.message); + assert_unreached('applyConstraints(): ' + error.message); }) }, 'exercises MediaStreamTrack.applyConstraints(constraints)');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getCapabilities.html b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getCapabilities.html index e41c4fe..2400e7d9 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getCapabilities.html +++ b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getCapabilities.html
@@ -8,15 +8,15 @@ </body> <script> -const meteringModeNames = ["none", "manual", "single-shot", "continuous"]; +const meteringModeNames = ['none', 'manual', 'single-shot', 'continuous']; // This test verifies that MediaTrackCapabilities are returned upon // MediaStreamTrack.getCapabilities(), with a mock Mojo service implementation. async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var mock_capabilities; @@ -139,7 +139,7 @@ }, 100); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) }, 'exercises MediaStreamTrack.getCapabilities()');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getSettings.html b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getSettings.html index e309b99..0202562 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getSettings.html +++ b/third_party/WebKit/LayoutTests/imagecapture/MediaStreamTrack-getSettings.html
@@ -9,7 +9,7 @@ </body> <script> -const meteringModeNames = ["none", "manual", "single-shot", "continuous"]; +const meteringModeNames = ['none', 'manual', 'single-shot', 'continuous']; // This test verifies that the settings defined in the mock Mojo service // implementation are the same as those returned by the corresponding @@ -17,8 +17,8 @@ async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var mock_settings; @@ -71,7 +71,7 @@ }, 100); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }); }, 'exercises MediaStreamTrack.getSettings()');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/getPhotoCapabilities.html b/third_party/WebKit/LayoutTests/imagecapture/getPhotoCapabilities.html index b14acdf..50de2e5 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/getPhotoCapabilities.html +++ b/third_party/WebKit/LayoutTests/imagecapture/getPhotoCapabilities.html
@@ -13,8 +13,8 @@ async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var stream = canvas.captureStream(); @@ -25,7 +25,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { assert_true(typeof capturer.getPhotoCapabilities == 'function'); @@ -58,7 +58,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error during getPhotoCapabilities(): " + error.message); + assert_unreached('Error during getPhotoCapabilities(): ' + error.message); }); }, 'exercises ImageCapture.getPhotoCapabilities()');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/getPhotoSettings.html b/third_party/WebKit/LayoutTests/imagecapture/getPhotoSettings.html index a6935363..818a659f 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/getPhotoSettings.html +++ b/third_party/WebKit/LayoutTests/imagecapture/getPhotoSettings.html
@@ -8,14 +8,14 @@ </body> <script> -const fillLightModeNames = ["off", "auto", "flash"]; +const fillLightModeNames = ['off', 'auto', 'flash']; // This test verifies that ImageCapture can call getPhotoSettings(), with a // mock Mojo interface implementation. async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var stream = canvas.captureStream(); @@ -27,7 +27,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { return capturer.getPhotoSettings(); @@ -40,7 +40,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error during getPhotoSettings(): " + error.message); + assert_unreached('Error during getPhotoSettings(): ' + error.message); }); }, 'exercises ImageCapture.getPhotoSettings()');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/setOptions-reject.html b/third_party/WebKit/LayoutTests/imagecapture/setOptions-reject.html index f554253..86765bce 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/setOptions-reject.html +++ b/third_party/WebKit/LayoutTests/imagecapture/setOptions-reject.html
@@ -9,8 +9,8 @@ <script> var canvas = document.getElementById('canvas'); -var context = canvas.getContext("2d"); -context.fillStyle = "red"; +var context = canvas.getContext('2d'); +context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); // This test verifies that ImageCapture.setOptions() rejects if any passed @@ -28,7 +28,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { theCapturer = capturer; @@ -36,7 +36,7 @@ }) .then(c => { const options = getOption(theMock.state()); - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, 'NotSupportedError', theCapturer.setOptions(options)); }); }); @@ -48,7 +48,7 @@ capabilities => ({ imageHeight: capabilities.height.min - 1 }), capabilities => ({ imageWidth: capabilities.width.max + 1 }), capabilities => ({ imageWidth: capabilities.width.min - 1 }), - capabilities => ({ fillLightMode: "off" }), + capabilities => ({ fillLightMode: 'off' }), ]; for (key in optionsGenerators) {
diff --git a/third_party/WebKit/LayoutTests/imagecapture/setOptions.html b/third_party/WebKit/LayoutTests/imagecapture/setOptions.html index d6c5c60..6a3ecd3c 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/setOptions.html +++ b/third_party/WebKit/LayoutTests/imagecapture/setOptions.html
@@ -8,14 +8,14 @@ </body> <script> -const fillLightModeNames = ["off", "auto", "flash"]; +const fillLightModeNames = ['off', 'auto', 'flash']; // This test verifies that ImageCapture can call setOptions()s, with a mock Mojo // interface implementation. async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var stream = canvas.captureStream(); @@ -23,7 +23,7 @@ const optionsDict = { imageWidth : 1080, imageHeight : 100, redEyeReduction : true, - fillLightMode : "flash" + fillLightMode : 'flash' }; mockImageCaptureReady .then(mock => { @@ -31,7 +31,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { return capturer.setOptions(optionsDict); @@ -59,7 +59,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error during setOptions(): " + error.message); + assert_unreached('Error during setOptions(): ' + error.message); }); }, 'exercises ImageCapture.setOptions(options)');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/takePhoto-with-PhotoSettings.html b/third_party/WebKit/LayoutTests/imagecapture/takePhoto-with-PhotoSettings.html index 86bfea5..9cc200b 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/takePhoto-with-PhotoSettings.html +++ b/third_party/WebKit/LayoutTests/imagecapture/takePhoto-with-PhotoSettings.html
@@ -8,15 +8,15 @@ </body> <script> -const fillLightModeNames = ["off", "auto", "flash"]; +const fillLightModeNames = ['off', 'auto', 'flash']; // This test verifies that ImageCapture can call takePhoto with a PhotoSettings // argument, with a mock Mojo interface implementation. async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var stream = canvas.captureStream(); @@ -24,7 +24,7 @@ const optionsDict = { imageWidth : 1080, imageHeight : 100, redEyeReduction : true, - fillLightMode : "flash" + fillLightMode : 'flash' }; mockImageCaptureReady .then(mock => { @@ -32,7 +32,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { return capturer.takePhoto(optionsDict); @@ -64,7 +64,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error during takePhoto(): " + error.message); + assert_unreached('Error during takePhoto(): ' + error.message); }); }, 'exercises ImageCapture.takePhoto(PhotoSettings dictionary)');
diff --git a/third_party/WebKit/LayoutTests/imagecapture/takePhoto.html b/third_party/WebKit/LayoutTests/imagecapture/takePhoto.html index 21950b47..f13f853 100644 --- a/third_party/WebKit/LayoutTests/imagecapture/takePhoto.html +++ b/third_party/WebKit/LayoutTests/imagecapture/takePhoto.html
@@ -13,8 +13,8 @@ async_test(function(t) { var canvas = document.getElementById('canvas'); - var context = canvas.getContext("2d"); - context.fillStyle = "red"; + var context = canvas.getContext('2d'); + context.fillStyle = 'red'; context.fillRect(0, 0, 10, 10); var stream = canvas.captureStream(); @@ -23,7 +23,7 @@ return new ImageCapture(stream.getVideoTracks()[0]); }, error => { - assert_unreached("Error creating MockImageCapture: " + error); + assert_unreached('Error creating MockImageCapture: ' + error); }) .then(capturer => { return capturer.takePhoto(); @@ -35,7 +35,7 @@ t.done(); }) .catch(error => { - assert_unreached("Error during takePhoto(): " + error.message); + assert_unreached('Error during takePhoto(): ' + error.message); }); }, 'exercises ImageCapture.takePhoto()');
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index c8ae593..3c48c5c5 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -5792,7 +5792,7 @@ // Set the address space before setting up CSP, as the latter may override // the former via the 'treat-as-public-address' directive (see - // https://mikewest.github.io/cors-rfc1918/#csp). + // https://wicg.github.io/cors-rfc1918/#csp). if (initializer.IsHostedInReservedIPRange()) { SetAddressSpace(GetSecurityOrigin()->IsLocalhost() ? kWebAddressSpaceLocal
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp index 330388de..467981e 100644 --- a/third_party/WebKit/Source/core/dom/Element.cpp +++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -467,9 +467,6 @@ options.behavior() == "smooth") { options.setBehavior("instant"); } - } else if (arg.isNull()) { - options.setBlock("start"); - options.setInlinePosition("nearest"); } scrollIntoViewWithOptions(options); }
diff --git a/third_party/WebKit/Source/core/dom/Element.idl b/third_party/WebKit/Source/core/dom/Element.idl index c0bbbc9..227b074 100644 --- a/third_party/WebKit/Source/core/dom/Element.idl +++ b/third_party/WebKit/Source/core/dom/Element.idl
@@ -95,6 +95,8 @@ ClientRectList getClientRects(); ClientRect getBoundingClientRect(); + // TODO(sunyunjia): Add default value for scrollIntoView() once + // crbug.com/734599 is fixed. void scrollIntoView(optional (ScrollIntoViewOptions or boolean) arg); [RuntimeEnabled=CSSOMSmoothScroll, ImplementedAs=scrollTo] void scroll(optional ScrollToOptions options); [RuntimeEnabled=CSSOMSmoothScroll, ImplementedAs=scrollTo] void scroll(unrestricted double x, unrestricted double y);
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp index 90e0d76..77b04ca 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.cpp
@@ -1154,6 +1154,10 @@ PerformPreLayoutTasks(); + VisualViewport& visual_viewport = frame_->GetPage()->GetVisualViewport(); + DoubleSize viewport_size(visual_viewport.VisibleWidthCSSPx(), + visual_viewport.VisibleHeightCSSPx()); + // TODO(crbug.com/460956): The notion of a single root for layout is no longer // applicable. Remove or update this code. LayoutObject* root_for_this_layout = GetLayoutView(); @@ -1322,6 +1326,15 @@ GetLayoutView()->AssertSubtreeIsLaidOut(); #endif + if (frame_->IsMainFrame() && + RuntimeEnabledFeatures::VisualViewportAPIEnabled()) { + // Scrollbars changing state can cause a visual viewport size change. + DoubleSize new_viewport_size(visual_viewport.VisibleWidthCSSPx(), + visual_viewport.VisibleHeightCSSPx()); + if (new_viewport_size != viewport_size) + frame_->GetDocument()->EnqueueVisualViewportResizeEvent(); + } + GetFrame().GetDocument()->LayoutUpdated(); CheckDoesNotNeedLayout(); } @@ -2159,7 +2172,7 @@ SetNeedsLayout(); } -void LocalFrameView::ScrollbarExistenceDidChange() { +void LocalFrameView::ScrollbarExistenceMaybeChanged() { // We check to make sure the view is attached to a frame() as this method can // be triggered before the view is attached by LocalFrame::createView(...) // setting various values such as setScrollBarModes(...) for example. An @@ -2174,14 +2187,8 @@ ScrollbarTheme::GetTheme().UsesOverlayScrollbars() && !ShouldUseCustomScrollbars(custom_scrollbar_element); - if (!uses_overlay_scrollbars) { - if (NeedsLayout()) - UpdateLayout(); - - if (frame_->IsMainFrame() && - RuntimeEnabledFeatures::VisualViewportAPIEnabled()) - frame_->GetDocument()->EnqueueVisualViewportResizeEvent(); - } + if (!uses_overlay_scrollbars && NeedsLayout()) + UpdateLayout(); if (!GetLayoutViewItem().IsNull() && GetLayoutViewItem().UsesCompositing()) { GetLayoutViewItem().Compositor()->FrameViewScrollbarsExistenceDidChange(); @@ -2957,7 +2964,7 @@ if (has_horizontal_scrollbar != should_have_horizontal_scrollbar || has_vertical_scrollbar != should_have_vertical_scrollbar) { - ScrollbarExistenceDidChange(); + ScrollbarExistenceMaybeChanged(); if (!VisualViewportSuppliesScrollbars()) UpdateScrollbarGeometry(); @@ -4320,7 +4327,7 @@ // changes due to window resizing for example). This layout will not re-enter // updateScrollbars and does not count towards our max layout pass total. if (!scrollbars_suppressed_) - ScrollbarExistenceDidChange(); + ScrollbarExistenceMaybeChanged(); bool has_horizontal_scrollbar = HorizontalScrollbar(); bool has_vertical_scrollbar = VerticalScrollbar(); @@ -4342,9 +4349,15 @@ if (scrollbars_suppressed_) return true; - if (!HasOverlayScrollbars()) + Element* custom_scrollbar_element = nullptr; + bool uses_overlay_scrollbars = + ScrollbarTheme::GetTheme().UsesOverlayScrollbars() && + !ShouldUseCustomScrollbars(custom_scrollbar_element); + + if (!uses_overlay_scrollbars) SetNeedsLayout(); - ScrollbarExistenceDidChange(); + + ScrollbarExistenceMaybeChanged(); return true; } @@ -4403,7 +4416,7 @@ scrollbar_manager_.HasVerticalScrollbar()) { scrollbar_manager_.SetHasHorizontalScrollbar(false); scrollbar_manager_.SetHasVerticalScrollbar(false); - ScrollbarExistenceDidChange(); + ScrollbarExistenceMaybeChanged(); } AdjustScrollOffsetFromUpdateScrollbars(); return;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameView.h b/third_party/WebKit/Source/core/frame/LocalFrameView.h index fbc737c..b7546756 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameView.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameView.h
@@ -956,7 +956,7 @@ DocumentLifecycle& Lifecycle() const; void ContentsResized() override; - void ScrollbarExistenceDidChange(); + void ScrollbarExistenceMaybeChanged(); // Methods to do point conversion via layoutObjects, in order to take // transforms into account.
diff --git a/third_party/WebKit/Source/core/frame/ScrollIntoViewOptions.idl b/third_party/WebKit/Source/core/frame/ScrollIntoViewOptions.idl index 49a2c831..8e22c35 100644 --- a/third_party/WebKit/Source/core/frame/ScrollIntoViewOptions.idl +++ b/third_party/WebKit/Source/core/frame/ScrollIntoViewOptions.idl
@@ -2,5 +2,5 @@ dictionary ScrollIntoViewOptions : ScrollOptions { ScrollLogicalPosition block = "center"; - ScrollLogicalPosition inlinePosition = "center"; + [ImplementedAs=inlinePosition] ScrollLogicalPosition inline = "center"; }; \ No newline at end of file
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.cpp b/third_party/WebKit/Source/core/frame/VisualViewport.cpp index 58c5cda..6712707 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.cpp +++ b/third_party/WebKit/Source/core/frame/VisualViewport.cpp
@@ -211,30 +211,13 @@ } double VisualViewport::Width() const { - if (!MainFrame()) - return 0; - UpdateStyleAndLayoutIgnorePendingStylesheets(); - - float zoom = MainFrame()->PageZoomFactor(); - float width_css_px = AdjustScrollForAbsoluteZoom(VisibleSize().Width(), zoom); - float scrollbar_thickness_css_px = - MainFrame()->View()->VerticalScrollbarWidth() / (zoom * scale_); - return width_css_px - scrollbar_thickness_css_px; + return VisibleWidthCSSPx(); } double VisualViewport::Height() const { - if (!MainFrame()) - return 0; - UpdateStyleAndLayoutIgnorePendingStylesheets(); - - float zoom = MainFrame()->PageZoomFactor(); - float height_css_px = - AdjustScrollForAbsoluteZoom(VisibleSize().Height(), zoom); - float scrollbar_thickness_css_px = - MainFrame()->View()->HorizontalScrollbarHeight() / (zoom * scale_); - return height_css_px - scrollbar_thickness_css_px; + return VisibleHeightCSSPx(); } double VisualViewport::ScaleForVisualViewport() const { @@ -247,6 +230,29 @@ NotifyRootFrameViewport(); } +double VisualViewport::VisibleWidthCSSPx() const { + if (!MainFrame()) + return 0; + + float zoom = MainFrame()->PageZoomFactor(); + float width_css_px = AdjustScrollForAbsoluteZoom(VisibleSize().Width(), zoom); + float scrollbar_thickness_css_px = + MainFrame()->View()->VerticalScrollbarWidth() / (zoom * scale_); + return width_css_px - scrollbar_thickness_css_px; +} + +double VisualViewport::VisibleHeightCSSPx() const { + if (!MainFrame()) + return 0; + + float zoom = MainFrame()->PageZoomFactor(); + float height_css_px = + AdjustScrollForAbsoluteZoom(VisibleSize().Height(), zoom); + float scrollbar_thickness_css_px = + MainFrame()->View()->HorizontalScrollbarHeight() / (zoom * scale_); + return height_css_px - scrollbar_thickness_css_px; +} + bool VisualViewport::DidSetScaleOrLocation(float scale, const FloatPoint& location) { if (!MainFrame())
diff --git a/third_party/WebKit/Source/core/frame/VisualViewport.h b/third_party/WebKit/Source/core/frame/VisualViewport.h index 2e922a4..ad72213c 100644 --- a/third_party/WebKit/Source/core/frame/VisualViewport.h +++ b/third_party/WebKit/Source/core/frame/VisualViewport.h
@@ -223,6 +223,10 @@ double Height() const; double ScaleForVisualViewport() const; + // Used to calculate Width and Height above but do not update layout. + double VisibleWidthCSSPx() const; + double VisibleHeightCSSPx() const; + // Used for gathering data on user pinch-zoom statistics. void UserDidChangeScale(); void SendUMAMetrics();
diff --git a/third_party/WebKit/Source/core/layout/ImageQualityController.cpp b/third_party/WebKit/Source/core/layout/ImageQualityController.cpp index d0d4eab..ded5857 100644 --- a/third_party/WebKit/Source/core/layout/ImageQualityController.cpp +++ b/third_party/WebKit/Source/core/layout/ImageQualityController.cpp
@@ -30,12 +30,9 @@ #include "core/layout/ImageQualityController.h" -#include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameView.h" #include "core/frame/Settings.h" -#include "core/layout/LayoutObject.h" -#include "core/page/ChromeClient.h" -#include "core/page/Page.h" +#include "core/loader/resource/ImageResourceObserver.h" +#include "core/style/ComputedStyle.h" namespace blink { @@ -52,9 +49,9 @@ return g_image_quality_controller; } -void ImageQualityController::Remove(LayoutObject& layout_object) { +void ImageQualityController::Remove(ImageResourceObserver& layout_observer) { if (g_image_quality_controller) { - g_image_quality_controller->ObjectDestroyed(layout_object); + g_image_quality_controller->ObjectDestroyed(layout_observer); if (g_image_quality_controller->IsEmpty()) { delete g_image_quality_controller; g_image_quality_controller = nullptr; @@ -62,28 +59,28 @@ } } -bool ImageQualityController::Has(const LayoutObject& layout_object) { +bool ImageQualityController::Has(const ImageResourceObserver& layout_observer) { return g_image_quality_controller && - g_image_quality_controller->object_layer_size_map_.Contains( - &layout_object); + g_image_quality_controller->observer_layer_size_map_.Contains( + &layout_observer); } InterpolationQuality ImageQualityController::ChooseInterpolationQuality( - const LayoutObject& object, + const ImageResourceObserver& observer, + const ComputedStyle& style, + const Settings* settings, Image* image, const void* layer, - const LayoutSize& layout_size) { - if (object.Style()->ImageRendering() == EImageRendering::kPixelated) + const LayoutSize& layout_size, + double last_frame_time_monotonic) { + if (style.ImageRendering() == EImageRendering::kPixelated) return kInterpolationNone; if (kInterpolationDefault == kInterpolationLow) return kInterpolationLow; - if (ShouldPaintAtLowQuality(object, image, layer, layout_size, - object.GetFrameView() - ->GetPage() - ->GetChromeClient() - .LastFrameTimeMonotonic())) + if (ShouldPaintAtLowQuality(observer, style, settings, image, layer, + layout_size, last_frame_time_monotonic)) return kInterpolationLow; // For images that are potentially animated we paint them at medium quality. @@ -109,47 +106,47 @@ timer_ = std::move(new_timer); } -void ImageQualityController::RemoveLayer(const LayoutObject& object, +void ImageQualityController::RemoveLayer(const ImageResourceObserver& observer, LayerSizeMap* inner_map, const void* layer) { if (inner_map) { inner_map->erase(layer); if (inner_map->IsEmpty()) - ObjectDestroyed(object); + ObjectDestroyed(observer); } } -void ImageQualityController::Set(const LayoutObject& object, +void ImageQualityController::Set(const ImageResourceObserver& observer, LayerSizeMap* inner_map, const void* layer, const LayoutSize& size, bool is_resizing) { if (inner_map) { inner_map->Set(layer, size); - object_layer_size_map_.find(&object)->value.is_resizing = is_resizing; + observer_layer_size_map_.find(&observer)->value.is_resizing = is_resizing; } else { ObjectResizeInfo new_resize_info; new_resize_info.layer_size_map.Set(layer, size); new_resize_info.is_resizing = is_resizing; - object_layer_size_map_.Set(&object, new_resize_info); + observer_layer_size_map_.Set(&observer, new_resize_info); } } -void ImageQualityController::ObjectDestroyed(const LayoutObject& object) { - object_layer_size_map_.erase(&object); - if (object_layer_size_map_.IsEmpty()) { +void ImageQualityController::ObjectDestroyed( + const ImageResourceObserver& observer) { + observer_layer_size_map_.erase(&observer); + if (observer_layer_size_map_.IsEmpty()) { timer_->Stop(); } } void ImageQualityController::HighQualityRepaintTimerFired(TimerBase*) { - for (auto& i : object_layer_size_map_) { - // Only invalidate the object if it is animating. + for (auto& i : observer_layer_size_map_) { + // Only invalidate the observer if it is animating. if (!i.value.is_resizing) continue; - i.key->GetMutableForPainting().SetShouldDoFullPaintInvalidation( - PaintInvalidationReason::kImage); + i.key->RequestFullPaintInvalidationForImage(); i.value.is_resizing = false; } frame_time_when_timer_started_ = 0.0; @@ -166,7 +163,9 @@ } bool ImageQualityController::ShouldPaintAtLowQuality( - const LayoutObject& object, + const ImageResourceObserver& observer, + const ComputedStyle& style, + const Settings* settings, Image* image, const void* layer, const LayoutSize& layout_size, @@ -179,23 +178,19 @@ if (!layer) return false; - if (object.Style()->ImageRendering() == - EImageRendering::kWebkitOptimizeContrast) + if (style.ImageRendering() == EImageRendering::kWebkitOptimizeContrast) return true; - if (LocalFrame* frame = object.GetFrame()) { - if (frame->GetSettings() && - frame->GetSettings()->GetUseDefaultImageInterpolationQuality()) - return false; - } + if (settings && settings->GetUseDefaultImageInterpolationQuality()) + return false; // Look ourselves up in the hashtables. - ObjectLayerSizeMap::iterator i = object_layer_size_map_.find(&object); + ResourceSizeMap::iterator i = observer_layer_size_map_.find(&observer); LayerSizeMap* inner_map = nullptr; - bool object_is_resizing = false; - if (i != object_layer_size_map_.end()) { + bool observer_is_resizing = false; + if (i != observer_layer_size_map_.end()) { inner_map = &i->value.layer_size_map; - object_is_resizing = i->value.is_resizing; + observer_is_resizing = i->value.is_resizing; } LayoutSize old_size; bool is_first_resize = true; @@ -209,16 +204,16 @@ if (layout_size == image->Size()) { // There is no scale in effect. If we had a scale in effect before, we can - // just remove this object from the list. - RemoveLayer(object, inner_map, layer); + // just remove this observer from the list. + RemoveLayer(observer, inner_map, layer); return false; } - // If an animated resize is active for this object, paint in low quality and + // If an animated resize is active for this observer, paint in low quality and // kick the timer ahead. - if (object_is_resizing) { + if (observer_is_resizing) { bool sizes_changed = old_size != layout_size; - Set(object, inner_map, layer, layout_size, sizes_changed); + Set(observer, inner_map, layer, layout_size, sizes_changed); if (sizes_changed) RestartTimer(last_frame_time_monotonic); return true; @@ -228,19 +223,19 @@ // size and set the timer. if (is_first_resize || old_size == layout_size) { RestartTimer(last_frame_time_monotonic); - Set(object, inner_map, layer, layout_size, false); + Set(observer, inner_map, layer, layout_size, false); return false; } // If the timer is no longer active, draw at high quality and don't // set the timer. if (!timer_->IsActive()) { - RemoveLayer(object, inner_map, layer); + RemoveLayer(observer, inner_map, layer); return false; } - // This object has been resized to two different sizes while the timer + // This observer has been resized to two different sizes while the timer // is active, so draw at low quality, set the flag for animated resizes and - // the object to the list for high quality redraw. - Set(object, inner_map, layer, layout_size, true); + // the observer to the list for high quality redraw. + Set(observer, inner_map, layer, layout_size, true); RestartTimer(last_frame_time_monotonic); return true; }
diff --git a/third_party/WebKit/Source/core/layout/ImageQualityController.h b/third_party/WebKit/Source/core/layout/ImageQualityController.h index a2c11b2..899362b 100644 --- a/third_party/WebKit/Source/core/layout/ImageQualityController.h +++ b/third_party/WebKit/Source/core/layout/ImageQualityController.h
@@ -41,7 +41,9 @@ namespace blink { -class LayoutObject; +class ImageResourceObserver; +class ComputedStyle; +class Settings; typedef HashMap<const void*, LayoutSize> LayerSizeMap; @@ -50,7 +52,7 @@ bool is_resizing; }; -typedef HashMap<const LayoutObject*, ObjectResizeInfo> ObjectLayerSizeMap; +typedef HashMap<const ImageResourceObserver*, ObjectResizeInfo> ResourceSizeMap; class CORE_EXPORT ImageQualityController final { WTF_MAKE_NONCOPYABLE(ImageQualityController); @@ -61,12 +63,16 @@ static ImageQualityController* GetImageQualityController(); - static void Remove(LayoutObject&); + static void Remove(ImageResourceObserver&); - InterpolationQuality ChooseInterpolationQuality(const LayoutObject&, - Image*, - const void* layer, - const LayoutSize&); + InterpolationQuality ChooseInterpolationQuality( + const ImageResourceObserver&, + const ComputedStyle&, + const Settings*, + Image*, + const void* layer, + const LayoutSize&, + double last_frame_time_monotonic); private: static const double kCLowQualityTimeThreshold; @@ -74,23 +80,25 @@ ImageQualityController(); - static bool Has(const LayoutObject&); - void Set(const LayoutObject&, + static bool Has(const ImageResourceObserver&); + void Set(const ImageResourceObserver&, LayerSizeMap* inner_map, const void* layer, const LayoutSize&, bool is_resizing); - bool ShouldPaintAtLowQuality(const LayoutObject&, + bool ShouldPaintAtLowQuality(const ImageResourceObserver&, + const ComputedStyle&, + const Settings*, Image*, const void* layer, const LayoutSize&, double last_frame_time_monotonic); - void RemoveLayer(const LayoutObject&, + void RemoveLayer(const ImageResourceObserver&, LayerSizeMap* inner_map, const void* layer); - void ObjectDestroyed(const LayoutObject&); - bool IsEmpty() { return object_layer_size_map_.IsEmpty(); } + void ObjectDestroyed(const ImageResourceObserver&); + bool IsEmpty() { return observer_layer_size_map_.IsEmpty(); } void HighQualityRepaintTimerFired(TimerBase*); void RestartTimer(double last_frame_time_monotonic); @@ -98,7 +106,7 @@ // Only for use in testing. void SetTimer(std::unique_ptr<TimerBase>); - ObjectLayerSizeMap object_layer_size_map_; + ResourceSizeMap observer_layer_size_map_; std::unique_ptr<TimerBase> timer_; double frame_time_when_timer_started_;
diff --git a/third_party/WebKit/Source/core/layout/ImageQualityControllerTest.cpp b/third_party/WebKit/Source/core/layout/ImageQualityControllerTest.cpp index d4f9424..bed3995b2 100644 --- a/third_party/WebKit/Source/core/layout/ImageQualityControllerTest.cpp +++ b/third_party/WebKit/Source/core/layout/ImageQualityControllerTest.cpp
@@ -28,12 +28,25 @@ ImageQualityController* controller_; }; +double FrameTime(const LayoutObject* obj) { + return obj->GetFrameView() + ->GetPage() + ->GetChromeClient() + .LastFrameTimeMonotonic(); +} + +const Settings* GetSettings(const LayoutObject* obj) { + return obj->GetFrame() ? obj->GetFrame()->GetSettings() : nullptr; +} + TEST_F(ImageQualityControllerTest, RegularImage) { SetBodyInnerHTML("<img src='myimage'></img>"); LayoutObject* obj = GetDocument().body()->firstChild()->GetLayoutObject(); - EXPECT_EQ(kInterpolationDefault, Controller()->ChooseInterpolationQuality( - *obj, nullptr, nullptr, LayoutSize())); + EXPECT_EQ(kInterpolationDefault, + Controller()->ChooseInterpolationQuality( + *obj, obj->StyleRef(), GetSettings(obj), nullptr, nullptr, + LayoutSize(), FrameTime(obj))); } TEST_F(ImageQualityControllerTest, ImageRenderingPixelated) { @@ -41,8 +54,10 @@ "<img src='myimage' style='image-rendering: pixelated'></img>"); LayoutObject* obj = GetDocument().body()->firstChild()->GetLayoutObject(); - EXPECT_EQ(kInterpolationNone, Controller()->ChooseInterpolationQuality( - *obj, nullptr, nullptr, LayoutSize())); + EXPECT_EQ(kInterpolationNone, + Controller()->ChooseInterpolationQuality( + *obj, obj->StyleRef(), GetSettings(obj), nullptr, nullptr, + LayoutSize(), FrameTime(obj))); } #if !USE(LOW_QUALITY_IMAGE_INTERPOLATION) @@ -72,8 +87,9 @@ RefPtr<TestImageAnimated> test_image = AdoptRef(new TestImageAnimated); EXPECT_EQ(kInterpolationMedium, - Controller()->ChooseInterpolationQuality(*img, test_image.Get(), - nullptr, LayoutSize())); + Controller()->ChooseInterpolationQuality( + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + nullptr, LayoutSize(), FrameTime(img))); } class TestImageWithContrast : public Image { @@ -107,7 +123,8 @@ AdoptRef(new TestImageWithContrast); EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize())); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(), FrameTime(img))); } class TestImageLowQuality : public Image { @@ -138,7 +155,8 @@ RefPtr<TestImageLowQuality> test_image = AdoptRef(new TestImageLowQuality); EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(1, 1))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(1, 1), FrameTime(img))); } // TODO(alexclarke): Remove this when possible. @@ -190,24 +208,28 @@ // timer's execution. EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(2, 2))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(2, 2), FrameTime(img))); // Go into low-quality mode now that the size changed. EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(3, 3))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(3, 3), FrameTime(img))); // Stay in low-quality mode since the size changed again. EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(4, 4))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(4, 4), FrameTime(img))); mock_timer->Fire(); // The timer fired before painting at another size, so this doesn't count as // animation. Therefore not painting at low quality. EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(4, 4))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(4, 4), FrameTime(img))); } TEST_F(ImageQualityControllerTest, @@ -231,36 +253,54 @@ // Paint once. This will kick off a timer to see if we resize it during that // timer's execution. - EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *animating_image, test_image.Get(), - test_image.Get(), LayoutSize(2, 2))); + EXPECT_EQ( + kInterpolationMedium, + Controller()->ChooseInterpolationQuality( + *animating_image, animating_image->StyleRef(), + GetSettings(animating_image), test_image.Get(), test_image.Get(), + LayoutSize(2, 2), FrameTime(animating_image))); // Go into low-quality mode now that the size changed. - EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *animating_image, test_image.Get(), - test_image.Get(), LayoutSize(3, 3))); + EXPECT_EQ( + kInterpolationLow, + Controller()->ChooseInterpolationQuality( + *animating_image, animating_image->StyleRef(), + GetSettings(animating_image), test_image.Get(), test_image.Get(), + LayoutSize(3, 3), FrameTime(animating_image))); // The non-animating image receives a medium-quality filter, even though the // other one is animating. - EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *non_animating_image, test_image.Get(), - test_image.Get(), LayoutSize(4, 4))); + EXPECT_EQ( + kInterpolationMedium, + Controller()->ChooseInterpolationQuality( + *non_animating_image, non_animating_image->StyleRef(), + GetSettings(non_animating_image), test_image.Get(), test_image.Get(), + LayoutSize(4, 4), FrameTime(non_animating_image))); // Now the second image has animated, so it also gets painted with a // low-quality filter. - EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *non_animating_image, test_image.Get(), - test_image.Get(), LayoutSize(3, 3))); + EXPECT_EQ( + kInterpolationLow, + Controller()->ChooseInterpolationQuality( + *non_animating_image, non_animating_image->StyleRef(), + GetSettings(non_animating_image), test_image.Get(), test_image.Get(), + LayoutSize(3, 3), FrameTime(non_animating_image))); mock_timer->Fire(); // The timer fired before painting at another size, so this doesn't count as // animation. Therefore not painting at low quality for any image. - EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *animating_image, test_image.Get(), - test_image.Get(), LayoutSize(4, 4))); - EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *non_animating_image, test_image.Get(), - test_image.Get(), LayoutSize(4, 4))); + EXPECT_EQ( + kInterpolationMedium, + Controller()->ChooseInterpolationQuality( + *animating_image, animating_image->StyleRef(), + GetSettings(animating_image), test_image.Get(), test_image.Get(), + LayoutSize(4, 4), FrameTime(animating_image))); + EXPECT_EQ( + kInterpolationMedium, + Controller()->ChooseInterpolationQuality( + *non_animating_image, non_animating_image->StyleRef(), + GetSettings(non_animating_image), test_image.Get(), test_image.Get(), + LayoutSize(4, 4), FrameTime(non_animating_image))); } TEST_F(ImageQualityControllerTest, @@ -280,17 +320,20 @@ // timer's execution. EXPECT_EQ(kInterpolationMedium, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(2, 2))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(2, 2), FrameTime(img))); // Go into low-quality mode now that the size changed. EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(3, 3))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(3, 3), FrameTime(img))); // Stay in low-quality mode since the size changed again. EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(4, 4))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(4, 4), FrameTime(img))); mock_timer->Stop(); EXPECT_FALSE(mock_timer->IsActive()); @@ -298,7 +341,8 @@ // to low quality. EXPECT_EQ(kInterpolationLow, Controller()->ChooseInterpolationQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(4, 4))); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(4, 4), FrameTime(img))); // Check that the timer was not kicked. It should not have been, since the // image was painted at the same size as last time. EXPECT_FALSE(mock_timer->IsActive()); @@ -320,7 +364,8 @@ // timer's execution. mock_timer->SetTime(0.1); EXPECT_FALSE(Controller()->ShouldPaintAtLowQuality( - *img, test_image.Get(), test_image.Get(), LayoutSize(2, 2), 0.1)); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(2, 2), 0.1)); EXPECT_EQ(ImageQualityController::kCLowQualityTimeThreshold, mock_timer->NextFireInterval()); @@ -329,8 +374,8 @@ 0.1 + ImageQualityController::kCTimerRestartThreshold / 2.0; mock_timer->SetTime(next_time); EXPECT_EQ(true, Controller()->ShouldPaintAtLowQuality( - *img, test_image.Get(), test_image.Get(), - LayoutSize(3, 3), next_time)); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(3, 3), next_time)); // The fire interval has decreased, because we have not restarted the timer. EXPECT_EQ(ImageQualityController::kCLowQualityTimeThreshold - ImageQualityController::kCTimerRestartThreshold / 2.0, @@ -340,8 +385,8 @@ // it is half over. next_time = 0.1 + ImageQualityController::kCTimerRestartThreshold + 0.01; EXPECT_EQ(true, Controller()->ShouldPaintAtLowQuality( - *img, test_image.Get(), test_image.Get(), - LayoutSize(4, 4), next_time)); + *img, img->StyleRef(), GetSettings(img), test_image.Get(), + test_image.Get(), LayoutSize(4, 4), next_time)); // Now the timer has restarted, leading to a larger fire interval. EXPECT_EQ(ImageQualityController::kCLowQualityTimeThreshold, mock_timer->NextFireInterval());
diff --git a/third_party/WebKit/Source/core/layout/LayoutObject.h b/third_party/WebKit/Source/core/layout/LayoutObject.h index 3b136db..f9c2a00 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutObject.h
@@ -1548,6 +1548,10 @@ void ImageChanged(WrappedImagePtr, const IntRect* = nullptr) override {} bool WillRenderImage() final; bool GetImageAnimationPolicy(ImageAnimationPolicy&) final; + void RequestFullPaintInvalidationForImage() const override { + GetMutableForPainting().SetShouldDoFullPaintInvalidation( + PaintInvalidationReason::kImage); + } std::pair<int, int> SelectionStartEnd() const;
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 4524fbfc..9c5f341 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -351,7 +351,7 @@ } // Non-secure origins may not make "external requests": - // https://mikewest.github.io/cors-rfc1918/#integration-fetch + // https://wicg.github.io/cors-rfc1918/#integration-fetch if (!loading_context_->IsSecureContext() && request.IsExternalRequest()) { DispatchDidFailAccessControlCheck( ResourceError(kErrorDomainBlinkInternal, 0, request.Url().GetString(),
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 7ebac83..1b02fd5 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -1586,7 +1586,7 @@ // Tack an 'Upgrade-Insecure-Requests' header to outgoing navigational // requests, as described in - // https://w3c.github.io/webappsec/specs/upgrade/#feature-detect + // https://w3c.github.io/webappsec-upgrade-insecure-requests/#feature-detect if (resource_request.GetFrameType() != WebURLRequest::kFrameTypeNone) { // Early return if the request has already been upgraded. if (!resource_request.HttpHeaderField(HTTPNames::Upgrade_Insecure_Requests)
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResourceObserver.h b/third_party/WebKit/Source/core/loader/resource/ImageResourceObserver.h index d7f9739c..8379683 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResourceObserver.h +++ b/third_party/WebKit/Source/core/loader/resource/ImageResourceObserver.h
@@ -71,6 +71,10 @@ return ResourcePriority(); } + // Requests a full repaint for the image, called by ImageQualityController + // to schedule a high-quality repaint after an animation. + virtual void RequestFullPaintInvalidationForImage() const {} + // Name for debugging, e.g. shown in memory-infra. virtual String DebugName() const = 0;
diff --git a/third_party/WebKit/Source/core/paint/BoxPainter.cpp b/third_party/WebKit/Source/core/paint/BoxPainter.cpp index 55b61d7..293732f9 100644 --- a/third_party/WebKit/Source/core/paint/BoxPainter.cpp +++ b/third_party/WebKit/Source/core/paint/BoxPainter.cpp
@@ -5,6 +5,8 @@ #include "core/paint/BoxPainter.h" #include "core/HTMLNames.h" +#include "core/frame/LocalFrame.h" +#include "core/frame/LocalFrameView.h" #include "core/frame/Settings.h" #include "core/html/HTMLFrameOwnerElement.h" #include "core/layout/BackgroundBleedAvoidance.h" @@ -16,6 +18,8 @@ #include "core/layout/LayoutTheme.h" #include "core/layout/compositing/CompositedLayerMapping.h" #include "core/layout/line/RootInlineBox.h" +#include "core/page/ChromeClient.h" +#include "core/page/Page.h" #include "core/paint/BackgroundImageGeometry.h" #include "core/paint/BoxBorderPainter.h" #include "core/paint/BoxDecorationData.h" @@ -248,13 +252,16 @@ STACK_ALLOCATED(); public: - ImagePaintContext(const LayoutBoxModelObject& obj, + ImagePaintContext(const ImageResourceObserver& image_client, + const Document& document, + const ComputedStyle& style, GraphicsContext& context, const FillLayer& layer, const StyleImage& style_image, SkBlendMode op, - const LayoutObject* background_object, - const LayoutSize& container_size) + const LayoutSize& container_size, + double frame_time, + const Settings* settings) : context_(context), previous_interpolation_quality_(context.ImageInterpolationQuality()) { SkBlendMode bg_op = @@ -262,14 +269,14 @@ // if op != SkBlendMode::kSrcOver, a mask is being painted. composite_op_ = (op == SkBlendMode::kSrcOver) ? bg_op : op; - const LayoutObject& image_client = - background_object ? *background_object : obj; - image_ = style_image.GetImage(image_client, image_client.GetDocument(), - image_client.StyleRef(), + image_ = style_image.GetImage(image_client, document, style, FlooredIntSize(container_size)); + interpolation_quality_ = + ImageQualityController::GetImageQualityController() + ->ChooseInterpolationQuality(image_client, style, settings, + image_.Get(), &layer, container_size, + frame_time); - interpolation_quality_ = BoxPainter::ChooseInterpolationQuality( - image_client, image_.Get(), &layer, container_size); if (interpolation_quality_ != previous_interpolation_quality_) context.SetImageInterpolationQuality(interpolation_quality_); @@ -304,6 +311,8 @@ const LayoutSize& box_size, SkBlendMode op, const LayoutObject* background_object, + double frame_time, + const Settings* settings, Optional<BackgroundImageGeometry>& geometry) { // Painting a background image from an ancestor onto a cell is a complex case. if (obj.IsTableCell() && background_object && @@ -376,9 +385,12 @@ if (!info.should_paint_image || image_tile.IsEmpty()) return true; - const ImagePaintContext image_context(obj, context, layer, *info.image, op, - background_object, - geometry->TileSize()); + const LayoutObject& image_client = + background_object ? *background_object : obj; + const ImagePaintContext image_context( + image_client, image_client.GetDocument(), image_client.StyleRef(), + context, layer, *info.image, op, geometry->TileSize(), frame_time, + settings); if (!image_context.GetImage()) return true; @@ -420,11 +432,14 @@ Optional<BackgroundImageGeometry> geometry; bool has_line_box_sibling = box && (box->NextLineBox() || box->PrevLineBox()); + const Page* page = obj.GetDocument().GetPage(); + double frame_time = page->GetChromeClient().LastFrameTimeMonotonic(); + const Settings* settings = obj.GetDocument().GetSettings(); // Fast path for drawing simple color backgrounds. if (PaintFastBottomLayer(obj, paint_info, info, bg_layer, rect, bleed_avoidance, has_line_box_sibling, box_size, op, - background_object, geometry)) { + background_object, frame_time, settings, geometry)) { return; } @@ -536,9 +551,12 @@ } if (!geometry->DestRect().IsEmpty()) { - const ImagePaintContext image_context(obj, context, bg_layer, *info.image, - op, background_object, - geometry->TileSize()); + const LayoutObject& image_client = + background_object ? *background_object : obj; + const ImagePaintContext image_context( + image_client, image_client.GetDocument(), image_client.StyleRef(), + context, bg_layer, *info.image, op, geometry->TileSize(), frame_time, + settings); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage", "data", InspectorPaintImageEvent::Data(obj, *info.image)); context.DrawTiledImage( @@ -656,15 +674,6 @@ paint_info.context.FillRect(paint_rect, Color::kBlack); } -InterpolationQuality BoxPainter::ChooseInterpolationQuality( - const LayoutObject& obj, - Image* image, - const void* layer, - const LayoutSize& size) { - return ImageQualityController::GetImageQualityController() - ->ChooseInterpolationQuality(obj, image, layer, size); -} - bool BoxPainter::PaintNinePieceImage(const LayoutBoxModelObject& obj, GraphicsContext& graphics_context, const LayoutRect& rect,
diff --git a/third_party/WebKit/Source/core/paint/BoxPainter.h b/third_party/WebKit/Source/core/paint/BoxPainter.h index bb6dbf9..fccb4b5 100644 --- a/third_party/WebKit/Source/core/paint/BoxPainter.h +++ b/third_party/WebKit/Source/core/paint/BoxPainter.h
@@ -19,7 +19,6 @@ class ComputedStyle; class FillLayer; class GraphicsContext; -class Image; class InlineFlowBox; class LayoutPoint; class LayoutRect; @@ -62,10 +61,6 @@ const LayoutSize& = LayoutSize(), SkBlendMode = SkBlendMode::kSrcOver, const LayoutObject* background_object = nullptr); - static InterpolationQuality ChooseInterpolationQuality(const LayoutObject&, - Image*, - const void*, - const LayoutSize&); static bool PaintNinePieceImage(const LayoutBoxModelObject&, GraphicsContext&, const LayoutRect&,
diff --git a/third_party/WebKit/Source/core/paint/ImagePainter.cpp b/third_party/WebKit/Source/core/paint/ImagePainter.cpp index f7092b01..7512c36 100644 --- a/third_party/WebKit/Source/core/paint/ImagePainter.cpp +++ b/third_party/WebKit/Source/core/paint/ImagePainter.cpp
@@ -10,11 +10,12 @@ #include "core/frame/LocalFrame.h" #include "core/html/HTMLAreaElement.h" #include "core/html/HTMLImageElement.h" +#include "core/layout/ImageQualityController.h" #include "core/layout/LayoutImage.h" #include "core/layout/LayoutReplaced.h" #include "core/layout/TextRunConstructor.h" +#include "core/page/ChromeClient.h" #include "core/page/Page.h" -#include "core/paint/BoxPainter.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/PaintInfo.h" #include "platform/geometry/LayoutPoint.h" @@ -150,10 +151,19 @@ // FIXME: why is interpolation quality selection not included in the // Instrumentation reported cost of drawing an image? + double frame_time = layout_image_.GetFrameView() + ->GetPage() + ->GetChromeClient() + .LastFrameTimeMonotonic(); + const Settings* settings = layout_image_.GetFrame() + ? layout_image_.GetFrame()->GetSettings() + : nullptr; InterpolationQuality interpolation_quality = - BoxPainter::ChooseInterpolationQuality( - layout_image_, image.Get(), image.Get(), - LayoutSize(pixel_snapped_dest_rect.Size())); + ImageQualityController::GetImageQualityController() + ->ChooseInterpolationQuality( + layout_image_, layout_image_.StyleRef(), settings, image.Get(), + image.Get(), LayoutSize(pixel_snapped_dest_rect.Size()), + frame_time); FloatRect src_rect = image->Rect(); // If the content rect requires clipping, adjust |srcRect| and
diff --git a/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp b/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp index cec9d15..c599138e 100644 --- a/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp +++ b/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp
@@ -6,7 +6,8 @@ #include "core/layout/ImageQualityController.h" #include "core/layout/LayoutBoxModelObject.h" -#include "core/paint/BoxPainter.h" +#include "core/page/ChromeClient.h" +#include "core/page/Page.h" #include "core/paint/NinePieceImageGrid.h" #include "core/style/ComputedStyle.h" #include "core/style/NinePieceImage.h" @@ -85,15 +86,18 @@ // is one. For generated images, the actual image data (gradient stops, etc.) // are scaled to effective zoom instead so we must take care not to cause // scale of them again. - IntSize image_size = RoundedIntSize(style_image->ImageSize( - layout_object.GetDocument(), 1, border_image_rect.Size())); - RefPtr<Image> image = - style_image->GetImage(layout_object, layout_object.GetDocument(), - layout_object.StyleRef(), image_size); + const Document& document = layout_object.GetDocument(); + IntSize image_size = RoundedIntSize( + style_image->ImageSize(document, 1, border_image_rect.Size())); + RefPtr<Image> image = style_image->GetImage( + layout_object, document, layout_object.StyleRef(), image_size); + double time = document.GetPage()->GetChromeClient().LastFrameTimeMonotonic(); InterpolationQuality interpolation_quality = - BoxPainter::ChooseInterpolationQuality(layout_object, image.Get(), 0, - rect_with_outsets.Size()); + ImageQualityController::GetImageQualityController() + ->ChooseInterpolationQuality(layout_object, layout_object.StyleRef(), + document.GetSettings(), image.Get(), + nullptr, rect_with_outsets.Size(), time); InterpolationQuality previous_interpolation_quality = graphics_context.ImageInterpolationQuality(); graphics_context.SetImageInterpolationQuality(interpolation_quality);
diff --git a/third_party/WebKit/Source/core/paint/SVGImagePainter.cpp b/third_party/WebKit/Source/core/paint/SVGImagePainter.cpp index 3ff10d9..9ac4947e 100644 --- a/third_party/WebKit/Source/core/paint/SVGImagePainter.cpp +++ b/third_party/WebKit/Source/core/paint/SVGImagePainter.cpp
@@ -4,9 +4,13 @@ #include "core/paint/SVGImagePainter.h" +#include "core/frame/LocalFrame.h" +#include "core/frame/LocalFrameView.h" #include "core/layout/ImageQualityController.h" #include "core/layout/LayoutImageResource.h" #include "core/layout/svg/LayoutSVGImage.h" +#include "core/page/ChromeClient.h" +#include "core/page/Page.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/ObjectPainter.h" #include "core/paint/PaintInfo.h" @@ -71,11 +75,15 @@ image_element->preserveAspectRatio()->CurrentValue()->TransformRect(dest_rect, src_rect); + const Document& document = layout_svg_image_.GetDocument(); InterpolationQuality interpolation_quality = kInterpolationDefault; - interpolation_quality = ImageQualityController::GetImageQualityController() - ->ChooseInterpolationQuality( - layout_svg_image_, image.Get(), image.Get(), - LayoutSize(dest_rect.Size())); + interpolation_quality = + ImageQualityController::GetImageQualityController() + ->ChooseInterpolationQuality( + layout_svg_image_, layout_svg_image_.StyleRef(), + document.GetSettings(), image.Get(), image.Get(), + LayoutSize(dest_rect.Size()), + document.GetPage()->GetChromeClient().LastFrameTimeMonotonic()); InterpolationQuality previous_interpolation_quality = paint_info.context.ImageInterpolationQuality();
diff --git a/third_party/WebKit/Source/modules/BUILD.gn b/third_party/WebKit/Source/modules/BUILD.gn index cf3443a..9383f6e 100644 --- a/third_party/WebKit/Source/modules/BUILD.gn +++ b/third_party/WebKit/Source/modules/BUILD.gn
@@ -194,6 +194,8 @@ "navigatorcontentutils/testing/NavigatorContentUtilsClientMock.h", "peerconnection/testing/InternalsRTCCertificate.cpp", "peerconnection/testing/InternalsRTCCertificate.h", + "peerconnection/testing/TestingPlatformSupportWithWebRTC.cpp", + "peerconnection/testing/TestingPlatformSupportWithWebRTC.h", "serviceworkers/testing/InternalsServiceWorker.cpp", "serviceworkers/testing/InternalsServiceWorker.h", "speech/testing/InternalsSpeechSynthesis.cpp", @@ -290,6 +292,7 @@ "payments/PaymentTestHelper.h", "payments/PaymentsValidatorsTest.cpp", "peerconnection/RTCDataChannelTest.cpp", + "peerconnection/RTCPeerConnectionTest.cpp", "presentation/MockWebPresentationClient.h", "presentation/PresentationAvailabilityTest.cpp", "presentation/PresentationReceiverTest.cpp",
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp index d22178f..27d1566 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp
@@ -222,6 +222,8 @@ MediaStreamCenter::Instance().DidAddMediaStreamTrack(descriptor_, track->Component()); + for (auto& observer : observers_) + observer->OnStreamAddTrack(this, track); } void MediaStream::removeTrack(MediaStreamTrack* track, @@ -258,6 +260,8 @@ MediaStreamCenter::Instance().DidRemoveMediaStreamTrack(descriptor_, track->Component()); + for (auto& observer : observers_) + observer->OnStreamRemoveTrack(this, track); } MediaStreamTrack* MediaStream::getTrackById(String id) { @@ -304,6 +308,15 @@ StreamEnded(); } +void MediaStream::RegisterObserver(MediaStreamObserver* observer) { + DCHECK(observer); + observers_.insert(observer); +} + +void MediaStream::UnregisterObserver(MediaStreamObserver* observer) { + observers_.erase(observer); +} + void MediaStream::StreamEnded() { if (!GetExecutionContext()) return; @@ -428,6 +441,7 @@ visitor->Trace(audio_tracks_); visitor->Trace(video_tracks_); visitor->Trace(descriptor_); + visitor->Trace(observers_); visitor->Trace(scheduled_events_); EventTargetWithInlineData::Trace(visitor); ContextClient::Trace(visitor);
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStream.h b/third_party/WebKit/Source/modules/mediastream/MediaStream.h index 01924d0..fcd0946 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStream.h +++ b/third_party/WebKit/Source/modules/mediastream/MediaStream.h
@@ -39,6 +39,18 @@ class ExecutionContext; class ScriptState; +class MODULES_EXPORT MediaStreamObserver : public GarbageCollectedMixin { + public: + virtual ~MediaStreamObserver() {} + + // Invoked when |MediaStream::addTrack| is called. + virtual void OnStreamAddTrack(MediaStream*, MediaStreamTrack*) = 0; + // Invoked when |MediaStream::removeTrack| is called. + virtual void OnStreamRemoveTrack(MediaStream*, MediaStreamTrack*) = 0; + + DEFINE_INLINE_VIRTUAL_TRACE() {} +}; + class MODULES_EXPORT MediaStream final : public EventTargetWithInlineData, public ContextClient, public URLRegistrable, @@ -73,6 +85,9 @@ void TrackEnded(); + void RegisterObserver(MediaStreamObserver*); + void UnregisterObserver(MediaStreamObserver*); + // MediaStreamDescriptorClient implementation void StreamEnded() override; void AddTrackByComponent(MediaStreamComponent*) override; @@ -111,6 +126,8 @@ MediaStreamTrackVector audio_tracks_; MediaStreamTrackVector video_tracks_; Member<MediaStreamDescriptor> descriptor_; + // Observers are informed when |addTrack| and |removeTrack| are called. + HeapHashSet<WeakMember<MediaStreamObserver>> observers_; TaskRunnerTimer<MediaStream> scheduled_event_timer_; HeapVector<Member<Event>> scheduled_events_;
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp b/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp index 023f078..b6da2392 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp
@@ -263,6 +263,8 @@ settings.setWidth(platform_settings.width); if (platform_settings.HasHeight()) settings.setHeight(platform_settings.height); + if (platform_settings.HasAspectRatio()) + settings.setAspectRatio(platform_settings.aspect_ratio); if (RuntimeEnabledFeatures::MediaCaptureDepthEnabled() && component_->Source()->GetType() == MediaStreamSource::kTypeVideo) { if (platform_settings.HasVideoKind())
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl index 2b6dddb..53e12bf 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl
@@ -7,8 +7,7 @@ dictionary MediaTrackSettings { long width; long height; - // aspectRatio is not implemented. - // double aspectRatio; + double aspectRatio; double frameRate; DOMString facingMode; // volume, sampleRate and sampleSize are not implemented.
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp index 97b35c5..15dd92002 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
@@ -1103,6 +1103,11 @@ } local_streams_.push_back(stream); + stream->RegisterObserver(this); + for (auto& track : stream->getTracks()) { + DCHECK(track->Component()); + tracks_.insert(track->Component(), track); + } bool valid = peer_handler_->AddStream(stream->Descriptor(), constraints); if (!valid) @@ -1127,6 +1132,7 @@ return; local_streams_.erase(pos); + stream->UnregisterObserver(this); peer_handler_->RemoveStream(stream->Descriptor()); @@ -1201,7 +1207,7 @@ // yet, create it. MediaStreamTrack* track = nullptr; if (web_rtp_senders[i]->Track()) { - track = GetLocalTrackById(web_rtp_senders[i]->Track()->Id()); + track = GetTrack(*web_rtp_senders[i]->Track()); DCHECK(track); } RTCRtpSender* rtp_sender = @@ -1225,8 +1231,7 @@ } else { // There does not exist a |RTCRtpReceiver| for this |WebRTCRtpReceiver| // yet, create it. - MediaStreamTrack* track = - GetRemoteTrackById(web_rtp_receivers[i]->Track().Id()); + MediaStreamTrack* track = GetTrack(web_rtp_receivers[i]->Track()); DCHECK(track); RTCRtpReceiver* rtp_receiver = new RTCRtpReceiver(std::move(web_rtp_receivers[i]), track); @@ -1278,24 +1283,9 @@ return channel; } -MediaStreamTrack* RTCPeerConnection::GetLocalTrackById( - const String& track_id) const { - for (const auto& local_stream : local_streams_) { - MediaStreamTrack* track = local_stream->getTrackById(track_id); - if (track) - return track; - } - return nullptr; -} - -MediaStreamTrack* RTCPeerConnection::GetRemoteTrackById( - const String& track_id) const { - for (const auto& remote_stream : remote_streams_) { - MediaStreamTrack* track = remote_stream->getTrackById(track_id); - if (track) - return track; - } - return nullptr; +MediaStreamTrack* RTCPeerConnection::GetTrack( + const WebMediaStreamTrack& web_track) const { + return tracks_.at(static_cast<MediaStreamComponent*>(web_track)); } void RTCPeerConnection::RemoveInactiveSenders() { @@ -1332,7 +1322,14 @@ DCHECK(track); - if (!GetLocalTrackById(track->id())) { + bool is_local_stream_track = false; + for (const auto& local_stream : local_streams_) { + if (local_stream->getTracks().Contains(track)) { + is_local_stream_track = true; + break; + } + } + if (!is_local_stream_track) { exception_state.ThrowDOMException( kSyntaxError, "No local stream is available for the track provided."); return nullptr; @@ -1352,6 +1349,21 @@ CloseInternal(); } +void RTCPeerConnection::OnStreamAddTrack(MediaStream* stream, + MediaStreamTrack* track) { + DCHECK(track); + DCHECK(track->Component()); + // Insert if not already present. + tracks_.insert(track->Component(), track); +} + +void RTCPeerConnection::OnStreamRemoveTrack(MediaStream* stream, + MediaStreamTrack* track) { + // Don't remove |track| from |tracks_|, it may be referenced by another + // component. |tracks_| uses weak members and will automatically have |track| + // removed if destroyed. +} + void RTCPeerConnection::NegotiationNeeded() { DCHECK(!closed_); ScheduleDispatchEvent(Event::Create(EventTypeNames::negotiationneeded)); @@ -1402,6 +1414,11 @@ MediaStream* stream = MediaStream::Create(GetExecutionContext(), remote_stream); remote_streams_.push_back(stream); + stream->RegisterObserver(this); + for (auto& track : stream->getTracks()) { + DCHECK(track->Component()); + tracks_.insert(track->Component(), track); + } ScheduleDispatchEvent( MediaStreamEvent::Create(EventTypeNames::addstream, stream)); @@ -1424,6 +1441,7 @@ size_t pos = remote_streams_.Find(stream); DCHECK(pos != kNotFound); remote_streams_.erase(pos); + stream->UnregisterObserver(this); // The receivers of removed tracks will have become inactive. RemoveInactiveReceivers(); @@ -1574,22 +1592,19 @@ void RTCPeerConnection::RecordRapporMetrics() { Document* document = ToDocument(GetExecutionContext()); - for (const auto& stream : local_streams_) { - if (stream->getAudioTracks().size() > 0) - HostsUsingFeatures::CountAnyWorld( - *document, HostsUsingFeatures::Feature::kRTCPeerConnectionAudio); - if (stream->getVideoTracks().size() > 0) - HostsUsingFeatures::CountAnyWorld( - *document, HostsUsingFeatures::Feature::kRTCPeerConnectionVideo); - } - - for (const auto& stream : remote_streams_) { - if (stream->getAudioTracks().size() > 0) - HostsUsingFeatures::CountAnyWorld( - *document, HostsUsingFeatures::Feature::kRTCPeerConnectionAudio); - if (stream->getVideoTracks().size() > 0) - HostsUsingFeatures::CountAnyWorld( - *document, HostsUsingFeatures::Feature::kRTCPeerConnectionVideo); + for (const auto& component : tracks_.Keys()) { + switch (component->Source()->GetType()) { + case MediaStreamSource::kTypeAudio: + HostsUsingFeatures::CountAnyWorld( + *document, HostsUsingFeatures::Feature::kRTCPeerConnectionAudio); + break; + case MediaStreamSource::kTypeVideo: + HostsUsingFeatures::CountAnyWorld( + *document, HostsUsingFeatures::Feature::kRTCPeerConnectionVideo); + break; + default: + NOTREACHED(); + } } if (has_data_channels_) @@ -1600,12 +1615,14 @@ DEFINE_TRACE(RTCPeerConnection) { visitor->Trace(local_streams_); visitor->Trace(remote_streams_); + visitor->Trace(tracks_); visitor->Trace(rtp_senders_); visitor->Trace(rtp_receivers_); visitor->Trace(dispatch_scheduled_event_runner_); visitor->Trace(scheduled_events_); EventTargetWithInlineData::Trace(visitor); SuspendableObject::Trace(visitor); + MediaStreamObserver::Trace(visitor); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.h b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.h index 765b7e4..4bc2b0f0 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.h +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.h
@@ -57,6 +57,7 @@ class RTCIceCandidateInitOrRTCIceCandidate; class RTCOfferOptions; class RTCPeerConnectionErrorCallback; +class RTCPeerConnectionTest; class RTCRtpReceiver; class RTCRtpSender; class RTCSessionDescription; @@ -67,10 +68,12 @@ class VoidCallback; struct WebRTCConfiguration; -class RTCPeerConnection final : public EventTargetWithInlineData, - public WebRTCPeerConnectionHandlerClient, - public ActiveScriptWrappable<RTCPeerConnection>, - public SuspendableObject { +class MODULES_EXPORT RTCPeerConnection final + : public EventTargetWithInlineData, + public WebRTCPeerConnectionHandlerClient, + public ActiveScriptWrappable<RTCPeerConnection>, + public SuspendableObject, + public MediaStreamObserver { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(RTCPeerConnection); USING_PRE_FINALIZER(RTCPeerConnection, Dispose); @@ -176,6 +179,10 @@ DEFINE_ATTRIBUTE_EVENT_LISTENER(icegatheringstatechange); DEFINE_ATTRIBUTE_EVENT_LISTENER(datachannel); + // MediaStreamObserver + void OnStreamAddTrack(MediaStream*, MediaStreamTrack*) override; + void OnStreamRemoveTrack(MediaStream*, MediaStreamTrack*) override; + // WebRTCPeerConnectionHandlerClient void NegotiationNeeded() override; void DidGenerateICECandidate(const WebRTCICECandidate&) override; @@ -204,6 +211,8 @@ DECLARE_VIRTUAL_TRACE(); private: + friend class RTCPeerConnectionTest; + typedef Function<bool()> BoolFunction; class EventWrapper : public GarbageCollectedFinalized<EventWrapper> { public: @@ -229,8 +238,7 @@ void ScheduleDispatchEvent(Event*); void ScheduleDispatchEvent(Event*, std::unique_ptr<BoolFunction>); void DispatchScheduledEvent(); - MediaStreamTrack* GetLocalTrackById(const String& track_id) const; - MediaStreamTrack* GetRemoteTrackById(const String& track_id) const; + MediaStreamTrack* GetTrack(const WebMediaStreamTrack& web_track) const; // Senders and receivers returned by the handler are in use by the peer // connection, a sender or receiver that is no longer in use is permanently // inactive and does not need to be referenced anymore. These methods removes @@ -258,11 +266,13 @@ ICEGatheringState ice_gathering_state_; ICEConnectionState ice_connection_state_; - // TODO(hbos): Move away from "addStream" and "removeStream" in favor of - // "addTrack" and "removeTrack". Update tracks, senders and receivers on - // relevant events. https://crbug.com/705901 MediaStreamVector local_streams_; MediaStreamVector remote_streams_; + // A map containing any track that is in use by the peer connection. This + // includes tracks of |local_streams_|, |remote_streams_|, |rtp_senders_| and + // |rtp_receivers_|. + HeapHashMap<WeakMember<MediaStreamComponent>, WeakMember<MediaStreamTrack>> + tracks_; HeapHashMap<uintptr_t, Member<RTCRtpSender>> rtp_senders_; HeapHashMap<uintptr_t, Member<RTCRtpReceiver>> rtp_receivers_;
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnectionTest.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnectionTest.cpp new file mode 100644 index 0000000..2530a422 --- /dev/null +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnectionTest.cpp
@@ -0,0 +1,236 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/peerconnection/RTCPeerConnection.h" + +#include <string> + +#include "bindings/core/v8/Dictionary.h" +#include "bindings/core/v8/V8BindingForTesting.h" +#include "modules/mediastream/MediaStream.h" +#include "modules/mediastream/MediaStreamTrack.h" +#include "modules/peerconnection/RTCConfiguration.h" +#include "modules/peerconnection/RTCIceServer.h" +#include "modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h" +#include "platform/heap/HeapAllocator.h" +#include "platform/testing/TestingPlatformSupport.h" +#include "public/platform/Platform.h" +#include "public/platform/WebRTCError.h" +#include "public/platform/WebRTCPeerConnectionHandler.h" +#include "public/platform/WebRTCRtpReceiver.h" +#include "public/platform/WebRTCRtpSender.h" +#include "public/platform/WebRTCSessionDescription.h" +#include "public/web/WebHeap.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +class RTCPeerConnectionTest : public ::testing::Test { + public: + RTCPeerConnection* CreatePC(V8TestingScope& scope) { + RTCConfiguration config; + RTCIceServer ice_server; + ice_server.setURL("stun:fake.stun.url"); + HeapVector<RTCIceServer> ice_servers; + ice_servers.push_back(ice_server); + config.setIceServers(ice_servers); + return RTCPeerConnection::Create(scope.GetExecutionContext(), config, + Dictionary(), scope.GetExceptionState()); + } + + MediaStreamTrack* CreateTrack(V8TestingScope& scope, + MediaStreamSource::StreamType type, + String id) { + MediaStreamSource* source = + MediaStreamSource::Create("sourceId", type, "sourceName", false); + MediaStreamComponent* component = MediaStreamComponent::Create(id, source); + return MediaStreamTrack::Create(scope.GetExecutionContext(), component); + } + + std::string GetExceptionMessage(V8TestingScope& scope) { + ExceptionState& exception_state = scope.GetExceptionState(); + return exception_state.HadException() + ? exception_state.Message().Utf8().data() + : ""; + } + + void AddStream(V8TestingScope& scope, + RTCPeerConnection* pc, + MediaStream* stream) { + pc->addStream(scope.GetScriptState(), stream, Dictionary(), + scope.GetExceptionState()); + EXPECT_EQ("", GetExceptionMessage(scope)); + } + + void RemoveStream(V8TestingScope& scope, + RTCPeerConnection* pc, + MediaStream* stream) { + pc->removeStream(stream, scope.GetExceptionState()); + EXPECT_EQ("", GetExceptionMessage(scope)); + } + + MediaStreamTrack* GetTrack(RTCPeerConnection* pc, + MediaStreamComponent* component) { + return pc->GetTrack(component); + } + + private: + ScopedTestingPlatformSupport<TestingPlatformSupportWithWebRTC> platform; +}; + +TEST_F(RTCPeerConnectionTest, GetAudioTrack) { + V8TestingScope scope; + RTCPeerConnection* pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + MediaStreamTrack* track = + CreateTrack(scope, MediaStreamSource::kTypeAudio, "audioTrack"); + HeapVector<Member<MediaStreamTrack>> tracks; + tracks.push_back(track); + MediaStream* stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + EXPECT_FALSE(GetTrack(pc, track->Component())); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, track->Component())); +} + +TEST_F(RTCPeerConnectionTest, GetVideoTrack) { + V8TestingScope scope; + RTCPeerConnection* pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + MediaStreamTrack* track = + CreateTrack(scope, MediaStreamSource::kTypeVideo, "videoTrack"); + HeapVector<Member<MediaStreamTrack>> tracks; + tracks.push_back(track); + MediaStream* stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + EXPECT_FALSE(GetTrack(pc, track->Component())); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, track->Component())); +} + +TEST_F(RTCPeerConnectionTest, GetAudioAndVideoTrack) { + V8TestingScope scope; + RTCPeerConnection* pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + HeapVector<Member<MediaStreamTrack>> tracks; + MediaStreamTrack* audio_track = + CreateTrack(scope, MediaStreamSource::kTypeAudio, "audioTrack"); + tracks.push_back(audio_track); + MediaStreamTrack* video_track = + CreateTrack(scope, MediaStreamSource::kTypeVideo, "videoTrack"); + tracks.push_back(video_track); + + MediaStream* stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + EXPECT_FALSE(GetTrack(pc, audio_track->Component())); + EXPECT_FALSE(GetTrack(pc, video_track->Component())); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, audio_track->Component())); + EXPECT_TRUE(GetTrack(pc, video_track->Component())); +} + +TEST_F(RTCPeerConnectionTest, GetTrackRemoveStreamAndGCAll) { + V8TestingScope scope; + Persistent<RTCPeerConnection> pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + MediaStreamTrack* track = + CreateTrack(scope, MediaStreamSource::kTypeAudio, "audioTrack"); + HeapVector<Member<MediaStreamTrack>> tracks; + tracks.push_back(track); + MediaStream* stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + MediaStreamComponent* track_component = track->Component(); + + EXPECT_FALSE(GetTrack(pc, track_component)); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, track_component)); + + RemoveStream(scope, pc, stream); + // This will destroy |MediaStream|, |MediaStreamTrack| and its + // |MediaStreamComponent|, which will remove its mapping from the peer + // connection. + WebHeap::CollectAllGarbageForTesting(); + EXPECT_FALSE(GetTrack(pc, track_component)); +} + +TEST_F(RTCPeerConnectionTest, + GetTrackRemoveStreamAndGCWithPersistentComponent) { + V8TestingScope scope; + Persistent<RTCPeerConnection> pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + MediaStreamTrack* track = + CreateTrack(scope, MediaStreamSource::kTypeAudio, "audioTrack"); + HeapVector<Member<MediaStreamTrack>> tracks; + tracks.push_back(track); + MediaStream* stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + Persistent<MediaStreamComponent> track_component = track->Component(); + + EXPECT_FALSE(GetTrack(pc, track_component)); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, track_component)); + + RemoveStream(scope, pc, stream); + // This will destroy |MediaStream| and |MediaStreamTrack| (but not + // |MediaStreamComponent|), which will remove its mapping from the peer + // connection. + WebHeap::CollectAllGarbageForTesting(); + EXPECT_FALSE(GetTrack(pc, track_component)); +} + +TEST_F(RTCPeerConnectionTest, GetTrackRemoveStreamAndGCWithPersistentStream) { + V8TestingScope scope; + Persistent<RTCPeerConnection> pc = CreatePC(scope); + EXPECT_EQ("", GetExceptionMessage(scope)); + ASSERT_TRUE(pc); + + MediaStreamTrack* track = + CreateTrack(scope, MediaStreamSource::kTypeAudio, "audioTrack"); + HeapVector<Member<MediaStreamTrack>> tracks; + tracks.push_back(track); + Persistent<MediaStream> stream = + MediaStream::Create(scope.GetExecutionContext(), tracks); + ASSERT_TRUE(stream); + + MediaStreamComponent* track_component = track->Component(); + + EXPECT_FALSE(GetTrack(pc, track_component)); + AddStream(scope, pc, stream); + EXPECT_TRUE(GetTrack(pc, track_component)); + + RemoveStream(scope, pc, stream); + // With a persistent |MediaStream|, the |MediaStreamTrack| and + // |MediaStreamComponent| will not be destroyed and continue to be mapped by + // peer connection. + WebHeap::CollectAllGarbageForTesting(); + EXPECT_TRUE(GetTrack(pc, track_component)); + + stream = nullptr; + // Now |MediaStream|, |MediaStreamTrack| and |MediaStreamComponent| will be + // destroyed and the mapping removed from the peer connection. + WebHeap::CollectAllGarbageForTesting(); + EXPECT_FALSE(GetTrack(pc, track_component)); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.cpp b/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.cpp new file mode 100644 index 0000000..ffbd1a0c --- /dev/null +++ b/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.cpp
@@ -0,0 +1,102 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h" + +#include "public/platform/WebRTCError.h" +#include "public/platform/WebRTCRtpReceiver.h" +#include "public/platform/WebRTCRtpSender.h" +#include "public/platform/WebRTCSessionDescription.h" +#include "public/platform/WebVector.h" + +namespace blink { + +MockWebRTCPeerConnectionHandler::MockWebRTCPeerConnectionHandler() {} + +MockWebRTCPeerConnectionHandler::~MockWebRTCPeerConnectionHandler() {} + +bool MockWebRTCPeerConnectionHandler::Initialize(const WebRTCConfiguration&, + const WebMediaConstraints&) { + return true; +} + +void MockWebRTCPeerConnectionHandler::CreateOffer( + const WebRTCSessionDescriptionRequest&, + const WebMediaConstraints&) {} + +void MockWebRTCPeerConnectionHandler::CreateOffer( + const WebRTCSessionDescriptionRequest&, + const WebRTCOfferOptions&) {} + +void MockWebRTCPeerConnectionHandler::CreateAnswer( + const WebRTCSessionDescriptionRequest&, + const WebMediaConstraints&) {} + +void MockWebRTCPeerConnectionHandler::CreateAnswer( + const WebRTCSessionDescriptionRequest&, + const WebRTCAnswerOptions&) {} + +void MockWebRTCPeerConnectionHandler::SetLocalDescription( + const WebRTCVoidRequest&, + const WebRTCSessionDescription&) {} + +void MockWebRTCPeerConnectionHandler::SetRemoteDescription( + const WebRTCVoidRequest&, + const WebRTCSessionDescription&) {} + +WebRTCSessionDescription MockWebRTCPeerConnectionHandler::LocalDescription() { + return WebRTCSessionDescription(); +} + +WebRTCSessionDescription MockWebRTCPeerConnectionHandler::RemoteDescription() { + return WebRTCSessionDescription(); +} + +WebRTCErrorType MockWebRTCPeerConnectionHandler::SetConfiguration( + const WebRTCConfiguration&) { + return WebRTCErrorType::kNone; +} + +bool MockWebRTCPeerConnectionHandler::AddStream(const WebMediaStream&, + const WebMediaConstraints&) { + return true; +} + +void MockWebRTCPeerConnectionHandler::RemoveStream(const WebMediaStream&) {} + +void MockWebRTCPeerConnectionHandler::GetStats(const WebRTCStatsRequest&) {} + +void MockWebRTCPeerConnectionHandler::GetStats( + std::unique_ptr<WebRTCStatsReportCallback>) {} + +WebVector<std::unique_ptr<WebRTCRtpSender>> +MockWebRTCPeerConnectionHandler::GetSenders() { + return WebVector<std::unique_ptr<WebRTCRtpSender>>(); +} + +WebVector<std::unique_ptr<WebRTCRtpReceiver>> +MockWebRTCPeerConnectionHandler::GetReceivers() { + return WebVector<std::unique_ptr<WebRTCRtpReceiver>>(); +} + +WebRTCDataChannelHandler* MockWebRTCPeerConnectionHandler::CreateDataChannel( + const WebString& label, + const WebRTCDataChannelInit&) { + return nullptr; +} + +WebRTCDTMFSenderHandler* MockWebRTCPeerConnectionHandler::CreateDTMFSender( + const WebMediaStreamTrack&) { + return nullptr; +} + +void MockWebRTCPeerConnectionHandler::Stop() {} + +std::unique_ptr<WebRTCPeerConnectionHandler> +TestingPlatformSupportWithWebRTC::CreateRTCPeerConnectionHandler( + WebRTCPeerConnectionHandlerClient*) { + return WTF::MakeUnique<MockWebRTCPeerConnectionHandler>(); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h b/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h new file mode 100644 index 0000000..52608f9 --- /dev/null +++ b/third_party/WebKit/Source/modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h
@@ -0,0 +1,54 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "bindings/core/v8/V8BindingForTesting.h" +#include "platform/testing/TestingPlatformSupport.h" +#include "public/platform/WebRTCPeerConnectionHandler.h" + +namespace blink { + +class MockWebRTCPeerConnectionHandler : public WebRTCPeerConnectionHandler { + public: + MockWebRTCPeerConnectionHandler(); + ~MockWebRTCPeerConnectionHandler() override; + + bool Initialize(const WebRTCConfiguration&, + const WebMediaConstraints&) override; + + void CreateOffer(const WebRTCSessionDescriptionRequest&, + const WebMediaConstraints&) override; + void CreateOffer(const WebRTCSessionDescriptionRequest&, + const WebRTCOfferOptions&) override; + void CreateAnswer(const WebRTCSessionDescriptionRequest&, + const WebMediaConstraints&) override; + void CreateAnswer(const WebRTCSessionDescriptionRequest&, + const WebRTCAnswerOptions&) override; + void SetLocalDescription(const WebRTCVoidRequest&, + const WebRTCSessionDescription&) override; + void SetRemoteDescription(const WebRTCVoidRequest&, + const WebRTCSessionDescription&) override; + WebRTCSessionDescription LocalDescription() override; + WebRTCSessionDescription RemoteDescription() override; + WebRTCErrorType SetConfiguration(const WebRTCConfiguration&) override; + bool AddStream(const WebMediaStream&, const WebMediaConstraints&) override; + void RemoveStream(const WebMediaStream&) override; + void GetStats(const WebRTCStatsRequest&) override; + void GetStats(std::unique_ptr<WebRTCStatsReportCallback>) override; + WebVector<std::unique_ptr<WebRTCRtpSender>> GetSenders() override; + WebVector<std::unique_ptr<WebRTCRtpReceiver>> GetReceivers() override; + WebRTCDataChannelHandler* CreateDataChannel( + const WebString& label, + const WebRTCDataChannelInit&) override; + WebRTCDTMFSenderHandler* CreateDTMFSender( + const WebMediaStreamTrack&) override; + void Stop() override; +}; + +class TestingPlatformSupportWithWebRTC : public TestingPlatformSupport { + public: + std::unique_ptr<WebRTCPeerConnectionHandler> CreateRTCPeerConnectionHandler( + WebRTCPeerConnectionHandlerClient*) override; +}; + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 55e3de9..6dfad22 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -597,6 +597,7 @@ "exported/WebRTCAnswerOptions.cpp", "exported/WebRTCICECandidate.cpp", "exported/WebRTCOfferOptions.cpp", + "exported/WebRTCPeerConnectionHandlerClient.cpp", "exported/WebRTCRtpContributingSource.cpp", "exported/WebRTCRtpReceiver.cpp", "exported/WebRTCRtpSender.cpp",
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCPeerConnectionHandlerClient.cpp b/third_party/WebKit/Source/platform/exported/WebRTCPeerConnectionHandlerClient.cpp new file mode 100644 index 0000000..2e2a5fce --- /dev/null +++ b/third_party/WebKit/Source/platform/exported/WebRTCPeerConnectionHandlerClient.cpp
@@ -0,0 +1,13 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "public/platform/WebRTCPeerConnectionHandlerClient.h" + +namespace blink { + +WebRTCPeerConnectionHandlerClient::~WebRTCPeerConnectionHandlerClient() {} + +void WebRTCPeerConnectionHandlerClient::ClosePeerConnection() {} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp index 75bb34b..b034c46 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp
@@ -24,6 +24,7 @@ #include "platform/graphics/filters/FEComposite.h" +#include "SkArithmeticImageFilter.h" #include "SkXfermodeImageFilter.h" #include "platform/graphics/filters/SkiaImageFilterBuilder.h" @@ -189,7 +190,7 @@ SkImageFilter::CropRect crop_rect = GetCropRect(); if (type_ == FECOMPOSITE_OPERATOR_ARITHMETIC) { - return SkXfermodeImageFilter::MakeArithmetic( + return SkArithmeticImageFilter::Make( SkFloatToScalar(k1_), SkFloatToScalar(k2_), SkFloatToScalar(k3_), SkFloatToScalar(k4_), requires_pm_color_validation, std::move(background), std::move(foreground), &crop_rect);
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h index fcf7c7e..f584471 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h
@@ -298,7 +298,7 @@ ui_start_time_ = ui_start_time_seconds; } - // https://mikewest.github.io/cors-rfc1918/#external-request + // https://wicg.github.io/cors-rfc1918/#external-request bool IsExternalRequest() const { return is_external_request_; } void SetExternalRequestStateFromRequestorAddressSpace(WebAddressSpace);
diff --git a/third_party/WebKit/Source/web/tests/scheduler/ActiveConnectionThrottlingTest.cpp b/third_party/WebKit/Source/web/tests/scheduler/ActiveConnectionThrottlingTest.cpp index c002ff8..fa763ade 100644 --- a/third_party/WebKit/Source/web/tests/scheduler/ActiveConnectionThrottlingTest.cpp +++ b/third_party/WebKit/Source/web/tests/scheduler/ActiveConnectionThrottlingTest.cpp
@@ -6,14 +6,10 @@ #include "core/frame/WebLocalFrameBase.h" #include "core/testing/sim/SimRequest.h" #include "core/testing/sim/SimTest.h" +#include "modules/peerconnection/testing/TestingPlatformSupportWithWebRTC.h" #include "platform/scheduler/renderer/web_view_scheduler.h" #include "platform/testing/TestingPlatformSupport.h" #include "platform/wtf/PtrUtil.h" -#include "public/platform/WebRTCError.h" -#include "public/platform/WebRTCPeerConnectionHandler.h" -#include "public/platform/WebRTCRtpReceiver.h" -#include "public/platform/WebRTCRtpSender.h" -#include "public/platform/WebRTCSessionDescription.h" #include "public/web/WebScriptSource.h" #include "testing/gtest/include/gtest/gtest.h" @@ -42,76 +38,6 @@ EXPECT_FALSE(WebView().Scheduler()->HasActiveConnectionForTest()); } -namespace { - -class MockWebRTCPeerConnectionHandler : public WebRTCPeerConnectionHandler { - public: - MockWebRTCPeerConnectionHandler() {} - ~MockWebRTCPeerConnectionHandler() override {} - - bool Initialize(const WebRTCConfiguration&, - const WebMediaConstraints&) override { - return true; - } - - void CreateOffer(const WebRTCSessionDescriptionRequest&, - const WebMediaConstraints&) override {} - void CreateOffer(const WebRTCSessionDescriptionRequest&, - const WebRTCOfferOptions&) override {} - void CreateAnswer(const WebRTCSessionDescriptionRequest&, - const WebMediaConstraints&) override {} - void CreateAnswer(const WebRTCSessionDescriptionRequest&, - const WebRTCAnswerOptions&) override {} - void SetLocalDescription(const WebRTCVoidRequest&, - const WebRTCSessionDescription&) override {} - void SetRemoteDescription(const WebRTCVoidRequest&, - const WebRTCSessionDescription&) override {} - WebRTCSessionDescription LocalDescription() override { - return WebRTCSessionDescription(); - } - WebRTCSessionDescription RemoteDescription() override { - return WebRTCSessionDescription(); - } - WebRTCErrorType SetConfiguration(const WebRTCConfiguration&) override { - return WebRTCErrorType::kNone; - } - bool AddStream(const WebMediaStream&, const WebMediaConstraints&) override { - return true; - } - void RemoveStream(const WebMediaStream&) override {} - void GetStats(const WebRTCStatsRequest&) override {} - void GetStats(std::unique_ptr<WebRTCStatsReportCallback>) override {} - blink::WebVector<std::unique_ptr<blink::WebRTCRtpSender>> GetSenders() - override { - return blink::WebVector<std::unique_ptr<blink::WebRTCRtpSender>>(); - } - blink::WebVector<std::unique_ptr<blink::WebRTCRtpReceiver>> GetReceivers() - override { - return blink::WebVector<std::unique_ptr<blink::WebRTCRtpReceiver>>(); - } - WebRTCDataChannelHandler* CreateDataChannel( - const WebString& label, - const WebRTCDataChannelInit&) override { - return nullptr; - } - WebRTCDTMFSenderHandler* CreateDTMFSender( - const WebMediaStreamTrack&) override { - return nullptr; - } - void Stop() override {} -}; - -class TestingPlatformSupportWithWebRTC : public TestingPlatformSupport { - public: - std::unique_ptr<blink::WebRTCPeerConnectionHandler> - CreateRTCPeerConnectionHandler( - blink::WebRTCPeerConnectionHandlerClient*) override { - return WTF::MakeUnique<MockWebRTCPeerConnectionHandler>(); - } -}; - -} // namespace - TEST_F(ActiveConnectionThrottlingTest, WebRTCStopsThrottling) { ScopedTestingPlatformSupport<TestingPlatformSupportWithWebRTC> platform;
diff --git a/third_party/WebKit/public/platform/WebAddressSpace.h b/third_party/WebKit/public/platform/WebAddressSpace.h index 6e80220..fed7e59 100644 --- a/third_party/WebKit/public/platform/WebAddressSpace.h +++ b/third_party/WebKit/public/platform/WebAddressSpace.h
@@ -8,7 +8,7 @@ namespace blink { // The ordering is important, as it's used to determine whether preflights are -// required, as per https://mikewest.github.io/cors-rfc1918/#framework +// required, as per https://wicg.github.io/cors-rfc1918/#framework enum WebAddressSpace { kWebAddressSpaceLocal = 0, // loopback, link local kWebAddressSpacePrivate, // Reserved by RFC1918
diff --git a/third_party/WebKit/public/platform/WebMediaStreamTrack.h b/third_party/WebKit/public/platform/WebMediaStreamTrack.h index 9e697add..0921b7d4 100644 --- a/third_party/WebKit/public/platform/WebMediaStreamTrack.h +++ b/third_party/WebKit/public/platform/WebMediaStreamTrack.h
@@ -47,6 +47,7 @@ bool HasFrameRate() const { return frame_rate >= 0.0; } bool HasWidth() const { return width >= 0; } bool HasHeight() const { return height >= 0; } + bool HasAspectRatio() const { return aspect_ratio >= 0.0; } bool HasFacingMode() const { return facing_mode != FacingMode::kNone; } bool HasVideoKind() const { return !video_kind.IsNull(); } bool HasFocalLengthX() const { return focal_length_x >= 0.0; } @@ -58,6 +59,7 @@ double frame_rate = -1.0; long width = -1; long height = -1; + double aspect_ratio = -1.0; WebString device_id; FacingMode facing_mode = FacingMode::kNone; // Media Capture Depth Stream Extensions.
diff --git a/third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h b/third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h index ae2dadc..0a2fccd8 100644 --- a/third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h +++ b/third_party/WebKit/public/platform/WebRTCPeerConnectionHandlerClient.h
@@ -31,13 +31,15 @@ #ifndef WebRTCPeerConnectionHandlerClient_h #define WebRTCPeerConnectionHandlerClient_h +#include "WebCommon.h" + namespace blink { class WebMediaStream; class WebRTCDataChannelHandler; class WebRTCICECandidate; -class WebRTCPeerConnectionHandlerClient { +class BLINK_PLATFORM_EXPORT WebRTCPeerConnectionHandlerClient { public: enum SignalingState { kSignalingStateStable = 1, @@ -67,7 +69,7 @@ kICEGatheringStateComplete = 3 }; - virtual ~WebRTCPeerConnectionHandlerClient() {} + virtual ~WebRTCPeerConnectionHandlerClient(); virtual void NegotiationNeeded() = 0; virtual void DidGenerateICECandidate(const WebRTCICECandidate&) = 0; @@ -78,7 +80,7 @@ virtual void DidRemoveRemoteStream(const WebMediaStream&) = 0; virtual void DidAddRemoteDataChannel(WebRTCDataChannelHandler*) = 0; virtual void ReleasePeerConnectionHandler() = 0; - virtual void ClosePeerConnection() {} + virtual void ClosePeerConnection(); }; } // namespace blink
diff --git a/third_party/WebKit/public/platform/WebURLRequest.h b/third_party/WebKit/public/platform/WebURLRequest.h index 6c648f04..dd10f78 100644 --- a/third_party/WebKit/public/platform/WebURLRequest.h +++ b/third_party/WebKit/public/platform/WebURLRequest.h
@@ -350,7 +350,7 @@ BLINK_PLATFORM_EXPORT void SetInputPerfMetricReportPolicy( WebURLRequest::InputToLoadPerfMetricReportPolicy); - // https://mikewest.github.io/cors-rfc1918/#external-request + // https://wicg.github.io/cors-rfc1918/#external-request BLINK_PLATFORM_EXPORT bool IsExternalRequest() const; BLINK_PLATFORM_EXPORT LoadingIPCType GetLoadingIPCType() const;
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index d57c292..64c2fcde 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -16607,6 +16607,30 @@ <description>Please enter the description of this user action.</description> </action> +<action name="Tablet_WindowCloseFromCaptionButton"> + <owner>xdai@chromium.org</owner> + <description> + User closed the window through the close button in the caption area in + tablet mode on Chrome OS. + </description> +</action> + +<action name="Tablet_WindowCloseFromContextMenu"> + <owner>xdai@chromium.org</owner> + <description> + User closed the window through the shelf context menu in tablet mode on + Chrome OS. + </description> +</action> + +<action name="Tablet_WindowCloseFromOverviewButton"> + <owner>xdai@chromium.org</owner> + <description> + User closed the window through the close button in overview mode in tablet + mode on Chrome OS. + </description> +</action> + <action name="TaskManagement.OpenInChromeActionButtonClicked"> <obsolete>The button option was removed and code deleted.</obsolete> <owner>dfalcantara@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 8a6d4ca..85b7dd52 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -77754,6 +77754,13 @@ </summary> </histogram> +<histogram name="ThirdPartyModules.ShellExtensionsCount" units="counts"> + <owner>pmonette@chromium.org</owner> + <summary> + The number of registered shell extensions found on the user's machine. + </summary> +</histogram> + <histogram name="ThirdPartyModules.Uninstallable" enum="BooleanUninstallable"> <owner>pmonette@chromium.org</owner> <summary>
diff --git a/ui/gfx/shadow_value.h b/ui/gfx/shadow_value.h index bf5d98d..2362600f 100644 --- a/ui/gfx/shadow_value.h +++ b/ui/gfx/shadow_value.h
@@ -64,6 +64,11 @@ SkColor color_; }; +inline bool operator==(const ShadowValue& lhs, const ShadowValue& rhs) { + return lhs.offset() == rhs.offset() && lhs.blur() == rhs.blur() && + lhs.color() == rhs.color(); +} + } // namespace gfx #endif // UI_GFX_SHADOW_VALUE_H_
diff --git a/ui/login/OWNERS b/ui/login/OWNERS index b280edc9..73d229a 100644 --- a/ui/login/OWNERS +++ b/ui/login/OWNERS
@@ -1,3 +1,4 @@ achuith@chromium.org alemate@chromium.org +jdufault@chromium.org xiyuan@chromium.org
diff --git a/ui/ozone/platform/drm/common/drm_util.cc b/ui/ozone/platform/drm/common/drm_util.cc index b4a1111..c70f4d8 100644 --- a/ui/ozone/platform/drm/common/drm_util.cc +++ b/ui/ozone/platform/drm/common/drm_util.cc
@@ -209,10 +209,10 @@ return params; } -std::unique_ptr<const display::DisplayMode> CreateDisplayModeFromParams( +std::unique_ptr<display::DisplayMode> CreateDisplayModeFromParams( const DisplayMode_Params& pmode) { - return base::MakeUnique<const display::DisplayMode>( - pmode.size, pmode.is_interlaced, pmode.refresh_rate); + return base::MakeUnique<display::DisplayMode>(pmode.size, pmode.is_interlaced, + pmode.refresh_rate); } const gfx::Size ModeSize(const drmModeModeInfo& mode) {
diff --git a/ui/ozone/platform/drm/common/drm_util.h b/ui/ozone/platform/drm/common/drm_util.h index 029d5c9..9fdfb016 100644 --- a/ui/ozone/platform/drm/common/drm_util.h +++ b/ui/ozone/platform/drm/common/drm_util.h
@@ -81,7 +81,7 @@ DisplayMode_Params GetDisplayModeParams(const display::DisplayMode& mode); -std::unique_ptr<const display::DisplayMode> CreateDisplayModeFromParams( +std::unique_ptr<display::DisplayMode> CreateDisplayModeFromParams( const DisplayMode_Params& pmode); bool MatchMode(const display::DisplayMode& display_mode,
diff --git a/ui/ozone/platform/drm/gpu/drm_thread.cc b/ui/ozone/platform/drm/gpu/drm_thread.cc index fa0fa43e..a91932da 100644 --- a/ui/ozone/platform/drm/gpu/drm_thread.cc +++ b/ui/ozone/platform/drm/gpu/drm_thread.cc
@@ -239,7 +239,7 @@ void DrmThread::ConfigureNativeDisplay( int64_t id, - std::unique_ptr<const display::DisplayMode> mode, + std::unique_ptr<display::DisplayMode> mode, const gfx::Point& origin, base::OnceCallback<void(int64_t, bool)> callback) { std::move(callback).Run(
diff --git a/ui/ozone/platform/drm/gpu/drm_thread.h b/ui/ozone/platform/drm/gpu/drm_thread.h index a5244e9..8fdecc9 100644 --- a/ui/ozone/platform/drm/gpu/drm_thread.h +++ b/ui/ozone/platform/drm/gpu/drm_thread.h
@@ -101,7 +101,7 @@ void RefreshNativeDisplays( base::OnceCallback<void(MovableDisplaySnapshots)> callback); void ConfigureNativeDisplay(int64_t id, - std::unique_ptr<const display::DisplayMode> mode, + std::unique_ptr<display::DisplayMode> mode, const gfx::Point& origin, base::OnceCallback<void(int64_t, bool)> callback); void DisableNativeDisplay(int64_t id,
diff --git a/ui/views/controls/label.cc b/ui/views/controls/label.cc index 1db98e3..fc58a16 100644 --- a/ui/views/controls/label.cc +++ b/ui/views/controls/label.cc
@@ -147,7 +147,8 @@ } void Label::SetShadows(const gfx::ShadowValues& shadows) { - // TODO(mukai): early exit if the specified shadows are same. + if (render_text_->shadows() == shadows) + return; is_first_paint_text_ = true; render_text_->set_shadows(shadows); ResetLayout();