diff --git a/DEPS b/DEPS index 7cc5d7f..16d61ad 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,11 @@ # 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': '49b7b6f38fc9d6cbcfa5865db364ff79c3ed7bfe', + 'skia_revision': '95cf16618a75610f509686a7c6d45e46a734a4e9', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '1c4fcefc1480ae6c2e9c6e456ee6aafa823215d9', + 'v8_revision': '6f1f6d7cea47d2fa95f83685cf4110312826dc3a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -410,7 +410,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': - Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '72c510ef4082934f80d526fcc72d66710baa9d25', + Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'df34c6894b820b2dbeafe3624fcdf5a41042e153', # Dependency of chromite.git and skia. 'src/third_party/pyelftools':
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java index 57bb10d..5ffa5586 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java
@@ -14,6 +14,7 @@ import android.webkit.MimeTypeMap; import org.chromium.base.CollectionUtil; +import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; @@ -24,6 +25,7 @@ import org.chromium.chrome.browser.share.ShareHelper; import org.chromium.chrome.browser.share.ShareParams; import org.chromium.chrome.browser.util.UrlUtilities; +import org.chromium.content.browser.BrowserStartupController; import org.chromium.content_public.common.ContentUrlConstants; import java.lang.annotation.Retention; @@ -171,6 +173,16 @@ static final int TYPE_PDF = 5; static final int NUM_TYPES = 6; + // Note: these values must match the ContextMenuSaveImage enum in histograms.xml. + // Only add new values at the end, right before NUM_SAVE_IMAGE_TYPES. + static final int TYPE_SAVE_IMAGE_LOADED = 0; + static final int TYPE_SAVE_IMAGE_FETCHED_LOFI = 1; + static final int TYPE_SAVE_IMAGE_NOT_DOWNLOADABLE = 2; + static final int TYPE_SAVE_IMAGE_DISABLED_AND_IS_NOT_IMAGE_PARAM = 3; + static final int TYPE_SAVE_IMAGE_DISABLED_AND_IS_IMAGE_PARAM = 4; + static final int TYPE_SAVE_IMAGE_SHOWN = 5; + static final int NUM_SAVE_IMAGE_TYPES = 6; + /** * Records a histogram entry when the user selects an item from a context menu. * @param params The ContextMenuParams describing the current context menu. @@ -219,6 +231,15 @@ RecordHistogram.recordEnumeratedHistogram( "ContextMenu.SaveLinkType", mimeType, NUM_TYPES); } + + /** + * Helper method to record MobileDownload.ContextMenu.SaveImage UMA + * @param type Type to record + */ + static void recordSaveImageUma(int type) { + RecordHistogram.recordEnumeratedHistogram( + "MobileDownload.ContextMenu.SaveImage", type, NUM_SAVE_IMAGE_TYPES); + } } /** @@ -325,6 +346,29 @@ groupedItems.remove(index); } + if (!groupedItems.isEmpty()) { + boolean hasSaveImage = false; + for (int i = 0; i < groupedItems.size(); ++i) { + Pair<Integer, List<ContextMenuItem>> menuList = groupedItems.get(i); + if (menuList.second != null + && menuList.second.contains(ChromeContextMenuItem.SAVE_IMAGE)) { + hasSaveImage = true; + break; + } + } + + if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .isStartupSuccessfullyCompleted()) { + if (!hasSaveImage) { + ContextMenuUma.recordSaveImageUma(params.isImage() + ? ContextMenuUma.TYPE_SAVE_IMAGE_DISABLED_AND_IS_IMAGE_PARAM + : ContextMenuUma + .TYPE_SAVE_IMAGE_DISABLED_AND_IS_NOT_IMAGE_PARAM); + } else { + ContextMenuUma.recordSaveImageUma(ContextMenuUma.TYPE_SAVE_IMAGE_SHOWN); + } + } + } return groupedItems; } @@ -464,13 +508,14 @@ disabledOptions.add(ChromeContextMenuItem.OPEN_IMAGE); disabledOptions.add(ChromeContextMenuItem.SEARCH_BY_IMAGE); disabledOptions.add(ChromeContextMenuItem.SHARE_IMAGE); + recordSaveImageContextMenuResult(true, isSrcDownloadableScheme); } else if (params.isImage() && !params.imageWasFetchedLoFi()) { disabledOptions.add(ChromeContextMenuItem.LOAD_ORIGINAL_IMAGE); if (!isSrcDownloadableScheme) { disabledOptions.add(ChromeContextMenuItem.SAVE_IMAGE); } - + recordSaveImageContextMenuResult(false, isSrcDownloadableScheme); // Avoid showing open image option for same image which is already opened. if (mDelegate.getPageUrl().equals(params.getSrcUrl())) { disabledOptions.add(ChromeContextMenuItem.OPEN_IMAGE); @@ -660,4 +705,28 @@ return params.getSrcUrl(); } } + + /** + * Record the UMA related to save image context menu option. + * @param wasFetchedLoFi The image was fectched LoFi. + * @param isDownloadableScheme The image is downloadable. + */ + private void recordSaveImageContextMenuResult( + boolean wasFetchedLoFi, boolean isDownloadableScheme) { + if (!BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .isStartupSuccessfullyCompleted()) { + return; + } + + ContextMenuUma.recordSaveImageUma(ContextMenuUma.TYPE_SAVE_IMAGE_LOADED); + + if (wasFetchedLoFi) { + ContextMenuUma.recordSaveImageUma(ContextMenuUma.TYPE_SAVE_IMAGE_FETCHED_LOFI); + return; + } + + if (!isDownloadableScheme) { + ContextMenuUma.recordSaveImageUma(ContextMenuUma.TYPE_SAVE_IMAGE_NOT_DOWNLOADABLE); + } + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java b/chrome/android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java index fcb0b97..8549cfe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java
@@ -102,11 +102,6 @@ return mDialog; } - @VisibleForTesting - public int getQueueLengthForTesting() { - return mRequestQueue.size(); - } - @Override public void onAndroidPermissionAccepted() { mDialogDelegate.onAccept(mSwitchView.isChecked());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java index 8b52fd4c..ce2b8028 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java
@@ -7,6 +7,7 @@ import android.accounts.Account; import android.content.Context; import android.os.StrictMode; +import android.support.annotation.MainThread; import android.util.Log; import org.chromium.base.ContextUtils; @@ -129,6 +130,7 @@ * @param scope The scope to get an auth token for (without Android-style 'oauth2:' prefix). * @param nativeCallback The pointer to the native callback that should be run upon completion. */ + @MainThread @CalledByNative public static void getOAuth2AuthToken( String username, String scope, final long nativeCallback) { @@ -166,6 +168,7 @@ * @param scope The scope to get an auth token for (without Android-style 'oauth2:' prefix). * @param callback called on successful and unsuccessful fetching of auth token. */ + @MainThread public static void getOAuth2AccessToken(Context context, Account account, String scope, AccountManagerHelper.GetAuthTokenCallback callback) { String oauth2Scope = OAUTH2_SCOPE_PREFIX + scope;
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index e8ab767..9760b7e3 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -873,7 +873,7 @@ Blocked from some sites </message> <message name="IDS_WEBSITE_SETTINGS_PERMISSIONS_ADS_BLOCK" desc="The Blocked string for the ads permission on Site Details"> - Block if site tends to show intrusive ads + Block if site tends to show intrusive ads (recommended) </message> <message name="IDS_WEBSITE_SETTINGS_CATEGORY_LOCATION_ASK" desc="Summary text explaining that sites need to ask for permission before knowing location and that it is the recommended setting."> Ask before allowing sites to know your location (recommended)
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/permissions/PermissionNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/permissions/PermissionNavigationTest.java index fe0168b21..b3eb1e9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/permissions/PermissionNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/permissions/PermissionNavigationTest.java
@@ -6,15 +6,12 @@ import android.support.test.filters.MediumTest; -import org.junit.Assert; - import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; -import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; /** @@ -40,15 +37,6 @@ runJavaScriptCodeInCurrentTab("requestGeolocationPermission()"); DialogShownCriteria criteriaShown = new DialogShownCriteria("Dialog not shown", true); CriteriaHelper.pollUiThread(criteriaShown); - Assert.assertEquals(0, PermissionDialogController.getInstance().getQueueLengthForTesting()); - - runJavaScriptCodeInCurrentTab("requestNotificationPermission()"); - CriteriaHelper.pollInstrumentationThread(new Criteria("Request not queued") { - @Override - public boolean isSatisfied() { - return PermissionDialogController.getInstance().getQueueLengthForTesting() == 1; - } - }); runJavaScriptCodeInCurrentTab("navigate()");
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index eed7b44d..6175f5c 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -2104,6 +2104,9 @@ <message name="IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK" desc="The block label for ads in site settings."> Blocked on sites that tend to show intrusive ads </message> + <message name="IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK_RECOMMENDED" desc="The block label for ads in site settings (with the 'recommended' suffix)."> + Blocked on sites that tend to show intrusive ads (recommended) + </message> <message name="IDS_SETTINGS_SITE_SETTINGS_AUTOMATIC_DOWNLOAD_ASK" desc="The allow label for automatic download in site settings."> Ask when a site tries to download files automatically after the first file </message>
diff --git a/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.cc b/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.cc index 9378ea2..56d9459 100644 --- a/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.cc +++ b/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.cc
@@ -8,6 +8,7 @@ #include "base/android/path_utils.h" #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_macros.h" #include "chrome/browser/android/download/download_controller.h" #include "chrome/browser/download/download_path_reservation_tracker.h" #include "chrome/browser/infobars/infobar_service.h" @@ -67,6 +68,7 @@ is_off_the_record_(download_item->GetBrowserContext()->IsOffTheRecord()), file_selected_callback_(file_selected_callback) { download_item_->AddObserver(this); + RecordDuplicateInfobarType(INFOBAR_SHOWN); } infobars::InfoBarDelegate::InfoBarIdentifier @@ -75,12 +77,16 @@ } bool ChromeDuplicateDownloadInfoBarDelegate::Accept() { - if (!download_item_) + if (!download_item_) { + RecordDuplicateInfobarType(INFOBAR_DOWNLOAD_CANCELED); return true; + } base::FilePath download_dir; - if (!base::android::GetDownloadsDirectory(&download_dir)) + if (!base::android::GetDownloadsDirectory(&download_dir)) { + RecordDuplicateInfobarType(INFOBAR_NO_DOWNLOAD_DIR); return true; + } DownloadPathReservationTracker::GetReservedPath( download_item_, @@ -89,6 +95,7 @@ true, DownloadPathReservationTracker::UNIQUIFY, base::Bind(&CreateNewFileDone, file_selected_callback_)); + RecordDuplicateInfobarType(INFOBAR_CREATE_NEW_FILE); return true; } @@ -116,5 +123,11 @@ return is_off_the_record_; } +void ChromeDuplicateDownloadInfoBarDelegate::RecordDuplicateInfobarType( + DuplicateInfobarType type) { + UMA_HISTOGRAM_ENUMERATION("MobileDownload.DuplicateInfobar", type, + INFOBAR_MAX); +} + } // namespace android } // namespace chrome
diff --git a/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.h b/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.h index 6de397a..ad1467c 100644 --- a/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.h +++ b/chrome/browser/android/download/chrome_duplicate_download_infobar_delegate.h
@@ -41,6 +41,18 @@ const base::FilePath& file_path, const DownloadTargetDeterminerDelegate::ConfirmationCallback& callback); + // UMA histogram enum for duplicate infobar. Keep this in sync with + // MobileDownloadDuplcaiteInfobar in histograms.xml. This should be + // append only. + enum DuplicateInfobarType { + INFOBAR_SHOWN = 0, + INFOBAR_DOWNLOAD_CANCELED, + INFOBAR_NO_DOWNLOAD_DIR, + INFOBAR_CREATE_NEW_FILE, + INFOBAR_MAX + }; + void RecordDuplicateInfobarType(DuplicateInfobarType type); + // DownloadOverwriteInfoBarDelegate: infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; bool Accept() override;
diff --git a/chrome/browser/android/download/download_controller.cc b/chrome/browser/android/download/download_controller.cc index 7d8ab1d..1427a83 100644 --- a/chrome/browser/android/download/download_controller.cc +++ b/chrome/browser/android/download/download_controller.cc
@@ -73,10 +73,21 @@ const std::string& extra_headers, bool granted) { content::WebContents* web_contents = wc_getter.Run(); - - if (!web_contents) + if (!granted) { + DownloadController::RecordStoragePermission( + DownloadController::StoragePermissionType::STORAGE_PERMISSION_DENIED); return; + } + if (!web_contents) { + DownloadController::RecordStoragePermission( + DownloadController::StoragePermissionType:: + STORAGE_PERMISSION_NO_WEB_CONTENTS); + return; + } + + DownloadController::RecordStoragePermission( + DownloadController::StoragePermissionType::STORAGE_PERMISSION_GRANTED); const GURL& url = is_link ? params.link_url : params.src_url; const GURL& referring_url = params.frame_url.is_empty() ? params.page_url : params.frame_url; @@ -188,6 +199,12 @@ } // static +void DownloadController::RecordStoragePermission(StoragePermissionType type) { + UMA_HISTOGRAM_ENUMERATION("MobileDownload.StoragePermission", type, + STORAGE_PERMISSION_MAX); +} + +// static DownloadController* DownloadController::GetInstance() { return base::Singleton<DownloadController>::get(); } @@ -392,6 +409,13 @@ const content::ResourceRequestInfo::WebContentsGetter& wc_getter( base::Bind(&GetWebContents, process_id, routing_id)); + RecordStoragePermission(StoragePermissionType::STORAGE_PERMISSION_REQUESTED); + + if (HasFileAccessPermission()) { + RecordStoragePermission( + StoragePermissionType::STORAGE_PERMISSION_NO_ACTION_NEEDED); + } + AcquireFileAccessPermission( wc_getter, base::Bind(&CreateContextMenuDownload, wc_getter, params, is_link, extra_headers));
diff --git a/chrome/browser/android/download/download_controller.h b/chrome/browser/android/download/download_controller.h index 80281c3..b426801 100644 --- a/chrome/browser/android/download/download_controller.h +++ b/chrome/browser/android/download/download_controller.h
@@ -62,6 +62,19 @@ }; static void RecordDownloadCancelReason(DownloadCancelReason reason); + // UMA histogram enum for download storage permission requests. Keep this + // in sync with MobileDownloadStoragePermission in histograms.xml. This should + // be append only. + enum StoragePermissionType { + STORAGE_PERMISSION_REQUESTED = 0, + STORAGE_PERMISSION_NO_ACTION_NEEDED, + STORAGE_PERMISSION_GRANTED, + STORAGE_PERMISSION_DENIED, + STORAGE_PERMISSION_NO_WEB_CONTENTS, + STORAGE_PERMISSION_MAX + }; + static void RecordStoragePermission(StoragePermissionType type); + // Callback when user permission prompt finishes. Args: whether file access // permission is acquired, which permission to update. typedef base::Callback<void(bool, const std::string&)>
diff --git a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.h b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.h index b11d7a4..761ec00d 100644 --- a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.h +++ b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.h
@@ -55,10 +55,8 @@ void OnClientConnected(mojo::edk::ScopedPlatformHandle handle) override; void OnListenError() override; - // The |acceptor_| must be created on a thread which allows blocking I/O, so - // part of the initialization of this class must be carried out on the file - // thread. - void InitOnFileThread(); + // The |acceptor_| must be created on a thread which allows blocking I/O. + void InitOnBackgroundThread(); // Called on the IO thread to begin listening for connections from app shims. void ListenOnIOThread();
diff --git a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm index f573a13d..984f61f 100644 --- a/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm +++ b/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm
@@ -6,26 +6,20 @@ #include <unistd.h> -#include "base/base64.h" #include "base/bind.h" -#include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/sha1.h" -#include "base/strings/string_util.h" +#include "base/task_scheduler/post_task.h" #include "chrome/browser/apps/app_shim/app_shim_handler_mac.h" #include "chrome/browser/apps/app_shim/app_shim_host_mac.h" #include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h" -#include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/mac/app_mode_common.h" #include "components/version_info/version_info.h" -using content::BrowserThread; - namespace { void CreateAppShimHost(mojo::edk::ScopedPlatformHandle handle) { @@ -35,7 +29,7 @@ base::FilePath GetDirectoryInTmpTemplate(const base::FilePath& user_data_dir) { base::FilePath temp_dir; - CHECK(PathService::Get(base::DIR_TEMP, &temp_dir)); + CHECK(base::PathService::Get(base::DIR_TEMP, &temp_dir)); // Check that it's shorter than the IPC socket length (104) minus the // intermediate folder ("/chrome-XXXXXX/") and kAppShimSocketShortName. DCHECK_GT(83u, temp_dir.value().length()); @@ -45,6 +39,8 @@ void DeleteSocketFiles(const base::FilePath& directory_in_tmp, const base::FilePath& symlink_path, const base::FilePath& version_path) { + base::ThreadRestrictions::AssertIOAllowed(); + // Delete in reverse order of creation. if (!version_path.empty()) base::DeleteFile(version_path, false); @@ -56,17 +52,20 @@ } // namespace -AppShimHostManager::AppShimHostManager() { -} +AppShimHostManager::AppShimHostManager() {} void AppShimHostManager::Init() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!extension_app_shim_handler_); extension_app_shim_handler_.reset(new apps::ExtensionAppShimHandler()); apps::AppShimHandler::SetDefaultHandler(extension_app_shim_handler_.get()); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - base::Bind(&AppShimHostManager::InitOnFileThread, this)); + + // If running the shim triggers Chrome startup, the user must wait for the + // socket to be set up before the shim will be usable. This also requires + // IO, so use MayBlock() with USER_VISIBLE. + base::PostTaskWithTraits( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&AppShimHostManager::InitOnBackgroundThread, this)); } AppShimHostManager::~AppShimHostManager() { @@ -82,22 +81,22 @@ base::FilePath user_data_dir; base::FilePath symlink_path; base::FilePath version_path; - if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) { + if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) { symlink_path = user_data_dir.Append(app_mode::kAppShimSocketSymlinkName); version_path = user_data_dir.Append(app_mode::kRunningChromeVersionSymlinkName); } - BrowserThread::PostTask( - BrowserThread::FILE, - FROM_HERE, - base::Bind( - &DeleteSocketFiles, directory_in_tmp_, symlink_path, version_path)); + base::PostTaskWithTraits(FROM_HERE, + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&DeleteSocketFiles, directory_in_tmp_, + symlink_path, version_path)); } -void AppShimHostManager::InitOnFileThread() { - DCHECK_CURRENTLY_ON(BrowserThread::FILE); +void AppShimHostManager::InitOnBackgroundThread() { + base::ThreadRestrictions::AssertIOAllowed(); base::FilePath user_data_dir; - if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) + if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return; // The socket path must be shorter than 104 chars (IPC::kMaxSocketNameLength). @@ -143,26 +142,26 @@ base::CreateSymbolicLink(base::FilePath(version_info::GetVersionNumber()), version_path); - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::Bind(&AppShimHostManager::ListenOnIOThread, this)); + content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::IO) + ->PostTask(FROM_HERE, + base::Bind(&AppShimHostManager::ListenOnIOThread, this)); } void AppShimHostManager::ListenOnIOThread() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (!acceptor_->Listen()) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&AppShimHostManager::OnListenError, this)); + content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) + ->PostTask(FROM_HERE, + base::Bind(&AppShimHostManager::OnListenError, this)); } } void AppShimHostManager::OnClientConnected( mojo::edk::ScopedPlatformHandle handle) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&CreateAppShimHost, base::Passed(&handle))); + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) + ->PostTask(FROM_HERE, + base::Bind(&CreateAppShimHost, base::Passed(&handle))); } void AppShimHostManager::OnListenError() {
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index bc8cea2f..f19c0ff 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -624,7 +624,6 @@ <if expr="_google_chrome"> <then> <include name="IDR_GOOGLE_XKB_MANIFEST" file="resources\chromeos\input_method\google_xkb_manifest.json" type="BINDATA" /> - <include name="IDR_GOOGLE_INPUT_TOOLS_MANIFEST" file="resources\chromeos\input_method\google_input_tools_manifest.json" type="BINDATA" /> </then> <else> <include name="IDR_XKB_MANIFEST" file="resources\chromeos\input_method\xkb_manifest.json" type="BINDATA" />
diff --git a/chrome/browser/chrome_service_worker_browsertest.cc b/chrome/browser/chrome_service_worker_browsertest.cc index 65a03a2..ae3b7e5 100644 --- a/chrome/browser/chrome_service_worker_browsertest.cc +++ b/chrome/browser/chrome_service_worker_browsertest.cc
@@ -387,7 +387,7 @@ IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerManifestFetchTest, SameOrigin) { // <link rel="manifest" href="manifest.json"> - EXPECT_EQ(RequestString(GetURL("/manifest.json"), "cors", "same-origin"), + EXPECT_EQ(RequestString(GetURL("/manifest.json"), "cors", "omit"), ExecuteManifestFetchTest("manifest.json", "")); } @@ -401,8 +401,7 @@ IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerManifestFetchTest, OtherOrigin) { // <link rel="manifest" href="https://www.example.com/manifest.json"> EXPECT_EQ( - RequestString("https://www.example.com/manifest.json", "cors", - "same-origin"), + RequestString("https://www.example.com/manifest.json", "cors", "omit"), ExecuteManifestFetchTest("https://www.example.com/manifest.json", "")); } @@ -434,9 +433,9 @@ std::string GetRequestStringForPNACL(const std::string& fragment) const { return RequestString(test_page_url_ + fragment, "navigate", "include") + RequestString(GetURL("/pnacl_url_loader.nmf"), "same-origin", - "include") + + "same-origin") + RequestString(GetURL("/pnacl_url_loader_newlib_pnacl.pexe"), - "same-origin", "include"); + "same-origin", "same-origin"); } std::string ExecutePNACLUrlLoaderTest(const std::string& mode) { @@ -471,7 +470,7 @@ // request.SetURL("/echo"); // request.SetAllowCrossOriginRequests(true); EXPECT_EQ(GetRequestStringForPNACL("#SameCORS") + - RequestString(GetURL("/echo"), "cors", "same-origin"), + RequestString(GetURL("/echo"), "cors", "omit"), ExecutePNACLUrlLoaderTest("SameCORS")); } @@ -512,10 +511,9 @@ // request.SetMethod("GET"); // request.SetURL("https://www.example.com/echo"); // request.SetAllowCrossOriginRequests(true); - EXPECT_EQ( - GetRequestStringForPNACL("#OtherCORS") + - RequestString("https://www.example.com/echo", "cors", "same-origin"), - ExecutePNACLUrlLoaderTest("OtherCORS")); + EXPECT_EQ(GetRequestStringForPNACL("#OtherCORS") + + RequestString("https://www.example.com/echo", "cors", "omit"), + ExecutePNACLUrlLoaderTest("OtherCORS")); } IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerFetchPPAPITest,
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 67d6bfc..3eb4e14 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1681,6 +1681,7 @@ "attestation/fake_certificate.cc", "attestation/fake_certificate.h", "attestation/platform_verification_flow_unittest.cc", + "authpolicy/auth_policy_credentials_manager_unittest.cc", "base/file_flusher_unittest.cc", "certificate_provider/certificate_provider_service_unittest.cc", "customization/customization_document_unittest.cc",
diff --git a/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.cc b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.cc index 40345b4..a2b3621 100644 --- a/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.cc +++ b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.cc
@@ -69,6 +69,8 @@ } // namespace +namespace chromeos { + AuthPolicyCredentialsManager::AuthPolicyCredentialsManager(Profile* profile) : profile_(profile) { const user_manager::User* user = @@ -135,10 +137,10 @@ break; case authpolicy::ActiveDirectoryUserStatus::PASSWORD_EXPIRED: ShowNotification(IDS_ACTIVE_DIRECTORY_PASSWORD_EXPIRED); - return; + break; case authpolicy::ActiveDirectoryUserStatus::PASSWORD_CHANGED: ShowNotification(IDS_ACTIVE_DIRECTORY_PASSWORD_CHANGED); - return; + break; } DCHECK(user_status.has_tgt_status()); @@ -149,10 +151,13 @@ case authpolicy::ActiveDirectoryUserStatus::TGT_EXPIRED: case authpolicy::ActiveDirectoryUserStatus::TGT_NOT_FOUND: ShowNotification(IDS_ACTIVE_DIRECTORY_REFRESH_AUTH_TOKEN); - return; + break; } - // Everything is ok. - user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id_, false); + const bool ok = user_status.tgt_status() == + authpolicy::ActiveDirectoryUserStatus::TGT_VALID && + user_status.password_status() == + authpolicy::ActiveDirectoryUserStatus::PASSWORD_VALID; + user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id_, !ok); } void AuthPolicyCredentialsManager::ScheduleGetUserStatus() { @@ -178,9 +183,9 @@ } void AuthPolicyCredentialsManager::StopObserveNetwork() { - DCHECK(chromeos::NetworkHandler::IsInitialized()); if (!is_observing_network_) return; + DCHECK(chromeos::NetworkHandler::IsInitialized()); is_observing_network_ = false; chromeos::NetworkHandler::Get()->network_state_handler()->RemoveObserver( this, FROM_HERE); @@ -202,8 +207,6 @@ } void AuthPolicyCredentialsManager::ShowNotification(int message_id) { - user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id_, true); - if (shown_notifications_.count(message_id) > 0) return; @@ -263,13 +266,14 @@ } // static -void AuthPolicyCredentialsManagerFactory::BuildForProfileIfActiveDirectory( +KeyedService* +AuthPolicyCredentialsManagerFactory::BuildForProfileIfActiveDirectory( Profile* profile) { const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); if (!user || !user->IsActiveDirectoryUser()) - return; - GetInstance()->GetServiceForBrowserContext(profile, true /* create */); + return nullptr; + return GetInstance()->GetServiceForBrowserContext(profile, true /* create */); } AuthPolicyCredentialsManagerFactory::AuthPolicyCredentialsManagerFactory() @@ -284,3 +288,5 @@ Profile* profile = Profile::FromBrowserContext(context); return new AuthPolicyCredentialsManager(profile); } + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.h b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.h index 0fec7e7..d53d66bf 100644 --- a/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.h +++ b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.h
@@ -27,6 +27,8 @@ struct DefaultSingletonTraits; } // namespace base +namespace chromeos { + // A service responsible for tracking user credential status. Created for each // Active Directory user profile. class AuthPolicyCredentialsManager @@ -46,6 +48,7 @@ void OnShuttingDown() override; private: + friend class AuthPolicyCredentialsManagerTest; // Calls AuthPolicyClient::GetUserStatus method. void GetUserStatus(); @@ -97,7 +100,10 @@ public: static AuthPolicyCredentialsManagerFactory* GetInstance(); - static void BuildForProfileIfActiveDirectory(Profile* profile); + // Returns nullptr in case profile is not Active Directory. Otherwise returns + // valid AuthPolicyCredentialsManager. Lifetime is managed by + // BrowserContextKeyedServiceFactory. + static KeyedService* BuildForProfileIfActiveDirectory(Profile* profile); private: friend struct base::DefaultSingletonTraits< @@ -112,4 +118,6 @@ DISALLOW_COPY_AND_ASSIGN(AuthPolicyCredentialsManagerFactory); }; +} // namespace chromeos + #endif // CHROME_BROWSER_CHROMEOS_AUTHPOLICY_AUTH_POLICY_CREDENTIALS_MANAGER_H_
diff --git a/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager_unittest.cc b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager_unittest.cc new file mode 100644 index 0000000..76cb219f --- /dev/null +++ b/chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager_unittest.cc
@@ -0,0 +1,188 @@ +// 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/chromeos/authpolicy/auth_policy_credentials_manager.h" + +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" +#include "chrome/browser/chromeos/login/users/mock_user_manager.h" +#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" +#include "chrome/browser/notifications/notification_test_util.h" +#include "chrome/browser/notifications/notification_ui_manager.h" +#include "chrome/grit/generated_resources.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_auth_policy_client.h" +#include "chromeos/network/network_handler.h" +#include "components/user_manager/user_manager.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { + +namespace { + +const char kProfileSigninNotificationId[] = "chrome://settings/signin/"; +const char kDisplayName[] = "DisplayName"; +const char kGivenName[] = "Given Name"; + +MATCHER_P(UserAccountDataEq, value, "Compares two UserAccountData") { + const user_manager::UserManager::UserAccountData& expected_data = value; + return expected_data.display_name() == arg.display_name() && + expected_data.given_name() == arg.given_name() && + expected_data.locale() == arg.locale(); +} + +} // namespace + +class AuthPolicyCredentialsManagerTest : public testing::Test { + public: + AuthPolicyCredentialsManagerTest() + : user_manager_enabler_(new MockUserManager()) {} + ~AuthPolicyCredentialsManagerTest() override = default; + + void SetUp() override { + chromeos::DBusThreadManager::Initialize(); + chromeos::NetworkHandler::Initialize(); + fake_auth_policy_client()->set_operation_delay( + base::TimeDelta::FromSeconds(0)); + + TestingBrowserProcess::GetGlobal()->SetNotificationUIManager( + base::MakeUnique<StubNotificationUIManager>()); + + TestingProfile::Builder profile_builder; + profile_builder.SetProfileName("user@gmail.com"); + profile_ = profile_builder.Build(); + account_id_ = AccountId::AdFromUserEmailObjGuid( + profile()->GetProfileUserName(), "1234567890"); + mock_user_manager()->AddUser(account_id_); + + base::RunLoop run_loop; + fake_auth_policy_client()->set_on_get_status_closure( + run_loop.QuitClosure()); + + auth_policy_credentials_manager_ = static_cast< + AuthPolicyCredentialsManager*>( + AuthPolicyCredentialsManagerFactory::BuildForProfileIfActiveDirectory( + profile())); + + EXPECT_CALL(*mock_user_manager(), + SaveForceOnlineSignin(account_id(), false)); + run_loop.Run(); + testing::Mock::VerifyAndClearExpectations(mock_user_manager()); + } + + void TearDown() override { + EXPECT_CALL(*mock_user_manager(), Shutdown()); + chromeos::NetworkHandler::Shutdown(); + chromeos::DBusThreadManager::Shutdown(); + } + + protected: + AccountId& account_id() { return account_id_; } + TestingProfile* profile() { return profile_.get(); } + AuthPolicyCredentialsManager* auth_policy_credentials_manager() { + return auth_policy_credentials_manager_; + } + chromeos::FakeAuthPolicyClient* fake_auth_policy_client() const { + return static_cast<chromeos::FakeAuthPolicyClient*>( + chromeos::DBusThreadManager::Get()->GetAuthPolicyClient()); + } + + MockUserManager* mock_user_manager() { + return static_cast<MockUserManager*>(user_manager::UserManager::Get()); + } + + int GetNumberOfNotifications() { + return TestingBrowserProcess::GetGlobal() + ->notification_ui_manager() + ->GetAllIdsByProfile(profile()) + .size(); + } + + bool CancelNotificationById(int message_id) { + const std::string notification_id = kProfileSigninNotificationId + + profile()->GetProfileUserName() + + std::to_string(message_id); + return TestingBrowserProcess::GetGlobal() + ->notification_ui_manager() + ->CancelById(notification_id, profile()); + } + + void CallGetUserStatusAndWait() { + base::RunLoop run_loop; + fake_auth_policy_client()->set_on_get_status_closure( + run_loop.QuitClosure()); + auth_policy_credentials_manager()->GetUserStatus(); + run_loop.Run(); + testing::Mock::VerifyAndClearExpectations(mock_user_manager()); + } + + private: + content::TestBrowserThreadBundle thread_bundle_; + AccountId account_id_; + std::unique_ptr<TestingProfile> profile_; + + // Owned by AuthPolicyCredentialsManagerFactory. + AuthPolicyCredentialsManager* auth_policy_credentials_manager_; + chromeos::ScopedUserManagerEnabler user_manager_enabler_; + + DISALLOW_COPY_AND_ASSIGN(AuthPolicyCredentialsManagerTest); +}; + +// Tests saving display and given name into user manager. No error means no +// notifications are shown. +TEST_F(AuthPolicyCredentialsManagerTest, SaveNames) { + fake_auth_policy_client()->set_display_name(kDisplayName); + fake_auth_policy_client()->set_given_name(kGivenName); + user_manager::UserManager::UserAccountData user_account_data( + base::UTF8ToUTF16(kDisplayName), base::UTF8ToUTF16(kGivenName), + std::string() /* locale */); + + EXPECT_CALL(*mock_user_manager(), + UpdateUserAccountData( + account_id(), + UserAccountDataEq(::testing::ByRef(user_account_data)))); + EXPECT_CALL(*mock_user_manager(), SaveForceOnlineSignin(account_id(), false)); + CallGetUserStatusAndWait(); + EXPECT_EQ(0, GetNumberOfNotifications()); +} + +// Tests notification is shown at most once for the same error. +TEST_F(AuthPolicyCredentialsManagerTest, ShowSameNotificationOnce) { + // In case of expired password save to force online signin and show + // notification. + fake_auth_policy_client()->set_password_status( + authpolicy::ActiveDirectoryUserStatus::PASSWORD_EXPIRED); + EXPECT_CALL(*mock_user_manager(), SaveForceOnlineSignin(account_id(), true)); + CallGetUserStatusAndWait(); + EXPECT_EQ(1, GetNumberOfNotifications()); + EXPECT_TRUE(CancelNotificationById(IDS_ACTIVE_DIRECTORY_PASSWORD_EXPIRED)); + + // Do not show the same notification twice. + EXPECT_CALL(*mock_user_manager(), SaveForceOnlineSignin(account_id(), true)); + CallGetUserStatusAndWait(); + EXPECT_EQ(0, GetNumberOfNotifications()); +} + +// Tests both notifications are shown if different errors occurs. +TEST_F(AuthPolicyCredentialsManagerTest, ShowDifferentNotifications) { + // In case of expired password save to force online signin and show + // notification. + fake_auth_policy_client()->set_password_status( + authpolicy::ActiveDirectoryUserStatus::PASSWORD_CHANGED); + fake_auth_policy_client()->set_tgt_status( + authpolicy::ActiveDirectoryUserStatus::TGT_EXPIRED); + EXPECT_CALL(*mock_user_manager(), SaveForceOnlineSignin(account_id(), true)); + CallGetUserStatusAndWait(); + EXPECT_EQ(2, GetNumberOfNotifications()); + EXPECT_TRUE(CancelNotificationById(IDS_ACTIVE_DIRECTORY_PASSWORD_CHANGED)); + EXPECT_TRUE(CancelNotificationById(IDS_ACTIVE_DIRECTORY_REFRESH_AUTH_TOKEN)); + EXPECT_EQ(0, GetNumberOfNotifications()); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc b/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc index 35308a7..af2e9752 100644 --- a/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc +++ b/chrome/browser/chromeos/login/enterprise_enrollment_browsertest.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_auth_policy_client.h" #include "chromeos/dbus/upstart_client.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" @@ -154,6 +155,9 @@ const std::string& realm) { EXPECT_EQ(kAdTestRealm, realm); })); })); }); + static_cast<FakeAuthPolicyClient*>( + DBusThreadManager::Get()->GetAuthPolicyClient()) + ->set_operation_delay(base::TimeDelta::FromSeconds(0)); } void SetupActiveDirectoryJSNotifications() {
diff --git a/chrome/browser/chromeos/login/login_browsertest.cc b/chrome/browser/chromeos/login/login_browsertest.cc index e567a7b..a1fd32e 100644 --- a/chrome/browser/chromeos/login/login_browsertest.cc +++ b/chrome/browser/chromeos/login/login_browsertest.cc
@@ -213,14 +213,14 @@ void SetUpOnMainThread() override { LoginManagerTest::SetUpOnMainThread(); - fake_auth_policy_client_ = static_cast<FakeAuthPolicyClient*>( - DBusThreadManager::Get()->GetAuthPolicyClient()); + fake_auth_policy_client()->set_operation_delay( + base::TimeDelta::FromSeconds(0)); } void MarkAsActiveDirectoryEnterprise() { StartupUtils::MarkOobeCompleted(); base::RunLoop loop; - fake_auth_policy_client_->RefreshDevicePolicy( + fake_auth_policy_client()->RefreshDevicePolicy( base::Bind(&ActiveDirectoryLoginTest::OnRefreshedPolicy, base::Unretained(this), loop.QuitClosure())); loop.Run(); @@ -309,7 +309,10 @@ return "document.querySelector('#offline-ad-auth /deep/ #" + element_id + "')"; } - FakeAuthPolicyClient* fake_auth_policy_client_ = nullptr; + FakeAuthPolicyClient* fake_auth_policy_client() { + return static_cast<FakeAuthPolicyClient*>( + DBusThreadManager::Get()->GetAuthPolicyClient()); + } private: // Used for the callback from FakeAuthPolicy::RefreshDevicePolicy. @@ -469,14 +472,14 @@ TestUserError(); TestDomainHidden(); - fake_auth_policy_client_->set_auth_error(authpolicy::ERROR_BAD_USER_NAME); + fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_BAD_USER_NAME); SubmitActiveDirectoryCredentials( std::string(kTestActiveDirectoryUser) + "@" + kTestRealm, kPassword); WaitForMessage(&message_queue, "\"ShowAuthError\""); TestUserError(); TestDomainVisible(); - fake_auth_policy_client_->set_auth_error(authpolicy::ERROR_BAD_PASSWORD); + fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_BAD_PASSWORD); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, kPassword); WaitForMessage(&message_queue, "\"ShowAuthError\""); TestPasswordError();
diff --git a/chrome/browser/download/download_item_model.cc b/chrome/browser/download/download_item_model.cc index adb8de5d..ce30910a 100644 --- a/chrome/browser/download/download_item_model.cc +++ b/chrome/browser/download/download_item_model.cc
@@ -613,6 +613,9 @@ } bool DownloadItemModel::ShouldNotifyUI() const { + if (download_->IsTransient()) + return false; + Profile* profile = Profile::FromBrowserContext(download_->GetBrowserContext()); DownloadCoreService* download_core_service =
diff --git a/chrome/browser/download/download_request_limiter_unittest.cc b/chrome/browser/download/download_request_limiter_unittest.cc index fafb613..a8d9907e 100644 --- a/chrome/browser/download/download_request_limiter_unittest.cc +++ b/chrome/browser/download/download_request_limiter_unittest.cc
@@ -10,7 +10,10 @@ #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/download/download_permission_request.h" +#include "chrome/browser/permissions/permission_request_manager.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -27,9 +30,6 @@ #include "chrome/browser/download/download_request_infobar_delegate_android.h" #include "chrome/browser/infobars/infobar_service.h" #else -#include "chrome/browser/download/download_permission_request.h" -#include "chrome/browser/permissions/permission_request_manager.h" -#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h" #endif using content::WebContents; @@ -40,119 +40,45 @@ CANCEL, WAIT }; - -#if defined(OS_ANDROID) -class TestingDelegate { - public: - void SetUp(WebContents* web_contents) { - InfoBarService::CreateForWebContents(web_contents); - fake_create_callback_ = - base::Bind(&TestingDelegate::FakeCreate, base::Unretained(this)); - DownloadRequestInfoBarDelegateAndroid::SetCallbackForTesting( - &fake_create_callback_); - ResetCounts(); - } - - void TearDown() { UnsetInfobarDelegate(); } - - void LoadCompleted(WebContents* /*web_contents*/) { - // No action needed on OS_ANDROID. - } - - void ResetCounts() { ask_allow_count_ = 0; } - - int AllowCount() { return ask_allow_count_; } - - void UpdateExpectations(TestingAction action) { testing_action_ = action; } - - void FakeCreate( - InfoBarService* infobar_service, - base::WeakPtr<DownloadRequestLimiter::TabDownloadState> host) { - ask_allow_count_++; - switch (testing_action_) { - case ACCEPT: - host->Accept(); - break; - case CANCEL: - host->Cancel(); - break; - case WAIT: - break; - } - } - - void UnsetInfobarDelegate() { - DownloadRequestInfoBarDelegateAndroid::SetCallbackForTesting(nullptr); - } - - private: - // Number of times ShouldAllowDownload was invoked. - int ask_allow_count_; - - // The action that FakeCreate() should take. - TestingAction testing_action_; - - DownloadRequestInfoBarDelegateAndroid::FakeCreateCallback - fake_create_callback_; -}; -#else -class TestingDelegate { - public: - void SetUp(WebContents* web_contents) { - PermissionRequestManager::CreateForWebContents(web_contents); - mock_permission_prompt_factory_.reset(new MockPermissionPromptFactory( - PermissionRequestManager::FromWebContents(web_contents))); - PermissionRequestManager::FromWebContents(web_contents) - ->DisplayPendingRequests(); - } - - void TearDown() { mock_permission_prompt_factory_.reset(); } - - void LoadCompleted(WebContents* web_contents) { - mock_permission_prompt_factory_->DocumentOnLoadCompletedInMainFrame(); - } - - void ResetCounts() { mock_permission_prompt_factory_->ResetCounts(); } - - int AllowCount() { return mock_permission_prompt_factory_->show_count(); } - - void UpdateExpectations(TestingAction action) { - // Set expectations for PermissionRequestManager. - PermissionRequestManager::AutoResponseType response_type = - PermissionRequestManager::DISMISS; - switch (action) { - case ACCEPT: - response_type = PermissionRequestManager::ACCEPT_ALL; - break; - case CANCEL: - response_type = PermissionRequestManager::DENY_ALL; - break; - case WAIT: - response_type = PermissionRequestManager::NONE; - break; - } - mock_permission_prompt_factory_->set_response_type(response_type); - } - - private: - std::unique_ptr<MockPermissionPromptFactory> mock_permission_prompt_factory_; -}; -#endif } // namespace class DownloadRequestLimiterTest : public ChromeRenderViewHostTestHarness { public: void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - testing_delegate_.SetUp(web_contents()); + + use_permission_request_manager_ = PermissionRequestManager::IsEnabled(); + + if (use_permission_request_manager_) { + PermissionRequestManager::CreateForWebContents(web_contents()); + PermissionRequestManager* manager = + PermissionRequestManager::FromWebContents(web_contents()); + mock_permission_prompt_factory_.reset( + new MockPermissionPromptFactory(manager)); + manager->DisplayPendingRequests(); + } else { +#if defined(OS_ANDROID) + InfoBarService::CreateForWebContents(web_contents()); + fake_create_callback_ = base::Bind( + &DownloadRequestLimiterTest::FakeCreate, base::Unretained(this)); + DownloadRequestInfoBarDelegateAndroid::SetCallbackForTesting( + &fake_create_callback_); +#endif + } UpdateExpectations(ACCEPT); - cancel_count_ = continue_count_ = 0; + ask_allow_count_ = cancel_count_ = continue_count_ = 0; download_request_limiter_ = new DownloadRequestLimiter(); } void TearDown() override { - testing_delegate_.TearDown(); + if (use_permission_request_manager_) { + mock_permission_prompt_factory_.reset(); + } else { +#if defined(OS_ANDROID) + UnsetInfobarDelegate(); +#endif + } ChromeRenderViewHostTestHarness::TearDown(); } @@ -192,7 +118,10 @@ EXPECT_EQ(expect_cancels, cancel_count_) << "line " << line; EXPECT_EQ(expect_asks, AskAllowCount()) << "line " << line; continue_count_ = cancel_count_ = 0; - testing_delegate_.ResetCounts(); + if (use_permission_request_manager_) + mock_permission_prompt_factory_->ResetCounts(); + else + ask_allow_count_ = 0; } void UpdateContentSettings(WebContents* web_contents, @@ -219,14 +148,62 @@ CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS, std::string(), setting); } - void LoadCompleted() { testing_delegate_.LoadCompleted(web_contents()); } + void LoadCompleted() { + if (use_permission_request_manager_) + mock_permission_prompt_factory_->DocumentOnLoadCompletedInMainFrame(); + } - int AskAllowCount() { return testing_delegate_.AllowCount(); } + int AskAllowCount() { + if (use_permission_request_manager_) + return mock_permission_prompt_factory_->show_count(); + return ask_allow_count_; + } void UpdateExpectations(TestingAction action) { - testing_delegate_.UpdateExpectations(action); + if (use_permission_request_manager_) { + // Set expectations for PermissionRequestManager. + PermissionRequestManager::AutoResponseType response_type = + PermissionRequestManager::DISMISS; + switch (action) { + case ACCEPT: + response_type = PermissionRequestManager::ACCEPT_ALL; + break; + case CANCEL: + response_type = PermissionRequestManager::DENY_ALL; + break; + case WAIT: + response_type = PermissionRequestManager::NONE; + break; + } + mock_permission_prompt_factory_->set_response_type(response_type); + } else { + testing_action_ = action; + } } +#if defined(OS_ANDROID) + void FakeCreate( + InfoBarService* infobar_service, + base::WeakPtr<DownloadRequestLimiter::TabDownloadState> host) { + ask_allow_count_++; + switch (testing_action_) { + case ACCEPT: + host->Accept(); + break; + case CANCEL: + host->Cancel(); + break; + case WAIT: + break; + } + } + + void UnsetInfobarDelegate() { + if (!use_permission_request_manager_) + DownloadRequestInfoBarDelegateAndroid::SetCallbackForTesting(nullptr); + } +#endif + scoped_refptr<DownloadRequestLimiter> download_request_limiter_; // Number of times ContinueDownload was invoked. @@ -235,7 +212,20 @@ // Number of times CancelDownload was invoked. int cancel_count_; - TestingDelegate testing_delegate_; + std::unique_ptr<MockPermissionPromptFactory> mock_permission_prompt_factory_; + + // TODO(timloh): Remove the members below here after crbug.com/606138 is done. + + bool use_permission_request_manager_; + + // Number of times ShouldAllowDownload was invoked. + int ask_allow_count_; + // The action that FakeCreate() should take. + TestingAction testing_action_; +#if defined(OS_ANDROID) + DownloadRequestInfoBarDelegateAndroid::FakeCreateCallback + fake_create_callback_; +#endif }; TEST_F(DownloadRequestLimiterTest, DownloadRequestLimiter_Allow) { @@ -571,7 +561,6 @@ download_request_limiter_->GetDownloadStatus(web_contents())); } -#if defined(OS_ANDROID) TEST_F(DownloadRequestLimiterTest, DownloadRequestLimiter_RawWebContents) { std::unique_ptr<WebContents> web_contents(CreateTestWebContents()); @@ -579,13 +568,12 @@ web_contents->GetController().LoadURL( url, content::Referrer(), ui::PAGE_TRANSITION_LINK, std::string()); - // DownloadRequestLimiter won't try to make a permission bubble if there's - // no permission bubble manager, so don't put one on the test WebContents. - - // DownloadRequestLimiter won't try to make an infobar if it doesn't have an - // InfoBarService, and we want to test that it will Cancel() instead of - // prompting when it doesn't have a InfoBarService, so unset the delegate. - testing_delegate_.UnsetInfobarDelegate(); +// DownloadRequestLimiter won't try to make a permission request or infobar +// if there is no PermissionRequestManager/InfoBarService, and we want to +// test that it will Cancel() instead of prompting. +#if defined(OS_ANDROID) + UnsetInfobarDelegate(); +#endif ExpectAndResetCounts(0, 0, 0, __LINE__); EXPECT_EQ(DownloadRequestLimiter::ALLOW_ONE_DOWNLOAD, download_request_limiter_->GetDownloadStatus(web_contents.get())); @@ -613,7 +601,6 @@ EXPECT_EQ(DownloadRequestLimiter::PROMPT_BEFORE_DOWNLOAD, download_request_limiter_->GetDownloadStatus(web_contents.get())); } -#endif TEST_F(DownloadRequestLimiterTest, DownloadRequestLimiter_SetHostContentSetting) {
diff --git a/chrome/browser/engagement/site_engagement_service_unittest.cc b/chrome/browser/engagement/site_engagement_service_unittest.cc index e029822..87eff98 100644 --- a/chrome/browser/engagement/site_engagement_service_unittest.cc +++ b/chrome/browser/engagement/site_engagement_service_unittest.cc
@@ -205,8 +205,8 @@ const GURL& url) { double score = 0; base::RunLoop run_loop; - content::BrowserThread::PostTaskAndReply( - thread_id, FROM_HERE, + content::BrowserThread::GetTaskRunnerForThread(thread_id)->PostTaskAndReply( + FROM_HERE, base::BindOnce(&SiteEngagementServiceTest::CheckScoreFromSettings, base::Unretained(this), settings_map, url, &score), run_loop.QuitClosure()); @@ -1759,9 +1759,9 @@ // All scores are 0 to start. EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, settings_map, url1)); - EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, settings_map, url2)); - EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, incognito_settings_map, url1)); EXPECT_EQ(0, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, incognito_settings_map, url2)); @@ -1771,11 +1771,11 @@ service->AddPoints(url1, 1); service->AddPoints(url2, 2); - EXPECT_EQ(1, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(1, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, settings_map, url1)); EXPECT_EQ(2, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, settings_map, url2)); - EXPECT_EQ(1, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(1, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, incognito_settings_map, url1)); EXPECT_EQ(2, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, incognito_settings_map, url2)); @@ -1788,11 +1788,11 @@ EXPECT_EQ(1, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, settings_map, url1)); - EXPECT_EQ(2, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(2, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, settings_map, url2)); EXPECT_EQ(4, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, incognito_settings_map, url1)); - EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, incognito_settings_map, url2)); service->AddPoints(url1, 2); @@ -1800,9 +1800,9 @@ EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, settings_map, url1)); - EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, settings_map, url2)); - EXPECT_EQ(4, CheckScoreFromSettingsOnThread(content::BrowserThread::FILE, + EXPECT_EQ(4, CheckScoreFromSettingsOnThread(content::BrowserThread::UI, incognito_settings_map, url1)); EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, incognito_settings_map, url2));
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc index 125b36d5..13864f7f 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc
@@ -15,7 +15,7 @@ #include "chrome/common/extensions/api/passwords_private.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_ui_utils.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_contents.h"
diff --git a/chrome/browser/notifications/notification_channels_provider_android.cc b/chrome/browser/notifications/notification_channels_provider_android.cc index f85426c..e367a84b 100644 --- a/chrome/browser/notifications/notification_channels_provider_android.cc +++ b/chrome/browser/notifications/notification_channels_provider_android.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/notifications/notification_channels_provider_android.h" +#include <algorithm> + #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/logging.h" @@ -17,6 +19,7 @@ #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" +#include "content/public/browser/browser_thread.h" #include "jni/NotificationSettingsBridge_jni.h" #include "url/gurl.h" #include "url/origin.h" @@ -125,7 +128,8 @@ NotificationChannelsProviderAndroid::NotificationChannelsProviderAndroid( std::unique_ptr<NotificationChannelsBridge> bridge) : bridge_(std::move(bridge)), - should_use_channels_(bridge_->ShouldUseChannelSettings()) {} + should_use_channels_(bridge_->ShouldUseChannelSettings()), + weak_factory_(this) {} NotificationChannelsProviderAndroid::~NotificationChannelsProviderAndroid() = default; @@ -140,6 +144,21 @@ return nullptr; } std::vector<NotificationChannel> channels = bridge_->GetChannels(); + std::sort(channels.begin(), channels.end()); + if (channels != cached_channels_) { + // This const_cast is not ideal but tolerated because it doesn't change the + // underlying state of NotificationChannelsProviderAndroid, and allows us to + // notify observers as soon as we detect changes to channels. + auto* provider = const_cast<NotificationChannelsProviderAndroid*>(this); + content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) + ->PostTask( + FROM_HERE, + base::BindOnce( + &NotificationChannelsProviderAndroid::NotifyObservers, + provider->weak_factory_.GetWeakPtr(), ContentSettingsPattern(), + ContentSettingsPattern(), content_type, std::string())); + provider->cached_channels_ = channels; + } return channels.empty() ? nullptr : base::MakeUnique<ChannelsRuleIterator>(std::move(channels)); @@ -182,6 +201,10 @@ NOTREACHED(); break; } + // TODO(awdf): Maybe update cached_channels before notifying here, to + // avoid notifying observers unnecessarily from GetRuleIterator. + NotifyObservers(primary_pattern, secondary_pattern, content_type, + resource_identifier); return true; }
diff --git a/chrome/browser/notifications/notification_channels_provider_android.h b/chrome/browser/notifications/notification_channels_provider_android.h index 896f350..d8034ba2 100644 --- a/chrome/browser/notifications/notification_channels_provider_android.h +++ b/chrome/browser/notifications/notification_channels_provider_android.h
@@ -6,8 +6,11 @@ #define CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_CHANNELS_PROVIDER_ANDROID_H_ #include <string> +#include <tuple> +#include <vector> #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "components/content_settings/core/browser/content_settings_observable_provider.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "components/content_settings/core/browser/content_settings_rule.h" @@ -22,6 +25,12 @@ struct NotificationChannel { NotificationChannel(std::string origin, NotificationChannelStatus status) : origin_(origin), status_(status) {} + bool operator==(const NotificationChannel& other) const { + return origin_ == other.origin_ && status_ == other.status_; + } + bool operator<(const NotificationChannel& other) const { + return std::tie(origin_, status_) < std::tie(other.origin_, other.status_); + } std::string origin_; NotificationChannelStatus status_ = NotificationChannelStatus::UNAVAILABLE; }; @@ -73,6 +82,14 @@ std::unique_ptr<NotificationChannelsBridge> bridge_; bool should_use_channels_; + // This cache is updated every time GetRuleIterator is called. It is used to + // check if any channels have changed their status since the previous call, + // in order to notify observers. This is necessary to detect channels getting + // blocked/enabled by the user, in the absence of a callback for this event. + std::vector<NotificationChannel> cached_channels_; + + base::WeakPtrFactory<NotificationChannelsProviderAndroid> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(NotificationChannelsProviderAndroid); };
diff --git a/chrome/browser/notifications/notification_channels_provider_android_unittest.cc b/chrome/browser/notifications/notification_channels_provider_android_unittest.cc index 991f1a4..32474ae 100644 --- a/chrome/browser/notifications/notification_channels_provider_android_unittest.cc +++ b/chrome/browser/notifications/notification_channels_provider_android_unittest.cc
@@ -5,15 +5,22 @@ #include "chrome/browser/notifications/notification_channels_provider_android.h" #include "base/memory/ptr_util.h" +#include "base/task_scheduler/task_scheduler.h" #include "base/values.h" +#include "chrome/browser/content_settings/content_settings_mock_observer.h" #include "components/content_settings/core/browser/content_settings_pref.h" #include "components/content_settings/core/browser/content_settings_rule.h" #include "components/content_settings/core/browser/content_settings_utils.h" #include "components/content_settings/core/common/content_settings_pattern.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +using ::testing::_; +using ::testing::InSequence; +using ::testing::MockFunction; using ::testing::Return; namespace { @@ -40,17 +47,24 @@ } protected: - // No leak because ownership is passed to channels_provider_ in constructor. - MockNotificationChannelsBridge* mock_bridge_; - std::unique_ptr<NotificationChannelsProviderAndroid> channels_provider_; void InitChannelsProvider(bool should_use_channels) { EXPECT_CALL(*mock_bridge_, ShouldUseChannelSettings()) .WillOnce(Return(should_use_channels)); + ON_CALL(*mock_bridge_, GetChannelStatus(_)) + .WillByDefault(Return(NotificationChannelStatus::UNAVAILABLE)); + // Can't use base::MakeUnique because the provider's constructor is private. channels_provider_ = base::WrapUnique(new NotificationChannelsProviderAndroid( base::WrapUnique(mock_bridge_))); } + + content::TestBrowserThreadBundle test_browser_thread_bundle_; + + // No leak because ownership is passed to channels_provider_ in constructor. + MockNotificationChannelsBridge* mock_bridge_; + + std::unique_ptr<NotificationChannelsProviderAndroid> channels_provider_; }; TEST_F(NotificationChannelsProviderAndroidTest, @@ -217,3 +231,77 @@ content_settings::ValueToContentSetting(second_rule.value.get())); EXPECT_FALSE(result->HasNext()); } + +TEST_F(NotificationChannelsProviderAndroidTest, + GetRuleIteratorNotifiesObserversIfStatusChanges) { + InitChannelsProvider(true /* should_use_channels */); + content_settings::MockObserver mock_observer; + channels_provider_->AddObserver(&mock_observer); + + // Set up sequenced expectations. The observer should be notified on the first + // GetRuleIterator, and then only if channel status has changed to blocked. + // See "Using Check Points" section of the GTest Cookbook: + // https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#using-check-points + MockFunction<void(std::string check_point_name)> check; + { + InSequence s; + EXPECT_CALL(check, Call("0: GetRuleIterator never called")); + // Report channel as enabled initially. + std::vector<NotificationChannel> channels; + channels.emplace_back("https://example.com", + NotificationChannelStatus::ENABLED); + EXPECT_CALL(*mock_bridge_, GetChannels()).WillOnce(Return(channels)); + + // Observer should be notified on first invocation of GetRuleIterator. + EXPECT_CALL( + mock_observer, + OnContentSettingChanged(_, _, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, "")); + EXPECT_CALL(check, Call("1: GetRuleIterator()")); + + // Continue to report channel as enabled. + EXPECT_CALL(*mock_bridge_, GetChannels()).WillOnce(Return(channels)); + + // Observer should not be notified this time. + EXPECT_CALL(check, Call("2: GetRuleIterator()")); + + // Now report channel as blocked. + channels[0].status_ = NotificationChannelStatus::BLOCKED; + EXPECT_CALL(*mock_bridge_, GetChannels()).WillOnce(Return(channels)); + + // GetRuleIterator should now notify observer. + EXPECT_CALL( + mock_observer, + OnContentSettingChanged(_, _, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, "")); + EXPECT_CALL(check, Call("3: GetRuleIterator()")); + } + + check.Call("0: GetRuleIterator never called"); + channels_provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + std::string(), false /* incognito */); + content::RunAllBlockingPoolTasksUntilIdle(); + check.Call("1: GetRuleIterator()"); + channels_provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + std::string(), false /* incognito */); + content::RunAllBlockingPoolTasksUntilIdle(); + check.Call("2: GetRuleIterator()"); + channels_provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + std::string(), false /* incognito */); + content::RunAllBlockingPoolTasksUntilIdle(); + check.Call("3: GetRuleIterator()"); +} + +TEST_F(NotificationChannelsProviderAndroidTest, + SetWebsiteSettingNotifiesObserver) { + InitChannelsProvider(true /* should_use_channels */); + content_settings::MockObserver mock_observer; + channels_provider_->AddObserver(&mock_observer); + + EXPECT_CALL(*mock_bridge_, CreateChannel(kTestOrigin, true /* enabled */)); + EXPECT_CALL( + mock_observer, + OnContentSettingChanged(_, _, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, "")); + channels_provider_->SetWebsiteSetting( + ContentSettingsPattern::FromString(kTestOrigin), ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + new base::Value(CONTENT_SETTING_ALLOW)); +}
diff --git a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc index 91380de..dfa1d52 100644 --- a/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc +++ b/chrome/browser/ntp_snippets/content_suggestions_service_factory.cc
@@ -403,8 +403,18 @@ std::move(subscription_manager), base::Bind(&safe_json::SafeJsonParser::Parse)); + scoped_refptr<base::SequencedTaskRunner> task_runner = + base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); + // TODO(mamir): Check if the same DB can be used for both remote suggestions + // and breaking news. Don't create a separate DB for breaking news in order to + // reduce the memory footprint. (crbug.com/735402) + base::FilePath database_dir( + profile->GetPath().Append(ntp_snippets::kBreakingNewsDatabaseFolder)); auto provider = base::MakeUnique<BreakingNewsSuggestionsProvider>( - service, std::move(handler), base::MakeUnique<base::DefaultClock>()); + service, std::move(handler), base::MakeUnique<base::DefaultClock>(), + base::MakeUnique<RemoteSuggestionsDatabase>(database_dir, task_runner)); provider->Start(); service->RegisterProvider(std::move(provider)); }
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 7b62b17..5fca438d 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -476,7 +476,8 @@ configuration_policy_provider_ = policy::UserPolicyManagerFactoryChromeOS::CreateForProfile( this, force_immediate_policy_load, sequenced_task_runner); - AuthPolicyCredentialsManagerFactory::BuildForProfileIfActiveDirectory(this); + chromeos::AuthPolicyCredentialsManagerFactory:: + BuildForProfileIfActiveDirectory(this); #else configuration_policy_provider_ = policy::UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
diff --git a/chrome/browser/resources/chromeos/input_method/google_input_tools_manifest.json b/chrome/browser/resources/chromeos/input_method/google_input_tools_manifest.json deleted file mode 100644 index 1b6c5048..0000000 --- a/chrome/browser/resources/chromeos/input_method/google_input_tools_manifest.json +++ /dev/null
@@ -1,856 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyRb75ZzKuseD4ZEposVSGTJQjdySVjVA0s2hgFYDJ3hRh5wATyWsLL7EYvbfi2K+hbYBvrxOQYot4eArQloShy4tdQTZovmTXIINIOzN3j/avFfrYSnJNV6C6gpGKglGVEw/lhf+6WdSnGoWjqXWQnnJltc2JtiAk51nkFJUWZwIDAQAB", - "name": "__MSG_chos_inputtool_title__", - "version": "4.3.2.3", - "description": "The Google Input Tools", - "default_locale": "en", - "incognito": "split", - "permissions": [ - "accessibilityFeatures.read", - "app.window.alpha", - "app.window.alwaysOnTop", - "app.window.ime", - "audioCapture", - "https://clients4.google.com/", - "https://dl.google.com/", - "https://www.googleapis.com/", - "input", - "inputMethodPrivate", - "metricsPrivate", - "system.display", - "tabs", - "tts", - "unlimitedStorage", - "virtualKeyboardPrivate" - ], - "background": { - "page": "background.html" - }, - "content_scripts": [ - { - "matches": [ - "https://www.googleapis.com/auth/imesync*" - ], - "js": [ - "chos_inject-debug.js" - ] - } - ], - "ime_path": "/usr/share/chromeos-assets/input_methods/input_tools", - "input_components": [ - { - "name": "__MSG_inputmethod_pinyin__", - "type": "ime", - "id": "zh-t-i0-pinyin", - "indicator": "\u62fc", - "description": "Pinyin", - "language": [ - "zh-CN", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=pinyin-zh-CN.compact.qwerty&language=zh-CN&passwordLayout=pinyin-zh-CN.en.compact.qwerty&name=inputmethod_pinyin", - "options_page": "hmm_options.html?code=zh-t-i0-pinyin" - }, - { - "name": "__MSG_inputmethod_traditional_pinyin__", - "type": "ime", - "id": "zh-hant-t-i0-pinyin", - "indicator": "\u62fc", - "description": "Pinyin for Tranditional Chinese", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=pinyin-zh-TW&language=zh-TW&passwordLayout=pinyin-zh-TW&name=inputmethod_traditional_pinyin", - "options_page": "hmm_options.html?code=zh-hant-t-i0-pinyin" - }, - { - "name": "__MSG_inputmethod_cangjie__", - "type": "ime", - "id": "zh-hant-t-i0-cangjie-1987", - "indicator": "\u5009", - "description": "Cangjie", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=cangjie&language=zh-TW&passwordLayout=cangjie&name=inputmethod_cangjie" - }, - { - "name": "__MSG_inputmethod_quick__", - "type": "ime", - "id": "zh-hant-t-i0-cangjie-1987-x-m0-simplified", - "indicator": "\u901f", - "description": "Quick", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=quick&language=zh-TW&passwordLayout=quick&name=inputmethod_quick" - }, - { - "name": "__MSG_inputmethod_cantonese__", - "type": "ime", - "id": "yue-hant-t-i0-und", - "indicator": "\u7CA4", - "description": "Cantonese", - "language": [ - "zh-TW" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=us&language=zh-CN&passwordLayout=us&name=inputmethod_cantonese" - }, - { - "name": "__MSG_inputmethod_wubi__", - "type": "ime", - "id": "zh-t-i0-wubi-1986", - "indicator": "\u4e94", - "description": "Wubi", - "language": [ - "zh-CN", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=wubi&language=zh-CN&passwordLayout=wubi&name=inputmethod_wubi" - }, - { - "name": "__MSG_inputmethod_array__", - "type": "ime", - "id": "zh-hant-t-i0-array-1992", - "indicator": "\u884c\u5217", - "description": "Array", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=array&language=zh-TW&passwordLayout=array&name=inputmethod_array" - }, - { - "name": "__MSG_inputmethod_dayi__", - "type": "ime", - "id": "zh-hant-t-i0-dayi-1988", - "indicator": "\u5927\u6613", - "description": "Dayi", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=dayi&language=zh-TW&passwordLayout=dayi&name=inputmethod_dayi" - }, - { - "name": "__MSG_inputmethod_zhuyin__", - "type": "ime", - "id": "zh-hant-t-i0-und", - "indicator": "\u6CE8", - "description": "Zhuyin", - "language": [ - "zh-TW", - "zh" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=zhuyin.compact.qwerty&language=zh-TW&passwordLayout=zhuyin.en.compact.qwerty&name=inputmethod_zhuyin", - "options_page": "hmm_options.html?code=zh-hant-t-i0-und" - }, - { - "name": "__MSG_transliteration_am__", - "type": "ime", - "id": "am-t-i0-und", - "description": "Amharic", - "language": "am", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=am&passwordLayout=t13n&name=transliteration_am" - }, - { - "name": "__MSG_transliteration_ar__", - "type": "ime", - "id": "ar-t-i0-und", - "description": "Arabic", - "language": "ar", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n-rtl&language=ar&passwordLayout=t13n-rtl&name=transliteration_ar" - }, - { - "name": "__MSG_transliteration_bn__", - "type": "ime", - "id": "bn-t-i0-und", - "description": "Bengali", - "language": "bn", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=bn&passwordLayout=t13n&name=transliteration_bn" - }, - { - "name": "__MSG_transliteration_el__", - "type": "ime", - "id": "el-t-i0-und", - "description": "Greek", - "language": "el", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=el&passwordLayout=t13n&name=transliteration_el" - }, - { - "name": "__MSG_transliteration_fa__", - "type": "ime", - "id": "fa-t-i0-und", - "description": "Persian", - "language": "fa", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n-rtl&language=fa&passwordLayout=t13n-rtl&name=transliteration_fa" - }, - { - "name": "__MSG_transliteration_gu__", - "type": "ime", - "id": "gu-t-i0-und", - "description": "Gujarati", - "language": "gu", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=gu&passwordLayout=t13n&name=transliteration_gu" - }, - { - "name": "__MSG_transliteration_he__", - "type": "ime", - "id": "he-t-i0-und", - "description": "Hebrew", - "language": "he", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n-rtl&language=he&passwordLayout=t13n-rtl&name=transliteration_he" - }, - { - "name": "__MSG_transliteration_hi__", - "type": "ime", - "id": "hi-t-i0-und", - "description": "Hindi", - "language": "hi", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=hi&passwordLayout=t13n&name=transliteration_hi" - }, - { - "name": "__MSG_transliteration_kn__", - "type": "ime", - "id": "kn-t-i0-und", - "description": "Kannada", - "language": "kn", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=kn&passwordLayout=t13n&name=transliteration_kn" - }, - { - "name": "__MSG_transliteration_ml__", - "type": "ime", - "id": "ml-t-i0-und", - "description": "Malayalam", - "language": "ml", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=ml&passwordLayout=t13n&name=transliteration_ml" - }, - { - "name": "__MSG_transliteration_mr__", - "type": "ime", - "id": "mr-t-i0-und", - "description": "Marathi", - "language": "mr", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=mr&passwordLayout=t13n&name=transliteration_mr" - }, - { - "name": "__MSG_transliteration_ne__", - "type": "ime", - "id": "ne-t-i0-und", - "description": "Nepali", - "language": "ne", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=ne&passwordLayout=t13n&name=transliteration_ne" - }, - { - "name": "__MSG_transliteration_or__", - "type": "ime", - "id": "or-t-i0-und", - "description": "Oriya", - "language": "or", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=or&passwordLayout=t13n&name=transliteration_or" - }, - { - "name": "__MSG_transliteration_pa__", - "type": "ime", - "id": "pa-t-i0-und", - "description": "Punjabi", - "language": "pa", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=pa&passwordLayout=t13n&name=transliteration_pa" - }, - { - "name": "__MSG_transliteration_sa__", - "type": "ime", - "id": "sa-t-i0-und", - "description": "Sanskrit", - "language": "sa", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=sa&passwordLayout=t13n&name=transliteration_sa" - }, - { - "name": "__MSG_transliteration_sr__", - "type": "ime", - "id": "sr-t-i0-und", - "description": "Serbian", - "language": "sr", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=sr&passwordLayout=t13n&name=transliteration_sr" - }, - { - "name": "__MSG_transliteration_ta__", - "type": "ime", - "id": "ta-t-i0-und", - "description": "Tamil", - "language": "ta", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=ta&passwordLayout=t13n&name=transliteration_ta" - }, - { - "name": "__MSG_transliteration_te__", - "type": "ime", - "id": "te-t-i0-und", - "description": "Telugu", - "language": "te", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=te&passwordLayout=t13n&name=transliteration_te" - }, - { - "name": "__MSG_transliteration_ti__", - "type": "ime", - "id": "ti-t-i0-und", - "description": "Tigrinya", - "language": "ti", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n&language=ti&passwordLayout=t13n&name=transliteration_ti" - }, - { - "name": "__MSG_transliteration_ur__", - "type": "ime", - "id": "ur-t-i0-und", - "description": "Urdu", - "language": "ur", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=t13n-rtl&language=ur&passwordLayout=t13n-rtl&name=transliteration_ur" - }, - { - "name": "__MSG_inputmethod_hangul__", - "type": "ime", - "id": "ko-t-i0-und", - "indicator": "\ud55c", - "description": "Korean input method.", - "language": "ko", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=ko&language=ko&passwordLayout=us-ltr&name=inputmethod_hangul", - "options_page": "hmm_options.html?code=ko-t-i0-und" - }, - { - "name": "__MSG_inputmethod_mozc_us__", - "type": "ime", - "id": "nacl_mozc_us", - "indicator": "\u3042", - "description": "Japanese input method.", - "language": "ja", - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=jp_us&language=ja&passwordLayout=us-ltr&name=appNameUSKeyboard", - "options_page": "mozc_option.html" - }, - { - "name": "__MSG_inputmethod_mozc_jp__", - "type": "ime", - "id": "nacl_mozc_jp", - "indicator": "\u3042", - "description": "Japanese input method.", - "language": "ja", - "layouts": [ - "jp" - ], - "input_view": "inputview.html#id=jp&language=ja&passwordLayout=us-ltr&name=appNameJPKeyboard", - "options_page": "mozc_option.html" - }, - { - "name": "__MSG_keyboard_bengali_phonetic__", - "type": "ime", - "id": "vkd_bn_phone", - "description": "", - "language": [ - "bn" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:bn_phone&language=bn&passwordLayout=us-ltr&name=keyboard_bengali_phonetic" - }, - { - "name": "__MSG_keyboard_gujarati_phonetic__", - "type": "ime", - "id": "vkd_gu_phone", - "description": "", - "language": [ - "gu" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:gu_phone&language=gu&passwordLayout=us-ltr&name=keyboard_gujarati_phonetic" - }, - { - "name": "__MSG_keyboard_devanagari_phonetic__", - "type": "ime", - "id": "vkd_deva_phone", - "description": "", - "language": [ - "hi", - "mr" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:deva_phone&language=hi&passwordLayout=us-ltr&name=keyboard_devanagari_phonetic" - }, - { - "name": "__MSG_keyboard_kannada_phonetic__", - "type": "ime", - "id": "vkd_kn_phone", - "description": "", - "language": [ - "kn" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:kn_phone&language=kn&passwordLayout=us-ltr&name=keyboard_kannada_phonetic" - }, - { - "name": "__MSG_keyboard_malayalam_phonetic__", - "type": "ime", - "id": "vkd_ml_phone", - "description": "", - "language": [ - "ml" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ml_phone&language=ml&passwordLayout=us-ltr&name=keyboard_malayalam_phonetic" - }, - { - "name": "__MSG_keyboard_tamil_inscript__", - "type": "ime", - "id": "vkd_ta_inscript", - "description": "", - "language": [ - "ta" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ta_inscript&language=ta&passwordLayout=us-ltr&name=keyboard_tamil_inscript" - }, - { - "name": "__MSG_keyboard_tamil_phonetic__", - "type": "ime", - "id": "vkd_ta_phone", - "description": "", - "language": [ - "ta" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ta_phone&language=ta&passwordLayout=us-ltr&name=keyboard_tamil_phonetic" - }, - { - "name": "__MSG_keyboard_tamil_tamil99__", - "type": "ime", - "id": "vkd_ta_tamil99", - "description": "", - "language": [ - "ta" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ta_tamil99&language=ta&passwordLayout=us-ltr&name=keyboard_tamil_tamil99" - }, - { - "name": "__MSG_keyboard_tamil_typewriter__", - "type": "ime", - "id": "vkd_ta_typewriter", - "description": "", - "language": [ - "ta" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ta_typewriter&language=ta&passwordLayout=us-ltr&name=keyboard_tamil_typewriter" - }, - { - "name": "__MSG_keyboard_tamil_itrans__", - "type": "ime", - "id": "vkd_ta_itrans", - "description": "", - "language": [ - "ta" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ta_itrans&language=ta&passwordLayout=us-ltr&name=keyboard_tamil_itrans" - }, - { - "name": "__MSG_keyboard_telugu_phonetic__", - "type": "ime", - "id": "vkd_te_phone", - "description": "", - "language": [ - "te" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:te_phone&language=te&passwordLayout=us-ltr&name=keyboard_telugu_phonetic" - }, - { - "name": "__MSG_keyboard_ethiopic__", - "type": "ime", - "id": "vkd_ethi", - "description": "", - "language": [ - "am" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ethi&language=am&passwordLayout=us-ltr&name=keyboard_ethiopic" - }, - { - "name": "__MSG_keyboard_thai_kedmanee__", - "type": "ime", - "id": "vkd_th", - "description": "", - "language": [ - "th" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:th&language=th&passwordLayout=us-ltr&name=keyboard_thai_kedmanee" - }, - { - "name": "__MSG_keyboard_thai_pattachote__", - "type": "ime", - "id": "vkd_th_pattajoti", - "description": "", - "language": [ - "th" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:th_pattajoti&language=th&passwordLayout=us-ltr&name=keyboard_thai_pattachote" - }, - { - "name": "__MSG_keyboard_thai_tis__", - "type": "ime", - "id": "vkd_th_tis", - "description": "", - "language": [ - "th" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:th_tis&language=th&passwordLayout=us-ltr&name=keyboard_thai_tis" - }, - { - "name": "__MSG_keyboard_persian__", - "type": "ime", - "id": "vkd_fa", - "description": "", - "language": [ - "fa" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:fa&language=fa&passwordLayout=us-rtl&name=keyboard_persian" - }, - { - "name": "__MSG_keyboard_vietnamese_tcvn__", - "type": "ime", - "id": "vkd_vi_tcvn", - "description": "", - "language": [ - "vi" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:vi_tcvn&language=vi&passwordLayout=us-ltr&name=keyboard_vietnamese_tcvn" - }, - { - "name": "__MSG_keyboard_vietnamese_telex__", - "type": "ime", - "id": "vkd_vi_telex", - "description": "", - "language": [ - "vi" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:vi_telex&language=vi&passwordLayout=us-ltr&name=keyboard_vietnamese_telex" - }, - { - "name": "__MSG_keyboard_vietnamese_viqr__", - "type": "ime", - "id": "vkd_vi_viqr", - "description": "", - "language": [ - "vi" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:vi_viqr&language=vi&passwordLayout=us-ltr&name=keyboard_vietnamese_viqr" - }, - { - "name": "__MSG_keyboard_vietnamese_vni__", - "type": "ime", - "id": "vkd_vi_vni", - "description": "", - "language": [ - "vi" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:vi_vni&language=vi&passwordLayout=us-ltr&name=keyboard_vietnamese_vni" - }, - { - "name": "__MSG_keyboard_arabic__", - "type": "ime", - "id": "vkd_ar", - "description": "", - "language": [ - "ar" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ar&language=ar&passwordLayout=us-rtl&name=keyboard_arabic" - }, - { - "name": "__MSG_keyboard_lao__", - "type": "ime", - "id": "vkd_lo", - "description": "", - "language": [ - "lo" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:lo&language=lo&passwordLayout=us-ltr&name=keyboard_laothian" - }, - { - "name": "__MSG_keyboard_nepali_inscript__", - "type": "ime", - "id": "vkd_ne_inscript", - "description": "", - "language": [ - "ne" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ne_inscript&language=ne&passwordLayout=us-ltr&name=keyboard_nepali_inscript" - }, - { - "name": "__MSG_keyboard_nepali_phonetic__", - "type": "ime", - "id": "vkd_ne_phone", - "description": "", - "language": [ - "ne" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ne_phone&language=ne&passwordLayout=us-ltr&name=keyboard_nepali_phonetic" - }, - { - "name": "__MSG_keyboard_khmer__", - "type": "ime", - "id": "vkd_km", - "description": "", - "language": [ - "km" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:km&language=km&passwordLayout=us-ltr&name=keyboard_khmer" - }, - { - "name": "__MSG_keyboard_myanmar__", - "type": "ime", - "id": "vkd_my", - "description": "", - "language": [ - "my" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:my&language=my&passwordLayout=us-ltr&name=keyboard_myanmar" - }, - { - "name": "__MSG_keyboard_sinhala__", - "type": "ime", - "id": "vkd_si", - "description": "", - "language": [ - "si" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:si&language=si&passwordLayout=us-ltr&name=keyboard_sinhala" - }, - { - "name": "__MSG_keyboard_soranikurdish_en__", - "type": "ime", - "id": "vkd_ckb_en", - "description": "Sorani Kurdish - English-based", - "language": [ - "ckb" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ckb_en&language=ckb&passwordLayout=us-rtl&name=keyboard_soranikurdish_en" - }, - { - "name": "__MSG_keyboard_soranikurdish_ar__", - "type": "ime", - "id": "vkd_ckb_ar", - "description": "Sorani Kurdish - Arabic-based", - "language": [ - "ckb" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ckb_ar&language=ckb&passwordLayout=us-rtl&name=keyboard_soranikurdish_ar" - }, - { - "name": "__MSG_keyboard_myanmar_myansan__", - "type": "ime", - "id": "vkd_my_myansan", - "description": "", - "language": [ - "my" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:my_myansan&language=my&passwordLayout=us-ltr&name=keyboard_myanmar_myansan" - }, - { - "name": "__MSG_keyboard_russian_phonetic_aatseel__", - "type": "ime", - "id": "vkd_ru_phone_aatseel", - "description": "", - "language": [ - "ru" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ru_phone_aatseel&language=ru&passwordLayout=us-ltr&name=keyboard_russian_phonetic_aatseel" - }, - { - "name": "__MSG_keyboard_russian_phonetic_yazhert__", - "type": "ime", - "id": "vkd_ru_phone_yazhert", - "description": "", - "language": [ - "ru" - ], - "layouts": [ - "us" - ], - "input_view": "inputview.html#id=m17n:ru_phone_yazhert&language=ru&passwordLayout=us-ltr&name=keyboard_russian_phonetic_yazhert" - } - ], - "manifest_version": 2 -}
diff --git a/chrome/browser/resources/md_bookmarks/command_manager.html b/chrome/browser/resources/md_bookmarks/command_manager.html index 1a87572..8245ee7 100644 --- a/chrome/browser/resources/md_bookmarks/command_manager.html +++ b/chrome/browser/resources/md_bookmarks/command_manager.html
@@ -10,7 +10,22 @@ <dom-module id="bookmarks-command-manager"> <template> - <style include="shared-style"></style> + <style include="shared-style"> + .label { + flex: 1; + } + + .sublabel { + -webkit-margin-start: 8px; + color: var(--secondary-text-color); + text-align: end; + width: 3ch; + } + + :host(:not([has-any-sublabel_])) .sublabel { + display: none; + } + </style> <dialog is="cr-action-menu" id="dropdown" on-mousedown="onMenuMousedown_"> <template is="dom-repeat" items="[[menuCommands_]]" as="command"> <button class="dropdown-item" @@ -18,7 +33,12 @@ hidden$="[[!isCommandVisible_(command, menuIds_)]]" disabled$="[[!isCommandEnabled_(command, menuIds_)]]" on-tap="onCommandClick_"> - [[getCommandLabel_(command, menuIds_)]] + <span class="label"> + [[getCommandLabel_(command, menuIds_)]] + </span> + <span class="sublabel"> + [[getCommandSublabel_(command, menuIds_)]] + </span> </button> <hr hidden$="[[!showDividerAfter_(command, menuIds_)]]"></hr> </template>
diff --git a/chrome/browser/resources/md_bookmarks/command_manager.js b/chrome/browser/resources/md_bookmarks/command_manager.js index 20c90a83..1fc42a70 100644 --- a/chrome/browser/resources/md_bookmarks/command_manager.js +++ b/chrome/browser/resources/md_bookmarks/command_manager.js
@@ -33,7 +33,16 @@ }, /** @private {Set<string>} */ - menuIds_: Object, + menuIds_: { + type: Object, + observer: 'onMenuIdsChanged_', + }, + + /** @private */ + hasAnySublabel_: { + type: Boolean, + reflectToAttribute: true, + }, /** @private */ globalCanEdit_: Boolean, @@ -425,7 +434,8 @@ * @private */ onCommandClick_: function(e) { - this.handle(e.target.getAttribute('command'), assert(this.menuIds_)); + this.handle( + e.currentTarget.getAttribute('command'), assert(this.menuIds_)); this.closeCommandMenu(); }, @@ -495,6 +505,35 @@ /** * @param {Command} command + * @return {string} + * @private + */ + getCommandSublabel_: function(command) { + var multipleNodes = this.menuIds_.size > 1 || + this.containsMatchingNode_(this.menuIds_, function(node) { + return !node.url; + }); + switch (command) { + case Command.OPEN_NEW_TAB: + var urls = this.expandUrls_(this.menuIds_); + return multipleNodes && urls.length > 0 ? String(urls.length) : ''; + default: + return ''; + } + }, + + /** @private */ + onMenuIdsChanged_: function() { + if (!this.menuIds_) + return; + + this.hasAnySublabel_ = this.menuCommands_.some(function(command) { + return this.getCommandSublabel_(command) != ''; + }.bind(this)); + }, + + /** + * @param {Command} command * @return {boolean} * @private */
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index e590768..e2ef551 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -411,7 +411,7 @@ <settings-subpage page-title="$i18n{siteSettingsAds}"> <category-default-setting category="{{ContentSettingsTypes.ADS}}" - toggle-off-label="$i18n{siteSettingsAdsBlock}" + toggle-off-label="$i18n{siteSettingsAdsBlockRecommended}" toggle-on-label="$i18n{siteSettingsAllowed}"> </category-default-setting> <category-setting-exceptions
diff --git a/chrome/browser/safe_browsing/incident_reporting/environment_data_collection.cc b/chrome/browser/safe_browsing/incident_reporting/environment_data_collection.cc index 31f905f9..06e02ec4 100644 --- a/chrome/browser/safe_browsing/incident_reporting/environment_data_collection.cc +++ b/chrome/browser/safe_browsing/incident_reporting/environment_data_collection.cc
@@ -6,19 +6,13 @@ #include <string> -#include "base/bind.h" -#include "base/callback_helpers.h" #include "base/cpu.h" -#include "base/logging.h" #include "base/sys_info.h" -#include "base/threading/platform_thread.h" -#include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/common/channel_info.h" #include "components/safe_browsing/csd.pb.h" #include "components/version_info/version_info.h" -#include "content/public/browser/browser_thread.h" namespace safe_browsing { @@ -70,17 +64,7 @@ } // namespace void CollectEnvironmentData(ClientIncidentReport_EnvironmentData* data) { - // Toggling priority only makes sense in a thread pool. base::ThreadRestrictions::AssertIOAllowed(); - // Reset priority when done with this task. - // TODO(fdoray): Post this task to the TaskScheduler with a BACKGROUND - // priority instead of toggling the priority within the task. - base::ScopedClosureRunner restore_priority( - base::Bind(&base::PlatformThread::SetCurrentThreadPriority, - base::PlatformThread::GetCurrentThreadPriority())); - // Lower priority for this task. - base::PlatformThread::SetCurrentThreadPriority( - base::ThreadPriority::BACKGROUND); // OS {
diff --git a/chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.cc b/chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.cc index 0275fdd..d0a150f 100644 --- a/chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.cc +++ b/chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.cc
@@ -18,6 +18,8 @@ #include "base/process/process_info.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" @@ -121,10 +123,17 @@ // Returns the shutdown behavior for the task runners of the incident reporting // service. Current metrics suggest that CONTINUE_ON_SHUTDOWN will reduce the // number of browser hangs on shutdown. -base::SequencedWorkerPool::WorkerShutdown GetShutdownBehavior() { +base::TaskShutdownBehavior GetShutdownBehavior() { return base::FeatureList::IsEnabled(features::kBrowserHangFixesExperiment) - ? base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN - : base::SequencedWorkerPool::SKIP_ON_SHUTDOWN; + ? base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN + : base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN; +} + +// Returns a task runner for blocking tasks in the background. +scoped_refptr<base::TaskRunner> GetBackgroundTaskRunner() { + return base::CreateTaskRunnerWithTraits({base::TaskPriority::BACKGROUND, + GetShutdownBehavior(), + base::MayBlock()}); } } // namespace @@ -315,9 +324,7 @@ safe_browsing_service ? safe_browsing_service->url_request_context() : nullptr), collect_environment_data_fn_(&CollectEnvironmentData), - environment_collection_task_runner_( - content::BrowserThread::GetBlockingPool() - ->GetTaskRunnerWithShutdownBehavior(GetShutdownBehavior())), + environment_collection_task_runner_(GetBackgroundTaskRunner()), environment_collection_pending_(), collation_timeout_pending_(), collation_timer_(FROM_HERE, @@ -326,8 +333,7 @@ &IncidentReportingService::OnCollationTimeout), delayed_analysis_callbacks_( base::TimeDelta::FromMilliseconds(kDefaultCallbackIntervalMs), - content::BrowserThread::GetBlockingPool() - ->GetTaskRunnerWithShutdownBehavior(GetShutdownBehavior())), + GetBackgroundTaskRunner()), download_metadata_manager_(content::BrowserThread::GetBlockingPool()), receiver_weak_ptr_factory_(this), weak_ptr_factory_(this) { @@ -408,9 +414,7 @@ : nullptr), url_request_context_getter_(request_context_getter), collect_environment_data_fn_(&CollectEnvironmentData), - environment_collection_task_runner_( - content::BrowserThread::GetBlockingPool() - ->GetTaskRunnerWithShutdownBehavior(GetShutdownBehavior())), + environment_collection_task_runner_(GetBackgroundTaskRunner()), environment_collection_pending_(), collation_timeout_pending_(), collation_timer_(FROM_HERE, @@ -437,9 +441,7 @@ environment_collection_task_runner_ = task_runner; } else { collect_environment_data_fn_ = &CollectEnvironmentData; - environment_collection_task_runner_ = - content::BrowserThread::GetBlockingPool() - ->GetTaskRunnerWithShutdownBehavior(GetShutdownBehavior()); + environment_collection_task_runner_ = GetBackgroundTaskRunner(); } }
diff --git a/chrome/browser/ui/passwords/manage_passwords_view_utils.cc b/chrome/browser/ui/passwords/manage_passwords_view_utils.cc index b7b1387e..ef85015 100644 --- a/chrome/browser/ui/passwords/manage_passwords_view_utils.cc +++ b/chrome/browser/ui/passwords/manage_passwords_view_utils.cc
@@ -15,7 +15,7 @@ #include "chrome/grit/generated_resources.h" #include "components/autofill/core/common/password_form.h" #include "components/browser_sync/profile_sync_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/elide_url.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
diff --git a/chrome/browser/ui/passwords/password_manager_presenter.cc b/chrome/browser/ui/passwords/password_manager_presenter.cc index 9c2dfe71..7dc4922 100644 --- a/chrome/browser/ui/passwords/password_manager_presenter.cc +++ b/chrome/browser/ui/passwords/password_manager_presenter.cc
@@ -30,7 +30,7 @@ #include "chrome/common/url_constants.h" #include "components/autofill/core/common/password_form.h" #include "components/browser_sync/profile_sync_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/import/password_importer.h" #include "components/password_manager/core/browser/password_ui_utils.h" #include "components/password_manager/core/common/password_manager_pref_names.h"
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index 4f27ee99..9b07071 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -1915,6 +1915,8 @@ {"noSitesAdded", IDS_SETTINGS_SITE_NO_SITES_ADDED}, {"siteSettingsAds", IDS_SETTINGS_SITE_SETTINGS_ADS}, {"siteSettingsAdsBlock", IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK}, + {"siteSettingsAdsBlockRecommended", + IDS_SETTINGS_SITE_SETTINGS_ADS_BLOCK_RECOMMENDED}, }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings));
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index 15619b6..9e449139f 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -2960,4 +2960,25 @@ // The username and password should have been autocompleted. CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true); } + +// Regression test for https://crbug.com/728028. +TEST_F(PasswordAutofillAgentTest, NoForm_MultipleAJAXEventsWithoutSubmission) { + LoadHTML(kNoFormHTML); + UpdateUsernameAndPasswordElements(); + + SimulateUsernameChange("Bob"); + SimulatePasswordChange("mypassword"); + + password_autofill_agent_->AJAXSucceeded(); + base::RunLoop().RunUntilIdle(); + + // Repeatedly occurring AJAX events without removing the input elements + // shouldn't be treated as a password submission. + password_autofill_agent_->AJAXSucceeded(); + base::RunLoop().RunUntilIdle(); + + ASSERT_FALSE(fake_driver_.called_password_form_submitted()); + ASSERT_FALSE(static_cast<bool>(fake_driver_.password_form_submitted())); +} + } // namespace autofill
diff --git a/chrome/test/data/webui/engagement/site_engagement_browsertest.js b/chrome/test/data/webui/engagement/site_engagement_browsertest.js index 0efbd08..96d75dd 100644 --- a/chrome/test/data/webui/engagement/site_engagement_browsertest.js +++ b/chrome/test/data/webui/engagement/site_engagement_browsertest.js
@@ -46,8 +46,13 @@ }, }; -// TODO(crbug.com/734716): This test is flaky. -TEST_F('SiteEngagementBrowserTest', 'DISABLED_All', function() { +// This test is flaky on Windows. See https://crbug.com/734716. +GEN('#if defined(OS_WIN)'); +GEN('#define MAYBE_All DISABLED_All'); +GEN('#else'); +GEN('#define MAYBE_All All'); +GEN('#endif'); +TEST_F('SiteEngagementBrowserTest', 'MAYBE_All', function() { test('check engagement values are loaded', function() { var originCells = Array.from(document.getElementsByClassName('origin-cell'));
diff --git a/chromeos/dbus/fake_auth_policy_client.cc b/chromeos/dbus/fake_auth_policy_client.cc index 515060f7..8050d58 100644 --- a/chromeos/dbus/fake_auth_policy_client.cc +++ b/chromeos/dbus/fake_auth_policy_client.cc
@@ -37,9 +37,9 @@ // |serialized_payload|. bool WritePolicyFile(const base::FilePath& policy_path, const std::string& serialized_payload, - const std::string& policy_type) { - base::PlatformThread::Sleep( - base::TimeDelta::FromSeconds(kOperationDelaySeconds)); + const std::string& policy_type, + const base::TimeDelta& delay) { + base::PlatformThread::Sleep(delay); em::PolicyData data; data.set_policy_value(serialized_payload); @@ -63,17 +63,18 @@ return bytes_written == static_cast<int>(serialized_response.size()); } -void PostDelayedClosure(base::OnceClosure closure) { +void PostDelayedClosure(base::OnceClosure closure, + const base::TimeDelta& delay) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, std::move(closure), - base::TimeDelta::FromSeconds(kOperationDelaySeconds)); + FROM_HERE, std::move(closure), delay); } } // namespace namespace chromeos { -FakeAuthPolicyClient::FakeAuthPolicyClient() {} +FakeAuthPolicyClient::FakeAuthPolicyClient() + : operation_delay_(base::TimeDelta::FromSeconds(kOperationDelaySeconds)) {} FakeAuthPolicyClient::~FakeAuthPolicyClient() {} @@ -100,7 +101,8 @@ error = authpolicy::ERROR_PARSE_UPN_FAILED; } } - PostDelayedClosure(base::BindOnce(std::move(callback), error)); + PostDelayedClosure(base::BindOnce(std::move(callback), error), + operation_delay_); } void FakeAuthPolicyClient::AuthenticateUser( @@ -122,15 +124,29 @@ } error = auth_error_; } - PostDelayedClosure(base::BindOnce(std::move(callback), error, account_info)); + PostDelayedClosure(base::BindOnce(std::move(callback), error, account_info), + operation_delay_); } void FakeAuthPolicyClient::GetUserStatus(const std::string& object_guid, GetUserStatusCallback callback) { authpolicy::ActiveDirectoryUserStatus user_status; - user_status.mutable_account_info()->set_account_id(object_guid); + user_status.set_password_status(password_status_); + user_status.set_tgt_status(tgt_status_); + + authpolicy::ActiveDirectoryAccountInfo* const account_info = + user_status.mutable_account_info(); + account_info->set_account_id(object_guid); + if (!display_name_.empty()) + account_info->set_display_name(display_name_); + if (!given_name_.empty()) + account_info->set_given_name(given_name_); + PostDelayedClosure( - base::BindOnce(std::move(callback), authpolicy::ERROR_NONE, user_status)); + base::BindOnce(std::move(callback), authpolicy::ERROR_NONE, user_status), + operation_delay_); + if (!on_get_status_closure_.is_null()) + PostDelayedClosure(std::move(on_get_status_closure_), operation_delay_); } void FakeAuthPolicyClient::RefreshDevicePolicy(RefreshPolicyCallback callback) { @@ -156,7 +172,7 @@ {base::MayBlock(), base::TaskPriority::BACKGROUND, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&WritePolicyFile, policy_path, payload, - "google/chromeos/device"), + "google/chromeos/device", operation_delay_), std::move(callback)); } @@ -189,7 +205,7 @@ {base::MayBlock(), base::TaskPriority::BACKGROUND, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&WritePolicyFile, policy_path, payload, - "google/chromeos/user"), + "google/chromeos/user", operation_delay_), std::move(callback)); }
diff --git a/chromeos/dbus/fake_auth_policy_client.h b/chromeos/dbus/fake_auth_policy_client.h index 96ea01f9..fdd7f6ac 100644 --- a/chromeos/dbus/fake_auth_policy_client.h +++ b/chromeos/dbus/fake_auth_policy_client.h
@@ -48,9 +48,44 @@ auth_error_ = auth_error; } + void set_display_name(const std::string& display_name) { + display_name_ = display_name; + } + + void set_given_name(const std::string& given_name) { + given_name_ = given_name; + } + + void set_password_status( + authpolicy::ActiveDirectoryUserStatus::PasswordStatus password_status) { + password_status_ = password_status; + } + + void set_tgt_status( + authpolicy::ActiveDirectoryUserStatus::TgtStatus tgt_status) { + tgt_status_ = tgt_status; + } + + void set_on_get_status_closure(base::OnceClosure on_get_status_closure) { + on_get_status_closure_ = std::move(on_get_status_closure); + } + + void set_operation_delay(const base::TimeDelta operation_delay) { + operation_delay_ = operation_delay; + } + private: bool started_ = false; + // If valid called after GetUserStatusCallback is called. + base::OnceClosure on_get_status_closure_; authpolicy::ErrorType auth_error_ = authpolicy::ERROR_NONE; + std::string display_name_; + std::string given_name_; + authpolicy::ActiveDirectoryUserStatus::PasswordStatus password_status_ = + authpolicy::ActiveDirectoryUserStatus::PASSWORD_VALID; + authpolicy::ActiveDirectoryUserStatus::TgtStatus tgt_status_ = + authpolicy::ActiveDirectoryUserStatus::TGT_VALID; + base::TimeDelta operation_delay_; DISALLOW_COPY_AND_ASSIGN(FakeAuthPolicyClient); };
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 44c5cdd9..6ccc3a2 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -1300,8 +1300,6 @@ return; } - RecordMemoryUsageHistograms(); - StartSyncingWithServer(); } @@ -2394,16 +2392,6 @@ sync_prefs_.SetCleanShutdown(false); } -void ProfileSyncService::RecordMemoryUsageHistograms() { - ModelTypeSet active_types = GetActiveDataTypes(); - for (ModelTypeSet::Iterator type_it = active_types.First(); type_it.Good(); - type_it.Inc()) { - auto dtc_it = data_type_controllers_.find(type_it.Get()); - if (dtc_it != data_type_controllers_.end()) - dtc_it->second->RecordMemoryUsageHistogram(); - } -} - const GURL& ProfileSyncService::sync_service_url() const { DCHECK(thread_checker_.CalledOnValidThread()); return sync_service_url_;
diff --git a/components/browser_sync/profile_sync_service.h b/components/browser_sync/profile_sync_service.h index ed8908c..a47fe59 100644 --- a/components/browser_sync/profile_sync_service.h +++ b/components/browser_sync/profile_sync_service.h
@@ -725,9 +725,6 @@ // Check if previous shutdown is shutdown cleanly. void ReportPreviousSessionMemoryWarningCount(); - // Estimates and records memory usage histograms per type. - void RecordMemoryUsageHistograms(); - // After user switches to custom passphrase encryption a set of steps needs to // be performed: //
diff --git a/components/download/components_unittests.filter b/components/download/components_unittests.filter index bd5ad26..023467a6 100644 --- a/components/download/components_unittests.filter +++ b/components/download/components_unittests.filter
@@ -7,6 +7,7 @@ DownloadServiceEntryUtilsTest.* DownloadServiceModelImplTest.* DownloadStoreTest.* +FileMonitorTest.* NetworkListenerTest.* ProtoConversionsTest.* ServiceConfigImplTest.* \ No newline at end of file
diff --git a/components/download/content/factory/download_service_factory.cc b/components/download/content/factory/download_service_factory.cc index a47e5b0..d440a04 100644 --- a/components/download/content/factory/download_service_factory.cc +++ b/components/download/content/factory/download_service_factory.cc
@@ -10,6 +10,7 @@ #include "components/download/internal/controller_impl.h" #include "components/download/internal/download_service_impl.h" #include "components/download/internal/download_store.h" +#include "components/download/internal/file_monitor_impl.h" #include "components/download/internal/model_impl.h" #include "components/download/internal/proto/entry.pb.h" #include "components/download/internal/scheduler/scheduler_impl.h" @@ -45,11 +46,12 @@ auto device_status_listener = base::MakeUnique<DeviceStatusListener>(); auto scheduler = base::MakeUnique<SchedulerImpl>( task_scheduler.get(), config.get(), client_set.get()); - + auto file_monitor = base::MakeUnique<FileMonitorImpl>( + files_storage_dir, background_task_runner, config->file_keep_alive_time); auto controller = base::MakeUnique<ControllerImpl>( config.get(), std::move(client_set), std::move(driver), std::move(model), std::move(device_status_listener), std::move(scheduler), - std::move(task_scheduler)); + std::move(task_scheduler), std::move(file_monitor), files_storage_dir); return new DownloadServiceImpl(std::move(config), std::move(controller)); }
diff --git a/components/download/content/internal/download_driver_impl.cc b/components/download/content/internal/download_driver_impl.cc index d6581da..415f043 100644 --- a/components/download/content/internal/download_driver_impl.cc +++ b/components/download/content/internal/download_driver_impl.cc
@@ -49,6 +49,8 @@ entry.paused = item->IsPaused(); entry.bytes_downloaded = item->GetReceivedBytes(); entry.expected_total_size = item->GetTotalBytes(); + entry.temporary_physical_file_path = item->GetFullPath(); + entry.completion_time = item->GetEndTime(); entry.response_headers = item->GetResponseHeaders(); entry.url_chain = item->GetUrlChain(); return entry;
diff --git a/components/download/internal/BUILD.gn b/components/download/internal/BUILD.gn index a78f8c0e..f138251 100644 --- a/components/download/internal/BUILD.gn +++ b/components/download/internal/BUILD.gn
@@ -34,6 +34,9 @@ "entry.h", "entry_utils.cc", "entry_utils.h", + "file_monitor.h", + "file_monitor_impl.cc", + "file_monitor_impl.h", "model.h", "model_impl.cc", "model_impl.h", @@ -73,6 +76,7 @@ "download_service_impl_unittest.cc", "download_store_unittest.cc", "entry_utils_unittest.cc", + "file_monitor_unittest.cc", "model_impl_unittest.cc", "proto_conversions_unittest.cc", "scheduler/device_status_listener_unittest.cc",
diff --git a/components/download/internal/config.cc b/components/download/internal/config.cc index 64bf46d..4aa195b 100644 --- a/components/download/internal/config.cc +++ b/components/download/internal/config.cc
@@ -31,6 +31,10 @@ // 12 hours by default. const uint32_t kDefaultFileKeepAliveTimeMinutes = 12 * 60; +// Default value for file cleanup window in minutes, the system will schedule a +// cleanup task within this window. +const uint32_t kDefaultFileCleanupWindowMinutes = 24 * 60; + // Default value for the start window time for OS to schedule background task. const uint32_t kDefaultWindowStartTimeSeconds = 300; /* 5 minutes. */ @@ -63,6 +67,9 @@ config->file_keep_alive_time = base::TimeDelta::FromMinutes(base::saturated_cast<int>(GetFinchConfigUInt( kFileKeepAliveTimeMinutesConfig, kDefaultFileKeepAliveTimeMinutes))); + config->file_cleanup_window = + base::TimeDelta::FromMinutes(base::saturated_cast<int>(GetFinchConfigUInt( + kFileCleanupWindowMinutesConfig, kDefaultFileCleanupWindowMinutes))); config->window_start_time_seconds = GetFinchConfigUInt( kWindowStartTimeConfig, kDefaultWindowStartTimeSeconds); config->window_end_time_seconds = @@ -77,6 +84,8 @@ max_retry_count(kDefaultMaxRetryCount), file_keep_alive_time(base::TimeDelta::FromMinutes( base::saturated_cast<int>(kDefaultFileKeepAliveTimeMinutes))), + file_cleanup_window(base::TimeDelta::FromMinutes( + base::saturated_cast<int>(kDefaultFileCleanupWindowMinutes))), window_start_time_seconds(kDefaultWindowStartTimeSeconds), window_end_time_seconds(kDefaultWindowEndTimeSeconds) {}
diff --git a/components/download/internal/config.h b/components/download/internal/config.h index b5d5991b..8135020 100644 --- a/components/download/internal/config.h +++ b/components/download/internal/config.h
@@ -27,6 +27,9 @@ // Configuration name for file keep alive time. constexpr char kFileKeepAliveTimeMinutesConfig[] = "file_keep_alive_time"; +// Configuration name for file keep alive time. +constexpr char kFileCleanupWindowMinutesConfig[] = "file_cleanup_window"; + // Configuration name for window start time. constexpr char kWindowStartTimeConfig[] = "window_start_time_seconds"; @@ -62,6 +65,10 @@ // deleting them if the client hasn't handle the files. base::TimeDelta file_keep_alive_time; + // The length of the flexible time window during which the scheduler must + // schedule a file cleanup task. + base::TimeDelta file_cleanup_window; + // The start window time in seconds for OS to schedule background task. // The OS will trigger the background task in this window. uint32_t window_start_time_seconds;
diff --git a/components/download/internal/controller_impl.cc b/components/download/internal/controller_impl.cc index 69bffa7b..2858f71 100644 --- a/components/download/internal/controller_impl.cc +++ b/components/download/internal/controller_impl.cc
@@ -15,6 +15,7 @@ #include "components/download/internal/config.h" #include "components/download/internal/entry.h" #include "components/download/internal/entry_utils.h" +#include "components/download/internal/file_monitor.h" #include "components/download/internal/model.h" #include "components/download/internal/scheduler/scheduler.h" #include "components/download/internal/stats.h" @@ -65,14 +66,18 @@ std::unique_ptr<Model> model, std::unique_ptr<DeviceStatusListener> device_status_listener, std::unique_ptr<Scheduler> scheduler, - std::unique_ptr<TaskScheduler> task_scheduler) + std::unique_ptr<TaskScheduler> task_scheduler, + std::unique_ptr<FileMonitor> file_monitor, + const base::FilePath& download_file_dir) : config_(config), + download_file_dir_(download_file_dir), clients_(std::move(clients)), driver_(std::move(driver)), model_(std::move(model)), device_status_listener_(std::move(device_status_listener)), scheduler_(std::move(scheduler)), task_scheduler_(std::move(task_scheduler)), + file_monitor_(std::move(file_monitor)), initializing_internals_(false), weak_ptr_factory_(this) {} @@ -84,6 +89,8 @@ initializing_internals_ = true; driver_->Initialize(this); model_->Initialize(this); + file_monitor_->Initialize(base::Bind(&ControllerImpl::OnFileMonitorReady, + weak_ptr_factory_.GetWeakPtr())); } const StartupStatus* ControllerImpl::GetStartupStatus() { @@ -92,6 +99,8 @@ void ControllerImpl::StartDownload(const DownloadParams& params) { DCHECK(startup_status_.Ok()); + DCHECK_LE(base::Time::Now(), params.scheduling_params.cancel_time); + KillTimedOutDownloads(); // TODO(dtrainor): Check if there are any downloads we can cancel. We don't // want to return a BACKOFF if we technically could time out a download to @@ -123,7 +132,9 @@ } start_callbacks_[params.guid] = params.callback; - model_->Add(Entry(params)); + Entry entry(params); + entry.target_file_path = download_file_dir_.AppendASCII(params.guid); + model_->Add(entry); } void ControllerImpl::PauseDownload(const std::string& guid) { @@ -235,7 +246,16 @@ while (!task_finished_callbacks_.empty()) { auto it = task_finished_callbacks_.begin(); - // TODO(shaktisahu): Execute the scheduled task. + if (it->first == DownloadTaskType::DOWNLOAD_TASK) { + ActivateMoreDownloads(); + } else if (it->first == DownloadTaskType::CLEANUP_TASK) { + auto timed_out_entries = + file_monitor_->CleanupFilesForCompletedEntries(model_->PeekEntries()); + for (auto* entry : timed_out_entries) { + DCHECK_EQ(Entry::State::COMPLETE, entry->state); + model_->Remove(entry->guid); + } + } HandleTaskFinished(it->first, false, stats::ScheduledTaskStatus::COMPLETED_NORMALLY); @@ -333,6 +353,12 @@ download.guid, download.bytes_downloaded)); } +void ControllerImpl::OnFileMonitorReady(bool success) { + DCHECK(!startup_status_.file_monitor_ok.has_value()); + startup_status_.file_monitor_ok = success; + AttemptToFinalizeSetup(); +} + void ControllerImpl::OnModelReady(bool success) { DCHECK(!startup_status_.model_ok.has_value()); startup_status_.model_ok = success; @@ -405,6 +431,7 @@ device_status_listener_->Start(this); PollActiveDriverDownloads(); CancelOrphanedRequests(); + CleanupUnknownFiles(); ResolveInitialRequestStates(); NotifyClientsOfStartup(); @@ -413,6 +440,8 @@ UpdateDriverStates(); ProcessScheduledTasks(); + KillTimedOutDownloads(); + // Pull the initial straw if active downloads haven't reach maximum. ActivateMoreDownloads(); } @@ -430,16 +459,33 @@ auto entries = model_->PeekEntries(); std::vector<std::string> guids_to_remove; + std::vector<base::FilePath> files_to_remove; for (auto* entry : entries) { - if (!clients_->GetClient(entry->client)) + if (!clients_->GetClient(entry->client)) { guids_to_remove.push_back(entry->guid); + files_to_remove.push_back(entry->target_file_path); + } } for (const auto& guid : guids_to_remove) { - // TODO(xingliu): Use file monitor to delete the files. driver_->Remove(guid); model_->Remove(guid); } + + file_monitor_->DeleteFiles(files_to_remove, + stats::FileCleanupReason::ORPHANED); +} + +void ControllerImpl::CleanupUnknownFiles() { + auto entries = model_->PeekEntries(); + std::vector<DriverEntry> driver_entries; + for (auto* entry : entries) { + base::Optional<DriverEntry> driver_entry = driver_->Find(entry->guid); + if (driver_entry.has_value()) + driver_entries.push_back(driver_entry.value()); + } + + file_monitor_->DeleteUnknownFiles(entries, driver_entries); } void ControllerImpl::ResolveInitialRequestStates() { @@ -656,23 +702,86 @@ DCHECK(driver_entry.has_value()); // TODO(dtrainor): Move the FilePath generation to the controller and store // it in Entry. Then pass it into the DownloadDriver. + entry->target_file_path = driver_entry->temporary_physical_file_path; + entry->completion_time = driver_entry->completion_time; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ControllerImpl::SendOnDownloadSucceeded, weak_ptr_factory_.GetWeakPtr(), entry->client, guid, base::FilePath(), driver_entry->bytes_downloaded)); TransitTo(entry, Entry::State::COMPLETE, model_.get()); + ScheduleCleanupTask(); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&ControllerImpl::SendOnDownloadFailed, weak_ptr_factory_.GetWeakPtr(), entry->client, guid, FailureReasonFromCompletionType(type))); + // TODO(dtrainor): Handle the case where we crash before the model write + // happens and we have no driver entry. + driver_->Remove(entry->guid); model_->Remove(guid); } ActivateMoreDownloads(); } +void ControllerImpl::ScheduleCleanupTask() { + base::Time earliest_completion_time = base::Time::Max(); + for (const Entry* entry : model_->PeekEntries()) { + if (entry->completion_time == base::Time() || + entry->state != Entry::State::COMPLETE) + continue; + if (entry->completion_time < earliest_completion_time) { + earliest_completion_time = entry->completion_time; + } + } + + if (earliest_completion_time == base::Time::Max()) + return; + + base::TimeDelta start_time = earliest_completion_time + + config_->file_keep_alive_time - + base::Time::Now(); + base::TimeDelta end_time = start_time + config_->file_cleanup_window; + + task_scheduler_->ScheduleTask(DownloadTaskType::CLEANUP_TASK, false, false, + start_time.InSeconds(), end_time.InSeconds()); +} + +void ControllerImpl::ScheduleKillDownloadTaskIfNecessary() { + base::Time earliest_cancel_time = base::Time::Max(); + for (const Entry* entry : model_->PeekEntries()) { + if (entry->state != Entry::State::COMPLETE && + entry->scheduling_params.cancel_time < earliest_cancel_time) { + earliest_cancel_time = entry->scheduling_params.cancel_time; + } + } + + if (earliest_cancel_time == base::Time::Max()) + return; + + base::TimeDelta time_to_cancel = + earliest_cancel_time > base::Time::Now() + ? earliest_cancel_time - base::Time::Now() + : base::TimeDelta(); + + cancel_downloads_callback_.Reset(base::Bind( + &ControllerImpl::KillTimedOutDownloads, weak_ptr_factory_.GetWeakPtr())); + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, cancel_downloads_callback_.callback(), time_to_cancel); +} + +void ControllerImpl::KillTimedOutDownloads() { + for (const Entry* entry : model_->PeekEntries()) { + if (entry->state != Entry::State::COMPLETE && + entry->scheduling_params.cancel_time <= base::Time::Now()) { + HandleCompleteDownload(CompletionType::TIMEOUT, entry->guid); + } + } + + ScheduleKillDownloadTaskIfNecessary(); +} + void ControllerImpl::ActivateMoreDownloads() { if (initializing_internals_) return;
diff --git a/components/download/internal/controller_impl.h b/components/download/internal/controller_impl.h index 0c20f9d..6405057 100644 --- a/components/download/internal/controller_impl.h +++ b/components/download/internal/controller_impl.h
@@ -9,6 +9,7 @@ #include <memory> #include <set> +#include "base/cancelable_callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" @@ -27,6 +28,7 @@ class ClientSet; class DownloadDriver; +class FileMonitor; class Model; class Scheduler; @@ -47,7 +49,9 @@ std::unique_ptr<Model> model, std::unique_ptr<DeviceStatusListener> device_status_listener, std::unique_ptr<Scheduler> scheduler, - std::unique_ptr<TaskScheduler> task_scheduler); + std::unique_ptr<TaskScheduler> task_scheduler, + std::unique_ptr<FileMonitor> file_monitor, + const base::FilePath& download_file_dir); ~ControllerImpl() override; // Controller implementation. @@ -85,6 +89,9 @@ DownloadClient client, const std::string& guid) override; + // Called when the file monitor and download file directory are initialized. + void OnFileMonitorReady(bool success); + // DeviceStatusListener::Observer implementation. void OnDeviceStatusChanged(const DeviceStatus& device_status) override; @@ -100,6 +107,9 @@ // Client in |clients_|. void CancelOrphanedRequests(); + // Cleans up any files that are left on the disk without any entries. + void CleanupUnknownFiles(); + // Fixes any discrepancies in state between |model_| and |driver_|. Meant to // resolve state issues during startup. void ResolveInitialRequestStates(); @@ -155,8 +165,22 @@ const std::string& guid, download::Client::FailureReason reason); + // Schedules a cleanup task in future based on status of entries. + void ScheduleCleanupTask(); + + // Posts a task to cancel the downloads in future based on the cancel_after + // time of the entries. If cancel time for an entry is already surpassed, the + // task will be posted right away which will clean the entry. + void ScheduleKillDownloadTaskIfNecessary(); + + // Kills the downloads which have surpassed their cancel_after time. + void KillTimedOutDownloads(); + Configuration* config_; + // The directory in which the downloaded files are stored. + const base::FilePath download_file_dir_; + // Owned Dependencies. std::unique_ptr<ClientSet> clients_; std::unique_ptr<DownloadDriver> driver_; @@ -164,6 +188,7 @@ std::unique_ptr<DeviceStatusListener> device_status_listener_; std::unique_ptr<Scheduler> scheduler_; std::unique_ptr<TaskScheduler> task_scheduler_; + std::unique_ptr<FileMonitor> file_monitor_; // Internal state. // Is set to true if this class is currently in the process of initializing @@ -175,6 +200,7 @@ std::set<std::string> externally_active_downloads_; std::map<std::string, DownloadParams::StartCallback> start_callbacks_; std::map<DownloadTaskType, TaskFinishedCallback> task_finished_callbacks_; + base::CancelableClosure cancel_downloads_callback_; // Only used to post tasks on the same thread. base::WeakPtrFactory<ControllerImpl> weak_ptr_factory_;
diff --git a/components/download/internal/controller_impl_unittest.cc b/components/download/internal/controller_impl_unittest.cc index 48a27877..3206db1 100644 --- a/components/download/internal/controller_impl_unittest.cc +++ b/components/download/internal/controller_impl_unittest.cc
@@ -11,13 +11,16 @@ #include "base/guid.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/strings/string_util.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/download/internal/client_set.h" #include "components/download/internal/config.h" #include "components/download/internal/entry.h" +#include "components/download/internal/file_monitor.h" #include "components/download/internal/model_impl.h" #include "components/download/internal/scheduler/scheduler.h" +#include "components/download/internal/stats.h" #include "components/download/internal/test/entry_utils.h" #include "components/download/internal/test/mock_client.h" #include "components/download/internal/test/test_device_status_listener.h" @@ -33,6 +36,9 @@ namespace { +const base::FilePath::CharType kDownloadDirPath[] = + FILE_PATH_LITERAL("/test/downloads"); + bool GuidInEntryList(const std::vector<Entry>& entries, const std::string& guid) { for (const auto& entry : entries) { @@ -49,6 +55,8 @@ return dentry; } +void NotifyTaskFinished(bool success) {} + class MockTaskScheduler : public TaskScheduler { public: MockTaskScheduler() = default; @@ -68,6 +76,25 @@ MOCK_METHOD2(Next, Entry*(const Model::EntryList&, const DeviceStatus&)); }; +class MockFileMonitor : public FileMonitor { + public: + MockFileMonitor() = default; + ~MockFileMonitor() override = default; + + void Initialize(const FileMonitor::InitCallback& callback) override; + MOCK_METHOD2(DeleteUnknownFiles, + void(const Model::EntryList&, const std::vector<DriverEntry>&)); + MOCK_METHOD1(CleanupFilesForCompletedEntries, + std::vector<Entry*>(const Model::EntryList&)); + MOCK_METHOD2(DeleteFiles, + void(const std::vector<base::FilePath>&, + stats::FileCleanupReason)); +}; + +void MockFileMonitor::Initialize(const FileMonitor::InitCallback& callback) { + callback.Run(true); +} + class DownloadServiceControllerImplTest : public testing::Test { public: DownloadServiceControllerImplTest() @@ -79,7 +106,8 @@ store_(nullptr), model_(nullptr), device_status_listener_(nullptr), - scheduler_(nullptr) { + scheduler_(nullptr), + file_monitor_(nullptr) { start_callback_ = base::Bind(&DownloadServiceControllerImplTest::StartCallback, base::Unretained(this)); @@ -92,6 +120,8 @@ auto driver = base::MakeUnique<test::TestDownloadDriver>(); auto store = base::MakeUnique<test::TestStore>(); config_ = base::MakeUnique<Configuration>(); + config_->file_keep_alive_time = base::TimeDelta::FromMinutes(10); + config_->file_cleanup_window = base::TimeDelta::FromMinutes(5); client_ = client.get(); driver_ = driver.get(); @@ -106,14 +136,20 @@ auto scheduler = base::MakeUnique<MockScheduler>(); auto task_scheduler = base::MakeUnique<MockTaskScheduler>(); + auto download_file_dir = base::FilePath(kDownloadDirPath); + auto file_monitor = base::MakeUnique<MockFileMonitor>(); + model_ = model.get(); device_status_listener_ = device_status_listener.get(); scheduler_ = scheduler.get(); + task_scheduler_ = task_scheduler.get(); + file_monitor_ = file_monitor.get(); controller_ = base::MakeUnique<ControllerImpl>( config_.get(), std::move(client_set), std::move(driver), std::move(model), std::move(device_status_listener), - std::move(scheduler), std::move(task_scheduler)); + std::move(scheduler), std::move(task_scheduler), + std::move(file_monitor), download_file_dir); } protected: @@ -139,6 +175,8 @@ ModelImpl* model_; test::TestDeviceStatusListener* device_status_listener_; MockScheduler* scheduler_; + MockTaskScheduler* task_scheduler_; + MockFileMonitor* file_monitor_; DownloadParams::StartCallback start_callback_; @@ -218,6 +256,50 @@ task_runner_->RunUntilIdle(); } +TEST_F(DownloadServiceControllerImplTest, UnknownFileDeletion) { + Entry entry1 = test::BuildBasicEntry(); + Entry entry2 = test::BuildBasicEntry(); + Entry entry3 = test::BuildBasicEntry(); + + std::vector<Entry> entries = {entry1, entry2, entry3}; + + DriverEntry dentry1 = + BuildDriverEntry(entry1, DriverEntry::State::IN_PROGRESS); + DriverEntry dentry3 = + BuildDriverEntry(entry3, DriverEntry::State::IN_PROGRESS); + std::vector<DriverEntry> dentries = {dentry1, dentry3}; + + EXPECT_CALL(*scheduler_, Next(_, _)).Times(1); + EXPECT_CALL(*scheduler_, Reschedule(_)).Times(1); + EXPECT_CALL(*file_monitor_, DeleteUnknownFiles(_, _)).Times(1); + + driver_->AddTestData(dentries); + controller_->Initialize(); + driver_->MakeReady(); + store_->TriggerInit(true, base::MakeUnique<std::vector<Entry>>(entries)); + + task_runner_->RunUntilIdle(); +} + +TEST_F(DownloadServiceControllerImplTest, + CleanupFilesForCompletedEntriesCalled) { + Entry entry1 = test::BuildBasicEntry(); + Entry entry2 = test::BuildBasicEntry(); + Entry entry3 = test::BuildBasicEntry(); + + std::vector<Entry> entries = {entry1, entry2, entry3}; + + EXPECT_CALL(*file_monitor_, CleanupFilesForCompletedEntries(_)).Times(1); + + controller_->Initialize(); + driver_->MakeReady(); + store_->TriggerInit(true, base::MakeUnique<std::vector<Entry>>(entries)); + controller_->OnStartScheduledTask(DownloadTaskType::CLEANUP_TASK, + base::Bind(&NotifyTaskFinished)); + + task_runner_->RunUntilIdle(); +} + TEST_F(DownloadServiceControllerImplTest, FailedInitWithBadModel) { EXPECT_CALL(*client_, OnServiceInitialized(_)).Times(0); @@ -270,6 +352,12 @@ // TODO(dtrainor): Compare the full DownloadParams with the full Entry. store_->TriggerUpdate(true); + std::vector<Entry> entries = store_->updated_entries(); + Entry entry = entries[0]; + DCHECK_EQ(entry.client, DownloadClient::TEST); + EXPECT_TRUE(base::StartsWith(entry.target_file_path.value(), kDownloadDirPath, + base::CompareCase::SENSITIVE)); + task_runner_->RunUntilIdle(); } @@ -590,14 +678,46 @@ DriverEntry driver_entry; driver_entry.guid = entry.guid; driver_entry.bytes_downloaded = 1024; + driver_entry.completion_time = base::Time::Now(); base::FilePath path = base::FilePath::FromUTF8Unsafe("123"); + EXPECT_CALL(*task_scheduler_, + ScheduleTask(DownloadTaskType::CLEANUP_TASK, _, _, _, _)) + .Times(1); driver_->NotifyDownloadSucceeded(driver_entry, path); EXPECT_EQ(Entry::State::COMPLETE, model_->Get(entry.guid)->state); task_runner_->RunUntilIdle(); } +TEST_F(DownloadServiceControllerImplTest, CleanupTaskScheduledAtEarliestTime) { + Entry entry1 = test::BuildBasicEntry(); + entry1.state = Entry::State::ACTIVE; + entry1.completion_time = base::Time::Now() - base::TimeDelta::FromMinutes(1); + Entry entry2 = test::BuildBasicEntry(); + entry2.state = Entry::State::COMPLETE; + entry2.completion_time = base::Time::Now() - base::TimeDelta::FromMinutes(2); + std::vector<Entry> entries = {entry1, entry2}; + + controller_->Initialize(); + store_->TriggerInit(true, base::MakeUnique<std::vector<Entry>>(entries)); + driver_->MakeReady(); + + DriverEntry driver_entry; + driver_entry.guid = entry1.guid; + driver_entry.bytes_downloaded = 1024; + driver_entry.completion_time = base::Time::Now(); + base::FilePath path = base::FilePath::FromUTF8Unsafe("123"); + + EXPECT_CALL(*task_scheduler_, ScheduleTask(DownloadTaskType::CLEANUP_TASK, + false, false, 479, 779)) + .Times(1); + driver_->NotifyDownloadSucceeded(driver_entry, path); + EXPECT_EQ(Entry::State::COMPLETE, model_->Get(entry1.guid)->state); + + task_runner_->RunUntilIdle(); +} + TEST_F(DownloadServiceControllerImplTest, OnDownloadUpdated) { Entry entry = test::BuildBasicEntry(); entry.state = Entry::State::ACTIVE; @@ -625,12 +745,13 @@ } TEST_F(DownloadServiceControllerImplTest, DownloadCompletionTest) { - // TODO(dtrainor): Simulate a TIMEOUT once that is supported. // TODO(dtrainor): Simulate a UNKNOWN once that is supported. Entry entry1 = test::BuildBasicEntry(Entry::State::ACTIVE); Entry entry2 = test::BuildBasicEntry(Entry::State::ACTIVE); Entry entry3 = test::BuildBasicEntry(Entry::State::ACTIVE); + Entry entry4 = test::BuildBasicEntry(Entry::State::ACTIVE); + entry4.scheduling_params.cancel_time = base::Time::Now(); DriverEntry dentry1 = BuildDriverEntry(entry1, DriverEntry::State::IN_PROGRESS); @@ -639,11 +760,16 @@ DriverEntry dentry3 = BuildDriverEntry(entry3, DriverEntry::State::IN_PROGRESS); - std::vector<Entry> entries = {entry1, entry2, entry3}; + std::vector<Entry> entries = {entry1, entry2, entry3, entry4}; std::vector<DriverEntry> dentries = {dentry1, dentry3}; EXPECT_CALL(*client_, OnServiceInitialized(_)).Times(1); + // Test FailureReason::TIMEDOUT. + EXPECT_CALL(*client_, + OnDownloadFailed(entry4.guid, Client::FailureReason::TIMEDOUT)) + .Times(1); + // Set up the Controller. driver_->AddTestData(dentries); controller_->Initialize(); @@ -957,4 +1083,30 @@ EXPECT_FALSE(driver_->Find(entry2.guid).value().paused); } +TEST_F(DownloadServiceControllerImplTest, CancelTimeTest) { + Entry entry1 = test::BuildBasicEntry(); + entry1.state = Entry::State::ACTIVE; + entry1.create_time = base::Time::Now() - base::TimeDelta::FromSeconds(10); + entry1.scheduling_params.cancel_time = + base::Time::Now() - base::TimeDelta::FromSeconds(5); + + Entry entry2 = test::BuildBasicEntry(); + entry2.state = Entry::State::COMPLETE; + entry2.create_time = base::Time::Now() - base::TimeDelta::FromSeconds(10); + entry2.scheduling_params.cancel_time = + base::Time::Now() - base::TimeDelta::FromSeconds(2); + std::vector<Entry> entries = {entry1, entry2}; + + EXPECT_CALL(*client_, OnServiceInitialized(_)).Times(1); + + controller_->Initialize(); + store_->TriggerInit(true, base::MakeUnique<std::vector<Entry>>(entries)); + driver_->MakeReady(); + task_runner_->RunUntilIdle(); + + // At startup, timed out entries should be killed. + std::vector<Entry*> updated_entries = model_->PeekEntries(); + EXPECT_EQ(1u, updated_entries.size()); +} + } // namespace download
diff --git a/components/download/internal/download_service_impl_unittest.cc b/components/download/internal/download_service_impl_unittest.cc index 11c14b3..0245b18 100644 --- a/components/download/internal/download_service_impl_unittest.cc +++ b/components/download/internal/download_service_impl_unittest.cc
@@ -55,6 +55,7 @@ startup_status.driver_ok = true; startup_status.model_ok = true; + startup_status.file_monitor_ok = true; EXPECT_EQ(DownloadService::ServiceStatus::READY, service_->GetStatus()); startup_status.driver_ok = false;
diff --git a/components/download/internal/driver_entry.h b/components/download/internal/driver_entry.h index 52f421b..07e2c21 100644 --- a/components/download/internal/driver_entry.h +++ b/components/download/internal/driver_entry.h
@@ -8,6 +8,7 @@ #include <string> #include <vector> +#include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "url/gurl.h" @@ -54,6 +55,15 @@ // http header is not presented. uint64_t expected_total_size; + // The physical file path for the download. It can be different from the + // target file path requested while the file is downloading, as it may + // download to a temporary path. + base::FilePath temporary_physical_file_path; + + // Time the download was marked as complete, base::Time() if the download is + // not yet complete. + base::Time completion_time; + // The response headers for the most recent download request. scoped_refptr<const net::HttpResponseHeaders> response_headers;
diff --git a/components/download/internal/entry.cc b/components/download/internal/entry.cc index 6cf6855e..aa411bdc 100644 --- a/components/download/internal/entry.cc +++ b/components/download/internal/entry.cc
@@ -18,4 +18,21 @@ Entry::~Entry() = default; +bool Entry::operator==(const Entry& other) const { + return client == other.client && guid == other.guid && + scheduling_params.cancel_time == other.scheduling_params.cancel_time && + scheduling_params.network_requirements == + other.scheduling_params.network_requirements && + scheduling_params.battery_requirements == + other.scheduling_params.battery_requirements && + scheduling_params.priority == other.scheduling_params.priority && + request_params.url == other.request_params.url && + request_params.method == other.request_params.method && + request_params.request_headers.ToString() == + other.request_params.request_headers.ToString() && + state == other.state && target_file_path == other.target_file_path && + create_time == other.create_time && + completion_time == other.completion_time; +} + } // namespace download
diff --git a/components/download/internal/entry.h b/components/download/internal/entry.h index 9f4a04ad..b376d833 100644 --- a/components/download/internal/entry.h +++ b/components/download/internal/entry.h
@@ -43,6 +43,8 @@ explicit Entry(const DownloadParams& params); ~Entry(); + bool operator==(const Entry& other) const; + // The feature that is requesting this download. DownloadClient client = DownloadClient::INVALID; @@ -62,6 +64,13 @@ // The state of the download to help the scheduler and loggers make the right // decisions about the download object. State state = State::NEW; + + // Target file path for this download. + base::FilePath target_file_path; + + // Time the download was marked as complete, base::Time() if the download is + // not yet complete. + base::Time completion_time; }; } // namespace download
diff --git a/components/download/internal/file_monitor.h b/components/download/internal/file_monitor.h new file mode 100644 index 0000000..e5179b0 --- /dev/null +++ b/components/download/internal/file_monitor.h
@@ -0,0 +1,52 @@ +// 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_DOWNLOAD_INTERNAL_FILE_MONITOR_H_ +#define COMPONENTS_DOWNLOAD_INTERNAL_FILE_MONITOR_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "components/download/internal/model.h" +#include "components/download/internal/stats.h" + +namespace base { +class FilePath; +} // namespace base + +namespace download { + +struct DriverEntry; +struct Entry; + +// An utility class containing various file cleanup methods. +class FileMonitor { + public: + using InitCallback = base::Callback<void(bool)>; + + // Creates the file directory for the downloads if it doesn't exist. + virtual void Initialize(const InitCallback& callback) = 0; + + // Deletes the files in storage directory that are not related to any entries + // in either database. + virtual void DeleteUnknownFiles( + const Model::EntryList& known_entries, + const std::vector<DriverEntry>& known_driver_entries) = 0; + + // Deletes the files for the database entries which have been completed and + // ready for cleanup. Returns the entries eligible for clean up. + virtual std::vector<Entry*> CleanupFilesForCompletedEntries( + const Model::EntryList& entries) = 0; + + // Deletes a list of files and logs UMA. + virtual void DeleteFiles(const std::vector<base::FilePath>& files_to_remove, + stats::FileCleanupReason reason) = 0; + + virtual ~FileMonitor() = default; +}; + +} // namespace download + +#endif // COMPONENTS_DOWNLOAD_INTERNAL_FILE_MONITOR_H_
diff --git a/components/download/internal/file_monitor_impl.cc b/components/download/internal/file_monitor_impl.cc new file mode 100644 index 0000000..3d706cd --- /dev/null +++ b/components/download/internal/file_monitor_impl.cc
@@ -0,0 +1,141 @@ +// 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/download/internal/file_monitor_impl.h" + +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/files/file_enumerator.h" +#include "base/files/file_util.h" +#include "base/memory/ptr_util.h" +#include "base/stl_util.h" +#include "base/task_runner_util.h" +#include "base/threading/thread_restrictions.h" + +namespace download { + +namespace { + +bool CreateDirectoryIfNotExists(const base::FilePath& dir_path) { + bool success = base::PathExists(dir_path); + if (!success) { + base::File::Error error; + success = base::CreateDirectoryAndGetError(dir_path, &error); + } + return success; +} + +} // namespace + +FileMonitorImpl::FileMonitorImpl( + const base::FilePath& download_file_dir, + const scoped_refptr<base::SequencedTaskRunner>& file_thread_task_runner, + base::TimeDelta file_keep_alive_time) + : download_file_dir_(download_file_dir), + file_keep_alive_time_(file_keep_alive_time), + file_thread_task_runner_(file_thread_task_runner), + weak_factory_(this) {} + +FileMonitorImpl::~FileMonitorImpl() = default; + +void FileMonitorImpl::Initialize(const InitCallback& callback) { + base::PostTaskAndReplyWithResult( + file_thread_task_runner_.get(), FROM_HERE, + base::Bind(&CreateDirectoryIfNotExists, download_file_dir_), callback); +} + +void FileMonitorImpl::DeleteUnknownFiles( + const Model::EntryList& known_entries, + const std::vector<DriverEntry>& known_driver_entries) { + std::set<base::FilePath> download_file_paths; + for (Entry* entry : known_entries) { + download_file_paths.insert(entry->target_file_path); + } + + for (const DriverEntry& driver_entry : known_driver_entries) { + download_file_paths.insert(driver_entry.temporary_physical_file_path); + } + + file_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&FileMonitorImpl::DeleteUnknownFilesOnFileThread, + weak_factory_.GetWeakPtr(), download_file_paths)); +} + +std::vector<Entry*> FileMonitorImpl::CleanupFilesForCompletedEntries( + const Model::EntryList& entries) { + std::vector<Entry*> entries_to_remove; + std::vector<base::FilePath> files_to_remove; + for (auto* entry : entries) { + if (!ReadyForCleanup(entry)) + continue; + + entries_to_remove.push_back(entry); + files_to_remove.push_back(entry->target_file_path); + } + + file_thread_task_runner_->PostTask( + FROM_HERE, base::Bind(&FileMonitorImpl::DeleteFilesOnFileThread, + weak_factory_.GetWeakPtr(), files_to_remove, + stats::FileCleanupReason::TIMEOUT)); + return entries_to_remove; +} + +void FileMonitorImpl::DeleteFiles( + const std::vector<base::FilePath>& files_to_remove, + stats::FileCleanupReason reason) { + file_thread_task_runner_->PostTask( + FROM_HERE, + base::Bind(&FileMonitorImpl::DeleteFilesOnFileThread, + weak_factory_.GetWeakPtr(), files_to_remove, reason)); +} + +void FileMonitorImpl::DeleteUnknownFilesOnFileThread( + const std::set<base::FilePath>& download_file_paths) { + base::ThreadRestrictions::AssertIOAllowed(); + std::set<base::FilePath> files_in_dir; + base::FileEnumerator file_enumerator( + download_file_dir_, false /* recursive */, base::FileEnumerator::FILES); + + for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); + path = file_enumerator.Next()) { + files_in_dir.insert(path); + } + + std::vector<base::FilePath> files_to_remove = + base::STLSetDifference<std::vector<base::FilePath>>(files_in_dir, + download_file_paths); + DeleteFilesOnFileThread(files_to_remove, stats::FileCleanupReason::UNKNOWN); +} + +void FileMonitorImpl::DeleteFilesOnFileThread( + const std::vector<base::FilePath>& paths, + stats::FileCleanupReason reason) { + base::ThreadRestrictions::AssertIOAllowed(); + int num_delete_attempted = 0; + int num_delete_failed = 0; + int num_delete_by_external = 0; + for (const base::FilePath& path : paths) { + if (!base::PathExists(path)) { + num_delete_by_external++; + continue; + } + + num_delete_attempted++; + DCHECK(!base::DirectoryExists(path)); + + if (!base::DeleteFile(path, false /* recursive */)) { + num_delete_failed++; + } + } + + stats::LogFileCleanupStatus(reason, num_delete_attempted, num_delete_failed, + num_delete_by_external); +} + +bool FileMonitorImpl::ReadyForCleanup(const Entry* entry) { + return entry->state == Entry::State::COMPLETE && + (base::Time::Now() - entry->completion_time) > file_keep_alive_time_; +} + +} // namespace download
diff --git a/components/download/internal/file_monitor_impl.h b/components/download/internal/file_monitor_impl.h new file mode 100644 index 0000000..2baa359 --- /dev/null +++ b/components/download/internal/file_monitor_impl.h
@@ -0,0 +1,64 @@ +// 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_DOWNLOAD_INTERNAL_FILE_MONITOR_IMPL_H_ +#define COMPONENTS_DOWNLOAD_INTERNAL_FILE_MONITOR_IMPL_H_ + +#include "components/download/internal/file_monitor.h" + +#include <memory> +#include <set> +#include <string> +#include <vector> + +#include "base/files/file_path.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "components/download/internal/driver_entry.h" +#include "components/download/internal/model.h" +#include "components/download/internal/stats.h" + +namespace download { + +struct Entry; + +// An utility class containing various file cleanup methods. +class FileMonitorImpl : public FileMonitor { + public: + FileMonitorImpl( + const base::FilePath& download_file_dir, + const scoped_refptr<base::SequencedTaskRunner>& file_thread_task_runner, + base::TimeDelta file_keep_alive_time); + ~FileMonitorImpl() override; + + void Initialize(const InitCallback& callback) override; + void DeleteUnknownFiles( + const Model::EntryList& known_entries, + const std::vector<DriverEntry>& known_driver_entries) override; + std::vector<Entry*> CleanupFilesForCompletedEntries( + const Model::EntryList& entries) override; + void DeleteFiles(const std::vector<base::FilePath>& files_to_remove, + stats::FileCleanupReason reason) override; + + private: + void DeleteUnknownFilesOnFileThread( + const std::set<base::FilePath>& paths_in_db); + void DeleteFilesOnFileThread(const std::vector<base::FilePath>& paths, + stats::FileCleanupReason reason); + bool ReadyForCleanup(const Entry* entry); + + const base::FilePath download_file_dir_; + const base::TimeDelta file_keep_alive_time_; + + scoped_refptr<base::SequencedTaskRunner> file_thread_task_runner_; + base::WeakPtrFactory<FileMonitorImpl> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(FileMonitorImpl); +}; + +} // namespace download + +#endif // COMPONENTS_DOWNLOAD_INTERNAL_FILE_MONITOR_IMPL_H_
diff --git a/components/download/internal/file_monitor_unittest.cc b/components/download/internal/file_monitor_unittest.cc new file mode 100644 index 0000000..268a4284 --- /dev/null +++ b/components/download/internal/file_monitor_unittest.cc
@@ -0,0 +1,141 @@ +// 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 <algorithm> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/guid.h" +#include "base/memory/ptr_util.h" +#include "base/test/test_simple_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" +#include "components/download/internal/driver_entry.h" +#include "components/download/internal/entry.h" +#include "components/download/internal/file_monitor_impl.h" +#include "components/download/internal/test/entry_utils.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::_; + +namespace download { + +class FileMonitorTest : public testing::Test { + public: + FileMonitorTest() + : task_runner_(new base::TestSimpleTaskRunner), handle_(task_runner_) { + EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); + download_dir_ = scoped_temp_dir_.GetPath(); + base::TimeDelta keep_alive_time = base::TimeDelta::FromHours(12); + monitor_ = base::MakeUnique<FileMonitorImpl>(download_dir_, task_runner_, + keep_alive_time); + } + ~FileMonitorTest() override = default; + + protected: + base::FilePath CreateTemporaryFile(std::string file_name); + + base::ScopedTempDir scoped_temp_dir_; + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + base::ThreadTaskRunnerHandle handle_; + base::FilePath download_dir_; + std::unique_ptr<FileMonitor> monitor_; + + private: + DISALLOW_COPY_AND_ASSIGN(FileMonitorTest); +}; + +base::FilePath FileMonitorTest::CreateTemporaryFile(std::string file_name) { + base::FilePath file_path = download_dir_.AppendASCII(file_name); + base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE); + EXPECT_TRUE(file.IsValid()); + file.Close(); + + return file_path; +} + +TEST_F(FileMonitorTest, TestDeleteUnknownFiles) { + Entry entry1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID()); + entry1.target_file_path = CreateTemporaryFile(entry1.guid); + + Entry entry2 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID()); + entry2.target_file_path = CreateTemporaryFile(entry2.guid); + + DriverEntry driver_entry1; + driver_entry1.guid = entry1.guid; + driver_entry1.temporary_physical_file_path = entry1.target_file_path; + + DriverEntry driver_entry2; + driver_entry2.guid = base::GenerateGUID(); + driver_entry2.temporary_physical_file_path = + CreateTemporaryFile(driver_entry2.guid); + + base::FilePath temp_file1 = CreateTemporaryFile("temp1"); + base::FilePath temp_file2 = CreateTemporaryFile("temp2"); + + auto check_file_existence = [&](bool e1, bool e2, bool de1, bool de2, bool t1, + bool t2) { + EXPECT_EQ(e1, base::PathExists(entry1.target_file_path)); + EXPECT_EQ(e2, base::PathExists(entry2.target_file_path)); + EXPECT_EQ(de1, + base::PathExists(driver_entry1.temporary_physical_file_path)); + EXPECT_EQ(de2, + base::PathExists(driver_entry2.temporary_physical_file_path)); + EXPECT_EQ(t1, base::PathExists(temp_file1)); + EXPECT_EQ(t2, base::PathExists(temp_file2)); + }; + + check_file_existence(true, true, true, true, true, true); + + std::vector<Entry*> entries = {&entry1, &entry2}; + std::vector<DriverEntry> driver_entries = {driver_entry1, driver_entry2}; + + monitor_->DeleteUnknownFiles(entries, driver_entries); + task_runner_->RunUntilIdle(); + check_file_existence(true, true, true, true, false, false); + + entries = {&entry2}; + driver_entries = {driver_entry1, driver_entry2}; + monitor_->DeleteUnknownFiles(entries, driver_entries); + task_runner_->RunUntilIdle(); + check_file_existence(true, true, true, true, false, false); + + entries = {&entry2}; + driver_entries = {driver_entry2}; + monitor_->DeleteUnknownFiles(entries, driver_entries); + task_runner_->RunUntilIdle(); + check_file_existence(false, true, false, true, false, false); + + entries.clear(); + driver_entries.clear(); + monitor_->DeleteUnknownFiles(entries, driver_entries); + task_runner_->RunUntilIdle(); + check_file_existence(false, false, false, false, false, false); +} + +TEST_F(FileMonitorTest, TestCleanupFilesForCompletedEntries) { + Entry entry1 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID()); + entry1.state = Entry::State::COMPLETE; + entry1.completion_time = base::Time::Now() - base::TimeDelta::FromHours(20); + EXPECT_TRUE( + base::CreateTemporaryFileInDir(download_dir_, &entry1.target_file_path)); + + Entry entry2 = test::BuildEntry(DownloadClient::TEST, base::GenerateGUID()); + entry2.state = Entry::State::ACTIVE; + EXPECT_TRUE( + base::CreateTemporaryFileInDir(download_dir_, &entry2.target_file_path)); + + std::vector<Entry*> entries = {&entry1, &entry2}; + std::vector<Entry*> entries_to_remove = + monitor_->CleanupFilesForCompletedEntries(entries); + task_runner_->RunUntilIdle(); + + EXPECT_EQ(1u, entries_to_remove.size()); + EXPECT_FALSE(base::PathExists(entry1.target_file_path)); + EXPECT_TRUE(base::PathExists(entry2.target_file_path)); +} + +} // namespace download
diff --git a/components/download/internal/proto/entry.proto b/components/download/internal/proto/entry.proto index 56e1f3a1..0a5bf7d8 100644 --- a/components/download/internal/proto/entry.proto +++ b/components/download/internal/proto/entry.proto
@@ -45,7 +45,9 @@ // Internal Tracking States. optional State state = 5; + optional string target_file_path = 6; - // Creation time of the entry, measured in milliseconds. - optional int64 create_time = 6; + // Uses internal time representation. + optional int64 create_time = 7; + optional int64 completion_time = 8; }
diff --git a/components/download/internal/proto_conversions.cc b/components/download/internal/proto_conversions.cc index 737920c..0e2c356 100644 --- a/components/download/internal/proto_conversions.cc +++ b/components/download/internal/proto_conversions.cc
@@ -248,7 +248,12 @@ SchedulingParamsFromProto(proto.scheduling_params()); entry.request_params = RequestParamsFromProto(proto.request_params()); entry.state = RequestStateFromProto(proto.state()); + entry.target_file_path = + base::FilePath::FromUTF8Unsafe(proto.target_file_path()); entry.create_time = base::Time::FromInternalValue(proto.create_time()); + entry.completion_time = + base::Time::FromInternalValue(proto.completion_time()); + return entry; } @@ -261,7 +266,9 @@ proto.mutable_scheduling_params()); RequestParamsToProto(entry.request_params, proto.mutable_request_params()); proto.set_state(RequestStateToProto(entry.state)); + proto.set_target_file_path(entry.target_file_path.AsUTF8Unsafe()); proto.set_create_time(entry.create_time.ToInternalValue()); + proto.set_completion_time(entry.completion_time.ToInternalValue()); return proto; }
diff --git a/components/download/internal/proto_conversions_unittest.cc b/components/download/internal/proto_conversions_unittest.cc index 3d1605d..cf0fb29f 100644 --- a/components/download/internal/proto_conversions_unittest.cc +++ b/components/download/internal/proto_conversions_unittest.cc
@@ -125,7 +125,8 @@ SchedulingParams::NetworkRequirements::OPTIMISTIC, SchedulingParams::BatteryRequirements::BATTERY_SENSITIVE, SchedulingParams::Priority::HIGH, GURL(TEST_URL), "GET", - Entry::State::ACTIVE); + Entry::State::ACTIVE, base::FilePath(FILE_PATH_LITERAL("/test/xyz")), + base::Time::Now(), base::Time::Now()); actual = EntryFromProto(EntryToProto(expected)); EXPECT_TRUE(test::CompareEntry(&expected, &actual)); } @@ -141,7 +142,8 @@ SchedulingParams::NetworkRequirements::OPTIMISTIC, SchedulingParams::BatteryRequirements::BATTERY_SENSITIVE, SchedulingParams::Priority::HIGH, GURL(TEST_URL), "GET", - Entry::State::ACTIVE)); + Entry::State::ACTIVE, base::FilePath(FILE_PATH_LITERAL("/test/xyz")), + base::Time::Now(), base::Time::Now())); auto actual = EntryVectorFromProto( EntryVectorToProto(base::MakeUnique<std::vector<Entry>>(expected)));
diff --git a/components/download/internal/startup_status.cc b/components/download/internal/startup_status.cc index 5531dd6..6560cec 100644 --- a/components/download/internal/startup_status.cc +++ b/components/download/internal/startup_status.cc
@@ -10,12 +10,13 @@ StartupStatus::~StartupStatus() = default; bool StartupStatus::Complete() const { - return driver_ok.has_value() && model_ok.has_value(); + return driver_ok.has_value() && model_ok.has_value() && + file_monitor_ok.has_value(); } bool StartupStatus::Ok() const { DCHECK(Complete()); - return driver_ok.value() && model_ok.value(); + return driver_ok.value() && model_ok.value() && file_monitor_ok.value(); } } // namespace download
diff --git a/components/download/internal/startup_status.h b/components/download/internal/startup_status.h index 3e21edf..c9c0676 100644 --- a/components/download/internal/startup_status.h +++ b/components/download/internal/startup_status.h
@@ -18,6 +18,7 @@ base::Optional<bool> driver_ok; base::Optional<bool> model_ok; + base::Optional<bool> file_monitor_ok; // Whether or not all components have finished initialization. Note that this // does not mean that all components were initialized successfully.
diff --git a/components/download/internal/stats.cc b/components/download/internal/stats.cc index b581c4d4..f0448eb4 100644 --- a/components/download/internal/stats.cc +++ b/components/download/internal/stats.cc
@@ -42,5 +42,17 @@ // TODO(dtrainor): Log |to_state|. } +void LogFileCleanupStatus(FileCleanupReason reason, + int attempted_cleanups, + int failed_cleanups, + int external_cleanups) { + DCHECK_NE(FileCleanupReason::EXTERNAL, reason); + // TODO(shaktisahu): Log |status| and |count|. +} + +void LogFileDeletionFailed(int count) { + // TODO(shaktisahu): Log |count|. +} + } // namespace stats } // namespace download
diff --git a/components/download/internal/stats.h b/components/download/internal/stats.h index 9997592..db3d40b 100644 --- a/components/download/internal/stats.h +++ b/components/download/internal/stats.h
@@ -75,6 +75,26 @@ COMPLETED_NORMALLY = 2, }; +// Enum used by UMA metrics to track various types of cleanup actions taken by +// the service. +enum class FileCleanupReason { + // The file was deleted by the service after timeout. + TIMEOUT = 0, + + // The database entry for the file was found not associated with any + // registered client. + ORPHANED = 1, + + // At startup, the file was found not being associated with any model entry or + // driver entry. + UNKNOWN = 2, + + // The file was cleaned up externally. Shouldn't be used by callers to log as + // it will be used only internally by the Stats class. + EXTERNAL = 3, + +}; + // Logs the results of starting up the Controller. Will log each failure reason // if |status| contains more than one initialization failure. void LogControllerStartupStatus(const StartupStatus& status); @@ -101,6 +121,12 @@ // to another on startup. void LogRecoveryOperation(Entry::State to_state); +// Logs statistics about the reasons of a file cleanup. +void LogFileCleanupStatus(FileCleanupReason reason, + int attempted_cleanups, + int failed_cleanups, + int external_cleanups); + } // namespace stats } // namespace download
diff --git a/components/download/internal/test/entry_utils.cc b/components/download/internal/test/entry_utils.cc index 9ed50ca..75d2d00 100644 --- a/components/download/internal/test/entry_utils.cc +++ b/components/download/internal/test/entry_utils.cc
@@ -14,21 +14,7 @@ if (expected == nullptr || actual == nullptr) return expected == actual; - // TODO(shaktisahu): Add operator== in Entry. - return expected->client == actual->client && expected->guid == actual->guid && - expected->scheduling_params.cancel_time == - actual->scheduling_params.cancel_time && - expected->scheduling_params.network_requirements == - actual->scheduling_params.network_requirements && - expected->scheduling_params.battery_requirements == - actual->scheduling_params.battery_requirements && - expected->scheduling_params.priority == - actual->scheduling_params.priority && - expected->request_params.url == actual->request_params.url && - expected->request_params.method == actual->request_params.method && - expected->request_params.request_headers.ToString() == - actual->request_params.request_headers.ToString() && - expected->state == actual->state; + return *expected == *actual; } bool CompareEntryList(const std::vector<Entry*>& expected, @@ -37,14 +23,9 @@ CompareEntry); } -bool EntryComparison(const Entry& expected, const Entry& actual) { - return CompareEntry(&expected, &actual); -} - bool CompareEntryList(const std::vector<Entry>& list1, const std::vector<Entry>& list2) { - return std::is_permutation(list1.begin(), list1.end(), list2.begin(), - EntryComparison); + return std::is_permutation(list1.begin(), list1.end(), list2.begin()); } Entry BuildBasicEntry() { @@ -72,7 +53,10 @@ SchedulingParams::Priority priority, const GURL& url, const std::string& request_method, - Entry::State state) { + Entry::State state, + const base::FilePath& target_file_path, + base::Time create_time, + base::Time completion_time) { Entry entry = BuildEntry(client, guid); entry.scheduling_params.cancel_time = cancel_time; entry.scheduling_params.network_requirements = network_requirements; @@ -81,6 +65,9 @@ entry.request_params.url = url; entry.request_params.method = request_method; entry.state = state; + entry.target_file_path = target_file_path; + entry.create_time = create_time; + entry.completion_time = completion_time; return entry; }
diff --git a/components/download/internal/test/entry_utils.h b/components/download/internal/test/entry_utils.h index 7ea94b8..404ca730 100644 --- a/components/download/internal/test/entry_utils.h +++ b/components/download/internal/test/entry_utils.h
@@ -35,7 +35,10 @@ SchedulingParams::Priority priority, const GURL& url, const std::string& request_method, - Entry::State state); + Entry::State state, + const base::FilePath& file_path, + base::Time create_time, + base::Time completion_time); } // namespace test } // namespace download
diff --git a/components/download/public/download_params.cc b/components/download/public/download_params.cc index 8d94dcf..2c3f1065 100644 --- a/components/download/public/download_params.cc +++ b/components/download/public/download_params.cc
@@ -9,7 +9,8 @@ namespace download { SchedulingParams::SchedulingParams() - : priority(Priority::DEFAULT), + : cancel_time(base::Time::Max()), + priority(Priority::DEFAULT), network_requirements(NetworkRequirements::NONE), battery_requirements(BatteryRequirements::BATTERY_INSENSITIVE) {}
diff --git a/components/download/public/download_params.h b/components/download/public/download_params.h index 7f54fca..96245ba0 100644 --- a/components/download/public/download_params.h +++ b/components/download/public/download_params.h
@@ -70,6 +70,7 @@ bool operator==(const SchedulingParams& rhs) const; // Cancel the download after this time. Will cancel in-progress downloads. + // base::Time::Max() if not specified. base::Time cancel_time; // The suggested priority. Non-UI priorities may not be honored by the
diff --git a/components/drive/chromeos/change_list_loader.cc b/components/drive/chromeos/change_list_loader.cc index a632c46..1229dda 100644 --- a/components/drive/chromeos/change_list_loader.cc +++ b/components/drive/chromeos/change_list_loader.cc
@@ -94,6 +94,9 @@ // Remember the time stamp for usage stats. start_time_ = base::TimeTicks::Now(); // This is full resource list fetch. + // + // NOTE: Because we already know the largest change ID, here we can use + // files.list instead of changes.list for speed. crbug.com/287602 scheduler_->GetAllFileList( base::Bind(&FullFeedFetcher::OnFileListFetched, weak_ptr_factory_.GetWeakPtr(), callback));
diff --git a/components/exo/buffer.cc b/components/exo/buffer.cc index 56bdd0ee..5e6b918 100644 --- a/components/exo/buffer.cc +++ b/components/exo/buffer.cc
@@ -46,6 +46,7 @@ GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, // DXT5 GL_ETC1_RGB8_OES, // ETC1 GL_R8_EXT, // R_8 + GL_R16_EXT, // R_16 GL_RG8_EXT, // RG_88 GL_RGB, // BGR_565 GL_RGBA, // RGBA_4444
diff --git a/components/nacl/renderer/ppb_nacl_private_impl.cc b/components/nacl/renderer/ppb_nacl_private_impl.cc index 9b4e72c..f6b2f94 100644 --- a/components/nacl/renderer/ppb_nacl_private_impl.cc +++ b/components/nacl/renderer/ppb_nacl_private_impl.cc
@@ -327,10 +327,12 @@ // Options settings here follow the original behavior in the trusted // plugin and PepperURLLoaderHost. if (document.GetSecurityOrigin().CanRequest(gurl)) { - options.allow_credentials = true; + options.fetch_credentials_mode = + blink::WebURLRequest::kFetchCredentialsModeSameOrigin; } else { options.fetch_request_mode = blink::WebURLRequest::kFetchRequestModeCORS; } + return document.GetFrame()->CreateAssociatedURLLoader(options); }
diff --git a/components/neterror/resources/neterror.html b/components/neterror/resources/neterror.html index 9797a377..615d1716 100644 --- a/components/neterror/resources/neterror.html +++ b/components/neterror/resources/neterror.html
@@ -5,10 +5,11 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>$i18n{title}</title> - <link rel="stylesheet" href="../../../components/security_interstitials/core/browser/resources/interstitial_common.css"> - <link rel="stylesheet" href="../../../components/security_interstitials/core/browser/resources/interstitial_large.css"> + <link rel="stylesheet" href="../../../components/security_interstitials/core/common/resources/interstitial_core.css"> + <link rel="stylesheet" href="../../../components/security_interstitials/core/common/resources/interstitial_common.css"> <link rel="stylesheet" href="neterror.css"> - <script src="../../../components/security_interstitials/core/browser/resources/interstitial_mobile_nav.js"></script> + <script src="../../../components/security_interstitials/core/common/resources/interstitial_common.js"></script> + <script src="../../../components/security_interstitials/core/common/resources/interstitial_mobile_nav.js"></script> <script src="neterror.js"></script> <script src="offline.js"></script> </head>
diff --git a/components/neterror/resources/neterror.js b/components/neterror/resources/neterror.js index 1617509..a7bc9348 100644 --- a/components/neterror/resources/neterror.js +++ b/components/neterror/resources/neterror.js
@@ -4,19 +4,19 @@ function toggleHelpBox() { var helpBoxOuter = document.getElementById('details'); - helpBoxOuter.classList.toggle('hidden'); + helpBoxOuter.classList.toggle(HIDDEN_CLASS); var detailsButton = document.getElementById('details-button'); - if (helpBoxOuter.classList.contains('hidden')) + if (helpBoxOuter.classList.contains(HIDDEN_CLASS)) detailsButton.innerText = detailsButton.detailsText; else detailsButton.innerText = detailsButton.hideDetailsText; // Details appears over the main content on small screens. if (mobileNav) { - document.getElementById('main-content').classList.toggle('hidden'); + document.getElementById('main-content').classList.toggle(HIDDEN_CLASS); var runnerContainer = document.querySelector('.runner-container'); if (runnerContainer) { - runnerContainer.classList.toggle('hidden'); + runnerContainer.classList.toggle(HIDDEN_CLASS); } } }
diff --git a/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.cc b/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.cc index 43ac077a..305f650 100644 --- a/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.cc +++ b/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.cc
@@ -18,13 +18,22 @@ BreakingNewsSuggestionsProvider::BreakingNewsSuggestionsProvider( ContentSuggestionsProvider::Observer* observer, std::unique_ptr<ContentSuggestionsGCMAppHandler> gcm_app_handler, - std::unique_ptr<base::Clock> clock) + std::unique_ptr<base::Clock> clock, + std::unique_ptr<RemoteSuggestionsDatabase> database) : ContentSuggestionsProvider(observer), gcm_app_handler_(std::move(gcm_app_handler)), clock_(std::move(clock)), + database_(std::move(database)), provided_category_( Category::FromKnownCategory(KnownCategories::BREAKING_NEWS)), - category_status_(CategoryStatus::INITIALIZING) {} + category_status_(CategoryStatus::INITIALIZING) { + database_->SetErrorCallback( + base::Bind(&BreakingNewsSuggestionsProvider::OnDatabaseError, + base::Unretained(this))); + database_->LoadSnippets( + base::Bind(&BreakingNewsSuggestionsProvider::OnDatabaseLoaded, + base::Unretained(this))); +} BreakingNewsSuggestionsProvider::~BreakingNewsSuggestionsProvider() { gcm_app_handler_->StopListening(); @@ -48,18 +57,18 @@ LOG(WARNING) << "Received invalid breaking news: " << content_json; return; } - DCHECK_EQ(categories.size(), (size_t)1); + DCHECK_EQ(categories.size(), static_cast<size_t>(1)); auto& fetched_category = categories[0]; Category category = fetched_category.category; DCHECK(category.IsKnownCategory(KnownCategories::BREAKING_NEWS)); - - std::vector<ContentSuggestion> suggestions; - for (const std::unique_ptr<RemoteSuggestion>& suggestion : - fetched_category.suggestions) { - suggestions.emplace_back(suggestion->ToContentSuggestion(category)); + if (database_->IsInitialized()) { + database_->SaveSnippets(fetched_category.suggestions); + } else { + // TODO(mamir): Check how often a breaking news is received before DB is + // initialized. + LOG(WARNING) << "Cannot store breaking news, database is not initialized."; } - - observer()->OnNewSuggestions(this, category, std::move(suggestions)); + NotifyNewSuggestions(std::move(fetched_category.suggestions)); } //////////////////////////////////////////////////////////////////////////////// @@ -123,4 +132,26 @@ // TODO(mamir): implement. } +void BreakingNewsSuggestionsProvider::OnDatabaseLoaded( + std::vector<std::unique_ptr<RemoteSuggestion>> suggestions) { + // TODO(mamir): check and update DB status. + NotifyNewSuggestions(std::move(suggestions)); +} + +void BreakingNewsSuggestionsProvider::OnDatabaseError() { + // TODO(mamir): implement. +} + +void BreakingNewsSuggestionsProvider::NotifyNewSuggestions( + std::vector<std::unique_ptr<RemoteSuggestion>> suggestions) { + std::vector<ContentSuggestion> result; + for (const std::unique_ptr<RemoteSuggestion>& suggestion : suggestions) { + result.emplace_back(suggestion->ToContentSuggestion(provided_category_)); + } + + DVLOG(1) << "NotifyNewSuggestions(): " << result.size() + << " items in category " << provided_category_; + observer()->OnNewSuggestions(this, provided_category_, std::move(result)); +} + } // namespace ntp_snippets
diff --git a/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.h b/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.h index d3eea2b3..0db1f78 100644 --- a/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.h +++ b/components/ntp_snippets/breaking_news/breaking_news_suggestions_provider.h
@@ -7,6 +7,7 @@ #include "components/ntp_snippets/category.h" #include "components/ntp_snippets/content_suggestions_provider.h" +#include "components/ntp_snippets/remote/remote_suggestions_database.h" #include "components/prefs/pref_registry_simple.h" namespace ntp_snippets { @@ -26,7 +27,8 @@ BreakingNewsSuggestionsProvider( ContentSuggestionsProvider::Observer* observer, std::unique_ptr<ContentSuggestionsGCMAppHandler> gcm_app_handler, - std::unique_ptr<base::Clock> clock); + std::unique_ptr<base::Clock> clock, + std::unique_ptr<RemoteSuggestionsDatabase> database); ~BreakingNewsSuggestionsProvider() override; // Starts the underlying GCM handler and registers the callback when GCM @@ -57,8 +59,20 @@ // the server. void OnNewContentSuggestion(std::unique_ptr<base::Value> content); + // Callbacks for the RemoteSuggestionsDatabase. + void OnDatabaseLoaded( + std::vector<std::unique_ptr<RemoteSuggestion>> suggestions); + void OnDatabaseError(); + + void NotifyNewSuggestions( + std::vector<std::unique_ptr<RemoteSuggestion>> suggestions); + std::unique_ptr<ContentSuggestionsGCMAppHandler> gcm_app_handler_; std::unique_ptr<base::Clock> clock_; + + // The database for persisting suggestions. + std::unique_ptr<RemoteSuggestionsDatabase> database_; + const Category provided_category_; CategoryStatus category_status_;
diff --git a/components/ntp_snippets/breaking_news/content_suggestions_gcm_app_handler.cc b/components/ntp_snippets/breaking_news/content_suggestions_gcm_app_handler.cc index 60ea6fa5..17009fa 100644 --- a/components/ntp_snippets/breaking_news/content_suggestions_gcm_app_handler.cc +++ b/components/ntp_snippets/breaking_news/content_suggestions_gcm_app_handler.cc
@@ -19,6 +19,7 @@ // The sender ID is used in the registration process. // See: https://developers.google.com/cloud-messaging/gcm#senderid +// TODO(mamir): use proper sender Id. const char kContentSuggestionsGCMSenderId[] = "128223710667"; // OAuth2 Scope passed to getToken to obtain GCM registration tokens.
diff --git a/components/ntp_snippets/ntp_snippets_constants.cc b/components/ntp_snippets/ntp_snippets_constants.cc index f65bce4..6fd0a20 100644 --- a/components/ntp_snippets/ntp_snippets_constants.cc +++ b/components/ntp_snippets/ntp_snippets_constants.cc
@@ -9,6 +9,9 @@ const base::FilePath::CharType kDatabaseFolder[] = FILE_PATH_LITERAL("NTPSnippets"); +const base::FilePath::CharType kBreakingNewsDatabaseFolder[] = + FILE_PATH_LITERAL("NTPBreakingNews"); + const char kContentSuggestionsServer[] = "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/fetch"; const char kContentSuggestionsStagingServer[] =
diff --git a/components/ntp_snippets/ntp_snippets_constants.h b/components/ntp_snippets/ntp_snippets_constants.h index 301ee44..1ce410c8 100644 --- a/components/ntp_snippets/ntp_snippets_constants.h +++ b/components/ntp_snippets/ntp_snippets_constants.h
@@ -13,6 +13,8 @@ // the name of the folder, not a full path - it must be appended to e.g. the // profile path. extern const base::FilePath::CharType kDatabaseFolder[]; +// TODO(mamir): Check if the same DB can be used. +extern const base::FilePath::CharType kBreakingNewsDatabaseFolder[]; // Server endpoints for fetching snippets. extern const char kContentSuggestionsServer[]; // used on stable/beta
diff --git a/components/password_manager/content/browser/credential_manager_impl.cc b/components/password_manager/content/browser/credential_manager_impl.cc index 608ccbb..d78025d 100644 --- a/components/password_manager/content/browser/credential_manager_impl.cc +++ b/components/password_manager/content/browser/credential_manager_impl.cc
@@ -14,7 +14,7 @@ #include "components/autofill/core/common/password_form.h" #include "components/password_manager/content/browser/content_password_manager_driver.h" #include "components/password_manager/content/browser/content_password_manager_driver_factory.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include "components/password_manager/core/browser/credential_manager_logger.h" #include "components/password_manager/core/browser/form_fetcher_impl.h" #include "components/password_manager/core/browser/form_saver.h"
diff --git a/components/password_manager/content/browser/credential_manager_impl_unittest.cc b/components/password_manager/content/browser/credential_manager_impl_unittest.cc index 0e7a132f..5c75ddd44 100644 --- a/components/password_manager/content/browser/credential_manager_impl_unittest.cc +++ b/components/password_manager/content/browser/credential_manager_impl_unittest.cc
@@ -22,8 +22,8 @@ #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h" #include "components/password_manager/core/browser/credential_manager_password_form_manager.h" -#include "components/password_manager/core/browser/mock_affiliated_match_helper.h" #include "components/password_manager/core/browser/password_manager.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h"
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index ac47b07b..9dbc03db 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -13,22 +13,26 @@ static_library("browser") { sources = [ - "affiliated_match_helper.cc", - "affiliated_match_helper.h", - "affiliation_backend.cc", - "affiliation_backend.h", - "affiliation_database.cc", - "affiliation_database.h", - "affiliation_fetch_throttler.cc", - "affiliation_fetch_throttler.h", - "affiliation_fetch_throttler_delegate.h", - "affiliation_fetcher.cc", - "affiliation_fetcher.h", - "affiliation_fetcher_delegate.h", - "affiliation_service.cc", - "affiliation_service.h", - "affiliation_utils.cc", - "affiliation_utils.h", + "android_affiliation/affiliated_match_helper.cc", + "android_affiliation/affiliated_match_helper.h", + "android_affiliation/affiliation_backend.cc", + "android_affiliation/affiliation_backend.h", + "android_affiliation/affiliation_database.cc", + "android_affiliation/affiliation_database.h", + "android_affiliation/affiliation_fetch_throttler.cc", + "android_affiliation/affiliation_fetch_throttler.h", + "android_affiliation/affiliation_fetch_throttler_delegate.h", + "android_affiliation/affiliation_fetcher.cc", + "android_affiliation/affiliation_fetcher.h", + "android_affiliation/affiliation_fetcher_delegate.h", + "android_affiliation/affiliation_service.cc", + "android_affiliation/affiliation_service.h", + "android_affiliation/affiliation_utils.cc", + "android_affiliation/affiliation_utils.h", + "android_affiliation/facet_manager.cc", + "android_affiliation/facet_manager.h", + "android_affiliation/facet_manager_host.h", + "android_affiliation/test_affiliation_fetcher_factory.h", "browser_save_password_progress_logger.cc", "browser_save_password_progress_logger.h", "credential_manager_logger.cc", @@ -46,9 +50,6 @@ "export/password_csv_writer.h", "export/password_exporter.cc", "export/password_exporter.h", - "facet_manager.cc", - "facet_manager.h", - "facet_manager_host.h", "form_fetcher.h", "form_fetcher_impl.cc", "form_fetcher_impl.h", @@ -127,7 +128,6 @@ "statistics_table.h", "suppressed_form_fetcher.cc", "suppressed_form_fetcher.h", - "test_affiliation_fetcher_factory.h", "webdata/logins_table.cc", "webdata/logins_table.h", "webdata/logins_table_win.cc", @@ -200,23 +200,23 @@ proto_library("proto") { sources = [ - "affiliation_api.proto", + "android_affiliation/affiliation_api.proto", ] } static_library("test_support") { testonly = true sources = [ - "fake_affiliation_api.cc", - "fake_affiliation_api.h", - "fake_affiliation_fetcher.cc", - "fake_affiliation_fetcher.h", + "android_affiliation/fake_affiliation_api.cc", + "android_affiliation/fake_affiliation_api.h", + "android_affiliation/fake_affiliation_fetcher.cc", + "android_affiliation/fake_affiliation_fetcher.h", + "android_affiliation/mock_affiliated_match_helper.cc", + "android_affiliation/mock_affiliated_match_helper.h", + "android_affiliation/mock_affiliation_consumer.cc", + "android_affiliation/mock_affiliation_consumer.h", "fake_form_fetcher.cc", "fake_form_fetcher.h", - "mock_affiliated_match_helper.cc", - "mock_affiliated_match_helper.h", - "mock_affiliation_consumer.cc", - "mock_affiliation_consumer.h", "mock_password_store.cc", "mock_password_store.h", "password_manager_test_utils.cc", @@ -284,20 +284,20 @@ source_set("unit_tests") { testonly = true sources = [ - "affiliated_match_helper_unittest.cc", - "affiliation_backend_unittest.cc", - "affiliation_database_unittest.cc", - "affiliation_fetch_throttler_unittest.cc", - "affiliation_fetcher_unittest.cc", - "affiliation_service_unittest.cc", - "affiliation_utils_unittest.cc", + "android_affiliation/affiliated_match_helper_unittest.cc", + "android_affiliation/affiliation_backend_unittest.cc", + "android_affiliation/affiliation_database_unittest.cc", + "android_affiliation/affiliation_fetch_throttler_unittest.cc", + "android_affiliation/affiliation_fetcher_unittest.cc", + "android_affiliation/affiliation_service_unittest.cc", + "android_affiliation/affiliation_utils_unittest.cc", + "android_affiliation/facet_manager_unittest.cc", "browser_save_password_progress_logger_unittest.cc", "credential_manager_logger_unittest.cc", "credential_manager_password_form_manager_unittest.cc", "export/csv_writer_unittest.cc", "export/password_csv_writer_unittest.cc", "export/password_exporter_unittest.cc", - "facet_manager_unittest.cc", "form_fetcher_impl_unittest.cc", "form_saver_impl_unittest.cc", "http_password_store_migrator_unittest.cc",
diff --git a/components/password_manager/core/browser/affiliated_match_helper.cc b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc similarity index 97% rename from components/password_manager/core/browser/affiliated_match_helper.cc rename to components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc index b88033a..b08c98f 100644 --- a/components/password_manager/core/browser/affiliated_match_helper.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc
@@ -2,7 +2,7 @@ // 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/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include <utility> @@ -12,7 +12,7 @@ #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/affiliated_match_helper.h b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h similarity index 94% rename from components/password_manager/core/browser/affiliated_match_helper.h rename to components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h index 50c7fd2..42b3c727 100644 --- a/components/password_manager/core/browser/affiliated_match_helper.h +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h
@@ -2,8 +2,8 @@ // 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_AFFILIATED_MATCH_HELPER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATED_MATCH_HELPER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATED_MATCH_HELPER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATED_MATCH_HELPER_H_ #include <memory> #include <string> @@ -13,7 +13,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h" @@ -157,4 +157,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATED_MATCH_HELPER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATED_MATCH_HELPER_H_
diff --git a/components/password_manager/core/browser/affiliated_match_helper_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc similarity index 98% rename from components/password_manager/core/browser/affiliated_match_helper_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc index 80e169e3c..8f480c68 100644 --- a/components/password_manager/core/browser/affiliated_match_helper_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc
@@ -2,7 +2,7 @@ // 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/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include <stddef.h> @@ -17,8 +17,8 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h" #include "base/threading/thread_task_runner_handle.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/test_password_store.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/affiliation_api.proto b/components/password_manager/core/browser/android_affiliation/affiliation_api.proto similarity index 100% rename from components/password_manager/core/browser/affiliation_api.proto rename to components/password_manager/core/browser/android_affiliation/affiliation_api.proto
diff --git a/components/password_manager/core/browser/affiliation_backend.cc b/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc similarity index 95% rename from components/password_manager/core/browser/affiliation_backend.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_backend.cc index 4ed027f..43cd38e 100644 --- a/components/password_manager/core/browser/affiliation_backend.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc
@@ -2,7 +2,7 @@ // 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/affiliation_backend.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_backend.h" #include <stdint.h> #include <algorithm> @@ -17,10 +17,10 @@ #include "base/time/clock.h" #include "base/time/tick_clock.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_database.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler.h" -#include "components/password_manager/core/browser/affiliation_fetcher.h" -#include "components/password_manager/core/browser/facet_manager.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_database.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager.h" #include "net/url_request/url_request_context_getter.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/affiliation_backend.h b/components/password_manager/core/browser/android_affiliation/affiliation_backend.h similarity index 88% rename from components/password_manager/core/browser/affiliation_backend.h rename to components/password_manager/core/browser/android_affiliation/affiliation_backend.h index 832c305..3f1f140 100644 --- a/components/password_manager/core/browser/affiliation_backend.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend.h
@@ -2,8 +2,8 @@ // 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_AFFILIATION_BACKEND_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_BACKEND_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_BACKEND_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_BACKEND_H_ #include <stddef.h> @@ -15,11 +15,11 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h" -#include "components/password_manager/core/browser/affiliation_fetcher_delegate.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" -#include "components/password_manager/core/browser/facet_manager_host.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager_host.h" namespace base { class Clock; @@ -164,4 +164,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_BACKEND_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_BACKEND_H_
diff --git a/components/password_manager/core/browser/affiliation_backend_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc similarity index 97% rename from components/password_manager/core/browser/affiliation_backend_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc index 9c10c76..b02cd72 100644 --- a/components/password_manager/core/browser/affiliation_backend_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc
@@ -2,7 +2,7 @@ // 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/affiliation_backend.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_backend.h" #include <stddef.h> @@ -17,12 +17,12 @@ #include "base/test/test_simple_task_runner.h" #include "base/time/clock.h" #include "base/time/tick_clock.h" -#include "components/password_manager/core/browser/affiliation_database.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h" -#include "components/password_manager/core/browser/facet_manager.h" -#include "components/password_manager/core/browser/fake_affiliation_api.h" -#include "components/password_manager/core/browser/mock_affiliation_consumer.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_database.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager.h" +#include "components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h" #include "net/url_request/url_request_context_getter.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/affiliation_database.cc b/components/password_manager/core/browser/android_affiliation/affiliation_database.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_database.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_database.cc index 1052aa9..35484d72 100644 --- a/components/password_manager/core/browser/affiliation_database.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database.cc
@@ -2,7 +2,7 @@ // 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/affiliation_database.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_database.h" #include <stdint.h>
diff --git a/components/password_manager/core/browser/affiliation_database.h b/components/password_manager/core/browser/android_affiliation/affiliation_database.h similarity index 89% rename from components/password_manager/core/browser/affiliation_database.h rename to components/password_manager/core/browser/android_affiliation/affiliation_database.h index c9b418c5..a79c94f 100644 --- a/components/password_manager/core/browser/affiliation_database.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database.h
@@ -2,14 +2,14 @@ // 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_AFFILIATION_DATABASE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_DATABASE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_DATABASE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_DATABASE_H_ #include <memory> #include "base/macros.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" namespace base { class FilePath; @@ -90,4 +90,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_DATABASE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_DATABASE_H_
diff --git a/components/password_manager/core/browser/affiliation_database_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_database_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc index 939a5bd..127ca55 100644 --- a/components/password_manager/core/browser/affiliation_database_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc
@@ -2,7 +2,7 @@ // 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/affiliation_database.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_database.h" #include <stdint.h>
diff --git a/components/password_manager/core/browser/affiliation_fetch_throttler.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.cc similarity index 95% rename from components/password_manager/core/browser/affiliation_fetch_throttler.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.cc index cb99eff0..0ec5f76a 100644 --- a/components/password_manager/core/browser/affiliation_fetch_throttler.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.cc
@@ -2,7 +2,7 @@ // 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/affiliation_fetch_throttler.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h" #include <stdint.h> @@ -11,7 +11,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/tick_clock.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/affiliation_fetch_throttler.h b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h similarity index 94% rename from components/password_manager/core/browser/affiliation_fetch_throttler.h rename to components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h index 42743aa..770cd65 100644 --- a/components/password_manager/core/browser/affiliation_fetch_throttler.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h
@@ -2,8 +2,8 @@ // 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_AFFILIATION_FETCH_THROTTLER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCH_THROTTLER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_H_ #include <stdint.h> @@ -132,4 +132,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCH_THROTTLER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_H_
diff --git a/components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h similarity index 74% rename from components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h rename to components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h index d1ad61cb..36d00c92 100644 --- a/components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h
@@ -2,8 +2,8 @@ // 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_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_ namespace password_manager { @@ -26,4 +26,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCH_THROTTLER_DELEGATE_H_
diff --git a/components/password_manager/core/browser/affiliation_fetch_throttler_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_unittest.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_fetch_throttler_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_unittest.cc index 9d15f5a..e365a68 100644 --- a/components/password_manager/core/browser/affiliation_fetch_throttler_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_unittest.cc
@@ -2,7 +2,7 @@ // 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/affiliation_fetch_throttler.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler.h" #include <stddef.h> #include <stdint.h> @@ -21,7 +21,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/tick_clock.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_fetch_throttler_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetch_throttler_delegate.h" #include "net/base/network_change_notifier.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/affiliation_fetcher.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc similarity index 95% rename from components/password_manager/core/browser/affiliation_fetcher.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc index fb486e7..b05d66b5 100644 --- a/components/password_manager/core/browser/affiliation_fetcher.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc
@@ -2,16 +2,16 @@ // 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/affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h" #include <stddef.h> #include <utility> #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" -#include "components/password_manager/core/browser/affiliation_api.pb.h" -#include "components/password_manager/core/browser/affiliation_utils.h" -#include "components/password_manager/core/browser/test_affiliation_fetcher_factory.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_api.pb.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/test_affiliation_fetcher_factory.h" #include "google_apis/google_api_keys.h" #include "net/base/load_flags.h" #include "net/base/url_util.h"
diff --git a/components/password_manager/core/browser/affiliation_fetcher.h b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h similarity index 88% rename from components/password_manager/core/browser/affiliation_fetcher.h rename to components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h index b606ce06..63498a5 100644 --- a/components/password_manager/core/browser/affiliation_fetcher.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h
@@ -2,15 +2,15 @@ // 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_AFFILIATION_FETCHER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCHER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_H_ #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "components/password_manager/core/browser/affiliation_fetcher_delegate.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "net/url_request/url_fetcher_delegate.h" class GURL; @@ -96,4 +96,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCHER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_H_
diff --git a/components/password_manager/core/browser/affiliation_fetcher_delegate.h b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h similarity index 80% rename from components/password_manager/core/browser/affiliation_fetcher_delegate.h rename to components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h index b67e636..d840ea0 100644 --- a/components/password_manager/core/browser/affiliation_fetcher_delegate.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h
@@ -2,13 +2,13 @@ // 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_AFFILIATION_FETCHER_DELEGATE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCHER_DELEGATE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_DELEGATE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_DELEGATE_H_ #include <memory> #include <vector> -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" namespace password_manager { @@ -43,4 +43,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_FETCHER_DELEGATE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_FETCHER_DELEGATE_H_
diff --git a/components/password_manager/core/browser/affiliation_fetcher_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_fetcher_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc index 1ee3c94..cf82af61 100644 --- a/components/password_manager/core/browser/affiliation_fetcher_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc
@@ -2,13 +2,13 @@ // 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/affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h" #include <utility> #include "base/macros.h" #include "base/test/null_task_runner.h" -#include "components/password_manager/core/browser/affiliation_api.pb.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_api.pb.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/components/password_manager/core/browser/affiliation_service.cc b/components/password_manager/core/browser/android_affiliation/affiliation_service.cc similarity index 94% rename from components/password_manager/core/browser/affiliation_service.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_service.cc index 0f986740..5646562 100644 --- a/components/password_manager/core/browser/affiliation_service.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service.cc
@@ -2,7 +2,7 @@ // 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/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -13,7 +13,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_clock.h" #include "base/time/default_tick_clock.h" -#include "components/password_manager/core/browser/affiliation_backend.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_backend.h" #include "net/url_request/url_request_context_getter.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/affiliation_service.h b/components/password_manager/core/browser/android_affiliation/affiliation_service.h similarity index 94% rename from components/password_manager/core/browser/affiliation_service.h rename to components/password_manager/core/browser/android_affiliation/affiliation_service.h index db90a022..835cccd9 100644 --- a/components/password_manager/core/browser/affiliation_service.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service.h
@@ -2,8 +2,8 @@ // 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_AFFILIATION_SERVICE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_SERVICE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_SERVICE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_SERVICE_H_ #include <string> @@ -13,7 +13,7 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" namespace base { class FilePath; @@ -169,4 +169,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_SERVICE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_SERVICE_H_
diff --git a/components/password_manager/core/browser/affiliation_service_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc similarity index 95% rename from components/password_manager/core/browser/affiliation_service_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc index 6e1e38b..f33f95c 100644 --- a/components/password_manager/core/browser/affiliation_service_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc
@@ -5,7 +5,7 @@ // Note: This test focuses on functionality implemented in AffiliationService // itself. More thorough The AffiliationBackend is tested in-depth separarately. -#include "components/password_manager/core/browser/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" #include <memory> @@ -16,8 +16,8 @@ #include "base/test/test_mock_time_task_runner.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" -#include "components/password_manager/core/browser/fake_affiliation_api.h" -#include "components/password_manager/core/browser/mock_affiliation_consumer.h" +#include "components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/affiliation_utils.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_utils.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_utils.cc index 19b9ba1c..9583702e 100644 --- a/components/password_manager/core/browser/affiliation_utils.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc
@@ -2,7 +2,7 @@ // 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/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include <algorithm> #include <ostream>
diff --git a/components/password_manager/core/browser/affiliation_utils.h b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h similarity index 96% rename from components/password_manager/core/browser/affiliation_utils.h rename to components/password_manager/core/browser/android_affiliation/affiliation_utils.h index 960d347..33ab8e4 100644 --- a/components/password_manager/core/browser/affiliation_utils.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h
@@ -41,15 +41,14 @@ // openssl sha -sha512 -binary | base64 | tr '+/' '-_' // -#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_UTILS_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_UTILS_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_UTILS_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_UTILS_H_ +#include <cstddef> #include <iosfwd> #include <string> #include <vector> -#include <stddef.h> - #include "base/containers/hash_tables.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" @@ -194,4 +193,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_AFFILIATION_UTILS_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_AFFILIATION_UTILS_H_
diff --git a/components/password_manager/core/browser/affiliation_utils_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc similarity index 98% rename from components/password_manager/core/browser/affiliation_utils_unittest.cc rename to components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc index c55232fa..99b32c2 100644 --- a/components/password_manager/core/browser/affiliation_utils_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc
@@ -2,7 +2,7 @@ // 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/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "base/command_line.h" #include "base/metrics/field_trial.h"
diff --git a/components/password_manager/core/browser/facet_manager.cc b/components/password_manager/core/browser/android_affiliation/facet_manager.cc similarity index 97% rename from components/password_manager/core/browser/facet_manager.cc rename to components/password_manager/core/browser/android_affiliation/facet_manager.cc index a0e9e86..68ed9c8 100644 --- a/components/password_manager/core/browser/facet_manager.cc +++ b/components/password_manager/core/browser/android_affiliation/facet_manager.cc
@@ -62,14 +62,14 @@ // [--------------- Cache is fresh ----------------)[-- Cache is stale .. // -#include "components/password_manager/core/browser/facet_manager.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager.h" #include "base/bind.h" #include "base/location.h" #include "base/task_runner.h" #include "base/time/clock.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/facet_manager_host.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager_host.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/facet_manager.h b/components/password_manager/core/browser/android_affiliation/facet_manager.h similarity index 91% rename from components/password_manager/core/browser/facet_manager.h rename to components/password_manager/core/browser/android_affiliation/facet_manager.h index 5e3ee77..916e6c4 100644 --- a/components/password_manager/core/browser/facet_manager.h +++ b/components/password_manager/core/browser/android_affiliation/facet_manager.h
@@ -2,8 +2,8 @@ // 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_FACET_MANAGER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FACET_MANAGER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_H_ #include <set> #include <vector> @@ -11,8 +11,8 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" namespace base { class Clock; @@ -134,4 +134,4 @@ }; } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FACET_MANAGER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_H_
diff --git a/components/password_manager/core/browser/facet_manager_host.h b/components/password_manager/core/browser/android_affiliation/facet_manager_host.h similarity index 80% rename from components/password_manager/core/browser/facet_manager_host.h rename to components/password_manager/core/browser/android_affiliation/facet_manager_host.h index 949616f3..cc5f14e 100644 --- a/components/password_manager/core/browser/facet_manager_host.h +++ b/components/password_manager/core/browser/android_affiliation/facet_manager_host.h
@@ -2,8 +2,8 @@ // 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_FACET_MANAGER_HOST_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FACET_MANAGER_HOST_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_HOST_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_HOST_H_ #include "base/macros.h" @@ -33,4 +33,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FACET_MANAGER_HOST_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_HOST_H_
diff --git a/components/password_manager/core/browser/facet_manager_unittest.cc b/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc similarity index 99% rename from components/password_manager/core/browser/facet_manager_unittest.cc rename to components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc index 7bb7c71..afd6c61 100644 --- a/components/password_manager/core/browser/facet_manager_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc
@@ -2,7 +2,7 @@ // 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/facet_manager.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager.h" #include <stddef.h> @@ -18,8 +18,8 @@ #include "base/test/test_simple_task_runner.h" #include "base/time/clock.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/facet_manager_host.h" -#include "components/password_manager/core/browser/mock_affiliation_consumer.h" +#include "components/password_manager/core/browser/android_affiliation/facet_manager_host.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/fake_affiliation_api.cc b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc similarity index 96% rename from components/password_manager/core/browser/fake_affiliation_api.cc rename to components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc index 6db19f0..d8ccd22 100644 --- a/components/password_manager/core/browser/fake_affiliation_api.cc +++ b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc
@@ -2,7 +2,7 @@ // 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/fake_affiliation_api.h" +#include "components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h" #include <algorithm> #include <memory>
diff --git a/components/password_manager/core/browser/fake_affiliation_api.h b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h similarity index 76% rename from components/password_manager/core/browser/fake_affiliation_api.h rename to components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h index 98d4b2e..a4129d6a 100644 --- a/components/password_manager/core/browser/fake_affiliation_api.h +++ b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.h
@@ -2,14 +2,14 @@ // 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_FAKE_AFFILIATION_API_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_AFFILIATION_API_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_API_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_API_H_ #include <vector> #include "base/macros.h" -#include "components/password_manager/core/browser/affiliation_utils.h" -#include "components/password_manager/core/browser/fake_affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.h" namespace password_manager { @@ -50,4 +50,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_AFFILIATION_API_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_API_H_
diff --git a/components/password_manager/core/browser/fake_affiliation_fetcher.cc b/components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.cc similarity index 95% rename from components/password_manager/core/browser/fake_affiliation_fetcher.cc rename to components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.cc index bad984f..e24ebe4 100644 --- a/components/password_manager/core/browser/fake_affiliation_fetcher.cc +++ b/components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.cc
@@ -2,7 +2,7 @@ // 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/fake_affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.h" #include <utility>
diff --git a/components/password_manager/core/browser/fake_affiliation_fetcher.h b/components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.h similarity index 82% rename from components/password_manager/core/browser/fake_affiliation_fetcher.h rename to components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.h index d2a5037..bf38b0c 100644 --- a/components/password_manager/core/browser/fake_affiliation_fetcher.h +++ b/components/password_manager/core/browser/android_affiliation/fake_affiliation_fetcher.h
@@ -2,16 +2,16 @@ // 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_FAKE_AFFILIATION_FETCHER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_AFFILIATION_FETCHER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_FETCHER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_FETCHER_H_ #include <memory> #include <queue> #include "base/macros.h" -#include "components/password_manager/core/browser/affiliation_fetcher.h" -#include "components/password_manager/core/browser/affiliation_fetcher_delegate.h" -#include "components/password_manager/core/browser/test_affiliation_fetcher_factory.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_fetcher_delegate.h" +#include "components/password_manager/core/browser/android_affiliation/test_affiliation_fetcher_factory.h" namespace password_manager { @@ -80,4 +80,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_AFFILIATION_FETCHER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FAKE_AFFILIATION_FETCHER_H_
diff --git a/components/password_manager/core/browser/mock_affiliated_match_helper.cc b/components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.cc similarity index 92% rename from components/password_manager/core/browser/mock_affiliated_match_helper.cc rename to components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.cc index aaf1c99..8c0fa94dd 100644 --- a/components/password_manager/core/browser/mock_affiliated_match_helper.cc +++ b/components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.cc
@@ -2,11 +2,11 @@ // 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/mock_affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h" #include "base/memory/ptr_util.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/mock_affiliated_match_helper.h b/components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h similarity index 84% rename from components/password_manager/core/browser/mock_affiliated_match_helper.h rename to components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h index cd843ce9..25ee2c02 100644 --- a/components/password_manager/core/browser/mock_affiliated_match_helper.h +++ b/components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h
@@ -2,11 +2,11 @@ // 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_MOCK_AFFILIATED_MATCH_HELPER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_AFFILIATED_MATCH_HELPER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATED_MATCH_HELPER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATED_MATCH_HELPER_H_ #include "base/macros.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,4 +61,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_AFFILIATED_MATCH_HELPER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATED_MATCH_HELPER_H_
diff --git a/components/password_manager/core/browser/mock_affiliation_consumer.cc b/components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.cc similarity index 91% rename from components/password_manager/core/browser/mock_affiliation_consumer.cc rename to components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.cc index 6f1d102..23a9c9c 100644 --- a/components/password_manager/core/browser/mock_affiliation_consumer.cc +++ b/components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.cc
@@ -2,7 +2,7 @@ // 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/mock_affiliation_consumer.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h" #include "base/bind.h" #include "base/bind_helpers.h"
diff --git a/components/password_manager/core/browser/mock_affiliation_consumer.h b/components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h similarity index 67% rename from components/password_manager/core/browser/mock_affiliation_consumer.h rename to components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h index 146e299..c597bc2f 100644 --- a/components/password_manager/core/browser/mock_affiliation_consumer.h +++ b/components/password_manager/core/browser/android_affiliation/mock_affiliation_consumer.h
@@ -2,12 +2,12 @@ // 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_MOCK_AFFILIATION_CONSUMER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_AFFILIATION_CONSUMER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATION_CONSUMER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATION_CONSUMER_H_ #include "base/macros.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "testing/gmock/include/gmock/gmock.h" namespace password_manager { @@ -36,4 +36,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_AFFILIATION_CONSUMER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_MOCK_AFFILIATION_CONSUMER_H_
diff --git a/components/password_manager/core/browser/test_affiliation_fetcher_factory.h b/components/password_manager/core/browser/android_affiliation/test_affiliation_fetcher_factory.h similarity index 78% rename from components/password_manager/core/browser/test_affiliation_fetcher_factory.h rename to components/password_manager/core/browser/android_affiliation/test_affiliation_fetcher_factory.h index e313702e..0f73812 100644 --- a/components/password_manager/core/browser/test_affiliation_fetcher_factory.h +++ b/components/password_manager/core/browser/android_affiliation/test_affiliation_fetcher_factory.h
@@ -2,8 +2,8 @@ // 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_TEST_AFFILIATION_FETCHER_FACTORY_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_TEST_AFFILIATION_FETCHER_FACTORY_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_TEST_AFFILIATION_FETCHER_FACTORY_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_TEST_AFFILIATION_FETCHER_FACTORY_H_ #include <vector> @@ -36,4 +36,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_TEST_AFFILIATION_FETCHER_FACTORY_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_TEST_AFFILIATION_FETCHER_FACTORY_H_
diff --git a/components/password_manager/core/browser/credential_manager_pending_request_task.cc b/components/password_manager/core/browser/credential_manager_pending_request_task.cc index 6901dc0..f6e9854 100644 --- a/components/password_manager/core/browser/credential_manager_pending_request_task.cc +++ b/components/password_manager/core/browser/credential_manager_pending_request_task.cc
@@ -13,7 +13,7 @@ #include "base/metrics/user_metrics.h" #include "base/stl_util.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include "components/password_manager/core/browser/password_bubble_experiment.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h"
diff --git a/components/password_manager/core/browser/login_database.cc b/components/password_manager/core/browser/login_database.cc index f1c45b6..99f7b03 100644 --- a/components/password_manager/core/browser/login_database.cc +++ b/components/password_manager/core/browser/login_database.cc
@@ -26,7 +26,7 @@ #include "base/time/time.h" #include "build/build_config.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h"
diff --git a/components/password_manager/core/browser/password_autofill_manager.cc b/components/password_manager/core/browser/password_autofill_manager.cc index a242d65..7ffed22 100644 --- a/components/password_manager/core/browser/password_autofill_manager.cc +++ b/components/password_manager/core/browser/password_autofill_manager.cc
@@ -24,7 +24,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_data_validation.h" #include "components/autofill/core/common/autofill_util.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/security_state/core/security_state.h"
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 9d9613e..043391c 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -24,7 +24,7 @@ #include "components/autofill/core/browser/proto/server.pb.h" #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/browser_save_password_progress_logger.h" #include "components/password_manager/core/browser/form_fetcher_impl.h" #include "components/password_manager/core/browser/form_saver.h"
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 1c6d8f7..61f01ab3 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -19,7 +19,7 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/form_data_predictions.h" #include "components/autofill/core/common/password_form_field_prediction_map.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/browser_save_password_progress_logger.h" #include "components/password_manager/core/browser/form_saver_impl.h" #include "components/password_manager/core/browser/keychain_migration_status_mac.h"
diff --git a/components/password_manager/core/browser/password_store.cc b/components/password_manager/core/browser/password_store.cc index 8b077e2..378e4a8 100644 --- a/components/password_manager/core/browser/password_store.cc +++ b/components/password_manager/core/browser/password_store.cc
@@ -16,7 +16,7 @@ #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "components/password_manager/core/browser/password_syncable_service.h"
diff --git a/components/password_manager/core/browser/password_store_factory_util.cc b/components/password_manager/core/browser/password_store_factory_util.cc index f4c9315..d692a742 100644 --- a/components/password_manager/core/browser/password_store_factory_util.cc +++ b/components/password_manager/core/browser/password_store_factory_util.cc
@@ -7,9 +7,9 @@ #include <utility> #include "base/memory/ptr_util.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_manager_constants.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/components/password_manager/core/browser/password_store_unittest.cc b/components/password_manager/core/browser/password_store_unittest.cc index 7f166a8..29ba50f13 100644 --- a/components/password_manager/core/browser/password_store_unittest.cc +++ b/components/password_manager/core/browser/password_store_unittest.cc
@@ -24,9 +24,9 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/mock_affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/mock_affiliated_match_helper.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_reuse_detector.h" #include "components/password_manager/core/browser/password_store_consumer.h"
diff --git a/components/password_manager/core/browser/password_ui_utils.cc b/components/password_manager/core/browser/password_ui_utils.cc index 34f03d68..49a2ad1a 100644 --- a/components/password_manager/core/browser/password_ui_utils.cc +++ b/components/password_manager/core/browser/password_ui_utils.cc
@@ -11,7 +11,7 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/url_formatter/elide_url.h" namespace password_manager {
diff --git a/components/security_interstitials/core/browser/resources/interstitial_badclock.css b/components/security_interstitials/core/browser/resources/interstitial_badclock.css new file mode 100644 index 0000000..5795edf --- /dev/null +++ b/components/security_interstitials/core/browser/resources/interstitial_badclock.css
@@ -0,0 +1,9 @@ +/* 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. */ + +.bad-clock .icon { + background-image: -webkit-image-set( + url(images/1x/clock.png) 1x, + url(images/2x/clock.png) 2x); +}
diff --git a/components/security_interstitials/core/browser/resources/interstitial_captiveportal.css b/components/security_interstitials/core/browser/resources/interstitial_captiveportal.css new file mode 100644 index 0000000..4a46002 --- /dev/null +++ b/components/security_interstitials/core/browser/resources/interstitial_captiveportal.css
@@ -0,0 +1,9 @@ +/* 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. */ + +.captive-portal .icon { + background-image: -webkit-image-set( + url(images/1x/captive_portal_page_icon.png) 1x, + url(images/2x/captive_portal_page_icon.png) 2x); +}
diff --git a/components/security_interstitials/core/browser/resources/interstitial_large.html b/components/security_interstitials/core/browser/resources/interstitial_large.html index 795491e..e60f225 100644 --- a/components/security_interstitials/core/browser/resources/interstitial_large.html +++ b/components/security_interstitials/core/browser/resources/interstitial_large.html
@@ -5,14 +5,18 @@ <meta name="viewport" content="initial-scale=1, minimum-scale=1, width=device-width"> <title>$i18n{tabTitle}</title> - <link rel="stylesheet" href="interstitial_common.css"> - <link rel="stylesheet" href="interstitial_large.css"> + <link rel="stylesheet" href="../../common/resources/interstitial_core.css"> + <link rel="stylesheet" href="../../common/resources/interstitial_common.css"> + <link rel="stylesheet" href="interstitial_badclock.css"> + <link rel="stylesheet" href="interstitial_captiveportal.css"> + <link rel="stylesheet" href="interstitial_safebrowsing.css"> + <link rel="stylesheet" href="interstitial_ssl.css"> <script src="../../../../../ui/webui/resources/js/util.js"></script> <script src="captive_portal.js"></script> <script src="ssl.js"></script> <script src="extended_reporting.js"></script> - <script src="interstitial_mobile_nav.js"></script> - <script src="interstitial_common.js"></script> + <script src="../../common/resources/interstitial_mobile_nav.js"></script> + <script src="../../common/resources/interstitial_common.js"></script> <script src="interstitial_large.js"></script> </head> <body id="body">
diff --git a/components/security_interstitials/core/browser/resources/interstitial_safebrowsing.css b/components/security_interstitials/core/browser/resources/interstitial_safebrowsing.css new file mode 100644 index 0000000..c274cd4 --- /dev/null +++ b/components/security_interstitials/core/browser/resources/interstitial_safebrowsing.css
@@ -0,0 +1,45 @@ +/* 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. */ + +body.safe-browsing { + background-color: rgb(206, 52, 38); + color: white; +} + +.safe-browsing :-webkit-any( + a, #details, #details-button, h1, h2, p, .small-link) { + color: white; +} + +.safe-browsing button { + background-color: rgba(255, 255, 255, .15); +} + +.safe-browsing button:active { + background-color: rgba(255, 255, 255, .25); +} + +.safe-browsing button:hover { + box-shadow: 0 2px 3px rgba(0, 0, 0, .5); +} + +.safe-browsing .error-code { + display: none; +} + +.safe-browsing .icon { + background-image: -webkit-image-set( + url(images/1x/triangle_white.png) 1x, + url(images/2x/triangle_white.png) 2x); +} + +@media (min-width: 240px) and (max-width: 420px) and + (min-height: 401px), + (min-width: 421px) and (min-height: 240px) and + (max-height: 560px) { + body.safe-browsing .nav-wrapper { + background: rgb(206, 52, 38); + box-shadow: 0 -22px 40px rgb(206, 52, 38); + } +} \ No newline at end of file
diff --git a/components/security_interstitials/core/browser/resources/interstitial_ssl.css b/components/security_interstitials/core/browser/resources/interstitial_ssl.css new file mode 100644 index 0000000..97fff226 --- /dev/null +++ b/components/security_interstitials/core/browser/resources/interstitial_ssl.css
@@ -0,0 +1,17 @@ +/* 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. */ + +.ssl .icon { + background-image: -webkit-image-set( + url(images/1x/triangle_red.png) 1x, + url(images/2x/triangle_red.png) 2x); +} + +.ssl-opt-in .checkbox { + border-color: #696969; +} + +.ssl-opt-in .checkbox::before { + border-color: #696969; +}
diff --git a/components/security_interstitials/core/browser/resources/interstitial_webview_quiet.html b/components/security_interstitials/core/browser/resources/interstitial_webview_quiet.html index bb46d05f..64cc0d2 100644 --- a/components/security_interstitials/core/browser/resources/interstitial_webview_quiet.html +++ b/components/security_interstitials/core/browser/resources/interstitial_webview_quiet.html
@@ -5,10 +5,10 @@ <meta name="viewport" content="initial-scale=1, minimum-scale=1, width=device-width"> <title>$i18n{tabTitle}</title> - <link rel="stylesheet" href="interstitial_common.css"> + <link rel="stylesheet" href="../../common/resources/interstitial_core.css"> <link rel="stylesheet" href="interstitial_webview_quiet.css"> <script src="../../../../../ui/webui/resources/js/util.js"></script> - <script src="interstitial_common.js"></script> + <script src="../../common/resources/interstitial_common.js"></script> <script src="interstitial_webview_quiet.js"></script> </head> <body id="body">
diff --git a/components/security_interstitials/core/browser/resources/interstitial_large.css b/components/security_interstitials/core/common/resources/interstitial_common.css similarity index 84% rename from components/security_interstitials/core/browser/resources/interstitial_large.css rename to components/security_interstitials/core/common/resources/interstitial_common.css index c14e72b..d868ff3 100644 --- a/components/security_interstitials/core/browser/resources/interstitial_large.css +++ b/components/security_interstitials/core/common/resources/interstitial_common.css
@@ -2,17 +2,6 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ -.bad-clock .icon { - background-image: -webkit-image-set( - url(images/1x/clock.png) 1x, - url(images/2x/clock.png) 2x); -} - -body.safe-browsing { - background-color: rgb(206, 52, 38); - color: white; -} - button { background: rgb(66, 133, 244); border: 0; @@ -149,50 +138,11 @@ width: 100%; } -.safe-browsing :-webkit-any( - a, #details, #details-button, h1, h2, p, .small-link) { - color: white; -} - -.safe-browsing button { - background-color: rgba(255, 255, 255, .15); -} - -.safe-browsing button:active { - background-color: rgba(255, 255, 255, .25); -} - -.safe-browsing button:hover { - box-shadow: 0 2px 3px rgba(0, 0, 0, .5); -} - -.safe-browsing .error-code { - display: none; -} - -.safe-browsing .icon { - background-image: -webkit-image-set( - url(images/1x/triangle_white.png) 1x, - url(images/2x/triangle_white.png) 2x); -} - .small-link { color: #696969; font-size: .875em; } -.ssl .icon { - background-image: -webkit-image-set( - url(images/1x/triangle_red.png) 1x, - url(images/2x/triangle_red.png) 2x); -} - -.captive-portal .icon { - background-image: -webkit-image-set( - url(images/1x/captive_portal_page_icon.png) 1x, - url(images/2x/captive_portal_page_icon.png) 2x); -} - .checkboxes { flex: 0 0 24px; } @@ -225,14 +175,6 @@ width: 9px; } -.ssl-opt-in .checkbox { - border-color: #696969; -} - -.ssl-opt-in .checkbox::before { - border-color: #696969; -} - input[type=checkbox]:checked ~ .checkbox::before { opacity: 1; } @@ -328,11 +270,6 @@ z-index: 2; } - body.safe-browsing .nav-wrapper { - background: rgb(206, 52, 38); - box-shadow: 0 -22px 40px rgb(206, 52, 38); - } - .interstitial-wrapper { max-width: 736px; }
diff --git a/components/security_interstitials/core/browser/resources/interstitial_common.js b/components/security_interstitials/core/common/resources/interstitial_common.js similarity index 100% rename from components/security_interstitials/core/browser/resources/interstitial_common.js rename to components/security_interstitials/core/common/resources/interstitial_common.js
diff --git a/components/security_interstitials/core/browser/resources/interstitial_common.css b/components/security_interstitials/core/common/resources/interstitial_core.css similarity index 100% rename from components/security_interstitials/core/browser/resources/interstitial_common.css rename to components/security_interstitials/core/common/resources/interstitial_core.css
diff --git a/components/security_interstitials/core/browser/resources/interstitial_mobile_nav.js b/components/security_interstitials/core/common/resources/interstitial_mobile_nav.js similarity index 100% rename from components/security_interstitials/core/browser/resources/interstitial_mobile_nav.js rename to components/security_interstitials/core/common/resources/interstitial_mobile_nav.js
diff --git a/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerHelper.java b/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerHelper.java index 761a728..9b3b9fe 100644 --- a/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerHelper.java +++ b/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerHelper.java
@@ -9,10 +9,14 @@ import android.app.Activity; import android.content.Context; import android.os.AsyncTask; +import android.support.annotation.AnyThread; +import android.support.annotation.MainThread; import android.support.annotation.Nullable; +import android.support.annotation.WorkerThread; import org.chromium.base.Callback; import org.chromium.base.Log; +import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.net.NetworkChangeNotifier; @@ -82,6 +86,7 @@ * * @param delegate the custom AccountManagerDelegate to use. */ + @AnyThread public static void initializeAccountManagerHelper(AccountManagerDelegate delegate) { if (!sInstance.compareAndSet(null, new AccountManagerHelper(delegate))) { throw new IllegalStateException("AccountManagerHelper is already initialized!"); @@ -94,6 +99,7 @@ * * @return a singleton instance */ + @AnyThread public static AccountManagerHelper get() { AccountManagerHelper instance = sInstance.get(); assert instance != null : "AccountManagerHelper is not initialized!"; @@ -109,6 +115,7 @@ * @param delegate the custom AccountManagerDelegate to use. */ @VisibleForTesting + @AnyThread public static void overrideAccountManagerHelperForTests( Context context, AccountManagerDelegate delegate) { sInstance.set(new AccountManagerHelper(delegate)); @@ -119,6 +126,7 @@ * Only for use in Tests. */ @VisibleForTesting + @AnyThread public static void resetAccountManagerHelperForTests() { sInstance.set(null); } @@ -126,6 +134,7 @@ /** * Creates an Account object for the given name. */ + @AnyThread public static Account createAccountFromName(String name) { return new Account(name, GOOGLE_ACCOUNT_TYPE); } @@ -135,6 +144,7 @@ * * See http://crbug.com/517697 for details. */ + @WorkerThread public List<String> getGoogleAccountNames() { List<String> accountNames = new ArrayList<>(); for (Account account : getGoogleAccounts()) { @@ -146,6 +156,7 @@ /** * Retrieves a list of the Google account names on the device asynchronously. */ + @MainThread public void getGoogleAccountNames(final Callback<List<String>> callback) { getGoogleAccounts(new Callback<Account[]>() { @Override @@ -164,6 +175,7 @@ * * See http://crbug.com/517697 for details. */ + @WorkerThread public Account[] getGoogleAccounts() { return mDelegate.getAccountsByType(GOOGLE_ACCOUNT_TYPE); } @@ -171,7 +183,9 @@ /** * Retrieves all Google accounts on the device asynchronously. */ + @MainThread public void getGoogleAccounts(final Callback<Account[]> callback) { + ThreadUtils.assertOnUiThread(); new AsyncTask<Void, Void, Account[]>() { @Override protected Account[] doInBackground(Void... params) { @@ -190,6 +204,7 @@ * * See http://crbug.com/517697 for details. */ + @WorkerThread public boolean hasGoogleAccounts() { return getGoogleAccounts().length > 0; } @@ -197,6 +212,7 @@ /** * Asynchronously determine whether any Google accounts have been added. */ + @MainThread public void hasGoogleAccounts(final Callback<Boolean> callback) { getGoogleAccounts(new Callback<Account[]>() { @Override @@ -224,6 +240,7 @@ * * See http://crbug.com/517697 for details. */ + @WorkerThread public Account getAccountFromName(String accountName) { String canonicalName = canonicalizeName(accountName); Account[] accounts = getGoogleAccounts(); @@ -238,6 +255,7 @@ /** * Asynchronously returns the account if it exists; null otherwise. */ + @MainThread public void getAccountFromName(String accountName, final Callback<Account> callback) { final String canonicalName = canonicalizeName(accountName); getGoogleAccounts(new Callback<Account[]>() { @@ -260,6 +278,7 @@ * * See http://crbug.com/517697 for details. */ + @WorkerThread public boolean hasAccountForName(String accountName) { return getAccountFromName(accountName) != null; } @@ -269,6 +288,7 @@ */ // TODO(maxbogue): Remove once this function is used outside of tests. @VisibleForTesting + @MainThread public void hasAccountForName(String accountName, final Callback<Boolean> callback) { getAccountFromName(accountName, new Callback<Account>() { @Override @@ -281,6 +301,7 @@ /** * @return Whether or not there is an account authenticator for Google accounts. */ + @AnyThread public boolean hasGoogleAccountAuthenticator() { AuthenticatorDescription[] descs = mDelegate.getAuthenticatorTypes(); for (AuthenticatorDescription desc : descs) { @@ -296,6 +317,7 @@ * * - Assumes that the account is a valid account. */ + @MainThread public void getAuthToken(final Account account, final String authTokenType, final GetAuthTokenCallback callback) { ConnectionRetry.runAuthTask(new AuthTask<String>() { @@ -319,6 +341,7 @@ * * - Assumes that the account is a valid account. */ + @MainThread public void getNewAuthToken(Account account, String authToken, String authTokenType, GetAuthTokenCallback callback) { invalidateAuthToken(authToken); @@ -328,6 +351,7 @@ /** * Clear an auth token from the local cache with respect to the ApplicationContext. */ + @MainThread public void invalidateAuthToken(final String authToken) { if (authToken == null || authToken.isEmpty()) { return; @@ -347,6 +371,7 @@ }); } + @MainThread public void checkChildAccount(Account account, Callback<Boolean> callback) { hasFeatures(account, new String[] {FEATURE_IS_CHILD_ACCOUNT_KEY}, callback); } @@ -357,6 +382,7 @@ private void hasFeatures( final Account account, final String[] features, final Callback<Boolean> callback) { + ThreadUtils.assertOnUiThread(); new AsyncTask<Void, Void, Boolean>() { @Override public Boolean doInBackground(Void... params) { @@ -374,6 +400,7 @@ * Asks the user to enter a new password for an account, updating the saved credentials for the * account. */ + @MainThread public void updateCredentials( Account account, Activity activity, @Nullable Callback<Boolean> callback) { mDelegate.updateCredentials(account, activity, callback); @@ -414,6 +441,7 @@ * as a {@link ConnectionTypeObserver} when this method is called. */ private void attempt() { + ThreadUtils.assertOnUiThread(); // Clear any transient error. mIsTransientError.set(false); new AsyncTask<Void, Void, T>() {
diff --git a/components/signin/core/browser/android/javatests/src/org/chromium/components/signin/test/AccountManagerHelperTest.java b/components/signin/core/browser/android/javatests/src/org/chromium/components/signin/test/AccountManagerHelperTest.java index f0acd3f0..8ac84b2 100644 --- a/components/signin/core/browser/android/javatests/src/org/chromium/components/signin/test/AccountManagerHelperTest.java +++ b/components/signin/core/browser/android/javatests/src/org/chromium/components/signin/test/AccountManagerHelperTest.java
@@ -9,6 +9,7 @@ import android.support.test.filters.SmallTest; import android.test.InstrumentationTestCase; +import org.chromium.base.ThreadUtils; import org.chromium.components.signin.AccountManagerHelper; import org.chromium.components.signin.test.util.AccountHolder; import org.chromium.components.signin.test.util.FakeAccountManagerDelegate; @@ -66,9 +67,14 @@ return account; } - private boolean hasAccountForName(String accountName) throws InterruptedException { - SimpleFuture<Boolean> result = new SimpleFuture<Boolean>(); - mHelper.hasAccountForName(accountName, result.createCallback()); + private boolean hasAccountForName(final String accountName) throws InterruptedException { + final SimpleFuture<Boolean> result = new SimpleFuture<Boolean>(); + ThreadUtils.postOnUiThread(new Runnable() { + @Override + public void run() { + mHelper.hasAccountForName(accountName, result.createCallback()); + } + }); return result.get(); } }
diff --git a/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java b/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java index b9641b7..e131335f 100644 --- a/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java +++ b/components/sync/android/java/src/org/chromium/components/sync/AndroidSyncSettings.java
@@ -14,6 +14,7 @@ import org.chromium.base.Callback; import org.chromium.base.ObserverList; +import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.components.signin.AccountManagerHelper; import org.chromium.components.signin.ChromeSigninController; @@ -248,24 +249,29 @@ StrictMode.setThreadPolicy(oldPolicy); // Disable the syncability of Chrome for all other accounts. - AccountManagerHelper.get().getGoogleAccounts(new Callback<Account[]>() { + ThreadUtils.postOnUiThread(new Runnable() { @Override - public void onResult(Account[] accounts) { - synchronized (mLock) { - StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); - for (Account account : accounts) { - if (!account.equals(mAccount) - && mSyncContentResolverDelegate.getIsSyncable( - account, mContractAuthority) - > 0) { - mSyncContentResolverDelegate.setIsSyncable( - account, mContractAuthority, 0); + public void run() { + AccountManagerHelper.get().getGoogleAccounts(new Callback<Account[]>() { + @Override + public void onResult(Account[] accounts) { + synchronized (mLock) { + StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); + for (Account account : accounts) { + if (!account.equals(mAccount) + && mSyncContentResolverDelegate.getIsSyncable( + account, mContractAuthority) + > 0) { + mSyncContentResolverDelegate.setIsSyncable( + account, mContractAuthority, 0); + } + } + StrictMode.setThreadPolicy(oldPolicy); } - } - StrictMode.setThreadPolicy(oldPolicy); - } - if (callback != null) callback.onResult(true); + if (callback != null) callback.onResult(true); + } + }); } }); }
diff --git a/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java b/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java index eac0a59..dd73c86 100644 --- a/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java +++ b/components/sync/android/javatests/src/org/chromium/components/sync/AndroidSyncSettingsTest.java
@@ -135,8 +135,8 @@ @Override protected void tearDown() throws Exception { - AccountManagerHelper.resetAccountManagerHelperForTests(); super.tearDown(); + AccountManagerHelper.resetAccountManagerHelperForTests(); } private void enableChromeSyncOnUiThread() {
diff --git a/components/sync/base/data_type_histogram.cc b/components/sync/base/data_type_histogram.cc index 45f563e..b8be026 100644 --- a/components/sync/base/data_type_histogram.cc +++ b/components/sync/base/data_type_histogram.cc
@@ -4,23 +4,10 @@ #include "components/sync/base/data_type_histogram.h" -#include "base/metrics/histogram_functions.h" #include "base/metrics/sparse_histogram.h" -const char kModelTypeMemoryHistogramPrefix[] = "Sync.ModelTypeMemoryKB."; - void SyncRecordDatatypeBin(const std::string& name, int sample, int value) { base::HistogramBase* histogram = base::SparseHistogram::FactoryGet( name, base::HistogramBase::kUmaTargetedHistogramFlag); histogram->AddCount(sample, value); } - -void SyncRecordMemoryKbHistogram(const std::string& histogram_name_prefix, - syncer::ModelType model_type, - size_t value) { - std::string type_string; - if (RealModelTypeToNotificationType(model_type, &type_string)) { - std::string full_histogram_name = histogram_name_prefix + type_string; - base::UmaHistogramCounts1M(full_histogram_name, value / 1024); - } -}
diff --git a/components/sync/base/data_type_histogram.h b/components/sync/base/data_type_histogram.h index 09cc6f3..642c8848 100644 --- a/components/sync/base/data_type_histogram.h +++ b/components/sync/base/data_type_histogram.h
@@ -11,21 +11,12 @@ #include "base/time/time.h" #include "components/sync/base/model_type.h" -// Prefix for histogram recording datatype's memory usage. -extern const char kModelTypeMemoryHistogramPrefix[]; - // This function adds |value| to |sample| bucket of histogram |name|. |value| // should be greater or equal to 1 and |name| can be variable. DataTypes are // mapped to proper |sample| bucket by using ModelTypeToHistogramInt() function. // So different DataTypes play the role of different buckets in this histogram. void SyncRecordDatatypeBin(const std::string& name, int sample, int value); -// Converts memory size |value| into kilobytes and records it into |model_type| -// related histogram with prefix |histogram_name_prefix|. -void SyncRecordMemoryKbHistogram(const std::string& histogram_name_prefix, - syncer::ModelType model_type, - size_t value); - // For now, this just implements UMA_HISTOGRAM_LONG_TIMES. This can be adjusted // if we feel the min, max, or bucket count amount are not appropriate. #define SYNC_FREQ_HISTOGRAM(name, time) \
diff --git a/components/sync/driver/data_type_controller.h b/components/sync/driver/data_type_controller.h index 8fd7bd8..7f9aecc 100644 --- a/components/sync/driver/data_type_controller.h +++ b/components/sync/driver/data_type_controller.h
@@ -162,9 +162,6 @@ // Used to display entity counts in chrome://sync-internals. virtual void GetStatusCounters(const StatusCountersCallback& callback) = 0; - // Estimates memory usage of type and records it into histogram. - virtual void RecordMemoryUsageHistogram() = 0; - protected: explicit DataTypeController(ModelType type);
diff --git a/components/sync/driver/directory_data_type_controller.cc b/components/sync/driver/directory_data_type_controller.cc index 3b2b879..a03ee3d 100644 --- a/components/sync/driver/directory_data_type_controller.cc +++ b/components/sync/driver/directory_data_type_controller.cc
@@ -9,7 +9,6 @@ #include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" -#include "components/sync/base/data_type_histogram.h" #include "components/sync/driver/sync_service.h" #include "components/sync/engine/model_type_configurer.h" #include "components/sync/syncable/syncable_read_transaction.h" @@ -84,14 +83,6 @@ callback.Run(type(), counters); } -void DirectoryDataTypeController::RecordMemoryUsageHistogram() { - syncer::syncable::Directory* directory = - sync_client_->GetSyncService()->GetUserShare()->directory.get(); - size_t memory_usage = directory->EstimateMemoryUsageByType(type()); - SyncRecordMemoryKbHistogram(kModelTypeMemoryHistogramPrefix, type(), - memory_usage); -} - // static std::unique_ptr<base::ListValue> DirectoryDataTypeController::GetAllNodesForTypeFromDirectory(
diff --git a/components/sync/driver/directory_data_type_controller.h b/components/sync/driver/directory_data_type_controller.h index 7c3f523..a521be1d 100644 --- a/components/sync/driver/directory_data_type_controller.h +++ b/components/sync/driver/directory_data_type_controller.h
@@ -49,7 +49,6 @@ void GetAllNodes(const AllNodesCallback& callback) override; void GetStatusCounters(const StatusCountersCallback& callback) override; - void RecordMemoryUsageHistogram() override; // Returns a ListValue representing all nodes for a specified type by querying // the directory.
diff --git a/components/sync/driver/model_type_controller.cc b/components/sync/driver/model_type_controller.cc index 5f67856..8e98059 100644 --- a/components/sync/driver/model_type_controller.cc +++ b/components/sync/driver/model_type_controller.cc
@@ -236,11 +236,6 @@ base::Bind(&ModelTypeDebugInfo::GetStatusCounters, callback)); } -void ModelTypeController::RecordMemoryUsageHistogram() { - PostBridgeTask(FROM_HERE, - base::Bind(&ModelTypeDebugInfo::RecordMemoryUsageHistogram)); -} - void ModelTypeController::ReportModelError(const ModelError& error) { DCHECK(CalledOnValidThread()); LoadModelsDone(UNRECOVERABLE_ERROR,
diff --git a/components/sync/driver/model_type_controller.h b/components/sync/driver/model_type_controller.h index 496c418..0e9edd6 100644 --- a/components/sync/driver/model_type_controller.h +++ b/components/sync/driver/model_type_controller.h
@@ -50,7 +50,6 @@ State state() const override; void GetAllNodes(const AllNodesCallback& callback) override; void GetStatusCounters(const StatusCountersCallback& callback) override; - void RecordMemoryUsageHistogram() override; private: void RecordStartFailure(ConfigureResult result) const;
diff --git a/components/sync/driver/proxy_data_type_controller.cc b/components/sync/driver/proxy_data_type_controller.cc index 837145b..08d3a953 100644 --- a/components/sync/driver/proxy_data_type_controller.cc +++ b/components/sync/driver/proxy_data_type_controller.cc
@@ -85,6 +85,4 @@ callback.Run(type(), counters); } -void ProxyDataTypeController::RecordMemoryUsageHistogram() {} - } // namespace syncer
diff --git a/components/sync/driver/proxy_data_type_controller.h b/components/sync/driver/proxy_data_type_controller.h index 93b3c13..2036f2a 100644 --- a/components/sync/driver/proxy_data_type_controller.h +++ b/components/sync/driver/proxy_data_type_controller.h
@@ -35,7 +35,6 @@ void DeactivateDataType(ModelTypeConfigurer* configurer) override; void GetAllNodes(const AllNodesCallback& callback) override; void GetStatusCounters(const StatusCountersCallback& callback) override; - void RecordMemoryUsageHistogram() override; private: State state_;
diff --git a/components/sync/model/model_type_debug_info.cc b/components/sync/model/model_type_debug_info.cc index 58887cc..f2f1dfd 100644 --- a/components/sync/model/model_type_debug_info.cc +++ b/components/sync/model/model_type_debug_info.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" -#include "components/sync/base/data_type_histogram.h" #include "components/sync/model_impl/processor_entity_tracker.h" #include "components/sync/protocol/proto_value_conversions.h" @@ -60,15 +59,6 @@ } } -// static -void ModelTypeDebugInfo::RecordMemoryUsageHistogram( - ModelTypeSyncBridge* bridge) { - SharedModelTypeProcessor* processor = GetProcessorFromBridge(bridge); - size_t memory_usage = processor->EstimateMemoryUsage(); - SyncRecordMemoryKbHistogram(kModelTypeMemoryHistogramPrefix, processor->type_, - memory_usage); -} - ModelTypeDebugInfo::ModelTypeDebugInfo() {} // static
diff --git a/components/sync/model/model_type_debug_info.h b/components/sync/model/model_type_debug_info.h index e8b94a3..74cc940 100644 --- a/components/sync/model/model_type_debug_info.h +++ b/components/sync/model/model_type_debug_info.h
@@ -35,10 +35,6 @@ callback, ModelTypeSyncBridge* bridge); - // Queries |bridge| for estimate of memory usage and records it in a - // histogram. - static void RecordMemoryUsageHistogram(ModelTypeSyncBridge* bridge); - private: ModelTypeDebugInfo();
diff --git a/components/sync/syncable/directory.cc b/components/sync/syncable/directory.cc index 14e0765e..c0a579e 100644 --- a/components/sync/syncable/directory.cc +++ b/components/sync/syncable/directory.cc
@@ -987,42 +987,6 @@ } } -// Iterates over entries of |map|, sums memory usage estimate of entries whose -// entry type is |model_type|. Passing owning container will also include memory -// estimate of EntryKernel. -template <typename Container> -size_t EstimateFiteredMapMemoryUsage(const Container& map, - ModelType model_type) { - using base::trace_event::EstimateMemoryUsage; - size_t memory_usage = 0; - for (const auto& kv : map) { - const ModelType entry_type = - GetModelTypeFromSpecifics(kv.second->ref(SPECIFICS)); - if (entry_type == model_type) { - memory_usage += EstimateMemoryUsage(kv); - } - } - return memory_usage; -} - -size_t Directory::EstimateMemoryUsageByType(ModelType model_type) { - using base::trace_event::EstimateMemoryUsage; - ReadTransaction trans(FROM_HERE, this); - ScopedKernelLock lock(this); - - size_t memory_usage = 0; - memory_usage += - EstimateFiteredMapMemoryUsage(kernel_->metahandles_map, model_type); - memory_usage += EstimateFiteredMapMemoryUsage(kernel_->ids_map, model_type); - memory_usage += - EstimateFiteredMapMemoryUsage(kernel_->server_tags_map, model_type); - memory_usage += - EstimateFiteredMapMemoryUsage(kernel_->client_tags_map, model_type); - memory_usage += EstimateMemoryUsage( - kernel_->persisted_info.download_progress[model_type]); - return memory_usage; -} - void Directory::SetDownloadProgress( ModelType model_type, const sync_pb::DataTypeProgressMarker& new_progress) { @@ -1210,12 +1174,13 @@ ModelType type, std::vector<int64_t>* result) { result->clear(); - for (const auto& handle_and_kernel : kernel_->metahandles_map) { - EntryKernel* entry = handle_and_kernel.second.get(); + for (MetahandlesMap::iterator it = kernel_->metahandles_map.begin(); + it != kernel_->metahandles_map.end(); ++it) { + EntryKernel* entry = it->second.get(); const ModelType entry_type = GetModelTypeFromSpecifics(entry->ref(SPECIFICS)); if (entry_type == type) - result->push_back(handle_and_kernel.first); + result->push_back(it->first); } }
diff --git a/components/sync/syncable/directory.h b/components/sync/syncable/directory.h index 5ac3296..7e9ff063 100644 --- a/components/sync/syncable/directory.h +++ b/components/sync/syncable/directory.h
@@ -292,10 +292,6 @@ // Adds memory statistics to |pmd| for chrome://tracing. void OnMemoryDump(base::trace_event::ProcessMemoryDump* pmd); - // Estimates memory usage of entries and corresponding indices of type - // |model_type|. - size_t EstimateMemoryUsageByType(ModelType model_type); - // Gets/Increments transaction version of a model type. Must be called when // holding kernel mutex. int64_t GetTransactionVersion(ModelType type) const;
diff --git a/components/translate/OWNERS b/components/translate/OWNERS index e9ba48d..3cf2d4d1 100644 --- a/components/translate/OWNERS +++ b/components/translate/OWNERS
@@ -8,4 +8,5 @@ droger@chromium.org groby@chromium.org hajimehoshi@chromium.org +napper@chromium.org toyoshim@chromium.org
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 1c89c14..c79072e 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -2037,8 +2037,6 @@ "renderer_host/native_web_keyboard_event_aura.cc", "renderer_host/render_widget_host_view_aura.cc", "renderer_host/render_widget_host_view_aura.h", - "renderer_host/ui_events_helper.cc", - "renderer_host/ui_events_helper.h", "web_contents/aura/gesture_nav_simple.cc", "web_contents/aura/gesture_nav_simple.h", "web_contents/aura/overscroll_navigation_overlay.cc",
diff --git a/content/browser/DEPS b/content/browser/DEPS index 5aafa562..ed5f31a5 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -137,6 +137,7 @@ "+third_party/WebKit/public/web/WebSharedWorkerCreationErrors.h", "+third_party/WebKit/public/web/WebTextDirection.h", "+third_party/WebKit/public/web/WebTreeScopeType.h", + "+third_party/WebKit/public/web/WebTriggeringEventInfo.h", # DO NOT ADD ANY CHROME OR COMPONENTS INCLUDES HERE!!! # See https://sites.google.com/a/chromium.org/dev/developers/content-module
diff --git a/content/browser/download/mhtml_generation_browsertest.cc b/content/browser/download/mhtml_generation_browsertest.cc index e0bc3a2..e13a93d2 100644 --- a/content/browser/download/mhtml_generation_browsertest.cc +++ b/content/browser/download/mhtml_generation_browsertest.cc
@@ -376,7 +376,13 @@ EXPECT_GT(ReadFileSizeFromDisk(path), 100); // Verify the actual file size. } -IN_PROC_BROWSER_TEST_F(MHTMLGenerationTest, InvalidPath) { +// TODO(crbug.com/672313): Flaky on Windows. +#if defined(OS_WIN) +#define MAYBE_InvalidPath DISABLED_InvalidPath +#else +#define MAYBE_InvalidPath InvalidPath +#endif +IN_PROC_BROWSER_TEST_F(MHTMLGenerationTest, MAYBE_InvalidPath) { base::FilePath path(FILE_PATH_LITERAL("/invalid/file/path")); GenerateMHTML(path, embedded_test_server()->GetURL(
diff --git a/content/browser/frame_host/navigator.h b/content/browser/frame_host/navigator.h index 424d828..c21d286 100644 --- a/content/browser/frame_host/navigator.h +++ b/content/browser/frame_host/navigator.h
@@ -11,6 +11,7 @@ #include "content/browser/frame_host/navigator_delegate.h" #include "content/common/content_export.h" #include "content/public/browser/navigation_controller.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" #include "ui/base/window_open_disposition.h" class GURL; @@ -123,7 +124,8 @@ WindowOpenDisposition disposition, bool force_new_process_for_new_contents, bool should_replace_current_entry, - bool user_gesture) {} + bool user_gesture, + blink::WebTriggeringEventInfo triggering_event_info) {} // The RenderFrameHostImpl wants to transfer the request to a new renderer. // |redirect_chain| contains any redirect URLs (excluding |url|) that happened
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index c51df45d..f21afa5 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -725,7 +725,8 @@ WindowOpenDisposition disposition, bool force_new_process_for_new_contents, bool should_replace_current_entry, - bool user_gesture) { + bool user_gesture, + blink::WebTriggeringEventInfo triggering_event_info) { // Note: This can be called for subframes (even when OOPIFs are not possible) // if the disposition calls for a different window. @@ -775,6 +776,7 @@ params.redirect_chain = redirect_chain; params.should_replace_current_entry = should_replace_current_entry; params.user_gesture = user_gesture; + params.triggering_event_info = triggering_event_info; // RequestOpenURL is used only for local frames, so we can get here only if // the navigation is initiated by a frame in the same SiteInstance as this
diff --git a/content/browser/frame_host/navigator_impl.h b/content/browser/frame_host/navigator_impl.h index 648e209..32fabc7 100644 --- a/content/browser/frame_host/navigator_impl.h +++ b/content/browser/frame_host/navigator_impl.h
@@ -64,16 +64,18 @@ bool is_same_document_history_load) override; bool NavigateNewChildFrame(RenderFrameHostImpl* render_frame_host, const GURL& default_url) override; - void RequestOpenURL(RenderFrameHostImpl* render_frame_host, - const GURL& url, - bool uses_post, - const scoped_refptr<ResourceRequestBodyImpl>& body, - const std::string& extra_headers, - const Referrer& referrer, - WindowOpenDisposition disposition, - bool force_new_process_for_new_contents, - bool should_replace_current_entry, - bool user_gesture) override; + void RequestOpenURL( + RenderFrameHostImpl* render_frame_host, + const GURL& url, + bool uses_post, + const scoped_refptr<ResourceRequestBodyImpl>& body, + const std::string& extra_headers, + const Referrer& referrer, + WindowOpenDisposition disposition, + bool force_new_process_for_new_contents, + bool should_replace_current_entry, + bool user_gesture, + blink::WebTriggeringEventInfo triggering_event_info) override; void RequestTransferURL(RenderFrameHostImpl* render_frame_host, const GURL& url, SiteInstance* source_site_instance,
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index c1a3487..09ea3e64 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1287,7 +1287,7 @@ this, validated_url, params.uses_post, params.resource_request_body, params.extra_headers, params.referrer, params.disposition, kForceNewProcessForNewContents, params.should_replace_current_entry, - params.user_gesture); + params.user_gesture, params.triggering_event_info); } void RenderFrameHostImpl::OnCancelInitialHistoryLoad() {
diff --git a/content/browser/gpu/gpu_internals_ui.cc b/content/browser/gpu/gpu_internals_ui.cc index 066f6d0..a982ead9f 100644 --- a/content/browser/gpu/gpu_internals_ui.cc +++ b/content/browser/gpu/gpu_internals_ui.cc
@@ -273,6 +273,8 @@ return "ETC1"; case gfx::BufferFormat::R_8: return "R_8"; + case gfx::BufferFormat::R_16: + return "R_16"; case gfx::BufferFormat::RG_88: return "RG_88"; case gfx::BufferFormat::BGR_565:
diff --git a/content/browser/renderer_host/input/touch_emulator.cc b/content/browser/renderer_host/input/touch_emulator.cc index 4f6eb86e..f0e3f01b 100644 --- a/content/browser/renderer_host/input/touch_emulator.cc +++ b/content/browser/renderer_host/input/touch_emulator.cc
@@ -6,6 +6,7 @@ #include "build/build_config.h" #include "content/browser/renderer_host/input/motion_event_web.h" +#include "content/browser/renderer_host/ui_events_helper.h" #include "content/common/input/web_touch_event_traits.h" #include "content/grit/content_resources.h" #include "content/public/common/content_client.h" @@ -258,10 +259,12 @@ return; const bool event_consumed = true; + const bool is_source_touch_event_set_non_blocking = false; // Block emulated event when emulated native stream is active. if (native_stream_active_sequence_count_) { gesture_provider_->OnTouchEventAck(event.unique_touch_event_id, - event_consumed); + event_consumed, + is_source_touch_event_set_non_blocking); return; } @@ -269,7 +272,8 @@ // Do not allow middle-sequence event to pass through, if start was blocked. if (!emulated_stream_active_sequence_count_ && !is_sequence_start) { gesture_provider_->OnTouchEventAck(event.unique_touch_event_id, - event_consumed); + event_consumed, + is_source_touch_event_set_non_blocking); return; } @@ -289,8 +293,9 @@ const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED; if (gesture_provider_) - gesture_provider_->OnTouchEventAck(event.unique_touch_event_id, - event_consumed); + gesture_provider_->OnTouchEventAck( + event.unique_touch_event_id, event_consumed, + InputEventAckStateIsSetNonBlocking(ack_result)); return true; }
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index e1437b4..96ce0c9 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -61,6 +61,7 @@ #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" +#include "content/browser/renderer_host/ui_events_helper.h" #include "content/common/gpu_stream_constants.h" #include "content/common/input_messages.h" #include "content/common/site_isolation_policy.h" @@ -1687,8 +1688,9 @@ void RenderWidgetHostViewAndroid::ProcessAckedTouchEvent( const TouchEventWithLatencyInfo& touch, InputEventAckState ack_result) { const bool event_consumed = ack_result == INPUT_EVENT_ACK_STATE_CONSUMED; - gesture_provider_.OnTouchEventAck(touch.event.unique_touch_event_id, - event_consumed); + gesture_provider_.OnTouchEventAck( + touch.event.unique_touch_event_id, event_consumed, + InputEventAckStateIsSetNonBlocking(ack_result)); } void RenderWidgetHostViewAndroid::GestureEventAck(
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 55fe541..a437295 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -1057,8 +1057,9 @@ for (size_t i = 0; i < touch.event.touches_length; ++i) { if (touch.event.touches[i].state == required_state) { DCHECK(!sent_ack); - host->dispatcher()->ProcessedTouchEvent(touch.event.unique_touch_event_id, - window_, result); + host->dispatcher()->ProcessedTouchEvent( + touch.event.unique_touch_event_id, window_, result, + InputEventAckStateIsSetNonBlocking(ack_result)); sent_ack = true; } }
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index bbb3fe7..a026c33 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -334,10 +334,14 @@ : WindowEventDispatcher(host), processed_touch_event_count_(0) {} - void ProcessedTouchEvent(uint32_t unique_event_id, - aura::Window* window, - ui::EventResult result) override { - WindowEventDispatcher::ProcessedTouchEvent(unique_event_id, window, result); + void ProcessedTouchEvent( + uint32_t unique_event_id, + aura::Window* window, + ui::EventResult result, + bool is_source_touch_event_set_non_blocking) override { + WindowEventDispatcher::ProcessedTouchEvent( + unique_event_id, window, result, + is_source_touch_event_set_non_blocking); processed_touch_event_count_++; }
diff --git a/content/browser/renderer_host/ui_events_helper.cc b/content/browser/renderer_host/ui_events_helper.cc index 8ee439c..9bfc3bb 100644 --- a/content/browser/renderer_host/ui_events_helper.cc +++ b/content/browser/renderer_host/ui_events_helper.cc
@@ -90,4 +90,14 @@ return true; } +bool InputEventAckStateIsSetNonBlocking(InputEventAckState ack_state) { + switch (ack_state) { + case INPUT_EVENT_ACK_STATE_SET_NON_BLOCKING: + case INPUT_EVENT_ACK_STATE_SET_NON_BLOCKING_DUE_TO_FLING: + return true; + default: + return false; + } +} + } // namespace content
diff --git a/content/browser/renderer_host/ui_events_helper.h b/content/browser/renderer_host/ui_events_helper.h index b04a8d35..2123a2a 100644 --- a/content/browser/renderer_host/ui_events_helper.h +++ b/content/browser/renderer_host/ui_events_helper.h
@@ -10,6 +10,7 @@ #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/common/content_export.h" +#include "content/common/input/input_event_ack_state.h" namespace ui { class TouchEvent; @@ -37,6 +38,10 @@ std::vector<std::unique_ptr<ui::TouchEvent>>* list, TouchEventCoordinateSystem coordinate_system); +// Utility to map the event ack state from the renderer, returns true if the +// event could be handled non-blocking. +bool InputEventAckStateIsSetNonBlocking(InputEventAckState); + } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_UI_EVENTS_HELPER_H_
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 872cdd4..43f8dc2 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -45,6 +45,7 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/url_request/url_request_slow_download_job.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" using IPC::IpcSecurityTestUtil; @@ -93,7 +94,7 @@ wc->GetFrameTree()->root()->navigator()->RequestOpenURL( wc->GetFrameTree()->root()->current_frame_host(), extension_url, false, nullptr, std::string(), Referrer(), WindowOpenDisposition::CURRENT_TAB, - false, false, true); + false, false, true, blink::WebTriggeringEventInfo::kFromTrustedEvent); // Since the navigation above requires a cross-process swap, there will be a // speculative/pending RenderFrameHost. Ensure it exists and is in a different
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 1f755b4..b47f556 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -1780,9 +1780,21 @@ event_recorder_.reset(); - bool should_restart = !is_redundant() && !start_callbacks_.empty() && - (old_status != EmbeddedWorkerStatus::STARTING) && - !in_dtor_ && !ping_controller_->IsTimedOut(); + // |start_callbacks_| can be non-empty if a start worker request arrived while + // the worker was stopping. The worker must be restarted to fulfill the + // request. + bool should_restart = !start_callbacks_.empty(); + if (is_redundant() || in_dtor_) { + // This worker will be destroyed soon. + should_restart = false; + } else if (ping_controller_->IsTimedOut()) { + // This worker is unresponsive and restart may fail. + should_restart = false; + } else if (old_status == EmbeddedWorkerStatus::STARTING) { + // This worker unexpectedly stopped because of start failure (e.g., process + // allocation failure) and restart is likely to fail again. + should_restart = false; + } if (!stop_time_.is_null()) { TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::StopWorker",
diff --git a/content/browser/service_worker/service_worker_version.h b/content/browser/service_worker/service_worker_version.h index b02df70e..e53d2169 100644 --- a/content/browser/service_worker/service_worker_version.h +++ b/content/browser/service_worker/service_worker_version.h
@@ -40,16 +40,10 @@ #include "ipc/ipc_message.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerEventResult.h" #include "ui/base/mojo/window_open_disposition.mojom.h" #include "url/gurl.h" #include "url/origin.h" -// Windows headers will redefine SendMessage. -#ifdef SendMessage -#undef SendMessage -#endif - namespace net { class HttpResponseInfo; } @@ -404,13 +398,8 @@ private: friend class base::RefCounted<ServiceWorkerVersion>; - friend class ServiceWorkerJobTest; - friend class ServiceWorkerMetrics; friend class ServiceWorkerReadFromCacheJobTest; - friend class ServiceWorkerStallInStoppingTest; - friend class ServiceWorkerURLRequestJobTest; friend class ServiceWorkerVersionBrowserTest; - friend class ServiceWorkerVersionTest; FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest, ActivateWaitingVersion); @@ -446,7 +435,6 @@ FRIEND_TEST_ALL_PREFIXES(ServiceWorkerActivationTest, SkipWaitingWithInflightRequest); - class Metrics; class PingController; struct RequestInfo { @@ -487,15 +475,11 @@ bool is_dispatched = false; }; - - typedef ServiceWorkerVersion self; using ServiceWorkerClients = std::vector<ServiceWorkerClientInfo>; using RequestInfoPriorityQueue = std::priority_queue<RequestInfo, std::vector<RequestInfo>, std::greater<RequestInfo>>; - using WebStatusCallback = - base::Callback<void(int, blink::WebServiceWorkerEventResult)>; // EmbeddedWorkerInstance Listener implementation which calls a callback // on receiving a particular IPC message. ResponseMessage is the type of
diff --git a/content/browser/webrtc/webrtc_image_capture_browsertest.cc b/content/browser/webrtc/webrtc_image_capture_browsertest.cc index 598d7a5a..0cd11af 100644 --- a/content/browser/webrtc/webrtc_image_capture_browsertest.cc +++ b/content/browser/webrtc/webrtc_image_capture_browsertest.cc
@@ -22,10 +22,6 @@ #if defined(OS_WIN) // These tests are flaky on WebRTC Windows bots: https://crbug.com/633242. -// As a mitigation for https://crbug.com/722038, access to the image capture -// controls has been put behind a feature flag kImageCaptureControls, which is -// disabled by default on Windows. In order to re-activate these tests on -// Windows, this feature must be enabled. #define MAYBE_GetPhotoCapabilities DISABLED_GetPhotoCapabilities #define MAYBE_GetPhotoSettings DISABLED_GetPhotoSettings #define MAYBE_TakePhoto DISABLED_TakePhoto
diff --git a/content/common/DEPS b/content/common/DEPS index 74e46d7..4ce7110 100644 --- a/content/common/DEPS +++ b/content/common/DEPS
@@ -76,5 +76,6 @@ "+third_party/WebKit/public/web/WebSharedWorkerCreationErrors.h", "+third_party/WebKit/public/web/WebTextDirection.h", "+third_party/WebKit/public/web/WebTreeScopeType.h", + "+third_party/WebKit/public/web/WebTriggeringEventInfo.h", "+third_party/WebKit/public/web/win/WebFontRendering.h" ]
diff --git a/content/common/content_security_policy/csp_source_list.cc b/content/common/content_security_policy/csp_source_list.cc index d48b7c77..31a5f496 100644 --- a/content/common/content_security_policy/csp_source_list.cc +++ b/content/common/content_security_policy/csp_source_list.cc
@@ -27,10 +27,7 @@ CSPSourceList::CSPSourceList(bool allow_self, bool allow_star, std::vector<CSPSource> sources) - : allow_self(allow_self), allow_star(allow_star), sources(sources) { - // When the '*' source is used, it must be the only one. - DCHECK(!allow_star || (!allow_self && sources.empty())); -} + : allow_self(allow_self), allow_star(allow_star), sources(sources) {} CSPSourceList::CSPSourceList(const CSPSourceList&) = default; CSPSourceList::~CSPSourceList() = default;
diff --git a/content/common/content_security_policy/csp_source_list_unittest.cc b/content/common/content_security_policy/csp_source_list_unittest.cc index e675263..1f4f001 100644 --- a/content/common/content_security_policy/csp_source_list_unittest.cc +++ b/content/common/content_security_policy/csp_source_list_unittest.cc
@@ -69,6 +69,26 @@ EXPECT_FALSE(Allow(source_list, GURL("ws://example.com"), &context)); } +TEST(CSPSourceList, AllowStarAndSelf) { + CSPContext context; + context.SetSelf(url::Origin(GURL("https://a.com"))); + CSPSourceList source_list(false, // allow_self + false, // allow_star + std::vector<CSPSource>()); + + // If the request is allowed by {*} and not by {'self'} then it should be + // allowed by the union {*,'self'}. + source_list.allow_self = true; + source_list.allow_star = false; + EXPECT_FALSE(Allow(source_list, GURL("http://b.com"), &context)); + source_list.allow_self = false; + source_list.allow_star = true; + EXPECT_TRUE(Allow(source_list, GURL("http://b.com"), &context)); + source_list.allow_self = true; + source_list.allow_star = true; + EXPECT_TRUE(Allow(source_list, GURL("http://b.com"), &context)); +} + TEST(CSPSourceList, AllowSelfWithUnspecifiedPort) { CSPContext context; context.SetSelf(url::Origin(GURL("chrome://print")));
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 92e5d7a..912df59 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -58,6 +58,7 @@ #include "third_party/WebKit/public/web/WebFrameOwnerProperties.h" #include "third_party/WebKit/public/web/WebFrameSerializerCacheControlPolicy.h" #include "third_party/WebKit/public/web/WebTreeScopeType.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/ipc/gfx_param_traits.h" @@ -119,6 +120,8 @@ blink::WebFeaturePolicyFeature::LAST_FEATURE) IPC_ENUM_TRAITS_MAX_VALUE(content::CSPDisposition, content::CSPDisposition::LAST) +IPC_ENUM_TRAITS_MAX_VALUE(blink::WebTriggeringEventInfo, + blink::WebTriggeringEventInfo::kLast) IPC_STRUCT_TRAITS_BEGIN(blink::WebFindOptions) IPC_STRUCT_TRAITS_MEMBER(forward) @@ -456,6 +459,7 @@ IPC_STRUCT_MEMBER(bool, should_replace_current_entry) IPC_STRUCT_MEMBER(bool, user_gesture) IPC_STRUCT_MEMBER(bool, is_history_navigation_in_new_child) + IPC_STRUCT_MEMBER(blink::WebTriggeringEventInfo, triggering_event_info) IPC_STRUCT_END() IPC_STRUCT_BEGIN(FrameHostMsg_DownloadUrl_Params)
diff --git a/content/public/browser/page_navigator.h b/content/public/browser/page_navigator.h index 166a0d51..0f8f474a 100644 --- a/content/public/browser/page_navigator.h +++ b/content/public/browser/page_navigator.h
@@ -19,6 +19,7 @@ #include "content/public/common/referrer.h" #include "content/public/common/resource_request_body.h" #include "ipc/ipc_message.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" #include "ui/base/page_transition_types.h" #include "ui/base/window_open_disposition.h" #include "url/gurl.h" @@ -102,6 +103,11 @@ // gesture if the navigation was initiated by the renderer. bool user_gesture; + // Whether the call to OpenURL was triggered by an Event, and what the + // isTrusted flag of the event was. + blink::WebTriggeringEventInfo triggering_event_info = + blink::WebTriggeringEventInfo::kUnknown; + // Indicates whether this navigation was started via context menu. bool started_from_context_menu;
diff --git a/content/public/test/fake_download_item.cc b/content/public/test/fake_download_item.cc index 49f7bc0..3ce5ff0 100644 --- a/content/public/test/fake_download_item.cc +++ b/content/public/test/fake_download_item.cc
@@ -294,7 +294,6 @@ } const base::FilePath& FakeDownloadItem::GetFullPath() const { - NOTREACHED(); return dummy_file_path; }
diff --git a/content/renderer/fetchers/manifest_fetcher.cc b/content/renderer/fetchers/manifest_fetcher.cc index 0f5fdc9..f809d53 100644 --- a/content/renderer/fetchers/manifest_fetcher.cc +++ b/content/renderer/fetchers/manifest_fetcher.cc
@@ -29,7 +29,11 @@ callback_ = callback; blink::WebAssociatedURLLoaderOptions options; - options.allow_credentials = use_credentials; + // See https://w3c.github.io/manifest/. Use "include" when use_credentials is + // true, and "omit" otherwise. + options.fetch_credentials_mode = + use_credentials ? blink::WebURLRequest::kFetchCredentialsModeInclude + : blink::WebURLRequest::kFetchCredentialsModeOmit; options.fetch_request_mode = blink::WebURLRequest::kFetchRequestModeCORS; fetcher_->SetLoaderOptions(options);
diff --git a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc index 4dfccb4..f992ccd 100644 --- a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc +++ b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc
@@ -35,7 +35,7 @@ fetcher_.reset(AssociatedResourceFetcher::Create(image_url)); WebAssociatedURLLoaderOptions options; - options.allow_credentials = true; + options.fetch_credentials_mode = WebURLRequest::kFetchCredentialsModeInclude; options.fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; fetcher_->SetLoaderOptions(options);
diff --git a/content/renderer/media/android/media_info_loader.cc b/content/renderer/media/android/media_info_loader.cc index 73e2ae0..9e19233 100644 --- a/content/renderer/media/android/media_info_loader.cc +++ b/content/renderer/media/android/media_info_loader.cc
@@ -66,7 +66,8 @@ } else { WebAssociatedURLLoaderOptions options; if (cors_mode_ == blink::WebMediaPlayer::kCORSModeUnspecified) { - options.allow_credentials = true; + request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeInclude); options.fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; allow_stored_credentials_ = true; } else { @@ -76,8 +77,12 @@ WebAssociatedURLLoaderOptions::kPreventPreflight; options.fetch_request_mode = WebURLRequest::kFetchRequestModeCORS; if (cors_mode_ == blink::WebMediaPlayer::kCORSModeUseCredentials) { - options.allow_credentials = true; + request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeInclude); allow_stored_credentials_ = true; + } else { + request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeSameOrigin); } } loader.reset(frame->CreateAssociatedURLLoader(options));
diff --git a/content/renderer/pepper/pepper_url_loader_host.cc b/content/renderer/pepper/pepper_url_loader_host.cc index 7418d35..467902e 100644 --- a/content/renderer/pepper/pepper_url_loader_host.cc +++ b/content/renderer/pepper/pepper_url_loader_host.cc
@@ -267,7 +267,8 @@ WebAssociatedURLLoaderOptions options; if (has_universal_access_) { - options.allow_credentials = true; + options.fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeInclude; options.fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; } else { // All other HTTP requests are untrusted. @@ -275,11 +276,15 @@ if (filled_in_request_data.allow_cross_origin_requests) { // Allow cross-origin requests with access control. The request specifies // if credentials are to be sent. - options.allow_credentials = filled_in_request_data.allow_credentials; + options.fetch_credentials_mode = + filled_in_request_data.allow_credentials + ? WebURLRequest::kFetchCredentialsModeInclude + : WebURLRequest::kFetchCredentialsModeOmit; options.fetch_request_mode = WebURLRequest::kFetchRequestModeCORS; } else { // Same-origin requests can always send credentials. - options.allow_credentials = true; + options.fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeInclude; } }
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index a10d6b0..e3ff259 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -3300,10 +3300,12 @@ Send(new FrameHostMsg_DownloadUrl(params)); } else { + // TODO(csharrison): Plumb triggering_event_info through Blink. OpenURL(request.Url(), IsHttpPost(request), GetRequestBodyForWebURLRequest(request), GetWebURLRequestHeaders(request), referrer, policy, - should_replace_current_entry, false); + should_replace_current_entry, false, + blink::WebTriggeringEventInfo::kUnknown); } } @@ -3456,6 +3458,8 @@ info.is_history_navigation_in_new_child_frame = pending_navigation_info_->history_navigation_in_new_child_frame; info.is_client_redirect = pending_navigation_info_->client_redirect; + info.triggering_event_info = + pending_navigation_info_->triggering_event_info; info.is_cache_disabled = pending_navigation_info_->cache_disabled; info.form = pending_navigation_info_->form; info.source_location = pending_navigation_info_->source_location; @@ -5313,7 +5317,8 @@ OpenURL(url, IsHttpPost(info.url_request), GetRequestBodyForWebURLRequest(info.url_request), GetWebURLRequestHeaders(info.url_request), referrer, - info.default_policy, info.replaces_current_history_item, false); + info.default_policy, info.replaces_current_history_item, false, + info.triggering_event_info); return blink::kWebNavigationPolicyIgnore; // Suppress the load here. } @@ -5346,7 +5351,8 @@ OpenURL(url, IsHttpPost(info.url_request), GetRequestBodyForWebURLRequest(info.url_request), GetWebURLRequestHeaders(info.url_request), referrer, - info.default_policy, info.replaces_current_history_item, true); + info.default_policy, info.replaces_current_history_item, true, + info.triggering_event_info); // Suppress the load in Blink but mark the frame as loading. return blink::kWebNavigationPolicyHandledByClientForInitialHistory; } else { @@ -5411,7 +5417,8 @@ GetRequestBodyForWebURLRequest(info.url_request), GetWebURLRequestHeaders(info.url_request), send_referrer ? referrer : Referrer(), info.default_policy, - info.replaces_current_history_item, false); + info.replaces_current_history_item, false, + info.triggering_event_info); return blink::kWebNavigationPolicyIgnore; // Suppress the load here. } } @@ -5453,7 +5460,8 @@ OpenURL(url, IsHttpPost(info.url_request), GetRequestBodyForWebURLRequest(info.url_request), GetWebURLRequestHeaders(info.url_request), Referrer(), - info.default_policy, info.replaces_current_history_item, false); + info.default_policy, info.replaces_current_history_item, false, + info.triggering_event_info); return blink::kWebNavigationPolicyIgnore; } @@ -5872,7 +5880,8 @@ const Referrer& referrer, WebNavigationPolicy policy, bool should_replace_current_entry, - bool is_history_navigation_in_new_child) { + bool is_history_navigation_in_new_child, + blink::WebTriggeringEventInfo triggering_event_info) { FrameHostMsg_OpenURL_Params params; params.url = url; params.uses_post = uses_post; @@ -5880,6 +5889,7 @@ params.extra_headers = extra_headers; params.referrer = referrer; params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy); + params.triggering_event_info = triggering_event_info; if (IsBrowserInitiated(pending_navigation_params_.get())) { // This is necessary to preserve the should_replace_current_entry value on @@ -6866,6 +6876,7 @@ history_navigation_in_new_child_frame( info.is_history_navigation_in_new_child_frame), client_redirect(info.is_client_redirect), + triggering_event_info(info.triggering_event_info), cache_disabled(info.is_cache_disabled), form(info.form), source_location(info.source_location) {}
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 26feefb7..8d6ebd4c 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -79,6 +79,7 @@ #include "third_party/WebKit/public/web/WebIconURL.h" #include "third_party/WebKit/public/web/WebMeaningfulLayout.h" #include "third_party/WebKit/public/web/WebScriptExecutionCallback.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" #include "ui/gfx/range/range.h" #include "url/gurl.h" #include "url/origin.h" @@ -978,7 +979,8 @@ const Referrer& referrer, blink::WebNavigationPolicy policy, bool should_replace_current_entry, - bool is_history_navigation_in_new_child); + bool is_history_navigation_in_new_child, + blink::WebTriggeringEventInfo triggering_event_info); // Performs a navigation in the frame. This provides a unified function for // the current code path and the browser-side navigation path (in @@ -1392,6 +1394,7 @@ bool replaces_current_history_item; bool history_navigation_in_new_child_frame; bool client_redirect; + blink::WebTriggeringEventInfo triggering_event_info; bool cache_disabled; blink::WebFormElement form; blink::WebSourceLocation source_location;
diff --git a/content/renderer/render_frame_proxy.cc b/content/renderer/render_frame_proxy.cc index 4b08cad..78f1cf4 100644 --- a/content/renderer/render_frame_proxy.cc +++ b/content/renderer/render_frame_proxy.cc
@@ -34,6 +34,7 @@ #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" #include "third_party/WebKit/public/web/WebView.h" @@ -497,6 +498,7 @@ params.disposition = WindowOpenDisposition::CURRENT_TAB; params.should_replace_current_entry = should_replace_current_entry; params.user_gesture = request.HasUserGesture(); + params.triggering_event_info = blink::WebTriggeringEventInfo::kUnknown; Send(new FrameHostMsg_OpenURL(routing_id_, params)); }
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index 8b4c0c5..e631c23 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -68,3 +68,8 @@ ['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=735228) + self.Flaky('Pixel_OffscreenCanvasTransferAfterStyleResize', + ['mac', 'linux', 'win', 'android'], bug=735171)
diff --git a/device/bluetooth/BUILD.gn b/device/bluetooth/BUILD.gn index 25dd04f..67776e1 100644 --- a/device/bluetooth/BUILD.gn +++ b/device/bluetooth/BUILD.gn
@@ -49,6 +49,8 @@ "test/fake_central.h", "test/fake_peripheral.cc", "test/fake_peripheral.h", + "test/fake_remote_gatt_characteristic.cc", + "test/fake_remote_gatt_characteristic.h", "test/fake_remote_gatt_service.cc", "test/fake_remote_gatt_service.h", ]
diff --git a/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom b/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom index bba5e49..cea5fd7 100644 --- a/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom +++ b/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom
@@ -31,9 +31,25 @@ }; // HCI Error Codes from BT 4.2 Vol 2 Part D 1.3 List Of Error Codes. -const uint16 kHCISuccess = 0x0000; +const uint16 kHCISuccess = 0x0000; const uint16 kHCIConnectionTimeout = 0x0008; +// GATT Error codes from BT 4.2 Vol 3 Part F 3.4.1.1 Error Response. +const uint16 kGATTSuccess = 0x0000; +const uint16 kGATTInvalidHandle = 0x0001; + +// Defined in BT 4.2 Vol 3 Part G 3.3.1. Characteristic Properties +struct CharacteristicProperties { + bool broadcast; + bool read; + bool write_without_response; + bool write; + bool notify; + bool indicate; + bool authenticated_signed_writes; + bool extended_properties; +}; + // FakeCentral allows clients to simulate events that a device in the // Central/Observer role would receive as well as monitor the operations // performed by the device in the Central/Observer role. @@ -95,4 +111,28 @@ // add the fake service. AddFakeService(string peripheral_address, UUID service_uuid) => (string? service_id); + + // Adds a fake GATT Characteristic with |characteristic_uuid| and |properties| + // to the fake service with |service_id|. The characteristic will be found + // when discovering the peripheral's GATT Attributes. Runs its callback with + // the fake characteristic's Id. Runs its callback with nullopt if it failed + // to add the fake characteristic. + AddFakeCharacteristic( + UUID characteristic_uuid, + CharacteristicProperties properties, + string service_id, + string peripheral_address) => (string? characteristic_id); + + // Sets the next read response for characteristic with |characteristics_id| + // in |service_id| and in |peripheral_address| to |code| and |value|. + // |code| could be a GATT Error Response from + // BT 4.2 Vol 3 Part F 3.4.1.1 Error Response or a number outside that range + // returned by specific platforms e.g. Android returns 0x101 to signal a GATT + // failure. + // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#GATT_FAILURE + // Calls callback with false if there was any error when simulating the next + // response. + SetNextReadCharacteristicResponse(uint16 gatt_code, array<uint8>? value, + string characteristic_id, string service_id, + string peripheral_address) => (bool success); };
diff --git a/device/bluetooth/test/fake_central.cc b/device/bluetooth/test/fake_central.cc index a3e8cf6..a0901664 100644 --- a/device/bluetooth/test/fake_central.cc +++ b/device/bluetooth/test/fake_central.cc
@@ -14,6 +14,8 @@ #include "device/bluetooth/bluetooth_uuid.h" #include "device/bluetooth/public/interfaces/test/fake_bluetooth.mojom.h" #include "device/bluetooth/test/fake_peripheral.h" +#include "device/bluetooth/test/fake_remote_gatt_characteristic.h" +#include "device/bluetooth/test/fake_remote_gatt_service.h" namespace bluetooth { @@ -89,6 +91,46 @@ std::move(callback).Run(fake_peripheral->AddFakeService(service_uuid)); } +void FakeCentral::AddFakeCharacteristic( + const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties, + const std::string& service_id, + const std::string& peripheral_address, + AddFakeCharacteristicCallback callback) { + auto device_iter = devices_.find(peripheral_address); + if (device_iter == devices_.end()) { + std::move(callback).Run(base::nullopt); + } + + FakeRemoteGattService* fake_remote_gatt_service = + static_cast<FakeRemoteGattService*>( + device_iter->second.get()->GetGattService(service_id)); + if (fake_remote_gatt_service == nullptr) { + std::move(callback).Run(base::nullopt); + } + + std::move(callback).Run(fake_remote_gatt_service->AddFakeCharacteristic( + characteristic_uuid, std::move(properties))); +} + +void FakeCentral::SetNextReadCharacteristicResponse( + uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value, + const std::string& characteristic_id, + const std::string& service_id, + const std::string& peripheral_address, + SetNextReadCharacteristicResponseCallback callback) { + FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic = + GetFakeRemoteGattCharacteristic(peripheral_address, service_id, + characteristic_id); + if (fake_remote_gatt_characteristic == nullptr) { + std::move(callback).Run(false); + } + + fake_remote_gatt_characteristic->SetNextReadResponse(gatt_code, value); + std::move(callback).Run(true); +} + std::string FakeCentral::GetAddress() const { NOTREACHED(); return std::string(); @@ -230,4 +272,24 @@ FakeCentral::~FakeCentral() {} +FakeRemoteGattCharacteristic* FakeCentral::GetFakeRemoteGattCharacteristic( + const std::string& peripheral_address, + const std::string& service_id, + const std::string& characteristic_id) const { + auto device_iter = devices_.find(peripheral_address); + if (device_iter == devices_.end()) { + return nullptr; + } + + FakeRemoteGattService* fake_remote_gatt_service = + static_cast<FakeRemoteGattService*>( + device_iter->second.get()->GetGattService(service_id)); + if (fake_remote_gatt_service == nullptr) { + return nullptr; + } + + return static_cast<FakeRemoteGattCharacteristic*>( + fake_remote_gatt_service->GetCharacteristic(characteristic_id)); +} + } // namespace bluetooth
diff --git a/device/bluetooth/test/fake_central.h b/device/bluetooth/test/fake_central.h index 4786038..ddcd94c 100644 --- a/device/bluetooth/test/fake_central.h +++ b/device/bluetooth/test/fake_central.h
@@ -15,6 +15,8 @@ namespace bluetooth { +class FakeRemoteGattCharacteristic; + // Implementation of FakeCentral in // src/device/bluetooth/public/interfaces/test/fake_bluetooth.mojom. // Implemented on top of the C++ device/bluetooth API, mainly @@ -41,6 +43,18 @@ void AddFakeService(const std::string& peripheral_address, const device::BluetoothUUID& service_uuid, AddFakeServiceCallback callback) override; + void AddFakeCharacteristic(const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties, + const std::string& service_id, + const std::string& peripheral_address, + AddFakeCharacteristicCallback callback) override; + void SetNextReadCharacteristicResponse( + uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value, + const std::string& characteristic_id, + const std::string& service_id, + const std::string& peripheral_address, + SetNextReadCharacteristicResponseCallback callback) override; // BluetoothAdapter overrides: std::string GetAddress() const override; @@ -101,6 +115,11 @@ private: ~FakeCentral() override; + FakeRemoteGattCharacteristic* GetFakeRemoteGattCharacteristic( + const std::string& peripheral_address, + const std::string& service_id, + const std::string& characteristic_id) const; + mojom::CentralState state_; mojo::Binding<mojom::FakeCentral> binding_; };
diff --git a/device/bluetooth/test/fake_peripheral.cc b/device/bluetooth/test/fake_peripheral.cc index 98ccb84..364db3e 100644 --- a/device/bluetooth/test/fake_peripheral.cc +++ b/device/bluetooth/test/fake_peripheral.cc
@@ -6,8 +6,9 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" -#include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" #include "device/bluetooth/bluetooth_uuid.h" #include "device/bluetooth/test/fake_remote_gatt_service.h" @@ -50,7 +51,9 @@ std::string FakePeripheral::AddFakeService( const device::BluetoothUUID& service_uuid) { - std::string new_service_id = base::SizeTToString(++last_service_id_); + // Attribute instance Ids need to be unique. + std::string new_service_id = + base::StringPrintf("%s_%zu", GetAddress().c_str(), ++last_service_id_); GattServiceMap::iterator it; bool inserted;
diff --git a/device/bluetooth/test/fake_remote_gatt_characteristic.cc b/device/bluetooth/test/fake_remote_gatt_characteristic.cc new file mode 100644 index 0000000..97fa0ecd --- /dev/null +++ b/device/bluetooth/test/fake_remote_gatt_characteristic.cc
@@ -0,0 +1,153 @@ +// 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 "device/bluetooth/test/fake_remote_gatt_characteristic.h" + +#include <utility> +#include <vector> + +#include "base/optional.h" +#include "device/bluetooth/bluetooth_uuid.h" +#include "device/bluetooth/public/interfaces/test/fake_bluetooth.mojom.h" + +namespace bluetooth { + +FakeRemoteGattCharacteristic::FakeRemoteGattCharacteristic( + const std::string& characteristic_id, + const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties, + device::BluetoothRemoteGattService* service) + : characteristic_id_(characteristic_id), + characteristic_uuid_(characteristic_uuid), + service_(service), + weak_ptr_factory_(this) { + properties_ = PROPERTY_NONE; + if (properties->broadcast) + properties_ |= PROPERTY_BROADCAST; + if (properties->read) + properties_ |= PROPERTY_READ; + if (properties->write_without_response) + properties_ |= PROPERTY_WRITE_WITHOUT_RESPONSE; + if (properties->write) + properties_ |= PROPERTY_WRITE; + if (properties->notify) + properties_ |= PROPERTY_NOTIFY; + if (properties->indicate) + properties_ |= PROPERTY_INDICATE; + if (properties->authenticated_signed_writes) + properties_ |= PROPERTY_AUTHENTICATED_SIGNED_WRITES; + if (properties->extended_properties) + properties_ |= PROPERTY_EXTENDED_PROPERTIES; +} + +FakeRemoteGattCharacteristic::~FakeRemoteGattCharacteristic() {} + +void FakeRemoteGattCharacteristic::SetNextReadResponse( + uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value) { + DCHECK(!next_read_response_); + next_read_response_.emplace(gatt_code, value); +} + +std::string FakeRemoteGattCharacteristic::GetIdentifier() const { + return characteristic_id_; +} + +device::BluetoothUUID FakeRemoteGattCharacteristic::GetUUID() const { + return characteristic_uuid_; +} + +FakeRemoteGattCharacteristic::Properties +FakeRemoteGattCharacteristic::GetProperties() const { + return properties_; +} + +FakeRemoteGattCharacteristic::Permissions +FakeRemoteGattCharacteristic::GetPermissions() const { + NOTREACHED(); + return PERMISSION_NONE; +} + +const std::vector<uint8_t>& FakeRemoteGattCharacteristic::GetValue() const { + NOTREACHED(); + return value_; +} + +device::BluetoothRemoteGattService* FakeRemoteGattCharacteristic::GetService() + const { + return service_; +} + +std::vector<device::BluetoothRemoteGattDescriptor*> +FakeRemoteGattCharacteristic::GetDescriptors() const { + NOTREACHED(); + return std::vector<device::BluetoothRemoteGattDescriptor*>(); +} + +device::BluetoothRemoteGattDescriptor* +FakeRemoteGattCharacteristic::GetDescriptor( + const std::string& identifier) const { + NOTREACHED(); + return nullptr; +} + +void FakeRemoteGattCharacteristic::ReadRemoteCharacteristic( + const ValueCallback& callback, + const ErrorCallback& error_callback) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(&FakeRemoteGattCharacteristic::DispatchReadResponse, + weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); +} + +void FakeRemoteGattCharacteristic::WriteRemoteCharacteristic( + const std::vector<uint8_t>& value, + const base::Closure& callback, + const ErrorCallback& error_callback) { + NOTREACHED(); +} + +void FakeRemoteGattCharacteristic::SubscribeToNotifications( + device::BluetoothRemoteGattDescriptor* ccc_descriptor, + const base::Closure& callback, + const ErrorCallback& error_callback) { + NOTREACHED(); +} + +void FakeRemoteGattCharacteristic::UnsubscribeFromNotifications( + device::BluetoothRemoteGattDescriptor* ccc_descriptor, + const base::Closure& callback, + const ErrorCallback& error_callback) { + NOTREACHED(); +} + +void FakeRemoteGattCharacteristic::DispatchReadResponse( + const ValueCallback& callback, + const ErrorCallback& error_callback) { + DCHECK(next_read_response_); + uint16_t gatt_code = next_read_response_->gatt_code; + base::Optional<std::vector<uint8_t>> value = + std::move(next_read_response_->value); + next_read_response_.reset(); + + if (gatt_code == mojom::kGATTSuccess) { + DCHECK(value); + value_ = std::move(value.value()); + callback.Run(value_); + return; + } else if (gatt_code == mojom::kGATTInvalidHandle) { + DCHECK(!value); + error_callback.Run(device::BluetoothGattService::GATT_ERROR_FAILED); + return; + } +} + +FakeRemoteGattCharacteristic::ReadResponse::ReadResponse( + uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value) + : gatt_code(gatt_code), value(value) {} + +FakeRemoteGattCharacteristic::ReadResponse::~ReadResponse() {} + +} // namespace bluetooth
diff --git a/device/bluetooth/test/fake_remote_gatt_characteristic.h b/device/bluetooth/test/fake_remote_gatt_characteristic.h new file mode 100644 index 0000000..c57017c --- /dev/null +++ b/device/bluetooth/test/fake_remote_gatt_characteristic.h
@@ -0,0 +1,100 @@ +// 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 DEVICE_BLUETOOTH_TEST_FAKE_REMOTE_GATT_CHARACTERISTIC_H_ +#define DEVICE_BLUETOOTH_TEST_FAKE_REMOTE_GATT_CHARACTERISTIC_H_ + +#include <string> +#include <vector> + +#include "base/memory/weak_ptr.h" +#include "device/bluetooth/bluetooth_remote_gatt_characteristic.h" +#include "device/bluetooth/bluetooth_uuid.h" +#include "device/bluetooth/public/interfaces/test/fake_bluetooth.mojom.h" + +namespace device { +class BluetoothRemoteGattService; +class BluetoothRemoteGattDescriptor; +} // namespace device + +namespace bluetooth { + +// Implements device::BluetoothRemoteGattCharacteristics. Meant to be used +// by FakeRemoteGattService to keep track of the characteristic's state and +// attributes. +class FakeRemoteGattCharacteristic + : public device::BluetoothRemoteGattCharacteristic { + public: + FakeRemoteGattCharacteristic(const std::string& characteristic_id, + const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties, + device::BluetoothRemoteGattService* service); + ~FakeRemoteGattCharacteristic() override; + + // If |gatt_code| is mojom::kGATTSuccess the next read request will call + // its success callback with |value|. Otherwise it will call its error + // callback. + void SetNextReadResponse(uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value); + + // device::BluetoothGattCharacteristic overrides: + std::string GetIdentifier() const override; + device::BluetoothUUID GetUUID() const override; + Properties GetProperties() const override; + Permissions GetPermissions() const override; + + // device::BluetoothRemoteGattCharacteristic overrides: + const std::vector<uint8_t>& GetValue() const override; + device::BluetoothRemoteGattService* GetService() const override; + std::vector<device::BluetoothRemoteGattDescriptor*> GetDescriptors() + const override; + device::BluetoothRemoteGattDescriptor* GetDescriptor( + const std::string& identifier) const override; + void ReadRemoteCharacteristic(const ValueCallback& callback, + const ErrorCallback& error_callback) override; + void WriteRemoteCharacteristic(const std::vector<uint8_t>& value, + const base::Closure& callback, + const ErrorCallback& error_callback) override; + + protected: + // device::BluetoothRemoteGattCharacteristic overrides: + void SubscribeToNotifications( + device::BluetoothRemoteGattDescriptor* ccc_descriptor, + const base::Closure& callback, + const ErrorCallback& error_callback) override; + void UnsubscribeFromNotifications( + device::BluetoothRemoteGattDescriptor* ccc_descriptor, + const base::Closure& callback, + const ErrorCallback& error_callback) override; + + private: + void DispatchReadResponse(const ValueCallback& callback, + const ErrorCallback& error_callback); + + const std::string characteristic_id_; + const device::BluetoothUUID characteristic_uuid_; + Properties properties_; + device::BluetoothRemoteGattService* service_; + std::vector<uint8_t> value_; + + struct ReadResponse { + ReadResponse(uint16_t gatt_code, + const base::Optional<std::vector<uint8_t>>& value); + ~ReadResponse(); + + uint16_t gatt_code; + base::Optional<std::vector<uint8_t>> value; + + DISALLOW_COPY_AND_ASSIGN(ReadResponse); + }; + + // Used to decide which callback should be called when + // ReadRemoteCharacteristic is called. + base::Optional<ReadResponse> next_read_response_; + + base::WeakPtrFactory<FakeRemoteGattCharacteristic> weak_ptr_factory_; +}; + +} // namespace bluetooth + +#endif // DEVICE_BLUETOOTH_TEST_FAKE_REMOTE_GATT_CHARACTERISTIC_H_
diff --git a/device/bluetooth/test/fake_remote_gatt_service.cc b/device/bluetooth/test/fake_remote_gatt_service.cc index 151c544..83dae00 100644 --- a/device/bluetooth/test/fake_remote_gatt_service.cc +++ b/device/bluetooth/test/fake_remote_gatt_service.cc
@@ -4,10 +4,17 @@ #include "device/bluetooth/test/fake_remote_gatt_service.h" +#include <map> +#include <memory> +#include <utility> #include <vector> +#include "base/memory/ptr_util.h" +#include "base/strings/stringprintf.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_uuid.h" +#include "device/bluetooth/public/interfaces/test/fake_bluetooth.mojom.h" +#include "device/bluetooth/test/fake_remote_gatt_characteristic.h" namespace bluetooth { @@ -19,10 +26,30 @@ : service_id_(service_id), service_uuid_(service_uuid), is_primary_(is_primary), - device_(device) {} + device_(device), + last_characteristic_id_(0) {} FakeRemoteGattService::~FakeRemoteGattService() {} +std::string FakeRemoteGattService::AddFakeCharacteristic( + const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties) { + FakeCharacteristicMap::iterator it; + bool inserted; + + // Attribute instance Ids need to be unique. + std::string new_characteristic_id = base::StringPrintf( + "%s_%zu", GetIdentifier().c_str(), ++last_characteristic_id_); + + std::tie(it, inserted) = fake_characteristics_.emplace( + new_characteristic_id, base::MakeUnique<FakeRemoteGattCharacteristic>( + new_characteristic_id, characteristic_uuid, + std::move(properties), this)); + + DCHECK(inserted); + return it->second->GetIdentifier(); +} + std::string FakeRemoteGattService::GetIdentifier() const { return service_id_; } @@ -41,8 +68,10 @@ std::vector<device::BluetoothRemoteGattCharacteristic*> FakeRemoteGattService::GetCharacteristics() const { - NOTREACHED(); - return std::vector<device::BluetoothRemoteGattCharacteristic*>(); + std::vector<device::BluetoothRemoteGattCharacteristic*> characteristics; + for (const auto& it : fake_characteristics_) + characteristics.push_back(it.second.get()); + return characteristics; } std::vector<device::BluetoothRemoteGattService*> @@ -53,8 +82,11 @@ device::BluetoothRemoteGattCharacteristic* FakeRemoteGattService::GetCharacteristic(const std::string& identifier) const { - NOTREACHED(); - return nullptr; + const auto& it = fake_characteristics_.find(identifier); + if (it == fake_characteristics_.end()) + return nullptr; + + return it->second.get(); } } // namespace bluetooth
diff --git a/device/bluetooth/test/fake_remote_gatt_service.h b/device/bluetooth/test/fake_remote_gatt_service.h index 35fb901..a966cc1 100644 --- a/device/bluetooth/test/fake_remote_gatt_service.h +++ b/device/bluetooth/test/fake_remote_gatt_service.h
@@ -4,11 +4,15 @@ #ifndef DEVICE_BLUETOOTH_TEST_FAKE_REMOTE_GATT_SERVICE_H_ #define DEVICE_BLUETOOTH_TEST_FAKE_REMOTE_GATT_SERVICE_H_ +#include <map> +#include <memory> #include <string> #include <vector> #include "device/bluetooth/bluetooth_remote_gatt_service.h" #include "device/bluetooth/bluetooth_uuid.h" +#include "device/bluetooth/public/interfaces/test/fake_bluetooth.mojom.h" +#include "device/bluetooth/test/fake_remote_gatt_characteristic.h" namespace device { class BluetoothDevice; @@ -28,6 +32,12 @@ device::BluetoothDevice* device); ~FakeRemoteGattService() override; + // Adds a fake characteristic with |characteristic_uuid| and |properties| + // to this service. Returns the characteristic's Id. + std::string AddFakeCharacteristic( + const device::BluetoothUUID& characteristic_uuid, + mojom::CharacteristicPropertiesPtr properties); + // device::BluetoothGattService overrides: std::string GetIdentifier() const override; device::BluetoothUUID GetUUID() const override; @@ -47,6 +57,12 @@ const device::BluetoothUUID service_uuid_; const bool is_primary_; device::BluetoothDevice* device_; + + size_t last_characteristic_id_; + + using FakeCharacteristicMap = + std::map<std::string, std::unique_ptr<FakeRemoteGattCharacteristic>>; + FakeCharacteristicMap fake_characteristics_; }; } // namespace bluetooth
diff --git a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.cc b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.cc index 22b266b..d9991a4 100644 --- a/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.cc +++ b/extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.cc
@@ -149,11 +149,14 @@ return; blink::WebFrame* frame = render_frame()->GetWebFrame(); + blink::WebAssociatedURLLoaderOptions options; // The embedded plugin is allowed to be cross-origin and we should always // send credentials/cookies with the request. options.fetch_request_mode = blink::WebURLRequest::kFetchRequestModeNoCORS; - options.allow_credentials = true; + options.fetch_credentials_mode = + blink::WebURLRequest::kFetchCredentialsModeInclude; + DCHECK(!loader_); loader_.reset(frame->CreateAssociatedURLLoader(options));
diff --git a/gpu/command_buffer/client/gles2_implementation.cc b/gpu/command_buffer/client/gles2_implementation.cc index afabb983..5d90ce2 100644 --- a/gpu/command_buffer/client/gles2_implementation.cc +++ b/gpu/command_buffer/client/gles2_implementation.cc
@@ -6236,6 +6236,8 @@ return capabilities.texture_format_dxt5; case GL_ETC1_RGB8_OES: return capabilities.texture_format_etc1; + case GL_R16_EXT: + return capabilities.texture_norm16; case GL_RED: case GL_RG_EXT: case GL_RGB:
diff --git a/gpu/command_buffer/common/gpu_memory_buffer_support.cc b/gpu/command_buffer/common/gpu_memory_buffer_support.cc index 481f0b2..2c96f1df 100644 --- a/gpu/command_buffer/common/gpu_memory_buffer_support.cc +++ b/gpu/command_buffer/common/gpu_memory_buffer_support.cc
@@ -18,6 +18,8 @@ switch (internalformat) { case GL_RED_EXT: return gfx::BufferFormat::R_8; + case GL_R16_EXT: + return gfx::BufferFormat::R_16; case GL_RG_EXT: return gfx::BufferFormat::RG_88; case GL_RGB: @@ -62,6 +64,7 @@ case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::YVU_420: @@ -96,6 +99,8 @@ return capabilities.texture_format_dxt5; case gfx::BufferFormat::ETC1: return capabilities.texture_format_etc1; + case gfx::BufferFormat::R_16: + return capabilities.texture_norm16; case gfx::BufferFormat::R_8: case gfx::BufferFormat::RG_88: return capabilities.texture_rg; @@ -135,6 +140,7 @@ // by the block size. return size.width() % 4 == 0 && size.height() % 4 == 0; case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444:
diff --git a/gpu/command_buffer/tests/gl_gpu_memory_buffer_unittest.cc b/gpu/command_buffer/tests/gl_gpu_memory_buffer_unittest.cc index b994f45..3f585cdb 100644 --- a/gpu/command_buffer/tests/gl_gpu_memory_buffer_unittest.cc +++ b/gpu/command_buffer/tests/gl_gpu_memory_buffer_unittest.cc
@@ -139,6 +139,7 @@ case gfx::BufferFormat::DXT1: case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::RGBX_8888: case gfx::BufferFormat::UYVY_422: @@ -155,6 +156,8 @@ switch (format) { case gfx::BufferFormat::R_8: return GL_RED; + case gfx::BufferFormat::R_16: + return GL_R16_EXT; case gfx::BufferFormat::RG_88: return GL_RG; case gfx::BufferFormat::BGR_565:
diff --git a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc index 54423d5..d138b1d 100644 --- a/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc +++ b/gpu/ipc/client/gpu_memory_buffer_impl_shared_memory.cc
@@ -129,6 +129,7 @@ // by the block size. return size.width() % 4 == 0 && size.height() % 4 == 0; case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444:
diff --git a/gpu/ipc/host/gpu_memory_buffer_support.cc b/gpu/ipc/host/gpu_memory_buffer_support.cc index 66884870..55c42a8 100644 --- a/gpu/ipc/host/gpu_memory_buffer_support.cc +++ b/gpu/ipc/host/gpu_memory_buffer_support.cc
@@ -38,11 +38,17 @@ #if defined(USE_OZONE) || defined(OS_MACOSX) if (AreNativeGpuMemoryBuffersEnabled()) { const gfx::BufferFormat kNativeFormats[] = { - gfx::BufferFormat::R_8, gfx::BufferFormat::RG_88, - gfx::BufferFormat::BGR_565, gfx::BufferFormat::RGBA_4444, - gfx::BufferFormat::RGBA_8888, gfx::BufferFormat::BGRA_8888, - gfx::BufferFormat::RGBA_F16, gfx::BufferFormat::UYVY_422, - gfx::BufferFormat::YVU_420, gfx::BufferFormat::YUV_420_BIPLANAR}; + gfx::BufferFormat::R_8, + gfx::BufferFormat::RG_88, + gfx::BufferFormat::R_16, + gfx::BufferFormat::BGR_565, + gfx::BufferFormat::RGBA_4444, + gfx::BufferFormat::RGBA_8888, + gfx::BufferFormat::BGRA_8888, + gfx::BufferFormat::RGBA_F16, + gfx::BufferFormat::UYVY_422, + gfx::BufferFormat::YVU_420, + gfx::BufferFormat::YUV_420_BIPLANAR}; const gfx::BufferUsage kNativeUsages[] = { gfx::BufferUsage::GPU_READ, gfx::BufferUsage::SCANOUT, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 8d7a651ad..4d9cae32 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -1931,7 +1931,6 @@ DCHECK(_localStatePrefObserverBridge); _settingsNavigationController = [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:_mainBrowserState - currentBrowserState:self.currentBrowserState delegate:self]; [[self topPresentedViewController] presentViewController:_settingsNavigationController
diff --git a/ios/chrome/browser/experimental_flags.h b/ios/chrome/browser/experimental_flags.h index 1f8875bee..6f1800d 100644 --- a/ios/chrome/browser/experimental_flags.h +++ b/ios/chrome/browser/experimental_flags.h
@@ -103,9 +103,6 @@ // Whether Bookmark reordering is enabled. bool IsBookmarkReorderingEnabled(); -// Whether Google Native App Launcher is enabled. -bool IsNativeAppLauncherEnabled(); - // Whether a new version of FeedbackKit is the preferred feedback UI provider. bool IsNewFeedbackKitEnabled();
diff --git a/ios/chrome/browser/experimental_flags.mm b/ios/chrome/browser/experimental_flags.mm index 01ed7db..3880c977 100644 --- a/ios/chrome/browser/experimental_flags.mm +++ b/ios/chrome/browser/experimental_flags.mm
@@ -281,11 +281,6 @@ return false; } -bool IsNativeAppLauncherEnabled() { - return [[NSUserDefaults standardUserDefaults] - boolForKey:@"NativeAppLauncherEnabled"]; -} - bool IsNewFeedbackKitEnabled() { return [[NSUserDefaults standardUserDefaults] boolForKey:@"NewFeedbackKitEnabled"];
diff --git a/ios/chrome/browser/metrics/BUILD.gn b/ios/chrome/browser/metrics/BUILD.gn index feff38a2..5b55c011 100644 --- a/ios/chrome/browser/metrics/BUILD.gn +++ b/ios/chrome/browser/metrics/BUILD.gn
@@ -93,8 +93,6 @@ "size_class_recorder.h", "size_class_recorder.mm", "size_class_recorder_private.h", - "tab_usage_recorder.h", - "tab_usage_recorder.mm", "tab_usage_recorder_delegate.h", ] deps = [ @@ -111,17 +109,41 @@ ] public_deps = [ ":metrics_internal_arc", + ":metrics_internal_noarc", ] - allow_circular_includes_from = [ ":metrics_internal_arc" ] + allow_circular_includes_from = [ + ":metrics_internal_arc", + ":metrics_internal_noarc", + ] libs = [ "UIKit.framework" ] } +source_set("metrics_internal_noarc") { + # TODO(crbug.com/731724) This target shouldn't be compiled with ARC until + # after it's converted to use WebStates instead of Tabs. + cflags_objc = [ "-fno-objc-arc" ] + + sources = [ + "tab_usage_recorder.h", + "tab_usage_recorder.mm", + ] + + deps = [ + ":metrics", + "//base", + "//ios/chrome/browser", + "//ios/chrome/browser/tabs", + "//ios/web", + ] +} + source_set("metrics_internal_arc") { sources = [ "tab_usage_recorder_web_state_list_observer.h", "tab_usage_recorder_web_state_list_observer.mm", ] deps = [ + ":metrics_internal_noarc", "//base", "//ios/chrome/browser/tabs", "//ios/chrome/browser/web_state_list",
diff --git a/ios/chrome/browser/metrics/tab_usage_recorder.mm b/ios/chrome/browser/metrics/tab_usage_recorder.mm index f4d1b87..2b73c672 100644 --- a/ios/chrome/browser/metrics/tab_usage_recorder.mm +++ b/ios/chrome/browser/metrics/tab_usage_recorder.mm
@@ -13,10 +13,6 @@ #import "ios/web/public/web_state/web_state.h" #import "ios/web/web_state/ui/crw_web_controller.h" -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - const char kTabUsageHistogramPrefix[] = "Tab"; // The histogram recording the state of the tab the user switches to.
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_store_factory.cc b/ios/chrome/browser/passwords/ios_chrome_password_store_factory.cc index 9377637..d5d74614 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_store_factory.cc +++ b/ios/chrome/browser/passwords/ios_chrome_password_store_factory.cc
@@ -14,9 +14,9 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/password_manager/core/browser/affiliated_match_helper.h" -#include "components/password_manager/core/browser/affiliation_service.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliated_match_helper.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_service.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/login_database.h" #include "components/password_manager/core/browser/password_store_default.h" #include "components/password_manager/core/browser/password_store_factory_util.h"
diff --git a/ios/chrome/browser/resources/Settings.bundle/Experimental.plist b/ios/chrome/browser/resources/Settings.bundle/Experimental.plist index 457b5c0..4176a698 100644 --- a/ios/chrome/browser/resources/Settings.bundle/Experimental.plist +++ b/ios/chrome/browser/resources/Settings.bundle/Experimental.plist
@@ -482,16 +482,6 @@ </dict> <dict> <key>Type</key> - <string>PSToggleSwitchSpecifier</string> - <key>Title</key> - <string>Enable Native App Launcher</string> - <key>Key</key> - <string>NativeAppLauncherEnabled</string> - <key>DefaultValue</key> - <false/> - </dict> - <dict> - <key>Type</key> <string>PSTextFieldSpecifier</string> <key>Title</key> <string>Origin Server Host</string>
diff --git a/ios/chrome/browser/tabs/tab.h b/ios/chrome/browser/tabs/tab.h index b7a857b..a768a15 100644 --- a/ios/chrome/browser/tabs/tab.h +++ b/ios/chrome/browser/tabs/tab.h
@@ -26,7 +26,6 @@ @class FullScreenController; @protocol FullScreenControllerDelegate; class GURL; -@class NativeAppNavigationController; @class OpenInController; @class OverscrollActionsController; @protocol OverscrollActionsControllerDelegate; @@ -284,9 +283,6 @@ // Called when the snapshot of the content will be taken. - (void)willUpdateSnapshot; -// Returns the NativeAppNavigationController for this tab. -- (NativeAppNavigationController*)nativeAppNavigationController; - // Called when this tab is shown. - (void)wasShown;
diff --git a/ios/chrome/browser/tabs/tab.mm b/ios/chrome/browser/tabs/tab.mm index 07b97175..b34088d 100644 --- a/ios/chrome/browser/tabs/tab.mm +++ b/ios/chrome/browser/tabs/tab.mm
@@ -60,7 +60,6 @@ #include "ios/chrome/browser/history/top_sites_factory.h" #include "ios/chrome/browser/infobars/infobar_manager_impl.h" #import "ios/chrome/browser/metrics/tab_usage_recorder.h" -#import "ios/chrome/browser/native_app_launcher/native_app_navigation_controller.h" #import "ios/chrome/browser/passwords/password_controller.h" #import "ios/chrome/browser/passwords/passwords_ui_delegate_impl.h" #include "ios/chrome/browser/pref_names.h" @@ -69,8 +68,6 @@ #include "ios/chrome/browser/sessions/ios_chrome_session_tab_helper.h" #include "ios/chrome/browser/signin/account_consistency_service_factory.h" #include "ios/chrome/browser/signin/account_reconcilor_factory.h" -#include "ios/chrome/browser/signin/authentication_service.h" -#include "ios/chrome/browser/signin/authentication_service_factory.h" #include "ios/chrome/browser/signin/signin_capability.h" #import "ios/chrome/browser/snapshots/snapshot_manager.h" #import "ios/chrome/browser/snapshots/snapshot_overlay_provider.h" @@ -105,9 +102,6 @@ #include "ios/chrome/browser/web/print_observer.h" #import "ios/chrome/browser/xcallback_parameters.h" #include "ios/chrome/grit/ios_strings.h" -#include "ios/public/provider/chrome/browser/chrome_browser_provider.h" -#import "ios/public/provider/chrome/browser/native_app_launcher/native_app_metadata.h" -#import "ios/public/provider/chrome/browser/native_app_launcher/native_app_whitelist_manager.h" #import "ios/web/navigation/navigation_item_impl.h" #import "ios/web/navigation/navigation_manager_impl.h" #include "ios/web/public/favicon_status.h" @@ -264,9 +258,6 @@ // Handles autofill. AutofillController* _autofillController; - // Handles GAL infobar on web pages. - NativeAppNavigationController* _nativeAppNavigationController; - // Handles caching and retrieving of snapshots. SnapshotManager* _snapshotManager; @@ -327,9 +318,6 @@ // Returns the OpenInController for this tab. - (OpenInController*)openInController; -// Initialize the Native App Launcher controller. -- (void)initNativeAppNavigationController; - // Handles exportable files if possible. - (void)handleExportableFile:(net::HttpResponseHeaders*)headers; @@ -477,9 +465,6 @@ initWithSnapshotManager:_snapshotManager tab:self]; - if (experimental_flags::IsNativeAppLauncherEnabled()) - [self initNativeAppNavigationController]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) @@ -1550,41 +1535,6 @@ return YES; } -- (BOOL)urlTriggersNativeAppLaunch:(const GURL&)url - sourceURL:(const GURL&)sourceURL - linkClicked:(BOOL)linkClicked { - // TODO(crbug/711511): If Native App Launcher is not enabled, returning NO - // bypasses all Link Navigation logic. This call should eventually be - // eliminated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return NO; - - // Don't open any native app directly when prerendering or from Incognito. - if (_isPrerenderTab || self.browserState->IsOffTheRecord()) - return NO; - - id<NativeAppMetadata> metadata = - [ios::GetChromeBrowserProvider()->GetNativeAppWhitelistManager() - nativeAppForURL:url]; - if (![metadata shouldAutoOpenLinks]) - return NO; - - AuthenticationService* authenticationService = - AuthenticationServiceFactory::GetForBrowserState(self.browserState); - ChromeIdentity* identity = authenticationService->GetAuthenticatedIdentity(); - - // Attempts to open external app without x-callback. - if ([self openExternalURL:[metadata launchURLWithURL:url identity:identity] - sourceURL:sourceURL - linkClicked:linkClicked]) { - return YES; - } - - // Auto-open didn't work. Reset the auto-open flag. - [metadata unsetShouldAutoOpenLinks]; - return NO; -} - - (double)lastVisitedTimestamp { return _lastVisitedTimestamp; } @@ -1844,23 +1794,6 @@ } } -- (NativeAppNavigationController*)nativeAppNavigationController { - // TODO(crbug.com/711511): If Native App Launcher is not enabled, simply - // return nil here. This method should eventually be eliminated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return nil; - return _nativeAppNavigationController; -} - -- (void)initNativeAppNavigationController { - if (_browserState->IsOffTheRecord()) - return; - DCHECK(!_nativeAppNavigationController); - _nativeAppNavigationController = - [[NativeAppNavigationController alloc] initWithWebState:self.webState]; - DCHECK(_nativeAppNavigationController); -} - - (void)wasShown { _visible = YES; [self updateFullscreenWithToolbarVisible:YES];
diff --git a/ios/chrome/browser/tabs/tab_unittest.mm b/ios/chrome/browser/tabs/tab_unittest.mm index 56de9c7..6b9c2a8b 100644 --- a/ios/chrome/browser/tabs/tab_unittest.mm +++ b/ios/chrome/browser/tabs/tab_unittest.mm
@@ -21,7 +21,6 @@ #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state_manager.h" #import "ios/chrome/browser/chrome_url_util.h" -#include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/history/history_service_factory.h" #import "ios/chrome/browser/tabs/legacy_tab_helper.h" #import "ios/chrome/browser/tabs/tab.h" @@ -32,11 +31,8 @@ #import "ios/chrome/browser/ui/open_in_controller_testing.h" #import "ios/chrome/browser/web/external_app_launcher.h" #include "ios/chrome/test/block_cleanup_test.h" -#include "ios/chrome/test/ios_chrome_scoped_testing_chrome_browser_provider.h" #include "ios/chrome/test/ios_chrome_scoped_testing_chrome_browser_state_manager.h" #include "ios/chrome/test/ios_chrome_scoped_testing_local_state.h" -#import "ios/public/provider/chrome/browser/native_app_launcher/fake_native_app_metadata.h" -#import "ios/public/provider/chrome/browser/native_app_launcher/fake_native_app_whitelist_manager.h" #include "ios/public/provider/chrome/browser/test_chrome_browser_provider.h" #import "ios/testing/ocmock_complex_type_helper.h" #import "ios/web/navigation/navigation_manager_impl.h" @@ -142,24 +138,6 @@ HistoryQueryResultsObserver::~HistoryQueryResultsObserver() {} -class FakeChromeBrowserProvider : public ios::TestChromeBrowserProvider { - public: - FakeChromeBrowserProvider(id<NativeAppMetadata> metadata) { - FakeNativeAppWhitelistManager* fakeManager = - [[FakeNativeAppWhitelistManager alloc] init]; - fakeManager.metadata = metadata; - manager_.reset(fakeManager); - } - ~FakeChromeBrowserProvider() override {} - - id<NativeAppWhitelistManager> GetNativeAppWhitelistManager() const override { - return manager_; - } - - private: - base::scoped_nsprotocol<id<NativeAppWhitelistManager>> manager_; -}; - // TODO(crbug.com/620465): can a TestWebState be used instead of a WebStateImpl // for those tests? This will require changing Tab to use a WebState instead of // a WebStateImpl first though. @@ -422,172 +400,4 @@ EXPECT_NSEQ(@"Document.pdf", [[tab_ openInController] suggestedFilename]); } -// A separate test fixture is used to test opening external URLs using Google -// App Launcher. In any of the tests for this feature, scenarios have to be -// tested with the regular ChromeBrowserState AND the incognito -// ChromeBrowserState. -// In Incognito, -urlTriggersNativeAppLaunch:sourceURL should always return NO. -class TabOpenAppTest : public TabTest { - protected: - // Tests that calling |urlTriggersNativeAppLaunch:sourceURL:linkClicked| calls - // |openURL:| the expected number of times. |return_value| is the value to be - // returned from |openURL:|. |expected_result| is the value that is checked - // for from |urlTriggersNativeAppLaunch:sourceURL:linkClicked|. - void TestOpenNativeAppURL(const GURL& url, - BOOL return_value, - NSUInteger expected_tab_call_count, - BOOL expected_result) { - ExpectWithMockedExternalAppLauncherOpenURL( - return_value, expected_tab_call_count, ^{ - EXPECT_EQ(expected_result, - [tab_ urlTriggersNativeAppLaunch:url - sourceURL:GURL("http://google.com") - linkClicked:YES]); - }); - } - - // Stubs out |openURL:| and checks how many times it was called. - void ExpectWithMockedExternalAppLauncherOpenURL( - BOOL return_value, - NSUInteger expected_tab_call_count, - ProceduralBlock expectation_block) { - __block NSUInteger counter = 0; - [mock_external_app_launcher_ - onSelector:@selector(openURL:linkClicked:) - callBlockExpectation:(id) ^ (const GURL& url, BOOL linkClicked) { - ++counter; - return return_value; - }]; - expectation_block(); - EXPECT_EQ(expected_tab_call_count, counter); - [mock_external_app_launcher_ - removeBlockExpectationOnSelector:@selector(openURL:linkClicked:)]; - } -}; - -// A version of TabOpenAppTests customized to use the off-the-record browser -// state (instead of the non-incognito one). -class TabOpenAppOffTheRecordTest : public TabOpenAppTest { - private: - bool UseOffTheRecordBrowserState() const override { return true; } -}; - -// Tests the opening of matching native apps. -TEST_F(TabOpenAppTest, testDummyURL) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - EXPECT_FALSE([tab_ browserState]->IsOffTheRecord()); - - GURL no_native_app_url("dummy string"); - TestOpenNativeAppURL(no_native_app_url, NO, 0, NO); -} - -TEST_F(TabOpenAppTest, testURL) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - - EXPECT_FALSE([tab_ browserState]->IsOffTheRecord()); - - GURL testURL("http://www.youtube.com/"); - // Fake metadata object to enable and disable autoopenlinks for testURL. - FakeNativeAppMetadata* metadata = [[FakeNativeAppMetadata alloc] init]; - IOSChromeScopedTestingChromeBrowserProvider provider( - base::MakeUnique<FakeChromeBrowserProvider>(metadata)); - // Turn auto open on. - int expectedCallCount = 1; - [metadata setShouldAutoOpenLinks:YES]; - TestOpenNativeAppURL(testURL, YES, expectedCallCount, YES); - TestOpenNativeAppURL(testURL, NO, expectedCallCount, NO); - - // Turn auto open off. - expectedCallCount = 0; - [metadata setShouldAutoOpenLinks:NO]; - TestOpenNativeAppURL(testURL, NO, expectedCallCount, NO); -} - -// TODO(crbug.com/330189): This test fails if Google Maps is installed (usually -// on device). -TEST_F(TabOpenAppTest, DISABLED_testResetShouldAutoOpenOnFailure) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - - EXPECT_FALSE([tab_ browserState]->IsOffTheRecord()); - - // With a regular profile. - GURL testURL("http://maps.google.com/"); - // Fake metadata object - FakeNativeAppMetadata* metadata = [[FakeNativeAppMetadata alloc] init]; - - // Turn auto open on. - [metadata setShouldAutoOpenLinks:YES]; - int expectedCallCount = 2; - TestOpenNativeAppURL(testURL, NO, expectedCallCount, NO); - EXPECT_FALSE([metadata shouldAutoOpenLinks]); -} - -// Tests the opening of matching native apps with off-the-record browser state. -TEST_F(TabOpenAppOffTheRecordTest, testDummyURL) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - - EXPECT_TRUE([tab_ browserState]->IsOffTheRecord()); - - GURL no_native_app_url("dummy string"); - TestOpenNativeAppURL(no_native_app_url, NO, 0, NO); -} - -TEST_F(TabOpenAppOffTheRecordTest, testURL) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - - EXPECT_TRUE([tab_ browserState]->IsOffTheRecord()); - - // With a regular chrome browser state. - GURL testURL("http://www.youtube.com/"); - // Mock metadata object to enable and disable autoopenlinks for testURL. - FakeNativeAppMetadata* metadata = [[FakeNativeAppMetadata alloc] init]; - IOSChromeScopedTestingChromeBrowserProvider provider( - base::MakeUnique<FakeChromeBrowserProvider>(metadata)); - - // Turn auto open on. - [metadata setShouldAutoOpenLinks:YES]; - TestOpenNativeAppURL(testURL, NO, 0, NO); - - // Turn auto open off. - [metadata setShouldAutoOpenLinks:NO]; - TestOpenNativeAppURL(testURL, NO, 0, NO); -} - -// TODO(crbug.com/330189): This test fails if Google Maps is installed (usually -// on device). -TEST_F(TabOpenAppOffTheRecordTest, DISABLED_testResetShouldAutoOpenOnFailure) { - // TODO(crbug/711511): Remove this test when Native App Launcher has been - // fully deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - - EXPECT_TRUE([tab_ browserState]->IsOffTheRecord()); - - // With a regular profile. - GURL testURL("http://maps.google.com/"); - // Fake metadata object. - FakeNativeAppMetadata* metadata = [[FakeNativeAppMetadata alloc] init]; - - // Turn auto open on. - [metadata setShouldAutoOpenLinks:YES]; - int expectedCallCount = 2; - TestOpenNativeAppURL(testURL, NO, expectedCallCount, NO); - EXPECT_FALSE([metadata shouldAutoOpenLinks]); -} - } // namespace
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 9f094c7..9780d13 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -62,7 +62,6 @@ #include "ios/chrome/browser/infobars/infobar_container_view.h" #import "ios/chrome/browser/metrics/new_tab_page_uma.h" #include "ios/chrome/browser/metrics/tab_usage_recorder.h" -#import "ios/chrome/browser/native_app_launcher/native_app_navigation_controller.h" #import "ios/chrome/browser/open_url_util.h" #import "ios/chrome/browser/passwords/password_controller.h" #include "ios/chrome/browser/pref_names.h" @@ -3766,8 +3765,6 @@ if (oldTab && newTab && canPruneItems) { [newTab navigationManager]->CopyStateFromAndPrune( [oldTab navigationManager]); - [[newTab nativeAppNavigationController] - copyStateFrom:[oldTab nativeAppNavigationController]]; [_model webStateList]->ReplaceWebStateAt([_model indexOfTab:oldTab], std::move(newWebState));
diff --git a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm index b80c9ac..25d33c5 100644 --- a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller.mm
@@ -14,7 +14,6 @@ #include "components/translate/core/browser/translate_pref_names.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/content_settings/host_content_settings_map_factory.h" -#include "ios/chrome/browser/experimental_flags.h" #import "ios/chrome/browser/prefs/pref_observer_bridge.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_model.h" @@ -58,8 +57,7 @@ ContentSettingBackedBoolean* _disablePopupsSetting; // This object contains the list of available Mail client apps that can - // handle mailto: URLs. The value can be nil if mailto: URL rewriting is - // not available because of experimental settings. + // handle mailto: URLs. MailtoURLRewriter* _mailtoURLRewriter; // Updatable Items @@ -104,10 +102,8 @@ inverted:YES]; [_disablePopupsSetting setObserver:self]; - if (!experimental_flags::IsNativeAppLauncherEnabled()) { - _mailtoURLRewriter = [[MailtoURLRewriter alloc] initWithStandardHandlers]; - [_mailtoURLRewriter setObserver:self]; - } + _mailtoURLRewriter = [[MailtoURLRewriter alloc] initWithStandardHandlers]; + [_mailtoURLRewriter setObserver:self]; [self loadModel]; } @@ -132,10 +128,8 @@ toSectionWithIdentifier:SectionIdentifierSettings]; [model addItem:[self translateItem] toSectionWithIdentifier:SectionIdentifierSettings]; - if (!experimental_flags::IsNativeAppLauncherEnabled()) { - [model addItem:[self composeEmailItem] - toSectionWithIdentifier:SectionIdentifierSettings]; - } + [model addItem:[self composeEmailItem] + toSectionWithIdentifier:SectionIdentifierSettings]; } - (CollectionViewItem*)blockPopupsItem {
diff --git a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller_unittest.mm index 9a68fe64..c584ff49 100644 --- a/ios/chrome/browser/ui/settings/content_settings_collection_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/content_settings_collection_view_controller_unittest.mm
@@ -5,7 +5,6 @@ #import "ios/chrome/browser/ui/settings/content_settings_collection_view_controller.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" -#include "ios/chrome/browser/experimental_flags.h" #import "ios/chrome/browser/ui/collection_view/cells/collection_view_detail_item.h" #import "ios/chrome/browser/ui/collection_view/collection_view_controller_test.h" #include "ios/chrome/grit/ios_strings.h" @@ -44,19 +43,12 @@ CheckTitleWithId(IDS_IOS_CONTENT_SETTINGS_TITLE); ASSERT_EQ(1, NumberOfSections()); - // Compose Email section is shown only if experiment is turned on. - bool show_compose_email_section = - !experimental_flags::IsNativeAppLauncherEnabled(); - int expectedNumberOfItems = show_compose_email_section ? 3 : 2; - EXPECT_EQ(expectedNumberOfItems, NumberOfItemsInSection(0)); + EXPECT_EQ(3, NumberOfItemsInSection(0)); CheckDetailItemTextWithIds(IDS_IOS_BLOCK_POPUPS, IDS_IOS_SETTING_ON, 0, 0); CheckDetailItemTextWithIds(IDS_IOS_TRANSLATE_SETTING, IDS_IOS_SETTING_ON, 0, 1); - if (show_compose_email_section) { - CollectionViewDetailItem* item = GetCollectionViewItem(0, 2); - EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_COMPOSE_EMAIL_SETTING), - item.text); - } + CollectionViewDetailItem* item = GetCollectionViewItem(0, 2); + EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_COMPOSE_EMAIL_SETTING), item.text); } } // namespace
diff --git a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm index 8b79c226..8d3dfa0 100644 --- a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm
@@ -7,7 +7,7 @@ #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "components/autofill/core/common/password_form.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_store.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/ui/collection_view/cells/MDCCollectionViewCell+Chrome.h"
diff --git a/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm b/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm index b6cff635..60bd7f3 100644 --- a/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm
@@ -18,7 +18,7 @@ #include "components/autofill/core/common/password_form.h" #include "components/google/core/browser/google_util.h" #include "components/keyed_service/core/service_access_type.h" -#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/password_manager_constants.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h"
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.h b/ios/chrome/browser/ui/settings/settings_collection_view_controller.h index e5ffd3f..664589b 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.h +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.h
@@ -37,13 +37,9 @@ @property(weak, nonatomic, readonly) SigninInteractionController* signinInteractionController; -// Initializes a new SettingsCollectionViewController. |mainBrowserState|, -// |currentBrowserState| and |dataSource| must not be nil. -// If |currentBrowserState| is not off the record, then it must be equal to -// |mainBrowserState|. -- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)mainBrowserState - currentBrowserState: - (ios::ChromeBrowserState*)currentBrowserState +// Initializes a new SettingsCollectionViewController. |browserState| must not +// be nil and must not be an off-the-record browser state. +- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState NS_DESIGNATED_INITIALIZER; - (instancetype)initWithStyle:(CollectionViewControllerStyle)style
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm index 4dca72ba..47f4dbe3 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -58,7 +58,6 @@ #import "ios/chrome/browser/ui/settings/cells/account_signin_item.h" #import "ios/chrome/browser/ui/settings/content_settings_collection_view_controller.h" #import "ios/chrome/browser/ui/settings/material_cell_catalog_view_controller.h" -#import "ios/chrome/browser/ui/settings/native_apps_collection_view_controller.h" #import "ios/chrome/browser/ui/settings/privacy_collection_view_controller.h" #import "ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.h" #import "ios/chrome/browser/ui/settings/search_engine_settings_collection_view_controller.h" @@ -112,7 +111,6 @@ ItemTypeSearchEngine, ItemTypeSavedPasswords, ItemTypeAutofill, - ItemTypeNativeApps, ItemTypeVoiceSearch, ItemTypePrivacy, ItemTypeContentSettings, @@ -185,12 +183,9 @@ PrefObserverDelegate, SigninPromoViewConsumer, SigninPromoViewDelegate> { - // The main browser state that hold the settings. Never off the record. - ios::ChromeBrowserState* _mainBrowserState; // weak + // The current browser state that hold the settings. Never off the record. + ios::ChromeBrowserState* _browserState; // weak - // The current browser state. It is either |_mainBrowserState| - // or |_mainBrowserState->GetOffTheRecordChromeBrowserState()|. - ios::ChromeBrowserState* _currentBrowserState; // weak std::unique_ptr<SigninObserverBridge> _notificationBridge; std::unique_ptr<SyncObserverBridge> _syncObserverBridge; SigninInteractionController* _signinInteractionController; @@ -239,24 +234,18 @@ #pragma mark Initialization -- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)mainBrowserState - currentBrowserState: - (ios::ChromeBrowserState*)currentBrowserState { - DCHECK(mainBrowserState); - DCHECK(currentBrowserState); - DCHECK_EQ(mainBrowserState, - currentBrowserState->GetOriginalChromeBrowserState()); +- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState { + // Checks that |browserState| is not an Incognito browser state. + DCHECK(browserState); + DCHECK_EQ(browserState, browserState->GetOriginalChromeBrowserState()); self = [super initWithStyle:CollectionViewControllerStyleAppBar]; if (self) { - _mainBrowserState = mainBrowserState; - _currentBrowserState = currentBrowserState; + _browserState = browserState; self.title = l10n_util::GetNSStringWithFixup(IDS_IOS_SETTINGS_TITLE); self.collectionViewAccessibilityIdentifier = kSettingsCollectionViewId; - _notificationBridge.reset( - new SigninObserverBridge(_mainBrowserState, self)); + _notificationBridge.reset(new SigninObserverBridge(_browserState, self)); syncer::SyncService* syncService = - IOSChromeProfileSyncServiceFactory::GetForBrowserState( - _mainBrowserState); + IOSChromeProfileSyncServiceFactory::GetForBrowserState(_browserState); _syncObserverBridge.reset(new SyncObserverBridge(self, syncService)); _showMemoryDebugToolsEnabled = [[PrefBackedBoolean alloc] @@ -265,12 +254,12 @@ [_showMemoryDebugToolsEnabled setObserver:self]; AuthenticationService* authService = - AuthenticationServiceFactory::GetForBrowserState(_mainBrowserState); + AuthenticationServiceFactory::GetForBrowserState(_browserState); _identity = authService->GetAuthenticatedIdentity(); _identityServiceObserver.reset( new ChromeIdentityServiceObserverBridge(self)); - PrefService* prefService = _mainBrowserState->GetPrefs(); + PrefService* prefService = _browserState->GetPrefs(); _voiceLocaleCode.Init(prefs::kVoiceSearchLocale, prefService); @@ -326,7 +315,7 @@ // Sign in/Account section [model addSectionWithIdentifier:SectionIdentifierSignIn]; AuthenticationService* authService = - AuthenticationServiceFactory::GetForBrowserState(_mainBrowserState); + AuthenticationServiceFactory::GetForBrowserState(_browserState); if (!authService->IsAuthenticated()) { if (!_hasRecordedSigninImpression) { // Once the Settings are open, this button impression will at most be @@ -361,10 +350,6 @@ toSectionWithIdentifier:SectionIdentifierBasics]; [model addItem:[self autoFillDetailItem] toSectionWithIdentifier:SectionIdentifierBasics]; - if (experimental_flags::IsNativeAppLauncherEnabled()) { - [model addItem:[self nativeAppsDetailItem] - toSectionWithIdentifier:SectionIdentifierBasics]; - } // Advanced Section [model addSectionWithIdentifier:SectionIdentifierAdvanced]; @@ -453,8 +438,7 @@ - (CollectionViewItem*)searchEngineDetailItem { NSString* defaultSearchEngineName = base::SysUTF16ToNSString(GetDefaultSearchEngineName( - ios::TemplateURLServiceFactory::GetForBrowserState( - _mainBrowserState))); + ios::TemplateURLServiceFactory::GetForBrowserState(_browserState))); _defaultSearchEngineItem = [self detailItemWithType:ItemTypeSearchEngine @@ -467,7 +451,7 @@ } - (CollectionViewItem*)savePasswordsDetailItem { - BOOL savePasswordsEnabled = _mainBrowserState->GetPrefs()->GetBoolean( + BOOL savePasswordsEnabled = _browserState->GetPrefs()->GetBoolean( password_manager::prefs::kPasswordManagerSavingEnabled); NSString* passwordsDetail = savePasswordsEnabled ? l10n_util::GetNSString(IDS_IOS_SETTING_ON) @@ -482,8 +466,8 @@ } - (CollectionViewItem*)autoFillDetailItem { - BOOL autofillEnabled = _mainBrowserState->GetPrefs()->GetBoolean( - autofill::prefs::kAutofillEnabled); + BOOL autofillEnabled = + _browserState->GetPrefs()->GetBoolean(autofill::prefs::kAutofillEnabled); NSString* autofillDetail = autofillEnabled ? l10n_util::GetNSString(IDS_IOS_SETTING_ON) : l10n_util::GetNSString(IDS_IOS_SETTING_OFF); @@ -495,13 +479,6 @@ return _autoFillDetailItem; } -- (CollectionViewItem*)nativeAppsDetailItem { - return [self - detailItemWithType:ItemTypeNativeApps - text:l10n_util::GetNSString(IDS_IOS_GOOGLE_APPS_SM_SETTINGS) - detailText:nil]; -} - - (CollectionViewItem*)voiceSearchDetailItem { voice::SpeechInputLocaleConfig* localeConfig = voice::SpeechInputLocaleConfig::GetInstance(); @@ -588,8 +565,7 @@ - (void)updateSearchCell { NSString* defaultSearchEngineName = base::SysUTF16ToNSString(GetDefaultSearchEngineName( - ios::TemplateURLServiceFactory::GetForBrowserState( - _mainBrowserState))); + ios::TemplateURLServiceFactory::GetForBrowserState(_browserState))); _defaultSearchEngineItem.detailText = defaultSearchEngineName; [self reconfigureCellsForItems:@[ _defaultSearchEngineItem ]]; @@ -639,7 +615,7 @@ if (itemType == ItemTypeSavedPasswords) { scoped_refptr<password_manager::PasswordStore> passwordStore = IOSChromePasswordStoreFactory::GetForBrowserState( - _mainBrowserState, ServiceAccessType::EXPLICIT_ACCESS); + _browserState, ServiceAccessType::EXPLICIT_ACCESS); if (!passwordStore) { // The password store factory returns a NULL password store if something // goes wrong during the password store initialization. Disable the save @@ -742,42 +718,37 @@ break; case ItemTypeAccount: controller = [[AccountsCollectionViewController alloc] - initWithBrowserState:_mainBrowserState + initWithBrowserState:_browserState closeSettingsOnAddAccount:NO]; break; case ItemTypeSearchEngine: controller = [[SearchEngineSettingsCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; + initWithBrowserState:_browserState]; break; case ItemTypeSavedPasswords: { controller = [[SavePasswordsCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; + initWithBrowserState:_browserState]; break; } case ItemTypeAutofill: controller = [[AutofillCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; - break; - case ItemTypeNativeApps: - controller = [[NativeAppsCollectionViewController alloc] - initWithURLRequestContextGetter:_currentBrowserState - ->GetRequestContext()]; + initWithBrowserState:_browserState]; break; case ItemTypeVoiceSearch: controller = [[VoicesearchCollectionViewController alloc] - initWithPrefs:_mainBrowserState->GetPrefs()]; + initWithPrefs:_browserState->GetPrefs()]; break; case ItemTypePrivacy: controller = [[PrivacyCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; + initWithBrowserState:_browserState]; break; case ItemTypeContentSettings: controller = [[ContentSettingsCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; + initWithBrowserState:_browserState]; break; case ItemTypeBandwidth: controller = [[BandwidthManagementCollectionViewController alloc] - initWithBrowserState:_mainBrowserState]; + initWithBrowserState:_browserState]; break; case ItemTypeAboutChrome: controller = [[AboutChromeCollectionViewController alloc] init]; @@ -928,7 +899,7 @@ - (void)updateIdentityAccountItem: (CollectionViewAccountItem*)identityAccountItem { AuthenticationService* authService = - AuthenticationServiceFactory::GetForBrowserState(_mainBrowserState); + AuthenticationServiceFactory::GetForBrowserState(_browserState); _identity = authService->GetAuthenticatedIdentity(); if (!_identity) { // This could occur during the sign out process. Just ignore as the account @@ -939,7 +910,7 @@ identityAccountItem.text = [_identity userFullName]; SyncSetupService* syncSetupService = - SyncSetupServiceFactory::GetForBrowserState(_mainBrowserState); + SyncSetupServiceFactory::GetForBrowserState(_browserState); if (!syncSetupService->HasFinishedInitialSetup()) { identityAccountItem.detailText = l10n_util::GetNSString(IDS_IOS_SYNC_SETUP_IN_PROGRESS); @@ -952,7 +923,7 @@ if (identityAccountItem.shouldDisplayError) { identityAccountItem.detailText = ios_internal::sync::GetSyncErrorDescriptionForBrowserState( - _mainBrowserState); + _browserState); } else { identityAccountItem.detailText = syncSetupService->IsSyncEnabled() @@ -988,7 +959,7 @@ base::RecordAction(base::UserMetricsAction("Signin_Signin_FromSettings")); DCHECK(!_signinInteractionController); _signinInteractionController = [[SigninInteractionController alloc] - initWithBrowserState:_mainBrowserState + initWithBrowserState:_browserState presentingViewController:self.navigationController isPresentedOnSettings:YES accessPoint:signin_metrics::AccessPoint:: @@ -1115,7 +1086,7 @@ if (preferenceName == password_manager::prefs::kPasswordManagerSavingEnabled) { BOOL savePasswordsEnabled = - _mainBrowserState->GetPrefs()->GetBoolean(preferenceName); + _browserState->GetPrefs()->GetBoolean(preferenceName); NSString* passwordsDetail = savePasswordsEnabled ? l10n_util::GetNSString(IDS_IOS_SETTING_ON) : l10n_util::GetNSString(IDS_IOS_SETTING_OFF); @@ -1126,7 +1097,7 @@ if (preferenceName == autofill::prefs::kAutofillEnabled) { BOOL autofillEnabled = - _mainBrowserState->GetPrefs()->GetBoolean(preferenceName); + _browserState->GetPrefs()->GetBoolean(preferenceName); NSString* autofillDetail = autofillEnabled ? l10n_util::GetNSString(IDS_IOS_SETTING_ON) : l10n_util::GetNSString(IDS_IOS_SETTING_OFF);
diff --git a/ios/chrome/browser/ui/settings/settings_egtest.mm b/ios/chrome/browser/ui/settings/settings_egtest.mm index 7ba1703d..bf4a1fe 100644 --- a/ios/chrome/browser/ui/settings/settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/settings_egtest.mm
@@ -21,7 +21,6 @@ #import "ios/chrome/app/main_controller.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/content_settings/host_content_settings_map_factory.h" -#include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/pref_names.h" #import "ios/chrome/browser/ui/browser_view_controller.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data_collection_view_controller.h" @@ -131,10 +130,6 @@ id<GREYMatcher> AutofillButton() { return ButtonWithAccessibilityLabelId(IDS_IOS_AUTOFILL); } -// Matcher for the Google Apps cell on the main Settings screen. -id<GREYMatcher> GoogleAppsButton() { - return ButtonWithAccessibilityLabelId(IDS_IOS_GOOGLE_APPS_SM_SETTINGS); -} // Matcher for the Google Chrome cell on the main Settings screen. id<GREYMatcher> GoogleChromeButton() { return ButtonWithAccessibilityLabelId(IDS_IOS_PRODUCT_NAME); @@ -881,17 +876,6 @@ [self closeSubSettingsMenu]; } -// Verifies the UI elements are accessible on the Google Apps page. -- (void)testAccessibilityOnGoogleApps { - // TODO(crbug/711511): Remove when Native App Launcher is full deprecated. - if (!experimental_flags::IsNativeAppLauncherEnabled()) - return; - [ChromeEarlGreyUI openSettingsMenu]; - [ChromeEarlGreyUI tapSettingsMenuButton:GoogleAppsButton()]; - chrome_test_util::VerifyAccessibilityForCurrentScreen(); - [self closeSubSettingsMenu]; -} - // Verifies the UI elements are accessible on the About Chrome page. - (void)testAccessibilityOnGoogleChrome { [ChromeEarlGreyUI openSettingsMenu];
diff --git a/ios/chrome/browser/ui/settings/settings_navigation_controller.h b/ios/chrome/browser/ui/settings/settings_navigation_controller.h index b0bd5f1a..3f917fe 100644 --- a/ios/chrome/browser/ui/settings/settings_navigation_controller.h +++ b/ios/chrome/browser/ui/settings/settings_navigation_controller.h
@@ -52,8 +52,6 @@ // clang-format off + (SettingsNavigationController*)newSettingsMainControllerWithMainBrowserState: (ios::ChromeBrowserState*)browserState - currentBrowserState: - (ios::ChromeBrowserState*)currentBrowserState delegate: (id<SettingsNavigationControllerDelegate>)delegate; // clang-format on
diff --git a/ios/chrome/browser/ui/settings/settings_navigation_controller.mm b/ios/chrome/browser/ui/settings/settings_navigation_controller.mm index 894f8c3..d3c885f 100644 --- a/ios/chrome/browser/ui/settings/settings_navigation_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_navigation_controller.mm
@@ -116,14 +116,11 @@ // clang-format off + (SettingsNavigationController*)newSettingsMainControllerWithMainBrowserState: (ios::ChromeBrowserState*)browserState - currentBrowserState: - (ios::ChromeBrowserState*)currentBrowserState delegate: (id<SettingsNavigationControllerDelegate>)delegate { // clang-format on UIViewController* controller = [[SettingsCollectionViewController alloc] - initWithBrowserState:browserState - currentBrowserState:currentBrowserState]; + initWithBrowserState:browserState]; SettingsNavigationController* nc = [[SettingsNavigationController alloc] initWithRootViewController:controller browserState:browserState
diff --git a/ios/chrome/browser/ui/settings/settings_navigation_controller_unittest.mm b/ios/chrome/browser/ui/settings/settings_navigation_controller_unittest.mm index 8924d91..95119d95 100644 --- a/ios/chrome/browser/ui/settings/settings_navigation_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/settings_navigation_controller_unittest.mm
@@ -91,8 +91,6 @@ [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:chrome_browser_state_ .get() - currentBrowserState:chrome_browser_state_ - .get() delegate:nil]; UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; @@ -114,8 +112,6 @@ [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:chrome_browser_state_ .get() - currentBrowserState:chrome_browser_state_ - .get() delegate:nil]; EXPECT_EQ(1U, [[settingsController viewControllers] count]); @@ -133,8 +129,6 @@ [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:chrome_browser_state_ .get() - currentBrowserState:chrome_browser_state_ - .get() delegate:mockDelegate_]; UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil]; @@ -157,8 +151,6 @@ [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:chrome_browser_state_ .get() - currentBrowserState:chrome_browser_state_ - .get() delegate:mockDelegate_]; EXPECT_EQ(1U, [[settingsController viewControllers] count]); [[mockDelegate_ expect] closeSettings];
diff --git a/ios/chrome/browser/ui/stack_view/BUILD.gn b/ios/chrome/browser/ui/stack_view/BUILD.gn index 73868e2..4f510a2 100644 --- a/ios/chrome/browser/ui/stack_view/BUILD.gn +++ b/ios/chrome/browser/ui/stack_view/BUILD.gn
@@ -52,6 +52,7 @@ } source_set("stack_view") { + configs += [ "//build/config/compiler:enable_arc" ] sources = [ "card_set.h", "card_set.mm",
diff --git a/ios/chrome/browser/ui/stack_view/card_set.h b/ios/chrome/browser/ui/stack_view/card_set.h index 030e6e35..8280ac7 100644 --- a/ios/chrome/browser/ui/stack_view/card_set.h +++ b/ios/chrome/browser/ui/stack_view/card_set.h
@@ -52,17 +52,17 @@ @property(nonatomic, readonly) NSArray* cards; // The card corresponding to the currently selected tab in the tab model. // Setting this property will change the selection in the tab model. -@property(nonatomic, assign, readwrite) StackCard* currentCard; +@property(nonatomic) StackCard* currentCard; // Set to the card that is currently animating closed, if any. -@property(nonatomic, assign, readwrite) StackCard* closingCard; +@property(nonatomic) StackCard* closingCard; // The view that cards should be displayed in. Changing the display view will // remove cards from the previous view, but they will not be re-displayed in the // new view without a call to updateCardVisibilities. -@property(nonatomic, retain, readwrite) UIView* displayView; +@property(nonatomic, strong, readwrite) UIView* displayView; // The side on which the close button should be displayed. @property(nonatomic, readonly) CardCloseButtonSide closeButtonSide; // The object to be notified about addition and removal of cards. -@property(nonatomic, assign, readwrite) id<CardSetObserver> observer; +@property(nonatomic, weak, readwrite) id<CardSetObserver> observer; // While YES, changes to the tab model will not affect the card stack. When // this is changed back to NO, the card stack will be completely rebuilt, so // this should be used very carefully. @@ -88,6 +88,10 @@ // outlive the card set. - (id)initWithModel:(TabModel*)model; +// Tears down any observation or other state. After this method is called, the +// receiver should be set to nil or otherwise marked for deallocation. +- (void)disconnect; + // The tab model backing the card set. // TODO(stuartmorgan): See if this can reasonably be internalized. - (TabModel*)tabModel;
diff --git a/ios/chrome/browser/ui/stack_view/card_set.mm b/ios/chrome/browser/ui/stack_view/card_set.mm index 67617e4..e23f0a2c 100644 --- a/ios/chrome/browser/ui/stack_view/card_set.mm +++ b/ios/chrome/browser/ui/stack_view/card_set.mm
@@ -7,7 +7,6 @@ #import <QuartzCore/QuartzCore.h> #include "base/logging.h" -#import "base/mac/scoped_nsobject.h" #import "ios/chrome/browser/tabs/tab.h" #import "ios/chrome/browser/tabs/tab_model.h" #include "ios/chrome/browser/ui/rtl_geometry.h" @@ -17,15 +16,19 @@ #include "ios/chrome/browser/ui/ui_util.h" #import "ios/web/web_state/ui/crw_web_controller.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace { const CGFloat kMaxCardStaggerPercentage = 0.35; } @interface CardSet ()<StackCardViewProvider, TabModelObserver> { - base::scoped_nsobject<TabModel> tabModel_; - base::scoped_nsobject<UIView> view_; - base::scoped_nsobject<CardStackLayoutManager> stackModel_; - base::scoped_nsobject<UIImageView> stackShadow_; + TabModel* tabModel_; + UIView* view_; + CardStackLayoutManager* stackModel_; + UIImageView* stackShadow_; } // Set to |YES| when the card set should draw a shadow around the entire stack. @@ -61,23 +64,26 @@ @synthesize closingCard = closingCard_; - (CardStackLayoutManager*)stackModel { - return stackModel_.get(); + return stackModel_; } - (id)initWithModel:(TabModel*)model { if ((self = [super init])) { - tabModel_.reset([model retain]); + tabModel_ = model; [tabModel_ addObserver:self]; - stackModel_.reset([[CardStackLayoutManager alloc] init]); + stackModel_ = [[CardStackLayoutManager alloc] init]; [self rebuildCards]; self.shouldShowShadow = YES; } return self; } -- (void)dealloc { +- (void)disconnect { [tabModel_ removeObserver:self]; - [super dealloc]; +} + +- (void)dealloc { + [self disconnect]; } #pragma mark Properties @@ -90,7 +96,7 @@ DCHECK([tabModel count] == 0); DCHECK([tabModel_ count] == 0); [tabModel_ removeObserver:self]; - tabModel_.reset([tabModel retain]); + tabModel_ = tabModel; if (!ignoresTabModelChanges_) [tabModel_ addObserver:self]; } @@ -122,11 +128,11 @@ } - (UIView*)displayView { - return view_.get(); + return view_; } - (void)setDisplayView:(UIView*)view { - if (view == view_.get()) + if (view == view_) return; for (StackCard* card in self.cards) { if (card.viewIsLive) { @@ -135,7 +141,7 @@ } } [stackShadow_ removeFromSuperview]; - view_.reset([view retain]); + view_ = view; // Add the stack shadow view to the new display view. if (!stackShadow_) { UIImage* shadowImage = [UIImage imageNamed:kCardShadowImageName]; @@ -145,7 +151,7 @@ shadowImage.size.width / 2.0, shadowImage.size.height / 2.0, shadowImage.size.width / 2.0)]; - stackShadow_.reset([[UIImageView alloc] initWithImage:shadowImage]); + stackShadow_ = [[UIImageView alloc] initWithImage:shadowImage]; [stackShadow_ setHidden:!self.cards.count]; } [view_ addSubview:stackShadow_]; @@ -154,7 +160,7 @@ // if/when the view is restored (e.g., if the view was purged due to a memory // warning while in a modal view and then restored when exiting the modal // view). - if (view_.get()) + if (view_) [self displayViewSizeWasChanged]; } @@ -404,7 +410,6 @@ - (void)removeCardAtIndex:(NSUInteger)index { DCHECK(index < [self.cards count]); StackCard* card = [self.cards objectAtIndex:index]; - [[card retain] autorelease]; [self.observer cardSet:self willRemoveCard:card atIndex:index]; [stackModel_ removeCard:card]; @@ -415,7 +420,7 @@ - (StackCard*)buildCardFromTab:(Tab*)tab { DCHECK(tab); - StackCard* card = [[[StackCard alloc] initWithViewProvider:self] autorelease]; + StackCard* card = [[StackCard alloc] initWithViewProvider:self]; card.size = [stackModel_ cardSize]; card.tabID = reinterpret_cast<NSUInteger>(tab); @@ -425,7 +430,7 @@ - (void)rebuildCards { [stackModel_ removeAllCards]; - for (Tab* tab in tabModel_.get()) { + for (Tab* tab in tabModel_) { StackCard* card = [self buildCardFromTab:tab]; [stackModel_ addCard:card]; } @@ -485,9 +490,8 @@ NSString* title = tab.title; if (![title length]) title = tab.urlDisplayString; - CardView* view = - [[[CardView alloc] initWithFrame:frame - isIncognito:[tabModel_ isOffTheRecord]] autorelease]; + CardView* view = [[CardView alloc] initWithFrame:frame + isIncognito:[tabModel_ isOffTheRecord]]; [view setTitle:title]; [view setFavicon:[tab favicon]]; [tab retrieveSnapshot:^(UIImage* image) { @@ -592,7 +596,7 @@ } - (void)setStackModelForTesting:(CardStackLayoutManager*)stackModel { - stackModel_.reset([stackModel retain]); + stackModel_ = stackModel; } @end
diff --git a/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.h b/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.h index 54d9428..ca23b74d 100644 --- a/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.h +++ b/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.h
@@ -15,15 +15,7 @@ // Encapsulates a stack of cards and their layout behavior, supporting // fanning the cards out along an axis and gathering them to fit in a given // area. -@interface CardStackLayoutManager : NSObject { - @private - base::scoped_nsobject<NSMutableArray> cards_; - // YES if the previous call to one of {|scrollCardAtIndex|, - // |handleMultitouchWithFirstDelta|} was to the former method; NO otherwise. - BOOL treatOverExtensionAsScroll_; - NSUInteger previousFirstPinchCardIndex_; - NSUInteger previousSecondPinchCardIndex_; -} +@interface CardStackLayoutManager : NSObject // The size of a card. Setting this property preserves card origins with the // exception that cards are moved as necessary to satisfy placement constraints
diff --git a/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.mm b/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.mm index cb84a71..decc498 100644 --- a/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.mm +++ b/ios/chrome/browser/ui/stack_view/card_stack_layout_manager.mm
@@ -9,9 +9,15 @@ #include "base/logging.h" #include "ios/chrome/browser/ui/rtl_geometry.h" +#import "ios/chrome/browser/ui/stack_view/card_view.h" #import "ios/chrome/browser/ui/stack_view/stack_card.h" +#import "ios/chrome/browser/ui/stack_view/title_label.h" #import "ios/chrome/browser/ui/ui_util.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace { // The maximum number of cards that should be staggered at a collapse point. @@ -34,7 +40,14 @@ } // namespace -@interface CardStackLayoutManager () +@interface CardStackLayoutManager () { + NSMutableArray* cards_; + // YES if the previous call to one of {|scrollCardAtIndex|, + // |handleMultitouchWithFirstDelta|} was to the former method; NO otherwise. + BOOL treatOverExtensionAsScroll_; + NSUInteger previousFirstPinchCardIndex_; + NSUInteger previousSecondPinchCardIndex_; +} // Exposes |kMinStackStaggerAmount| for tests. - (CGFloat)minStackStaggerAmount; @@ -194,7 +207,7 @@ - (id)init { if ((self = [super init])) { - cards_.reset([[NSMutableArray alloc] init]); + cards_ = [[NSMutableArray alloc] init]; layoutIsVertical_ = YES; lastStartStackCardIndex_ = -1; firstEndStackCardIndex_ = -1; @@ -247,7 +260,7 @@ NSUInteger i = 0; CGFloat previousFirstCardOffset = 0; CGFloat newFirstCardOffset = 0; - for (StackCard* card in cards_.get()) { + for (StackCard* card in cards_) { CGFloat offset = [self cardOffsetOnLayoutAxis:card]; card.size = cardSize_; CGFloat newOffset = offset; @@ -289,7 +302,7 @@ - (void)setLayoutAxisPosition:(CGFloat)position { layoutAxisPosition_ = position; - for (StackCard* card in cards_.get()) { + for (StackCard* card in cards_) { LayoutRect layout = card.layout; if (layoutIsVertical_) layout.position.leading = position - 0.5 * layout.size.width; @@ -1128,7 +1141,7 @@ } - (void)setSynchronizeCardViews:(BOOL)synchronizeViews { - for (StackCard* card in cards_.get()) { + for (StackCard* card in cards_) { card.synchronizeView = synchronizeViews; } }
diff --git a/ios/chrome/browser/ui/stack_view/card_stack_pinch_gesture_recognizer.mm b/ios/chrome/browser/ui/stack_view/card_stack_pinch_gesture_recognizer.mm index d5a8021..ad6727f 100644 --- a/ios/chrome/browser/ui/stack_view/card_stack_pinch_gesture_recognizer.mm +++ b/ios/chrome/browser/ui/stack_view/card_stack_pinch_gesture_recognizer.mm
@@ -6,6 +6,10 @@ #include "base/logging.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + @interface CardStackPinchGestureRecognizer () // Returns the number of non-ended, non-cancelled touches in |event|.
diff --git a/ios/chrome/browser/ui/stack_view/card_view.h b/ios/chrome/browser/ui/stack_view/card_view.h index 298a995..137dec21 100644 --- a/ios/chrome/browser/ui/stack_view/card_view.h +++ b/ios/chrome/browser/ui/stack_view/card_view.h
@@ -52,7 +52,7 @@ @property(nonatomic, assign) BOOL isActiveTab; // The snapshot displayed on the card. -@property(nonatomic, retain) UIImage* image; +@property(nonatomic, strong) UIImage* image; // Whether the card view should render its shadow. @property(nonatomic, assign) BOOL shouldShowShadow;
diff --git a/ios/chrome/browser/ui/stack_view/card_view.mm b/ios/chrome/browser/ui/stack_view/card_view.mm index 0ca24d4..1cf1260 100644 --- a/ios/chrome/browser/ui/stack_view/card_view.mm +++ b/ios/chrome/browser/ui/stack_view/card_view.mm
@@ -26,8 +26,7 @@ #include <algorithm> #import "base/mac/foundation_util.h" -#import "base/mac/objc_property_releaser.h" -#import "base/mac/scoped_nsobject.h" + #include "components/strings/grit/components_strings.h" #import "ios/chrome/browser/ui/animation_util.h" #import "ios/chrome/browser/ui/reversed_animation.h" @@ -43,6 +42,10 @@ #include "ui/gfx/image/image.h" #import "ui/gfx/ios/uikit_util.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + using ios::material::TimingFunction; const UIEdgeInsets kCardImageInsets = {48.0, 4.0, 4.0, 4.0}; @@ -85,10 +88,10 @@ @interface CardTabView : UIView @property(nonatomic, assign) CardCloseButtonSide closeButtonSide; -@property(nonatomic, retain) UIImageView* favIconView; -@property(nonatomic, retain) UIImage* favicon; -@property(nonatomic, retain) CloseButton* closeButton; -@property(nonatomic, retain) TitleLabel* titleLabel; +@property(nonatomic, strong) UIImageView* favIconView; +@property(nonatomic, strong) UIImage* favicon; +@property(nonatomic, strong) CloseButton* closeButton; +@property(nonatomic, strong) TitleLabel* titleLabel; @property(nonatomic, assign) BOOL isIncognito; // Layout helper selectors that calculate the frames for subviews given the @@ -124,9 +127,7 @@ @end -@implementation CardTabView { - base::mac::ObjCPropertyReleaser _propertyReleaser_CardTabView; -} +@implementation CardTabView #pragma mark - Property Implementation @@ -146,7 +147,6 @@ if (!self) return self; - _propertyReleaser_CardTabView.Init(self, [CardTabView class]); _isIncognito = isIncognito; UIImage* image = ImageWithName(@"default_favicon", _isIncognito); @@ -272,8 +272,6 @@ - (void)setFavicon:(UIImage*)favicon { if (favicon != _favicon) { - [favicon retain]; - [_favicon release]; _favicon = favicon; [self updateFaviconImage]; } @@ -437,22 +435,22 @@ #pragma mark - @interface CardView () { - base::scoped_nsobject<UIImageView> _contents; - base::scoped_nsobject<CardTabView> _tab; - id _cardCloseTarget; // weak + UIImageView* _contents; + CardTabView* _tab; + __weak id _cardCloseTarget; SEL _cardCloseAction; - id _accessibilityTarget; // weak + __weak id _accessibilityTarget; SEL _accessibilityAction; BOOL _isIncognito; // YES if the card should use the incognito styling. // Pieces of the card frame, split into four UIViews. - base::scoped_nsobject<UIImageView> _frameLeft; - base::scoped_nsobject<UIImageView> _frameRight; - base::scoped_nsobject<UIImageView> _frameTop; - base::scoped_nsobject<UIImageView> _frameBottom; - base::scoped_nsobject<UIImageView> _frameShadowImageView; - base::scoped_nsobject<CALayer> _shadowMask; + UIImageView* _frameLeft; + UIImageView* _frameRight; + UIImageView* _frameTop; + UIImageView* _frameBottom; + UIImageView* _frameShadowImageView; + CALayer* _shadowMask; } // The LayoutRect for the CardTabView. @@ -511,7 +509,7 @@ self.contentMode = UIViewContentModeRedraw; CGRect shadowFrame = UIEdgeInsetsInsetRect(bounds, kCardShadowLayoutOutsets); - _frameShadowImageView.reset([[UIImageView alloc] initWithFrame:shadowFrame]); + _frameShadowImageView = [[UIImageView alloc] initWithFrame:shadowFrame]; [_frameShadowImageView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; @@ -526,7 +524,7 @@ [_frameShadowImageView setImage:image]; CGRect snapshotFrame = UIEdgeInsetsInsetRect(bounds, kCardImageInsets); - _contents.reset([[UIImageView alloc] initWithFrame:snapshotFrame]); + _contents = [[UIImageView alloc] initWithFrame:snapshotFrame]; [_contents setClipsToBounds:YES]; [_contents setContentMode:UIViewContentModeScaleAspectFill]; [_contents setFrame:snapshotFrame]; @@ -539,7 +537,7 @@ UIEdgeInsets imageStretchInsets = UIEdgeInsetsMake( 0.5 * image.size.height, 0.0, 0.5 * image.size.height, 0.0); image = [image resizableImageWithCapInsets:imageStretchInsets]; - _frameLeft.reset([[UIImageView alloc] initWithImage:image]); + _frameLeft = [[UIImageView alloc] initWithImage:image]; [self addSubview:_frameLeft]; image = [UIImage imageNamed:isIncognito ? @"border_frame_incognito_right" @@ -547,7 +545,7 @@ imageStretchInsets = UIEdgeInsetsMake(0.5 * image.size.height, 0.0, 0.5 * image.size.height, 0.0); image = [image resizableImageWithCapInsets:imageStretchInsets]; - _frameRight.reset([[UIImageView alloc] initWithImage:image]); + _frameRight = [[UIImageView alloc] initWithImage:image]; [self addSubview:_frameRight]; image = [UIImage imageNamed:isIncognito ? @"border_frame_incognito_top" @@ -555,7 +553,7 @@ imageStretchInsets = UIEdgeInsetsMake(0.0, 0.5 * image.size.width, 0.0, 0.5 * image.size.width); image = [image resizableImageWithCapInsets:imageStretchInsets]; - _frameTop.reset([[UIImageView alloc] initWithImage:image]); + _frameTop = [[UIImageView alloc] initWithImage:image]; [self addSubview:_frameTop]; image = [UIImage imageNamed:isIncognito ? @"border_frame_incognito_bottom" @@ -563,12 +561,11 @@ imageStretchInsets = UIEdgeInsetsMake(0.0, 0.5 * image.size.width, 0.0, 0.5 * image.size.width); image = [image resizableImageWithCapInsets:imageStretchInsets]; - _frameBottom.reset([[UIImageView alloc] initWithImage:image]); + _frameBottom = [[UIImageView alloc] initWithImage:image]; [self addSubview:_frameBottom]; - _tab.reset([[CardTabView alloc] - initWithFrame:LayoutRectGetRect([self tabLayout]) - isIncognito:_isIncognito]); + _tab = [[CardTabView alloc] initWithFrame:LayoutRectGetRect([self tabLayout]) + isIncognito:_isIncognito]; [_tab setCloseButtonSide:IsPortrait() ? CardCloseButtonSide::TRAILING : CardCloseButtonSide::LEADING]; [[_tab closeButton] addTarget:self @@ -647,7 +644,10 @@ } - (void)closeButtonWasTapped:(id)sender { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [_cardCloseTarget performSelector:_cardCloseAction withObject:self]; +#pragma clang diagnostic pop // Disable the tab's close button to prevent touch handling from the button // while it's animating closed. [_tab closeButton].enabled = NO; @@ -679,7 +679,7 @@ } - (void)updateImageBoundsAndZoom { - UIImageView* imageView = _contents.get(); + UIImageView* imageView = _contents; DCHECK(!CGRectEqualToRect(self.bounds, CGRectZero)); imageView.frame = UIEdgeInsetsInsetRect(self.bounds, kCardImageInsets); @@ -698,8 +698,7 @@ // Create copy of animation (animations become immutable after they're added // to the layer). - base::scoped_nsobject<CAAnimationGroup> updatedAnimation( - static_cast<CAAnimationGroup*>([snapshotAnimation copy])); + CAAnimationGroup* updatedAnimation = [snapshotAnimation copy]; // Extract begin and end sizes of the card. CAAnimation* cardAnimation = [self.layer animationForKey:kCardViewAnimationKey]; @@ -746,7 +745,7 @@ if (self.shouldMaskShadow) { if (!_shadowMask) { - _shadowMask.reset([[CALayer alloc] init]); + _shadowMask = [[CALayer alloc] init]; [_shadowMask setBackgroundColor:[UIColor blackColor].CGColor]; } [_frameShadowImageView layer].mask = _shadowMask; @@ -952,7 +951,7 @@ forKey:kCardViewAnimationKey]; if (self.shouldMaskShadow) { frameAnimation = FrameAnimationMake( - _shadowMask.get(), [self shadowMaskFrameForBounds:beginBounds], + _shadowMask, [self shadowMaskFrameForBounds:beginBounds], [self shadowMaskFrameForBounds:endBounds]); frameAnimation.duration = frameDuration; frameAnimation.timingFunction = frameTiming; @@ -1029,7 +1028,10 @@ } - (void)elementDidBecomeFocused:(id)sender { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [_accessibilityTarget performSelector:_accessibilityAction withObject:sender]; +#pragma clang diagnostic pop } @end
diff --git a/ios/chrome/browser/ui/stack_view/close_button.mm b/ios/chrome/browser/ui/stack_view/close_button.mm index 45ff4f35..c272c305 100644 --- a/ios/chrome/browser/ui/stack_view/close_button.mm +++ b/ios/chrome/browser/ui/stack_view/close_button.mm
@@ -6,8 +6,12 @@ #include "base/logging.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + @implementation CloseButton { - id _accessibilityTarget; // weak + __weak id _accessibilityTarget; SEL _accessibilityAction; } @@ -20,7 +24,10 @@ } - (void)accessibilityElementDidBecomeFocused { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [_accessibilityTarget performSelector:_accessibilityAction withObject:self]; +#pragma clang diagnostic pop } @end
diff --git a/ios/chrome/browser/ui/stack_view/page_animation_util.mm b/ios/chrome/browser/ui/stack_view/page_animation_util.mm index 3e66bd4..a43792e 100644 --- a/ios/chrome/browser/ui/stack_view/page_animation_util.mm +++ b/ios/chrome/browser/ui/stack_view/page_animation_util.mm
@@ -7,12 +7,15 @@ #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> -#import "base/mac/scoped_nsobject.h" #import "ios/chrome/browser/ui/animation_util.h" #include "ios/chrome/browser/ui/rtl_geometry.h" #import "ios/chrome/browser/ui/stack_view/card_view.h" #import "ios/chrome/common/material_timing.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + using ios::material::TimingFunction; namespace { @@ -56,8 +59,8 @@ const UIEdgeInsets kShadowStretchInsets = {28.0, 28.0, 28.0, 28.0}; const UIEdgeInsets kShadowLayoutOutset = {-10.0, -11.0, -12.0, -11.0}; CGRect shadowFrame = UIEdgeInsetsInsetRect(frame, kShadowLayoutOutset); - base::scoped_nsobject<UIImageView> frameShadowImageView( - [[UIImageView alloc] initWithFrame:shadowFrame]); + UIImageView* frameShadowImageView = + [[UIImageView alloc] initWithFrame:shadowFrame]; [frameShadowImageView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; @@ -103,8 +106,7 @@ // Create paper background. CGRect paperFrame = CGRectOffset(endFrame, 0, paperOffset); paperFrame.size.height -= paperOffset; - base::scoped_nsobject<PaperView> paper( - [[PaperView alloc] initWithFrame:paperFrame]); + PaperView* paper = [[PaperView alloc] initWithFrame:paperFrame]; [parent insertSubview:paper belowSubview:view]; [paper addSubview:view]; [paper setBackgroundColor:isOffTheRecord @@ -209,8 +211,7 @@ BOOL isPortrait, void (^completion)(void)) { // Create paper background. - base::scoped_nsobject<PaperView> paper( - [[PaperView alloc] initWithFrame:CGRectZero]); + PaperView* paper = [[PaperView alloc] initWithFrame:CGRectZero]; UIView* parent = [currentPageCard superview]; [parent insertSubview:paper aboveSubview:currentPageCard]; CGRect pageBounds = currentPageCard.bounds;
diff --git a/ios/chrome/browser/ui/stack_view/stack_card.mm b/ios/chrome/browser/ui/stack_view/stack_card.mm index e809fbb..a530736 100644 --- a/ios/chrome/browser/ui/stack_view/stack_card.mm +++ b/ios/chrome/browser/ui/stack_view/stack_card.mm
@@ -5,14 +5,17 @@ #import "ios/chrome/browser/ui/stack_view/stack_card.h" #include "base/logging.h" -#import "base/mac/scoped_nsobject.h" #import "ios/chrome/browser/ui/rtl_geometry.h" #import "ios/chrome/browser/ui/stack_view/card_view.h" #import "ios/chrome/browser/ui/ui_util.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + @interface StackCard () { - id<StackCardViewProvider> _viewProvider; - base::scoped_nsobject<CardView> _view; + __weak id<StackCardViewProvider> _viewProvider; + CardView* _view; } // The pixel-aligned frame generated by applying |self.layout| under the current @@ -47,18 +50,17 @@ - (void)releaseView { if (self.viewIsLive) - _view.reset(); + _view = nil; } #pragma mark - Properties - (CardView*)view { if (!_view) { - _view.reset([[_viewProvider cardViewWithFrame:self.frame forStackCard:self] - retain]); - _view.get().isActiveTab = _isActiveTab; + _view = [_viewProvider cardViewWithFrame:self.frame forStackCard:self]; + _view.isActiveTab = _isActiveTab; } - return _view.get(); + return _view; } - (void)setLayout:(LayoutRect)layout { @@ -91,7 +93,7 @@ - (void)setIsActiveTab:(BOOL)isActiveTab { _isActiveTab = isActiveTab; - _view.get().isActiveTab = _isActiveTab; + _view.isActiveTab = _isActiveTab; } - (BOOL)viewIsLive {
diff --git a/ios/chrome/browser/ui/stack_view/stack_view_controller.h b/ios/chrome/browser/ui/stack_view/stack_view_controller.h index 047e369..05979e3 100644 --- a/ios/chrome/browser/ui/stack_view/stack_view_controller.h +++ b/ios/chrome/browser/ui/stack_view/stack_view_controller.h
@@ -27,8 +27,8 @@ // Controller for the tab-switching UI displayed as a stack of tabs. @interface StackViewController : UIViewController<TabSwitcher> -@property(nonatomic, assign) id<TabSwitcherDelegate> delegate; -@property(nonatomic, assign) id<StackViewControllerTestDelegate> testDelegate; +@property(nonatomic, weak) id<TabSwitcherDelegate> delegate; +@property(nonatomic, weak) id<StackViewControllerTestDelegate> testDelegate; // Initializes with the given tab models, which must not be nil. // |activeTabModel| is the model which starts active, and must be one of the
diff --git a/ios/chrome/browser/ui/stack_view/stack_view_controller.mm b/ios/chrome/browser/ui/stack_view/stack_view_controller.mm index 6b2a75f6..0f69111d 100644 --- a/ios/chrome/browser/ui/stack_view/stack_view_controller.mm +++ b/ios/chrome/browser/ui/stack_view/stack_view_controller.mm
@@ -12,13 +12,11 @@ #include "base/format_macros.h" #import "base/ios/block_types.h" -#import "base/ios/weak_nsobject.h" #include "base/logging.h" #import "base/mac/bundle_locations.h" #import "base/mac/foundation_util.h" -#import "base/mac/objc_property_releaser.h" + #include "base/mac/scoped_block.h" -#import "base/mac/scoped_nsobject.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" @@ -58,6 +56,10 @@ #import "net/base/mac/url_conversions.h" #include "ui/base/l10n/l10n_util.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + using base::UserMetricsAction; // To obtain scroll behavior, places the card stacks' display views within a @@ -441,45 +443,44 @@ @end @implementation StackViewController { - base::scoped_nsobject<UIScrollView> _scrollView; + UIScrollView* _scrollView; // The view containing the stack view's background. - base::scoped_nsobject<UIView> _backgroundView; + UIView* _backgroundView; // The main card set. - base::scoped_nsobject<CardSet> _mainCardSet; + CardSet* _mainCardSet; // The off-the-record card set. - base::scoped_nsobject<CardSet> _otrCardSet; + CardSet* _otrCardSet; // The currently active card set; one of _mainCardSet or _otrCardSet. - CardSet* _activeCardSet; // weak - id<TabSwitcherDelegate> _delegate; // weak - id<StackViewControllerTestDelegate> _testDelegate; // weak + __weak CardSet* _activeCardSet; + __weak id<TabSwitcherDelegate> _delegate; + __weak id<StackViewControllerTestDelegate> _testDelegate; // Controller for the stack view toolbar. - base::scoped_nsobject<StackViewToolbarController> _toolbarController; + StackViewToolbarController* _toolbarController; // The size of a card at the time the stack was first shown. CGSize _initialCardSize; // The previous orientation of the interface. UIInterfaceOrientation _lastInterfaceOrientation; // Gesture recognizer to catch taps on the inactive stack. - base::scoped_nsobject<UITapGestureRecognizer> _modeSwitchRecognizer; + UITapGestureRecognizer* _modeSwitchRecognizer; // Gesture recognizer to catch pinches in the active scroll view. - base::scoped_nsobject<UIGestureRecognizer> _pinchRecognizer; + UIGestureRecognizer* _pinchRecognizer; // Gesture recognizer to catch swipes to switch decks/dismiss cards. - base::scoped_nsobject<UIGestureRecognizer> _swipeGestureRecognizer; + UIGestureRecognizer* _swipeGestureRecognizer; // Gesture recognizer that determines whether an ambiguous swipe action // (i.e., a swipe on an active card in the direction that would cause a deck // change) should trigger a change of decks or a card dismissal. - base::scoped_nsobject<UILongPressGestureRecognizer> - _swipeDismissesCardRecognizer; + UILongPressGestureRecognizer* _swipeDismissesCardRecognizer; // Tracks the parameters of gesture-related events. - base::scoped_nsobject<GestureStateTracker> _gestureStateTracker; + GestureStateTracker* _gestureStateTracker; // If |YES|, callbacks to |scrollViewDidScroll:| do not trigger scrolling. // Default is |NO|. BOOL _ignoreScrollCallbacks; // The scroll view's pan gesture recognizer. - UIPanGestureRecognizer* _scrollGestureRecognizer; // weak + __weak UIPanGestureRecognizer* _scrollGestureRecognizer; // Because the removal of the StackCard during a swipe happens in a callback, // track which direction the animation should dismiss with. // |_reverseDismissCard| is only set when the dismissal happens in reverse. - base::scoped_nsobject<StackCard> _reverseDismissCard; + StackCard* _reverseDismissCard; // |YES| if the stack view is in the process of being dismissed. BOOL _isBeingDismissed; // |YES| if the stack view is currently active. @@ -489,8 +490,6 @@ // |YES| if there is card set animation being processed. For testing only. // Save last touch point used by new tab animation. CGPoint _lastTapPoint; - - base::mac::ObjCPropertyReleaser _propertyReleaserStackViewController; } @synthesize activeCardSet = _activeCardSet; @@ -513,25 +512,23 @@ DCHECK(activeCardSet == otrCardSet || activeCardSet == mainCardSet); self = [super initWithNibName:nil bundle:nil]; if (self) { - _propertyReleaserStackViewController.Init(self, - [StackViewController class]); [self setUpWithMainCardSet:mainCardSet otrCardSet:otrCardSet activeCardSet:activeCardSet]; - _swipeDismissesCardRecognizer.reset([[UILongPressGestureRecognizer alloc] + _swipeDismissesCardRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self - action:@selector(handleLongPressFrom:)]); + action:@selector(handleLongPressFrom:)]; [_swipeDismissesCardRecognizer setMinimumPressDuration: kPressDurationForAmbiguousSwipeToTriggerDismissal]; [_swipeDismissesCardRecognizer setDelegate:self]; - _pinchRecognizer.reset([[CardStackPinchGestureRecognizer alloc] + _pinchRecognizer = [[CardStackPinchGestureRecognizer alloc] initWithTarget:self - action:@selector(handlePinchFrom:)]); + action:@selector(handlePinchFrom:)]; [_pinchRecognizer setDelegate:self]; - _modeSwitchRecognizer.reset([[UITapGestureRecognizer alloc] + _modeSwitchRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self - action:@selector(handleTapFrom:)]); + action:@selector(handleTapFrom:)]; [_modeSwitchRecognizer setDelegate:self]; } return self; @@ -543,12 +540,10 @@ DCHECK(mainModel); DCHECK(otrModel); DCHECK(activeModel == otrModel || activeModel == mainModel); - base::scoped_nsobject<CardSet> mainCardSet( - [[CardSet alloc] initWithModel:mainModel]); - base::scoped_nsobject<CardSet> otrCardSet( - [[CardSet alloc] initWithModel:otrModel]); + CardSet* mainCardSet = [[CardSet alloc] initWithModel:mainModel]; + CardSet* otrCardSet = [[CardSet alloc] initWithModel:otrModel]; CardSet* activeCardSet = - (activeModel == mainModel) ? mainCardSet.get() : otrCardSet.get(); + (activeModel == mainModel) ? mainCardSet : otrCardSet; return [self initWithMainCardSet:mainCardSet otrCardSet:otrCardSet activeCardSet:activeCardSet]; @@ -568,21 +563,21 @@ - (void)setUpWithMainCardSet:(CardSet*)mainCardSet otrCardSet:(CardSet*)otrCardSet activeCardSet:(CardSet*)activeCardSet { - _mainCardSet.reset([mainCardSet retain]); - _otrCardSet.reset([otrCardSet retain]); + _mainCardSet = mainCardSet; + _otrCardSet = otrCardSet; if (experimental_flags::IsLRUSnapshotCacheEnabled()) { [_mainCardSet setKeepOnlyVisibleCardViewsAlive:YES]; [_otrCardSet setKeepOnlyVisibleCardViewsAlive:YES]; } _activeCardSet = (activeCardSet == mainCardSet) ? mainCardSet : otrCardSet; - _gestureStateTracker.reset([[GestureStateTracker alloc] init]); - _pinchRecognizer.reset([[CardStackPinchGestureRecognizer alloc] + _gestureStateTracker = [[GestureStateTracker alloc] init]; + _pinchRecognizer = [[CardStackPinchGestureRecognizer alloc] initWithTarget:self - action:@selector(handlePinchFrom:)]); + action:@selector(handlePinchFrom:)]; [_pinchRecognizer setDelegate:self]; - _modeSwitchRecognizer.reset([[UITapGestureRecognizer alloc] - initWithTarget:self - action:@selector(handleTapFrom:)]); + _modeSwitchRecognizer = + [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleTapFrom:)]; [_modeSwitchRecognizer setDelegate:self]; } @@ -593,12 +588,10 @@ DCHECK(otrModel); DCHECK(activeModel == otrModel || activeModel == mainModel); DCHECK(!_isActive); - base::scoped_nsobject<CardSet> mainCardSet( - [[CardSet alloc] initWithModel:mainModel]); - base::scoped_nsobject<CardSet> otrCardSet( - [[CardSet alloc] initWithModel:otrModel]); + CardSet* mainCardSet = [[CardSet alloc] initWithModel:mainModel]; + CardSet* otrCardSet = [[CardSet alloc] initWithModel:otrModel]; CardSet* activeCardSet = - (activeModel == mainModel) ? mainCardSet.get() : otrCardSet.get(); + (activeModel == mainModel) ? mainCardSet : otrCardSet; [self setUpWithMainCardSet:mainCardSet otrCardSet:otrCardSet activeCardSet:activeCardSet]; @@ -630,16 +623,20 @@ // memory notification is not received and the view is never unloaded. [self deregisterForNotifications]; - _mainCardSet.reset(); - _otrCardSet.reset(); + [_mainCardSet disconnect]; + _mainCardSet = nil; + + [_otrCardSet disconnect]; + _otrCardSet = nil; + _activeCardSet = nil; // Remove gesture recognizers and notifications. [self prepareForDismissal]; - _gestureStateTracker.reset(); - _pinchRecognizer.reset(); - _modeSwitchRecognizer.reset(); - _swipeGestureRecognizer.reset(); + _gestureStateTracker = nil; + _pinchRecognizer = nil; + _modeSwitchRecognizer = nil; + _swipeGestureRecognizer = nil; // The cards need to recompute their sizes the next time they are shown. _initialCardSize.height = _initialCardSize.width = 0.0f; @@ -676,12 +673,10 @@ - (void)setUpDisplayViews { CGRect displayViewFrame = CGRectMake(0, 0, [_scrollView frame].size.width, [_scrollView frame].size.height); - base::scoped_nsobject<UIView> mainDisplayView( - [[UIView alloc] initWithFrame:displayViewFrame]); + UIView* mainDisplayView = [[UIView alloc] initWithFrame:displayViewFrame]; [mainDisplayView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; - base::scoped_nsobject<UIView> otrDisplayView( - [[UIView alloc] initWithFrame:displayViewFrame]); + UIView* otrDisplayView = [[UIView alloc] initWithFrame:displayViewFrame]; [otrDisplayView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; @@ -714,7 +709,7 @@ [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)]; [panGestureRecognizer setMaximumNumberOfTouches:1]; - _swipeGestureRecognizer.reset(panGestureRecognizer); + _swipeGestureRecognizer = panGestureRecognizer; [[self view] addGestureRecognizer:_swipeGestureRecognizer]; [_swipeGestureRecognizer setDelegate:self]; } @@ -722,13 +717,13 @@ - (void)loadView { [super loadView]; - _backgroundView.reset([[UIView alloc] initWithFrame:self.view.bounds]); + _backgroundView = [[UIView alloc] initWithFrame:self.view.bounds]; [_backgroundView setAutoresizingMask:(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)]; [self.view addSubview:_backgroundView]; - _toolbarController.reset( - [[StackViewToolbarController alloc] initWithStackViewToolbar]); + _toolbarController = + [[StackViewToolbarController alloc] initWithStackViewToolbar]; CGRect toolbarFrame = [self.view bounds]; toolbarFrame.origin.y = CGRectGetMinY([[_toolbarController view] frame]); toolbarFrame.size.height = CGRectGetHeight([[_toolbarController view] frame]); @@ -742,7 +737,7 @@ toolbarFrame.size.height - kVerticalToolbarOverlap, 0.0, 0.0, 0.0); CGRect scrollViewFrame = UIEdgeInsetsInsetRect(self.view.bounds, contentInsets); - _scrollView.reset([[UIScrollView alloc] initWithFrame:scrollViewFrame]); + _scrollView = [[UIScrollView alloc] initWithFrame:scrollViewFrame]; [self.view addSubview:_scrollView]; [_scrollView setAutoresizingMask:(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)]; @@ -783,7 +778,7 @@ // Reset the gesture state tracker to clear gesture-related information from // the last time the stack view was shown. - _gestureStateTracker.reset([[GestureStateTracker alloc] init]); + _gestureStateTracker = [[GestureStateTracker alloc] init]; [super viewWillAppear:animated]; } @@ -816,7 +811,6 @@ [_mainCardSet setObserver:nil]; [_otrCardSet setObserver:nil]; [self cleanUpViewsAndNotifications]; - [super dealloc]; } // Overridden to always return NO, ensuring that the status bar shows in @@ -960,8 +954,8 @@ // Stop pre-loading cards. [NSObject cancelPreviousPerformRequestsWithTarget:self]; [_scrollView setDelegate:nil]; - _scrollView.reset(); - _backgroundView.reset(); + _scrollView = nil; + _backgroundView = nil; [[NSNotificationCenter defaultCenter] removeObserver:self]; } @@ -1077,8 +1071,8 @@ // world. // (see the comment in -cardSet:willRemoveCard:atIndex for details). [_scrollView setScrollEnabled:NO]; - _pinchRecognizer.get().enabled = NO; - _swipeGestureRecognizer.get().enabled = NO; + _pinchRecognizer.enabled = NO; + _swipeGestureRecognizer.enabled = NO; } - (void)enableGestureHandlers { @@ -1087,8 +1081,8 @@ // world. // (see the comment in -cardSet:willRemoveCard:atIndex for details). [_scrollView setScrollEnabled:YES]; - _pinchRecognizer.get().enabled = YES; - _swipeGestureRecognizer.get().enabled = YES; + _pinchRecognizer.enabled = YES; + _swipeGestureRecognizer.enabled = YES; } - (void)activeCardCountChanged { @@ -1217,11 +1211,11 @@ #pragma mark Current Set Handling - (BOOL)isCurrentSetIncognito { - return _activeCardSet == _otrCardSet.get(); + return _activeCardSet == _otrCardSet; } - (CardSet*)inactiveCardSet { - return [self isCurrentSetIncognito] ? _mainCardSet.get() : _otrCardSet.get(); + return [self isCurrentSetIncognito] ? _mainCardSet : _otrCardSet; } - (void)setActiveCardSet:(CardSet*)cardSet { @@ -1474,7 +1468,7 @@ [_activeCardSet fanOutCardsWithStartIndex:0]; [self postOpenTabsAccessibilityNotification]; UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, - _toolbarController.get().view); + _toolbarController.view); } } @@ -1585,8 +1579,7 @@ self.transitionToolbarFrame = self.transitionToolbarController.view.frame; // Create dummy toolbar background view. - self.dummyToolbarBackgroundView = - [[[UIView alloc] initWithFrame:CGRectZero] autorelease]; + self.dummyToolbarBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; [self.dummyToolbarBackgroundView setClipsToBounds:YES]; // Set the transition completion block. @@ -2065,8 +2058,7 @@ CGRect viewBounds, remainder; CGRectDivide([self.view bounds], &remainder, &viewBounds, statusBarHeight, CGRectMinYEdge); - UIImageView* newCard = - [[[UIImageView alloc] initWithFrame:viewBounds] autorelease]; + UIImageView* newCard = [[UIImageView alloc] initWithFrame:viewBounds]; // Temporarily resize the tab's view to ensure it matches the card while // generating a snapshot, but then restore the original frame. CGRect originalTabFrame = [tab view].frame; @@ -2112,7 +2104,7 @@ return NO; if ((recognizer == _pinchRecognizer) || - (recognizer == _swipeGestureRecognizer.get())) + (recognizer == _swipeGestureRecognizer)) return YES; // Only the mode switch recognizer should be triggered in the inactive deck @@ -2120,7 +2112,7 @@ CGPoint touchLocation = [touch locationInView:_scrollView]; BOOL inInactiveDeckRegion = CGRectContainsPoint([self inactiveDeckRegion], touchLocation); - if (recognizer == _modeSwitchRecognizer.get()) + if (recognizer == _modeSwitchRecognizer) return inInactiveDeckRegion; else if (inInactiveDeckRegion) return NO; @@ -2128,7 +2120,7 @@ // Extract the card on which the touch is occurring. CardView* cardView = nil; StackCard* card = nil; - if (recognizer == _swipeDismissesCardRecognizer.get()) { + if (recognizer == _swipeDismissesCardRecognizer) { UIView* activeView = _activeCardSet.displayView; CGPoint locationInActiveView = [touch locationInView:activeView]; NSUInteger cardIndex = [self indexOfCardAtPoint:locationInActiveView]; @@ -2180,8 +2172,8 @@ (gestureRecognizer == _swipeGestureRecognizer || otherGestureRecognizer == _swipeGestureRecognizer); BOOL swipeDismissesCardRecognizerInvolved = - (gestureRecognizer == _swipeDismissesCardRecognizer.get() || - otherGestureRecognizer == _swipeDismissesCardRecognizer.get()); + (gestureRecognizer == _swipeDismissesCardRecognizer || + otherGestureRecognizer == _swipeDismissesCardRecognizer); if (swipeRecognizerInvolved && swipeDismissesCardRecognizerInvolved) return YES; @@ -2244,7 +2236,7 @@ DCHECK(!_isBeingDismissed); DCHECK(_isActive); - if (recognizer == _swipeDismissesCardRecognizer.get()) + if (recognizer == _swipeDismissesCardRecognizer) return; UIGestureRecognizerState state = [recognizer state]; @@ -2419,7 +2411,7 @@ if (recognizer.state != UIGestureRecognizerStateEnded) return; - if (recognizer == _modeSwitchRecognizer.get()) { + if (recognizer == _modeSwitchRecognizer) { DCHECK(CGRectContainsPoint([self inactiveDeckRegion], [recognizer locationInView:_scrollView])); [self setActiveCardSet:[self inactiveCardSet]]; @@ -2659,7 +2651,7 @@ // Track card if animation should dismiss in reverse from the norm of // clockwise in portrait, counter-clockwise in landscape. if ((isPortrait && !clockwise) || (!isPortrait && clockwise)) - _reverseDismissCard.reset([card retain]); + _reverseDismissCard = card; // This will trigger the completion of the close card animation. [self closeTab:card.view]; } else { @@ -2729,8 +2721,8 @@ } - (void)showToolsMenuPopup { - base::scoped_nsobject<ToolsMenuConfiguration> configuration( - [[ToolsMenuConfiguration alloc] initWithDisplayView:[self view]]); + ToolsMenuConfiguration* configuration = + [[ToolsMenuConfiguration alloc] initWithDisplayView:[self view]]; [configuration setInTabSwitcher:YES]; // When checking for the existence of tabs, catch the case where the main set // is both active and empty, but the incognito set has some cards. @@ -2919,7 +2911,7 @@ completion:nil]; // Reset |reverseDismissCard| if that card was the one dismissed. if ((isPortrait && !clockwise) || (!isPortrait && clockwise)) - _reverseDismissCard.reset(); + _reverseDismissCard = nil; } // Nil out the the closing card after all closing animations have finished. [CATransaction begin]; @@ -2927,7 +2919,7 @@ cardSet.closingCard = nil; }]; // If the last incognito card closes, switch back to just the main set. - if ([cardSet.cards count] == 0 && cardSet == _otrCardSet.get()) { + if ([cardSet.cards count] == 0 && cardSet == _otrCardSet) { [self displayMainCardSetOnly]; } else { NSUInteger numCards = [[cardSet cards] count]; @@ -2976,18 +2968,18 @@ [card.view addAccessibilityTarget:self action:@selector(accessibilityFocusedOnElement:)]; - base::scoped_nsobject<UIGestureRecognizer> tapRecognizer([ - [UITapGestureRecognizer alloc] initWithTarget:self - action:@selector(handleTapFrom:)]); - tapRecognizer.get().delegate = self; - [card.view addGestureRecognizer:tapRecognizer.get()]; + UIGestureRecognizer* tapRecognizer = + [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleTapFrom:)]; + tapRecognizer.delegate = self; + [card.view addGestureRecognizer:tapRecognizer]; - base::scoped_nsobject<UIGestureRecognizer> longPressRecognizer( + UIGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self - action:@selector(handleLongPressFrom:)]); - longPressRecognizer.get().delegate = self; - [card.view addGestureRecognizer:longPressRecognizer.get()]; + action:@selector(handleLongPressFrom:)]; + longPressRecognizer.delegate = self; + [card.view addGestureRecognizer:longPressRecognizer]; } - (void)cardSetRecreatedCards:(CardSet*)cardSet { @@ -3473,15 +3465,12 @@ #pragma mark - UIResponder - (NSArray*)keyCommands { - base::WeakNSObject<StackViewController> weakSelf(self); + __weak StackViewController* weakSelf = self; // Block to execute a command from the |tag|. - base::mac::ScopedBlock<void (^)(NSInteger)> execute( - ^(NSInteger tag) { - [weakSelf - chromeExecuteCommand:[GenericChromeCommand commandWithTag:tag]]; - }, - base::scoped_policy::RETAIN); + void (^execute)(NSInteger) = ^(NSInteger tag) { + [weakSelf chromeExecuteCommand:[GenericChromeCommand commandWithTag:tag]]; + }; return @[ [UIKeyCommand cr_keyCommandWithInput:@"t" @@ -3490,9 +3479,9 @@ IDS_IOS_TOOLS_MENU_NEW_TAB) action:^{ if ([weakSelf isCurrentSetIncognito]) - execute.get()(IDC_NEW_INCOGNITO_TAB); + execute(IDC_NEW_INCOGNITO_TAB); else - execute.get()(IDC_NEW_TAB); + execute(IDC_NEW_TAB); }], [UIKeyCommand cr_keyCommandWithInput:@"n" @@ -3500,16 +3489,16 @@ title:l10n_util::GetNSStringWithFixup( IDS_IOS_TOOLS_MENU_NEW_INCOGNITO_TAB) action:^{ - execute.get()(IDC_NEW_INCOGNITO_TAB); + execute(IDC_NEW_INCOGNITO_TAB); }], [UIKeyCommand cr_keyCommandWithInput:@"n" modifierFlags:UIKeyModifierCommand title:nil action:^{ if ([weakSelf isCurrentSetIncognito]) - execute.get()(IDC_NEW_INCOGNITO_TAB); + execute(IDC_NEW_INCOGNITO_TAB); else - execute.get()(IDC_NEW_TAB); + execute(IDC_NEW_TAB); }], ]; } @@ -3519,7 +3508,7 @@ @implementation StackViewController (Testing) - (UIScrollView*)scrollView { - return _scrollView.get(); + return _scrollView; } @end
diff --git a/ios/chrome/browser/ui/stack_view/stack_view_controller_private.h b/ios/chrome/browser/ui/stack_view/stack_view_controller_private.h index 0bdbdf1..fc01b99f 100644 --- a/ios/chrome/browser/ui/stack_view/stack_view_controller_private.h +++ b/ios/chrome/browser/ui/stack_view/stack_view_controller_private.h
@@ -68,7 +68,7 @@ - (CGRect)inactiveDeckRegion; // The currently active card set. -@property(nonatomic, readonly) CardSet* activeCardSet; +@property(nonatomic, weak, readonly) CardSet* activeCardSet; // The current transition style. @property(nonatomic, assign) StackTransitionStyle transitionStyle; @@ -78,13 +78,13 @@ @property(nonatomic, assign) BOOL transitionWasCancelled; // The owner of |transitionToolbarController|. -@property(nonatomic, retain) id<ToolbarOwner> transitionToolbarOwner; +@property(nonatomic, strong) id<ToolbarOwner> transitionToolbarOwner; // The toolbar controller used in transition animations. -@property(nonatomic, retain) ToolbarController* transitionToolbarController; +@property(nonatomic, strong) ToolbarController* transitionToolbarController; // The dummy view used in the transition animation. -@property(nonatomic, retain) UIView* dummyToolbarBackgroundView; +@property(nonatomic, strong) UIView* dummyToolbarBackgroundView; // The cached frame of the transition toolbar's frame. @property(nonatomic, assign) CGRect transitionToolbarFrame; @@ -92,7 +92,7 @@ // Records which card was tapped mid-presentation animation, if any. // TODO(crbug.com/546209): Implement reversed animations for dismissing with a // new selected card mid-presentation. -@property(nonatomic, retain) StackCard* transitionTappedCard; +@property(nonatomic, strong) StackCard* transitionTappedCard; // |YES| if there is card set animation being processed. @property(nonatomic, readonly) BOOL inActiveDeckChangeAnimation;
diff --git a/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm b/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm index cc9fceb3..8960e4f9 100644 --- a/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm +++ b/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm
@@ -12,6 +12,10 @@ #include "ios/chrome/browser/ui/toolbar/new_tab_button.h" #import "ios/chrome/browser/ui/uikit_ui_util.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + using base::UserMetricsAction; namespace { @@ -21,19 +25,19 @@ } @implementation StackViewToolbarController { - base::scoped_nsobject<UIView> _stackViewToolbar; - base::scoped_nsobject<NewTabButton> _openNewTabButton; + UIView* _stackViewToolbar; + NewTabButton* _openNewTabButton; } - (instancetype)initWithStackViewToolbar { self = [super initWithStyle:ToolbarControllerStyleDarkMode]; if (self) { - _stackViewToolbar.reset( - [[UIView alloc] initWithFrame:[self specificControlsArea]]); + _stackViewToolbar = + [[UIView alloc] initWithFrame:[self specificControlsArea]]; [_stackViewToolbar setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth]; - _openNewTabButton.reset([[NewTabButton alloc] initWithFrame:CGRectZero]); + _openNewTabButton = [[NewTabButton alloc] initWithFrame:CGRectZero]; [_openNewTabButton setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | @@ -61,11 +65,11 @@ } - (NewTabButton*)openNewTabButton { - return _openNewTabButton.get(); + return _openNewTabButton; } - (IBAction)recordUserMetrics:(id)sender { - if (sender == _openNewTabButton.get()) + if (sender == _openNewTabButton) base::RecordAction(UserMetricsAction("MobileToolbarStackViewNewTab")); else [super recordUserMetrics:sender];
diff --git a/ios/chrome/browser/ui/stack_view/title_label.mm b/ios/chrome/browser/ui/stack_view/title_label.mm index 841625e..8f6c98e 100644 --- a/ios/chrome/browser/ui/stack_view/title_label.mm +++ b/ios/chrome/browser/ui/stack_view/title_label.mm
@@ -6,8 +6,12 @@ #include "base/logging.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + @implementation TitleLabel { - id _accessibilityTarget; // weak + __weak id _accessibilityTarget; SEL _accessibilityAction; } @@ -20,7 +24,10 @@ } - (void)accessibilityElementDidBecomeFocused { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" [_accessibilityTarget performSelector:_accessibilityAction withObject:self]; +#pragma clang diagnostic pop } @end
diff --git a/ios/chrome/browser/web/external_app_launcher.mm b/ios/chrome/browser/web/external_app_launcher.mm index 6cc7ee5..50017a1 100644 --- a/ios/chrome/browser/web/external_app_launcher.mm +++ b/ios/chrome/browser/web/external_app_launcher.mm
@@ -10,7 +10,6 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/sys_string_conversions.h" #include "components/strings/grit/components_strings.h" -#include "ios/chrome/browser/experimental_flags.h" #import "ios/chrome/browser/open_url_util.h" #import "ios/chrome/browser/web/mailto_url_rewriter.h" #include "ios/chrome/grit/ios_strings.h" @@ -170,8 +169,7 @@ } // Replaces |URL| with a rewritten URL if it is of mailto: scheme. - if (!experimental_flags::IsNativeAppLauncherEnabled() && - gURL.SchemeIs(url::kMailToScheme)) { + if (gURL.SchemeIs(url::kMailToScheme)) { MailtoURLRewriter* rewriter = [[MailtoURLRewriter alloc] initWithStandardHandlers]; NSString* launchURL = [rewriter rewriteMailtoURL:gURL];
diff --git a/ios/clean/chrome/browser/ui/settings/settings_coordinator.mm b/ios/clean/chrome/browser/ui/settings/settings_coordinator.mm index b01ca7f8..3fcc5f91 100644 --- a/ios/clean/chrome/browser/ui/settings/settings_coordinator.mm +++ b/ios/clean/chrome/browser/ui/settings/settings_coordinator.mm
@@ -27,8 +27,6 @@ self.viewController = [SettingsNavigationController newSettingsMainControllerWithMainBrowserState:self.browser ->browser_state() - currentBrowserState:self.browser - ->browser_state() delegate:self]; [super start]; }
diff --git a/ios/clean/chrome/browser/ui/tools/BUILD.gn b/ios/clean/chrome/browser/ui/tools/BUILD.gn index dafafc3..f5831769 100644 --- a/ios/clean/chrome/browser/ui/tools/BUILD.gn +++ b/ios/clean/chrome/browser/ui/tools/BUILD.gn
@@ -9,8 +9,6 @@ "tools_mediator.h", "tools_mediator.mm", "tools_mediator_private.h", - "tools_menu_model.h", - "tools_menu_model.mm", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -18,9 +16,6 @@ deps = [ ":tools_ui", "//base", - "//components/strings", - "//ios/chrome/app/strings", - "//ios/chrome/browser/ui/tools_menu", "//ios/clean/chrome/browser/ui/animators", "//ios/clean/chrome/browser/ui/commands", "//ios/clean/chrome/browser/ui/presenters", @@ -38,10 +33,11 @@ "menu_overflow_controls_stackview.mm", "menu_view_controller.h", "menu_view_controller.mm", - "tools_actions.h", "tools_consumer.h", "tools_menu_item.h", "tools_menu_item.mm", + "tools_menu_model.h", + "tools_menu_model.mm", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -49,8 +45,11 @@ deps = [ "//base", "//base:i18n", + "//components/strings", + "//ios/chrome/app/strings", "//ios/chrome/app/theme", "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/tools_menu", "//ios/clean/chrome/browser/ui/commands", "//ios/clean/chrome/browser/ui/toolbar:toolbar_components_ui", "//ios/third_party/material_components_ios",
diff --git a/ios/clean/chrome/browser/ui/tools/menu_view_controller.mm b/ios/clean/chrome/browser/ui/tools/menu_view_controller.mm index 81e8c123..e27b6a7 100644 --- a/ios/clean/chrome/browser/ui/tools/menu_view_controller.mm +++ b/ios/clean/chrome/browser/ui/tools/menu_view_controller.mm
@@ -11,13 +11,13 @@ #import "ios/chrome/browser/ui/rtl_geometry.h" #import "ios/chrome/browser/ui/uikit_ui_util.h" #include "ios/chrome/grit/ios_theme_resources.h" +#import "ios/clean/chrome/browser/ui/commands/find_in_page_visibility_commands.h" #import "ios/clean/chrome/browser/ui/commands/navigation_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_button.h" #import "ios/clean/chrome/browser/ui/toolbar/toolbar_constants.h" #import "ios/clean/chrome/browser/ui/tools/menu_overflow_controls_stackview.h" -#import "ios/clean/chrome/browser/ui/tools/tools_actions.h" #import "ios/clean/chrome/browser/ui/tools/tools_menu_item.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" @@ -33,7 +33,7 @@ const CGFloat kCloseButtonHeight = 44.0; } -@interface MenuViewController ()<ToolsActions> +@interface MenuViewController () @property(nonatomic, strong) UIScrollView* menuScrollView; @property(nonatomic, strong) UIStackView* menuStackView; @property(nonatomic, strong) NSArray<ToolsMenuItem*>* menuItems; @@ -237,6 +237,8 @@ // CloseMenu Button Constraint. [self.closeMenuButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor], + [self.closeMenuButton.topAnchor + constraintEqualToAnchor:self.menuScrollView.topAnchor], ]]; }
diff --git a/ios/clean/chrome/browser/ui/tools/tools_actions.h b/ios/clean/chrome/browser/ui/tools/tools_actions.h deleted file mode 100644 index 4a2a83b..0000000 --- a/ios/clean/chrome/browser/ui/tools/tools_actions.h +++ /dev/null
@@ -1,17 +0,0 @@ -// 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 IOS_CLEAN_CHROME_BROWSER_UI_TOOLS_TOOLS_ACTIONS_H_ -#define IOS_CLEAN_CHROME_BROWSER_UI_TOOLS_TOOLS_ACTIONS_H_ - -// Target/Action methods related to the tools menu. -@protocol ToolsActions -@optional - -// Shows the UI for Find in Page. -- (void)showFindInPage; - -@end - -#endif // IOS_CLEAN_CHROME_BROWSER_UI_TOOLS_TOOLS_ACTIONS_H_
diff --git a/ios/clean/chrome/browser/ui/tools/tools_menu_model.mm b/ios/clean/chrome/browser/ui/tools/tools_menu_model.mm index 4e19fa90..1d7d1ad 100644 --- a/ios/clean/chrome/browser/ui/tools/tools_menu_model.mm +++ b/ios/clean/chrome/browser/ui/tools/tools_menu_model.mm
@@ -7,8 +7,8 @@ #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/ui/tools_menu/tools_menu_constants.h" #include "ios/chrome/grit/ios_strings.h" +#import "ios/clean/chrome/browser/ui/commands/find_in_page_visibility_commands.h" #import "ios/clean/chrome/browser/ui/commands/settings_commands.h" -#import "ios/clean/chrome/browser/ui/tools/tools_actions.h" // Declare all the possible items. const MenuModelItem itemsModelList[] = {
diff --git a/ios/showcase/BUILD.gn b/ios/showcase/BUILD.gn index a086611c..2428b75 100644 --- a/ios/showcase/BUILD.gn +++ b/ios/showcase/BUILD.gn
@@ -34,6 +34,7 @@ "//ios/showcase/tab", "//ios/showcase/tab_grid", "//ios/showcase/toolbar", + "//ios/showcase/tools_menu", "//ios/showcase/uikit_table_view_cell", "//ios/showcase/widget", ]
diff --git a/ios/showcase/core/showcase_model.mm b/ios/showcase/core/showcase_model.mm index 51bd3f4..f974949 100644 --- a/ios/showcase/core/showcase_model.mm +++ b/ios/showcase/core/showcase_model.mm
@@ -23,7 +23,7 @@ }, @{ showcase::kClassForDisplayKey : @"MenuViewController", - showcase::kClassForInstantiationKey : @"MenuViewController", + showcase::kClassForInstantiationKey : @"SCToolsCoordinator", showcase::kUseCaseKey : @"Tools menu", }, @{
diff --git a/ios/showcase/tools_menu/BUILD.gn b/ios/showcase/tools_menu/BUILD.gn new file mode 100644 index 0000000..6ab5355 --- /dev/null +++ b/ios/showcase/tools_menu/BUILD.gn
@@ -0,0 +1,19 @@ +# 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. + +source_set("tools_menu") { + sources = [ + "sc_tools_coordinator.h", + "sc_tools_coordinator.mm", + ] + deps = [ + "//base", + "//ios/clean/chrome/browser/ui/commands", + "//ios/clean/chrome/browser/ui/tools:tools_ui", + "//ios/showcase/common", + "//ui/base", + ] + libs = [ "UIKit.framework" ] + configs += [ "//build/config/compiler:enable_arc" ] +}
diff --git a/ios/showcase/tools_menu/sc_tools_coordinator.h b/ios/showcase/tools_menu/sc_tools_coordinator.h new file mode 100644 index 0000000..c4cd82f --- /dev/null +++ b/ios/showcase/tools_menu/sc_tools_coordinator.h
@@ -0,0 +1,15 @@ +// 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 IOS_SHOWCASE_TOOLS_MENU_SC_TOOLS_COORDINATOR_H_ +#define IOS_SHOWCASE_TOOLS_MENU_SC_TOOLS_COORDINATOR_H_ + +#import <UIKit/UIKit.h> + +#import "ios/showcase/common/navigation_coordinator.h" + +@interface SCToolsCoordinator : NSObject<NavigationCoordinator> +@end + +#endif // IOS_SHOWCASE_TOOLS_MENU_SC_TOOLS_COORDINATOR_H_
diff --git a/ios/showcase/tools_menu/sc_tools_coordinator.mm b/ios/showcase/tools_menu/sc_tools_coordinator.mm new file mode 100644 index 0000000..9ff28a3a --- /dev/null +++ b/ios/showcase/tools_menu/sc_tools_coordinator.mm
@@ -0,0 +1,63 @@ +// 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. + +#import "ios/showcase/tools_menu/sc_tools_coordinator.h" + +#include "base/macros.h" +#import "ios/clean/chrome/browser/ui/commands/find_in_page_visibility_commands.h" +#import "ios/clean/chrome/browser/ui/commands/navigation_commands.h" +#import "ios/clean/chrome/browser/ui/commands/settings_commands.h" +#import "ios/clean/chrome/browser/ui/commands/tools_menu_commands.h" +#import "ios/clean/chrome/browser/ui/tools/menu_view_controller.h" +#import "ios/clean/chrome/browser/ui/tools/tools_menu_item.h" +#import "ios/clean/chrome/browser/ui/tools/tools_menu_model.h" +#import "ios/showcase/common/protocol_alerter.h" +#include "ui/base/l10n/l10n_util.h" + +@interface SCToolsCoordinator () +@property(nonatomic, strong) ProtocolAlerter* alerter; +@end + +@implementation SCToolsCoordinator +@synthesize baseViewController = _baseViewController; +@synthesize alerter = _alerter; + +#pragma mark - BrowserCoordinator + +- (void)start { + self.alerter = [[ProtocolAlerter alloc] initWithProtocols:@[ + @protocol(FindInPageVisibilityCommands), @protocol(NavigationCommands), + @protocol(ToolsMenuCommands), @protocol(SettingsCommands) + ]]; + self.alerter.baseViewController = self.baseViewController; + + MenuViewController* viewController = [[MenuViewController alloc] init]; + viewController.modalPresentationStyle = UIModalPresentationCustom; + viewController.dispatcher = + static_cast<id<FindInPageVisibilityCommands, NavigationCommands, + ToolsMenuCommands, SettingsCommands>>(self.alerter); + + NSMutableArray* menuItems = [NSMutableArray array]; + + // Load the full model into the VC. + for (size_t i = 0; i < arraysize(itemsModelList); ++i) { + const MenuModelItem& modelItem = itemsModelList[i]; + ToolsMenuItem* menuItem = [[ToolsMenuItem alloc] init]; + menuItem.title = l10n_util::GetNSStringWithFixup(modelItem.title_id); + menuItem.action = NSSelectorFromString(modelItem.selector); + [menuItems addObject:menuItem]; + } + [viewController setToolsMenuItems:menuItems]; + + // The Overflow controls will only be displayed on CompactWidth SizeClasses. + [viewController setDisplayOverflowControls:YES]; + + // Since the close MenuButton is always located on the top right corner, + // set the navigation translucency to NO so it doesn't cover the button. + self.baseViewController.navigationBar.translucent = NO; + + [self.baseViewController pushViewController:viewController animated:YES]; +} + +@end
diff --git a/ios/web/public/web_state/ui/crw_web_delegate.h b/ios/web/public/web_state/ui/crw_web_delegate.h index 181cf06..ce7f274a 100644 --- a/ios/web/public/web_state/ui/crw_web_delegate.h +++ b/ios/web/public/web_state/ui/crw_web_delegate.h
@@ -70,15 +70,6 @@ - (BOOL)webController:(CRWWebController*)webController shouldOpenExternalURL:(const GURL&)URL; -// Called when |URL| is deemed suitable to be opened in a matching native app. -// Needs to return whether |URL| was opened in a matching native app. -// Also triggering user action |linkClicked| is passed to use it when needed. -// The return value indicates if the native app was launched, not if a native -// app was found. -- (BOOL)urlTriggersNativeAppLaunch:(const GURL&)URL - sourceURL:(const GURL&)sourceURL - linkClicked:(BOOL)linkClicked; - // Called to ask the delegate for a controller to display the given url, // which contained content that the UIWebView couldn't display. Returns // the native controller to display if the delegate can handle the url,
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 49e05b2..81a8edd 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -755,11 +755,6 @@ - (BOOL)shouldOpenURL:(const GURL&)url mainDocumentURL:(const GURL&)mainDocumentURL linkClicked:(BOOL)linkClicked; -// Called when |URL| needs to be opened in a matching native app. -// Returns YES if the url was succesfully opened in the native app. -- (BOOL)urlTriggersNativeAppLaunch:(const GURL&)URL - sourceURL:(const GURL&)sourceURL - linkActivatedNavigation:(BOOL)linkActivatedNavigation; // Returns YES if the navigation action is associated with a main frame request. - (BOOL)isMainFrameNavigationAction:(WKNavigationAction*)action; // Returns whether external URL navigation action should be opened. @@ -2947,43 +2942,17 @@ // method, which provides less information than the WKWebView version. Audit // this for things that should be handled in the subclass instead. - (BOOL)shouldAllowLoadWithNavigationAction:(WKNavigationAction*)action { - NSURLRequest* request = action.request; - GURL requestURL = net::GURLWithNSURL(request.URL); - // External application launcher needs |isNavigationTypeLinkActivated| to // decide if the user intended to open the application by clicking on a link. BOOL isNavigationTypeLinkActivated = action.navigationType == WKNavigationTypeLinkActivated; - // Checks if the link navigation leads to a launch of an external app. - // TODO(crbug.com/704417): External apps will not be launched from clicking - // a Bookmarked URL or a Recently Closed URL. - // TODO(crbug.com/607780): Revise the logic of allowing external app launch - // and move it to externalAppLauncher. - BOOL isOpenInNewTabNavigation = !(self.navigationManagerImpl->GetItemCount()); - BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType]; - if (isPossibleLinkClick || isOpenInNewTabNavigation) { - web::NavigationItem* item = self.currentNavItem; - const GURL currentNavigationURL = - item ? item->GetVirtualURL() : GURL::EmptyGURL(); - // Check If the URL is handled by a native app. - if ([self urlTriggersNativeAppLaunch:requestURL - sourceURL:currentNavigationURL - linkActivatedNavigation:isNavigationTypeLinkActivated]) { - // External app has been launched successfully. Stop the current page - // load operation (e.g. notifying all observers) and record the URL so - // that errors reported following the 'NO' reply can be safely ignored. - if ([self shouldClosePageOnNativeApplicationLoad]) - _webStateImpl->CloseWebState(); - [self stopLoading]; - [_openedApplicationURL addObject:request.URL]; - return NO; - } - } - // The WebDelegate may instruct the CRWWebController to stop loading, and // instead instruct the next page to be loaded in an animation. + NSURLRequest* request = action.request; + GURL requestURL = net::GURLWithNSURL(request.URL); GURL mainDocumentURL = net::GURLWithNSURL(request.mainDocumentURL); + BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType]; DCHECK(_webView); if (![self shouldOpenURL:requestURL mainDocumentURL:mainDocumentURL @@ -3821,19 +3790,6 @@ [_delegate webController:self shouldOpenExternalURL:requestURL]; } -- (BOOL)urlTriggersNativeAppLaunch:(const GURL&)URL - sourceURL:(const GURL&)sourceURL - linkActivatedNavigation:(BOOL)linkActivatedNavigation { - if (![_delegate respondsToSelector:@selector(urlTriggersNativeAppLaunch: - sourceURL: - linkClicked:)]) { - return NO; - } - return [_delegate urlTriggersNativeAppLaunch:URL - sourceURL:sourceURL - linkClicked:linkActivatedNavigation]; -} - - (CGFloat)headerHeight { if (![_delegate respondsToSelector:@selector(headerHeightForWebController:)]) return 0.0f;
diff --git a/media/audio/audio_io.h b/media/audio/audio_io.h index 272c617e..d8d0e699 100644 --- a/media/audio/audio_io.h +++ b/media/audio/audio_io.h
@@ -119,18 +119,10 @@ // Called by the audio recorder when a full packet of audio data is // available. This is called from a special audio thread and the // implementation should return as soon as possible. - // TODO(henrika): should be pure virtual when old OnData() is phased out. virtual void OnData(AudioInputStream* stream, const AudioBus* source, uint32_t hardware_delay_bytes, - double volume) {} - - // TODO(henrika): don't use; to be removed. - virtual void OnData(AudioInputStream* stream, - const uint8_t* src, - uint32_t size, - uint32_t hardware_delay_bytes, - double volume) {} + double volume) = 0; // There was an error while recording audio. The audio sink cannot be // destroyed yet. No direct action needed by the AudioInputStream, but it
diff --git a/media/base/media_switches.cc b/media/base/media_switches.cc index df77c1c..70ece28 100644 --- a/media/base/media_switches.cc +++ b/media/base/media_switches.cc
@@ -288,15 +288,6 @@ const base::Feature kDelayCopyNV12Textures{"DelayCopyNV12Textures", base::FEATURE_ENABLED_BY_DEFAULT}; -// Enables code paths accessing controls exposed by video capture devices in the -// context of capturing still images. Note that several webcam drivers have -// shown issues when accessing these controls, resulting in symptoms such as -// video capture outputting blank images or images with incorrect settings for -// things like zoom, white balance, contrast, focus, etc, see -// https://crbug.com/722038. -const base::Feature kImageCaptureControls{"ImageCaptureControls", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Enables H264 HW encode acceleration using Media Foundation for Windows. const base::Feature kMediaFoundationH264Encoding{ "MediaFoundationH264Encoding", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/media/base/media_switches.h b/media/base/media_switches.h index 772b5b3..89e2e61 100644 --- a/media/base/media_switches.h +++ b/media/base/media_switches.h
@@ -129,7 +129,6 @@ #if defined(OS_WIN) MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoding; MEDIA_EXPORT extern const base::Feature kDelayCopyNV12Textures; -MEDIA_EXPORT extern const base::Feature kImageCaptureControls; MEDIA_EXPORT extern const base::Feature kMediaFoundationH264Encoding; #endif // defined(OS_WIN)
diff --git a/media/blink/resource_multibuffer_data_provider.cc b/media/blink/resource_multibuffer_data_provider.cc index 7a7c2f5..378e9e5 100644 --- a/media/blink/resource_multibuffer_data_provider.cc +++ b/media/blink/resource_multibuffer_data_provider.cc
@@ -114,7 +114,8 @@ } else { WebAssociatedURLLoaderOptions options; if (url_data_->cors_mode() == UrlData::CORS_UNSPECIFIED) { - options.allow_credentials = true; + options.fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeInclude; options.fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; } else { options.expose_all_response_headers = true; @@ -122,8 +123,13 @@ options.preflight_policy = WebAssociatedURLLoaderOptions::kPreventPreflight; options.fetch_request_mode = WebURLRequest::kFetchRequestModeCORS; - if (url_data_->cors_mode() == UrlData::CORS_USE_CREDENTIALS) - options.allow_credentials = true; + if (url_data_->cors_mode() == UrlData::CORS_USE_CREDENTIALS) { + options.fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeInclude; + } else { + options.fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeSameOrigin; + } } loader.reset(url_data_->frame()->CreateAssociatedURLLoader(options)); }
diff --git a/media/capture/video/win/video_capture_device_factory_win.cc b/media/capture/video/win/video_capture_device_factory_win.cc index c9172b63..c044c52 100644 --- a/media/capture/video/win/video_capture_device_factory_win.cc +++ b/media/capture/video/win/video_capture_device_factory_win.cc
@@ -426,9 +426,7 @@ device.reset(); } else if (device_descriptor.capture_api == VideoCaptureApi::WIN_DIRECT_SHOW) { - device.reset(new VideoCaptureDeviceWin( - device_descriptor, - base::FeatureList::IsEnabled(kImageCaptureControls))); + device.reset(new VideoCaptureDeviceWin(device_descriptor)); DVLOG(1) << " DirectShow Device: " << device_descriptor.display_name; if (!static_cast<VideoCaptureDeviceWin*>(device.get())->Init()) device.reset();
diff --git a/media/capture/video/win/video_capture_device_win.cc b/media/capture/video/win/video_capture_device_win.cc index 532722a..ce27a07c 100644 --- a/media/capture/video/win/video_capture_device_win.cc +++ b/media/capture/video/win/video_capture_device_win.cc
@@ -264,10 +264,8 @@ } VideoCaptureDeviceWin::VideoCaptureDeviceWin( - const VideoCaptureDeviceDescriptor& device_descriptor, - bool allow_image_capture_controls) + const VideoCaptureDeviceDescriptor& device_descriptor) : device_descriptor_(device_descriptor), - allow_image_capture_controls_(allow_image_capture_controls), state_(kIdle), white_balance_mode_manual_(false), exposure_mode_manual_(false) { @@ -468,13 +466,8 @@ client_->OnStarted(); state_ = kCapturing; - if (allow_image_capture_controls_) - InitializeVideoAndCameraControls(); -} - -void VideoCaptureDeviceWin::InitializeVideoAndCameraControls() { base::win::ScopedComPtr<IKsTopologyInfo> info; - HRESULT hr = capture_filter_.CopyTo(info.GetAddressOf()); + hr = capture_filter_.CopyTo(info.GetAddressOf()); if (FAILED(hr)) { SetErrorState(FROM_HERE, "Failed to obtain the topology info.", hr); return; @@ -532,10 +525,6 @@ void VideoCaptureDeviceWin::TakePhoto(TakePhotoCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); - - if (!allow_image_capture_controls_) - return; - // DirectShow has other means of capturing still pictures, e.g. connecting a // SampleGrabber filter to a PIN_CATEGORY_STILL of |capture_filter_|. This // way, however, is not widespread and proves too cumbersome, so we just grab @@ -546,7 +535,7 @@ void VideoCaptureDeviceWin::GetPhotoState(GetPhotoStateCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!camera_control_ || !video_control_ || !allow_image_capture_controls_) + if (!camera_control_ || !video_control_) return; auto photo_capabilities = mojom::PhotoState::New(); @@ -638,7 +627,7 @@ VideoCaptureDevice::SetPhotoOptionsCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!camera_control_ || !video_control_ || !allow_image_capture_controls_) + if (!camera_control_ || !video_control_) return; HRESULT hr;
diff --git a/media/capture/video/win/video_capture_device_win.h b/media/capture/video/win/video_capture_device_win.h index f6d28d7..8a2ed6cc 100644 --- a/media/capture/video/win/video_capture_device_win.h +++ b/media/capture/video/win/video_capture_device_win.h
@@ -65,8 +65,8 @@ static VideoPixelFormat TranslateMediaSubtypeToPixelFormat( const GUID& sub_type); - VideoCaptureDeviceWin(const VideoCaptureDeviceDescriptor& device_descriptor, - bool allow_image_capture_controls); + explicit VideoCaptureDeviceWin( + const VideoCaptureDeviceDescriptor& device_descriptor); ~VideoCaptureDeviceWin() override; // Opens the device driver for this device. bool Init(); @@ -89,8 +89,6 @@ // User needs to recover by destroying the object. }; - void InitializeVideoAndCameraControls(); - // Implements SinkFilterObserver. void FrameReceived(const uint8_t* buffer, int length, @@ -104,7 +102,6 @@ HRESULT hr); const VideoCaptureDeviceDescriptor device_descriptor_; - const bool allow_image_capture_controls_; InternalState state_; std::unique_ptr<VideoCaptureDevice::Client> client_;
diff --git a/net/data/ssl/certificate_transparency/log_list.json b/net/data/ssl/certificate_transparency/log_list.json index 214c0354..6ea5b39 100644 --- a/net/data/ssl/certificate_transparency/log_list.json +++ b/net/data/ssl/certificate_transparency/log_list.json
@@ -67,6 +67,16 @@ "dns_api_endpoint": "digicert.ct.googleapis.com" }, { + "description": "DigiCert Log Server 2", + "key": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzF05L2a4TH/BLgOhNKPoioYCrkoRxvcmajeb8Dj4XQmNY+gxa4Zmz3mzJTwe33i0qMVp+rfwgnliQ/bM/oFmhA==", + "url": "ct2.digicert-ct.com/log/", + "maximum_merge_delay": 86400, + "operated_by": [ + 1 + ], + "dns_api_endpoint": "digicert2.ct.googleapis.com" + }, + { "description": "Symantec log", "key": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEluqsHEYMG1XcDfy1lCdGV0JwOmkY4r87xNuroPS2bMBTP01CEDPwWJePa75y9CrsHEKqAy8afig1dpkIPSEUhg==", "url": "ct.ws.symantec.com/", @@ -87,6 +97,16 @@ "dns_api_endpoint": "symantec-vega.ct.googleapis.com" }, { + "description": "Symantec 'Sirius' log", + "key": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEowJkhCK7JewN47zCyYl93UXQ7uYVhY/Z5xcbE4Dq7bKFN61qxdglnfr0tPNuFiglN+qjN2Syxwv9UeXBBfQOtQ==", + "url": "sirius.ws.symantec.com/", + "maximum_merge_delay": 86400, + "operated_by": [ + 2 + ], + "dns_api_endpoint": "symantec-sirius.ct.googleapis.com" + }, + { "description": "Certly.IO log", "key": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECyPLhWKYYUgEc+tUXfPQB4wtGS2MNvXrjwFCCnyYJifBtd2Sk7Cu+Js9DNhMTh35FftHaHu6ZrclnNBKwmbbSA==", "url": "log.certly.io/",
diff --git a/testing/buildbot/chromium.goma.json b/testing/buildbot/chromium.goma.json index 0967ef4..8d3bcf8 100644 --- a/testing/buildbot/chromium.goma.json +++ b/testing/buildbot/chromium.goma.json
@@ -1 +1,22 @@ -{} +{ + "Chromium Linux Goma GCE Staging": { + "additional_compile_targets": [ + "all" + ] + }, + "Chromium Linux Goma Staging": { + "additional_compile_targets": [ + "all" + ] + }, + "Chromium Mac Goma Staging": { + "additional_compile_targets": [ + "all" + ] + }, + "CrWinGomaStaging": { + "additional_compile_targets": [ + "all" + ] + } +}
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 218c6b3..6ae40072 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -23347,6 +23347,7 @@ crbug.com/591099 virtual/mojo-loading/http/tests/inspector/appcache/appcache-iframe-manifests.html [ Pass Timeout ] crbug.com/591099 virtual/mojo-loading/http/tests/inspector/appcache/appcache-manifest-with-non-existing-file.html [ Pass Timeout ] crbug.com/591099 virtual/mojo-loading/http/tests/inspector/appcache/appcache-swap.html [ Pass Timeout ] +crbug.com/591099 virtual/mojo-loading/http/tests/inspector/application-panel/storage-view-reports-quota.html [ Pass Timeout ] crbug.com/591099 virtual/mojo-loading/http/tests/inspector/bindings/livelocation-main-frame-navigated.html [ Failure Pass Timeout ] crbug.com/591099 virtual/mojo-loading/http/tests/inspector/network/network-fetch.html [ Pass Timeout ] crbug.com/591099 virtual/mojo-loading/http/tests/inspector/network/network-filters.html [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/characteristicProperties.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/characteristicProperties.html index 8961b76..ffbb923 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/characteristicProperties.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/characteristicProperties.html
@@ -2,25 +2,25 @@ <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script src="../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => { - return Promise.all([service.getCharacteristic('body_sensor_location'), - service.getCharacteristic('heart_rate_measurement')]); - }).then(characteristics => { - let bsl_properties = characteristics[0].properties; - let bsl_expected_properties = new TestCharacteristicProperties({read: true}); - assert_properties_equal(bsl_properties, bsl_expected_properties); + return getHealthThermometerService() + .then(({service}) => Promise.all([ + service.getCharacteristic('temperature_measurement'), + service.getCharacteristic('measurement_interval')])) + .then(([temperature_measurement, measurement_interval]) => { + let tm_expected_properties = new TestCharacteristicProperties([ + 'indicate']); + assert_properties_equal(temperature_measurement.properties, + tm_expected_properties); - let hrm_properties = characteristics[1].properties; - let hrm_expected_properties = new TestCharacteristicProperties({notify: true}); - assert_properties_equal(hrm_properties, hrm_expected_properties); + let mi_expected_properties = new TestCharacteristicProperties([ + 'read', 'write', 'indicate']); + assert_properties_equal(measurement_interval.properties, + mi_expected_properties); }); }, 'HeartRate device properties'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/add-multiple-event-listeners.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/add-multiple-event-listeners.html index fc640eba..9fbb4f9 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/add-multiple-event-listeners.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/add-multiple-event-listeners.html
@@ -2,20 +2,19 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => service.getCharacteristic('body_sensor_location')) - .then(characteristic => { - return assert_promise_resolves_after_event(characteristic, - 'readValue', - 'characteristicvaluechanged', - 3 /* attach 3 listeners */); + return getMeasurementIntervalCharacteristic() + .then(({characteristic, fake_characteristic}) => { + return fake_characteristic.setNextReadResponse(GATT_SUCCESS, [0,1,2]) + .then(() => assert_promise_resolves_after_event( + characteristic, + 'readValue', + 'characteristicvaluechanged', + 3 /* attach 3 listeners */)); }).then(results => { let read_value = results[0].buffer; let event_values = results.slice(1).map(v => v.buffer);
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/event-is-fired.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/event-is-fired.html index e95a09b..b1456067 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/event-is-fired.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/event-is-fired.html
@@ -2,19 +2,18 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => service.getCharacteristic('body_sensor_location')) - .then(characteristic => { - return assert_promise_resolves_after_event(characteristic, - 'readValue', - 'characteristicvaluechanged'); + return getMeasurementIntervalCharacteristic() + .then(({characteristic, fake_characteristic}) => { + return fake_characteristic.setNextReadResponse(GATT_SUCCESS, [0, 1, 2]) + .then(() => assert_promise_resolves_after_event( + characteristic, + 'readValue', + 'characteristicvaluechanged')); }).then(results => { let read_value = results[0].buffer; let event_value = results[1].buffer;
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-succeeds.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-succeeds.html index 3ca5e83..d762359 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-succeeds.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-succeeds.html
@@ -2,21 +2,21 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('generic_access')) - .then(service => service.getCharacteristic('gap.device_name')) - .then(characteristic => characteristic.readValue()) - .then(value => { - let decoder = new TextDecoder('utf-8'); - let value_str = decoder.decode(value); - assert_equals(value_str, 'Heart Rate Device'); + const EXPECTED_VALUE = [0, 1, 2]; + return getMeasurementIntervalCharacteristic() + .then(({characteristic, fake_characteristic}) => { + return fake_characteristic.setNextReadResponse( + GATT_SUCCESS, EXPECTED_VALUE) + .then(() => characteristic.readValue()) + .then(value => { + assert_array_equals(Array.from(new Uint8Array(value.buffer)), + EXPECTED_VALUE); + }); }); }, 'A read request succeeds and returns the characteristic\'s value.'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-updates-value.html b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-updates-value.html index 5dccc792..081c38a 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-updates-value.html +++ b/third_party/WebKit/LayoutTests/bluetooth/characteristic/readValue/read-updates-value.html
@@ -2,23 +2,24 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('generic_access')) - .then(service => service.getCharacteristic('gap.device_name')) - .then(characteristic => { + const EXPECTED_VALUE = [0, 1, 2]; + return getMeasurementIntervalCharacteristic() + .then(({characteristic, fake_characteristic}) => { assert_equals(characteristic.value, null); - return characteristic.readValue().then(() => { - let decoder = new TextDecoder('utf-8'); - let value_str = decoder.decode(characteristic.value); - assert_equals(value_str, 'Heart Rate Device'); - }) + return fake_characteristic + .setNextReadResponse( + GATT_SUCCESS, EXPECTED_VALUE) + .then(() => characteristic.readValue()) + .then(() => { + assert_array_equals( + Array.from(new Uint8Array(characteristic.value.buffer)), + EXPECTED_VALUE); + }); }); }, 'Succesful read should update characteristic.value'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/blocklisted-characteristic.js b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/blocklisted-characteristic.js index 34669a5..c4de902bf 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/blocklisted-characteristic.js +++ b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/blocklisted-characteristic.js
@@ -1,10 +1,7 @@ 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('BlocklistTestAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['device_information']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('device_information')) + return getHIDDevice({filters: [{services: ['device_information']}]}) + .then(({device}) => device.gatt.getPrimaryService('device_information')) .then(service => { return assert_promise_rejects_with_message( service.CALLS([
diff --git a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/characteristic-not-found.js b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/characteristic-not-found.js index 8b7269a..4bbb3db 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/characteristic-not-found.js +++ b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/characteristic-not-found.js
@@ -1,17 +1,13 @@ 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('heart_rate')) - .then(service => assert_promise_rejects_with_message( + return getEmptyHealthThermometerService() + .then(({service}) => assert_promise_rejects_with_message( service.CALLS([ getCharacteristic('battery_level')| getCharacteristics('battery_level')[UUID] ]), new DOMException( 'No Characteristics matching UUID ' + battery_level.uuid + ' found ' + - 'in Service with UUID ' + heart_rate.uuid + '.', + 'in Service with UUID ' + health_thermometer.uuid + '.', 'NotFoundError'))); }, 'Request for absent characteristics with UUID. Reject with NotFoundError.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/get-same-object.js b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/get-same-object.js index ef18953..c33952e 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/get-same-object.js +++ b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/get-same-object.js
@@ -1,31 +1,24 @@ 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => Promise.all([ + return getHealthThermometerService() + .then(({service}) => Promise.all([ service.CALLS([ - getCharacteristic('body_sensor_location')| + getCharacteristic('measurement_interval')| getCharacteristics()| - getCharacteristics('body_sensor_location')[UUID]]), + getCharacteristics('measurement_interval')[UUID]]), service.PREVIOUS_CALL])) - .then(characteristics_arrays => { + .then(([characteristics_first_call, characteristics_second_call]) => { // Convert to arrays if necessary. - for (let i = 0; i < characteristics_arrays.length; i++) { - characteristics_arrays[i] = [].concat(characteristics_arrays[i]); - } + characteristics_first_call = [].concat(characteristics_first_call); + characteristics_second_call = [].concat(characteristics_second_call); - for (let i = 1; i < characteristics_arrays.length; i++) { - assert_equals(characteristics_arrays[0].length, - characteristics_arrays[i].length); - } + let first_call_set = new Set(characteristics_first_call); + assert_equals(characteristics_first_call.length, first_call_set.size); + let second_call_set = new Set(characteristics_second_call); + assert_equals(characteristics_second_call.length, second_call_set.size); - let base_set = new Set(characteristics_arrays[0]); - for (let characteristics of characteristics_arrays) { - characteristics.forEach( - characteristic => assert_true(base_set.has(characteristic))); - } + characteristics_first_call.forEach(characteristic => { + assert_true(second_call_set.has(characteristic)); + }); }); }, 'Calls to FUNCTION_NAME should return the same object.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/invalid-characteristic-name.js b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/invalid-characteristic-name.js index 70866d3..74c1e9db 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/invalid-characteristic-name.js +++ b/third_party/WebKit/LayoutTests/bluetooth/script-tests/service/invalid-characteristic-name.js
@@ -1,12 +1,7 @@ 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('generic_access')) - .then(service => { + return getHealthThermometerService() + .then(({service}) => { return assert_promise_rejects_with_message( service.CALLS([ getCharacteristic('wrong_name')|
diff --git a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services-with-uuid.html b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services-with-uuid.html index 39d834d..15d1086 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services-with-uuid.html +++ b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services-with-uuid.html
@@ -8,7 +8,7 @@ 'use strict'; promise_test(() => { return getHIDDevice({ - filters: [{services: ['battery_service']}], + filters: [{services: ['device_information']}], optionalServices: ['human_interface_device']}) .then(({device}) => assert_promise_rejects_with_message( device.gatt.getPrimaryServices('human_interface_device'),
diff --git a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services.html b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services.html index f7d2592a..08842d5 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services.html +++ b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/blocklisted-services.html
@@ -8,7 +8,7 @@ 'use strict'; promise_test(() => { return getHIDDevice({ - filters: [{services: ['battery_service']}], + filters: [{services: ['device_information']}], optionalServices: [ 'generic_access', 'human_interface_device' @@ -20,7 +20,7 @@ assert_equals(uuid_set.size, 2); assert_true(uuid_set.has(BluetoothUUID.getService('generic_access'))); - assert_true(uuid_set.has(BluetoothUUID.getService('battery_service'))); + assert_true(uuid_set.has(BluetoothUUID.getService('device_information'))); assert_false( uuid_set.has(BluetoothUUID.getService('human_interface_device'))); });
diff --git a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/correct-services.html b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/correct-services.html index 5228f3d..ec51588 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/correct-services.html +++ b/third_party/WebKit/LayoutTests/bluetooth/server/getPrimaryServices/correct-services.html
@@ -2,20 +2,36 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('TwoHeartRateServicesAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryServices('heart_rate')) - .then(services => Promise.all([ - services[0].getCharacteristics(), - services[1].getCharacteristics()])) - .then(characteristics_arrays => { - assert_equals(characteristics_arrays[0].length, 2); - assert_equals(characteristics_arrays[1].length, 1); + return getConnectedHealthThermometerDevice({ + filters: [{services: ['health_thermometer']}] + }) + .then(({device, fake_peripheral, fake_health_thermometer}) => { + return fake_peripheral.addFakeService({uuid: 'health_thermometer'}) + .then(fake_service => Promise.all([ + fake_service.addFakeCharacteristic({ + uuid: 'temperature_measurement', properties: ['indicate']}), + fake_service.addFakeCharacteristic({ + uuid: 'temperature_measurement', properties: ['indicate']}) + ])) + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => device.gatt.getPrimaryServices('health_thermometer')) + .then(services => Promise.all([ + services[0].getCharacteristics(), + services[1].getCharacteristics()])) + .then(([characteristics1, characteristics2]) => { + if (characteristics1.length === 2) + assert_equals(characteristics2.length, 3); + else if (characteristics2.length === 2) + assert_equals(characteristics1.length, 3); + else + assert_unreached('Invalid lengths.'); + }); }); }, 'Find correct services with UUID.'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/characteristic-found.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/characteristic-found.html index 860f215..0b8a44d 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/characteristic-found.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/characteristic-found.html
@@ -2,24 +2,22 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('generic_access')) + return getHealthThermometerDevice() + .then(({device}) => device.gatt.getPrimaryService('health_thermometer')) .then(service => { return Promise.all([ - service.getCharacteristic(device_name.alias), - service.getCharacteristic(device_name.name), - service.getCharacteristic(device_name.uuid)]) + service.getCharacteristic(measurement_interval.alias), + service.getCharacteristic(measurement_interval.name), + service.getCharacteristic(measurement_interval.uuid)]) .then(characteristics => { characteristics.forEach(characteristic => { assert_equals( - characteristic.uuid, device_name.uuid, + characteristic.uuid, measurement_interval.uuid, 'Characteristic UUID should be the same as requested UUID.'); assert_equals( characteristic.service, service,
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-blocklisted-characteristic.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-blocklisted-characteristic.html index 8298f96..b712dd53 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-blocklisted-characteristic.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-blocklisted-characteristic.html
@@ -8,11 +8,8 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('BlocklistTestAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['device_information']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('device_information')) + return getHIDDevice({filters: [{services: ['device_information']}]}) + .then(({device}) => device.gatt.getPrimaryService('device_information')) .then(service => { return assert_promise_rejects_with_message( service.getCharacteristic('serial_number_string'),
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-characteristic-not-found.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-characteristic-not-found.html index 2fc5c3e..6f35b9d 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-characteristic-not-found.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-characteristic-not-found.html
@@ -8,16 +8,12 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('heart_rate')) - .then(service => assert_promise_rejects_with_message( + return getEmptyHealthThermometerService() + .then(({service}) => assert_promise_rejects_with_message( service.getCharacteristic('battery_level'), new DOMException( 'No Characteristics matching UUID ' + battery_level.uuid + ' found ' + - 'in Service with UUID ' + heart_rate.uuid + '.', + 'in Service with UUID ' + health_thermometer.uuid + '.', 'NotFoundError'))); }, 'Request for absent characteristics with UUID. Reject with NotFoundError.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-get-same-object.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-get-same-object.html index 95551ad..fe50b84dd 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-get-same-object.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-get-same-object.html
@@ -8,30 +8,23 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => Promise.all([ - service.getCharacteristic('body_sensor_location'), - service.getCharacteristic('body_sensor_location')])) - .then(characteristics_arrays => { + return getHealthThermometerService() + .then(({service}) => Promise.all([ + service.getCharacteristic('measurement_interval'), + service.getCharacteristic('measurement_interval')])) + .then(([characteristics_first_call, characteristics_second_call]) => { // Convert to arrays if necessary. - for (let i = 0; i < characteristics_arrays.length; i++) { - characteristics_arrays[i] = [].concat(characteristics_arrays[i]); - } + characteristics_first_call = [].concat(characteristics_first_call); + characteristics_second_call = [].concat(characteristics_second_call); - for (let i = 1; i < characteristics_arrays.length; i++) { - assert_equals(characteristics_arrays[0].length, - characteristics_arrays[i].length); - } + let first_call_set = new Set(characteristics_first_call); + assert_equals(characteristics_first_call.length, first_call_set.size); + let second_call_set = new Set(characteristics_second_call); + assert_equals(characteristics_second_call.length, second_call_set.size); - let base_set = new Set(characteristics_arrays[0]); - for (let characteristics of characteristics_arrays) { - characteristics.forEach( - characteristic => assert_true(base_set.has(characteristic))); - } + characteristics_first_call.forEach(characteristic => { + assert_true(second_call_set.has(characteristic)); + }); }); }, 'Calls to getCharacteristic should return the same object.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-invalid-characteristic-name.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-invalid-characteristic-name.html index bedf50d..7cf635b 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-invalid-characteristic-name.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristic/gen-invalid-characteristic-name.html
@@ -8,13 +8,8 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('generic_access')) - .then(service => { + return getHealthThermometerService() + .then(({service}) => { return assert_promise_rejects_with_message( service.getCharacteristic('wrong_name'), new DOMException(
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/blocklisted-characteristics.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/blocklisted-characteristics.html index 905dfdff..5ae3941 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/blocklisted-characteristics.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/blocklisted-characteristics.html
@@ -2,14 +2,13 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('BlocklistTestAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['device_information']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('device_information')) + return getHIDDevice({filters: [{services: ['device_information']}]}) + .then(({device}) => device.gatt.getPrimaryService('device_information')) .then(service => assert_promise_rejects_with_message( service.getCharacteristics(), new DOMException('No Characteristics found in service.',
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found-with-uuid.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found-with-uuid.html index 3ae6c49b..788994f2 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found-with-uuid.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found-with-uuid.html
@@ -2,26 +2,47 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => Promise.all([ - service.getCharacteristics(body_sensor_location.alias), - service.getCharacteristics(body_sensor_location.name), - service.getCharacteristics(body_sensor_location.uuid)])) - .then(characteristics_arrays => { - characteristics_arrays.forEach(characteristics => { - assert_equals(characteristics.length, 2); - assert_equals(characteristics[0].uuid, - BluetoothUUID.getCharacteristic('body_sensor_location')); - assert_equals(characteristics[1].uuid, - BluetoothUUID.getCharacteristic('body_sensor_location')); - }); + return getDiscoveredHealthThermometerDevice() + .then(({device, fake_peripheral}) => { + // Setup a device with two measurement intervals. + return fake_peripheral.setNextGATTConnectionResponse({ + code: HCI_SUCCESS}) + .then(() => device.gatt.connect()) + .then(() => fake_peripheral.addFakeService({ + uuid: 'health_thermometer'})) + .then(fake_health_thermometer => Promise.all([ + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'measurement_interval', + properties: ['read', 'write', 'indicate']}), + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'measurement_interval', + properties: ['read', 'write', 'indicate']}), + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'temperature_measurement', + properties: ['indicate']}) + ])) + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => device.gatt.getPrimaryService('health_thermometer')) + // Actual test starts. + .then((service) => Promise.all([ + service.getCharacteristics(measurement_interval.alias), + service.getCharacteristics(measurement_interval.name), + service.getCharacteristics(measurement_interval.uuid)])) + .then(characteristics_arrays => { + characteristics_arrays.forEach(characteristics => { + assert_equals(characteristics.length, 2); + assert_equals(characteristics[0].uuid, + measurement_interval.uuid); + assert_equals(characteristics[1].uuid, + measurement_interval.uuid); + }); + }); }); }, 'Find characteristics with UUID in service.'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found.html index 2d170d04..d5b884d 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-found.html
@@ -2,23 +2,48 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => service.getCharacteristics()) - .then(characteristics => { - assert_equals(characteristics.length, 3); - assert_equals(characteristics[0].uuid, - BluetoothUUID.getCharacteristic('heart_rate_measurement')); - assert_equals(characteristics[1].uuid, - BluetoothUUID.getCharacteristic('body_sensor_location')); - assert_equals(characteristics[2].uuid, - BluetoothUUID.getCharacteristic('body_sensor_location')); + return getDiscoveredHealthThermometerDevice() + .then(({device, fake_peripheral}) => { + // Setup a device with two measurement intervals. + return fake_peripheral.setNextGATTConnectionResponse({ + code: HCI_SUCCESS}) + .then(() => device.gatt.connect()) + .then(() => fake_peripheral.addFakeService({ + uuid: 'health_thermometer'})) + .then(fake_health_thermometer => Promise.all([ + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'measurement_interval', + properties: ['read', 'write', 'indicate']}), + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'measurement_interval', + properties: ['read', 'write', 'indicate']}), + fake_health_thermometer.addFakeCharacteristic({ + uuid: 'temperature_measurement', + properties: ['indicate']}) + ])) + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => device.gatt.getPrimaryService('health_thermometer')) + // Actual test starts. + .then(service => service.getCharacteristics()) + .then(characteristics => { + // Expect three characteristic instances. + assert_equals(characteristics.length, 3); + + let uuid_set = new Set(characteristics.map(c => c.uuid)); + // Two of the expected characteristics are 'measurement_interval', + // so only 2 unique UUID. + assert_equals(uuid_set.size, 2); + assert_true(uuid_set.has(BluetoothUUID.getCharacteristic( + 'measurement_interval'))); + assert_true(uuid_set.has(BluetoothUUID.getCharacteristic( + 'temperature_measurement'))); + }); }); }, 'Find all characteristics in a service.'); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-not-found.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-not-found.html index 97bcc3f1..e3baf08e 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-not-found.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/characteristics-not-found.html
@@ -2,15 +2,13 @@ <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> +<script src="../../../resources/bluetooth/web-bluetooth-test.js"></script> +<script src="../../../resources/mojo-helpers.js"></script> <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('MissingCharacteristicHeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => assert_promise_rejects_with_message( + return getEmptyHealthThermometerService() + .then(({service}) => assert_promise_rejects_with_message( service.getCharacteristics(), new DOMException('No Characteristics found in service.', 'NotFoundError')))
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-blocklisted-characteristic-with-uuid.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-blocklisted-characteristic-with-uuid.html index dec3ef40..f1118b6 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-blocklisted-characteristic-with-uuid.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-blocklisted-characteristic-with-uuid.html
@@ -8,11 +8,8 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('BlocklistTestAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['device_information']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('device_information')) + return getHIDDevice({filters: [{services: ['device_information']}]}) + .then(({device}) => device.gatt.getPrimaryService('device_information')) .then(service => { return assert_promise_rejects_with_message( service.getCharacteristics('serial_number_string'),
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-characteristic-not-found-with-uuid.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-characteristic-not-found-with-uuid.html index 5519358..450ffc35 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-characteristic-not-found-with-uuid.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-characteristic-not-found-with-uuid.html
@@ -8,16 +8,12 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('heart_rate')) - .then(service => assert_promise_rejects_with_message( + return getEmptyHealthThermometerService() + .then(({service}) => assert_promise_rejects_with_message( service.getCharacteristics('battery_level'), new DOMException( 'No Characteristics matching UUID ' + battery_level.uuid + ' found ' + - 'in Service with UUID ' + heart_rate.uuid + '.', + 'in Service with UUID ' + health_thermometer.uuid + '.', 'NotFoundError'))); }, 'Request for absent characteristics with UUID. Reject with NotFoundError.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object-with-uuid.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object-with-uuid.html index 6cee86b..bb5fb548 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object-with-uuid.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object-with-uuid.html
@@ -8,30 +8,23 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => Promise.all([ - service.getCharacteristics('body_sensor_location'), - service.getCharacteristics('body_sensor_location')])) - .then(characteristics_arrays => { + return getHealthThermometerService() + .then(({service}) => Promise.all([ + service.getCharacteristics('measurement_interval'), + service.getCharacteristics('measurement_interval')])) + .then(([characteristics_first_call, characteristics_second_call]) => { // Convert to arrays if necessary. - for (let i = 0; i < characteristics_arrays.length; i++) { - characteristics_arrays[i] = [].concat(characteristics_arrays[i]); - } + characteristics_first_call = [].concat(characteristics_first_call); + characteristics_second_call = [].concat(characteristics_second_call); - for (let i = 1; i < characteristics_arrays.length; i++) { - assert_equals(characteristics_arrays[0].length, - characteristics_arrays[i].length); - } + let first_call_set = new Set(characteristics_first_call); + assert_equals(characteristics_first_call.length, first_call_set.size); + let second_call_set = new Set(characteristics_second_call); + assert_equals(characteristics_second_call.length, second_call_set.size); - let base_set = new Set(characteristics_arrays[0]); - for (let characteristics of characteristics_arrays) { - characteristics.forEach( - characteristic => assert_true(base_set.has(characteristic))); - } + characteristics_first_call.forEach(characteristic => { + assert_true(second_call_set.has(characteristic)); + }); }); }, 'Calls to getCharacteristics should return the same object.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object.html index 8f97af7..202ac30f 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-get-same-object.html
@@ -8,30 +8,23 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryService('heart_rate')) - .then(service => Promise.all([ + return getHealthThermometerService() + .then(({service}) => Promise.all([ service.getCharacteristics(), service.getCharacteristics()])) - .then(characteristics_arrays => { + .then(([characteristics_first_call, characteristics_second_call]) => { // Convert to arrays if necessary. - for (let i = 0; i < characteristics_arrays.length; i++) { - characteristics_arrays[i] = [].concat(characteristics_arrays[i]); - } + characteristics_first_call = [].concat(characteristics_first_call); + characteristics_second_call = [].concat(characteristics_second_call); - for (let i = 1; i < characteristics_arrays.length; i++) { - assert_equals(characteristics_arrays[0].length, - characteristics_arrays[i].length); - } + let first_call_set = new Set(characteristics_first_call); + assert_equals(characteristics_first_call.length, first_call_set.size); + let second_call_set = new Set(characteristics_second_call); + assert_equals(characteristics_second_call.length, second_call_set.size); - let base_set = new Set(characteristics_arrays[0]); - for (let characteristics of characteristics_arrays) { - characteristics.forEach( - characteristic => assert_true(base_set.has(characteristic))); - } + characteristics_first_call.forEach(characteristic => { + assert_true(second_call_set.has(characteristic)); + }); }); }, 'Calls to getCharacteristics should return the same object.');
diff --git a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-invalid-characteristic-name.html b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-invalid-characteristic-name.html index 3b1c15a1..47d6e498 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-invalid-characteristic-name.html +++ b/third_party/WebKit/LayoutTests/bluetooth/service/getCharacteristics/gen-invalid-characteristic-name.html
@@ -8,13 +8,8 @@ <script> 'use strict'; promise_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithKeyDown({ - filters: [{services: ['heart_rate']}], - optionalServices: ['generic_access']})) - .then(device => device.gatt.connect()) - .then(gatt => gatt.getPrimaryService('generic_access')) - .then(service => { + return getHealthThermometerService() + .then(({service}) => { return assert_promise_rejects_with_message( service.getCharacteristics('wrong_name'), new DOMException(
diff --git a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/securitypolicyviolation/script-sample.html b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/securitypolicyviolation/script-sample.html index 2087f46..9b292b6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/securitypolicyviolation/script-sample.html +++ b/third_party/WebKit/LayoutTests/external/wpt/content-security-policy/securitypolicyviolation/script-sample.html
@@ -55,7 +55,7 @@ if (e.blockedURI != "eval") return; - assert_equals(e.sample, ""); + assert_equals(e.sample, "assert_unreached('eval')"); t.done(); })); try {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/innerText/getter-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/innerText/getter-expected.txt index 3859073f..2c99539 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/innerText/getter-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/innerText/getter-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 206 tests; 125 PASS, 81 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 206 tests; 126 PASS, 80 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Simplest possible test ("<div>abc") PASS Leading whitespace removed ("<div> abc") PASS Trailing whitespace removed ("<div>abc ") @@ -50,8 +50,8 @@ PASS display:none child of svg ("<div style='display:none' id='target'>abc") PASS child of display:none child of svg ("<div style='display:none'><div id='target'>abc") PASS display:contents container ("<div style='display:contents'>abc") -FAIL display:contents container ("<div><div style='display:contents'>abc") assert_equals: expected "abc" but got "" -FAIL display:contents rendered ("<div>123<span style='display:contents'>abc") assert_equals: expected "123abc" but got "123" +FAIL display:contents container ("<div><div style='display:contents'>abc") assert_equals: expected "abc" but got "abc\n" +PASS display:contents rendered ("<div>123<span style='display:contents'>abc") FAIL display:contents not processed via textContent ("<div style='display:contents'> ") assert_equals: expected "" but got " " PASS display:contents not processed via textContent ("<div><div style='display:contents'> ") PASS visibility:hidden container ("<div style='visibility:hidden'>abc")
diff --git a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-cors-xhr.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-cors-xhr.https-expected.txt deleted file mode 100644 index 49c7086b..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/service-workers/service-worker/fetch-cors-xhr.https-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Verify CORS XHR of fetch() in a Service Worker assert_equals: expected "finish" but got "failure:Result of url:https://web-platform.test:8444/service-workers/service-worker/resources/fetch-access-control.py?mode=cors&url=https%3A%2F%2Fwww1.web-platform.test%3A8444%2Fservice-workers%2Fservice-worker%2Fresources%2Ffetch-access-control.py%3FACAOrigin%3Dhttps%3A%2F%2Fweb-platform.test%3A8444 with_credentials: false must be SUCCESS but FAIL" -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/fast/inline/empty-inline-create-linebox.html b/third_party/WebKit/LayoutTests/fast/inline/empty-inline-create-linebox.html new file mode 100644 index 0000000..0a974e9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/inline/empty-inline-create-linebox.html
@@ -0,0 +1,114 @@ +<!DOCTYPE html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<style> +#container { + font: 10px/1; +} +</style> +<div id=log></div> +<div id=container> + <div> + <div>before</div> + <div><span></span></div> + <div>after</div> + </div> + <div> + <div>before</div> + <div><span style="margin-bottom:1px"></span></div> + <div>after</div> + </div> + <div> + <div>before</div> + <div><span style="border-bottom:1px solid"></span></div> + <div>after</div> + </div> + <div> + <div>before</div> + <div><span style="padding-bottom:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-left:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="border-left:1px solid"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="padding-left:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-right:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="border-right:1px solid"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="padding-right:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-left:-1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-right:-1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-left:1px;margin-right:-1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-left:-1px;border-left:1px solid"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-left:-1px;padding-left:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-right:-1px;border-right:1px solid"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-right:-1px;padding-right:1px"></span></div> + <div>after</div> + </div> + <div data-has-height=true> + <div>before</div> + <div><span style="margin-right:1px"></span><span style="margin-left:-1px"></span></div> + <div>after</div> + </div> +</div> +<script> +let tests = container.children; +for (let i = 0; i < tests.length; i++) { + let block = tests[i]; + let target = block.children[1]; + let name = (block.dataset.hasHeight ? "Has height" : "Zero height") + + " when " + target.innerHTML; + test(() => { + let has_height = target.offsetHeight > 0; + assert_equals(has_height, !!block.dataset.hasHeight); + }, name); +} +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/network/json-preview.html b/third_party/WebKit/LayoutTests/http/tests/inspector/network/json-preview.html index 44660ef7d..f47f6a0 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/network/json-preview.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/network/json-preview.html
@@ -17,9 +17,8 @@ async function testPreviewer(request) { var previewView = new Network.RequestPreviewView(request, null); - var previewerPromise = InspectorTest.addSnifferPromise(previewView, "_previewViewHandledForTest"); previewView.wasShown(); - var previewer = await previewerPromise; + var previewer = await previewView._previewViewPromise; InspectorTest.addResult("Its previewer is searchable: " + (previewer && previewer instanceof UI.SearchableView)); InspectorTest.addResult("Its previewer is the JSON previewer: " + (previewer && previewer._searchProvider && previewer._searchProvider instanceof Network.JSONView)); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/network/network-choose-preview-view.html b/third_party/WebKit/LayoutTests/http/tests/inspector/network/network-choose-preview-view.html index caeaf143..746b5f25 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/network/network-choose-preview-view.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/network/network-choose-preview-view.html
@@ -30,9 +30,8 @@ { var request = createNetworkRequest(contentType, content, statusCode); var previewView = new Network.RequestPreviewView(request, new Network.RequestResponseView(request)); - var previewerPromise = InspectorTest.addSnifferPromise(previewView, "_previewViewHandledForTest"); previewView.wasShown(); - InspectorTest.addResult("Its previewer type: " + getViewName(await previewerPromise)); + InspectorTest.addResult("Its previewer type: " + getViewName(await previewView._previewViewPromise)); } InspectorTest.addResult("Simple JSON");
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/network/preview-searchable.html b/third_party/WebKit/LayoutTests/http/tests/inspector/network/preview-searchable.html index f1ed3d8a..55a5735b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/network/preview-searchable.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/network/preview-searchable.html
@@ -60,9 +60,12 @@ callback(); } + function trySearches(request, searches, callback) { - InspectorTest.addSniffer(Network.RequestPreviewView.prototype, "_previewViewHandledForTest", previewViewHandled.bind(this, searches, callback)); + InspectorTest.addSniffer(Network.RequestPreviewView.prototype, "_showPreviewView", async function() { + previewViewHandled(searches, callback, await this._previewViewPromise); + }); var networkPanel = UI.panels.network; networkPanel._showRequest(request); var itemView = networkPanel._networkItemView;
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-xhr-iframe.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-xhr-iframe.html index 738a537..455a795 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-xhr-iframe.html +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/fetch-request-xhr-iframe.html
@@ -190,7 +190,7 @@ return xhr_send(host_info['HTTP_ORIGIN'], 'GET', '', false) .then(function(response){ assert_equals(response.mode, 'cors'); - assert_equals(response.credentials, 'include'); + assert_equals(response.credentials, 'same-origin'); return xhr_send(host_info['HTTP_ORIGIN'], 'GET', '', true); }) .then(function(response){
diff --git a/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/request-from-popup-expected.txt b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/request-from-popup-expected.txt index e15d53e..e55f8fb 100644 --- a/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/request-from-popup-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/xmlhttprequest/request-from-popup-expected.txt
@@ -1,4 +1,3 @@ -CONSOLE ERROR: XMLHttpRequest cannot load http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow-access-control-origin-header.cgi. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Test for bug 4343: XMLHttpRequest doesn't work in a JavaScript-created window. SUCCESS
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js b/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js index fbff635..4a353a54 100644 --- a/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js +++ b/third_party/WebKit/LayoutTests/resources/bluetooth/bluetooth-helpers.js
@@ -6,6 +6,11 @@ const HCI_SUCCESS = 0x0000; const HCI_CONNECTION_TIMEOUT = 0x0008; +// GATT Error codes. Used for GATT operations responses. +// BT 4.2 Vol 3 Part F 3.4.1.1 Error Response +const GATT_SUCCESS = 0x0000; +const GATT_INVALID_HANDLE = 0x0001; + // Bluetooth UUID constants: // Services: var blocklist_test_service_uuid = "611c954a-263b-4f4a-aab6-01ddb953f985"; @@ -354,16 +359,25 @@ } class TestCharacteristicProperties { + // |properties| is an array of strings for property bits to be set + // as true. constructor(properties) { - this.broadcast = properties.broadcast || false; - this.read = properties.read || false; - this.writeWithoutResponse = properties.writeWithoutResponse || false; - this.write = properties.write || false; - this.notify = properties.notify || false; - this.indicate = properties.indicate || false; - this.authenticatedSignedWrites = properties.authenticatedSignedWrites || false; - this.reliableWrite = properties.reliableWrite || false; - this.writableAuxiliaries = properties.writableAuxiliaries || false; + this.broadcast = false; + this.read = false; + this.writeWithoutResponse = false; + this.write = false; + this.notify = false; + this.indicate = false; + this.authenticatedSignedWrites = false; + this.reliableWrite = false; + this.writableAuxiliaries = false; + + properties.forEach(val => { + if (this.hasOwnProperty(val)) + this[val] = true; + else + throw `Invalid member '${val}'`; + }); } } @@ -460,15 +474,20 @@ // its corresponding FakePeripheral and FakeRemoteGATTServices. // The simulated device is called 'Health Thermometer' it has two known service // UUIDs: 'generic_access' and 'health_thermometer' which correspond to two -// services with the same UUIDs. The device has been connected to and its -// services are ready to be discovered. -// TODO(crbug.com/719816): Add characteristics and descriptors. +// services with the same UUIDs. The 'health thermometer' service contains three +// characteristics: +// - 'temperature_measurement' (indicate), +// - 'temperature_type' (read), +// - 'measurement_interval' (read, write, indicate) +// The device has been connected to and its attributes are ready to be +// discovered. +// TODO(crbug.com/719816): Add descriptors. function getHealthThermometerDevice(options) { let device; let fake_peripheral; let fake_generic_access; let fake_health_thermometer; - + let fake_measurement_interval; return getConnectedHealthThermometerDevice(options) .then(result => { ({ @@ -476,6 +495,7 @@ fake_peripheral, fake_generic_access, fake_health_thermometer, + fake_measurement_interval, } = result); }) .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ @@ -484,7 +504,8 @@ device: device, fake_peripheral: fake_peripheral, fake_generic_access: fake_generic_access, - fake_health_thermometer1: fake_health_thermometer, + fake_health_thermometer: fake_health_thermometer, + fake_measurement_interval: fake_measurement_interval, })); } @@ -519,6 +540,34 @@ })); } +// Returns an object containing a Health Thermometer BluetoothRemoteGattService +// and its corresponding FakeRemoteGATTService. +function getHealthThermometerService() { + return getHealthThermometerDevice() + .then(result => { + return result.device.gatt.getPrimaryService('health_thermometer') + .then(service => ({ + service: service, + fake_service: result.fake_health_thermometer + })); + }); +} + +// Returns an object containing a Measurement Interval +// BluetoothRemoteGATTCharacteristic and its corresponding +// FakeRemoteGATTCharacteristic. +function getMeasurementIntervalCharacteristic() { + return getHealthThermometerDevice() + .then(result => { + return result.device.gatt.getPrimaryService('health_thermometer') + .then(service => service.getCharacteristic('measurement_interval')) + .then(characteristic => ({ + characteristic: characteristic, + fake_characteristic: result.fake_measurement_interval + })); + }); +} + // Similar to getHealthThermometerDevice except the GATT discovery // response has not been set yet so more attributes can still be added. function getConnectedHealthThermometerDevice(options) { @@ -526,6 +575,9 @@ let fake_peripheral; let fake_generic_access; let fake_health_thermometer; + let fake_measurement_interval; + let fake_temperature_measurement; + let fake_temperature_type; return getDiscoveredHealthThermometerDevice(options) .then(result => { ({device, fake_peripheral} = result); @@ -538,11 +590,23 @@ .then(() => fake_peripheral.addFakeService({ uuid: 'health_thermometer'})) .then(s => fake_health_thermometer = s) + .then(() => fake_health_thermometer.addFakeCharacteristic({ + uuid: 'measurement_interval', properties: ['read', 'write', 'indicate']})) + .then(c => fake_measurement_interval = c) + .then(() => fake_health_thermometer.addFakeCharacteristic({ + uuid: 'temperature_measurement', properties: ['indicate']})) + .then(c => fake_temperature_measurement = c) + .then(() => fake_health_thermometer.addFakeCharacteristic({ + uuid: 'temperature_type', properties: ['read']})) + .then(c => fake_temperature_type = c) .then(() => ({ device: device, fake_peripheral: fake_peripheral, fake_generic_access: fake_generic_access, fake_health_thermometer: fake_health_thermometer, + fake_measurement_interval: fake_measurement_interval, + fake_temperature_measurement: fake_temperature_measurement, + fake_temperature_type: fake_temperature_type, })); } @@ -604,32 +668,61 @@ }); } +// Similar to getHealthThermometerService() except the service has no +// characteristics or included services. +function getEmptyHealthThermometerService(options) { + let device; + let fake_peripheral; + let fake_health_thermometer; + return getDiscoveredHealthThermometerDevice(options) + .then(result => ({device, fake_peripheral} = result)) + .then(() => fake_peripheral.setNextGATTConnectionResponse({ + code: HCI_SUCCESS})) + .then(() => device.gatt.connect()) + .then(() => fake_peripheral.addFakeService({uuid: 'health_thermometer'})) + .then(s => fake_health_thermometer = s) + .then(() => fake_peripheral.setNextGATTDiscoveryResponse({ + code: HCI_SUCCESS})) + .then(() => device.gatt.getPrimaryService('health_thermometer')) + .then(service => ({ + service: service, + fake_health_thermometer: fake_health_thermometer, + })); +} + // Returns a BluetoothDevice discovered using |options| and its // corresponding FakePeripheral. // The simulated device is called 'HID Device' it has three known service -// UUIDs: 'generic_access', 'battery_service', 'human_interface_device'. The -// device has been connected to and its services are ready to be discovered. -// TODO(crbug.com/719816): Add characteristics and descriptors. +// UUIDs: 'generic_access', 'device_information', 'human_interface_device'. +// The primary service with 'device_information' UUID has a characteristics +// with UUID 'serial_number_string'. The device has been connected to and its +// attributes are ready to be discovered. +// TODO(crbug.com/719816): Add descriptors. function getHIDDevice(options) { return setUpPreconnectedDevice({ address: '10:10:10:10:10:10', name: 'HID Device', knownServiceUUIDs: [ 'generic_access', - 'battery_service', + 'device_information', 'human_interface_device' ], }) .then(fake_peripheral => { return requestDeviceWithKeyDown(options) .then(device => { - return fake_peripheral.setNextGATTConnectionResponse({ + return fake_peripheral + .setNextGATTConnectionResponse({ code: HCI_SUCCESS}) .then(() => device.gatt.connect()) .then(() => fake_peripheral.addFakeService({ uuid: 'generic_access'})) .then(() => fake_peripheral.addFakeService({ - uuid: 'battery_service'})) + uuid: 'device_information'})) + // Blocklisted Characteristic: + // https://github.com/WebBluetoothCG/registries/blob/master/gatt_blocklist.txt + .then(dev_info => dev_info.addFakeCharacteristic({ + uuid: 'serial_number_string', properties: ['read']})) .then(() => fake_peripheral.addFakeService({ uuid: 'human_interface_device'})) .then(() => fake_peripheral.setNextGATTDiscoveryResponse({
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js b/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js index 648ea2b..915b512 100644 --- a/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js +++ b/third_party/WebKit/LayoutTests/resources/bluetooth/web-bluetooth-test.js
@@ -21,6 +21,7 @@ FakeBluetoothPtr: mojo_.FakeBluetoothPtr, FakeCentral: mojo_.FakeCentral, FakeCentralPtr: mojo_.FakeCentralPtr, + CharacteristicProperties: mojo_.CharacteristicProperties, }] = mojo_.modules; return mojo_; @@ -39,6 +40,37 @@ } } + // Mapping of the property names of + // BluetoothCharacteristicProperties defined in + // https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties + // to property names of the CharacteristicProperties mojo struct. + const CHARACTERISTIC_PROPERTIES_WEB_TO_MOJO = { + broadcast: 'broadcast', + read: 'read', + write_without_response: 'write_without_response', + write: 'write', + notify: 'notify', + indicate: 'indicate', + authenticatedSignedWrites: 'authenticated_signed_writes', + extended_properties: 'extended_properties', + }; + + function ArrayToMojoCharacteristicProperties(arr) { + let struct = new mojo_.CharacteristicProperties(); + + arr.forEach(val => { + let mojo_property = + CHARACTERISTIC_PROPERTIES_WEB_TO_MOJO[val]; + + if (struct.hasOwnProperty(mojo_property)) + struct[mojo_property] = true; + else + throw `Invalid member '${val}' for CharacteristicProperties`; + }); + + return struct; + } + class FakeBluetooth { constructor() { this.fake_bluetooth_ptr_ = undefined; @@ -150,7 +182,6 @@ class FakePeripheral { constructor(address, fake_central_ptr) { this.address = address; - this.services_ = []; this.fake_central_ptr_ = fake_central_ptr; } @@ -177,12 +208,8 @@ if (service_id === null) throw 'addFakeService failed'; - let fake_service = new FakeRemoteGATTService( + return new FakeRemoteGATTService( service_id, this.address, this.fake_central_ptr_); - - this.services_.push(fake_service); - - return fake_service; } // Sets the next GATT Discovery request response for peripheral with @@ -216,6 +243,53 @@ this.peripheral_address_ = peripheral_address; this.fake_central_ptr_ = fake_central_ptr; } + + // Adds a fake GATT Characteristic with |uuid| and |properties| + // to this fake service. The characteristic will be found when discovering + // the peripheral's GATT Attributes. Returns a FakeRemoteGATTCharacteristic + // corresponding to the added characteristic. + async addFakeCharacteristic({uuid, properties}) { + let {characteristic_id} = await this.fake_central_ptr_.addFakeCharacteristic( + {uuid: BluetoothUUID.getCharacteristic(uuid)}, + ArrayToMojoCharacteristicProperties(properties), + this.service_id_, + this.peripheral_address_ + ); + + if (characteristic_id === null) throw 'addFakeCharacteristic failed'; + + return new FakeRemoteGATTCharacteristic( + characteristic_id, this.service_id_, + this.peripheral_address_, this.fake_central_ptr_); + } + } + + class FakeRemoteGATTCharacteristic { + constructor(characteristic_id, service_id, peripheral_address, fake_central_ptr) { + this.ids_ = [characteristic_id, service_id, peripheral_address]; + this.fake_central_ptr_ = fake_central_ptr; + } + + // Sets the next read response for characteristic to |code| and |value|. + // |code| could be a GATT Error Response from + // BT 4.2 Vol 3 Part F 3.4.1.1 Error Response or a number outside that range + // returned by specific platforms e.g. Android returns 0x101 to signal a GATT + // failure. + // https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#GATT_FAILURE + async setNextReadResponse(gatt_code, value=null) { + if (gatt_code === 0 && value === null) { + throw '|value| can\'t be null if read should success.'; + } + if (gatt_code !== 0 && value !== null) { + throw '|value| must be null if read should fail.'; + } + + let {success} = + await this.fake_central_ptr_.setNextReadCharacteristicResponse( + gatt_code, value, ...this.ids_); + + if (!success) throw 'setNextReadCharacteristicResponse failed'; + } } navigator.bluetooth.test = new FakeBluetooth();
diff --git a/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp b/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp index 3b33bb8..d8c2cd1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/LocalWindowProxy.cpp
@@ -148,7 +148,8 @@ ContentSecurityPolicy* csp = GetFrame()->GetDocument()->GetContentSecurityPolicy(); context->AllowCodeGenerationFromStrings(csp->AllowEval( - 0, SecurityViolationReportingPolicy::kSuppressReporting)); + 0, SecurityViolationReportingPolicy::kSuppressReporting, + ContentSecurityPolicy::kWillNotThrowException, g_empty_string)); context->SetErrorMessageForCodeGenerationFromStrings( V8String(GetIsolate(), csp->EvalDisabledErrorMessage())); } else {
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.cpp index e0f6d7b..6a3d8159 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.cpp
@@ -427,8 +427,9 @@ } std::unique_ptr<TextResourceDecoder> decoder( - TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - WTF::TextEncoding(resource->Encoding()))); + TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + WTF::TextEncoding(resource->Encoding())))); decoder->CheckForBOM(maybe_bom, kMaximumLengthOfBOM); // The encoding may change when we see the BOM. Check for BOM now
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp index 49e0f58..e73d30701 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp
@@ -295,13 +295,21 @@ } static bool CodeGenerationCheckCallbackInMainThread( - v8::Local<v8::Context> context) { + v8::Local<v8::Context> context, + v8::Local<v8::String> source) { if (ExecutionContext* execution_context = ToExecutionContext(context)) { if (ContentSecurityPolicy* policy = - ToDocument(execution_context)->GetContentSecurityPolicy()) - return policy->AllowEval(ScriptState::From(context), - SecurityViolationReportingPolicy::kReport, - ContentSecurityPolicy::kWillThrowException); + ToDocument(execution_context)->GetContentSecurityPolicy()) { + v8::String::Value source_str(source); + UChar snippet[ContentSecurityPolicy::kMaxSampleLength + 1]; + size_t len = std::min((sizeof(snippet) / sizeof(UChar)) - 1, + static_cast<size_t>(source_str.length())); + memcpy(snippet, *source_str, len * sizeof(UChar)); + snippet[len] = 0; + return policy->AllowEval( + ScriptState::From(context), SecurityViolationReportingPolicy::kReport, + ContentSecurityPolicy::kWillThrowException, snippet); + } } return false; }
diff --git a/third_party/WebKit/Source/bindings/scripts/idl_definitions.py b/third_party/WebKit/Source/bindings/scripts/idl_definitions.py index c649278..1b2209a 100644 --- a/third_party/WebKit/Source/bindings/scripts/idl_definitions.py +++ b/third_party/WebKit/Source/bindings/scripts/idl_definitions.py
@@ -320,11 +320,19 @@ has_indexed_property_getter = False has_integer_typed_length = False + def is_blacklisted_attribute_type(idl_type): + return idl_type.is_callback_function or \ + idl_type.is_dictionary or \ + idl_type.is_record_type or \ + idl_type.is_sequence_type + children = node.GetChildren() for child in children: child_class = child.GetClass() if child_class == 'Attribute': attr = IdlAttribute(child) + if is_blacklisted_attribute_type(attr.idl_type): + raise ValueError('Type "%s" cannot be used as an attribute.' % attr.idl_type) if attr.idl_type.is_integer_type and attr.name == 'length': has_integer_typed_length = True self.attributes.append(attr)
diff --git a/third_party/WebKit/Source/bindings/tests/idls/core/TestCallbackFunctions.idl b/third_party/WebKit/Source/bindings/tests/idls/core/TestCallbackFunctions.idl index 5bd02fd1..10edce1 100644 --- a/third_party/WebKit/Source/bindings/tests/idls/core/TestCallbackFunctions.idl +++ b/third_party/WebKit/Source/bindings/tests/idls/core/TestCallbackFunctions.idl
@@ -15,9 +15,6 @@ callback VoidCallbackFunctionTypedef = void (String arg); interface TestCallbackFunctions { - // Attributes - attribute VoidCallbackFunction voidCallbackFunctionAttribute; - attribute AnyCallbackFunctionOptionalAnyArg anyCallbackFunctionOptionalAnyArgAttribute; // Extended attributes [CustomElementCallbacks] readonly attribute long customElementsCallbacksReadonlyAttribute;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp index 1eef9d9e..3a06db2 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp
@@ -69,52 +69,6 @@ namespace TestCallbackFunctionsV8Internal { -static void voidCallbackFunctionAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Local<v8::Object> holder = info.Holder(); - - TestCallbackFunctions* impl = V8TestCallbackFunctions::toImpl(holder); - - V8SetReturnValueFast(info, impl->voidCallbackFunctionAttribute(), impl); -} - -static void voidCallbackFunctionAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Isolate* isolate = info.GetIsolate(); - ALLOW_UNUSED_LOCAL(isolate); - - v8::Local<v8::Object> holder = info.Holder(); - ALLOW_UNUSED_LOCAL(holder); - - TestCallbackFunctions* impl = V8TestCallbackFunctions::toImpl(holder); - - // Prepare the value to be set. - VoidCallbackFunction* cppValue = VoidCallbackFunction::Create(ScriptState::Current(info.GetIsolate()), v8Value); - - impl->setVoidCallbackFunctionAttribute(cppValue); -} - -static void anyCallbackFunctionOptionalAnyArgAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Local<v8::Object> holder = info.Holder(); - - TestCallbackFunctions* impl = V8TestCallbackFunctions::toImpl(holder); - - V8SetReturnValueFast(info, impl->anyCallbackFunctionOptionalAnyArgAttribute(), impl); -} - -static void anyCallbackFunctionOptionalAnyArgAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Isolate* isolate = info.GetIsolate(); - ALLOW_UNUSED_LOCAL(isolate); - - v8::Local<v8::Object> holder = info.Holder(); - ALLOW_UNUSED_LOCAL(holder); - - TestCallbackFunctions* impl = V8TestCallbackFunctions::toImpl(holder); - - // Prepare the value to be set. - AnyCallbackFunctionOptionalAnyArg* cppValue = AnyCallbackFunctionOptionalAnyArg::Create(ScriptState::Current(info.GetIsolate()), v8Value); - - impl->setAnyCallbackFunctionOptionalAnyArgAttribute(cppValue); -} - static void customElementsCallbacksReadonlyAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); @@ -245,26 +199,6 @@ } // namespace TestCallbackFunctionsV8Internal -void V8TestCallbackFunctions::voidCallbackFunctionAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { - TestCallbackFunctionsV8Internal::voidCallbackFunctionAttributeAttributeGetter(info); -} - -void V8TestCallbackFunctions::voidCallbackFunctionAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Local<v8::Value> v8Value = info[0]; - - TestCallbackFunctionsV8Internal::voidCallbackFunctionAttributeAttributeSetter(v8Value, info); -} - -void V8TestCallbackFunctions::anyCallbackFunctionOptionalAnyArgAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { - TestCallbackFunctionsV8Internal::anyCallbackFunctionOptionalAnyArgAttributeAttributeGetter(info); -} - -void V8TestCallbackFunctions::anyCallbackFunctionOptionalAnyArgAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { - v8::Local<v8::Value> v8Value = info[0]; - - TestCallbackFunctionsV8Internal::anyCallbackFunctionOptionalAnyArgAttributeAttributeSetter(v8Value, info); -} - void V8TestCallbackFunctions::customElementsCallbacksReadonlyAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TestCallbackFunctionsV8Internal::customElementsCallbacksReadonlyAttributeAttributeGetter(info); } @@ -302,10 +236,6 @@ } static const V8DOMConfiguration::AccessorConfiguration V8TestCallbackFunctionsAccessors[] = { - { "voidCallbackFunctionAttribute", V8TestCallbackFunctions::voidCallbackFunctionAttributeAttributeGetterCallback, V8TestCallbackFunctions::voidCallbackFunctionAttributeAttributeSetterCallback, nullptr, nullptr, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kAllWorlds }, - - { "anyCallbackFunctionOptionalAnyArgAttribute", V8TestCallbackFunctions::anyCallbackFunctionOptionalAnyArgAttributeAttributeGetterCallback, V8TestCallbackFunctions::anyCallbackFunctionOptionalAnyArgAttributeAttributeSetterCallback, nullptr, nullptr, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kAllWorlds }, - { "customElementsCallbacksReadonlyAttribute", V8TestCallbackFunctions::customElementsCallbacksReadonlyAttributeAttributeGetterCallback, nullptr, nullptr, nullptr, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kAllWorlds }, };
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.h b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.h index 02bf3462..dcbaead 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.h
@@ -46,10 +46,6 @@ // Callback functions - CORE_EXPORT static void voidCallbackFunctionAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); - CORE_EXPORT static void voidCallbackFunctionAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); - CORE_EXPORT static void anyCallbackFunctionOptionalAnyArgAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); - CORE_EXPORT static void anyCallbackFunctionOptionalAnyArgAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void customElementsCallbacksReadonlyAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void returnCallbackFunctionMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index 34f7b232..407b4e0 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -458,7 +458,12 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIAlignItems.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIAlignOrJustifyContent.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIAlignOrJustifySelf.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIAnimationDirection.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIAnimationFillMode.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIAnimationIterationCount.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIAnimationName.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIAnimationPlayState.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIBackgroundColor.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIBaselineShift.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIBorderImageOutset.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIBorderImageRepeat.h", @@ -466,6 +471,7 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIBorderImageWidth.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIBorderRadius.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIBorderWidth.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIBoxShadow.h", "$blink_core_output_dir/css/properties/CSSPropertyAPICaretColor.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIClip.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIClipPath.h", @@ -492,6 +498,7 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIFontVariantLigatures.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIFontVariantNumeric.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIFontVariationSettings.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIFontWeight.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIFragmentation.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIGridAutoFlow.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIGridAutoLine.h", @@ -506,6 +513,7 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPILineHeightStep.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIMargin.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIMarker.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIObjectPosition.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIOffsetAnchor.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIOffsetDistance.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIOffsetPath.h", @@ -521,6 +529,7 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIPaintOrder.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIPaintStroke.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIPerspective.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIPerspectiveOrigin.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIQuotes.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIRadius.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIRotate.h", @@ -541,11 +550,13 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPITextDecorationLine.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITextDecorationSkip.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITextIndent.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPITextShadow.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITextSizeAdjust.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITextUnderlinePosition.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITouchAction.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITransform.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITransformOrigin.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPITransitionProperty.h", "$blink_core_output_dir/css/properties/CSSPropertyAPITranslate.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIVerticalAlign.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitBorderImage.h", @@ -553,6 +564,7 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitBorderWidth.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitBoxFlex.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitBoxFlexGroup.h", + "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitBoxReflect.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitFontSizeDelta.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitHighlight.h", "$blink_core_output_dir/css/properties/CSSPropertyAPIWebkitLineClamp.h",
diff --git a/third_party/WebKit/Source/core/DEPS b/third_party/WebKit/Source/core/DEPS index 9c96f57a..76e014f4 100644 --- a/third_party/WebKit/Source/core/DEPS +++ b/third_party/WebKit/Source/core/DEPS
@@ -15,4 +15,11 @@ "+third_party/skia/include", "+ui/gfx/geometry", "-web", + # We do not want any new dependencies into core/exported until we resolve + # controller layer. + "!core/exported", + # We do not want any new dependencies on Web(Local|Remote)FrameBase.h until + # we resolve the control layer. + "!core/frame/WebLocalFrameBase.h", + "!core/frame/WebRemoteFrameBase.h" ]
diff --git a/third_party/WebKit/Source/core/css/BUILD.gn b/third_party/WebKit/Source/core/css/BUILD.gn index 2f94d0a..72fc55b2 100644 --- a/third_party/WebKit/Source/core/css/BUILD.gn +++ b/third_party/WebKit/Source/core/css/BUILD.gn
@@ -376,7 +376,12 @@ "properties/CSSPropertyAPIAlignItems.cpp", "properties/CSSPropertyAPIAlignOrJustifyContent.cpp", "properties/CSSPropertyAPIAlignOrJustifySelf.cpp", + "properties/CSSPropertyAPIAnimationDirection.cpp", + "properties/CSSPropertyAPIAnimationFillMode.cpp", + "properties/CSSPropertyAPIAnimationIterationCount.cpp", "properties/CSSPropertyAPIAnimationName.cpp", + "properties/CSSPropertyAPIAnimationPlayState.cpp", + "properties/CSSPropertyAPIBackgroundColor.cpp", "properties/CSSPropertyAPIBaselineShift.cpp", "properties/CSSPropertyAPIBorderImageOutset.cpp", "properties/CSSPropertyAPIBorderImageRepeat.cpp", @@ -384,6 +389,7 @@ "properties/CSSPropertyAPIBorderImageWidth.cpp", "properties/CSSPropertyAPIBorderRadius.cpp", "properties/CSSPropertyAPIBorderWidth.cpp", + "properties/CSSPropertyAPIBoxShadow.cpp", "properties/CSSPropertyAPICaretColor.cpp", "properties/CSSPropertyAPIClip.cpp", "properties/CSSPropertyAPIClipPath.cpp", @@ -410,6 +416,7 @@ "properties/CSSPropertyAPIFontVariantLigatures.cpp", "properties/CSSPropertyAPIFontVariantNumeric.cpp", "properties/CSSPropertyAPIFontVariationSettings.cpp", + "properties/CSSPropertyAPIFontWeight.cpp", "properties/CSSPropertyAPIFragmentation.cpp", "properties/CSSPropertyAPIGridAutoFlow.cpp", "properties/CSSPropertyAPIGridAutoLine.cpp", @@ -424,6 +431,7 @@ "properties/CSSPropertyAPILineHeightStep.cpp", "properties/CSSPropertyAPIMargin.cpp", "properties/CSSPropertyAPIMarker.cpp", + "properties/CSSPropertyAPIObjectPosition.cpp", "properties/CSSPropertyAPIOffsetAnchor.cpp", "properties/CSSPropertyAPIOffsetDistance.cpp", "properties/CSSPropertyAPIOffsetPath.cpp", @@ -439,6 +447,7 @@ "properties/CSSPropertyAPIPaintOrder.cpp", "properties/CSSPropertyAPIPaintStroke.cpp", "properties/CSSPropertyAPIPerspective.cpp", + "properties/CSSPropertyAPIPerspectiveOrigin.cpp", "properties/CSSPropertyAPIQuotes.cpp", "properties/CSSPropertyAPIRadius.cpp", "properties/CSSPropertyAPIRotate.cpp", @@ -459,11 +468,13 @@ "properties/CSSPropertyAPITextDecorationLine.cpp", "properties/CSSPropertyAPITextDecorationSkip.cpp", "properties/CSSPropertyAPITextIndent.cpp", + "properties/CSSPropertyAPITextShadow.cpp", "properties/CSSPropertyAPITextSizeAdjust.cpp", "properties/CSSPropertyAPITextUnderlinePosition.cpp", "properties/CSSPropertyAPITouchAction.cpp", "properties/CSSPropertyAPITransform.cpp", "properties/CSSPropertyAPITransformOrigin.cpp", + "properties/CSSPropertyAPITransitionProperty.cpp", "properties/CSSPropertyAPITranslate.cpp", "properties/CSSPropertyAPIVerticalAlign.cpp", "properties/CSSPropertyAPIWebkitBorderImage.cpp", @@ -471,6 +482,7 @@ "properties/CSSPropertyAPIWebkitBorderWidth.cpp", "properties/CSSPropertyAPIWebkitBoxFlex.cpp", "properties/CSSPropertyAPIWebkitBoxFlexGroup.cpp", + "properties/CSSPropertyAPIWebkitBoxReflect.cpp", "properties/CSSPropertyAPIWebkitFontSizeDelta.cpp", "properties/CSSPropertyAPIWebkitHighlight.cpp", "properties/CSSPropertyAPIWebkitLineClamp.cpp",
diff --git a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp index 9e4857a..74d1469 100644 --- a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -40,6 +40,7 @@ #include "platform/loader/fetch/ResourceLoaderOptions.h" #include "platform/weborigin/SecurityPolicy.h" #include "platform/wtf/text/StringBuilder.h" +#include "public/platform/WebURLRequest.h" namespace blink { @@ -82,8 +83,7 @@ ResourceRequest resource_request(absolute_resource_); resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_.referrer_policy, resource_request.Url(), referrer_.referrer)); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::css; FetchParameters params(resource_request, options); if (RuntimeEnabledFeatures::WebFontsCacheAwareTimeoutAdaptationEnabled())
diff --git a/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp b/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp index 55b9873..565dc73 100644 --- a/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
@@ -113,8 +113,7 @@ ImageWithScale image = BestImageForScaleFactor(device_scale_factor); ResourceRequest resource_request(document.CompleteURL(image.image_url)); resource_request.SetHTTPReferrer(image.referrer); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::css; FetchParameters params(resource_request, options); @@ -122,6 +121,7 @@ params.SetCrossOriginAccessControl(document.GetSecurityOrigin(), cross_origin); } + if (document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params);
diff --git a/third_party/WebKit/Source/core/css/CSSImageValue.cpp b/third_party/WebKit/Source/core/css/CSSImageValue.cpp index 1012766..367a9f0 100644 --- a/third_party/WebKit/Source/core/css/CSSImageValue.cpp +++ b/third_party/WebKit/Source/core/css/CSSImageValue.cpp
@@ -61,8 +61,7 @@ ResourceRequest resource_request(absolute_url_); resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_.referrer_policy, resource_request.Url(), referrer_.referrer)); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = initiator_name_.IsEmpty() ? FetchInitiatorTypeNames::css : initiator_name_; @@ -72,6 +71,7 @@ params.SetCrossOriginAccessControl(document.GetSecurityOrigin(), cross_origin); } + if (document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params);
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index e143700..08bb9ae6 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -307,6 +307,8 @@ }, { name: "animation-direction", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, keywords: ["normal", "reverse", "alternate", "alternate-reverse"], priority: "Animation", @@ -319,11 +321,15 @@ }, { name: "animation-fill-mode", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, priority: "Animation", }, { name: "animation-iteration-count", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, keywords: ["infinite"], priority: "Animation", @@ -338,6 +344,8 @@ }, { name: "animation-play-state", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, priority: "Animation", }, @@ -358,6 +366,8 @@ }, { name: "transition-property", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, priority: "Animation", }, @@ -482,6 +492,8 @@ }, { name: "font-weight", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertFontWeight", is_descriptor: true, font: true, @@ -653,6 +665,8 @@ }, { name: "background-color", + api_class: true, + api_methods: ["parseSingleValue"], custom_all: true, interpolable: true, }, @@ -935,6 +949,8 @@ }, { name: "box-shadow", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertShadowList", interpolable: true, field_template: "storage_only", @@ -1725,6 +1741,8 @@ }, { name: "object-position", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertPosition", interpolable: true, field_template: "external", @@ -1955,6 +1973,8 @@ }, { name: "perspective-origin", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertPosition", interpolable: true, field_template: "external", @@ -2555,6 +2575,8 @@ }, { name: "text-shadow", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertShadowList", inherited: true, interpolable: true, @@ -2883,6 +2905,8 @@ }, { name: "-webkit-box-reflect", + api_class: true, + api_methods: ["parseSingleValue"], converter: "ConvertBoxReflect", field_template: "storage_only", type_name: "StyleReflection",
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleExtraFields.json5 b/third_party/WebKit/Source/core/css/ComputedStyleExtraFields.json5 index 4120b96..e078f4b 100644 --- a/third_party/WebKit/Source/core/css/ComputedStyleExtraFields.json5 +++ b/third_party/WebKit/Source/core/css/ComputedStyleExtraFields.json5
@@ -475,10 +475,9 @@ { name: "SelfOrAncestorHasDirAutoAttribute", inherited: true, - field_template: "storage_only", + field_template: "primitive", type_name: "bool", default_value: "false", - field_size: 1, field_group: "rare-inherited", }, // Though position: sticky is not itself an inherited property, being a @@ -707,34 +706,30 @@ }, { name: "HasCurrentOpacityAnimation", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasCurrentTransformAnimation", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasCurrentFilterAnimation", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasCurrentBackdropFilterAnimation", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { @@ -769,12 +764,16 @@ custom_compare: true, default_value: "false", }, + // A stacking context is painted atomically and defines a stacking order, + // whereas a containing stacking context defines in which order the stacking + // contexts below are painted. + // See CSS 2.1, Appendix E (https://www.w3.org/TR/CSS21/zindex.html) for more + // details. { name: "IsStackingContext", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, // Plugins require accelerated compositing for reasons external to blink. @@ -783,43 +782,38 @@ // when the plugin becomes composited. { name: "RequiresAcceleratedCompositingForExternalReasons", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasInlineTransform", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasCompositorProxy", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, // Style adjustment for appearance is disabled when certain properties are set. { name: "HasAuthorBackground", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, { name: "HasAuthorBorder", - field_template: "storage_only", + field_template: "primitive", type_name: "bool", field_group: "rare-non-inherited", - field_size: 1, default_value: "false", }, {
diff --git a/third_party/WebKit/Source/core/css/StyleRuleImport.cpp b/third_party/WebKit/Source/core/css/StyleRuleImport.cpp index 49a94f2e..d6ca7a6 100644 --- a/third_party/WebKit/Source/core/css/StyleRuleImport.cpp +++ b/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
@@ -131,8 +131,7 @@ root_sheet = sheet; } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::css; FetchParameters params(ResourceRequest(abs_url), options); params.SetCharset(parent_style_sheet_->Charset());
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserToken.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserToken.cpp index c61f198..2129e33 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserToken.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserToken.cpp
@@ -13,9 +13,6 @@ namespace blink { -CSSParserToken::CSSParserToken(CSSParserTokenType type, BlockType block_type) - : type_(type), block_type_(block_type) {} - // Just a helper used for Delimiter tokens. CSSParserToken::CSSParserToken(CSSParserTokenType type, UChar c) : type_(type), block_type_(kNotBlock), delimiter_(c) { @@ -23,14 +20,6 @@ } CSSParserToken::CSSParserToken(CSSParserTokenType type, - StringView value, - BlockType block_type) - : type_(type), block_type_(block_type) { - InitValueFromStringView(value); - id_ = -1; -} - -CSSParserToken::CSSParserToken(CSSParserTokenType type, double numeric_value, NumericValueType numeric_value_type, NumericSign sign)
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserToken.h b/third_party/WebKit/Source/core/css/parser/CSSParserToken.h index 7b5483d..059d8d13 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserToken.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserToken.h
@@ -74,8 +74,15 @@ kBlockEnd, }; - CSSParserToken(CSSParserTokenType, BlockType = kNotBlock); - CSSParserToken(CSSParserTokenType, StringView, BlockType = kNotBlock); + CSSParserToken(CSSParserTokenType type, BlockType block_type = kNotBlock) + : type_(type), block_type_(block_type) {} + CSSParserToken(CSSParserTokenType type, + StringView value, + BlockType block_type = kNotBlock) + : type_(type), block_type_(block_type) { + InitValueFromStringView(value); + id_ = -1; + } CSSParserToken(CSSParserTokenType, UChar); // for DelimiterToken CSSParserToken(CSSParserTokenType,
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index c21a17a..6494591a 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -713,34 +713,6 @@ return nullptr; } -static CSSValue* ConsumeReflect(CSSParserTokenRange& range, - const CSSParserContext* context) { - CSSIdentifierValue* direction = - ConsumeIdent<CSSValueAbove, CSSValueBelow, CSSValueLeft, CSSValueRight>( - range); - if (!direction) - return nullptr; - - CSSPrimitiveValue* offset = nullptr; - if (range.AtEnd()) { - offset = CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kPixels); - } else { - offset = ConsumeLengthOrPercent(range, context->Mode(), kValueRangeAll, - UnitlessQuirk::kForbid); - if (!offset) - return nullptr; - } - - CSSValue* mask = nullptr; - if (!range.AtEnd()) { - mask = - CSSPropertyBorderImageUtils::ConsumeWebkitBorderImage(range, context); - if (!mask) - return nullptr; - } - return CSSReflectValue::Create(direction, offset, mask); -} - static CSSValue* ConsumeBackgroundBlendMode(CSSParserTokenRange& range) { CSSValueID id = range.Peek().Id(); if (id == CSSValueNormal || id == CSSValueOverlay || @@ -1401,8 +1373,6 @@ } switch (property) { - case CSSPropertyFontWeight: - return CSSPropertyFontUtils::ConsumeFontWeight(range_); case CSSPropertyMaxWidth: case CSSPropertyMaxHeight: return CSSPropertyLengthUtils::ConsumeMaxWidthOrHeight( @@ -1422,48 +1392,16 @@ case CSSPropertyWebkitLogicalWidth: case CSSPropertyWebkitLogicalHeight: return CSSPropertyLengthUtils::ConsumeWidthOrHeight(range_, *context_); - case CSSPropertyObjectPosition: - return ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - WebFeature::kThreeValuedPositionObjectPosition); - case CSSPropertyPerspectiveOrigin: - return ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - WebFeature::kThreeValuedPositionPerspectiveOrigin); case CSSPropertyWebkitHyphenateCharacter: case CSSPropertyWebkitLocale: return ConsumeLocale(range_); case CSSPropertyAnimationDelay: case CSSPropertyTransitionDelay: return ConsumeCommaSeparatedList(ConsumeTime, range_, kValueRangeAll); - case CSSPropertyAnimationDirection: - return ConsumeCommaSeparatedList( - ConsumeIdent<CSSValueNormal, CSSValueAlternate, CSSValueReverse, - CSSValueAlternateReverse>, - range_); case CSSPropertyAnimationDuration: case CSSPropertyTransitionDuration: return ConsumeCommaSeparatedList(ConsumeTime, range_, kValueRangeNonNegative); - case CSSPropertyAnimationFillMode: - return ConsumeCommaSeparatedList( - ConsumeIdent<CSSValueNone, CSSValueForwards, CSSValueBackwards, - CSSValueBoth>, - range_); - case CSSPropertyAnimationIterationCount: - return ConsumeCommaSeparatedList(CSSPropertyAnimationIterationCountUtils:: - ConsumeAnimationIterationCount, - range_); - case CSSPropertyAnimationPlayState: - return ConsumeCommaSeparatedList( - ConsumeIdent<CSSValueRunning, CSSValuePaused>, range_); - case CSSPropertyTransitionProperty: { - CSSValueList* list = ConsumeCommaSeparatedList( - CSSPropertyTransitionPropertyUtils::ConsumeTransitionProperty, - range_); - if (!list || - !CSSPropertyTransitionPropertyUtils::IsValidPropertyList(*list)) - return nullptr; - return list; - } case CSSPropertyAnimationTimingFunction: case CSSPropertyTransitionTimingFunction: return ConsumeCommaSeparatedList(ConsumeAnimationTimingFunction, range_); @@ -1472,8 +1410,6 @@ return ConsumeLengthOrPercent(range_, context_->Mode(), kValueRangeNonNegative); case CSSPropertyColor: - case CSSPropertyBackgroundColor: - return ConsumeColor(range_, context_->Mode(), InQuirksMode()); case CSSPropertyBorderBottomColor: case CSSPropertyBorderLeftColor: case CSSPropertyBorderRightColor: @@ -1495,12 +1431,6 @@ return CSSPropertyWebkitBorderWidthUtils::ConsumeBorderWidth( range_, context_->Mode(), unitless); } - case CSSPropertyTextShadow: - return CSSPropertyBoxShadowUtils::ConsumeShadow( - range_, context_->Mode(), AllowInsetAndSpread::kForbid); - case CSSPropertyBoxShadow: - return CSSPropertyBoxShadowUtils::ConsumeShadow( - range_, context_->Mode(), AllowInsetAndSpread::kAllow); case CSSPropertyFilter: case CSSPropertyBackdropFilter: return ConsumeFilter(range_, context_); @@ -1560,8 +1490,6 @@ case CSSPropertyWebkitBorderImage: return CSSPropertyBorderImageUtils::ConsumeWebkitBorderImage(range_, context_); - case CSSPropertyWebkitBoxReflect: - return ConsumeReflect(range_, context_); case CSSPropertyBackgroundAttachment: case CSSPropertyBackgroundBlendMode: case CSSPropertyBackgroundClip:
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationDirection.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationDirection.cpp new file mode 100644 index 0000000..98739a9 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationDirection.cpp
@@ -0,0 +1,23 @@ +// 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 "core/css/properties/CSSPropertyAPIAnimationDirection.h" + +#include "core/CSSValueKeywords.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIAnimationDirection::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( + CSSPropertyParserHelpers::ConsumeIdent<CSSValueNormal, CSSValueAlternate, + CSSValueReverse, + CSSValueAlternateReverse>, + range); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationFillMode.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationFillMode.cpp new file mode 100644 index 0000000..4cd78f7 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationFillMode.cpp
@@ -0,0 +1,22 @@ +// 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 "core/css/properties/CSSPropertyAPIAnimationFillMode.h" + +#include "core/CSSValueKeywords.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIAnimationFillMode::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( + CSSPropertyParserHelpers::ConsumeIdent<CSSValueNone, CSSValueForwards, + CSSValueBackwards, CSSValueBoth>, + range); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationIterationCount.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationIterationCount.cpp new file mode 100644 index 0000000..f7b4e1f --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationIterationCount.cpp
@@ -0,0 +1,22 @@ +// 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 "core/css/properties/CSSPropertyAPIAnimationIterationCount.h" + +#include "core/CSSValueKeywords.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" +#include "core/css/properties/CSSPropertyAnimationIterationCountUtils.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIAnimationIterationCount::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( + CSSPropertyAnimationIterationCountUtils::ConsumeAnimationIterationCount, + range); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationPlayState.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationPlayState.cpp new file mode 100644 index 0000000..7d80b9a --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationPlayState.cpp
@@ -0,0 +1,21 @@ +// 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 "core/css/properties/CSSPropertyAPIAnimationPlayState.h" + +#include "core/CSSValueKeywords.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIAnimationPlayState::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( + CSSPropertyParserHelpers::ConsumeIdent<CSSValueRunning, CSSValuePaused>, + range); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBackgroundColor.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBackgroundColor.cpp new file mode 100644 index 0000000..6254c51 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBackgroundColor.cpp
@@ -0,0 +1,21 @@ +// 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 "core/css/properties/CSSPropertyAPIBackgroundColor.h" + +#include "core/css/parser/CSSParserContext.h" +#include "core/css/parser/CSSParserMode.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIBackgroundColor::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return CSSPropertyParserHelpers::ConsumeColor( + range, context.Mode(), IsQuirksModeBehavior(context.Mode())); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBoxShadow.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBoxShadow.cpp new file mode 100644 index 0000000..e95fd19 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIBoxShadow.cpp
@@ -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. + +#include "core/css/properties/CSSPropertyAPIBoxShadow.h" + +#include "core/css/parser/CSSParserContext.h" +#include "core/css/properties/CSSPropertyBoxShadowUtils.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIBoxShadow::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return CSSPropertyBoxShadowUtils::ConsumeShadow(range, context.Mode(), + AllowInsetAndSpread::kAllow); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIFontWeight.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIFontWeight.cpp new file mode 100644 index 0000000..16de6c58 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIFontWeight.cpp
@@ -0,0 +1,18 @@ +// 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 "core/css/properties/CSSPropertyAPIFontWeight.h" + +#include "core/css/properties/CSSPropertyFontUtils.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIFontWeight::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + return CSSPropertyFontUtils::ConsumeFontWeight(range); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIObjectPosition.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIObjectPosition.cpp new file mode 100644 index 0000000..89a55f96 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIObjectPosition.cpp
@@ -0,0 +1,21 @@ +// 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 "core/css/properties/CSSPropertyAPIObjectPosition.h" + +#include "core/css/CSSValuePair.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIObjectPosition::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return ConsumePosition(range, context, + CSSPropertyParserHelpers::UnitlessQuirk::kForbid, + WebFeature::kThreeValuedPositionObjectPosition); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIPerspectiveOrigin.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIPerspectiveOrigin.cpp new file mode 100644 index 0000000..56bc7ac2 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIPerspectiveOrigin.cpp
@@ -0,0 +1,21 @@ +// 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 "core/css/properties/CSSPropertyAPIPerspectiveOrigin.h" + +#include "core/css/CSSValuePair.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +const CSSValue* CSSPropertyAPIPerspectiveOrigin::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return ConsumePosition(range, context, + CSSPropertyParserHelpers::UnitlessQuirk::kForbid, + WebFeature::kThreeValuedPositionPerspectiveOrigin); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITextShadow.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITextShadow.cpp new file mode 100644 index 0000000..47cdf4a --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITextShadow.cpp
@@ -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. + +#include "core/css/properties/CSSPropertyAPITextShadow.h" + +#include "core/css/parser/CSSParserContext.h" +#include "core/css/properties/CSSPropertyBoxShadowUtils.h" + +namespace blink { + +const CSSValue* CSSPropertyAPITextShadow::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return CSSPropertyBoxShadowUtils::ConsumeShadow(range, context.Mode(), + AllowInsetAndSpread::kForbid); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransitionProperty.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransitionProperty.cpp new file mode 100644 index 0000000..30f9798 --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransitionProperty.cpp
@@ -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 "core/css/properties/CSSPropertyAPITransitionProperty.h" + +#include "core/css/CSSValueList.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" +#include "core/css/properties/CSSPropertyTransitionPropertyUtils.h" + +namespace blink { + +const CSSValue* CSSPropertyAPITransitionProperty::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext&, + const CSSParserLocalContext&) { + CSSValueList* list = CSSPropertyParserHelpers::ConsumeCommaSeparatedList( + CSSPropertyTransitionPropertyUtils::ConsumeTransitionProperty, range); + if (!list || !CSSPropertyTransitionPropertyUtils::IsValidPropertyList(*list)) + return nullptr; + return list; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitBoxReflect.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitBoxReflect.cpp new file mode 100644 index 0000000..70f5771b --- /dev/null +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitBoxReflect.cpp
@@ -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 "core/css/properties/CSSPropertyAPIWebkitBoxReflect.h" + +#include "core/css/CSSPrimitiveValue.h" +#include "core/css/CSSReflectValue.h" +#include "core/css/parser/CSSParserContext.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" +#include "core/css/properties/CSSPropertyBorderImageUtils.h" + +namespace blink { + +namespace { + +static CSSValue* ConsumeReflect(CSSParserTokenRange& range, + const CSSParserContext* context) { + CSSIdentifierValue* direction = CSSPropertyParserHelpers::ConsumeIdent< + CSSValueAbove, CSSValueBelow, CSSValueLeft, CSSValueRight>(range); + if (!direction) + return nullptr; + + CSSPrimitiveValue* offset = nullptr; + if (range.AtEnd()) { + offset = CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kPixels); + } else { + offset = ConsumeLengthOrPercent( + range, context->Mode(), kValueRangeAll, + CSSPropertyParserHelpers::UnitlessQuirk::kForbid); + if (!offset) + return nullptr; + } + + CSSValue* mask = nullptr; + if (!range.AtEnd()) { + mask = + CSSPropertyBorderImageUtils::ConsumeWebkitBorderImage(range, context); + if (!mask) + return nullptr; + } + return CSSReflectValue::Create(direction, offset, mask); +} + +} // namespace + +const CSSValue* CSSPropertyAPIWebkitBoxReflect::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + return ConsumeReflect(range, &context); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/AXObjectCacheBase.h b/third_party/WebKit/Source/core/dom/AXObjectCacheBase.h index 4192e4102..f1c119f 100644 --- a/third_party/WebKit/Source/core/dom/AXObjectCacheBase.h +++ b/third_party/WebKit/Source/core/dom/AXObjectCacheBase.h
@@ -13,10 +13,9 @@ class LayoutObject; class Node; class AXObject; -class AXObjectImpl; // AXObjectCacheBase is a temporary class that sits between AXObjectCache and -// AXObjectImpl and contains methods required by web/ that we don't want to be +// AXObject and contains methods required by web/ that we don't want to be // available in the public API (AXObjectCache). // TODO(dmazzoni): Once all dependencies in web/ use this class instead of // AXObjectCacheImpl, refactor usages to use AXObjectCache instead (introducing
diff --git a/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.cpp b/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.cpp index 4aec88f..95b1bc7 100644 --- a/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.cpp
@@ -4,7 +4,6 @@ #include "core/dom/DocumentShutdownObserver.h" -#include "core/dom/Document.h" #include "core/dom/DocumentShutdownNotifier.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.h b/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.h index d3e83589..51342bb 100644 --- a/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.h +++ b/third_party/WebKit/Source/core/dom/DocumentShutdownObserver.h
@@ -6,12 +6,11 @@ #define DocumentShutdownObserver_h #include "core/CoreExport.h" +#include "core/dom/Document.h" #include "platform/LifecycleObserver.h" namespace blink { -class Document; - // This class is a base class for classes which observe Document shutdown // synchronously. // Note: this functionality is also provided by SynchronousMutationObserver,
diff --git a/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp b/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp index 3cafc420..d7f5c1f 100644 --- a/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp +++ b/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
@@ -150,8 +150,7 @@ String url = GetDocument().CompleteURL(href).GetString(); StyleSheetResource* resource = nullptr; - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::processinginstruction; FetchParameters params(ResourceRequest(GetDocument().CompleteURL(href)), options);
diff --git a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp index 27e76960b..5d7f061 100644 --- a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp +++ b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
@@ -721,8 +721,7 @@ DocumentWriteIntervention::kDoNotFetchDocWrittenScript; } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = element_->InitiatorName(); FetchParameters params(resource_request, options);
diff --git a/third_party/WebKit/Source/core/editing/PlainTextRange.cpp b/third_party/WebKit/Source/core/editing/PlainTextRange.cpp index 849d7e4..90eefdb 100644 --- a/third_party/WebKit/Source/core/editing/PlainTextRange.cpp +++ b/third_party/WebKit/Source/core/editing/PlainTextRange.cpp
@@ -184,10 +184,10 @@ DocumentLifecycle::DisallowTransitionScope disallow_transition( scope.GetDocument().Lifecycle()); - size_t start = TextIterator::RangeLength( - Position(&const_cast<ContainerNode&>(scope), 0), range.StartPosition()); - size_t end = TextIterator::RangeLength( - Position(&const_cast<ContainerNode&>(scope), 0), range.EndPosition()); + size_t start = + TextIterator::RangeLength(Position(scope, 0), range.StartPosition()); + size_t end = + TextIterator::RangeLength(Position(scope, 0), range.EndPosition()); return PlainTextRange(start, end); }
diff --git a/third_party/WebKit/Source/core/editing/Position.cpp b/third_party/WebKit/Source/core/editing/Position.cpp index 1627ec1..1377761 100644 --- a/third_party/WebKit/Source/core/editing/Position.cpp +++ b/third_party/WebKit/Source/core/editing/Position.cpp
@@ -112,9 +112,13 @@ DCHECK_NE(anchor_type_, PositionAnchorType::kOffsetInAnchor); } +// TODO(editing-dev): Once we change type of |anchor_node_| to +// |Member<const Node>|, we should get rid of |const_cast<Node*>()|. +// See http://crbug.com/735327 template <typename Strategy> -PositionTemplate<Strategy>::PositionTemplate(Node* anchor_node, int offset) - : anchor_node_(anchor_node), +PositionTemplate<Strategy>::PositionTemplate(const Node* anchor_node, + int offset) + : anchor_node_(const_cast<Node*>(anchor_node)), offset_(offset), anchor_type_(PositionAnchorType::kOffsetInAnchor) { if (anchor_node_) @@ -127,6 +131,11 @@ } template <typename Strategy> +PositionTemplate<Strategy>::PositionTemplate(const Node& anchor_node, + int offset) + : PositionTemplate(&anchor_node, offset) {} + +template <typename Strategy> PositionTemplate<Strategy>::PositionTemplate(const PositionTemplate& other) : anchor_node_(other.anchor_node_), offset_(other.offset_),
diff --git a/third_party/WebKit/Source/core/editing/Position.h b/third_party/WebKit/Source/core/editing/Position.h index 5d05192..81a64ea 100644 --- a/third_party/WebKit/Source/core/editing/Position.h +++ b/third_party/WebKit/Source/core/editing/Position.h
@@ -70,8 +70,12 @@ PositionTemplate(Node* anchor_node, PositionAnchorType); // For creating offset positions: - // FIXME: This constructor should eventually go away. See bug 63040. - PositionTemplate(Node* anchor_node, int offset); + PositionTemplate(const Node& anchor_node, int offset); + // TODO(editing-dev): We should not pass |nullptr| as |anchor_node| for + // |Position| constructor. + // TODO(editing-dev): This constructor should eventually go away. See bug + // http://wkb.ug/63040. + PositionTemplate(const Node* anchor_node, int offset); PositionTemplate(const PositionTemplate&); @@ -209,6 +213,8 @@ return IsAfterAnchor() || IsAfterChildren(); } + // TODO(editing-dev): Since we should consider |Position| is constant in + // tree, we should use |Member<const Node>|. see http://crbug.com/735327 Member<Node> anchor_node_; // m_offset can be the offset inside m_anchorNode, or if // editingIgnoresContent(m_anchorNode) returns true, then other places in
diff --git a/third_party/WebKit/Source/core/editing/SelectionEditor.cpp b/third_party/WebKit/Source/core/editing/SelectionEditor.cpp index 4f3e990c..fdf7cea 100644 --- a/third_party/WebKit/Source/core/editing/SelectionEditor.cpp +++ b/third_party/WebKit/Source/core/editing/SelectionEditor.cpp
@@ -277,8 +277,6 @@ DidFinishTextChange(new_base, new_extent); } -// TODO(yosin): We should introduce |Position(const Text&, int)| to avoid -// |const_cast<Text*>|. static Position UpdatePostionAfterAdoptingTextNodesMerged( const Position& position, const Text& merged_node, @@ -292,21 +290,21 @@ return position; case PositionAnchorType::kBeforeAnchor: if (anchor_node == node_to_be_removed) - return Position(const_cast<Text*>(&merged_node), merged_node.length()); + return Position(merged_node, merged_node.length()); return position; case PositionAnchorType::kAfterAnchor: if (anchor_node == node_to_be_removed) - return Position(const_cast<Text*>(&merged_node), merged_node.length()); + return Position(merged_node, merged_node.length()); if (anchor_node == merged_node) - return Position(const_cast<Text*>(&merged_node), old_length); + return Position(merged_node, old_length); return position; case PositionAnchorType::kOffsetInAnchor: { const int offset = position.OffsetInContainerNode(); if (anchor_node == node_to_be_removed) - return Position(const_cast<Text*>(&merged_node), old_length + offset); + return Position(merged_node, old_length + offset); if (anchor_node == node_to_be_removed.parentNode() && offset == node_to_be_removed_with_index.Index()) { - return Position(const_cast<Text*>(&merged_node), old_length); + return Position(merged_node, old_length); } return position; }
diff --git a/third_party/WebKit/Source/core/editing/TextFinder.cpp b/third_party/WebKit/Source/core/editing/TextFinder.cpp index 62376f3f..5bb2ca8 100644 --- a/third_party/WebKit/Source/core/editing/TextFinder.cpp +++ b/third_party/WebKit/Source/core/editing/TextFinder.cpp
@@ -57,8 +57,6 @@ namespace blink { -class AXObjectImpl; - TextFinder::FindMatch::FindMatch(Range* range, int ordinal) : range_(range), ordinal_(ordinal) {}
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp index d6842c7..2fda8a6 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
@@ -766,9 +766,10 @@ return InlineBoxPosition(inline_box, caret_offset); // For example, abc 123 ^ CBA - inline_box = InlineBoxTraversal::FindRightBoundaryOfEntireBidiRun( - *inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretRightmostOffset()); + InlineBox* const result_box = + InlineBoxTraversal::FindRightBoundaryOfEntireBidiRun(*inline_box, + level); + return InlineBoxPosition(result_box, result_box->CaretRightmostOffset()); } if (IsStartOfDifferentDirection(inline_box)) @@ -781,9 +782,9 @@ if (next_box && next_box->BidiLevel() == level) return InlineBoxPosition(inline_box, caret_offset); - inline_box = + InlineBox* const result_box = InlineBoxTraversal::FindLeftBoundaryOfEntireBidiRun(*inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretLeftmostOffset()); + return InlineBoxPosition(result_box, result_box->CaretLeftmostOffset()); } static InlineBoxPosition AdjustInlineBoxPositionForTextDirection( @@ -796,24 +797,23 @@ const unsigned char level = inline_box->BidiLevel(); if (caret_offset == inline_box->CaretLeftmostOffset()) { - InlineBox* prev_box = inline_box->PrevLeafChildIgnoringLineBreak(); + InlineBox* const prev_box = inline_box->PrevLeafChildIgnoringLineBreak(); if (!prev_box || prev_box->BidiLevel() < level) { // Left edge of a secondary run. Set to the right edge of the entire // run. - inline_box = + InlineBox* const result_box = InlineBoxTraversal::FindRightBoundaryOfEntireBidiRunIgnoringLineBreak( *inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretRightmostOffset()); + return InlineBoxPosition(result_box, result_box->CaretRightmostOffset()); } - if (prev_box->BidiLevel() > level) { - // Right edge of a "tertiary" run. Set to the left edge of that run. - inline_box = - InlineBoxTraversal::FindLeftBoundaryOfBidiRunIgnoringLineBreak( - *inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretLeftmostOffset()); - } - return InlineBoxPosition(inline_box, caret_offset); + if (prev_box->BidiLevel() <= level) + return InlineBoxPosition(inline_box, caret_offset); + // Right edge of a "tertiary" run. Set to the left edge of that run. + InlineBox* const result_box = + InlineBoxTraversal::FindLeftBoundaryOfBidiRunIgnoringLineBreak( + *inline_box, level); + return InlineBoxPosition(result_box, result_box->CaretLeftmostOffset()); } if (unicode_bidi == UnicodeBidi::kPlaintext) { @@ -822,23 +822,24 @@ return InlineBoxPosition(inline_box, inline_box->CaretRightmostOffset()); } - InlineBox* next_box = inline_box->NextLeafChildIgnoringLineBreak(); + InlineBox* const next_box = inline_box->NextLeafChildIgnoringLineBreak(); if (!next_box || next_box->BidiLevel() < level) { // Right edge of a secondary run. Set to the left edge of the entire // run. - inline_box = + InlineBox* const result_box = InlineBoxTraversal::FindLeftBoundaryOfEntireBidiRunIgnoringLineBreak( *inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretLeftmostOffset()); + return InlineBoxPosition(result_box, result_box->CaretLeftmostOffset()); } if (next_box->BidiLevel() <= level) return InlineBoxPosition(inline_box, caret_offset); // Left edge of a "tertiary" run. Set to the right edge of that run. - inline_box = InlineBoxTraversal::FindRightBoundaryOfBidiRunIgnoringLineBreak( - *inline_box, level); - return InlineBoxPosition(inline_box, inline_box->CaretRightmostOffset()); + InlineBox* const result_box = + InlineBoxTraversal::FindRightBoundaryOfBidiRunIgnoringLineBreak( + *inline_box, level); + return InlineBoxPosition(result_box, result_box->CaretRightmostOffset()); } // Returns true if |caret_offset| is at edge of |box| based on |affinity|.
diff --git a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp index eaba282..65ac5ee 100644 --- a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp +++ b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp
@@ -79,10 +79,14 @@ .Build(); } +static inline bool HasDisplayContents(const Node& node) { + return node.IsElementNode() && ToElement(node).HasDisplayContentsStyle(); +} + // Checks if |advance()| skips the descendants of |node|, which is the case if // |node| is neither a shadow root nor the owner of a layout object. static bool NotSkipping(const Node& node) { - return node.GetLayoutObject() || + return node.GetLayoutObject() || HasDisplayContents(node) || (node.IsShadowRoot() && node.OwnerShadowHost()->GetLayoutObject()); } @@ -293,13 +297,13 @@ LayoutObject* layout_object = node_->GetLayoutObject(); if (!layout_object) { - if (node_->IsShadowRoot()) { - // A shadow root doesn't have a layoutObject, but we want to visit - // children anyway. + if (node_->IsShadowRoot() || HasDisplayContents(*node_)) { + // Shadow roots or display: contents elements don't have LayoutObjects, + // but we want to visit children anyway. iteration_progress_ = iteration_progress_ < kHandledNode ? kHandledNode : iteration_progress_; - handle_shadow_root_ = true; + handle_shadow_root_ = node_->IsShadowRoot(); } else { iteration_progress_ = kHandledChildren; }
diff --git a/third_party/WebKit/Source/core/editing/iterators/TextIteratorTest.cpp b/third_party/WebKit/Source/core/editing/iterators/TextIteratorTest.cpp index 357042e..93eae7b8 100644 --- a/third_party/WebKit/Source/core/editing/iterators/TextIteratorTest.cpp +++ b/third_party/WebKit/Source/core/editing/iterators/TextIteratorTest.cpp
@@ -934,4 +934,12 @@ EXPECT_EQ("xyz", String(buffer.Data())); } +TEST_F(TextIteratorTest, VisitsDisplayContentsChildren) { + SetBodyContent( + "<p>Hello, \ntext</p><p style='display: contents'>iterator.</p>"); + + EXPECT_EQ("[Hello, ][text][iterator.]", Iterate<DOMTree>()); + EXPECT_EQ("[Hello, ][text][iterator.]", Iterate<FlatTree>()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/markers/TextMatchMarkerListImpl.cpp b/third_party/WebKit/Source/core/editing/markers/TextMatchMarkerListImpl.cpp index 6a89e3c..1bf76df 100644 --- a/third_party/WebKit/Source/core/editing/markers/TextMatchMarkerListImpl.cpp +++ b/third_party/WebKit/Source/core/editing/markers/TextMatchMarkerListImpl.cpp
@@ -58,8 +58,8 @@ } static void UpdateMarkerLayoutRect(const Node& node, TextMatchMarker& marker) { - const Position start_position(&const_cast<Node&>(node), marker.StartOffset()); - const Position end_position(&const_cast<Node&>(node), marker.EndOffset()); + const Position start_position(node, marker.StartOffset()); + const Position end_position(node, marker.EndOffset()); EphemeralRange range(start_position, end_position); marker.SetLayoutRect(LayoutRect(ComputeTextRect(range))); }
diff --git a/third_party/WebKit/Source/core/exported/DEPS b/third_party/WebKit/Source/core/exported/DEPS index fbc3d4f..09e1f4ec 100644 --- a/third_party/WebKit/Source/core/exported/DEPS +++ b/third_party/WebKit/Source/core/exported/DEPS
@@ -1,3 +1,6 @@ include_rules = [ + # Files in exported are allowed to take dependencies on other files in + # exported. + "+core/exported", "+public/web", ]
diff --git a/third_party/WebKit/Source/core/exported/README.md b/third_party/WebKit/Source/core/exported/README.md new file mode 100644 index 0000000..76cf552 --- /dev/null +++ b/third_party/WebKit/Source/core/exported/README.md
@@ -0,0 +1,2 @@ +Files that are implementations of abstract classes defined in public/web/ that +have no dependencies on modules/.
diff --git a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp index 9cb72c1..c9425140 100644 --- a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImpl.cpp
@@ -390,11 +390,9 @@ static_cast<PreflightPolicy>(options_.preflight_policy); options.fetch_request_mode = options_.fetch_request_mode; - StoredCredentials allow_credentials = options_.allow_credentials - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; - ResourceLoaderOptions resource_loader_options( - allow_credentials, kClientDidNotRequestCredentials); + new_request.SetFetchCredentialsMode(options_.fetch_credentials_mode); + + ResourceLoaderOptions resource_loader_options; resource_loader_options.data_buffering_policy = kDoNotBufferData; const ResourceRequest& webcore_request = new_request.ToResourceRequest();
diff --git a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp index 2506615..5eaf05cd 100644 --- a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp +++ b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp
@@ -358,7 +358,7 @@ // Send credentials. This will cause the CORS checks to fail, because // credentials can't be sent to a server which returns the header // "access-control-allow-origin" with "*" as its value. - options.allow_credentials = true; + options.fetch_credentials_mode = WebURLRequest::kFetchCredentialsModeInclude; options.fetch_request_mode = WebURLRequest::kFetchRequestModeCORS; expected_loader_ = CreateAssociatedURLLoader(options); EXPECT_TRUE(expected_loader_);
diff --git a/third_party/WebKit/Source/core/exported/WebImageDecoder.cpp b/third_party/WebKit/Source/core/exported/WebImageDecoder.cpp index 1da10eb..b4dfb1d 100644 --- a/third_party/WebKit/Source/core/exported/WebImageDecoder.cpp +++ b/third_party/WebKit/Source/core/exported/WebImageDecoder.cpp
@@ -64,7 +64,7 @@ void WebImageDecoder::SetData(const WebData& data, bool all_data_received) { DCHECK(private_); - private_->SetData(PassRefPtr<SharedBuffer>(data).Get(), all_data_received); + private_->SetData(data, all_data_received); } bool WebImageDecoder::IsFailed() const {
diff --git a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp index e4f398b9..fdc6f8b 100644 --- a/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebSharedWorkerImpl.cpp
@@ -193,13 +193,17 @@ loading_document_ = main_frame_->GetFrame()->GetDocument(); WebURLRequest::FetchRequestMode fetch_request_mode = - (static_cast<KURL>(url_)).ProtocolIsData() - ? WebURLRequest::kFetchRequestModeNoCORS - : WebURLRequest::kFetchRequestModeSameOrigin; + WebURLRequest::kFetchRequestModeSameOrigin; + WebURLRequest::FetchCredentialsMode fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeSameOrigin; + if ((static_cast<KURL>(url_)).ProtocolIsData()) { + fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; + fetch_credentials_mode = WebURLRequest::kFetchCredentialsModeInclude; + } main_script_loader_->LoadAsynchronously( *loading_document_.Get(), url_, fetch_request_mode, - creation_address_space_, + fetch_credentials_mode, creation_address_space_, Bind(&WebSharedWorkerImpl::DidReceiveScriptLoaderResponse, WTF::Unretained(this)), Bind(&WebSharedWorkerImpl::OnScriptLoaderFinished,
diff --git a/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp b/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp index 0162edd..3fabee9 100644 --- a/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp +++ b/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp
@@ -44,6 +44,7 @@ #include "platform/loader/fetch/ResourceLoaderOptions.h" #include "platform/loader/fetch/ResourceRequest.h" #include "platform/loader/fetch/ResourceResponse.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/wtf/PassRefPtr.h" #include "platform/wtf/PtrUtil.h" #include "platform/wtf/RefPtr.h" @@ -102,8 +103,7 @@ options.content_security_policy_enforcement = kDoNotEnforceContentSecurityPolicy; - ResourceLoaderOptions resource_loader_options( - kAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; // Use special initiator to hide the request from the inspector. resource_loader_options.initiator_info.name = FetchInitiatorTypeNames::internal; @@ -366,9 +366,9 @@ // FIXME: consider supporting incremental decoding to improve the perf. StringBuilder builder; if (!decoder_) { - decoder_ = TextResourceDecoder::Create( - TextResourceDecoder::kPlainTextContent, - encoding_.IsValid() ? encoding_ : UTF8Encoding()); + decoder_ = TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + encoding_.IsValid() ? encoding_ : UTF8Encoding())); } builder.Append(decoder_->Decode(static_cast<const char*>(raw_data_->Data()), raw_data_->ByteLength()));
diff --git a/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp b/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp index 01caf94..b79a7e3 100644 --- a/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp +++ b/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp
@@ -47,15 +47,17 @@ static bool IsAllowed(ScriptState* script_state, ExecutionContext* execution_context, - bool is_eval) { + bool is_eval, + const String& source) { if (execution_context->IsDocument()) { Document* document = static_cast<Document*>(execution_context); if (!document->GetFrame()) return false; if (is_eval && !document->GetContentSecurityPolicy()->AllowEval( script_state, SecurityViolationReportingPolicy::kReport, - ContentSecurityPolicy::kWillNotThrowException)) + ContentSecurityPolicy::kWillNotThrowException, source)) { return false; + } return true; } if (execution_context->IsWorkerGlobalScope()) { @@ -66,10 +68,11 @@ ContentSecurityPolicy* policy = worker_global_scope->GetContentSecurityPolicy(); if (is_eval && policy && - !policy->AllowEval(script_state, - SecurityViolationReportingPolicy::kReport, - ContentSecurityPolicy::kWillNotThrowException)) + !policy->AllowEval( + script_state, SecurityViolationReportingPolicy::kReport, + ContentSecurityPolicy::kWillNotThrowException, source)) { return false; + } return true; } NOTREACHED(); @@ -82,7 +85,7 @@ int timeout, const Vector<ScriptValue>& arguments) { ExecutionContext* execution_context = event_target.GetExecutionContext(); - if (!IsAllowed(script_state, execution_context, false)) + if (!IsAllowed(script_state, execution_context, false, g_empty_string)) return 0; if (timeout >= 0 && execution_context->IsDocument()) { // FIXME: Crude hack that attempts to pass idle time to V8. This should @@ -100,7 +103,7 @@ int timeout, const Vector<ScriptValue>&) { ExecutionContext* execution_context = event_target.GetExecutionContext(); - if (!IsAllowed(script_state, execution_context, true)) + if (!IsAllowed(script_state, execution_context, true, handler)) return 0; // Don't allow setting timeouts to run empty functions. Was historically a // perfomance issue. @@ -122,7 +125,7 @@ int timeout, const Vector<ScriptValue>& arguments) { ExecutionContext* execution_context = event_target.GetExecutionContext(); - if (!IsAllowed(script_state, execution_context, false)) + if (!IsAllowed(script_state, execution_context, false, g_empty_string)) return 0; ScheduledAction* action = ScheduledAction::Create( script_state, execution_context, handler, arguments); @@ -135,7 +138,7 @@ int timeout, const Vector<ScriptValue>&) { ExecutionContext* execution_context = event_target.GetExecutionContext(); - if (!IsAllowed(script_state, execution_context, true)) + if (!IsAllowed(script_state, execution_context, true, handler)) return 0; // Don't allow setting timeouts to run empty functions. Was historically a // perfomance issue.
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameClient.h b/third_party/WebKit/Source/core/frame/LocalFrameClient.h index d80ad75e..979bc3a 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameClient.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameClient.h
@@ -55,6 +55,7 @@ #include "public/platform/WebInsecureRequestPolicy.h" #include "public/platform/WebLoadingBehaviorFlag.h" #include "public/platform/WebURLRequest.h" +#include "public/web/WebTriggeringEventInfo.h" #include "v8/include/v8.h" namespace service_manager { @@ -130,6 +131,7 @@ NavigationPolicy, bool should_replace_current_entry, bool is_client_redirect, + WebTriggeringEventInfo, HTMLFormElement*, ContentSecurityPolicyDisposition should_check_main_world_content_security_policy) = 0;
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index ed713dc3..f390c9a 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -178,7 +178,8 @@ const String& message, const KURL& blocked_url, ScriptState* script_state, - const ContentSecurityPolicy::ExceptionStatus exception_status) const { + const ContentSecurityPolicy::ExceptionStatus exception_status, + const String& content) const { String report_message = IsReportOnly() ? "[Report Only] " + message : message; // Print a console message if it won't be redundant with a // JavaScript exception that the caller will throw. (Exceptions will @@ -193,7 +194,8 @@ policy_->ReportViolation(directive_text, effective_type, message, blocked_url, report_endpoints_, header_, header_type_, ContentSecurityPolicy::kEvalViolation, - std::unique_ptr<SourceLocation>()); + std::unique_ptr<SourceLocation>(), nullptr, + RedirectStatus::kFollowedRedirect, nullptr, content); } bool CSPDirectiveList::CheckEval(SourceListDirective* directive) const { @@ -382,7 +384,8 @@ SourceListDirective* directive, const String& console_message, ScriptState* script_state, - ContentSecurityPolicy::ExceptionStatus exception_status) const { + ContentSecurityPolicy::ExceptionStatus exception_status, + const String& content) const { if (CheckEval(directive)) return true; @@ -395,7 +398,10 @@ ReportViolationWithState( directive->GetText(), ContentSecurityPolicy::DirectiveType::kScriptSrc, console_message + "\"" + directive->GetText() + "\"." + suffix + "\n", - KURL(), script_state, exception_status); + KURL(), script_state, exception_status, + policy_->ExperimentalFeaturesEnabled() && directive->AllowReportSample() + ? content + : g_empty_string); if (!IsReportOnly()) { policy_->ReportBlockedScriptExecutionToInspector(directive->GetText()); return false; @@ -648,14 +654,15 @@ bool CSPDirectiveList::AllowEval( ScriptState* script_state, SecurityViolationReportingPolicy reporting_policy, - ContentSecurityPolicy::ExceptionStatus exception_status) const { + ContentSecurityPolicy::ExceptionStatus exception_status, + const String& content) const { if (reporting_policy == SecurityViolationReportingPolicy::kReport) { return CheckEvalAndReportViolation( OperativeDirective(script_src_.Get()), "Refused to evaluate a string as JavaScript because 'unsafe-eval' is " "not an allowed source of script in the following Content Security " "Policy directive: ", - script_state, exception_status); + script_state, exception_status, content); } return CheckEval(OperativeDirective(script_src_.Get())); }
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.h b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.h index ed3d0cd..32115651 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.h +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.h
@@ -69,8 +69,8 @@ const String& style_content) const; bool AllowEval(ScriptState*, SecurityViolationReportingPolicy, - ContentSecurityPolicy::ExceptionStatus = - ContentSecurityPolicy::kWillNotThrowException) const; + ContentSecurityPolicy::ExceptionStatus, + const String& script_content) const; bool AllowPluginType(const String& type, const String& type_attribute, const KURL&, @@ -233,13 +233,13 @@ const WTF::OrdinalNumber& context_line, Element*, const String& source) const; - void ReportViolationWithState( - const String& directive_text, - const ContentSecurityPolicy::DirectiveType&, - const String& message, - const KURL& blocked_url, - ScriptState*, - const ContentSecurityPolicy::ExceptionStatus) const; + void ReportViolationWithState(const String& directive_text, + const ContentSecurityPolicy::DirectiveType&, + const String& message, + const KURL& blocked_url, + ScriptState*, + const ContentSecurityPolicy::ExceptionStatus, + const String& content) const; bool CheckEval(SourceListDirective*) const; bool CheckDynamic(SourceListDirective*) const; @@ -261,12 +261,11 @@ eval_disabled_error_message_ = error_message; } - bool CheckEvalAndReportViolation( - SourceListDirective*, - const String& console_message, - ScriptState*, - ContentSecurityPolicy::ExceptionStatus = - ContentSecurityPolicy::kWillNotThrowException) const; + bool CheckEvalAndReportViolation(SourceListDirective*, + const String& console_message, + ScriptState*, + ContentSecurityPolicy::ExceptionStatus, + const String& script_content) const; bool CheckInlineAndReportViolation(SourceListDirective*, const String& console_message, Element*,
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 7f98269..191e78b 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -338,10 +338,12 @@ Member<CSPDirectiveList> policy = CSPDirectiveList::Create(this, begin, position, type, source); - if (!policy->AllowEval( - 0, SecurityViolationReportingPolicy::kSuppressReporting) && - disable_eval_error_message_.IsNull()) + if (!policy->AllowEval(0, + SecurityViolationReportingPolicy::kSuppressReporting, + kWillNotThrowException, g_empty_string) && + disable_eval_error_message_.IsNull()) { disable_eval_error_message_ = policy->EvalDisabledErrorMessage(); + } policies_.push_back(policy.Release()); @@ -418,18 +420,20 @@ return headers; } -template <bool (CSPDirectiveList::*allowed)( - ScriptState* script_state, - SecurityViolationReportingPolicy, - ContentSecurityPolicy::ExceptionStatus) const> +template < + bool (CSPDirectiveList::*allowed)(ScriptState* script_state, + SecurityViolationReportingPolicy, + ContentSecurityPolicy::ExceptionStatus, + const String& script_content) const> bool IsAllowedByAll(const CSPDirectiveListVector& policies, ScriptState* script_state, SecurityViolationReportingPolicy reporting_policy, - ContentSecurityPolicy::ExceptionStatus exception_status) { + ContentSecurityPolicy::ExceptionStatus exception_status, + const String& script_content) { bool is_allowed = true; for (const auto& policy : policies) { is_allowed &= (policy.Get()->*allowed)(script_state, reporting_policy, - exception_status); + exception_status, script_content); } return is_allowed; } @@ -690,16 +694,20 @@ bool ContentSecurityPolicy::AllowEval( ScriptState* script_state, SecurityViolationReportingPolicy reporting_policy, - ContentSecurityPolicy::ExceptionStatus exception_status) const { + ContentSecurityPolicy::ExceptionStatus exception_status, + const String& script_content) const { return IsAllowedByAll<&CSPDirectiveList::AllowEval>( - policies_, script_state, reporting_policy, exception_status); + policies_, script_state, reporting_policy, exception_status, + script_content); } String ContentSecurityPolicy::EvalDisabledErrorMessage() const { for (const auto& policy : policies_) { - if (!policy->AllowEval( - 0, SecurityViolationReportingPolicy::kSuppressReporting)) + if (!policy->AllowEval(0, + SecurityViolationReportingPolicy::kSuppressReporting, + kWillNotThrowException, g_empty_string)) { return policy->EvalDisabledErrorMessage(); + } } return String(); } @@ -1155,8 +1163,10 @@ init.setColumnNumber(0); } - if (!script_source.IsEmpty()) - init.setSample(script_source.StripWhiteSpace().Left(40)); + if (!script_source.IsEmpty()) { + init.setSample(script_source.StripWhiteSpace().Left( + ContentSecurityPolicy::kMaxSampleLength)); + } } void ContentSecurityPolicy::ReportViolation(
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h index 817dc1ef..2de91b11 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h
@@ -126,6 +126,8 @@ kCheckReportOnly }; + static const size_t kMaxSampleLength = 40; + static ContentSecurityPolicy* Create() { return new ContentSecurityPolicy(); } ~ContentSecurityPolicy(); DECLARE_TRACE(); @@ -172,10 +174,10 @@ // exception in the event of a violation. When the caller will throw // an exception, ContentSecurityPolicy does not log a violation // message to the console because it would be redundant. - bool AllowEval(ScriptState* = nullptr, - SecurityViolationReportingPolicy = - SecurityViolationReportingPolicy::kReport, - ExceptionStatus = kWillNotThrowException) const; + bool AllowEval(ScriptState*, + SecurityViolationReportingPolicy, + ExceptionStatus, + const String& script_content) const; bool AllowPluginType(const String& type, const String& type_attribute, const KURL&,
diff --git a/third_party/WebKit/Source/core/html/LinkStyle.cpp b/third_party/WebKit/Source/core/html/LinkStyle.cpp index 39988f2..00230a06 100644 --- a/third_party/WebKit/Source/core/html/LinkStyle.cpp +++ b/third_party/WebKit/Source/core/html/LinkStyle.cpp
@@ -326,8 +326,7 @@ referrer_policy, url, GetDocument().OutgoingReferrer())); } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = owner_->localName(); FetchParameters params(resource_request, options); params.SetCharset(charset);
diff --git a/third_party/WebKit/Source/core/html/imports/LinkImport.cpp b/third_party/WebKit/Source/core/html/imports/LinkImport.cpp index d3bcae9..7a7f35b 100644 --- a/third_party/WebKit/Source/core/html/imports/LinkImport.cpp +++ b/third_party/WebKit/Source/core/html/imports/LinkImport.cpp
@@ -97,8 +97,7 @@ referrer_policy, url, GetDocument().OutgoingReferrer())); } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = owner_->localName(); FetchParameters params(resource_request, options); params.SetCharset(GetCharset());
diff --git a/third_party/WebKit/Source/core/html/parser/PreloadRequest.cpp b/third_party/WebKit/Source/core/html/parser/PreloadRequest.cpp index e42a603..e1540b9 100644 --- a/third_party/WebKit/Source/core/html/parser/PreloadRequest.cpp +++ b/third_party/WebKit/Source/core/html/parser/PreloadRequest.cpp
@@ -52,8 +52,7 @@ if (resource_type_ == Resource::kScript) MaybeDisallowFetchForDocWrittenScript(resource_request, defer_, *document); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info = initiator_info; FetchParameters params(resource_request, options);
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp index 3506eb94..16f8f8f 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp
@@ -25,7 +25,6 @@ #include "core/HTMLNames.h" #include "core/dom/DOMImplementation.h" #include "core/html/parser/HTMLMetaCharsetParser.h" -#include "platform/Language.h" #include "platform/text/TextEncodingDetector.h" #include "platform/wtf/StringExtras.h" #include "platform/wtf/text/TextCodec.h" @@ -118,11 +117,11 @@ } const WTF::TextEncoding& TextResourceDecoder::DefaultEncoding( - ContentType content_type, + TextResourceDecoderOptions::ContentType content_type, const WTF::TextEncoding& specified_default_encoding) { // Despite 8.5 "Text/xml with Omitted Charset" of RFC 3023, we assume UTF-8 // instead of US-ASCII for text/xml. This matches Firefox. - if (content_type == kXMLContent) + if (content_type == TextResourceDecoderOptions::kXMLContent) return UTF8Encoding(); if (!specified_default_encoding.IsValid()) return Latin1Encoding(); @@ -130,39 +129,22 @@ } TextResourceDecoder::TextResourceDecoder( - ContentType content_type, - const WTF::TextEncoding& specified_default_encoding, - EncodingDetectionOption encoding_detection_option, - const KURL& hint_url) - : content_type_(content_type), - encoding_(DefaultEncoding(content_type_, specified_default_encoding)), + const TextResourceDecoderOptions& options) + : options_(options), + encoding_(DefaultEncoding(options_.GetContentType(), + options_.DefaultEncoding())), source_(kDefaultEncoding), - hint_encoding_(0), - hint_url_(hint_url), checked_for_bom_(false), checked_for_css_charset_(false), checked_for_xml_charset_(false), checked_for_meta_charset_(false), - use_lenient_xml_decoding_(false), - saw_error_(false), - encoding_detection_option_(encoding_detection_option) { - hint_language_[0] = 0; - if (encoding_detection_option_ == kAlwaysUseUTF8ForText) { - DCHECK(content_type_ == kPlainTextContent && encoding_ == UTF8Encoding()); - } else if (encoding_detection_option_ == kUseAllAutoDetection) { - // Checking empty URL helps unit testing. Providing defaultLanguage() is - // sometimes difficult in tests. - if (!hint_url.IsEmpty()) { - // This object is created in the main thread, but used in another thread. - // We should not share an AtomicString. - AtomicString locale = DefaultLanguage(); - if (locale.length() >= 2) { - // defaultLanguage() is always an ASCII string. - hint_language_[0] = static_cast<char>(locale[0]); - hint_language_[1] = static_cast<char>(locale[1]); - hint_language_[2] = 0; - } - } + saw_error_(false) { + // TODO(hiroshige): Move the invariant check to TextResourceDecoderOptions. + if (options_.GetEncodingDetectionOption() == + TextResourceDecoderOptions::kAlwaysUseUTF8ForText) { + DCHECK_EQ(options_.GetContentType(), + TextResourceDecoderOptions::kPlainTextContent); + DCHECK(encoding_ == UTF8Encoding()); } } @@ -255,7 +237,8 @@ if (c1 == 0xEF && c2 == 0xBB && c3 == 0xBF) { SetEncoding(UTF8Encoding(), kAutoDetectedEncoding); length_of_bom = 3; - } else if (encoding_detection_option_ != kAlwaysUseUTF8ForText) { + } else if (options_.GetEncodingDetectionOption() != + TextResourceDecoderOptions::kAlwaysUseUTF8ForText) { if (c1 == 0xFF && c2 == 0xFE && buffer_length + len >= 4) { if (c3 || c4) { SetEncoding(UTF16LittleEndianEncoding(), kAutoDetectedEncoding); @@ -409,18 +392,19 @@ // in the first place. void TextResourceDecoder::AutoDetectEncodingIfAllowed(const char* data, size_t len) { - if (encoding_detection_option_ != kUseAllAutoDetection) + if (options_.GetEncodingDetectionOption() != + TextResourceDecoderOptions::kUseAllAutoDetection) return; // Just checking hint_encoding_ suffices here because it's only set // in SetHintEncoding when the source is AutoDetectedEncoding. if (!(source_ == kDefaultEncoding || - (source_ == kEncodingFromParentFrame && hint_encoding_))) + (source_ == kEncodingFromParentFrame && options_.HintEncoding()))) return; WTF::TextEncoding detected_encoding; - if (DetectTextEncoding(data, len, hint_encoding_, hint_url_, hint_language_, - &detected_encoding)) + if (DetectTextEncoding(data, len, options_.HintEncoding(), options_.HintURL(), + options_.HintLanguage(), &detected_encoding)) SetEncoding(detected_encoding, kEncodingFromContentSniffing); } @@ -440,16 +424,17 @@ bool moved_data_to_buffer = false; - if (content_type_ == kCSSContent && !checked_for_css_charset_) { + if (options_.GetContentType() == TextResourceDecoderOptions::kCSSContent && + !checked_for_css_charset_) { if (!CheckForCSSCharset(data, len, moved_data_to_buffer)) return g_empty_string; } // We check XML declaration in HTML content only if there is enough data // available - if (((content_type_ == kHTMLContent && + if (((options_.GetContentType() == TextResourceDecoderOptions::kHTMLContent && len >= kMinimumLengthOfXMLDeclaration) || - content_type_ == kXMLContent) && + options_.GetContentType() == TextResourceDecoderOptions::kXMLContent) && !checked_for_xml_charset_) { if (!CheckForXMLCharset(data, len, moved_data_to_buffer)) return g_empty_string; @@ -469,7 +454,8 @@ length_for_decode = buffer_.size() - length_of_bom; } - if (content_type_ == kHTMLContent && !checked_for_meta_charset_) + if (options_.GetContentType() == TextResourceDecoderOptions::kHTMLContent && + !checked_for_meta_charset_) CheckForMetaCharset(data_for_decode, length_for_decode); AutoDetectEncodingIfAllowed(data, len); @@ -481,7 +467,9 @@ String result = codec_->Decode( data_for_decode, length_for_decode, WTF::kDoNotFlush, - content_type_ == kXMLContent && !use_lenient_xml_decoding_, saw_error_); + options_.GetContentType() == TextResourceDecoderOptions::kXMLContent && + !options_.GetUseLenientXMLDecoding(), + saw_error_); buffer_.clear(); return result; @@ -491,10 +479,14 @@ // If we can not identify the encoding even after a document is completely // loaded, we need to detect the encoding if other conditions for // autodetection is satisfied. - if (buffer_.size() && - ((!checked_for_xml_charset_ && - (content_type_ == kHTMLContent || content_type_ == kXMLContent)) || - (!checked_for_css_charset_ && (content_type_ == kCSSContent)))) { + if (buffer_.size() && ((!checked_for_xml_charset_ && + (options_.GetContentType() == + TextResourceDecoderOptions::kHTMLContent || + options_.GetContentType() == + TextResourceDecoderOptions::kXMLContent)) || + (!checked_for_css_charset_ && + (options_.GetContentType() == + TextResourceDecoderOptions::kCSSContent)))) { AutoDetectEncodingIfAllowed(buffer_.data(), buffer_.size()); } @@ -503,7 +495,9 @@ String result = codec_->Decode( buffer_.data(), buffer_.size(), WTF::kFetchEOF, - content_type_ == kXMLContent && !use_lenient_xml_decoding_, saw_error_); + options_.GetContentType() == TextResourceDecoderOptions::kXMLContent && + !options_.GetUseLenientXMLDecoding(), + saw_error_); buffer_.clear(); codec_.reset(); checked_for_bom_ = false; // Skip BOM again when re-decoding.
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h index 81f5a90..ab79678 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h
@@ -25,6 +25,7 @@ #include <memory> #include "core/CoreExport.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/weborigin/KURL.h" #include "platform/wtf/PtrUtil.h" #include "platform/wtf/text/TextEncoding.h" @@ -49,36 +50,11 @@ kEncodingFromParentFrame }; - enum ContentType { - kPlainTextContent, - kHTMLContent, - kXMLContent, - kCSSContent, - kMaxContentType = kCSSContent - }; // PlainText only checks for BOM. - static std::unique_ptr<TextResourceDecoder> Create( - ContentType content_type, - const WTF::TextEncoding& default_encoding = WTF::TextEncoding()) { - return WTF::WrapUnique( - new TextResourceDecoder(content_type, default_encoding, - kUseContentAndBOMBasedDetection, KURL())); + const TextResourceDecoderOptions& options) { + return WTF::WrapUnique(new TextResourceDecoder(options)); } - static std::unique_ptr<TextResourceDecoder> CreateWithAutoDetection( - ContentType content_type, - const WTF::TextEncoding& default_encoding, - const KURL& url) { - return WTF::WrapUnique(new TextResourceDecoder( - content_type, default_encoding, kUseAllAutoDetection, url)); - } - - // Corresponds to utf-8 decode in Encoding spec: - // https://encoding.spec.whatwg.org/#utf-8-decode. - static std::unique_ptr<TextResourceDecoder> CreateAlwaysUseUTF8ForText() { - return WTF::WrapUnique(new TextResourceDecoder( - kPlainTextContent, UTF8Encoding(), kAlwaysUseUTF8ForText, KURL())); - } ~TextResourceDecoder(); void SetEncoding(const WTF::TextEncoding&, EncodingSource); @@ -91,43 +67,15 @@ String Decode(const char* data, size_t length); String Flush(); - void SetHintEncoding(const WTF::TextEncoding& encoding) { - hint_encoding_ = encoding.GetName(); - } - - void UseLenientXMLDecoding() { use_lenient_xml_decoding_ = true; } bool SawError() const { return saw_error_; } size_t CheckForBOM(const char*, size_t); protected: - // TextResourceDecoder does three kind of encoding detection: - // 1. By BOM, - // 2. By Content if |m_contentType| is not |PlainTextContext| - // (e.g. <meta> tag for HTML), and - // 3. By detectTextEncoding(). - enum EncodingDetectionOption { - // Use 1. + 2. + 3. - kUseAllAutoDetection, - - // Use 1. + 2. - kUseContentAndBOMBasedDetection, - - // Use None of them. - // |m_contentType| must be |PlainTextContent| and - // |m_encoding| must be UTF8Encoding. - // This doesn't change encoding based on BOMs, but still processes - // utf-8 BOMs so that utf-8 BOMs don't appear in the decoded result. - kAlwaysUseUTF8ForText - }; - - TextResourceDecoder(ContentType, - const WTF::TextEncoding& default_encoding, - EncodingDetectionOption, - const KURL& hint_url); + TextResourceDecoder(const TextResourceDecoderOptions&); private: static const WTF::TextEncoding& DefaultEncoding( - ContentType, + TextResourceDecoderOptions::ContentType, const WTF::TextEncoding& default_encoding); bool CheckForCSSCharset(const char*, size_t, bool& moved_data_to_buffer); @@ -135,21 +83,17 @@ void CheckForMetaCharset(const char*, size_t); void AutoDetectEncodingIfAllowed(const char* data, size_t len); - ContentType content_type_; + const TextResourceDecoderOptions options_; + WTF::TextEncoding encoding_; std::unique_ptr<TextCodec> codec_; EncodingSource source_; - const char* hint_encoding_; - const KURL hint_url_; Vector<char> buffer_; - char hint_language_[3]; bool checked_for_bom_; bool checked_for_css_charset_; bool checked_for_xml_charset_; bool checked_for_meta_charset_; - bool use_lenient_xml_decoding_; // Don't stop on XML decoding errors. bool saw_error_; - EncodingDetectionOption encoding_detection_option_; std::unique_ptr<HTMLMetaCharsetParser> charset_parser_; };
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoderForFuzzing.h b/third_party/WebKit/Source/core/html/parser/TextResourceDecoderForFuzzing.h index 5b3c0b8..28abd933 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoderForFuzzing.h +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoderForFuzzing.h
@@ -15,26 +15,44 @@ class TextResourceDecoderForFuzzing : public TextResourceDecoder { public: - // Note: Charsets can be long (see the various encodings in wtf/text). For - // instance: "unicode-1-1-utf-8". To ensure good coverage, set a generous max - // limit for these sizes (32 bytes should be good). TextResourceDecoderForFuzzing(FuzzedDataProvider& fuzzed_data) - : TextResourceDecoder(static_cast<TextResourceDecoder::ContentType>( - fuzzed_data.ConsumeInt32InRange( - TextResourceDecoder::kPlainTextContent, - TextResourceDecoder::kMaxContentType)), - WTF::TextEncoding(String::FromUTF8( - fuzzed_data.ConsumeBytesInRange(0, 32))), - FuzzedOption(fuzzed_data), - KURL()) {} + : TextResourceDecoder(FuzzedOption(fuzzed_data)) {} private: - static TextResourceDecoder::EncodingDetectionOption FuzzedOption( + static TextResourceDecoderOptions FuzzedOption( FuzzedDataProvider& fuzzed_data) { - // Don't use AlwaysUseUTF8ForText which requires knowing the mimeType - // ahead of time. - return fuzzed_data.ConsumeBool() ? kUseAllAutoDetection - : kUseContentAndBOMBasedDetection; + switch (static_cast<TextResourceDecoderOptions::EncodingDetectionOption>( + fuzzed_data.ConsumeInt32InRange( + TextResourceDecoderOptions::kUseAllAutoDetection, + TextResourceDecoderOptions::kAlwaysUseUTF8ForText))) { + case TextResourceDecoderOptions::kUseAllAutoDetection: + return TextResourceDecoderOptions::CreateWithAutoDetection( + FuzzedContentType(fuzzed_data), FuzzedEncoding(fuzzed_data), + WTF::TextEncoding(), KURL()); + + case TextResourceDecoderOptions::kUseContentAndBOMBasedDetection: + return TextResourceDecoderOptions(FuzzedContentType(fuzzed_data), + FuzzedEncoding(fuzzed_data)); + + case TextResourceDecoderOptions::kAlwaysUseUTF8ForText: + return TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText(); + } + } + + static TextResourceDecoderOptions::ContentType FuzzedContentType( + FuzzedDataProvider& fuzzed_data) { + return static_cast<TextResourceDecoderOptions::ContentType>( + fuzzed_data.ConsumeInt32InRange( + TextResourceDecoderOptions::kPlainTextContent, + TextResourceDecoderOptions::kMaxContentType)); + } + + static WTF::TextEncoding FuzzedEncoding(FuzzedDataProvider& fuzzed_data) { + // Note: Charsets can be long (see the various encodings in + // wtf/text). For instance: "unicode-1-1-utf-8". To ensure good coverage, + // set a generous max limit for these sizes (32 bytes should be good). + return WTF::TextEncoding( + String::FromUTF8(fuzzed_data.ConsumeBytesInRange(0, 32))); } };
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoderTest.cpp b/third_party/WebKit/Source/core/html/parser/TextResourceDecoderTest.cpp index 84f6e54..ec6c4feb 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoderTest.cpp +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoderTest.cpp
@@ -10,7 +10,8 @@ TEST(TextResourceDecoderTest, BasicUTF16) { std::unique_ptr<TextResourceDecoder> decoder = - TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent); + TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent)); WTF::String decoded; const unsigned char kFooLE[] = {0xff, 0xfe, 0x66, 0x00, @@ -20,7 +21,8 @@ decoded = decoded + decoder->Flush(); EXPECT_EQ("foo", decoded); - decoder = TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent); + decoder = TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent)); const unsigned char kFooBE[] = {0xfe, 0xff, 0x00, 0x66, 0x00, 0x6f, 0x00, 0x6f}; decoded = @@ -31,7 +33,8 @@ TEST(TextResourceDecoderTest, UTF16Pieces) { std::unique_ptr<TextResourceDecoder> decoder = - TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent); + TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent)); WTF::String decoded; const unsigned char kFoo[] = {0xff, 0xfe, 0x66, 0x00, 0x6f, 0x00, 0x6f, 0x00};
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp index 1a67319..693be2a 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
@@ -37,6 +37,7 @@ #include "core/html/track/vtt/VTTRegion.h" #include "core/html/track/vtt/VTTScanner.h" #include "platform/RuntimeEnabledFeatures.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/text/SegmentedString.h" #include "platform/wtf/text/CharacterNames.h" #include "platform/wtf/text/WTFString.h" @@ -82,9 +83,9 @@ VTTParser::VTTParser(VTTParserClient* client, Document& document) : document_(&document), state_(kInitial), - decoder_( - TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - UTF8Encoding())), + decoder_(TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + UTF8Encoding()))), current_start_time_(0), current_end_time_(0), client_(client) {}
diff --git a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp index 6c45055..98ae48a 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -63,6 +63,7 @@ #include "platform/loader/fetch/MemoryCache.h" #include "platform/loader/fetch/Resource.h" #include "platform/loader/fetch/ResourceFetcher.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/network/mime/MIMETypeRegistry.h" #include "platform/weborigin/SecurityOrigin.h" #include "platform/wtf/CurrentTime.h" @@ -143,27 +144,28 @@ const String& mime_type, const String& text_encoding_name) { if (!text_encoding_name.IsEmpty()) { - return TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - WTF::TextEncoding(text_encoding_name)); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + WTF::TextEncoding(text_encoding_name))); } if (DOMImplementation::IsXMLMIMEType(mime_type)) { - std::unique_ptr<TextResourceDecoder> decoder = - TextResourceDecoder::Create(TextResourceDecoder::kXMLContent); - decoder->UseLenientXMLDecoding(); - return decoder; + TextResourceDecoderOptions options(TextResourceDecoderOptions::kXMLContent); + options.SetUseLenientXMLDecoding(); + return TextResourceDecoder::Create(options); } if (DeprecatedEqualIgnoringCase(mime_type, "text/html")) { - return TextResourceDecoder::Create(TextResourceDecoder::kHTMLContent, - UTF8Encoding()); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kHTMLContent, UTF8Encoding())); } if (MIMETypeRegistry::IsSupportedJavaScriptMIMEType(mime_type) || DOMImplementation::IsJSONMIMEType(mime_type)) { - return TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - UTF8Encoding()); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, UTF8Encoding())); } if (DOMImplementation::IsTextMIMEType(mime_type)) { - return TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - WTF::TextEncoding("ISO-8859-1")); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + WTF::TextEncoding("ISO-8859-1"))); } return std::unique_ptr<TextResourceDecoder>(); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp index 2842f43..025753a 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp
@@ -125,8 +125,7 @@ if (!resource_request.Url().GetString().IsEmpty()) { urls_to_fetch.insert(resource_request.Url().GetString()); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::internal; FetchParameters params(resource_request, options); Resource* resource = RawResource::Fetch(params, document->Fetcher()); @@ -151,8 +150,7 @@ ResourceRequest resource_request(url); resource_request.SetRequestContext( WebURLRequest::kRequestContextInternal); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::internal; FetchParameters params(resource_request, options); Resource* resource =
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc index 5a5b989..4a35415f1 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc
@@ -52,8 +52,11 @@ for (auto& box : stack_) { box.fragment_start = 0; box.metrics = NGLineHeightMetrics(); - // Existing box states are wrapped boxes, and hence no left edges. - box.border_edges.line_left = false; + if (box.needs_box_fragment) { + box.line_left_position = LayoutUnit(); + // Existing box states are wrapped boxes, and hence no left edges. + box.border_edges.line_left = false; + } DCHECK(box.pending_descendants.IsEmpty()); } } @@ -72,12 +75,20 @@ NGInlineBoxState* NGInlineLayoutStateStack::OnOpenTag( const NGInlineItem& item, - NGLineBoxFragmentBuilder* line_box) { + const NGInlineItemResult& item_result, + NGLineBoxFragmentBuilder* line_box, + LayoutUnit position) { stack_.resize(stack_.size() + 1); NGInlineBoxState* box = &stack_.back(); box->fragment_start = line_box->Children().size(); box->item = &item; box->style = item.Style(); + + // Compute box properties regardless of needs_box_fragment since close tag may + // also set needs_box_fragment. + box->line_left_position = position + item_result.margins.inline_start; + box->borders_paddings_block_start = item_result.borders_paddings_block_start; + box->borders_paddings_block_end = item_result.borders_paddings_block_end; return box; } @@ -126,20 +137,17 @@ } } -void NGInlineBoxState::SetNeedsBoxFragment( - const NGInlineItem& item, - const NGInlineItemResult& item_result, - LayoutUnit position) { - needs_box_fragment = true; - line_left_position = position + item_result.margins.inline_start; - borders_paddings_block_start = item_result.borders_paddings_block_start; - borders_paddings_block_end = item_result.borders_paddings_block_end; - // We have left edge on open tag, and if the box is not a continuation. - // TODO(kojii): Needs review when we change SplitInlines(). - bool has_line_left_edge = item.Style()->IsLeftToRightDirection() - ? item.HasStartEdge() - : item.HasEndEdge(); - border_edges = {true, false, true, has_line_left_edge}; +void NGInlineBoxState::SetNeedsBoxFragment(bool when_empty) { + needs_box_fragment_when_empty = when_empty; + if (!needs_box_fragment) { + needs_box_fragment = true; + // We have left edge on open tag, and if the box is not a continuation. + // TODO(kojii): Needs review when we change SplitInlines(). + bool has_line_left_edge = item->Style()->IsLeftToRightDirection() + ? item->HasStartEdge() + : item->HasEndEdge(); + border_edges = {true, false, true, has_line_left_edge}; + } } void NGInlineBoxState::SetLineRightForBoxFragment( @@ -164,8 +172,10 @@ NGInlineBoxState* box, NGLineBoxFragmentBuilder* line_box, FontBaseline baseline_type) { + DCHECK(box->needs_box_fragment); LayoutUnit inline_size = box->line_right_position - box->line_left_position; - if (box->fragment_start == line_box->Children().size() && inline_size <= 0) { + if (box->fragment_start == line_box->Children().size() && + !box->needs_box_fragment_when_empty) { // Don't create a box if the inline box is "empty". // Inline boxes with inline margins/borders/paddings are not "empty", // but background doesn't make difference in this context.
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h index 4e24390..cbc48e7 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h
@@ -51,6 +51,7 @@ Vector<NGPendingPositions> pending_descendants; bool include_used_fonts = false; bool needs_box_fragment = false; + bool needs_box_fragment_when_empty = false; // Compute text metrics for a box. All text in a box share the same metrics. void ComputeTextMetrics(const ComputedStyle& style, FontBaseline); @@ -60,9 +61,7 @@ FontBaseline); // Create a box fragment for this box. - void SetNeedsBoxFragment(const NGInlineItem&, - const NGInlineItemResult&, - LayoutUnit position); + void SetNeedsBoxFragment(bool when_empty); void SetLineRightForBoxFragment(const NGInlineItem&, const NGInlineItemResult&, LayoutUnit position); @@ -82,7 +81,10 @@ NGInlineBoxState* OnBeginPlaceItems(const ComputedStyle*, FontBaseline); // Push a box state stack. - NGInlineBoxState* OnOpenTag(const NGInlineItem&, NGLineBoxFragmentBuilder*); + NGInlineBoxState* OnOpenTag(const NGInlineItem&, + const NGInlineItemResult&, + NGLineBoxFragmentBuilder*, + LayoutUnit position); // Pop a box state stack. NGInlineBoxState* OnCloseTag(const NGInlineItem&,
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.cc index 60c5bfb..d0200c3 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.cc
@@ -31,4 +31,12 @@ line_style_ = layout_object->Style(); } +void NGLineInfo::SetLineLocation(LayoutUnit line_left, + LayoutUnit available_width, + LayoutUnit line_top) { + line_left_ = line_left; + available_width_ = available_width; + line_top_ = line_top; +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.h index ea695dd8..66cbaae 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_item_result.h
@@ -48,6 +48,9 @@ LayoutUnit borders_paddings_block_start; LayoutUnit borders_paddings_block_end; + // Create a box when the box is empty, for open/close tags. + unsigned needs_box_when_empty : 1; + // Inside of this is not breakable. // Used only during line breaking. unsigned no_break_opportunities_inside : 1; @@ -95,9 +98,19 @@ NGInlineItemResults& Results() { return results_; } const NGInlineItemResults& Results() const { return results_; } + LayoutUnit LineLeft() const { return line_left_; } + LayoutUnit AvailableWidth() const { return available_width_; } + LayoutUnit LineTop() const { return line_top_; } + void SetLineLocation(LayoutUnit line_left, + LayoutUnit available_width, + LayoutUnit line_top); + private: const ComputedStyle* line_style_ = nullptr; NGInlineItemResults results_; + LayoutUnit line_left_; + LayoutUnit available_width_; + LayoutUnit line_top_; bool is_first_line_ = false; bool is_last_line_ = false; };
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc index 1b1bbfa3..fedf935 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.cc
@@ -30,6 +30,14 @@ namespace blink { namespace { +inline bool ShouldCreateBoxFragment(const NGInlineItem& item, + const NGInlineItemResult& item_result) { + DCHECK(item.Style()); + const ComputedStyle& style = *item.Style(); + // TODO(kojii): We might need more conditions to create box fragments. + return style.HasBoxDecorationBackground() || item_result.needs_box_when_empty; +} + NGLogicalOffset GetOriginPointForFloats( const NGLogicalOffset& container_bfc_offset, LayoutUnit content_size) { @@ -57,16 +65,6 @@ ComputePadding(ConstraintSpace(), Style()); } -// The offset of 'line-left' side. -// https://drafts.csswg.org/css-writing-modes/#line-left -LayoutUnit NGInlineLayoutAlgorithm::LogicalLeftOffset( - const NGLayoutOpportunity& opportunity) const { - // TODO(kojii): We need to convert 'line start' to 'line left'. They're - // different in RTL. Maybe there are more where start and left are misused. - return opportunity.InlineStartOffset() - - ConstraintSpace().BfcOffset().inline_offset; -} - bool NGInlineLayoutAlgorithm::CreateLine( NGLineInfo* line_info, RefPtr<NGInlineBreakToken> break_token) { @@ -176,19 +174,21 @@ item_result.end_offset); line_box.AddChild(std::move(text_fragment), {position, box->text_top}); } else if (item.Type() == NGInlineItem::kOpenTag) { - box = box_states_.OnOpenTag(item, &line_box); + box = box_states_.OnOpenTag(item, item_result, &line_box, position); // Compute text metrics for all inline boxes since even empty inlines // influence the line height. // https://drafts.csswg.org/css2/visudet.html#line-height box->ComputeTextMetrics(*item.Style(), baseline_type_); text_builder.SetDirection(box->style->Direction()); - // TODO(kojii): We may need more conditions to create box fragments. - if (item.Style()->HasBoxDecorationBackground()) - box->SetNeedsBoxFragment(item, item_result, position); + if (ShouldCreateBoxFragment(item, item_result)) + box->SetNeedsBoxFragment(item_result.needs_box_when_empty); } else if (item.Type() == NGInlineItem::kCloseTag) { position += item_result.inline_size; - if (box->needs_box_fragment) + if (box->needs_box_fragment || item_result.needs_box_when_empty) { + if (item_result.needs_box_when_empty) + box->SetNeedsBoxFragment(true); box->SetLineRightForBoxFragment(item, item_result, position); + } box = box_states_.OnCloseTag(item, &line_box, box, baseline_type_); continue; } else if (item.Type() == NGInlineItem::kAtomicInline) { @@ -217,11 +217,15 @@ return true; // The line was empty. } + // NGLineBreaker should have determined we need a line box, and that has + // resolved the BFC offset. + DCHECK(container_builder_.BfcOffset().has_value()); + box_states_.OnEndPlaceItems(&line_box, baseline_type_, position); // The baselines are always placed at pixel boundaries. Not doing so results // in incorrect layout of text decorations, most notably underlines. - LayoutUnit baseline = content_size_ + line_box.Metrics().ascent; + LayoutUnit baseline = line_info->LineTop() + line_box.Metrics().ascent; baseline = LayoutUnit(baseline.Round()); // Check if the line fits into the constraint space in block direction. @@ -243,13 +247,12 @@ // the line box to the line top. line_box.MoveChildrenInBlockDirection(baseline); - NGLayoutOpportunity line_opp = FindLayoutOpportunityForLine(); - LayoutUnit inline_size = position; - NGLogicalOffset offset(LogicalLeftOffset(line_opp), + NGLogicalOffset offset(line_info->LineLeft(), baseline - box_states_.LineBoxState().metrics.ascent); ApplyTextAlign(line_style.GetTextAlign(line_info->IsLastLine()), - &offset.inline_offset, inline_size, line_opp.InlineSize()); + &offset.inline_offset, inline_size, + line_info->AvailableWidth()); line_box.SetInlineSize(inline_size); container_builder_.AddChild(line_box.ToLineBoxFragment(), offset); @@ -271,7 +274,8 @@ NGTextFragmentBuilder* text_builder) { DCHECK(item_result->layout_result); - NGInlineBoxState* box = box_states_.OnOpenTag(item, line_box); + NGInlineBoxState* box = + box_states_.OnOpenTag(item, *item_result, line_box, position); // For replaced elements, inline-block elements, and inline-table elements, // the height is the height of their margin box. @@ -392,25 +396,6 @@ return content_size; } -NGLayoutOpportunity NGInlineLayoutAlgorithm::FindLayoutOpportunityForLine() { - // TODO(ikilpatrick): Using the constraint space BFC offset here seems wrong. - // Logically we shouldn't hit this codepath when placing the items as we - // shouldn't have anything to place. - // - // Consider reworking PlaceItems to make sure this doesn't occur. - NGLogicalOffset iter_offset = ConstraintSpace().BfcOffset(); - if (container_builder_.BfcOffset()) { - iter_offset = ContainerBfcOffset(); - iter_offset += {border_and_padding_.inline_start, LayoutUnit()}; - } - iter_offset.block_offset += content_size_; - - return NGLayoutOpportunityIterator(ConstraintSpace().Exclusions().get(), - ConstraintSpace().AvailableSize(), - iter_offset) - .Next(); -} - RefPtr<NGLayoutResult> NGInlineLayoutAlgorithm::Layout() { // If we are resuming from a break token our start border and padding is // within a previous fragment.
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h index fb49785..805f944 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_layout_algorithm.h
@@ -50,8 +50,6 @@ private: bool IsHorizontalWritingMode() const { return is_horizontal_writing_mode_; } - LayoutUnit LogicalLeftOffset(const NGLayoutOpportunity&) const; - void BidiReorder(NGInlineItemResults*); bool PlaceItems(NGLineInfo*, RefPtr<NGInlineBreakToken>); @@ -69,8 +67,6 @@ LayoutUnit ComputeContentSize(const NGLineInfo&, LayoutUnit line_bottom); - NGLayoutOpportunity FindLayoutOpportunityForLine(); - NGInlineLayoutStateStack box_states_; LayoutUnit content_size_; LayoutUnit max_inline_size_;
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc index 57e63b8c..3d174486 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.cc
@@ -77,7 +77,8 @@ bool NGLineBreaker::NextLine(NGLineInfo* line_info, const NGLogicalOffset& content_offset) { - BreakLine(line_info, content_offset); + content_offset_ = content_offset; + BreakLine(line_info); // TODO(kojii): When editing, or caret is enabled, trailing spaces at wrap // point should not be removed. For other cases, we can a) remove, b) leave @@ -85,24 +86,33 @@ // measuring. Need to decide which one works the best. SkipCollapsibleWhitespaces(); - return !line_info->Results().IsEmpty(); + if (line_info->Results().IsEmpty()) + return false; + + // TODO(kojii): There are cases where we need to PlaceItems() without creating + // line boxes. These cases need to be reviewed. + if (should_create_line_box_) + ComputeLineLocation(line_info); + + return true; } -void NGLineBreaker::BreakLine(NGLineInfo* line_info, - const NGLogicalOffset& content_offset) { +void NGLineBreaker::BreakLine(NGLineInfo* line_info) { NGInlineItemResults* item_results = &line_info->Results(); item_results->clear(); const Vector<NGInlineItem>& items = node_.Items(); line_info->SetLineStyle(node_, !item_index_ && !offset_); SetCurrentStyle(line_info->LineStyle()); position_ = LayoutUnit(0); + should_create_line_box_ = false; LineBreakState state = LineBreakState::kNotBreakable; // We are only able to calculate our available_width if our container has // been positioned in the BFC coordinate space yet. - WTF::Optional<LayoutUnit> available_width; if (container_builder_->BfcOffset()) - available_width = ComputeAvailableWidth(content_offset); + UpdateAvailableWidth(); + else + opportunity_.reset(); while (item_index_ < items.size()) { // CloseTag prohibits to break before. @@ -118,32 +128,15 @@ line_info->SetIsLastLine(false); return; } - if (state == LineBreakState::kIsBreakable && available_width && - position_ > available_width.value()) - return HandleOverflow(available_width.value(), line_info); - - // We resolve the BFC-offset of the container if this line has an item with - // inline-size. Floats, and tags do not allow us to resolve the BFC-offset. - // - // If this line just has a float we place it in the unpositioned float list - // which will be positioned later. - bool should_resolve_bfc_offset = - !container_builder_->BfcOffset() && - (item.Type() == NGInlineItem::kText || - item.Type() == NGInlineItem::kAtomicInline || - item.Type() == NGInlineItem::kControl); - - if (should_resolve_bfc_offset) { - ResolveBFCOffset(); - available_width = ComputeAvailableWidth(content_offset); - } + if (state == LineBreakState::kIsBreakable && HasAvailableWidth() && + position_ > AvailableWidth()) + return HandleOverflow(line_info); item_results->push_back( NGInlineItemResult(item_index_, offset_, item.EndOffset())); NGInlineItemResult* item_result = &item_results->back(); if (item.Type() == NGInlineItem::kText) { - DCHECK(available_width); - state = HandleText(item, available_width.value(), item_result); + state = HandleText(item, item_result); } else if (item.Type() == NGInlineItem::kAtomicInline) { state = HandleAtomicInline(item, item_result); } else if (item.Type() == NGInlineItem::kControl) { @@ -156,47 +149,47 @@ HandleOpenTag(item, item_result); state = LineBreakState::kNotBreakable; } else if (item.Type() == NGInlineItem::kFloating) { - HandleFloat(item, content_offset, &available_width, item_results); + HandleFloat(item, item_results); } else { MoveToNextOf(item); } } - if (state == LineBreakState::kIsBreakable && available_width && - position_ > available_width.value()) - return HandleOverflow(available_width.value(), line_info); + if (state == LineBreakState::kIsBreakable && HasAvailableWidth() && + position_ > AvailableWidth()) + return HandleOverflow(line_info); line_info->SetIsLastLine(true); } -// Resolves the BFC offset for the container, and positions any pending floats. -void NGLineBreaker::ResolveBFCOffset() { - LayoutUnit container_bfc_block_offset = - constraint_space_->BfcOffset().block_offset + - constraint_space_->MarginStrut().Sum(); - MaybeUpdateFragmentBfcOffset(*constraint_space_, container_bfc_block_offset, - container_builder_); - PositionPendingFloats(container_bfc_block_offset, container_builder_, - constraint_space_); -} - -// Returns the inline size of the first layout opportunity from the given +// Update the inline size of the first layout opportunity from the given // content_offset. -LayoutUnit NGLineBreaker::ComputeAvailableWidth( - const NGLogicalOffset& content_offset) const { +void NGLineBreaker::UpdateAvailableWidth() { NGLogicalOffset offset = container_builder_->BfcOffset().value(); - offset += content_offset; + offset += content_offset_; NGLayoutOpportunityIterator iter(constraint_space_->Exclusions().get(), constraint_space_->AvailableSize(), offset); - NGLayoutOpportunity opportunity = iter.Next(); - return opportunity.InlineSize(); -}; + opportunity_ = iter.Next(); +} + +void NGLineBreaker::ComputeLineLocation(NGLineInfo* line_info) const { + // Both NGLayoutOpportunity and BfcOffset are in visual order that + // "inline-start" are actually "line-left". + // https://drafts.csswg.org/css-writing-modes-3/#line-left + LayoutUnit line_left = opportunity_.value().InlineStartOffset() - + constraint_space_->BfcOffset().inline_offset; + line_info->SetLineLocation(line_left, AvailableWidth(), + content_offset_.block_offset); +} NGLineBreaker::LineBreakState NGLineBreaker::HandleText( const NGInlineItem& item, - LayoutUnit available_width, NGInlineItemResult* item_result) { DCHECK_EQ(item.Type(), NGInlineItem::kText); + if (!should_create_line_box_) + SetShouldCreateLineBox(); + LayoutUnit available_width = AvailableWidth(); + // If the start offset is at the item boundary, try to add the entire item. if (offset_ == item.StartOffset()) { item_result->inline_size = item.InlineSize(); @@ -289,6 +282,10 @@ const NGInlineItem& item, NGInlineItemResult* item_result) { DCHECK_EQ(item.Length(), 1u); + + if (!should_create_line_box_) + SetShouldCreateLineBox(); + UChar character = node_.Text()[item.StartOffset()]; if (character == kNewlineCharacter) { MoveToNextOf(item); @@ -309,6 +306,10 @@ const NGInlineItem& item, NGInlineItemResult* item_result) { DCHECK_EQ(item.Type(), NGInlineItem::kAtomicInline); + + if (!should_create_line_box_) + SetShouldCreateLineBox(); + NGBlockNode node = NGBlockNode(ToLayoutBox(item.GetLayoutObject())); const ComputedStyle& style = node.Style(); NGConstraintSpaceBuilder constraint_space_builder(constraint_space_); @@ -355,8 +356,6 @@ // // TODO(glebl): Add the support of clearance for inline floats. void NGLineBreaker::HandleFloat(const NGInlineItem& item, - const NGLogicalOffset& content_offset, - WTF::Optional<LayoutUnit>* available_width, NGInlineItemResults* item_results) { NGBlockNode node(ToLayoutBox(item.GetLayoutObject())); @@ -380,8 +379,8 @@ // I.e. we may not have come across any text yet, in order to be able to // resolve the BFC position. bool float_does_not_fit = - !available_width->has_value() || - position_ + inline_size + margins.InlineSum() > available_width->value(); + !HasAvailableWidth() || + position_ + inline_size + margins.InlineSum() > AvailableWidth(); // Check if we already have a pending float. That's because a float cannot be // higher than any block or floated box generated before. @@ -391,7 +390,7 @@ } else { NGLogicalOffset container_bfc_offset = container_builder_->BfcOffset().value(); - unpositioned_float->origin_offset = container_bfc_offset + content_offset; + unpositioned_float->origin_offset = container_bfc_offset + content_offset_; unpositioned_float->from_offset.block_offset = container_bfc_offset.block_offset; unpositioned_float->parent_bfc_block_offset = @@ -402,7 +401,7 @@ // We need to recalculate the available_width as the float probably // consumed space on the line. - *available_width = ComputeAvailableWidth(content_offset); + UpdateAvailableWidth(); } // Floats are already positioned in the container_builder. @@ -414,6 +413,7 @@ NGInlineItemResult* item_result) { DCHECK(item.Style()); const ComputedStyle& style = *item.Style(); + item_result->needs_box_when_empty = false; if (style.HasBorder() || style.HasPadding() || (style.HasMargin() && item.HasStartEdge())) { NGBoxStrut borders = ComputeBorders(*constraint_space_, style); @@ -429,6 +429,11 @@ item_result->inline_size = item_result->margins.inline_start + borders.inline_start + paddings.inline_start; position_ += item_result->inline_size; + + item_result->needs_box_when_empty = + item_result->inline_size || item_result->margins.inline_start; + if (item_result->needs_box_when_empty && !should_create_line_box_) + SetShouldCreateLineBox(); } } SetCurrentStyle(style); @@ -437,16 +442,23 @@ void NGLineBreaker::HandleCloseTag(const NGInlineItem& item, NGInlineItemResult* item_result) { + item_result->needs_box_when_empty = false; if (item.HasEndEdge()) { DCHECK(item.Style()); - item_result->margins = ComputeMargins(*constraint_space_, *item.Style(), + const ComputedStyle& style = *item.Style(); + item_result->margins = ComputeMargins(*constraint_space_, style, constraint_space_->WritingMode(), constraint_space_->Direction()); - NGBoxStrut borders = ComputeBorders(*constraint_space_, *item.Style()); - NGBoxStrut paddings = ComputePadding(*constraint_space_, *item.Style()); + NGBoxStrut borders = ComputeBorders(*constraint_space_, style); + NGBoxStrut paddings = ComputePadding(*constraint_space_, style); item_result->inline_size = item_result->margins.inline_end + borders.inline_end + paddings.inline_end; position_ += item_result->inline_size; + + item_result->needs_box_when_empty = + item_result->inline_size || item_result->margins.inline_end; + if (item_result->needs_box_when_empty && !should_create_line_box_) + SetShouldCreateLineBox(); } DCHECK(item.GetLayoutObject() && item.GetLayoutObject()->Parent()); SetCurrentStyle(item.GetLayoutObject()->Parent()->StyleRef()); @@ -456,10 +468,10 @@ // Handles when the last item overflows. // At this point, item_results does not fit into the current line, and there // are no break opportunities in item_results.back(). -void NGLineBreaker::HandleOverflow(LayoutUnit available_width, - NGLineInfo* line_info) { +void NGLineBreaker::HandleOverflow(NGLineInfo* line_info) { NGInlineItemResults* item_results = &line_info->Results(); const Vector<NGInlineItem>& items = node_.Items(); + LayoutUnit available_width = AvailableWidth(); LayoutUnit rewind_width = available_width - position_; DCHECK_LT(rewind_width, 0); @@ -537,6 +549,28 @@ line_info->SetIsLastLine(false); } +void NGLineBreaker::SetShouldCreateLineBox() { + DCHECK(!should_create_line_box_); + should_create_line_box_ = true; + + // We resolve the BFC-offset of the container if this line has a line box. + // A line box prevents collapsing margins between boxes before and after, + // but not all lines create line boxes. + // + // If this line just has a float we place it in the unpositioned float list + // which will be positioned later. + if (!container_builder_->BfcOffset()) { + LayoutUnit container_bfc_block_offset = + constraint_space_->BfcOffset().block_offset + + constraint_space_->MarginStrut().Sum(); + MaybeUpdateFragmentBfcOffset(*constraint_space_, container_bfc_block_offset, + container_builder_); + PositionPendingFloats(container_bfc_block_offset, container_builder_, + constraint_space_); + UpdateAvailableWidth(); + } +} + void NGLineBreaker::SetCurrentStyle(const ComputedStyle& style) { auto_wrap_ = style.AutoWrap();
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h index 16cb269..bc694d69 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_line_breaker.h
@@ -8,6 +8,7 @@ #include "core/CoreExport.h" #include "core/layout/ng/inline/ng_inline_item_result.h" #include "core/layout/ng/inline/ng_inline_node.h" +#include "core/layout/ng/ng_layout_opportunity_iterator.h" #include "platform/fonts/shaping/HarfBuzzShaper.h" #include "platform/fonts/shaping/ShapeResultSpacing.h" #include "platform/heap/Handle.h" @@ -43,10 +44,14 @@ RefPtr<NGInlineBreakToken> CreateBreakToken() const; private: - void BreakLine(NGLineInfo*, const NGLogicalOffset&); + void BreakLine(NGLineInfo*); - void ResolveBFCOffset(); - LayoutUnit ComputeAvailableWidth(const NGLogicalOffset&) const; + bool HasAvailableWidth() const { return opportunity_.has_value(); } + LayoutUnit AvailableWidth() const { + return opportunity_.value().InlineSize(); + } + void UpdateAvailableWidth(); + void ComputeLineLocation(NGLineInfo*) const; enum class LineBreakState { // The current position is not breakable. @@ -60,7 +65,6 @@ }; LineBreakState HandleText(const NGInlineItem&, - LayoutUnit available_width, NGInlineItemResult*); void BreakText(NGInlineItemResult*, const NGInlineItem&, @@ -69,16 +73,16 @@ LineBreakState HandleControlItem(const NGInlineItem&, NGInlineItemResult*); LineBreakState HandleAtomicInline(const NGInlineItem&, NGInlineItemResult*); void HandleFloat(const NGInlineItem&, - const NGLogicalOffset&, - WTF::Optional<LayoutUnit>* available_width, NGInlineItemResults*); void HandleOpenTag(const NGInlineItem&, NGInlineItemResult*); void HandleCloseTag(const NGInlineItem&, NGInlineItemResult*); - void HandleOverflow(LayoutUnit available_width, NGLineInfo*); + void HandleOverflow(NGLineInfo*); void Rewind(NGLineInfo*, unsigned new_end); + void SetShouldCreateLineBox(); + void SetCurrentStyle(const ComputedStyle&); void MoveToNextOf(const NGInlineItem&); @@ -92,11 +96,14 @@ unsigned item_index_; unsigned offset_; LayoutUnit position_; + WTF::Optional<NGLayoutOpportunity> opportunity_; + NGLogicalOffset content_offset_; LazyLineBreakIterator break_iterator_; HarfBuzzShaper shaper_; ShapeResultSpacing<String> spacing_; unsigned auto_wrap_ : 1; + unsigned should_create_line_box_ : 1; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp index acef7b34..feb1aaa 100644 --- a/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp
@@ -257,11 +257,15 @@ policy->DidReceiveHeader("script-src https://bar.test", kContentSecurityPolicyHeaderTypeReport, kContentSecurityPolicyHeaderSourceHTTP); + KURL url(KURL(), "http://baz.test"); ResourceRequest resource_request(url); resource_request.SetRequestContext(WebURLRequest::kRequestContextScript); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); + + ResourceLoaderOptions options; + EXPECT_EQ(ResourceRequestBlockedReason::CSP, fetch_context_->CanFollowRedirect( Resource::kScript, resource_request, url, options, @@ -280,11 +284,15 @@ policy->DidReceiveHeader("script-src https://bar.test", kContentSecurityPolicyHeaderTypeReport, kContentSecurityPolicyHeaderSourceHTTP); + KURL url(KURL(), "http://baz.test"); ResourceRequest resource_request(url); resource_request.SetRequestContext(WebURLRequest::kRequestContextScript); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); + + ResourceLoaderOptions options; + EXPECT_EQ(ResourceRequestBlockedReason::CSP, fetch_context_->AllowResponse(Resource::kScript, resource_request, url, options));
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index bfeb81c..0287ed2 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -865,8 +865,7 @@ GetTiming().MarkFetchStart(); } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.data_buffering_policy = kDoNotBufferData; options.initiator_info.name = FetchInitiatorTypeNames::document; FetchParameters fetch_params(request_, options);
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 9c5f341..0c16946b 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -167,13 +167,12 @@ loading_context_(&loading_context), options_(options), resource_loader_options_(resource_loader_options), - force_do_not_allow_stored_credentials_(false), + cors_flag_(false), + suborigin_force_credentials_(false), security_origin_(resource_loader_options_.security_origin), - same_origin_request_(false), is_using_data_consumer_handle_(false), async_(blocking_behavior == kLoadAsynchronously), request_context_(WebURLRequest::kRequestContextUnspecified), - actual_options_(kAllowStoredCredentials, kClientRequestedCredentials), timeout_timer_(loading_context_->GetTaskRunner(TaskType::kNetworking), this, &DocumentThreadableLoader::DidTimeout), @@ -200,13 +199,25 @@ // Setting an outgoing referer is only supported in the async code path. DCHECK(async_ || request.HttpReferrer().IsEmpty()); - same_origin_request_ = - GetSecurityOrigin()->CanRequestNoSuborigin(request.Url()); + if (options_.fetch_request_mode != WebURLRequest::kFetchRequestModeNoCORS) + cors_flag_ = !GetSecurityOrigin()->CanRequestNoSuborigin(request.Url()); + request_context_ = request.GetRequestContext(); redirect_mode_ = request.GetFetchRedirectMode(); - if (!same_origin_request_ && options_.fetch_request_mode == - WebURLRequest::kFetchRequestModeSameOrigin) { + // Per https://w3c.github.io/webappsec-suborigins/#security-model-opt-outs, + // credentials are forced when credentials mode is "same-origin", the + // 'unsafe-credentials' option is set, and the request's physical origin is + // the same as the URL's. + + suborigin_force_credentials_ = + GetSecurityOrigin()->HasSuboriginAndShouldAllowCredentialsFor( + request.Url()); + + // The CORS flag variable is not yet used at the step in the spec that + // corresponds to this line, but divert |cors_flag_| here for convenience. + if (cors_flag_ && options_.fetch_request_mode == + WebURLRequest::kFetchRequestModeSameOrigin) { probe::documentThreadableLoaderFailedToStartLoadingForClient(GetDocument(), client_); ThreadableLoaderClient* client = client_; @@ -245,10 +256,9 @@ ResourceRequest new_request(request); if (request_context_ != WebURLRequest::kRequestContextFetch) { // When the request context is not "fetch", |fetch_request_mode| - // represents the fetch request mode, and |allow_credentials| represents - // the fetch credentials mode. So we set those flags here so that we can see - // the correct request mode and credentials mode in the service worker's - // fetch event handler. + // represents the fetch request mode. So we set that flag here so that we + // can see the correct request mode in the service worker's fetch event + // handler. switch (options_.fetch_request_mode) { case WebURLRequest::kFetchRequestModeSameOrigin: case WebURLRequest::kFetchRequestModeCORS: @@ -263,13 +273,6 @@ break; } new_request.SetFetchRequestMode(options_.fetch_request_mode); - if (resource_loader_options_.allow_credentials == kAllowStoredCredentials) { - new_request.SetFetchCredentialsMode( - WebURLRequest::kFetchCredentialsModeInclude); - } else { - new_request.SetFetchCredentialsMode( - WebURLRequest::kFetchCredentialsModeSameOrigin); - } } // We assume that ServiceWorker is skipped for sync requests and unsupported @@ -303,10 +306,8 @@ } void DocumentThreadableLoader::DispatchInitialRequest( - const ResourceRequest& request) { - if (!request.IsExternalRequest() && - (same_origin_request_ || - options_.fetch_request_mode == WebURLRequest::kFetchRequestModeNoCORS)) { + ResourceRequest& request) { + if (!request.IsExternalRequest() && !cors_flag_) { LoadRequest(request, resource_loader_options_); return; } @@ -367,17 +368,6 @@ cross_origin_request.RemoveUserAndPassFromURL(); - cross_origin_request.SetAllowStoredCredentials(EffectiveAllowCredentials() == - kAllowStoredCredentials); - - // We update the credentials mode according to effectiveAllowCredentials() - // here for backward compatibility. But this is not correct. - // FIXME: We should set it in the caller of DocumentThreadableLoader. - cross_origin_request.SetFetchCredentialsMode( - EffectiveAllowCredentials() == kAllowStoredCredentials - ? WebURLRequest::kFetchCredentialsModeInclude - : WebURLRequest::kFetchCredentialsModeOmit); - bool skip_preflight = false; if (options_.preflight_policy == kPreventPreflight) { skip_preflight = true; @@ -423,7 +413,8 @@ IsMainThread() && CrossOriginPreflightResultCache::Shared().CanSkipPreflight( GetSecurityOrigin()->ToString(), cross_origin_request.Url(), - EffectiveAllowCredentials(), cross_origin_request.HttpMethod(), + cross_origin_request.GetFetchCredentialsMode(), + cross_origin_request.HttpMethod(), cross_origin_request.HttpHeaderFields()); if (can_skip_preflight && !should_force_preflight) { PrepareCrossOriginRequest(cross_origin_request); @@ -440,7 +431,6 @@ // Create a ResourceLoaderOptions for preflight. ResourceLoaderOptions preflight_options = cross_origin_options; - preflight_options.allow_credentials = kDoNotAllowStoredCredentials; actual_request_ = cross_origin_request; actual_options_ = cross_origin_options; @@ -523,6 +513,8 @@ DCHECK_EQ(resource, this->GetResource()); DCHECK(async_); + suborigin_force_credentials_ = false; + checker_.RedirectReceived(); if (!actual_request_.IsNull()) { @@ -605,12 +597,12 @@ CrossOriginAccessControl::RedirectErrorString(builder, redirect_status, request.Url()); access_control_error_description = builder.ToString(); - } else if (!same_origin_request_) { - // The redirect response must pass the access control check if the original - // request was not same-origin. + } else if (cors_flag_) { + // The redirect response must pass the access control check if the CORS + // flag is set. CrossOriginAccessControl::AccessStatus cors_status = CrossOriginAccessControl::CheckAccess(redirect_response, - EffectiveAllowCredentials(), + request.GetFetchCredentialsMode(), GetSecurityOrigin()); allow_redirect = cors_status == CrossOriginAccessControl::kAccessAllowed; if (!allow_redirect) { @@ -640,11 +632,14 @@ // CrossOriginAccessControl::handleRedirect(). ClearResource(); - // If the original request wasn't same-origin, then if the request URL origin - // is not same origin with the original URL origin, set the source origin to a - // globally unique identifier. (If the original request was same-origin, the - // origin of the new request should be the original URL origin.) - if (!same_origin_request_) { + // If + // - CORS flag is set, and + // - the origin of the redirect target URL is not same origin with the origin + // of the current request's URL + // set the source origin to a unique opaque origin. + // + // See https://fetch.spec.whatwg.org/#http-redirect-fetch. + if (cors_flag_) { RefPtr<SecurityOrigin> original_origin = SecurityOrigin::Create(redirect_response.Url()); RefPtr<SecurityOrigin> request_origin = @@ -652,15 +647,11 @@ if (!original_origin->IsSameSchemeHostPort(request_origin.Get())) security_origin_ = SecurityOrigin::CreateUnique(); } - // Force any subsequent requests to use these checks. - same_origin_request_ = false; - // Since the request is no longer same-origin, if the user didn't request - // credentials in the first place, update our state so we neither request them - // nor expect they must be allowed. - if (resource_loader_options_.credentials_requested == - kClientDidNotRequestCredentials) - force_do_not_allow_stored_credentials_ = true; + // Set |cors_flag_| so that further logic (corresponds to the main fetch in + // the spec) will be performed with CORS flag set. + // See https://fetch.spec.whatwg.org/#http-redirect-fetch. + cors_flag_ = true; // Save the referrer to use when following the redirect. override_referrer_ = true; @@ -738,7 +729,9 @@ if (handle) is_using_data_consumer_handle_ = true; - HandleResponse(resource->Identifier(), response, std::move(handle)); + HandleResponse(resource->Identifier(), + resource->GetResourceRequest().GetFetchCredentialsMode(), + response, std::move(handle)); } void DocumentThreadableLoader::HandlePreflightResponse( @@ -747,7 +740,8 @@ CrossOriginAccessControl::AccessStatus cors_status = CrossOriginAccessControl::CheckAccess( - response, EffectiveAllowCredentials(), GetSecurityOrigin()); + response, actual_request_.GetFetchCredentialsMode(), + GetSecurityOrigin()); if (cors_status != CrossOriginAccessControl::kAccessAllowed) { StringBuilder builder; builder.Append( @@ -783,8 +777,8 @@ } std::unique_ptr<CrossOriginPreflightResultCacheItem> preflight_result = - WTF::WrapUnique( - new CrossOriginPreflightResultCacheItem(EffectiveAllowCredentials())); + WTF::WrapUnique(new CrossOriginPreflightResultCacheItem( + actual_request_.GetFetchCredentialsMode())); if (!preflight_result->Parse(response, access_control_error_description) || !preflight_result->AllowsCrossOriginMethod( actual_request_.HttpMethod(), access_control_error_description) || @@ -819,6 +813,7 @@ void DocumentThreadableLoader::HandleResponse( unsigned long identifier, + WebURLRequest::FetchCredentialsMode credentials_mode, const ResourceResponse& response, std::unique_ptr<WebDataConsumerHandle> handle) { DCHECK(client_); @@ -861,13 +856,13 @@ fallback_request_for_service_worker_.Url())); fallback_request_for_service_worker_ = ResourceRequest(); - if (!same_origin_request_ && - (options_.fetch_request_mode == WebURLRequest::kFetchRequestModeCORS || + if ((options_.fetch_request_mode == WebURLRequest::kFetchRequestModeCORS || options_.fetch_request_mode == - WebURLRequest::kFetchRequestModeCORSWithForcedPreflight)) { + WebURLRequest::kFetchRequestModeCORSWithForcedPreflight) && + cors_flag_) { CrossOriginAccessControl::AccessStatus cors_status = - CrossOriginAccessControl::CheckAccess( - response, EffectiveAllowCredentials(), GetSecurityOrigin()); + CrossOriginAccessControl::CheckAccess(response, credentials_mode, + GetSecurityOrigin()); if (cors_status != CrossOriginAccessControl::kAccessAllowed) { ReportResponseReceived(identifier, response); StringBuilder builder; @@ -942,11 +937,7 @@ DCHECK(fallback_request_for_service_worker_.IsNull()); if (!actual_request_.IsNull()) { - DCHECK(!same_origin_request_); - DCHECK(options_.fetch_request_mode == - WebURLRequest::kFetchRequestModeCORS || - options_.fetch_request_mode == - WebURLRequest::kFetchRequestModeCORSWithForcedPreflight); + DCHECK(actual_request_.IsExternalRequest() || cors_flag_); LoadActualRequest(); return; } @@ -992,8 +983,7 @@ ResourceRequest actual_request = actual_request_; ResourceLoaderOptions actual_options = actual_options_; actual_request_ = ResourceRequest(); - actual_options_ = ResourceLoaderOptions(kAllowStoredCredentials, - kClientRequestedCredentials); + actual_options_ = ResourceLoaderOptions(); ClearResource(); @@ -1127,9 +1117,10 @@ return; } - HandleResponse(identifier, response, nullptr); + HandleResponse(identifier, request.GetFetchCredentialsMode(), response, + nullptr); - // handleResponse() may detect an error. In such a case (check |m_client| as + // HandleResponse() may detect an error. In such a case (check |m_client| as // it gets reset by clear() call), skip the rest. // // |this| is alive here since loadResourceSynchronously() keeps it alive until @@ -1154,16 +1145,32 @@ } void DocumentThreadableLoader::LoadRequest( - const ResourceRequest& request, + ResourceRequest& request, ResourceLoaderOptions resource_loader_options) { - // Any credential should have been removed from the cross-site requests. - const KURL& request_url = request.Url(); - DCHECK(same_origin_request_ || request_url.User().IsEmpty()); - DCHECK(same_origin_request_ || request_url.Pass().IsEmpty()); + resource_loader_options.cors_handling_by_resource_fetcher = + kDisableCORSHandlingByResourceFetcher; - // Update resourceLoaderOptions with enforced values. - if (force_do_not_allow_stored_credentials_) - resource_loader_options.allow_credentials = kDoNotAllowStoredCredentials; + bool allow_stored_credentials = false; + switch (request.GetFetchCredentialsMode()) { + case WebURLRequest::kFetchCredentialsModeOmit: + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + // TODO(tyoshino): It's wrong to use |cors_flag| here. Fix it to use the + // response tainting. + // + // TODO(tyoshino): The credentials mode must work even when the "no-cors" + // mode is in use. See the following issues: + // - https://github.com/whatwg/fetch/issues/130 + // - https://github.com/whatwg/fetch/issues/169 + allow_stored_credentials = !cors_flag_ || suborigin_force_credentials_; + break; + case WebURLRequest::kFetchCredentialsModeInclude: + case WebURLRequest::kFetchCredentialsModePassword: + allow_stored_credentials = true; + break; + } + request.SetAllowStoredCredentials(allow_stored_credentials); + resource_loader_options.security_origin = security_origin_; if (async_) LoadRequestAsync(request, resource_loader_options); @@ -1175,13 +1182,7 @@ if (options_.fetch_request_mode == WebURLRequest::kFetchRequestModeNoCORS) return true; - return same_origin_request_ && GetSecurityOrigin()->CanRequest(url); -} - -StoredCredentials DocumentThreadableLoader::EffectiveAllowCredentials() const { - if (force_do_not_allow_stored_credentials_) - return kDoNotAllowStoredCredentials; - return resource_loader_options_.allow_credentials; + return !cors_flag_ && GetSecurityOrigin()->CanRequest(url); } const SecurityOrigin* DocumentThreadableLoader::GetSecurityOrigin() const {
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h index 6c038cca..364f6c0f 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
@@ -118,7 +118,11 @@ // Methods containing code to handle resource fetch results which are common // to both sync and async mode. + // + // The FetchCredentialsMode argument must be the request's credentials mode. + // It's used for CORS check. void HandleResponse(unsigned long identifier, + WebURLRequest::FetchCredentialsMode, const ResourceResponse&, std::unique_ptr<WebDataConsumerHandle>); void HandleReceivedData(const char* data, size_t data_length); @@ -128,7 +132,7 @@ // Calls the appropriate loading method according to policy and data about // origin. Only for handling the initial load (including fallback after // consulting ServiceWorker). - void DispatchInitialRequest(const ResourceRequest&); + void DispatchInitialRequest(ResourceRequest&); void MakeCrossOriginAccessRequest(const ResourceRequest&); // Loads m_fallbackRequestForServiceWorker. void LoadFallbackRequestForServiceWorker(); @@ -149,12 +153,15 @@ void LoadRequestSync(const ResourceRequest&, ResourceLoaderOptions); void PrepareCrossOriginRequest(ResourceRequest&); - void LoadRequest(const ResourceRequest&, ResourceLoaderOptions); + // This method modifies the ResourceRequest by calling + // SetAllowStoredCredentials() on it based on same-origin-ness and the + // credentials mode. + // + // This method configures the ResourceLoaderOptions so that the underlying + // ResourceFetcher doesn't perform some part of the CORS logic since this + // class performs it by itself. + void LoadRequest(ResourceRequest&, ResourceLoaderOptions); bool IsAllowedRedirect(const KURL&) const; - // Returns DoNotAllowStoredCredentials if m_forceDoNotAllowStoredCredentials - // is set. Otherwise, just returns allowCredentials value of - // m_resourceLoaderOptions. - StoredCredentials EffectiveAllowCredentials() const; // TODO(hiroshige): After crbug.com/633696 is fixed, // - Remove RawResourceClientStateChecker logic, @@ -196,13 +203,11 @@ // up-to-date values from them and this variable, and use it. const ResourceLoaderOptions resource_loader_options_; - bool force_do_not_allow_stored_credentials_; + // Corresponds to the CORS flag in the Fetch spec. + bool cors_flag_; + bool suborigin_force_credentials_; RefPtr<SecurityOrigin> security_origin_; - // True while the initial URL and all the URLs of the redirects this object - // has followed, if any, are same-origin to getSecurityOrigin(). - bool same_origin_request_; - // Set to true when the response data is given to a data consumer handle. bool is_using_data_consumer_handle_;
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.cpp b/third_party/WebKit/Source/core/loader/EmptyClients.cpp index 4e77ef26..40784ad 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.cpp +++ b/third_party/WebKit/Source/core/loader/EmptyClients.cpp
@@ -144,6 +144,7 @@ NavigationPolicy, bool, bool, + WebTriggeringEventInfo, HTMLFormElement*, ContentSecurityPolicyDisposition) { return kNavigationPolicyIgnore;
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.h b/third_party/WebKit/Source/core/loader/EmptyClients.h index 7d0e2d5..d66d8e41 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.h +++ b/third_party/WebKit/Source/core/loader/EmptyClients.h
@@ -284,6 +284,7 @@ NavigationPolicy, bool, bool, + WebTriggeringEventInfo, HTMLFormElement*, ContentSecurityPolicyDisposition) override;
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp index 6c976d2..a9dee6a 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp
@@ -196,8 +196,9 @@ SecurityViolationReportingPolicy reporting_policy) { KURL input_url(kParsedURLString, "http://example.com/"); ResourceRequest resource_request(input_url); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; return fetch_context->CanRequest( Resource::kImage, resource_request, input_url, options, reporting_policy, FetchParameters::kUseDefaultOriginRestrictionForType); @@ -496,8 +497,9 @@ KURL url(KURL(), "http://baz.test"); ResourceRequest resource_request(url); resource_request.SetRequestContext(WebURLRequest::kRequestContextScript); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; fetch_context->PopulateResourceRequest( url, Resource::kScript, ClientHintsPreferences(), FetchParameters::ResourceWidth(), options, @@ -893,6 +895,8 @@ DispatchDidLoadResourceFromMemoryCache) { ResourceRequest resource_request(url); resource_request.SetRequestContext(WebURLRequest::kRequestContextImage); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); Resource* resource = MockResource::Create(resource_request); EXPECT_CALL(*client, DispatchDidLoadResourceFromMemoryCache( @@ -913,6 +917,8 @@ MemoryCacheCertificateError) { ResourceRequest resource_request(url); resource_request.SetRequestContext(WebURLRequest::kRequestContextImage); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); ResourceResponse response; response.SetURL(url); response.SetHasMajorCertificateErrors(true); @@ -1047,6 +1053,7 @@ TEST_F(FrameFetchContextTest, DispatchDidReceiveResponseWhenDetached) { ResourceRequest request(KURL(KURL(), "https://www.example.com/")); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); Resource* resource = MockResource::Create(request); ResourceResponse response; @@ -1119,6 +1126,7 @@ TEST_F(FrameFetchContextTest, DidLoadResourceWhenDetached) { ResourceRequest request(KURL(KURL(), "https://www.example.com/")); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); Resource* resource = MockResource::Create(request); dummy_page_holder = nullptr; @@ -1229,6 +1237,8 @@ TEST_F(FrameFetchContextTest, PopulateResourceRequestWhenDetached) { KURL url(KURL(), "https://www.example.com/"); ResourceRequest request(url); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ClientHintsPreferences client_hints_preferences; client_hints_preferences.SetShouldSendDeviceRAM(true); client_hints_preferences.SetShouldSendDPR(true); @@ -1236,8 +1246,7 @@ client_hints_preferences.SetShouldSendViewportWidth(true); FetchParameters::ResourceWidth resource_width; - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + ResourceLoaderOptions options; document->GetClientHintsPreferences().SetShouldSendDeviceRAM(true); document->GetClientHintsPreferences().SetShouldSendDPR(true);
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 8b04332..e60229e6 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -1272,6 +1272,7 @@ NavigationPolicy policy, FrameLoadType frame_load_type, bool is_client_redirect, + WebTriggeringEventInfo triggering_event_info, HTMLFormElement* form) { // Don't ask if we are loading an empty URL. if (request.Url().IsEmpty() || substitute_data.IsValid()) @@ -1300,8 +1301,8 @@ frame_load_type == kFrameLoadTypeReplaceCurrentItem; policy = Client()->DecidePolicyForNavigation( request, origin_document, loader, type, policy, - replaces_current_history_item, is_client_redirect, form, - should_check_main_world_content_security_policy); + replaces_current_history_item, is_client_redirect, triggering_event_info, + form, should_check_main_world_content_security_policy); if (policy == kNavigationPolicyCurrentTab || policy == kNavigationPolicyIgnore || policy == kNavigationPolicyHandledByClient || @@ -1341,7 +1342,8 @@ // during the first navigation and not during redirects. nullptr, // origin_document substitute_data, loader, should_check_main_world_content_security_policy, - type, policy, frame_load_type, is_client_redirect, form); + type, policy, frame_load_type, is_client_redirect, + WebTriggeringEventInfo::kNotFromEvent, form); } NavigationPolicy FrameLoader::CheckLoadCanStart( @@ -1369,6 +1371,13 @@ ContentSecurityPolicy::CheckHeaderType::kCheckReportOnly); ModifyRequestForCSP(resource_request, nullptr); + WebTriggeringEventInfo triggering_event_info = + WebTriggeringEventInfo::kNotFromEvent; + if (frame_load_request.TriggeringEvent()) { + triggering_event_info = frame_load_request.TriggeringEvent()->isTrusted() + ? WebTriggeringEventInfo::kFromTrustedEvent + : WebTriggeringEventInfo::kFromUntrustedEvent; + } return ShouldContinueForNavigationPolicy( resource_request, frame_load_request.OriginDocument(), frame_load_request.GetSubstituteData(), nullptr, @@ -1376,7 +1385,7 @@ navigation_type, navigation_policy, type, frame_load_request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect, - frame_load_request.Form()); + triggering_event_info, frame_load_request.Form()); } void FrameLoader::StartLoad(FrameLoadRequest& frame_load_request,
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.h b/third_party/WebKit/Source/core/loader/FrameLoader.h index 8dd44d5..0827dc3 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.h +++ b/third_party/WebKit/Source/core/loader/FrameLoader.h
@@ -49,6 +49,7 @@ #include "platform/wtf/Forward.h" #include "platform/wtf/HashSet.h" #include "public/platform/WebInsecureRequestPolicy.h" +#include "public/web/WebTriggeringEventInfo.h" #include <memory> @@ -192,6 +193,7 @@ NavigationPolicy, FrameLoadType, bool is_client_redirect, + WebTriggeringEventInfo, HTMLFormElement*); // Like ShouldContinueForNavigationPolicy, but should be used when following
diff --git a/third_party/WebKit/Source/core/loader/HistoryItem.cpp b/third_party/WebKit/Source/core/loader/HistoryItem.cpp index 1c0ff7f..96342dd 100644 --- a/third_party/WebKit/Source/core/loader/HistoryItem.cpp +++ b/third_party/WebKit/Source/core/loader/HistoryItem.cpp
@@ -149,7 +149,7 @@ } } -void HistoryItem::SetFormData(PassRefPtr<EncodedFormData> form_data) { +void HistoryItem::SetFormData(RefPtr<EncodedFormData> form_data) { form_data_ = std::move(form_data); }
diff --git a/third_party/WebKit/Source/core/loader/HistoryItem.h b/third_party/WebKit/Source/core/loader/HistoryItem.h index fc02d8e3..4c5729c 100644 --- a/third_party/WebKit/Source/core/loader/HistoryItem.h +++ b/third_party/WebKit/Source/core/loader/HistoryItem.h
@@ -106,7 +106,7 @@ } void SetFormInfoFromRequest(const ResourceRequest&); - void SetFormData(PassRefPtr<EncodedFormData>); + void SetFormData(RefPtr<EncodedFormData>); void SetFormContentType(const AtomicString&); ResourceRequest GenerateResourceRequest(WebCachePolicy);
diff --git a/third_party/WebKit/Source/core/loader/ImageLoader.cpp b/third_party/WebKit/Source/core/loader/ImageLoader.cpp index 0bbe164..4c7a48e 100644 --- a/third_party/WebKit/Source/core/loader/ImageLoader.cpp +++ b/third_party/WebKit/Source/core/loader/ImageLoader.cpp
@@ -305,8 +305,7 @@ if (!url.IsNull() && !url.IsEmpty()) { // Unlike raw <img>, we block mixed content inside of <picture> or // <img srcset>. - ResourceLoaderOptions resource_loader_options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { @@ -407,8 +406,9 @@ // funneling the main resource bytes into image_, so just create an // ImageResource to be populated later. if (loading_image_document_) { - ImageResource* image_resource = ImageResource::Create( - ResourceRequest(ImageSourceToKURL(element_->ImageSourceURL()))); + ResourceRequest request(ImageSourceToKURL(element_->ImageSourceURL())); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ImageResource* image_resource = ImageResource::Create(request); image_resource->SetStatus(ResourceStatus::kPending); image_resource->NotifyStartLoad(); SetImageForImageDocument(image_resource);
diff --git a/third_party/WebKit/Source/core/loader/LinkLoader.cpp b/third_party/WebKit/Source/core/loader/LinkLoader.cpp index d37d6e8..72bedc26 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoader.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoader.cpp
@@ -350,8 +350,7 @@ referrer_policy, href, document.OutgoingReferrer())); } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::link; FetchParameters link_fetch_params(resource_request, options); link_fetch_params.SetCharset(document.Encoding()); @@ -385,8 +384,7 @@ referrer_policy, href, document.OutgoingReferrer())); } - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::link; FetchParameters link_fetch_params(resource_request, options); if (cross_origin != kCrossOriginAttributeNotSet) {
diff --git a/third_party/WebKit/Source/core/loader/PingLoader.cpp b/third_party/WebKit/Source/core/loader/PingLoader.cpp index 621a0f7..b86bbe12 100644 --- a/third_party/WebKit/Source/core/loader/PingLoader.cpp +++ b/third_party/WebKit/Source/core/loader/PingLoader.cpp
@@ -195,10 +195,7 @@ WTF_MAKE_NONCOPYABLE(PingLoaderImpl); public: - PingLoaderImpl(LocalFrame*, - ResourceRequest&, - const AtomicString&, - StoredCredentials); + PingLoaderImpl(LocalFrame*, ResourceRequest&, const AtomicString&); ~PingLoaderImpl() override; DECLARE_VIRTUAL_TRACE(); @@ -236,8 +233,7 @@ PingLoaderImpl::PingLoaderImpl(LocalFrame* frame, ResourceRequest& request, - const AtomicString& initiator, - StoredCredentials credentials_allowed) + const AtomicString& initiator) : ContextClient(frame), timeout_(this, &PingLoaderImpl::Timeout), url_(request.Url()), @@ -271,9 +267,28 @@ loader_ = fetch_context.CreateURLLoader(request); DCHECK(loader_); + WrappedResourceRequest wrapped_request(request); - wrapped_request.SetAllowStoredCredentials(credentials_allowed == - kAllowStoredCredentials); + + bool allow_stored_credentials = false; + switch (request.GetFetchCredentialsMode()) { + case WebURLRequest::kFetchCredentialsModeOmit: + NOTREACHED(); + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + allow_stored_credentials = + frame->GetDocument()->GetSecurityOrigin()->CanRequestNoSuborigin( + request.Url()); + break; + case WebURLRequest::kFetchCredentialsModeInclude: + allow_stored_credentials = true; + break; + case WebURLRequest::kFetchCredentialsModePassword: + NOTREACHED(); + break; + } + request.SetAllowStoredCredentials(allow_stored_credentials); + loader_->LoadAsynchronously(wrapped_request, this); // If the server never responds, FrameLoader won't be able to cancel this load @@ -309,13 +324,13 @@ DCHECK(!redirect_response.IsNull()); String error_description; - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); - // TODO(tyoshino): Save updated data in options.securityOrigin and pass it + ResourceLoaderOptions options; + // TODO(tyoshino): Save updated data in options.security_origin and pass it // on the next time. if (!CrossOriginAccessControl::HandleRedirect( - origin_, new_request, redirect_response, kAllowStoredCredentials, - options, error_description)) { + origin_, new_request, redirect_response, + passed_new_request.GetFetchCredentialsMode(), options, + error_description)) { if (GetFrame()) { if (GetFrame()->GetDocument()) { GetFrame()->GetDocument()->AddConsoleMessage(ConsoleMessage::Create( @@ -410,16 +425,14 @@ bool SendPingCommon(LocalFrame* frame, ResourceRequest& request, - const AtomicString& initiator, - StoredCredentials credentials_allowed) { + const AtomicString& initiator) { request.SetKeepalive(true); if (MixedContentChecker::ShouldBlockFetch(frame, request, request.Url())) return false; // The loader keeps itself alive until it receives a response and disposes // itself. - PingLoaderImpl* loader = - new PingLoaderImpl(frame, request, initiator, credentials_allowed); + PingLoaderImpl* loader = new PingLoaderImpl(frame, request, initiator); DCHECK(loader); return true; @@ -468,8 +481,7 @@ beacon.Serialize(request); - return SendPingCommon(frame, request, FetchInitiatorTypeNames::beacon, - kAllowStoredCredentials); + return SendPingCommon(frame, request, FetchInitiatorTypeNames::beacon); } } // namespace @@ -480,8 +492,7 @@ FinishPingRequestInitialization(request, frame, WebURLRequest::kRequestContextPing); - SendPingCommon(frame, request, FetchInitiatorTypeNames::ping, - kAllowStoredCredentials); + SendPingCommon(frame, request, FetchInitiatorTypeNames::ping); } // http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing @@ -520,8 +531,7 @@ AtomicString(frame->GetDocument()->Url().GetString())); } - SendPingCommon(frame, request, FetchInitiatorTypeNames::ping, - kAllowStoredCredentials); + SendPingCommon(frame, request, FetchInitiatorTypeNames::ping); } void PingLoader::SendViolationReport(LocalFrame* frame, @@ -539,16 +549,12 @@ break; } request.SetHTTPBody(std::move(report)); + request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeSameOrigin); FinishPingRequestInitialization(request, frame, WebURLRequest::kRequestContextCSPReport); - StoredCredentials credentials_allowed = - SecurityOrigin::Create(report_url) - ->IsSameSchemeHostPort(frame->GetDocument()->GetSecurityOrigin()) - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; - SendPingCommon(frame, request, FetchInitiatorTypeNames::violationreport, - credentials_allowed); + SendPingCommon(frame, request, FetchInitiatorTypeNames::violationreport); } bool PingLoader::SendBeacon(LocalFrame* frame,
diff --git a/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp b/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp index 2fe7d76..8a71e53 100644 --- a/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp +++ b/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -86,14 +86,15 @@ return WTF::TextEncoding(); } -TextResourceDecoder::ContentType DetermineContentType(const String& mime_type) { +TextResourceDecoderOptions::ContentType DetermineContentType( + const String& mime_type) { if (DeprecatedEqualIgnoringCase(mime_type, "text/css")) - return TextResourceDecoder::kCSSContent; + return TextResourceDecoderOptions::kCSSContent; if (DeprecatedEqualIgnoringCase(mime_type, "text/html")) - return TextResourceDecoder::kHTMLContent; + return TextResourceDecoderOptions::kHTMLContent; if (DOMImplementation::IsXMLMIMEType(mime_type)) - return TextResourceDecoder::kXMLContent; - return TextResourceDecoder::kPlainTextContent; + return TextResourceDecoderOptions::kXMLContent; + return TextResourceDecoderOptions::kPlainTextContent; } } // namespace @@ -105,44 +106,16 @@ TextResourceDecoderBuilder::~TextResourceDecoderBuilder() {} -inline std::unique_ptr<TextResourceDecoder> -TextResourceDecoderBuilder::CreateDecoderInstance(Document* document) { +std::unique_ptr<TextResourceDecoder> TextResourceDecoderBuilder::BuildFor( + Document* document) { const WTF::TextEncoding encoding_from_domain = GetEncodingFromDomain(document->Url()); - if (LocalFrame* frame = document->GetFrame()) { - if (Settings* settings = frame->GetSettings()) { - const WTF::TextEncoding hint_encoding = - encoding_from_domain.IsValid() - ? encoding_from_domain - : WTF::TextEncoding(settings->GetDefaultTextEncodingName()); - // Disable autodetection for XML to honor the default encoding (UTF-8) for - // unlabelled documents. - if (DOMImplementation::IsXMLMIMEType(mime_type_)) { - return TextResourceDecoder::Create(TextResourceDecoder::kXMLContent, - hint_encoding); - } - return TextResourceDecoder::CreateWithAutoDetection( - DetermineContentType(mime_type_), hint_encoding, document->Url()); - } - } - return TextResourceDecoder::Create(DetermineContentType(mime_type_), - encoding_from_domain); -} - -inline void TextResourceDecoderBuilder::SetupEncoding( - TextResourceDecoder* decoder, - Document* document) { LocalFrame* frame = document->GetFrame(); LocalFrame* parent_frame = 0; if (frame && frame->Tree().Parent() && frame->Tree().Parent()->IsLocalFrame()) parent_frame = ToLocalFrame(frame->Tree().Parent()); - if (!encoding_.IsEmpty()) { - decoder->SetEncoding(WTF::TextEncoding(encoding_.GetString()), - TextResourceDecoder::kEncodingFromHTTPHeader); - } - // Set the hint encoding to the parent frame encoding only if the parent and // the current frames share the security origin. We impose this condition // because somebody can make a child frameg63 containing a carefully crafted @@ -151,22 +124,45 @@ // could be an attack vector. // FIXME: This might be too cautious for non-7bit-encodings and we may // consider relaxing this later after testing. - if (frame && CanReferToParentFrameEncoding(frame, parent_frame)) { - if (parent_frame->GetDocument()->EncodingWasDetectedHeuristically()) - decoder->SetHintEncoding(parent_frame->GetDocument()->Encoding()); + const bool use_hint_encoding = + frame && CanReferToParentFrameEncoding(frame, parent_frame); - if (encoding_.IsEmpty()) { - decoder->SetEncoding(parent_frame->GetDocument()->Encoding(), - TextResourceDecoder::kEncodingFromParentFrame); + std::unique_ptr<TextResourceDecoder> decoder; + if (frame && frame->GetSettings()) { + const WTF::TextEncoding default_encoding = + encoding_from_domain.IsValid() + ? encoding_from_domain + : WTF::TextEncoding( + frame->GetSettings()->GetDefaultTextEncodingName()); + // Disable autodetection for XML to honor the default encoding (UTF-8) for + // unlabelled documents. + if (DOMImplementation::IsXMLMIMEType(mime_type_)) { + decoder = TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kXMLContent, default_encoding)); + } else { + WTF::TextEncoding hint_encoding; + if (use_hint_encoding && + parent_frame->GetDocument()->EncodingWasDetectedHeuristically()) + hint_encoding = parent_frame->GetDocument()->Encoding(); + decoder = TextResourceDecoder::Create( + TextResourceDecoderOptions::CreateWithAutoDetection( + DetermineContentType(mime_type_), default_encoding, hint_encoding, + document->Url())); } + } else { + decoder = TextResourceDecoder::Create(TextResourceDecoderOptions( + DetermineContentType(mime_type_), encoding_from_domain)); } -} + DCHECK(decoder); -std::unique_ptr<TextResourceDecoder> TextResourceDecoderBuilder::BuildFor( - Document* document) { - std::unique_ptr<TextResourceDecoder> decoder = - CreateDecoderInstance(document); - SetupEncoding(decoder.get(), document); + if (!encoding_.IsEmpty()) { + decoder->SetEncoding(WTF::TextEncoding(encoding_.GetString()), + TextResourceDecoder::kEncodingFromHTTPHeader); + } else if (use_hint_encoding) { + decoder->SetEncoding(parent_frame->GetDocument()->Encoding(), + TextResourceDecoder::kEncodingFromParentFrame); + } + return decoder; }
diff --git a/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h b/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h index 2fd19a9..263f9a2 100644 --- a/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h +++ b/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h
@@ -58,9 +58,6 @@ void Clear(); private: - std::unique_ptr<TextResourceDecoder> CreateDecoderInstance(Document*); - void SetupEncoding(TextResourceDecoder*, Document*); - AtomicString mime_type_; AtomicString encoding_; };
diff --git a/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp b/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp index 22d553c..53725e4a 100644 --- a/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp +++ b/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
@@ -70,7 +70,8 @@ const ResourceRequest& request, const ResourceResponse&) { DCHECK_EQ(this->GetResource(), resource); - if (resource->Options().cors_enabled == kIsCORSEnabled || + if (resource->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS || GetDocument().GetSecurityOrigin()->CanRequestNoSuborigin(request.Url())) return true; @@ -126,9 +127,9 @@ CrossOriginAttributeValue cross_origin) { CancelLoad(); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::texttrack; + FetchParameters cue_fetch_params(ResourceRequest(url), options); if (cross_origin != kCrossOriginAttributeNotSet) {
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp index a1555c0c..033c3e62 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoaderTest.cpp
@@ -132,8 +132,7 @@ WebURLRequest::FetchRequestMode fetch_request_mode) override { ThreadableLoaderOptions options; options.fetch_request_mode = fetch_request_mode; - ResourceLoaderOptions resource_loader_options( - kDoNotAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; loader_ = DocumentThreadableLoader::Create( *ThreadableLoadingContext::Create(GetDocument()), client, options, resource_loader_options); @@ -284,8 +283,7 @@ ThreadableLoaderOptions options; options.fetch_request_mode = fetch_request_mode; - ResourceLoaderOptions resource_loader_options( - kDoNotAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; // Ensure that WorkerThreadableLoader is created. // ThreadableLoader::create() determines whether it should create @@ -306,6 +304,7 @@ DCHECK(worker_thread_->IsCurrentThread()); ResourceRequest request(request_data.get()); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); loader_->Start(request); event->Signal(); } @@ -347,6 +346,7 @@ void StartLoader(const KURL& url) { ResourceRequest request(url); request.SetRequestContext(WebURLRequest::kRequestContextObject); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); helper_->StartLoader(request); }
diff --git a/third_party/WebKit/Source/core/loader/WorkletScriptLoader.cpp b/third_party/WebKit/Source/core/loader/WorkletScriptLoader.cpp index d274d90..e932937 100644 --- a/third_party/WebKit/Source/core/loader/WorkletScriptLoader.cpp +++ b/third_party/WebKit/Source/core/loader/WorkletScriptLoader.cpp
@@ -23,8 +23,7 @@ ResourceRequest resource_request(module_url_record); resource_request.SetRequestContext(WebURLRequest::kRequestContextScript); - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::internal; FetchParameters params(resource_request, options); ScriptResource* resource = ScriptResource::Fetch(params, fetcher_);
diff --git a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp index 32577c3..6c25e3b5 100644 --- a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp +++ b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp
@@ -49,6 +49,8 @@ #include "platform/exported/WrappedResourceRequest.h" #include "platform/exported/WrappedResourceResponse.h" #include "platform/weborigin/SecurityOrigin.h" +#include "platform/wtf/Assertions.h" +#include "public/platform/WebApplicationCacheHost.h" #include "public/platform/WebURL.h" #include "public/platform/WebURLError.h" #include "public/platform/WebURLRequest.h" @@ -359,4 +361,32 @@ visitor->Trace(document_loader_); } +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUncached, + ApplicationCacheHost::kUncached); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kIdle, ApplicationCacheHost::kIdle); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kChecking, + ApplicationCacheHost::kChecking); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kDownloading, + ApplicationCacheHost::kDownloading); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUpdateReady, + ApplicationCacheHost::kUpdateready); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kObsolete, + ApplicationCacheHost::kObsolete); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kCheckingEvent, + ApplicationCacheHost::kCheckingEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kErrorEvent, + ApplicationCacheHost::kErrorEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kNoUpdateEvent, + ApplicationCacheHost::kNoupdateEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kDownloadingEvent, + ApplicationCacheHost::kDownloadingEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kProgressEvent, + ApplicationCacheHost::kProgressEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUpdateReadyEvent, + ApplicationCacheHost::kUpdatereadyEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kCachedEvent, + ApplicationCacheHost::kCachedEvent); +STATIC_ASSERT_ENUM(WebApplicationCacheHost::kObsoleteEvent, + ApplicationCacheHost::kObsoleteEvent); + } // namespace blink
diff --git a/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoader.cpp b/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoader.cpp index 8f1676a..6b91ebd 100644 --- a/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoader.cpp +++ b/third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoader.cpp
@@ -91,8 +91,7 @@ // -> FetchResourceType is specified by ScriptResource::fetch // parser metadata is parser state, - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + ResourceLoaderOptions options; options.parser_disposition = module_request.ParserState(); // As initiator for module script fetch is not specified in HTML spec, // we specity "" as initiator per: @@ -116,15 +115,8 @@ // https://fetch.spec.whatwg.org/#concept-request-origin // ... mode is "cors", ... // ... credentials mode is credentials mode, ... - // TODO(tyoshino): FetchCredentialsMode should be used to communicate CORS - // mode. - CrossOriginAttributeValue cross_origin = - module_request.CredentialsMode() == - WebURLRequest::kFetchCredentialsModeInclude - ? kCrossOriginAttributeUseCredentials - : kCrossOriginAttributeAnonymous; fetch_params.SetCrossOriginAccessControl(modulator_->GetSecurityOrigin(), - cross_origin); + module_request.CredentialsMode()); // Module scripts are always async. fetch_params.SetDefer(FetchParameters::kLazyLoad);
diff --git a/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.cpp b/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.cpp index c47aadc..26fa5d82 100644 --- a/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.cpp +++ b/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.cpp
@@ -94,6 +94,12 @@ } // namespace +CrossOriginPreflightResultCacheItem::CrossOriginPreflightResultCacheItem( + WebURLRequest::FetchCredentialsMode credentials_mode) + : absolute_expiry_time_(0), + credentials_( + FetchUtils::ShouldTreatCredentialsModeAsInclude(credentials_mode)) {} + bool CrossOriginPreflightResultCacheItem::Parse( const ResourceResponse& response, String& error_description) { @@ -160,14 +166,14 @@ } bool CrossOriginPreflightResultCacheItem::AllowsRequest( - StoredCredentials include_credentials, + WebURLRequest::FetchCredentialsMode credentials_mode, const String& method, const HTTPHeaderMap& request_headers) const { String ignored_explanation; if (absolute_expiry_time_ < CurrentTime()) return false; - if (include_credentials == kAllowStoredCredentials && - credentials_ == kDoNotAllowStoredCredentials) + if (!credentials_ && + FetchUtils::ShouldTreatCredentialsModeAsInclude(credentials_mode)) return false; if (!AllowsCrossOriginMethod(method, ignored_explanation)) return false; @@ -194,7 +200,7 @@ bool CrossOriginPreflightResultCache::CanSkipPreflight( const String& origin, const KURL& url, - StoredCredentials include_credentials, + WebURLRequest::FetchCredentialsMode credentials_mode, const String& method, const HTTPHeaderMap& request_headers) { DCHECK(IsMainThread()); @@ -203,8 +209,7 @@ if (cache_it == preflight_hash_map_.end()) return false; - if (cache_it->value->AllowsRequest(include_credentials, method, - request_headers)) + if (cache_it->value->AllowsRequest(credentials_mode, method, request_headers)) return true; preflight_hash_map_.erase(cache_it);
diff --git a/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.h b/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.h index 1f7d9df..73fc24b3 100644 --- a/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.h +++ b/third_party/WebKit/Source/core/loader/private/CrossOriginPreflightResultCache.h
@@ -33,25 +33,28 @@ #include "platform/wtf/HashMap.h" #include "platform/wtf/HashSet.h" #include "platform/wtf/text/StringHash.h" +#include "public/platform/WebURLRequest.h" namespace blink { class HTTPHeaderMap; class ResourceResponse; +// Represents an entry of the CORS-preflight cache. +// See https://fetch.spec.whatwg.org/#concept-cache. class CrossOriginPreflightResultCacheItem { WTF_MAKE_NONCOPYABLE(CrossOriginPreflightResultCacheItem); USING_FAST_MALLOC(CrossOriginPreflightResultCacheItem); public: - explicit CrossOriginPreflightResultCacheItem(StoredCredentials credentials) - : absolute_expiry_time_(0), credentials_(credentials) {} + explicit CrossOriginPreflightResultCacheItem( + WebURLRequest::FetchCredentialsMode); bool Parse(const ResourceResponse&, String& error_description); bool AllowsCrossOriginMethod(const String&, String& error_description) const; bool AllowsCrossOriginHeaders(const HTTPHeaderMap&, String& error_description) const; - bool AllowsRequest(StoredCredentials, + bool AllowsRequest(WebURLRequest::FetchCredentialsMode, const String& method, const HTTPHeaderMap& request_headers) const; @@ -62,7 +65,9 @@ // be to start a timer for the expiration delta that removes this from the // cache when it fires. double absolute_expiry_time_; - StoredCredentials credentials_; + + // Corresponds to the fields of the CORS-preflight cache with the same name. + bool credentials_; HashSet<String> methods_; HeadersSet headers_; }; @@ -79,7 +84,7 @@ std::unique_ptr<CrossOriginPreflightResultCacheItem>); bool CanSkipPreflight(const String& origin, const KURL&, - StoredCredentials, + WebURLRequest::FetchCredentialsMode, const String& method, const HTTPHeaderMap& request_headers);
diff --git a/third_party/WebKit/Source/core/loader/resource/CSSStyleSheetResource.cpp b/third_party/WebKit/Source/core/loader/resource/CSSStyleSheetResource.cpp index 380eec13..407bbf0 100644 --- a/third_party/WebKit/Source/core/loader/resource/CSSStyleSheetResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/CSSStyleSheetResource.cpp
@@ -35,6 +35,7 @@ #include "platform/loader/fetch/ResourceClientWalker.h" #include "platform/loader/fetch/ResourceFetcher.h" #include "platform/loader/fetch/ResourceLoaderOptions.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/weborigin/SecurityPolicy.h" #include "platform/wtf/CurrentTime.h" @@ -57,8 +58,8 @@ const KURL& url, const String& charset) { ResourceRequest request(url); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; return new CSSStyleSheetResource(request, options, charset); } @@ -69,7 +70,7 @@ : StyleSheetResource(resource_request, kCSSStyleSheet, options, - TextResourceDecoder::kCSSContent, + TextResourceDecoderOptions::kCSSContent, charset), did_notify_first_data_(false) {}
diff --git a/third_party/WebKit/Source/core/loader/resource/DocumentResource.cpp b/third_party/WebKit/Source/core/loader/resource/DocumentResource.cpp index e80640e..afdd93d 100644 --- a/third_party/WebKit/Source/core/loader/resource/DocumentResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/DocumentResource.cpp
@@ -26,6 +26,7 @@ #include "platform/SharedBuffer.h" #include "platform/loader/fetch/FetchParameters.h" #include "platform/loader/fetch/ResourceFetcher.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/wtf/text/StringBuilder.h" namespace blink { @@ -45,7 +46,7 @@ : TextResource(request, type, options, - TextResourceDecoder::kXMLContent, + TextResourceDecoderOptions::kXMLContent, String()) { // FIXME: We'll support more types to support HTMLImports. DCHECK_EQ(type, kSVGDocument);
diff --git a/third_party/WebKit/Source/core/loader/resource/FontResource.h b/third_party/WebKit/Source/core/loader/resource/FontResource.h index b47df15..6c5d0d3 100644 --- a/third_party/WebKit/Source/core/loader/resource/FontResource.h +++ b/third_party/WebKit/Source/core/loader/resource/FontResource.h
@@ -72,13 +72,12 @@ WebProcessMemoryDump*) const override; private: - class FontResourceFactory : public ResourceFactory { + class FontResourceFactory : public NonTextResourceFactory { public: - FontResourceFactory() : ResourceFactory(Resource::kFont) {} + FontResourceFactory() : NonTextResourceFactory(Resource::kFont) {} Resource* Create(const ResourceRequest& request, - const ResourceLoaderOptions& options, - const String& charset) const override { + const ResourceLoaderOptions& options) const override { return new FontResource(request, options); } };
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp b/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp index 2f99f05..ce3260f1 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/ImageResource.cpp
@@ -126,16 +126,16 @@ const Member<ImageResource> resource_; }; -class ImageResource::ImageResourceFactory : public ResourceFactory { +class ImageResource::ImageResourceFactory : public NonTextResourceFactory { STACK_ALLOCATED(); public: ImageResourceFactory(const FetchParameters& fetch_params) - : ResourceFactory(Resource::kImage), fetch_params_(&fetch_params) {} + : NonTextResourceFactory(Resource::kImage), + fetch_params_(&fetch_params) {} Resource* Create(const ResourceRequest& request, - const ResourceLoaderOptions& options, - const String&) const override { + const ResourceLoaderOptions& options) const override { return new ImageResource(request, options, ImageResourceContent::CreateNotStarted(), fetch_params_->GetPlaceholderImageRequestType() == @@ -195,8 +195,7 @@ } ImageResource* ImageResource::Create(const ResourceRequest& request) { - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + ResourceLoaderOptions options; return new ImageResource(request, options, ImageResourceContent::CreateNotStarted(), false); } @@ -293,7 +292,7 @@ Resource::AllClientsAndObserversRemoved(); } -PassRefPtr<const SharedBuffer> ImageResource::ResourceBuffer() const { +RefPtr<const SharedBuffer> ImageResource::ResourceBuffer() const { if (Data()) return Data(); return GetContent()->ResourceBuffer();
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResource.h b/third_party/WebKit/Source/core/loader/resource/ImageResource.h index 144cf7ed..fbc4bf1 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResource.h +++ b/third_party/WebKit/Source/core/loader/resource/ImageResource.h
@@ -83,7 +83,7 @@ bool CanReuse(const FetchParameters&) const override; bool CanUseCacheValidator() const override; - PassRefPtr<const SharedBuffer> ResourceBuffer() const override; + RefPtr<const SharedBuffer> ResourceBuffer() const override; void NotifyStartLoad() override; void ResponseReceived(const ResourceResponse&, std::unique_ptr<WebDataConsumerHandle>) override;
diff --git a/third_party/WebKit/Source/core/loader/resource/ImageResourceTest.cpp b/third_party/WebKit/Source/core/loader/resource/ImageResourceTest.cpp index 7abc915..3c3b469 100644 --- a/third_party/WebKit/Source/core/loader/resource/ImageResourceTest.cpp +++ b/third_party/WebKit/Source/core/loader/resource/ImageResourceTest.cpp
@@ -612,6 +612,7 @@ ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath()); ResourceRequest request(test_url); request.SetPreviewsState(WebURLRequest::kServerLoFiOn); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); ImageResource* image_resource = ImageResource::Create(request); image_resource->SetStatus(ResourceStatus::kPending); image_resource->NotifyStartLoad();
diff --git a/third_party/WebKit/Source/core/loader/resource/LinkFetchResource.h b/third_party/WebKit/Source/core/loader/resource/LinkFetchResource.h index 0cbe035..aa57dfc6 100644 --- a/third_party/WebKit/Source/core/loader/resource/LinkFetchResource.h +++ b/third_party/WebKit/Source/core/loader/resource/LinkFetchResource.h
@@ -21,13 +21,13 @@ ~LinkFetchResource() override; private: - class LinkResourceFactory : public ResourceFactory { + class LinkResourceFactory : public NonTextResourceFactory { public: - explicit LinkResourceFactory(Resource::Type type) : ResourceFactory(type) {} + explicit LinkResourceFactory(Resource::Type type) + : NonTextResourceFactory(type) {} Resource* Create(const ResourceRequest& request, - const ResourceLoaderOptions& options, - const String& charset) const override { + const ResourceLoaderOptions& options) const override { return new LinkFetchResource(request, GetType(), options); } };
diff --git a/third_party/WebKit/Source/core/loader/resource/ScriptResource.cpp b/third_party/WebKit/Source/core/loader/resource/ScriptResource.cpp index cc819e0..7dcea00 100644 --- a/third_party/WebKit/Source/core/loader/resource/ScriptResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/ScriptResource.cpp
@@ -33,6 +33,7 @@ #include "platform/loader/fetch/IntegrityMetadata.h" #include "platform/loader/fetch/ResourceClientWalker.h" #include "platform/loader/fetch/ResourceFetcher.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/network/mime/MIMETypeRegistry.h" namespace blink { @@ -55,7 +56,7 @@ : TextResource(resource_request, kScript, options, - TextResourceDecoder::kPlainTextContent, + TextResourceDecoderOptions::kPlainTextContent, charset) {} ScriptResource::~ScriptResource() {}
diff --git a/third_party/WebKit/Source/core/loader/resource/ScriptResource.h b/third_party/WebKit/Source/core/loader/resource/ScriptResource.h index 2065dd6..b1ccd9bf 100644 --- a/third_party/WebKit/Source/core/loader/resource/ScriptResource.h +++ b/third_party/WebKit/Source/core/loader/resource/ScriptResource.h
@@ -61,8 +61,8 @@ // Public for testing static ScriptResource* Create(const KURL& url, const String& charset) { ResourceRequest request(url); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; return new ScriptResource(request, options, charset); }
diff --git a/third_party/WebKit/Source/core/loader/resource/StyleSheetResource.h b/third_party/WebKit/Source/core/loader/resource/StyleSheetResource.h index 1653c45..0841f5d5 100644 --- a/third_party/WebKit/Source/core/loader/resource/StyleSheetResource.h +++ b/third_party/WebKit/Source/core/loader/resource/StyleSheetResource.h
@@ -33,6 +33,7 @@ #include "core/CoreExport.h" #include "core/loader/resource/TextResource.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" namespace blink { @@ -45,7 +46,7 @@ StyleSheetResource(const ResourceRequest& request, Type type, const ResourceLoaderOptions& options, - TextResourceDecoder::ContentType content_type, + TextResourceDecoderOptions::ContentType content_type, const String& charset) : TextResource(request, type, options, content_type, charset) {} };
diff --git a/third_party/WebKit/Source/core/loader/resource/TextResource.cpp b/third_party/WebKit/Source/core/loader/resource/TextResource.cpp index 91d4a814..be6bb3a 100644 --- a/third_party/WebKit/Source/core/loader/resource/TextResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/TextResource.cpp
@@ -6,6 +6,7 @@ #include "core/html/parser/TextResourceDecoder.h" #include "platform/SharedBuffer.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/wtf/text/StringBuilder.h" namespace blink { @@ -13,11 +14,12 @@ TextResource::TextResource(const ResourceRequest& resource_request, Resource::Type type, const ResourceLoaderOptions& options, - TextResourceDecoder::ContentType content_type, + TextResourceDecoderOptions::ContentType content_type, const String& charset) : Resource(resource_request, type, options), - decoder_(TextResourceDecoder::Create(content_type, - WTF::TextEncoding(charset))) {} + decoder_(TextResourceDecoder::Create( + TextResourceDecoderOptions(content_type, + WTF::TextEncoding(charset)))) {} TextResource::~TextResource() {}
diff --git a/third_party/WebKit/Source/core/loader/resource/TextResource.h b/third_party/WebKit/Source/core/loader/resource/TextResource.h index 8ba18c6..4ccf00b 100644 --- a/third_party/WebKit/Source/core/loader/resource/TextResource.h +++ b/third_party/WebKit/Source/core/loader/resource/TextResource.h
@@ -9,6 +9,7 @@ #include "core/CoreExport.h" #include "core/html/parser/TextResourceDecoder.h" #include "platform/loader/fetch/Resource.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" namespace blink { @@ -28,7 +29,7 @@ TextResource(const ResourceRequest&, Type, const ResourceLoaderOptions&, - TextResourceDecoder::ContentType, + TextResourceDecoderOptions::ContentType, const String& charset); ~TextResource() override;
diff --git a/third_party/WebKit/Source/core/loader/resource/XSLStyleSheetResource.cpp b/third_party/WebKit/Source/core/loader/resource/XSLStyleSheetResource.cpp index b7c08df..0358a49 100644 --- a/third_party/WebKit/Source/core/loader/resource/XSLStyleSheetResource.cpp +++ b/third_party/WebKit/Source/core/loader/resource/XSLStyleSheetResource.cpp
@@ -32,6 +32,7 @@ #include "platform/loader/fetch/FetchParameters.h" #include "platform/loader/fetch/ResourceClientWalker.h" #include "platform/loader/fetch/ResourceFetcher.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" namespace blink { @@ -75,7 +76,7 @@ : StyleSheetResource(resource_request, kXSLStyleSheet, options, - TextResourceDecoder::kXMLContent, + TextResourceDecoderOptions::kXMLContent, charset) {} void XSLStyleSheetResource::DidAddClient(ResourceClient* c) {
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerTest.cpp index c9be82e..e2b35b3f 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerTest.cpp
@@ -1050,7 +1050,7 @@ RefPtr<ComputedStyle> old_style = ComputedStyle::Clone(target_object->StyleRef()); ComputedStyle* new_style = target_object->MutableStyle(); - new_style->SetHasCurrentTransformAnimation(); + new_style->SetHasCurrentTransformAnimation(true); target_paint_layer->UpdateTransform(old_style.Get(), *new_style); EXPECT_NE(nullptr, target_paint_layer->Transform());
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.h b/third_party/WebKit/Source/core/style/ComputedStyle.h index b5b5b928..ba4d918 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.h +++ b/third_party/WebKit/Source/core/style/ComputedStyle.h
@@ -1475,98 +1475,11 @@ SetEmptyStateInternal(b); } - bool HasInlineTransform() const { - return rare_non_inherited_data_->has_inline_transform_; - } - void SetHasInlineTransform(bool b) { - SET_VAR(rare_non_inherited_data_, has_inline_transform_, b); - } - - bool HasCompositorProxy() const { - return rare_non_inherited_data_->has_compositor_proxy_; - } - void SetHasCompositorProxy(bool b) { - SET_VAR(rare_non_inherited_data_, has_compositor_proxy_, b); - } - - bool RequiresAcceleratedCompositingForExternalReasons(bool b) { - return rare_non_inherited_data_ - ->requires_accelerated_compositing_for_external_reasons_; - } - void SetRequiresAcceleratedCompositingForExternalReasons(bool b) { - SET_VAR(rare_non_inherited_data_, - requires_accelerated_compositing_for_external_reasons_, b); - } - - bool HasAuthorBackground() const { - return rare_non_inherited_data_->has_author_background_; - }; - void SetHasAuthorBackground(bool author_background) { - SET_VAR(rare_non_inherited_data_, has_author_background_, - author_background); - } - - bool HasAuthorBorder() const { - return rare_non_inherited_data_->has_author_border_; - }; - void SetHasAuthorBorder(bool author_border) { - SET_VAR(rare_non_inherited_data_, has_author_border_, author_border); - } - - // A stacking context is painted atomically and defines a stacking order, - // whereas a containing stacking context defines in which order the stacking - // contexts below are painted. - // See CSS 2.1, Appendix E (https://www.w3.org/TR/CSS21/zindex.html) for more - // details. - bool IsStackingContext() const { - return rare_non_inherited_data_->is_stacking_context_; - } - void SetIsStackingContext(bool b) { - SET_VAR(rare_non_inherited_data_, is_stacking_context_, b); - } - float TextAutosizingMultiplier() const { return TextAutosizingMultiplierInternal(); } void SetTextAutosizingMultiplier(float); - bool SelfOrAncestorHasDirAutoAttribute() const { - return SelfOrAncestorHasDirAutoAttributeInternal(); - } - void SetSelfOrAncestorHasDirAutoAttribute(bool v) { - SetSelfOrAncestorHasDirAutoAttributeInternal(v); - } - - // Animation flags. - bool HasCurrentOpacityAnimation() const { - return rare_non_inherited_data_->has_current_opacity_animation_; - } - void SetHasCurrentOpacityAnimation(bool b = true) { - SET_VAR(rare_non_inherited_data_, has_current_opacity_animation_, b); - } - - bool HasCurrentTransformAnimation() const { - return rare_non_inherited_data_->has_current_transform_animation_; - } - void SetHasCurrentTransformAnimation(bool b = true) { - SET_VAR(rare_non_inherited_data_, has_current_transform_animation_, b); - } - - bool HasCurrentFilterAnimation() const { - return rare_non_inherited_data_->has_current_filter_animation_; - } - void SetHasCurrentFilterAnimation(bool b = true) { - SET_VAR(rare_non_inherited_data_, has_current_filter_animation_, b); - } - - bool HasCurrentBackdropFilterAnimation() const { - return rare_non_inherited_data_->has_current_backdrop_filter_animation_; - } - void SetHasCurrentBackdropFilterAnimation(bool b = true) { - SET_VAR(rare_non_inherited_data_, has_current_backdrop_filter_animation_, - b); - } - // Column utility functions. void ClearMultiCol(); bool SpecifiesColumns() const {
diff --git a/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp b/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp index 1d4a738d6..264a3a1 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp +++ b/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp
@@ -96,7 +96,7 @@ UpdatePropertySpecificDifferencesRespectsTransformAnimation) { RefPtr<ComputedStyle> style = ComputedStyle::Create(); RefPtr<ComputedStyle> other = ComputedStyle::Clone(*style); - other->SetHasCurrentTransformAnimation(); + other->SetHasCurrentTransformAnimation(true); StyleDifference diff; style->UpdatePropertySpecificDifferences(*other, diff); EXPECT_TRUE(diff.TransformChanged());
diff --git a/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp b/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp index 36cdc7d..f56345c8 100644 --- a/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp +++ b/third_party/WebKit/Source/core/svg/SVGElementProxy.cpp
@@ -136,8 +136,7 @@ void SVGElementProxy::Resolve(Document& document) { if (is_local_ || id_.IsEmpty() || url_.IsEmpty()) return; - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::css; FetchParameters params(ResourceRequest(url_), options); document_ = DocumentResource::FetchSVGDocument(params, document.Fetcher());
diff --git a/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp b/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp index 1901564..b8d3495d5 100644 --- a/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
@@ -71,8 +71,7 @@ } void SVGFEImageElement::FetchImageResource() { - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = localName(); FetchParameters params( ResourceRequest(GetDocument().CompleteURL(HrefString())), options);
diff --git a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp index 32d7fceb..ef50bde 100644 --- a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
@@ -211,8 +211,8 @@ (resource_ && EqualIgnoringFragmentIdentifier(resolved_url, resource_->Url()))) return; - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + + ResourceLoaderOptions options; options.initiator_info.name = localName(); FetchParameters params(ResourceRequest(resolved_url), options); SetDocumentResource(
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp index 88d2ae7..f737b142 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp
@@ -51,12 +51,17 @@ return false; WebURLRequest::FetchRequestMode fetch_request_mode = - script_url.ProtocolIsData() ? WebURLRequest::kFetchRequestModeNoCORS - : WebURLRequest::kFetchRequestModeSameOrigin; + WebURLRequest::kFetchRequestModeSameOrigin; + WebURLRequest::FetchCredentialsMode fetch_credentials_mode = + WebURLRequest::kFetchCredentialsModeSameOrigin; + if (script_url.ProtocolIsData()) { + fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; + fetch_credentials_mode = WebURLRequest::kFetchCredentialsModeInclude; + } script_loader_ = WorkerScriptLoader::Create(); script_loader_->LoadAsynchronously( - *context, script_url, fetch_request_mode, + *context, script_url, fetch_request_mode, fetch_credentials_mode, context->GetSecurityContext().AddressSpace(), WTF::Bind(&InProcessWorkerBase::OnResponse, WrapPersistent(this)), WTF::Bind(&InProcessWorkerBase::OnFinished, WrapPersistent(this)));
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp index 2aa06faa..f080592 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -194,7 +194,7 @@ RefPtr<WorkerScriptLoader> script_loader(WorkerScriptLoader::Create()); script_loader->SetRequestContext(WebURLRequest::kRequestContextScript); script_loader->LoadSynchronously( - execution_context, complete_url, WebURLRequest::kFetchRequestModeNoCORS, + execution_context, complete_url, execution_context.GetSecurityContext().AddressSpace()); // If the fetching attempt failed, throw a NetworkError exception and
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp index 8493752..2e0e5139 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
@@ -38,6 +38,7 @@ #include "platform/HTTPNames.h" #include "platform/loader/fetch/ResourceLoaderOptions.h" #include "platform/loader/fetch/ResourceResponse.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/network/ContentSecurityPolicyResponseHeaders.h" #include "platform/network/NetworkUtils.h" #include "platform/weborigin/SecurityOrigin.h" @@ -65,22 +66,22 @@ void WorkerScriptLoader::LoadSynchronously( ExecutionContext& execution_context, const KURL& url, - WebURLRequest::FetchRequestMode fetch_request_mode, WebAddressSpace creation_address_space) { url_ = url; execution_context_ = &execution_context; ResourceRequest request(CreateResourceRequest(creation_address_space)); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeInclude); + SECURITY_DCHECK(execution_context.IsWorkerGlobalScope()); ThreadableLoaderOptions options; - options.fetch_request_mode = fetch_request_mode; + options.fetch_request_mode = WebURLRequest::kFetchRequestModeNoCORS; // FIXME: Should we add EnforceScriptSrcDirective here? options.content_security_policy_enforcement = kDoNotEnforceContentSecurityPolicy; - ResourceLoaderOptions resource_loader_options( - kAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; WorkerThreadableLoader::LoadResourceSynchronously( ToWorkerGlobalScope(execution_context), request, *this, options, @@ -91,6 +92,7 @@ ExecutionContext& execution_context, const KURL& url, WebURLRequest::FetchRequestMode fetch_request_mode, + WebURLRequest::FetchCredentialsMode fetch_credentials_mode, WebAddressSpace creation_address_space, std::unique_ptr<WTF::Closure> response_callback, std::unique_ptr<WTF::Closure> finished_callback) { @@ -101,11 +103,12 @@ execution_context_ = &execution_context; ResourceRequest request(CreateResourceRequest(creation_address_space)); + request.SetFetchCredentialsMode(fetch_credentials_mode); + ThreadableLoaderOptions options; options.fetch_request_mode = fetch_request_mode; - ResourceLoaderOptions resource_loader_options( - kAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; // During create, callbacks may happen which could remove the last reference // to this object, while some of the callchain assumes that the client and @@ -180,12 +183,12 @@ if (!decoder_) { if (!response_encoding_.IsEmpty()) { - decoder_ = - TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - WTF::TextEncoding(response_encoding_)); + decoder_ = TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + WTF::TextEncoding(response_encoding_))); } else { - decoder_ = TextResourceDecoder::Create( - TextResourceDecoder::kPlainTextContent, UTF8Encoding()); + decoder_ = TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, UTF8Encoding())); } }
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h index fb8f4a4..9dea16d 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
@@ -62,13 +62,13 @@ void LoadSynchronously(ExecutionContext&, const KURL&, - WebURLRequest::FetchRequestMode, WebAddressSpace); // Note that callbacks could be invoked before loadAsynchronously() returns. void LoadAsynchronously(ExecutionContext&, const KURL&, WebURLRequest::FetchRequestMode, + WebURLRequest::FetchCredentialsMode, WebAddressSpace, std::unique_ptr<WTF::Closure> response_callback, std::unique_ptr<WTF::Closure> finished_callback);
diff --git a/third_party/WebKit/Source/core/xml/XSLImportRule.cpp b/third_party/WebKit/Source/core/xml/XSLImportRule.cpp index 883df75..e218b102 100644 --- a/third_party/WebKit/Source/core/xml/XSLImportRule.cpp +++ b/third_party/WebKit/Source/core/xml/XSLImportRule.cpp
@@ -88,8 +88,7 @@ return; } - ResourceLoaderOptions fetch_options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions fetch_options; fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml; FetchParameters params(ResourceRequest(owner_document->CompleteURL(abs_href)), fetch_options);
diff --git a/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp b/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp index f64bed106..64c5e0b6a 100644 --- a/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp +++ b/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -105,8 +105,7 @@ reinterpret_cast<const char*>(uri)); xmlFree(base); - ResourceLoaderOptions fetch_options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions fetch_options; fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml; FetchParameters params(ResourceRequest(url), fetch_options); params.SetOriginRestriction(FetchParameters::kRestrictToSameOrigin);
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index ba99c44..e362be8 100644 --- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -646,8 +646,7 @@ Document* document = XMLDocumentParserScope::current_document_; XMLDocumentParserScope scope(0); // FIXME: We should restore the original global error handler as well. - ResourceLoaderOptions options(kAllowStoredCredentials, - kClientRequestedCredentials); + ResourceLoaderOptions options; options.initiator_info.name = FetchInitiatorTypeNames::xml; FetchParameters params(ResourceRequest(url), options); Resource* resource =
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index 4996a56..354559b9 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
@@ -71,6 +71,7 @@ #include "platform/loader/fetch/ResourceError.h" #include "platform/loader/fetch/ResourceLoaderOptions.h" #include "platform/loader/fetch/ResourceRequest.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/network/HTTPParsers.h" #include "platform/network/NetworkLog.h" #include "platform/network/ParsedContentType.h" @@ -969,15 +970,7 @@ same_origin_request_ = GetSecurityOrigin()->CanRequestNoSuborigin(url_); - // Per https://w3c.github.io/webappsec-suborigins/#security-model-opt-outs, - // credentials are forced when credentials mode is "same-origin", the - // 'unsafe-credentials' option is set, and the request's physical origin is - // the same as the URL's. - bool include_credentials = - GetSecurityOrigin()->HasSuboriginAndShouldAllowCredentialsFor(url_) || - with_credentials_; - - if (!same_origin_request_ && include_credentials) { + if (!same_origin_request_ && with_credentials_) { UseCounter::Count(&execution_context, WebFeature::kXMLHttpRequestCrossOriginWithCredentials); } @@ -1024,15 +1017,7 @@ : kEnforceContentSecurityPolicy; options.timeout_milliseconds = timeout_milliseconds_; - StoredCredentials allow_credentials = - (same_origin_request_ || include_credentials) - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; - CredentialRequest credentials_requested = - with_credentials_ ? kClientRequestedCredentials - : kClientDidNotRequestCredentials; - ResourceLoaderOptions resource_loader_options(allow_credentials, - credentials_requested); + ResourceLoaderOptions resource_loader_options; resource_loader_options.security_origin = GetSecurityOrigin(); resource_loader_options.initiator_info.name = FetchInitiatorTypeNames::xmlhttprequest; @@ -1713,35 +1698,35 @@ std::unique_ptr<TextResourceDecoder> XMLHttpRequest::CreateDecoder() const { if (response_type_code_ == kResponseTypeJSON) { - return TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - UTF8Encoding()); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, UTF8Encoding())); } if (!final_response_charset_.IsEmpty()) { - return TextResourceDecoder::Create( - TextResourceDecoder::kPlainTextContent, - WTF::TextEncoding(final_response_charset_)); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, + WTF::TextEncoding(final_response_charset_))); } // allow TextResourceDecoder to look inside the m_response if it's XML or HTML if (ResponseIsXML()) { - std::unique_ptr<TextResourceDecoder> decoder = - TextResourceDecoder::Create(TextResourceDecoder::kXMLContent); + TextResourceDecoderOptions options(TextResourceDecoderOptions::kXMLContent); + // Don't stop on encoding errors, unlike it is done for other kinds // of XML resources. This matches the behavior of previous WebKit // versions, Firefox and Opera. - decoder->UseLenientXMLDecoding(); + options.SetUseLenientXMLDecoding(); - return decoder; + return TextResourceDecoder::Create(options); } if (ResponseIsHTML()) { - return TextResourceDecoder::Create(TextResourceDecoder::kHTMLContent, - UTF8Encoding()); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kHTMLContent, UTF8Encoding())); } - return TextResourceDecoder::Create(TextResourceDecoder::kPlainTextContent, - UTF8Encoding()); + return TextResourceDecoder::Create(TextResourceDecoderOptions( + TextResourceDecoderOptions::kPlainTextContent, UTF8Encoding())); } void XMLHttpRequest::DidReceiveData(const char* data, unsigned len) {
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js index 099abf3..db085ea 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkItemView.js
@@ -28,9 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * @unrestricted - */ Network.NetworkItemView = class extends UI.TabbedPane { /** * @param {!SDK.NetworkRequest} request @@ -55,7 +52,7 @@ this.appendTab('eventSource', Common.UIString('EventStream'), new Network.EventSourceMessagesView(request)); } else { var responseView = new Network.RequestResponseView(request); - var previewView = new Network.RequestPreviewView(request, responseView); + var previewView = new Network.RequestPreviewView(request); this.appendTab('preview', Common.UIString('Preview'), previewView); this.appendTab('response', Common.UIString('Response'), responseView); } @@ -103,43 +100,3 @@ return this._request; } }; - -/** - * @unrestricted - */ -Network.RequestContentView = class extends Network.RequestView { - /** - * @param {!SDK.NetworkRequest} request - */ - constructor(request) { - super(request); - } - - /** - * @override - */ - wasShown() { - this._ensureInnerViewShown(); - } - - _ensureInnerViewShown() { - if (this._innerViewShowRequested) - return; - this._innerViewShowRequested = true; - - /** - * @param {?string} content - * @this {Network.RequestContentView} - */ - function callback(content) { - this._innerViewShowRequested = false; - this.contentLoaded(); - } - - this.request.requestContent().then(callback.bind(this)); - } - - contentLoaded() { - // Should be implemented by subclasses. - } -};
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestPreviewView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestPreviewView.js index c99d068..6ccb311d 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestPreviewView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestPreviewView.js
@@ -28,65 +28,14 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * @unrestricted - */ -Network.RequestPreviewView = class extends Network.RequestContentView { +Network.RequestPreviewView = class extends Network.RequestView { /** * @param {!SDK.NetworkRequest} request - * @param {!UI.Widget} responseView */ - constructor(request, responseView) { + constructor(request) { super(request); - this._responseView = responseView; - /** @type {?UI.Widget} */ - this._previewView = null; - } - - /** - * @override - */ - contentLoaded() { - if (!this.request.content && !this.request.contentError()) { - if (!this._emptyWidget) { - this._emptyWidget = this._createEmptyWidget(); - this._emptyWidget.show(this.element); - this._previewView = this._emptyWidget; - this._previewViewHandledForTest(this._previewView); - } - return; - } - if (this._emptyWidget) { - this._emptyWidget.detach(); - delete this._emptyWidget; - this._previewView = null; - } - - if (!this._previewView) - this._createPreviewView(handlePreviewView.bind(this)); - else - this._previewView.show(this.element); - - /** - * @param {!UI.Widget} view - * @this {Network.RequestPreviewView} - */ - function handlePreviewView(view) { - this._previewView = view; - view.show(this.element); - if (view instanceof UI.SimpleView) { - var toolbar = new UI.Toolbar('network-item-preview-toolbar', this.element); - for (var item of /** @type {!UI.SimpleView} */ (this._previewView).syncToolbarItems()) - toolbar.appendToolbarItem(item); - } - this._previewViewHandledForTest(view); - } - } - - /** - * @param {!UI.Widget} view - */ - _previewViewHandledForTest(view) { + /** @type {?Promise<!UI.Widget>} */ + this._previewViewPromise = null; } /** @@ -105,40 +54,66 @@ } /** - * @return {string} + * @param {string} content + * @param {string} mimeType + * @return {?UI.SearchableView} */ - _requestContent() { - var content = this.request.content; - return this.request.contentEncoded ? window.atob(content || '') : (content || ''); + _xmlView(content, mimeType) { + var parsedXML = Network.XMLView.parseXML(content, mimeType); + return parsedXML ? Network.XMLView.createSearchableView(parsedXML) : null; } /** - * @param {?Network.ParsedJSON} parsedJSON - * @return {?UI.SearchableView} + * @param {string} content + * @return {!Promise<?UI.SearchableView>} */ - _jsonView(parsedJSON) { + async _jsonView(content) { + // We support non-strict JSON parsing by parsing an AST tree which is why we offload it to a worker. + var parsedJSON = await Network.JSONView.parseJSON(content); if (!parsedJSON || typeof parsedJSON.data !== 'object') return null; return Network.JSONView.createSearchableView(/** @type {!Network.ParsedJSON} */ (parsedJSON)); } /** - * @return {?UI.SearchableView} + * @override */ - _xmlView() { - var parsedXML = Network.XMLView.parseXML(this._requestContent(), this.request.mimeType); - return parsedXML ? Network.XMLView.createSearchableView(parsedXML) : null; + wasShown() { + this._showPreviewView(); + } + + async _showPreviewView() { + if (!this._previewViewPromise) + this._previewViewPromise = this._createPreviewView(); + var previewView = await this._previewViewPromise; + if (this.element.contains(previewView.element)) + return; + + previewView.show(this.element); + + if (previewView instanceof UI.SimpleView) { + var toolbar = new UI.Toolbar('network-item-preview-toolbar', this.element); + for (var item of previewView.syncToolbarItems()) + toolbar.appendToolbarItem(item); + } } /** + * @param {!SDK.NetworkRequest.ContentData} contentData * @return {?Network.RequestHTMLView} */ - _htmlErrorPreview() { - var whitelist = ['text/html', 'text/plain', 'application/xhtml+xml']; - if (whitelist.indexOf(this.request.mimeType) === -1) + _htmlErrorPreview(contentData) { + // We can assume the status code has been set already because fetching contentData should wait for request to be + // finished. + if (!this.request.hasErrorStatusCode() && this.request.resourceType() !== Common.resourceTypes.XHR) return null; - var dataURL = this.request.asDataURL(); + var whitelist = new Set(['text/html', 'text/plain', 'application/xhtml+xml']); + if (!whitelist.has(this.request.mimeType)) + return null; + + var dataURL = Common.ContentProvider.contentAsDataURL( + contentData.content, this.request.mimeType, contentData.encoded, contentData.encoded ? 'utf-8' : null); if (dataURL === null) return null; @@ -146,47 +121,38 @@ } /** - * @param {function(!UI.Widget)} callback + * @return {!Promise<!UI.Widget>} */ - _createPreviewView(callback) { - if (this.request.contentError()) { - callback(this._createMessageView(Common.UIString('Failed to load response data'))); - return; - } + async _createPreviewView() { + var contentData = await this.request.contentData(); + if (contentData.error) + return this._createMessageView(Common.UIString('Failed to load response data')); - var xmlView = this._xmlView(); - if (xmlView) { - callback(xmlView); - return; - } + var content = contentData.content || ''; + if (contentData.encoded) + content = window.atob(content); + if (!content) + return this._createEmptyWidget(); - Network.JSONView.parseJSON(this._requestContent()).then(chooseView.bind(this)).then(callback); + var xmlView = this._xmlView(content, this.request.mimeType); + if (xmlView) + return xmlView; - /** - * @this {Network.RequestPreviewView} - * @param {?Network.ParsedJSON} jsonData - * @return {!UI.Widget} - */ - function chooseView(jsonData) { - if (jsonData) { - var jsonView = this._jsonView(jsonData); - if (jsonView) - return jsonView; - } + var jsonView = await this._jsonView(content); + if (jsonView) + return jsonView; - if (this.request.hasErrorStatusCode() || this.request.resourceType() === Common.resourceTypes.XHR) { - var htmlErrorPreview = this._htmlErrorPreview(); - if (htmlErrorPreview) - return htmlErrorPreview; - } + var htmlErrorPreview = this._htmlErrorPreview(contentData); + if (htmlErrorPreview) + return htmlErrorPreview; - if (this._responseView.sourceView) - return this._responseView.sourceView; + var sourceView = await Network.RequestResponseView.sourceViewForRequest(this.request); + if (sourceView) + return sourceView; - if (this.request.resourceType() === Common.resourceTypes.Other) - return this._createEmptyWidget(); + if (this.request.resourceType() === Common.resourceTypes.Other) + return this._createEmptyWidget(); - return Network.RequestView.nonSourceViewForRequest(this.request); - } + return Network.RequestView.nonSourceViewForRequest(this.request); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js index 5b8008b..2c2eeb5 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestResponseView.js
@@ -28,25 +28,36 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * @unrestricted - */ -Network.RequestResponseView = class extends Network.RequestContentView { +Network.RequestResponseView = class extends Network.RequestView { /** * @param {!SDK.NetworkRequest} request */ constructor(request) { super(request); + /** @type {?Promise<!UI.Widget>} */ + this._responseView = null; } - get sourceView() { - if (this._sourceView || !Network.RequestView.hasTextContent(this.request)) - return this._sourceView; + /** + * @param {!SDK.NetworkRequest} request + * @return {!Promise<?UI.SearchableView>} + */ + static async sourceViewForRequest(request) { + var sourceView = request[Network.RequestResponseView._sourceViewSymbol]; + if (sourceView !== undefined) + return sourceView; - var contentProvider = new Network.RequestResponseView.ContentProvider(this.request); - var highlighterType = this.request.resourceType().canonicalMimeType() || this.request.mimeType; - this._sourceView = SourceFrame.ResourceSourceFrame.createSearchableView(contentProvider, highlighterType); - return this._sourceView; + var contentData = await request.contentData(); + if (!Network.RequestView.hasTextContent(request, contentData)) { + request[Network.RequestResponseView._sourceViewSymbol] = null; + return null; + } + + var contentProvider = new Network.RequestResponseView.ContentProvider(request); + var highlighterType = request.resourceType().canonicalMimeType() || request.mimeType; + sourceView = SourceFrame.ResourceSourceFrame.createSearchableView(contentProvider, highlighterType); + request[Network.RequestResponseView._sourceViewSymbol] = sourceView; + return sourceView; } /** @@ -60,32 +71,35 @@ /** * @override */ - contentLoaded() { - if ((!this.request.content || !this.sourceView) && !this.request.contentError()) { - if (!this._emptyWidget) { - this._emptyWidget = this._createMessageView(Common.UIString('This request has no response data available.')); - this._emptyWidget.show(this.element); - } - } else { - if (this._emptyWidget) { - this._emptyWidget.detach(); - delete this._emptyWidget; - } + wasShown() { + this._showResponseView(); + } - if (this.request.content && this.sourceView) { - this.sourceView.show(this.element); - } else { - if (!this._errorView) - this._errorView = this._createMessageView(Common.UIString('Failed to load response data')); - this._errorView.show(this.element); - } - } + async _showResponseView() { + if (!this._responseView) + this._responseView = this._createResponseView(); + var responseView = await this._responseView; + if (this.element.contains(responseView.element)) + return; + + responseView.show(this.element); + } + + async _createResponseView() { + var contentData = await this.request.contentData(); + var sourceView = await Network.RequestResponseView.sourceViewForRequest(this.request); + if ((!contentData.content || !sourceView) && !contentData.error) + return this._createMessageView(Common.UIString('This request has no response data available.')); + if (contentData.content && sourceView) + return sourceView; + return this._createMessageView(Common.UIString('Failed to load response data')); } }; +Network.RequestResponseView._sourceViewSymbol = Symbol('RequestResponseSourceView'); + /** * @implements {Common.ContentProvider} - * @unrestricted */ Network.RequestResponseView.ContentProvider = class { /** @@ -115,16 +129,9 @@ * @override * @return {!Promise<?string>} */ - requestContent() { - /** - * @param {?string} content - * @this {Network.RequestResponseView.ContentProvider} - */ - function decodeContent(content) { - return this._request.contentEncoded ? window.atob(content || '') : content; - } - - return this._request.requestContent().then(decodeContent.bind(this)); + async requestContent() { + var contentData = await this._request.contentData(); + return contentData.encoded ? window.atob(contentData.content || '') : contentData.content; } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestView.js index 4c20859..bc5f9237 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestView.js
@@ -28,9 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * @unrestricted - */ Network.RequestView = class extends UI.VBox { /** * @param {!SDK.NetworkRequest} request @@ -44,13 +41,14 @@ /** * @param {!SDK.NetworkRequest} request + * @param {!SDK.NetworkRequest.ContentData} contentData * @return {boolean} */ - static hasTextContent(request) { + static hasTextContent(request, contentData) { if (request.resourceType().isTextType()) return true; - if (request.resourceType() === Common.resourceTypes.Other || request.hasErrorStatusCode()) - return !!request.content && !request.contentEncoded; + if (request.resourceType() === Common.resourceTypes.Other || contentData.error) + return !!contentData.content && !contentData.encoded; return false; }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.cpp b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.cpp index b0f9208b..4bb9d3da 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.cpp
@@ -45,10 +45,9 @@ return new AXARIAGrid(layout_object, ax_object_cache); } -bool AXARIAGrid::AddTableRowChild( - AXObjectImpl* child, - HeapHashSet<Member<AXObjectImpl>>& appended_rows, - unsigned& column_count) { +bool AXARIAGrid::AddTableRowChild(AXObject* child, + HeapHashSet<Member<AXObject>>& appended_rows, + unsigned& column_count) { if (!child || child->RoleValue() != kRowRole) return false; @@ -90,8 +89,8 @@ if (!layout_object_) return; - HeapVector<Member<AXObjectImpl>> children; - for (AXObjectImpl* child = RawFirstChild(); child; + HeapVector<Member<AXObject>> children; + for (AXObject* child = RawFirstChild(); child; child = child->RawNextSibling()) children.push_back(child); ComputeAriaOwnsChildren(children); @@ -99,7 +98,7 @@ AXObjectCacheImpl& ax_cache = AxObjectCache(); // Only add children that are actually rows. - HeapHashSet<Member<AXObjectImpl>> appended_rows; + HeapHashSet<Member<AXObject>> appended_rows; unsigned column_count = 0; for (const auto& child : children) { if (!AddTableRowChild(child, appended_rows, column_count)) { @@ -126,7 +125,7 @@ children_.push_back(column); } - AXObjectImpl* header_container_object = HeaderContainer(); + AXObject* header_container_object = HeaderContainer(); if (header_container_object && !header_container_object->AccessibilityIsIgnored()) children_.push_back(header_container_object);
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h index 82317b8..4a9cc7fb 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGrid.h
@@ -59,8 +59,8 @@ bool SupportsSelectedRows() override { return true; } bool IsTableExposableThroughAccessibility() const override { return true; } - bool AddTableRowChild(AXObjectImpl*, - HeapHashSet<Member<AXObjectImpl>>& appended_rows, + bool AddTableRowChild(AXObject*, + HeapHashSet<Member<AXObject>>& appended_rows, unsigned& column_count); };
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.cpp b/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.cpp index 2a37099..21fe2a9 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.cpp
@@ -55,8 +55,8 @@ return EqualIgnoringASCIICase(role, "rowheader"); } -AXObjectImpl* AXARIAGridCell::ParentTable() const { - AXObjectImpl* parent = ParentObjectUnignored(); +AXObject* AXARIAGridCell::ParentTable() const { + AXObject* parent = ParentObjectUnignored(); if (!parent) return 0; @@ -74,7 +74,7 @@ } void AXARIAGridCell::RowIndexRange(std::pair<unsigned, unsigned>& row_range) { - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (!parent) return; @@ -104,7 +104,7 @@ void AXARIAGridCell::ColumnIndexRange( std::pair<unsigned, unsigned>& column_range) { - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (!parent) return;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.h b/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.h index c1214a5..71eff986 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.h +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGridCell.h
@@ -54,7 +54,7 @@ protected: bool IsAriaColumnHeader() const; bool IsAriaRowHeader() const; - AXObjectImpl* ParentTable() const override; + AXObject* ParentTable() const override; }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXARIAGridRow.cpp b/third_party/WebKit/Source/modules/accessibility/AXARIAGridRow.cpp index 75b5906..092adf80 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXARIAGridRow.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXARIAGridRow.cpp
@@ -45,7 +45,7 @@ } bool AXARIAGridRow::IsARIATreeGridRow() const { - AXObjectImpl* parent = ParentTable(); + AXObject* parent = ParentTable(); if (!parent) return false;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp b/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp new file mode 100644 index 0000000..80bbd38e --- /dev/null +++ b/third_party/WebKit/Source/modules/accessibility/AXEnums.cpp
@@ -0,0 +1,254 @@ +// 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/accessibility/AXEnums.h" + +#include "core/HTMLElementTypeHelpers.h" +#include "core/dom/Element.h" +#include "core/dom/Node.h" +#include "platform/wtf/Assertions.h" +#include "platform/wtf/HashSet.h" +#include "platform/wtf/text/StringHash.h" +#include "platform/wtf/text/WTFString.h" +#include "public/web/WebAXEnums.h" + +namespace blink { + +STATIC_ASSERT_ENUM(kWebAXRoleAbbr, kAbbrRole); +STATIC_ASSERT_ENUM(kWebAXRoleAlertDialog, kAlertDialogRole); +STATIC_ASSERT_ENUM(kWebAXRoleAlert, kAlertRole); +STATIC_ASSERT_ENUM(kWebAXRoleAnchor, kAnchorRole); +STATIC_ASSERT_ENUM(kWebAXRoleAnnotation, kAnnotationRole); +STATIC_ASSERT_ENUM(kWebAXRoleApplication, kApplicationRole); +STATIC_ASSERT_ENUM(kWebAXRoleArticle, kArticleRole); +STATIC_ASSERT_ENUM(kWebAXRoleAudio, kAudioRole); +STATIC_ASSERT_ENUM(kWebAXRoleBanner, kBannerRole); +STATIC_ASSERT_ENUM(kWebAXRoleBlockquote, kBlockquoteRole); +STATIC_ASSERT_ENUM(kWebAXRoleBusyIndicator, kBusyIndicatorRole); +STATIC_ASSERT_ENUM(kWebAXRoleButton, kButtonRole); +STATIC_ASSERT_ENUM(kWebAXRoleCanvas, kCanvasRole); +STATIC_ASSERT_ENUM(kWebAXRoleCaption, kCaptionRole); +STATIC_ASSERT_ENUM(kWebAXRoleCell, kCellRole); +STATIC_ASSERT_ENUM(kWebAXRoleCheckBox, kCheckBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleColorWell, kColorWellRole); +STATIC_ASSERT_ENUM(kWebAXRoleColumnHeader, kColumnHeaderRole); +STATIC_ASSERT_ENUM(kWebAXRoleColumn, kColumnRole); +STATIC_ASSERT_ENUM(kWebAXRoleComboBox, kComboBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleComplementary, kComplementaryRole); +STATIC_ASSERT_ENUM(kWebAXRoleContentInfo, kContentInfoRole); +STATIC_ASSERT_ENUM(kWebAXRoleDate, kDateRole); +STATIC_ASSERT_ENUM(kWebAXRoleDateTime, kDateTimeRole); +STATIC_ASSERT_ENUM(kWebAXRoleDefinition, kDefinitionRole); +STATIC_ASSERT_ENUM(kWebAXRoleDescriptionListDetail, kDescriptionListDetailRole); +STATIC_ASSERT_ENUM(kWebAXRoleDescriptionList, kDescriptionListRole); +STATIC_ASSERT_ENUM(kWebAXRoleDescriptionListTerm, kDescriptionListTermRole); +STATIC_ASSERT_ENUM(kWebAXRoleDetails, kDetailsRole); +STATIC_ASSERT_ENUM(kWebAXRoleDialog, kDialogRole); +STATIC_ASSERT_ENUM(kWebAXRoleDirectory, kDirectoryRole); +STATIC_ASSERT_ENUM(kWebAXRoleDisclosureTriangle, kDisclosureTriangleRole); +STATIC_ASSERT_ENUM(kWebAXRoleDocument, kDocumentRole); +STATIC_ASSERT_ENUM(kWebAXRoleEmbeddedObject, kEmbeddedObjectRole); +STATIC_ASSERT_ENUM(kWebAXRoleFeed, kFeedRole); +STATIC_ASSERT_ENUM(kWebAXRoleFigcaption, kFigcaptionRole); +STATIC_ASSERT_ENUM(kWebAXRoleFigure, kFigureRole); +STATIC_ASSERT_ENUM(kWebAXRoleFooter, kFooterRole); +STATIC_ASSERT_ENUM(kWebAXRoleForm, kFormRole); +STATIC_ASSERT_ENUM(kWebAXRoleGenericContainer, kGenericContainerRole); +STATIC_ASSERT_ENUM(kWebAXRoleGrid, kGridRole); +STATIC_ASSERT_ENUM(kWebAXRoleGroup, kGroupRole); +STATIC_ASSERT_ENUM(kWebAXRoleHeading, kHeadingRole); +STATIC_ASSERT_ENUM(kWebAXRoleIframe, kIframeRole); +STATIC_ASSERT_ENUM(kWebAXRoleIframePresentational, kIframePresentationalRole); +STATIC_ASSERT_ENUM(kWebAXRoleIgnored, kIgnoredRole); +STATIC_ASSERT_ENUM(kWebAXRoleImageMapLink, kImageMapLinkRole); +STATIC_ASSERT_ENUM(kWebAXRoleImageMap, kImageMapRole); +STATIC_ASSERT_ENUM(kWebAXRoleImage, kImageRole); +STATIC_ASSERT_ENUM(kWebAXRoleInlineTextBox, kInlineTextBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleInputTime, kInputTimeRole); +STATIC_ASSERT_ENUM(kWebAXRoleLabel, kLabelRole); +STATIC_ASSERT_ENUM(kWebAXRoleLegend, kLegendRole); +STATIC_ASSERT_ENUM(kWebAXRoleLineBreak, kLineBreakRole); +STATIC_ASSERT_ENUM(kWebAXRoleLink, kLinkRole); +STATIC_ASSERT_ENUM(kWebAXRoleListBoxOption, kListBoxOptionRole); +STATIC_ASSERT_ENUM(kWebAXRoleListBox, kListBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleListItem, kListItemRole); +STATIC_ASSERT_ENUM(kWebAXRoleListMarker, kListMarkerRole); +STATIC_ASSERT_ENUM(kWebAXRoleList, kListRole); +STATIC_ASSERT_ENUM(kWebAXRoleLog, kLogRole); +STATIC_ASSERT_ENUM(kWebAXRoleMain, kMainRole); +STATIC_ASSERT_ENUM(kWebAXRoleMark, kMarkRole); +STATIC_ASSERT_ENUM(kWebAXRoleMarquee, kMarqueeRole); +STATIC_ASSERT_ENUM(kWebAXRoleMath, kMathRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuBar, kMenuBarRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuButton, kMenuButtonRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuItem, kMenuItemRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuItemCheckBox, kMenuItemCheckBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuItemRadio, kMenuItemRadioRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuListOption, kMenuListOptionRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenuListPopup, kMenuListPopupRole); +STATIC_ASSERT_ENUM(kWebAXRoleMenu, kMenuRole); +STATIC_ASSERT_ENUM(kWebAXRoleMeter, kMeterRole); +STATIC_ASSERT_ENUM(kWebAXRoleNavigation, kNavigationRole); +STATIC_ASSERT_ENUM(kWebAXRoleNone, kNoneRole); +STATIC_ASSERT_ENUM(kWebAXRoleNote, kNoteRole); +STATIC_ASSERT_ENUM(kWebAXRoleOutline, kOutlineRole); +STATIC_ASSERT_ENUM(kWebAXRoleParagraph, kParagraphRole); +STATIC_ASSERT_ENUM(kWebAXRolePopUpButton, kPopUpButtonRole); +STATIC_ASSERT_ENUM(kWebAXRolePre, kPreRole); +STATIC_ASSERT_ENUM(kWebAXRolePresentational, kPresentationalRole); +STATIC_ASSERT_ENUM(kWebAXRoleProgressIndicator, kProgressIndicatorRole); +STATIC_ASSERT_ENUM(kWebAXRoleRadioButton, kRadioButtonRole); +STATIC_ASSERT_ENUM(kWebAXRoleRadioGroup, kRadioGroupRole); +STATIC_ASSERT_ENUM(kWebAXRoleRegion, kRegionRole); +STATIC_ASSERT_ENUM(kWebAXRoleRootWebArea, kRootWebAreaRole); +STATIC_ASSERT_ENUM(kWebAXRoleRowHeader, kRowHeaderRole); +STATIC_ASSERT_ENUM(kWebAXRoleRow, kRowRole); +STATIC_ASSERT_ENUM(kWebAXRoleRuby, kRubyRole); +STATIC_ASSERT_ENUM(kWebAXRoleRuler, kRulerRole); +STATIC_ASSERT_ENUM(kWebAXRoleSVGRoot, kSVGRootRole); +STATIC_ASSERT_ENUM(kWebAXRoleScrollArea, kScrollAreaRole); +STATIC_ASSERT_ENUM(kWebAXRoleScrollBar, kScrollBarRole); +STATIC_ASSERT_ENUM(kWebAXRoleSeamlessWebArea, kSeamlessWebAreaRole); +STATIC_ASSERT_ENUM(kWebAXRoleSearch, kSearchRole); +STATIC_ASSERT_ENUM(kWebAXRoleSearchBox, kSearchBoxRole); +STATIC_ASSERT_ENUM(kWebAXRoleSlider, kSliderRole); +STATIC_ASSERT_ENUM(kWebAXRoleSliderThumb, kSliderThumbRole); +STATIC_ASSERT_ENUM(kWebAXRoleSpinButtonPart, kSpinButtonPartRole); +STATIC_ASSERT_ENUM(kWebAXRoleSpinButton, kSpinButtonRole); +STATIC_ASSERT_ENUM(kWebAXRoleSplitter, kSplitterRole); +STATIC_ASSERT_ENUM(kWebAXRoleStaticText, kStaticTextRole); +STATIC_ASSERT_ENUM(kWebAXRoleStatus, kStatusRole); +STATIC_ASSERT_ENUM(kWebAXRoleSwitch, kSwitchRole); +STATIC_ASSERT_ENUM(kWebAXRoleTabGroup, kTabGroupRole); +STATIC_ASSERT_ENUM(kWebAXRoleTabList, kTabListRole); +STATIC_ASSERT_ENUM(kWebAXRoleTabPanel, kTabPanelRole); +STATIC_ASSERT_ENUM(kWebAXRoleTab, kTabRole); +STATIC_ASSERT_ENUM(kWebAXRoleTableHeaderContainer, kTableHeaderContainerRole); +STATIC_ASSERT_ENUM(kWebAXRoleTable, kTableRole); +STATIC_ASSERT_ENUM(kWebAXRoleTerm, kTermRole); +STATIC_ASSERT_ENUM(kWebAXRoleTextField, kTextFieldRole); +STATIC_ASSERT_ENUM(kWebAXRoleTime, kTimeRole); +STATIC_ASSERT_ENUM(kWebAXRoleTimer, kTimerRole); +STATIC_ASSERT_ENUM(kWebAXRoleToggleButton, kToggleButtonRole); +STATIC_ASSERT_ENUM(kWebAXRoleToolbar, kToolbarRole); +STATIC_ASSERT_ENUM(kWebAXRoleTreeGrid, kTreeGridRole); +STATIC_ASSERT_ENUM(kWebAXRoleTreeItem, kTreeItemRole); +STATIC_ASSERT_ENUM(kWebAXRoleTree, kTreeRole); +STATIC_ASSERT_ENUM(kWebAXRoleUnknown, kUnknownRole); +STATIC_ASSERT_ENUM(kWebAXRoleUserInterfaceTooltip, kUserInterfaceTooltipRole); +STATIC_ASSERT_ENUM(kWebAXRoleVideo, kVideoRole); +STATIC_ASSERT_ENUM(kWebAXRoleWebArea, kWebAreaRole); +STATIC_ASSERT_ENUM(kWebAXRoleWindow, kWindowRole); + +STATIC_ASSERT_ENUM(kWebAXStateBusy, kAXBusyState); +STATIC_ASSERT_ENUM(kWebAXStateEnabled, kAXEnabledState); +STATIC_ASSERT_ENUM(kWebAXStateExpanded, kAXExpandedState); +STATIC_ASSERT_ENUM(kWebAXStateFocusable, kAXFocusableState); +STATIC_ASSERT_ENUM(kWebAXStateFocused, kAXFocusedState); +STATIC_ASSERT_ENUM(kWebAXStateHaspopup, kAXHaspopupState); +STATIC_ASSERT_ENUM(kWebAXStateHovered, kAXHoveredState); +STATIC_ASSERT_ENUM(kWebAXStateInvisible, kAXInvisibleState); +STATIC_ASSERT_ENUM(kWebAXStateLinked, kAXLinkedState); +STATIC_ASSERT_ENUM(kWebAXStateMultiline, kAXMultilineState); +STATIC_ASSERT_ENUM(kWebAXStateMultiselectable, kAXMultiselectableState); +STATIC_ASSERT_ENUM(kWebAXStateOffscreen, kAXOffscreenState); +STATIC_ASSERT_ENUM(kWebAXStateProtected, kAXProtectedState); +STATIC_ASSERT_ENUM(kWebAXStateReadonly, kAXReadonlyState); +STATIC_ASSERT_ENUM(kWebAXStateRequired, kAXRequiredState); +STATIC_ASSERT_ENUM(kWebAXStateSelectable, kAXSelectableState); +STATIC_ASSERT_ENUM(kWebAXStateSelected, kAXSelectedState); +STATIC_ASSERT_ENUM(kWebAXStateVertical, kAXVerticalState); +STATIC_ASSERT_ENUM(kWebAXStateVisited, kAXVisitedState); + +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kNone, AXDefaultActionVerb::kNone); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kActivate, + AXDefaultActionVerb::kActivate); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kCheck, AXDefaultActionVerb::kCheck); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kClick, AXDefaultActionVerb::kClick); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kJump, AXDefaultActionVerb::kJump); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kOpen, AXDefaultActionVerb::kOpen); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kPress, AXDefaultActionVerb::kPress); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kSelect, + AXDefaultActionVerb::kSelect); +STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kUncheck, + AXDefaultActionVerb::kUncheck); + +STATIC_ASSERT_ENUM(kWebAXTextDirectionLR, kAccessibilityTextDirectionLTR); +STATIC_ASSERT_ENUM(kWebAXTextDirectionRL, kAccessibilityTextDirectionRTL); +STATIC_ASSERT_ENUM(kWebAXTextDirectionTB, kAccessibilityTextDirectionTTB); +STATIC_ASSERT_ENUM(kWebAXTextDirectionBT, kAccessibilityTextDirectionBTT); + +STATIC_ASSERT_ENUM(kWebAXSortDirectionUndefined, kSortDirectionUndefined); +STATIC_ASSERT_ENUM(kWebAXSortDirectionNone, kSortDirectionNone); +STATIC_ASSERT_ENUM(kWebAXSortDirectionAscending, kSortDirectionAscending); +STATIC_ASSERT_ENUM(kWebAXSortDirectionDescending, kSortDirectionDescending); +STATIC_ASSERT_ENUM(kWebAXSortDirectionOther, kSortDirectionOther); + +STATIC_ASSERT_ENUM(kWebAXExpandedUndefined, kExpandedUndefined); +STATIC_ASSERT_ENUM(kWebAXExpandedCollapsed, kExpandedCollapsed); +STATIC_ASSERT_ENUM(kWebAXExpandedExpanded, kExpandedExpanded); + +STATIC_ASSERT_ENUM(kWebAXOrientationUndefined, + kAccessibilityOrientationUndefined); +STATIC_ASSERT_ENUM(kWebAXOrientationVertical, + kAccessibilityOrientationVertical); +STATIC_ASSERT_ENUM(kWebAXOrientationHorizontal, + kAccessibilityOrientationHorizontal); + +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateUndefined, kAriaCurrentStateUndefined); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateFalse, kAriaCurrentStateFalse); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateTrue, kAriaCurrentStateTrue); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStatePage, kAriaCurrentStatePage); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateStep, kAriaCurrentStateStep); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateLocation, kAriaCurrentStateLocation); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateDate, kAriaCurrentStateDate); +STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateTime, kAriaCurrentStateTime); + +STATIC_ASSERT_ENUM(kWebAXInvalidStateUndefined, kInvalidStateUndefined); +STATIC_ASSERT_ENUM(kWebAXInvalidStateFalse, kInvalidStateFalse); +STATIC_ASSERT_ENUM(kWebAXInvalidStateTrue, kInvalidStateTrue); +STATIC_ASSERT_ENUM(kWebAXInvalidStateSpelling, kInvalidStateSpelling); +STATIC_ASSERT_ENUM(kWebAXInvalidStateGrammar, kInvalidStateGrammar); +STATIC_ASSERT_ENUM(kWebAXInvalidStateOther, kInvalidStateOther); + +STATIC_ASSERT_ENUM(kWebAXTextStyleNone, kTextStyleNone); +STATIC_ASSERT_ENUM(kWebAXTextStyleBold, kTextStyleBold); +STATIC_ASSERT_ENUM(kWebAXTextStyleItalic, kTextStyleItalic); +STATIC_ASSERT_ENUM(kWebAXTextStyleUnderline, kTextStyleUnderline); +STATIC_ASSERT_ENUM(kWebAXTextStyleLineThrough, kTextStyleLineThrough); + +STATIC_ASSERT_ENUM(kWebAXNameFromUninitialized, kAXNameFromUninitialized); +STATIC_ASSERT_ENUM(kWebAXNameFromAttribute, kAXNameFromAttribute); +STATIC_ASSERT_ENUM(kWebAXNameFromAttributeExplicitlyEmpty, + kAXNameFromAttributeExplicitlyEmpty); +STATIC_ASSERT_ENUM(kWebAXNameFromCaption, kAXNameFromCaption); +STATIC_ASSERT_ENUM(kWebAXNameFromContents, kAXNameFromContents); +STATIC_ASSERT_ENUM(kWebAXNameFromPlaceholder, kAXNameFromPlaceholder); +STATIC_ASSERT_ENUM(kWebAXNameFromRelatedElement, kAXNameFromRelatedElement); +STATIC_ASSERT_ENUM(kWebAXNameFromValue, kAXNameFromValue); +STATIC_ASSERT_ENUM(kWebAXNameFromTitle, kAXNameFromTitle); + +STATIC_ASSERT_ENUM(kWebAXDescriptionFromUninitialized, + kAXDescriptionFromUninitialized); +STATIC_ASSERT_ENUM(kWebAXDescriptionFromAttribute, kAXDescriptionFromAttribute); +STATIC_ASSERT_ENUM(kWebAXDescriptionFromContents, kAXDescriptionFromContents); +STATIC_ASSERT_ENUM(kWebAXDescriptionFromRelatedElement, + kAXDescriptionFromRelatedElement); + +STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaKeyShortcuts, + AXStringAttribute::kAriaKeyShortcuts); +STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaRoleDescription, + AXStringAttribute::kAriaRoleDescription); +STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaActiveDescendant, + AXObjectAttribute::kAriaActiveDescendant); +STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaErrorMessage, + AXObjectAttribute::kAriaErrorMessage); +STATIC_ASSERT_ENUM(WebAXObjectVectorAttribute::kAriaControls, + AXObjectVectorAttribute::kAriaControls); +STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaDetails, + AXObjectAttribute::kAriaDetails); +STATIC_ASSERT_ENUM(WebAXObjectVectorAttribute::kAriaFlowTo, + AXObjectVectorAttribute::kAriaFlowTo); +#undef STATIC_ASSERT_ENUM +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXEnums.h b/third_party/WebKit/Source/modules/accessibility/AXEnums.h new file mode 100644 index 0000000..da80528b --- /dev/null +++ b/third_party/WebKit/Source/modules/accessibility/AXEnums.h
@@ -0,0 +1,285 @@ +// 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 AXEnums_h +#define AXEnums_h + +#include "core/CoreExport.h" + +namespace blink { + +enum AccessibilityRole { + kUnknownRole = 0, // Not mapped in platform APIs, generally indicates a bug + kAbbrRole, // No mapping to ARIA role. + kAlertDialogRole, + kAlertRole, + kAnchorRole, // No mapping to ARIA role. + kAnnotationRole, // No mapping to ARIA role. + kApplicationRole, + kArticleRole, + kAudioRole, // No mapping to ARIA role. + kBannerRole, + kBlockquoteRole, // No mapping to ARIA role. + kBusyIndicatorRole, // No mapping to ARIA role. + kButtonRole, + kCanvasRole, // No mapping to ARIA role. + kCaptionRole, // No mapping to ARIA role. + kCellRole, + kCheckBoxRole, + kColorWellRole, // No mapping to ARIA role. + kColumnHeaderRole, + kColumnRole, // No mapping to ARIA role. + kComboBoxRole, + kComplementaryRole, + kContentInfoRole, + kDateRole, // No mapping to ARIA role. + kDateTimeRole, // No mapping to ARIA role. + kDefinitionRole, + kDescriptionListDetailRole, // No mapping to ARIA role. + kDescriptionListRole, // No mapping to ARIA role. + kDescriptionListTermRole, // No mapping to ARIA role. + kDetailsRole, // No mapping to ARIA role. + kDialogRole, + kDirectoryRole, + kDisclosureTriangleRole, // No mapping to ARIA role. + kDocumentRole, + kEmbeddedObjectRole, // No mapping to ARIA role. + kFeedRole, + kFigcaptionRole, // No mapping to ARIA role. + kFigureRole, + kFooterRole, + kFormRole, + kGenericContainerRole, // No role was defined for this container + kGridRole, + kGroupRole, + kHeadingRole, + kIframePresentationalRole, // No mapping to ARIA role. + kIframeRole, // No mapping to ARIA role. + kIgnoredRole, // No mapping to ARIA role. + kImageMapLinkRole, // No mapping to ARIA role. + kImageMapRole, // No mapping to ARIA role. + kImageRole, + kInlineTextBoxRole, // No mapping to ARIA role. + kInputTimeRole, // No mapping to ARIA role. + kLabelRole, + kLegendRole, // No mapping to ARIA role. + kLineBreakRole, // No mapping to ARIA role. + kLinkRole, + kListBoxOptionRole, + kListBoxRole, + kListItemRole, + kListMarkerRole, // No mapping to ARIA role. + kListRole, + kLogRole, + kMainRole, + kMarkRole, // No mapping to ARIA role. + kMarqueeRole, + kMathRole, + kMenuBarRole, + kMenuButtonRole, + kMenuItemRole, + kMenuItemCheckBoxRole, + kMenuItemRadioRole, + kMenuListOptionRole, + kMenuListPopupRole, + kMenuRole, + kMeterRole, + kNavigationRole, + kNoneRole, // ARIA role of "none" + kNoteRole, + kOutlineRole, // No mapping to ARIA role. + kParagraphRole, // No mapping to ARIA role. + kPopUpButtonRole, + kPreRole, // No mapping to ARIA role. + kPresentationalRole, + kProgressIndicatorRole, + kRadioButtonRole, + kRadioGroupRole, + kRegionRole, + kRootWebAreaRole, // No mapping to ARIA role. + kRowHeaderRole, + kRowRole, + kRubyRole, // No mapping to ARIA role. + kRulerRole, // No mapping to ARIA role. + kSVGRootRole, // No mapping to ARIA role. + kScrollAreaRole, // No mapping to ARIA role. + kScrollBarRole, + kSeamlessWebAreaRole, // No mapping to ARIA role. + kSearchRole, + kSearchBoxRole, + kSliderRole, + kSliderThumbRole, // No mapping to ARIA role. + kSpinButtonPartRole, // No mapping to ARIA role. + kSpinButtonRole, + kSplitterRole, + kStaticTextRole, // No mapping to ARIA role. + kStatusRole, + kSwitchRole, + kTabGroupRole, // No mapping to ARIA role. + kTabListRole, + kTabPanelRole, + kTabRole, + kTableHeaderContainerRole, // No mapping to ARIA role. + kTableRole, + kTermRole, + kTextFieldRole, + kTimeRole, // No mapping to ARIA role. + kTimerRole, + kToggleButtonRole, + kToolbarRole, + kTreeGridRole, + kTreeItemRole, + kTreeRole, + kUserInterfaceTooltipRole, + kVideoRole, // No mapping to ARIA role. + kWebAreaRole, // No mapping to ARIA role. + kWindowRole, // No mapping to ARIA role. + kNumRoles +}; + +enum AccessibilityState { + kAXBusyState, + kAXEnabledState, + kAXExpandedState, + kAXFocusableState, + kAXFocusedState, + kAXHaspopupState, + kAXHoveredState, + kAXInvisibleState, + kAXLinkedState, + kAXMultilineState, + kAXMultiselectableState, + kAXOffscreenState, + kAXProtectedState, + kAXReadonlyState, + kAXRequiredState, + kAXSelectableState, + kAXSelectedState, + kAXVerticalState, + kAXVisitedState +}; + +enum AccessibilityOrientation { + kAccessibilityOrientationUndefined = 0, + kAccessibilityOrientationVertical, + kAccessibilityOrientationHorizontal, +}; + +enum class AXDefaultActionVerb { + kNone = 0, + kActivate, + kCheck, + kClick, + kJump, + kOpen, + kPress, + kSelect, + kUncheck +}; + +enum class AXSupportedAction { + kNone = 0, + kActivate, + kCheck, + kClick, + kJump, + kOpen, + kPress, + kSelect, + kUncheck +}; + +enum AccessibilityTextDirection { + kAccessibilityTextDirectionLTR, + kAccessibilityTextDirectionRTL, + kAccessibilityTextDirectionTTB, + kAccessibilityTextDirectionBTT +}; + +enum SortDirection { + kSortDirectionUndefined = 0, + kSortDirectionNone, + kSortDirectionAscending, + kSortDirectionDescending, + kSortDirectionOther +}; + +enum AccessibilityExpanded { + kExpandedUndefined = 0, + kExpandedCollapsed, + kExpandedExpanded, +}; + +enum AriaCurrentState { + kAriaCurrentStateUndefined = 0, + kAriaCurrentStateFalse, + kAriaCurrentStateTrue, + kAriaCurrentStatePage, + kAriaCurrentStateStep, + kAriaCurrentStateLocation, + kAriaCurrentStateDate, + kAriaCurrentStateTime +}; + +enum InvalidState { + kInvalidStateUndefined = 0, + kInvalidStateFalse, + kInvalidStateTrue, + kInvalidStateSpelling, + kInvalidStateGrammar, + kInvalidStateOther +}; + +enum TextStyle { + kTextStyleNone = 0, + kTextStyleBold = 1 << 0, + kTextStyleItalic = 1 << 1, + kTextStyleUnderline = 1 << 2, + kTextStyleLineThrough = 1 << 3 +}; + +enum class AXStringAttribute { + kAriaKeyShortcuts, + kAriaRoleDescription, +}; + +enum class AXObjectAttribute { + kAriaActiveDescendant, + kAriaDetails, + kAriaErrorMessage, +}; + +enum class AXObjectVectorAttribute { + kAriaControls, + kAriaFlowTo, +}; + +// The source of the accessible name of an element. This is needed +// because on some platforms this determines how the accessible name +// is exposed. +enum AXNameFrom { + kAXNameFromUninitialized = -1, + kAXNameFromAttribute = 0, + kAXNameFromAttributeExplicitlyEmpty, + kAXNameFromCaption, + kAXNameFromContents, + kAXNameFromPlaceholder, + kAXNameFromRelatedElement, + kAXNameFromValue, + kAXNameFromTitle, +}; + +// The source of the accessible description of an element. This is needed +// because on some platforms this determines how the accessible description +// is exposed. +enum AXDescriptionFrom { + kAXDescriptionFromUninitialized = -1, + kAXDescriptionFromAttribute = 0, + kAXDescriptionFromContents, + kAXDescriptionFromRelatedElement, +}; + +} // namespace blink + +#endif // AXEnums_h
diff --git a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp index fcfa4ab73..b8bca55 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp
@@ -57,7 +57,7 @@ return Traversal<HTMLMapElement>::FirstAncestor(*area); } -AXObjectImpl* AXImageMapLink::ComputeParent() const { +AXObject* AXImageMapLink::ComputeParent() const { DCHECK(!IsDetached()); if (parent_) return parent_; @@ -72,7 +72,7 @@ const AtomicString& aria_role = GetAOMPropertyOrARIAAttribute(AOMStringProperty::kRole); if (!aria_role.IsEmpty()) - return AXObjectImpl::AriaRoleToWebCoreRole(aria_role); + return AXObject::AriaRoleToWebCoreRole(aria_role); return kLinkRole; } @@ -98,7 +98,7 @@ } void AXImageMapLink::GetRelativeBounds( - AXObjectImpl** out_container, + AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const { *out_container = nullptr;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h index cf7b9df..a52ba70 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h +++ b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h
@@ -61,8 +61,8 @@ KURL Url() const override; bool IsLink() const override { return true; } bool IsLinked() const override { return true; } - AXObjectImpl* ComputeParent() const override; - void GetRelativeBounds(AXObjectImpl** out_container, + AXObject* ComputeParent() const override; + void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const override;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp index 305dfbc..068a1d7 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp
@@ -41,8 +41,7 @@ AXInlineTextBox::AXInlineTextBox( PassRefPtr<AbstractInlineTextBox> inline_text_box, AXObjectCacheImpl& ax_object_cache) - : AXObjectImpl(ax_object_cache), - inline_text_box_(std::move(inline_text_box)) {} + : AXObject(ax_object_cache), inline_text_box_(std::move(inline_text_box)) {} AXInlineTextBox* AXInlineTextBox::Create( PassRefPtr<AbstractInlineTextBox> inline_text_box, @@ -53,12 +52,12 @@ void AXInlineTextBox::Init() {} void AXInlineTextBox::Detach() { - AXObjectImpl::Detach(); + AXObject::Detach(); inline_text_box_ = nullptr; } void AXInlineTextBox::GetRelativeBounds( - AXObjectImpl** out_container, + AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const { *out_container = nullptr; @@ -82,7 +81,7 @@ bool AXInlineTextBox::ComputeAccessibilityIsIgnored( IgnoredReasons* ignored_reasons) const { - AXObjectImpl* parent = ParentObject(); + AXObject* parent = ParentObject(); if (!parent) return false; @@ -124,9 +123,8 @@ AXRange(word_boundaries[i].start_index, word_boundaries[i].end_index); } -String AXInlineTextBox::GetName( - AXNameFrom& name_from, - AXObjectImpl::AXObjectVector* name_objects) const { +String AXInlineTextBox::GetName(AXNameFrom& name_from, + AXObject::AXObjectVector* name_objects) const { if (!inline_text_box_) return String(); @@ -134,7 +132,7 @@ return inline_text_box_->GetText(); } -AXObjectImpl* AXInlineTextBox::ComputeParent() const { +AXObject* AXInlineTextBox::ComputeParent() const { DCHECK(!IsDetached()); if (!inline_text_box_ || !ax_object_cache_) return 0; @@ -148,7 +146,7 @@ // top to bottom and bottom to top via the CSS writing-mode property. AccessibilityTextDirection AXInlineTextBox::GetTextDirection() const { if (!inline_text_box_) - return AXObjectImpl::GetTextDirection(); + return AXObject::GetTextDirection(); switch (inline_text_box_->GetDirection()) { case AbstractInlineTextBox::kLeftToRight: @@ -161,10 +159,10 @@ return kAccessibilityTextDirectionBTT; } - return AXObjectImpl::GetTextDirection(); + return AXObject::GetTextDirection(); } -AXObjectImpl* AXInlineTextBox::NextOnLine() const { +AXObject* AXInlineTextBox::NextOnLine() const { RefPtr<AbstractInlineTextBox> next_on_line = inline_text_box_->NextOnLine(); if (next_on_line) return ax_object_cache_->GetOrCreate(next_on_line.Get()); @@ -175,7 +173,7 @@ return ParentObject()->NextOnLine(); } -AXObjectImpl* AXInlineTextBox::PreviousOnLine() const { +AXObject* AXInlineTextBox::PreviousOnLine() const { RefPtr<AbstractInlineTextBox> previous_on_line = inline_text_box_->PreviousOnLine(); if (previous_on_line)
diff --git a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h index ca75ce5..923cbcf 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h +++ b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h
@@ -30,14 +30,14 @@ #define AXInlineTextBox_h #include "core/layout/line/AbstractInlineTextBox.h" -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" namespace blink { class Node; class AXObjectCacheImpl; -class AXInlineTextBox final : public AXObjectImpl { +class AXInlineTextBox final : public AXObject { WTF_MAKE_NONCOPYABLE(AXInlineTextBox); private: @@ -56,17 +56,17 @@ public: AccessibilityRole RoleValue() const override { return kInlineTextBoxRole; } String GetName(AXNameFrom&, - AXObjectImpl::AXObjectVector* name_objects) const override; + AXObject::AXObjectVector* name_objects) const override; void TextCharacterOffsets(Vector<int>&) const override; void GetWordBoundaries(Vector<AXRange>&) const override; - void GetRelativeBounds(AXObjectImpl** out_container, + void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const override; - AXObjectImpl* ComputeParent() const override; + AXObject* ComputeParent() const override; AccessibilityTextDirection GetTextDirection() const override; Node* GetNode() const override { return inline_text_box_->GetNode(); } - AXObjectImpl* NextOnLine() const override; - AXObjectImpl* PreviousOnLine() const override; + AXObject* NextOnLine() const override; + AXObject* PreviousOnLine() const override; private: RefPtr<AbstractInlineTextBox> inline_text_box_;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp index eca6b42..c890377e 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp
@@ -319,7 +319,7 @@ // Check object role or purpose. // -static bool IsLinkable(const AXObjectImpl& object) { +static bool IsLinkable(const AXObject& object) { if (!object.GetLayoutObject()) return false; @@ -342,7 +342,7 @@ Document& document = GetLayoutObject()->GetDocument(); HTMLElement* body = document.body(); if (body && HasEditableStyle(*body)) { - AXObjectImpl* ax_body = AxObjectCache().GetOrCreate(body); + AXObject* ax_body = AxObjectCache().GetOrCreate(body); return ax_body && ax_body != ax_body->AriaHiddenRoot(); } @@ -362,7 +362,7 @@ Document& document = layout_object_->GetDocument(); HTMLElement* body = document.body(); if (body && HasRichlyEditableStyle(*body)) { - AXObjectImpl* ax_body = AxObjectCache().GetOrCreate(body); + AXObject* ax_body = AxObjectCache().GetOrCreate(body); return ax_body && ax_body != ax_body->AriaHiddenRoot(); } @@ -404,7 +404,7 @@ Document& document = layout_object_->GetDocument(); HTMLElement* body = document.body(); if (body && HasEditableStyle(*body)) { - AXObjectImpl* ax_body = AxObjectCache().GetOrCreate(body); + AXObject* ax_body = AxObjectCache().GetOrCreate(body); return !ax_body || ax_body == ax_body->AriaHiddenRoot(); } @@ -433,7 +433,7 @@ Element* focused_element = GetDocument()->FocusedElement(); if (!focused_element) return false; - AXObjectImpl* focused_object = AxObjectCache().GetOrCreate(focused_element); + AXObject* focused_object = AxObjectCache().GetOrCreate(focused_element); if (!focused_object || !focused_object->IsAXLayoutObject()) return false; @@ -463,11 +463,11 @@ // Selection follows focus, but ONLY in single selection containers, // and only if aria-selected was not present to override - AXObjectImpl* container = ContainerWidget(); + AXObject* container = ContainerWidget(); if (!container || container->IsMultiSelectable()) return false; - AXObjectImpl* focused_object = AxObjectCache().FocusedObject(); + AXObject* focused_object = AxObjectCache().FocusedObject(); return focused_object == this || (focused_object && focused_object->ActiveDescendant() == this); } @@ -498,7 +498,7 @@ return kIgnoreObject; } - return AXObjectImpl::DefaultObjectInclusion(ignored_reasons); + return AXObject::DefaultObjectInclusion(ignored_reasons); } bool AXLayoutObject::ComputeAccessibilityIsIgnored( @@ -539,7 +539,7 @@ if (HasInheritedPresentationalRole()) { if (ignored_reasons) { - const AXObjectImpl* inherits_from = InheritsPresentationalRoleFrom(); + const AXObject* inherits_from = InheritsPresentationalRoleFrom(); if (inherits_from == this) ignored_reasons->push_back(IgnoredReason(kAXPresentationalRole)); else @@ -550,7 +550,7 @@ } // An ARIA tree can only have tree items and static text as children. - if (AXObjectImpl* tree_ancestor = TreeAncestorDisallowingChild()) { + if (AXObject* tree_ancestor = TreeAncestorDisallowingChild()) { if (ignored_reasons) ignored_reasons->push_back( IgnoredReason(kAXAncestorDisallowsChild, tree_ancestor)); @@ -569,13 +569,13 @@ // Find out if this element is inside of a label element. If so, it may be // ignored because it's the label for a checkbox or radio button. - AXObjectImpl* control_object = CorrespondingControlForLabelElement(); + AXObject* control_object = CorrespondingControlForLabelElement(); if (control_object && control_object->IsCheckboxOrRadio() && control_object->NameFromLabelElement()) { if (ignored_reasons) { HTMLLabelElement* label = LabelElementContainer(); if (label && label != GetNode()) { - AXObjectImpl* label_ax_object = AxObjectCache().GetOrCreate(label); + AXObject* label_ax_object = AxObjectCache().GetOrCreate(label); ignored_reasons->push_back( IgnoredReason(kAXLabelContainer, label_ax_object)); } @@ -597,7 +597,7 @@ if (layout_object_->IsText()) { // Static text beneath MenuItems and MenuButtons are just reported along // with the menu item, so it's ignored on an individual level. - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (parent && (parent->AriaRoleAttribute() == kMenuItemRole || parent->AriaRoleAttribute() == kMenuButtonRole)) { if (ignored_reasons) @@ -613,7 +613,7 @@ } // Don't ignore static text in editable text controls. - for (AXObjectImpl* parent = ParentObject(); parent; + for (AXObject* parent = ParentObject(); parent; parent = parent->ParentObject()) { if (parent->RoleValue() == kTextFieldRole) return false; @@ -806,7 +806,7 @@ // Color::blend should be called like this: background.blend(foreground). for (LayoutObject* layout_object = GetLayoutObject(); layout_object; layout_object = layout_object->Parent()) { - const AXObjectImpl* ax_parent = AxObjectCache().GetOrCreate(layout_object); + const AXObject* ax_parent = AxObjectCache().GetOrCreate(layout_object); if (ax_parent && ax_parent != this) { Color parent_color = ax_parent->BackgroundColor(); blended_color = parent_color.Blend(blended_color); @@ -1077,13 +1077,13 @@ } } -AXObjectImpl* AXLayoutObject::NextOnLine() const { +AXObject* AXLayoutObject::NextOnLine() const { if (!GetLayoutObject()) return nullptr; - AXObjectImpl* result = nullptr; + AXObject* result = nullptr; if (GetLayoutObject()->IsListMarker()) { - AXObjectImpl* next_sibling = RawNextSibling(); + AXObject* next_sibling = RawNextSibling(); if (!next_sibling || !next_sibling->Children().size()) return nullptr; result = next_sibling->Children()[0].Get(); @@ -1116,7 +1116,7 @@ return result; } -AXObjectImpl* AXLayoutObject::PreviousOnLine() const { +AXObject* AXLayoutObject::PreviousOnLine() const { if (!GetLayoutObject()) return nullptr; @@ -1129,7 +1129,7 @@ if (!inline_box) return nullptr; - AXObjectImpl* result = nullptr; + AXObject* result = nullptr; for (InlineBox* prev = inline_box->PrevOnLine(); prev; prev = prev->PrevOnLine()) { LayoutObject* layout_object = @@ -1288,10 +1288,9 @@ } } -AXObjectImpl* AXLayoutObject::AncestorForWhichThisIsAPresentationalChild() - const { +AXObject* AXLayoutObject::AncestorForWhichThisIsAPresentationalChild() const { // Walk the parent chain looking for a parent that has presentational children - AXObjectImpl* parent = ParentObjectIfExists(); + AXObject* parent = ParentObjectIfExists(); while (parent) { if (parent->AriaRoleHasPresentationalChildren()) break; @@ -1394,8 +1393,7 @@ // Hit testing. // -AXObjectImpl* AXLayoutObject::AccessibilityHitTest( - const IntPoint& point) const { +AXObject* AXLayoutObject::AccessibilityHitTest(const IntPoint& point) const { if (!layout_object_ || !layout_object_->HasLayer()) return nullptr; @@ -1422,7 +1420,7 @@ if (!obj) return nullptr; - AXObjectImpl* result = AxObjectCache().GetOrCreate(obj); + AXObject* result = AxObjectCache().GetOrCreate(obj); result->UpdateChildrenIfNecessary(); // Allow the element to perform any hit-testing it might need to do to reach @@ -1432,7 +1430,7 @@ // If this element is the label of a control, a hit test should return the // control. if (result->IsAXLayoutObject()) { - AXObjectImpl* control_object = + AXObject* control_object = ToAXLayoutObject(result)->CorrespondingControlForLabelElement(); if (control_object && control_object->NameFromLabelElement()) return control_object; @@ -1444,19 +1442,19 @@ return result; } -AXObjectImpl* AXLayoutObject::ElementAccessibilityHitTest( +AXObject* AXLayoutObject::ElementAccessibilityHitTest( const IntPoint& point) const { if (IsSVGImage()) return RemoteSVGElementHitTest(point); - return AXObjectImpl::ElementAccessibilityHitTest(point); + return AXObject::ElementAccessibilityHitTest(point); } // // High-level accessibility tree access. // -AXObjectImpl* AXLayoutObject::ComputeParent() const { +AXObject* AXLayoutObject::ComputeParent() const { DCHECK(!IsDetached()); if (!layout_object_) return 0; @@ -1467,7 +1465,7 @@ // menuButton and its corresponding menu are DOM siblings, but Accessibility // needs them to be parent/child. if (AriaRoleAttribute() == kMenuRole) { - AXObjectImpl* parent = MenuButtonForMenu(); + AXObject* parent = MenuButtonForMenu(); if (parent) return parent; } @@ -1485,7 +1483,7 @@ return 0; } -AXObjectImpl* AXLayoutObject::ComputeParentIfExists() const { +AXObject* AXLayoutObject::ComputeParentIfExists() const { if (!layout_object_) return 0; @@ -1495,7 +1493,7 @@ // menuButton and its corresponding menu are DOM siblings, but Accessibility // needs them to be parent/child. if (AriaRoleAttribute() == kMenuRole) { - AXObjectImpl* parent = MenuButtonForMenu(); + AXObject* parent = MenuButtonForMenu(); if (parent) return parent; } @@ -1518,7 +1516,7 @@ // accessibility module. // -AXObjectImpl* AXLayoutObject::RawFirstChild() const { +AXObject* AXLayoutObject::RawFirstChild() const { if (!layout_object_) return 0; @@ -1530,7 +1528,7 @@ return AxObjectCache().GetOrCreate(first_child); } -AXObjectImpl* AXLayoutObject::RawNextSibling() const { +AXObject* AXLayoutObject::RawNextSibling() const { if (!layout_object_) return 0; @@ -1598,10 +1596,10 @@ if (!CanHaveChildren()) return; - HeapVector<Member<AXObjectImpl>> owned_children; + HeapVector<Member<AXObject>> owned_children; ComputeAriaOwnsChildren(owned_children); - for (AXObjectImpl* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { + for (AXObject* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { if (!AxObjectCache().IsAriaOwned(obj)) { obj->SetParent(this); AddChild(obj); @@ -1636,11 +1634,11 @@ if (NeedsToUpdateChildren()) ClearChildren(); - AXObjectImpl::UpdateChildrenIfNecessary(); + AXObject::UpdateChildrenIfNecessary(); } void AXLayoutObject::ClearChildren() { - AXObjectImpl::ClearChildren(); + AXObject::ClearChildren(); children_dirty_ = false; } @@ -1727,7 +1725,7 @@ // Functions that retrieve the current selection. // -AXObjectImpl::AXRange AXLayoutObject::Selection() const { +AXObject::AXRange AXLayoutObject::Selection() const { AXRange text_selection = TextControlSelection(); if (text_selection.IsValid()) return text_selection; @@ -1754,7 +1752,7 @@ DCHECK(anchor_node); AXLayoutObject* anchor_object = nullptr; - // Find the closest node that has a corresponding AXObjectImpl. + // Find the closest node that has a corresponding AXObject. // This is because some nodes may be aria hidden or might not even have // a layout object if they are part of the shadow DOM. while (anchor_node) { @@ -1797,7 +1795,7 @@ // Gets only the start and end offsets of the selection computed using the // current object as the starting point. Returns a null selection if there is // no selection in the subtree rooted at this object. -AXObjectImpl::AXRange AXLayoutObject::SelectionUnderObject() const { +AXObject::AXRange AXLayoutObject::SelectionUnderObject() const { AXRange text_selection = TextControlSelection(); if (text_selection.IsValid()) return text_selection; @@ -1831,7 +1829,7 @@ return AXRange(start, end); } -AXObjectImpl::AXRange AXLayoutObject::TextControlSelection() const { +AXObject::AXRange AXLayoutObject::TextControlSelection() const { if (!GetLayoutObject()) return AXRange(); @@ -1848,7 +1846,7 @@ if (!layout) return AXRange(); - AXObjectImpl* ax_object = AxObjectCache().GetOrCreate(layout); + AXObject* ax_object = AxObjectCache().GetOrCreate(layout); if (!ax_object || !ax_object->IsAXLayoutObject()) return AXRange(); @@ -1893,7 +1891,7 @@ if (IsDetached()) return nullptr; - AXObjectImpl* ax_object = AxObjectCache().GetOrCreate(&node); + AXObject* ax_object = AxObjectCache().GetOrCreate(&node); if (!ax_object) return nullptr; @@ -1908,7 +1906,7 @@ // // Convert from an accessible object and offset to a VisiblePosition. -static VisiblePosition ToVisiblePosition(AXObjectImpl* obj, int offset) { +static VisiblePosition ToVisiblePosition(AXObject* obj, int offset) { if (!obj->GetNode()) return VisiblePosition(); @@ -1934,7 +1932,7 @@ static_cast<unsigned>(offset) > (obj->Children().size() - 1) ? offset - 1 : offset; - AXObjectImpl* child_obj = obj->Children()[clamped_offset]; + AXObject* child_obj = obj->Children()[clamped_offset]; Node* child_node = child_obj->GetNode(); if (!child_node || !child_node->parentNode()) return VisiblePosition(); @@ -1967,9 +1965,9 @@ if (!GetLayoutObject() || !selection.IsValid()) return; - AXObjectImpl* anchor_object = + AXObject* anchor_object = selection.anchor_object ? selection.anchor_object.Get() : this; - AXObjectImpl* focus_object = + AXObject* focus_object = selection.focus_object ? selection.focus_object.Get() : this; if (!IsValidSelectionBound(anchor_object) || @@ -2021,8 +2019,7 @@ .Build()); } -bool AXLayoutObject::IsValidSelectionBound( - const AXObjectImpl* bound_object) const { +bool AXLayoutObject::IsValidSelectionBound(const AXObject* bound_object) const { return GetLayoutObject() && bound_object && !bound_object->IsDetached() && bound_object->IsAXLayoutObject() && bound_object->GetLayoutObject() && bound_object->GetLayoutObject()->GetFrame() == @@ -2053,7 +2050,7 @@ if (!GetLayoutObject()) return; - AXObjectImpl* focused_object = AxObjectCache().FocusedObject(); + AXObject* focused_object = AxObjectCache().FocusedObject(); if (focused_object == this && SupportsActiveDescendant()) { AxObjectCache().PostNotification( GetLayoutObject(), AXObjectCacheImpl::kAXActiveDescendantChanged); @@ -2062,7 +2059,7 @@ void AXLayoutObject::HandleAriaExpandedChanged() { // Find if a parent of this object should handle aria-expanded changes. - AXObjectImpl* container_parent = this->ParentObject(); + AXObject* container_parent = this->ParentObject(); while (container_parent) { bool found_parent = false; @@ -2182,7 +2179,7 @@ for (RefPtr<AbstractInlineTextBox> box = layout_text->FirstAbstractInlineTextBox(); box.Get(); box = box->NextInlineTextBox()) { - AXObjectImpl* ax_object = AxObjectCache().GetOrCreate(box.Get()); + AXObject* ax_object = AxObjectCache().GetOrCreate(box.Get()); if (!ax_object->AccessibilityIsIgnored()) children_.push_back(ax_object); } @@ -2215,11 +2212,11 @@ // Private. // -AXObjectImpl* AXLayoutObject::TreeAncestorDisallowingChild() const { +AXObject* AXLayoutObject::TreeAncestorDisallowingChild() const { // Determine if this is in a tree. If so, we apply special behavior to make it // work like an AXOutline. - AXObjectImpl* ax_obj = ParentObject(); - AXObjectImpl* tree_ancestor = 0; + AXObject* ax_obj = ParentObject(); + AXObject* tree_ancestor = 0; while (ax_obj) { if (ax_obj->IsTree()) { tree_ancestor = ax_obj; @@ -2249,7 +2246,7 @@ // The ARIA spec says a tab item can also be selected if it is aria-labeled by // a tabpanel that has keyboard focus inside of it, or if a tabpanel in its // aria-controls list has KB focus inside of it. - AXObjectImpl* focused_element = AxObjectCache().FocusedObject(); + AXObject* focused_element = AxObjectCache().FocusedObject(); if (!focused_element) return false; @@ -2257,13 +2254,13 @@ ElementsFromAttribute(elements, aria_controlsAttr); for (const auto& element : elements) { - AXObjectImpl* tab_panel = AxObjectCache().GetOrCreate(element); + AXObject* tab_panel = AxObjectCache().GetOrCreate(element); // A tab item should only control tab panels. if (!tab_panel || tab_panel->RoleValue() != kTabPanelRole) continue; - AXObjectImpl* check_focus_element = focused_element; + AXObject* check_focus_element = focused_element; // Check if the focused element is a descendant of the element controlled by // the tab item. while (check_focus_element) { @@ -2276,13 +2273,13 @@ return false; } -AXObjectImpl* AXLayoutObject::AccessibilityImageMapHitTest( +AXObject* AXLayoutObject::AccessibilityImageMapHitTest( HTMLAreaElement* area, const IntPoint& point) const { if (!area) return 0; - AXObjectImpl* parent = AxObjectCache().GetOrCreate(area->ImageElement()); + AXObject* parent = AxObjectCache().GetOrCreate(area->ImageElement()); if (!parent) return 0; @@ -2360,9 +2357,8 @@ return 0; } -AXObjectImpl* AXLayoutObject::RemoteSVGElementHitTest( - const IntPoint& point) const { - AXObjectImpl* remote = RemoteSVGRootElement(); +AXObject* AXLayoutObject::RemoteSVGElementHitTest(const IntPoint& point) const { + AXObject* remote = RemoteSVGRootElement(); if (!remote) return 0; @@ -2376,7 +2372,7 @@ // coordinates only. void AXLayoutObject::OffsetBoundingBoxForRemoteSVGElement( LayoutRect& rect) const { - for (AXObjectImpl* parent = ParentObject(); parent; + for (AXObject* parent = ParentObject(); parent; parent = parent->ParentObject()) { if (parent->IsAXSVGRoot()) { rect.MoveBy( @@ -2415,7 +2411,7 @@ for (Node& child : NodeTraversal::ChildrenOf(*node)) { if (child.GetLayoutObject()) { // Find out where the last layout sibling is located within m_children. - if (AXObjectImpl* child_object = + if (AXObject* child_object = AxObjectCache().Get(child.GetLayoutObject())) { if (child_object->AccessibilityIsIgnored()) { const auto& children = child_object->Children(); @@ -2470,7 +2466,7 @@ for (HTMLAreaElement& area : Traversal<HTMLAreaElement>::DescendantsOf(*map)) { // add an <area> element for this child if it has a link - AXObjectImpl* obj = AxObjectCache().GetOrCreate(&area); + AXObject* obj = AxObjectCache().GetOrCreate(&area); if (obj) { AXImageMapLink* area_object = ToAXImageMapLink(obj); area_object->SetParent(this); @@ -2498,8 +2494,7 @@ void AXLayoutObject::AddPopupChildren() { if (!isHTMLInputElement(GetNode())) return; - if (AXObjectImpl* ax_popup = - ToAXObjectImpl(toHTMLInputElement(GetNode())->PopupRootAXObject())) + if (AXObject* ax_popup = toHTMLInputElement(GetNode())->PopupRootAXObject()) children_.push_back(ax_popup); }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.h b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.h index 1898ac0..b901d05 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.h
@@ -54,7 +54,7 @@ static AXLayoutObject* Create(LayoutObject*, AXObjectCacheImpl&); ~AXLayoutObject() override; - // Public, overridden from AXObjectImpl. + // Public, overridden from AXObject. LayoutObject* GetLayoutObject() const final { return layout_object_; } LayoutBoxModelObject* GetLayoutBoxModelObject() const; ScrollableArea* GetScrollableAreaIfScrollable() const final; @@ -69,7 +69,7 @@ } // - // Overridden from AXObjectImpl. + // Overridden from AXObject. // void Init() override; @@ -111,8 +111,8 @@ // Inline text boxes. void LoadInlineTextBoxes() override; - AXObjectImpl* NextOnLine() const override; - AXObjectImpl* PreviousOnLine() const override; + AXObject* NextOnLine() const override; + AXObject* PreviousOnLine() const override; // Properties of interactive elements. String StringValue() const override; @@ -124,7 +124,7 @@ bool AriaHasPopup() const override; bool AriaRoleHasPresentationalChildren() const override; - AXObjectImpl* AncestorForWhichThisIsAPresentationalChild() const override; + AXObject* AncestorForWhichThisIsAPresentationalChild() const override; bool SupportsARIADragging() const override; bool SupportsARIADropping() const override; bool SupportsARIAFlowTo() const override; @@ -151,18 +151,18 @@ void SetSelection(const AXRange&) override; // Hit testing. - AXObjectImpl* AccessibilityHitTest(const IntPoint&) const override; - AXObjectImpl* ElementAccessibilityHitTest(const IntPoint&) const override; + AXObject* AccessibilityHitTest(const IntPoint&) const override; + AXObject* ElementAccessibilityHitTest(const IntPoint&) const override; // High-level accessibility tree access. Other modules should only use these // functions. - AXObjectImpl* ComputeParent() const override; - AXObjectImpl* ComputeParentIfExists() const override; + AXObject* ComputeParent() const override; + AXObject* ComputeParentIfExists() const override; // Low-level accessibility tree exploration, only for use within the // accessibility module. - AXObjectImpl* RawFirstChild() const override; - AXObjectImpl* RawNextSibling() const override; + AXObject* RawFirstChild() const override; + AXObject* RawNextSibling() const override; void AddChildren() override; bool CanHaveChildren() const override; void UpdateChildrenIfNecessary() override; @@ -192,16 +192,16 @@ void LineBreaks(Vector<int>&) const final; private: - AXObjectImpl* TreeAncestorDisallowingChild() const; + AXObject* TreeAncestorDisallowingChild() const; bool IsTabItemSelected() const; - bool IsValidSelectionBound(const AXObjectImpl*) const; - AXObjectImpl* AccessibilityImageMapHitTest(HTMLAreaElement*, - const IntPoint&) const; + bool IsValidSelectionBound(const AXObject*) const; + AXObject* AccessibilityImageMapHitTest(HTMLAreaElement*, + const IntPoint&) const; LayoutObject* LayoutParentObject() const; bool IsSVGImage() const; void DetachRemoteSVGRoot(); AXSVGRoot* RemoteSVGRootElement() const; - AXObjectImpl* RemoteSVGElementHitTest(const IntPoint&) const; + AXObject* RemoteSVGElementHitTest(const IntPoint&) const; void OffsetBoundingBoxForRemoteSVGElement(LayoutRect&) const; void AddHiddenChildren(); void AddTextFieldChildren();
diff --git a/third_party/WebKit/Source/modules/accessibility/AXListBox.cpp b/third_party/WebKit/Source/modules/accessibility/AXListBox.cpp index 763a72f..af73e43d 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXListBox.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXListBox.cpp
@@ -57,7 +57,7 @@ return kListBoxRole; } -AXObjectImpl* AXListBox::ActiveDescendant() { +AXObject* AXListBox::ActiveDescendant() { if (!isHTMLSelectElement(GetNode())) return nullptr;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXListBox.h b/third_party/WebKit/Source/modules/accessibility/AXListBox.h index d40e283f..d2853e9 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXListBox.h +++ b/third_party/WebKit/Source/modules/accessibility/AXListBox.h
@@ -47,7 +47,7 @@ AccessibilityRole DetermineAccessibilityRole() final; bool IsAXListBox() const override { return true; } - AXObjectImpl* ActiveDescendant() final; + AXObject* ActiveDescendant() final; void ActiveIndexChanged();
diff --git a/third_party/WebKit/Source/modules/accessibility/AXListBoxOption.cpp b/third_party/WebKit/Source/modules/accessibility/AXListBoxOption.cpp index 76e28f1..9b101ada 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXListBoxOption.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXListBoxOption.cpp
@@ -65,7 +65,7 @@ } bool AXListBoxOption::IsParentPresentationalRole() const { - AXObjectImpl* parent = ParentObject(); + AXObject* parent = ParentObject(); if (!parent) return false;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp index 70c0bad4d..d00ae6c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp
@@ -46,7 +46,7 @@ AXObjectCacheImpl& ax_object_cache) : AXLayoutObject(layout_object, ax_object_cache) {} -AXObjectImpl* AccessibilityMediaControl::Create( +AXObject* AccessibilityMediaControl::Create( LayoutObject* layout_object, AXObjectCacheImpl& ax_object_cache) { DCHECK(layout_object->GetNode()); @@ -276,9 +276,8 @@ AXObjectCacheImpl& ax_object_cache) : AccessibilityMediaControl(layout_object, ax_object_cache) {} -AXObjectImpl* AXMediaControlsContainer::Create( - LayoutObject* layout_object, - AXObjectCacheImpl& ax_object_cache) { +AXObject* AXMediaControlsContainer::Create(LayoutObject* layout_object, + AXObjectCacheImpl& ax_object_cache) { return new AXMediaControlsContainer(layout_object, ax_object_cache); } @@ -322,7 +321,7 @@ AXObjectCacheImpl& ax_object_cache) : AXSlider(layout_object, ax_object_cache) {} -AXObjectImpl* AccessibilityMediaTimeline::Create( +AXObject* AccessibilityMediaTimeline::Create( LayoutObject* layout_object, AXObjectCacheImpl& ax_object_cache) { return new AccessibilityMediaTimeline(layout_object, ax_object_cache); @@ -354,7 +353,7 @@ AXObjectCacheImpl& ax_object_cache) : AccessibilityMediaControl(layout_object, ax_object_cache) {} -AXObjectImpl* AccessibilityMediaTimeDisplay::Create( +AXObject* AccessibilityMediaTimeDisplay::Create( LayoutObject* layout_object, AXObjectCacheImpl& ax_object_cache) { return new AccessibilityMediaTimeDisplay(layout_object, ax_object_cache);
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.h b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.h index 353aec4..07b70bf 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.h +++ b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.h
@@ -40,7 +40,7 @@ WTF_MAKE_NONCOPYABLE(AccessibilityMediaControl); public: - static AXObjectImpl* Create(LayoutObject*, AXObjectCacheImpl&); + static AXObject* Create(LayoutObject*, AXObjectCacheImpl&); ~AccessibilityMediaControl() override {} AccessibilityRole RoleValue() const override; @@ -65,7 +65,7 @@ WTF_MAKE_NONCOPYABLE(AccessibilityMediaTimeline); public: - static AXObjectImpl* Create(LayoutObject*, AXObjectCacheImpl&); + static AXObject* Create(LayoutObject*, AXObjectCacheImpl&); ~AccessibilityMediaTimeline() override {} String Description(AXNameFrom, @@ -81,7 +81,7 @@ WTF_MAKE_NONCOPYABLE(AXMediaControlsContainer); public: - static AXObjectImpl* Create(LayoutObject*, AXObjectCacheImpl&); + static AXObject* Create(LayoutObject*, AXObjectCacheImpl&); ~AXMediaControlsContainer() override {} AccessibilityRole RoleValue() const override { return kToolbarRole; } @@ -105,7 +105,7 @@ WTF_MAKE_NONCOPYABLE(AccessibilityMediaTimeDisplay); public: - static AXObjectImpl* Create(LayoutObject*, AXObjectCacheImpl&); + static AXObject* Create(LayoutObject*, AXObjectCacheImpl&); ~AccessibilityMediaTimeDisplay() override {} AccessibilityRole RoleValue() const override { return kStaticTextRole; }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuList.cpp b/third_party/WebKit/Source/modules/accessibility/AXMenuList.cpp index 193badc..6da17f6 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuList.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuList.cpp
@@ -78,7 +78,7 @@ AXObjectCacheImpl& cache = AxObjectCache(); - AXObjectImpl* list = cache.GetOrCreate(kMenuListPopupRole); + AXObject* list = cache.GetOrCreate(kMenuListPopupRole); if (!list) return;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp index f8c4eec..156fd55d 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp
@@ -71,14 +71,14 @@ return element_; } -AXObjectImpl* AXMenuListOption::ComputeParent() const { +AXObject* AXMenuListOption::ComputeParent() const { Node* node = GetNode(); if (!node) return nullptr; HTMLSelectElement* select = toHTMLOptionElement(node)->OwnerSelectElement(); if (!select) return nullptr; - AXObjectImpl* select_ax_object = AxObjectCache().GetOrCreate(select); + AXObject* select_ax_object = AxObjectCache().GetOrCreate(select); // This happens if the <select> is not rendered. Return it and move on. if (!select_ax_object->IsMenuList()) @@ -156,19 +156,19 @@ } void AXMenuListOption::GetRelativeBounds( - AXObjectImpl** out_container, + AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity(); - AXObjectImpl* parent = ParentObject(); + AXObject* parent = ParentObject(); if (!parent) return; DCHECK(parent->IsMenuListPopup()); - AXObjectImpl* grandparent = parent->ParentObject(); + AXObject* grandparent = parent->ParentObject(); if (!grandparent) return; DCHECK(grandparent->IsMenuList());
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h index 32f42e9..7df77da 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h
@@ -55,7 +55,7 @@ LocalFrameView* DocumentFrameView() const override; AccessibilityRole RoleValue() const override; bool CanHaveChildren() const override { return false; } - AXObjectImpl* ComputeParent() const override; + AXObject* ComputeParent() const override; Element* ActionElement() const override; bool IsEnabled() const override; @@ -66,7 +66,7 @@ bool CanSetSelectedAttribute() const override; bool CanSetFocusAttribute() const override; - void GetRelativeBounds(AXObjectImpl** out_container, + void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const override; String TextAlternative(bool recursive,
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.cpp b/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.cpp index f78cb77..c189b5c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.cpp
@@ -65,7 +65,7 @@ if (!isHTMLOptionElement(*element)) return 0; - AXObjectImpl* object = AxObjectCache().GetOrCreate(element); + AXObject* object = AxObjectCache().GetOrCreate(element); if (!object || !object->IsMenuListOption()) return 0; @@ -137,13 +137,13 @@ AXObjectCacheImpl& cache = AxObjectCache(); if (old_index != option_index && old_index >= 0 && old_index < static_cast<int>(children_.size())) { - AXObjectImpl* previous_child = children_[old_index].Get(); + AXObject* previous_child = children_[old_index].Get(); cache.PostNotification(previous_child, AXObjectCacheImpl::kAXMenuListItemUnselected); } if (option_index >= 0 && option_index < static_cast<int>(children_.size())) { - AXObjectImpl* child = children_[option_index].Get(); + AXObject* child = children_[option_index].Get(); cache.PostNotification(this, AXObjectCacheImpl::kAXActiveDescendantChanged); cache.PostNotification(child, AXObjectCacheImpl::kAXMenuListItemSelected); } @@ -172,7 +172,7 @@ AXObjectCacheImpl::kAXFocusedUIElementChanged); } -AXObjectImpl* AXMenuListPopup::ActiveDescendant() { +AXObject* AXMenuListPopup::ActiveDescendant() { if (active_index_ < 0 || active_index_ >= static_cast<int>(Children().size())) return nullptr;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.h b/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.h index d442109..a8008d3 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.h +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListPopup.h
@@ -48,7 +48,7 @@ void DidUpdateActiveOption(int option_index, bool fire_notifications = true); void DidShow(); void DidHide(); - AXObjectImpl* ActiveDescendant() final; + AXObject* ActiveDescendant() final; void UpdateChildrenIfNecessary() override; private:
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMockObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXMockObject.cpp index bb2adde3..1c46fa2 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMockObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMockObject.cpp
@@ -30,7 +30,7 @@ namespace blink { AXMockObject::AXMockObject(AXObjectCacheImpl& ax_object_cache) - : AXObjectImpl(ax_object_cache) {} + : AXObject(ax_object_cache) {} AXMockObject::~AXMockObject() {}
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMockObject.h b/third_party/WebKit/Source/modules/accessibility/AXMockObject.h index 29afc406..e83ff1a 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMockObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXMockObject.h
@@ -27,13 +27,13 @@ #define AXMockObject_h #include "modules/ModulesExport.h" -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" namespace blink { class AXObjectCacheImpl; -class MODULES_EXPORT AXMockObject : public AXObjectImpl { +class MODULES_EXPORT AXMockObject : public AXObject { WTF_MAKE_NONCOPYABLE(AXMockObject); protected: @@ -42,8 +42,8 @@ public: ~AXMockObject() override; - // AXObjectImpl overrides. - AXObjectImpl* ComputeParent() const override { return parent_; } + // AXObject overrides. + AXObject* ComputeParent() const override { return parent_; } bool IsEnabled() const override { return true; } private:
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp index 3a543dd..e68f52e 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp
@@ -79,7 +79,7 @@ USING_FAST_MALLOC(SparseAttributeSetter); public: - virtual void Run(const AXObjectImpl&, + virtual void Run(const AXObject&, AXSparseAttributeClient&, const AtomicString& value) = 0; }; @@ -91,7 +91,7 @@ private: AXBoolAttribute attribute_; - void Run(const AXObjectImpl& obj, + void Run(const AXObject& obj, AXSparseAttributeClient& attribute_map, const AtomicString& value) override { attribute_map.AddBoolAttribute(attribute_, @@ -106,7 +106,7 @@ private: AXStringAttribute attribute_; - void Run(const AXObjectImpl& obj, + void Run(const AXObject& obj, AXSparseAttributeClient& attribute_map, const AtomicString& value) override { attribute_map.AddStringAttribute(attribute_, value); @@ -120,7 +120,7 @@ private: AXObjectAttribute attribute_; - void Run(const AXObjectImpl& obj, + void Run(const AXObject& obj, AXSparseAttributeClient& attribute_map, const AtomicString& value) override { if (value.IsNull() || value.IsEmpty()) @@ -132,7 +132,7 @@ Element* target = ToElement(node)->GetTreeScope().getElementById(value); if (!target) return; - AXObjectImpl* ax_target = obj.AxObjectCache().GetOrCreate(target); + AXObject* ax_target = obj.AxObjectCache().GetOrCreate(target); if (ax_target) attribute_map.AddObjectAttribute(attribute_, *ax_target); } @@ -146,7 +146,7 @@ private: AXObjectVectorAttribute attribute_; - void Run(const AXObjectImpl& obj, + void Run(const AXObject& obj, AXSparseAttributeClient& attribute_map, const AtomicString& value) override { Node* node = obj.GetNode(); @@ -163,12 +163,11 @@ if (ids.IsEmpty()) return; - HeapVector<Member<AXObjectImpl>> objects; + HeapVector<Member<AXObject>> objects; TreeScope& scope = node->GetTreeScope(); for (const auto& id : ids) { if (Element* id_element = scope.getElementById(AtomicString(id))) { - AXObjectImpl* ax_id_element = - obj.AxObjectCache().GetOrCreate(id_element); + AXObject* ax_id_element = obj.AxObjectCache().GetOrCreate(id_element); if (ax_id_element && !ax_id_element->AccessibilityIsIgnored()) objects.push_back(ax_id_element); } @@ -215,7 +214,7 @@ } AXNodeObject::AXNodeObject(Node* node, AXObjectCacheImpl& ax_object_cache) - : AXObjectImpl(ax_object_cache), + : AXObject(ax_object_cache), aria_role_(kUnknownRole), children_dirty_(false), node_(node) {} @@ -243,7 +242,7 @@ AXObjectCacheImpl::kAXValueChanged); } -AXObjectImpl* AXNodeObject::ActiveDescendant() { +AXObject* AXNodeObject::ActiveDescendant() { if (!node_ || !node_->IsElementNode()) return nullptr; @@ -258,14 +257,14 @@ if (!descendant) return nullptr; - AXObjectImpl* ax_descendant = AxObjectCache().GetOrCreate(descendant); + AXObject* ax_descendant = AxObjectCache().GetOrCreate(descendant); return ax_descendant; } bool AXNodeObject::ComputeAccessibilityIsIgnored( IgnoredReasons* ignored_reasons) const { #if DCHECK_IS_ON() - // Double-check that an AXObjectImpl is never accessed before + // Double-check that an AXObject is never accessed before // it's been initialized. DCHECK(initialized_); #endif @@ -280,13 +279,13 @@ } // Ignore labels that are already referenced by a control. - AXObjectImpl* control_object = CorrespondingControlForLabelElement(); + AXObject* control_object = CorrespondingControlForLabelElement(); if (control_object && control_object->IsCheckboxOrRadio() && control_object->NameFromLabelElement()) { if (ignored_reasons) { HTMLLabelElement* label = LabelElementContainer(); if (label && label != GetNode()) { - AXObjectImpl* label_ax_object = AxObjectCache().GetOrCreate(label); + AXObject* label_ax_object = AxObjectCache().GetOrCreate(label); ignored_reasons->push_back( IgnoredReason(kAXLabelContainer, label_ax_object)); } @@ -318,7 +317,7 @@ isHTMLDListElement(*node); } -static bool IsPresentationalInTable(AXObjectImpl* parent, +static bool IsPresentationalInTable(AXObject* parent, HTMLElement* current_element) { if (!current_element) return false; @@ -345,7 +344,7 @@ IsHTMLTableSectionElement(ToHTMLElement(*parent_node))) { // Because TableSections have ignored role, presentation should be checked // with its parent node. - AXObjectImpl* table_object = parent->ParentObject(); + AXObject* table_object = parent->ParentObject(); Node* table_node = table_object ? table_object->GetNode() : 0; return isHTMLTableElement(table_node) && table_object->HasInheritedPresentationalRole(); @@ -353,7 +352,7 @@ return false; } -static bool IsRequiredOwnedElement(AXObjectImpl* parent, +static bool IsRequiredOwnedElement(AXObject* parent, AccessibilityRole current_role, HTMLElement* current_element) { Node* parent_node = parent->GetNode(); @@ -383,7 +382,7 @@ return false; } -const AXObjectImpl* AXNodeObject::InheritsPresentationalRoleFrom() const { +const AXObject* AXNodeObject::InheritsPresentationalRoleFrom() const { // ARIA states if an item can get focus, it should not be presentational. if (CanSetFocusAttribute()) return 0; @@ -398,7 +397,7 @@ if (AriaRoleAttribute() != kUnknownRole) return 0; - AXObjectImpl* parent = ParentObject(); + AXObject* parent = ParentObject(); if (!parent) return 0; @@ -721,13 +720,13 @@ void AXNodeObject::AccessibilityChildrenFromAttribute( QualifiedName attr, - AXObjectImpl::AXObjectVector& children) const { + AXObject::AXObjectVector& children) const { HeapVector<Member<Element>> elements; ElementsFromAttribute(elements, attr); AXObjectCacheImpl& cache = AxObjectCache(); for (const auto& element : elements) { - if (AXObjectImpl* child = cache.GetOrCreate(element)) { + if (AXObject* child = cache.GetOrCreate(element)) { // Only aria-labelledby and aria-describedby can target hidden elements. if (child->AccessibilityIsIgnored() && attr != aria_labelledbyAttr && attr != aria_labeledbyAttr && attr != aria_describedbyAttr) { @@ -801,13 +800,13 @@ return true; } -AXObjectImpl* AXNodeObject::MenuButtonForMenu() const { +AXObject* AXNodeObject::MenuButtonForMenu() const { Element* menu_item = MenuItemElementForMenu(); if (menu_item) { // ARIA just has generic menu items. AppKit needs to know if this is a top // level items like MenuBarButton or MenuBarItem - AXObjectImpl* menu_item_ax = AxObjectCache().GetOrCreate(menu_item); + AXObject* menu_item_ax = AxObjectCache().GetOrCreate(menu_item); if (menu_item_ax && menu_item_ax->IsMenuButton()) return menu_item_ax; } @@ -878,7 +877,7 @@ if (role != kListBoxOptionRole && role != kMenuItemRole) return role; - for (AXObjectImpl* parent = ParentObject(); + for (AXObject* parent = ParentObject(); parent && !parent->AccessibilityIsIgnored(); parent = parent->ParentObject()) { AccessibilityRole parent_aria_role = parent->AriaRoleAttribute(); @@ -910,7 +909,7 @@ } void AXNodeObject::Detach() { - AXObjectImpl::Detach(); + AXObject::Detach(); node_ = nullptr; } @@ -958,7 +957,7 @@ return false; return ((node->IsElementNode() && ToElement(node)->IsFormControlElement()) || - AXObjectImpl::IsARIAControl(AriaRoleAttribute())); + AXObject::IsARIAControl(AriaRoleAttribute())); } bool AXNodeObject::IsControllingVideoElement() const { @@ -1172,7 +1171,7 @@ return true; } - return AXObjectImpl::IsClickable(); + return AXObject::IsClickable(); } bool AXNodeObject::IsEnabled() const { @@ -1303,7 +1302,7 @@ IsEnabled() && CanSetFocusAttribute()) { return true; } - return AXObjectImpl::CanSetSelectedAttribute(); + return AXObject::CanSetSelectedAttribute(); } bool AXNodeObject::CanvasHasFallbackContent() const { @@ -1376,7 +1375,7 @@ // Hierarchy leveling starts at 1, to match the aria-level spec. // We measure tree hierarchy by the number of groups that the item is within. level = 1; - for (AXObjectImpl* parent = ParentObject(); parent; + for (AXObject* parent = ParentObject(); parent; parent = parent->ParentObject()) { AccessibilityRole parent_role = parent->RoleValue(); if (parent_role == kGroupRole) @@ -1428,29 +1427,29 @@ } } -AXObjectImpl* AXNodeObject::InPageLinkTarget() const { +AXObject* AXNodeObject::InPageLinkTarget() const { if (!node_ || !isHTMLAnchorElement(node_) || !GetDocument()) - return AXObjectImpl::InPageLinkTarget(); + return AXObject::InPageLinkTarget(); HTMLAnchorElement* anchor = toHTMLAnchorElement(node_); DCHECK(anchor); KURL link_url = anchor->Href(); if (!link_url.IsValid()) - return AXObjectImpl::InPageLinkTarget(); + return AXObject::InPageLinkTarget(); String fragment = link_url.FragmentIdentifier(); if (fragment.IsEmpty()) - return AXObjectImpl::InPageLinkTarget(); + return AXObject::InPageLinkTarget(); KURL document_url = GetDocument()->Url(); if (!document_url.IsValid() || !EqualIgnoringFragmentIdentifier(document_url, link_url)) { - return AXObjectImpl::InPageLinkTarget(); + return AXObject::InPageLinkTarget(); } TreeScope& tree_scope = anchor->GetTreeScope(); Element* target = tree_scope.FindAnchor(fragment); if (!target) - return AXObjectImpl::InPageLinkTarget(); + return AXObject::InPageLinkTarget(); // If the target is not in the accessibility tree, get the first unignored // sibling. return AxObjectCache().FirstAccessibleObjectFromNode(target); @@ -1488,11 +1487,11 @@ case kTreeGridRole: return orientation; default: - return AXObjectImpl::Orientation(); + return AXObject::Orientation(); } } -AXObjectImpl::AXObjectVector AXNodeObject::RadioButtonsInGroup() const { +AXObject::AXObjectVector AXNodeObject::RadioButtonsInGroup() const { AXObjectVector radio_buttons; if (!node_ || RoleValue() != kRadioButtonRole) return radio_buttons; @@ -1502,7 +1501,7 @@ HeapVector<Member<HTMLInputElement>> html_radio_buttons = FindAllRadioButtonsWithSameName(radio_button); for (size_t i = 0; i < html_radio_buttons.size(); ++i) { - AXObjectImpl* ax_radio_button = + AXObject* ax_radio_button = AxObjectCache().GetOrCreate(html_radio_buttons[i]); if (ax_radio_button) radio_buttons.push_back(ax_radio_button); @@ -1512,10 +1511,10 @@ // If the immediate parent is a radio group, return all its children that are // radio buttons. - AXObjectImpl* parent = ParentObject(); + AXObject* parent = ParentObject(); if (parent && parent->RoleValue() == kRadioGroupRole) { for (size_t i = 0; i < parent->Children().size(); ++i) { - AXObjectImpl* child = parent->Children()[i]; + AXObject* child = parent->Children()[i]; DCHECK(child); if (child->RoleValue() == kRadioButtonRole && !child->AccessibilityIsIgnored()) { @@ -1577,12 +1576,12 @@ RGBA32 AXNodeObject::ColorValue() const { if (!isHTMLInputElement(GetNode()) || !IsColorWell()) - return AXObjectImpl::ColorValue(); + return AXObject::ColorValue(); HTMLInputElement* input = toHTMLInputElement(GetNode()); const AtomicString& type = input->getAttribute(typeAttr); if (!EqualIgnoringASCIICase(type, "color")) - return AXObjectImpl::ColorValue(); + return AXObject::ColorValue(); // HTMLInputElement::value always returns a string parseable by Color. Color color; @@ -1615,7 +1614,7 @@ if (!attribute_value.IsEmpty()) return kAriaCurrentStateTrue; - return AXObjectImpl::GetAriaCurrentState(); + return AXObject::GetAriaCurrentState(); } InvalidState AXNodeObject::GetInvalidState() const { @@ -1642,7 +1641,7 @@ return is_invalid ? kInvalidStateTrue : kInvalidStateFalse; } - return AXObjectImpl::GetInvalidState(); + return AXObject::GetInvalidState(); } int AXNodeObject::PosInSet() const { @@ -1651,7 +1650,7 @@ if (HasAOMPropertyOrARIAAttribute(AOMUIntProperty::kPosInSet, pos_in_set)) return pos_in_set; - return AXObjectImpl::IndexInParent() + 1; + return AXObject::IndexInParent() + 1; } return 0; @@ -1931,20 +1930,20 @@ return String(); StringBuilder accumulated_text; - AXObjectImpl* previous = nullptr; + AXObject* previous = nullptr; AXObjectVector children; - HeapVector<Member<AXObjectImpl>> owned_children; + HeapVector<Member<AXObject>> owned_children; ComputeAriaOwnsChildren(owned_children); - for (AXObjectImpl* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { + for (AXObject* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { if (!AxObjectCache().IsAriaOwned(obj)) children.push_back(obj); } for (const auto& owned_child : owned_children) children.push_back(owned_child); - for (AXObjectImpl* child : children) { + for (AXObject* child : children) { // Don't recurse into children that are explicitly marked as aria-hidden. // Note that we don't call isInertOrAriaHidden because that would return // true if any ancestor is hidden, but we need to be able to compute the @@ -2019,12 +2018,12 @@ } void AXNodeObject::GetRelativeBounds( - AXObjectImpl** out_container, + AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const { if (LayoutObjectForRelativeBounds()) { - AXObjectImpl::GetRelativeBounds(out_container, out_bounds_in_container, - out_container_transform); + AXObject::GetRelativeBounds(out_container, out_bounds_in_container, + out_container_transform); return; } @@ -2050,8 +2049,8 @@ Vector<FloatRect> rects; for (Node& child : NodeTraversal::ChildrenOf(*GetNode())) { if (child.IsHTMLElement()) { - if (AXObjectImpl* obj = AxObjectCache().Get(&child)) { - AXObjectImpl* container; + if (AXObject* obj = AxObjectCache().Get(&child)) { + AXObject* container; FloatRect bounds; obj->GetRelativeBounds(&container, bounds, out_container_transform); if (container) { @@ -2072,7 +2071,7 @@ // children, for now, let's return the position of the ancestor that does have // a position, and make it the width of that parent, and about the height of a // line of text, so that it's clear the object is a child of the parent. - for (AXObjectImpl* position_provider = ParentObject(); position_provider; + for (AXObject* position_provider = ParentObject(); position_provider; position_provider = position_provider->ParentObject()) { if (position_provider->IsAXLayoutObject()) { position_provider->GetRelativeBounds( @@ -2103,7 +2102,7 @@ return parent_node; } -AXObjectImpl* AXNodeObject::ComputeParent() const { +AXObject* AXNodeObject::ComputeParent() const { DCHECK(!IsDetached()); if (Node* parent_node = GetParentNodeForComputeParent(GetNode())) return AxObjectCache().GetOrCreate(parent_node); @@ -2111,14 +2110,14 @@ return nullptr; } -AXObjectImpl* AXNodeObject::ComputeParentIfExists() const { +AXObject* AXNodeObject::ComputeParentIfExists() const { if (Node* parent_node = GetParentNodeForComputeParent(GetNode())) return AxObjectCache().Get(parent_node); return nullptr; } -AXObjectImpl* AXNodeObject::RawFirstChild() const { +AXObject* AXNodeObject::RawFirstChild() const { if (!GetNode()) return 0; @@ -2130,7 +2129,7 @@ return AxObjectCache().GetOrCreate(first_child); } -AXObjectImpl* AXNodeObject::RawNextSibling() const { +AXObject* AXNodeObject::RawNextSibling() const { if (!GetNode()) return 0; @@ -2158,11 +2157,11 @@ if (GetLayoutObject() && !isHTMLCanvasElement(*node_)) return; - HeapVector<Member<AXObjectImpl>> owned_children; + HeapVector<Member<AXObject>> owned_children; ComputeAriaOwnsChildren(owned_children); for (Node& child : NodeTraversal::ChildrenOf(*node_)) { - AXObjectImpl* child_obj = AxObjectCache().GetOrCreate(&child); + AXObject* child_obj = AxObjectCache().GetOrCreate(&child); if (child_obj && !AxObjectCache().IsAriaOwned(child_obj)) AddChild(child_obj); } @@ -2174,11 +2173,11 @@ child->SetParent(this); } -void AXNodeObject::AddChild(AXObjectImpl* child) { +void AXNodeObject::AddChild(AXObject* child) { InsertChild(child, children_.size()); } -void AXNodeObject::InsertChild(AXObjectImpl* child, unsigned index) { +void AXNodeObject::InsertChild(AXObject* child, unsigned index) { if (!child) return; @@ -2257,7 +2256,7 @@ return ToElement(node); } - if (AXObjectImpl::IsARIAInput(AriaRoleAttribute())) + if (AXObject::IsARIAInput(AriaRoleAttribute())) return ToElement(node); if (IsImageButton()) @@ -2316,7 +2315,7 @@ node_ = node; } -AXObjectImpl* AXNodeObject::CorrespondingControlForLabelElement() const { +AXObject* AXNodeObject::CorrespondingControlForLabelElement() const { HTMLLabelElement* label_element = LabelElementContainer(); if (!label_element) return 0; @@ -2415,7 +2414,7 @@ // If AX elements are created now, they could interrogate the layout tree // while it's in a funky state. At the same time, process ARIA live region // changes. - for (AXObjectImpl* parent = this; parent; + for (AXObject* parent = this; parent; parent = parent->ParentObjectIfExists()) { parent->SetNeedsToUpdateChildren(); @@ -2447,13 +2446,12 @@ AxObjectCache().PostNotification(this, AXObjectCacheImpl::kAXSelectedTextChanged); if (GetDocument()) { - AXObjectImpl* document_object = - AxObjectCache().GetOrCreate(GetDocument()); + AXObject* document_object = AxObjectCache().GetOrCreate(GetDocument()); AxObjectCache().PostNotification( document_object, AXObjectCacheImpl::kAXDocumentSelectionChanged); } } else { - AXObjectImpl::SelectionChanged(); // Calls selectionChanged on parent. + AXObject::SelectionChanged(); // Calls selectionChanged on parent. } } @@ -2463,7 +2461,7 @@ AXObjectCacheImpl& cache = AxObjectCache(); for (Node* parent_node = GetNode(); parent_node; parent_node = parent_node->parentNode()) { - AXObjectImpl* parent = cache.Get(parent_node); + AXObject* parent = cache.Get(parent_node); if (!parent) continue; @@ -2490,7 +2488,7 @@ } void AXNodeObject::ComputeAriaOwnsChildren( - HeapVector<Member<AXObjectImpl>>& owned_children) const { + HeapVector<Member<AXObject>>& owned_children) const { if (!HasAttribute(aria_ownsAttr)) return; @@ -2742,8 +2740,7 @@ } } if (figcaption) { - AXObjectImpl* figcaption_ax_object = - AxObjectCache().GetOrCreate(figcaption); + AXObject* figcaption_ax_object = AxObjectCache().GetOrCreate(figcaption); if (figcaption_ax_object) { text_alternative = RecursiveTextAlternative(*figcaption_ax_object, false, visited); @@ -2807,7 +2804,7 @@ } HTMLTableCaptionElement* caption = table_element->caption(); if (caption) { - AXObjectImpl* caption_ax_object = AxObjectCache().GetOrCreate(caption); + AXObject* caption_ax_object = AxObjectCache().GetOrCreate(caption); if (caption_ax_object) { text_alternative = RecursiveTextAlternative(*caption_ax_object, false, visited); @@ -2864,7 +2861,7 @@ ToContainerNode(*(GetNode())), HasTagName(SVGNames::titleTag)); if (title) { - AXObjectImpl* title_ax_object = AxObjectCache().GetOrCreate(title); + AXObject* title_ax_object = AxObjectCache().GetOrCreate(title); if (title_ax_object && !visited.Contains(title_ax_object)) { text_alternative = RecursiveTextAlternative(*title_ax_object, false, visited); @@ -2896,7 +2893,7 @@ } HTMLElement* legend = toHTMLFieldSetElement(GetNode())->Legend(); if (legend) { - AXObjectImpl* legend_ax_object = AxObjectCache().GetOrCreate(legend); + AXObject* legend_ax_object = AxObjectCache().GetOrCreate(legend); // Avoid an infinite loop if (legend_ax_object && !visited.Contains(legend_ax_object)) { text_alternative = @@ -2959,8 +2956,7 @@ text_alternative = document->title(); Element* title_element = document->TitleElement(); - AXObjectImpl* title_ax_object = - AxObjectCache().GetOrCreate(title_element); + AXObject* title_ax_object = AxObjectCache().GetOrCreate(title_element); if (title_ax_object) { if (related_objects) { local_related_objects.push_back( @@ -3087,7 +3083,7 @@ } HTMLTableCaptionElement* caption = table_element->caption(); if (caption) { - AXObjectImpl* caption_ax_object = AxObjectCache().GetOrCreate(caption); + AXObject* caption_ax_object = AxObjectCache().GetOrCreate(caption); if (caption_ax_object) { AXObjectSet visited; description = @@ -3218,7 +3214,7 @@ DEFINE_TRACE(AXNodeObject) { visitor->Trace(node_); - AXObjectImpl::Trace(visitor); + AXObject::Trace(visitor); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h index 0b779ef..5e03781 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h
@@ -30,7 +30,7 @@ #define AXNodeObject_h #include "modules/ModulesExport.h" -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" #include "platform/wtf/Forward.h" namespace blink { @@ -40,7 +40,7 @@ class HTMLLabelElement; class Node; -class MODULES_EXPORT AXNodeObject : public AXObjectImpl { +class MODULES_EXPORT AXNodeObject : public AXObject { WTF_MAKE_NONCOPYABLE(AXNodeObject); protected: @@ -60,35 +60,35 @@ #endif bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const override; - const AXObjectImpl* InheritsPresentationalRoleFrom() const override; + const AXObject* InheritsPresentationalRoleFrom() const override; virtual AccessibilityRole DetermineAccessibilityRole(); virtual AccessibilityRole NativeAccessibilityRoleIgnoringAria() const; String AccessibilityDescriptionForElements( HeapVector<Member<Element>>& elements) const; void AlterSliderValue(bool increase); - AXObjectImpl* ActiveDescendant() override; + AXObject* ActiveDescendant() override; String AriaAccessibilityDescription() const; String AriaAutoComplete() const; AccessibilityRole DetermineAriaRoleAttribute() const; void AccessibilityChildrenFromAttribute(QualifiedName attr, - AXObjectImpl::AXObjectVector&) const; + AXObject::AXObjectVector&) const; bool HasContentEditableAttributeSet() const; bool IsTextControl() const override; // This returns true if it's focusable but it's not content editable and it's // not a control or ARIA control. bool IsGenericFocusableElement() const; - AXObjectImpl* MenuButtonForMenu() const; + AXObject* MenuButtonForMenu() const; Element* MenuItemElementForMenu() const; Element* MouseButtonListener() const; AccessibilityRole RemapAriaRoleDueToParent(AccessibilityRole) const; bool IsNativeCheckboxOrRadio() const; void SetNode(Node*); - AXObjectImpl* CorrespondingControlForLabelElement() const; + AXObject* CorrespondingControlForLabelElement() const; HTMLLabelElement* LabelElementContainer() const; // - // Overridden from AXObjectImpl. + // Overridden from AXObject. // void Init() override; @@ -146,7 +146,7 @@ unsigned HierarchicalLevel() const final; void Markers(Vector<DocumentMarker::MarkerType>&, Vector<AXRange>&) const override; - AXObjectImpl* InPageLinkTarget() const override; + AXObject* InPageLinkTarget() const override; AccessibilityOrientation Orientation() const override; AXObjectVector RadioButtonsInGroup() const override; static HeapVector<Member<HTMLInputElement>> FindAllRadioButtonsWithSameName( @@ -185,21 +185,21 @@ bool NameFromLabelElement() const override; // Location - void GetRelativeBounds(AXObjectImpl** out_container, + void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const override; // High-level accessibility tree access. - AXObjectImpl* ComputeParent() const override; - AXObjectImpl* ComputeParentIfExists() const override; + AXObject* ComputeParent() const override; + AXObject* ComputeParentIfExists() const override; // Low-level accessibility tree exploration. - AXObjectImpl* RawFirstChild() const override; - AXObjectImpl* RawNextSibling() const override; + AXObject* RawFirstChild() const override; + AXObject* RawNextSibling() const override; void AddChildren() override; bool CanHaveChildren() const override; - void AddChild(AXObjectImpl*); - void InsertChild(AXObjectImpl*, unsigned index); + void AddChild(AXObject*); + void InsertChild(AXObject*, unsigned index); // DOM and Render tree access. Element* ActionElement() const override; @@ -225,7 +225,7 @@ // Aria-owns. void ComputeAriaOwnsChildren( - HeapVector<Member<AXObjectImpl>>& owned_children) const; + HeapVector<Member<AXObject>>& owned_children) const; private: Member<Node> node_;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp index f0db96ae..9f0dddb 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -1,254 +1,2096 @@ -// 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. +/* + * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ #include "modules/accessibility/AXObject.h" -#include "core/HTMLElementTypeHelpers.h" -#include "core/dom/Element.h" -#include "core/dom/Node.h" -#include "platform/wtf/Assertions.h" +#include "SkMatrix44.h" +#include "core/InputTypeNames.h" +#include "core/css/resolver/StyleResolver.h" +#include "core/dom/AccessibleNode.h" +#include "core/dom/UserGestureIndicator.h" +#include "core/editing/EditingUtilities.h" +#include "core/editing/VisibleUnits.h" +#include "core/frame/LocalFrame.h" +#include "core/frame/LocalFrameView.h" +#include "core/frame/Settings.h" +#include "core/html/HTMLDialogElement.h" +#include "core/html/HTMLFrameOwnerElement.h" +#include "core/html/HTMLInputElement.h" +#include "core/html/parser/HTMLParserIdioms.h" +#include "core/layout/LayoutBoxModelObject.h" +#include "modules/accessibility/AXObjectCacheImpl.h" +#include "platform/text/PlatformLocale.h" #include "platform/wtf/HashSet.h" -#include "platform/wtf/text/StringHash.h" +#include "platform/wtf/StdLibExtras.h" #include "platform/wtf/text/WTFString.h" -#include "public/web/WebAXEnums.h" + +using blink::WebLocalizedString; namespace blink { -STATIC_ASSERT_ENUM(kWebAXRoleAbbr, kAbbrRole); -STATIC_ASSERT_ENUM(kWebAXRoleAlertDialog, kAlertDialogRole); -STATIC_ASSERT_ENUM(kWebAXRoleAlert, kAlertRole); -STATIC_ASSERT_ENUM(kWebAXRoleAnchor, kAnchorRole); -STATIC_ASSERT_ENUM(kWebAXRoleAnnotation, kAnnotationRole); -STATIC_ASSERT_ENUM(kWebAXRoleApplication, kApplicationRole); -STATIC_ASSERT_ENUM(kWebAXRoleArticle, kArticleRole); -STATIC_ASSERT_ENUM(kWebAXRoleAudio, kAudioRole); -STATIC_ASSERT_ENUM(kWebAXRoleBanner, kBannerRole); -STATIC_ASSERT_ENUM(kWebAXRoleBlockquote, kBlockquoteRole); -STATIC_ASSERT_ENUM(kWebAXRoleBusyIndicator, kBusyIndicatorRole); -STATIC_ASSERT_ENUM(kWebAXRoleButton, kButtonRole); -STATIC_ASSERT_ENUM(kWebAXRoleCanvas, kCanvasRole); -STATIC_ASSERT_ENUM(kWebAXRoleCaption, kCaptionRole); -STATIC_ASSERT_ENUM(kWebAXRoleCell, kCellRole); -STATIC_ASSERT_ENUM(kWebAXRoleCheckBox, kCheckBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleColorWell, kColorWellRole); -STATIC_ASSERT_ENUM(kWebAXRoleColumnHeader, kColumnHeaderRole); -STATIC_ASSERT_ENUM(kWebAXRoleColumn, kColumnRole); -STATIC_ASSERT_ENUM(kWebAXRoleComboBox, kComboBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleComplementary, kComplementaryRole); -STATIC_ASSERT_ENUM(kWebAXRoleContentInfo, kContentInfoRole); -STATIC_ASSERT_ENUM(kWebAXRoleDate, kDateRole); -STATIC_ASSERT_ENUM(kWebAXRoleDateTime, kDateTimeRole); -STATIC_ASSERT_ENUM(kWebAXRoleDefinition, kDefinitionRole); -STATIC_ASSERT_ENUM(kWebAXRoleDescriptionListDetail, kDescriptionListDetailRole); -STATIC_ASSERT_ENUM(kWebAXRoleDescriptionList, kDescriptionListRole); -STATIC_ASSERT_ENUM(kWebAXRoleDescriptionListTerm, kDescriptionListTermRole); -STATIC_ASSERT_ENUM(kWebAXRoleDetails, kDetailsRole); -STATIC_ASSERT_ENUM(kWebAXRoleDialog, kDialogRole); -STATIC_ASSERT_ENUM(kWebAXRoleDirectory, kDirectoryRole); -STATIC_ASSERT_ENUM(kWebAXRoleDisclosureTriangle, kDisclosureTriangleRole); -STATIC_ASSERT_ENUM(kWebAXRoleDocument, kDocumentRole); -STATIC_ASSERT_ENUM(kWebAXRoleEmbeddedObject, kEmbeddedObjectRole); -STATIC_ASSERT_ENUM(kWebAXRoleFeed, kFeedRole); -STATIC_ASSERT_ENUM(kWebAXRoleFigcaption, kFigcaptionRole); -STATIC_ASSERT_ENUM(kWebAXRoleFigure, kFigureRole); -STATIC_ASSERT_ENUM(kWebAXRoleFooter, kFooterRole); -STATIC_ASSERT_ENUM(kWebAXRoleForm, kFormRole); -STATIC_ASSERT_ENUM(kWebAXRoleGenericContainer, kGenericContainerRole); -STATIC_ASSERT_ENUM(kWebAXRoleGrid, kGridRole); -STATIC_ASSERT_ENUM(kWebAXRoleGroup, kGroupRole); -STATIC_ASSERT_ENUM(kWebAXRoleHeading, kHeadingRole); -STATIC_ASSERT_ENUM(kWebAXRoleIframe, kIframeRole); -STATIC_ASSERT_ENUM(kWebAXRoleIframePresentational, kIframePresentationalRole); -STATIC_ASSERT_ENUM(kWebAXRoleIgnored, kIgnoredRole); -STATIC_ASSERT_ENUM(kWebAXRoleImageMapLink, kImageMapLinkRole); -STATIC_ASSERT_ENUM(kWebAXRoleImageMap, kImageMapRole); -STATIC_ASSERT_ENUM(kWebAXRoleImage, kImageRole); -STATIC_ASSERT_ENUM(kWebAXRoleInlineTextBox, kInlineTextBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleInputTime, kInputTimeRole); -STATIC_ASSERT_ENUM(kWebAXRoleLabel, kLabelRole); -STATIC_ASSERT_ENUM(kWebAXRoleLegend, kLegendRole); -STATIC_ASSERT_ENUM(kWebAXRoleLineBreak, kLineBreakRole); -STATIC_ASSERT_ENUM(kWebAXRoleLink, kLinkRole); -STATIC_ASSERT_ENUM(kWebAXRoleListBoxOption, kListBoxOptionRole); -STATIC_ASSERT_ENUM(kWebAXRoleListBox, kListBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleListItem, kListItemRole); -STATIC_ASSERT_ENUM(kWebAXRoleListMarker, kListMarkerRole); -STATIC_ASSERT_ENUM(kWebAXRoleList, kListRole); -STATIC_ASSERT_ENUM(kWebAXRoleLog, kLogRole); -STATIC_ASSERT_ENUM(kWebAXRoleMain, kMainRole); -STATIC_ASSERT_ENUM(kWebAXRoleMark, kMarkRole); -STATIC_ASSERT_ENUM(kWebAXRoleMarquee, kMarqueeRole); -STATIC_ASSERT_ENUM(kWebAXRoleMath, kMathRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuBar, kMenuBarRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuButton, kMenuButtonRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuItem, kMenuItemRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuItemCheckBox, kMenuItemCheckBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuItemRadio, kMenuItemRadioRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuListOption, kMenuListOptionRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenuListPopup, kMenuListPopupRole); -STATIC_ASSERT_ENUM(kWebAXRoleMenu, kMenuRole); -STATIC_ASSERT_ENUM(kWebAXRoleMeter, kMeterRole); -STATIC_ASSERT_ENUM(kWebAXRoleNavigation, kNavigationRole); -STATIC_ASSERT_ENUM(kWebAXRoleNone, kNoneRole); -STATIC_ASSERT_ENUM(kWebAXRoleNote, kNoteRole); -STATIC_ASSERT_ENUM(kWebAXRoleOutline, kOutlineRole); -STATIC_ASSERT_ENUM(kWebAXRoleParagraph, kParagraphRole); -STATIC_ASSERT_ENUM(kWebAXRolePopUpButton, kPopUpButtonRole); -STATIC_ASSERT_ENUM(kWebAXRolePre, kPreRole); -STATIC_ASSERT_ENUM(kWebAXRolePresentational, kPresentationalRole); -STATIC_ASSERT_ENUM(kWebAXRoleProgressIndicator, kProgressIndicatorRole); -STATIC_ASSERT_ENUM(kWebAXRoleRadioButton, kRadioButtonRole); -STATIC_ASSERT_ENUM(kWebAXRoleRadioGroup, kRadioGroupRole); -STATIC_ASSERT_ENUM(kWebAXRoleRegion, kRegionRole); -STATIC_ASSERT_ENUM(kWebAXRoleRootWebArea, kRootWebAreaRole); -STATIC_ASSERT_ENUM(kWebAXRoleRowHeader, kRowHeaderRole); -STATIC_ASSERT_ENUM(kWebAXRoleRow, kRowRole); -STATIC_ASSERT_ENUM(kWebAXRoleRuby, kRubyRole); -STATIC_ASSERT_ENUM(kWebAXRoleRuler, kRulerRole); -STATIC_ASSERT_ENUM(kWebAXRoleSVGRoot, kSVGRootRole); -STATIC_ASSERT_ENUM(kWebAXRoleScrollArea, kScrollAreaRole); -STATIC_ASSERT_ENUM(kWebAXRoleScrollBar, kScrollBarRole); -STATIC_ASSERT_ENUM(kWebAXRoleSeamlessWebArea, kSeamlessWebAreaRole); -STATIC_ASSERT_ENUM(kWebAXRoleSearch, kSearchRole); -STATIC_ASSERT_ENUM(kWebAXRoleSearchBox, kSearchBoxRole); -STATIC_ASSERT_ENUM(kWebAXRoleSlider, kSliderRole); -STATIC_ASSERT_ENUM(kWebAXRoleSliderThumb, kSliderThumbRole); -STATIC_ASSERT_ENUM(kWebAXRoleSpinButtonPart, kSpinButtonPartRole); -STATIC_ASSERT_ENUM(kWebAXRoleSpinButton, kSpinButtonRole); -STATIC_ASSERT_ENUM(kWebAXRoleSplitter, kSplitterRole); -STATIC_ASSERT_ENUM(kWebAXRoleStaticText, kStaticTextRole); -STATIC_ASSERT_ENUM(kWebAXRoleStatus, kStatusRole); -STATIC_ASSERT_ENUM(kWebAXRoleSwitch, kSwitchRole); -STATIC_ASSERT_ENUM(kWebAXRoleTabGroup, kTabGroupRole); -STATIC_ASSERT_ENUM(kWebAXRoleTabList, kTabListRole); -STATIC_ASSERT_ENUM(kWebAXRoleTabPanel, kTabPanelRole); -STATIC_ASSERT_ENUM(kWebAXRoleTab, kTabRole); -STATIC_ASSERT_ENUM(kWebAXRoleTableHeaderContainer, kTableHeaderContainerRole); -STATIC_ASSERT_ENUM(kWebAXRoleTable, kTableRole); -STATIC_ASSERT_ENUM(kWebAXRoleTerm, kTermRole); -STATIC_ASSERT_ENUM(kWebAXRoleTextField, kTextFieldRole); -STATIC_ASSERT_ENUM(kWebAXRoleTime, kTimeRole); -STATIC_ASSERT_ENUM(kWebAXRoleTimer, kTimerRole); -STATIC_ASSERT_ENUM(kWebAXRoleToggleButton, kToggleButtonRole); -STATIC_ASSERT_ENUM(kWebAXRoleToolbar, kToolbarRole); -STATIC_ASSERT_ENUM(kWebAXRoleTreeGrid, kTreeGridRole); -STATIC_ASSERT_ENUM(kWebAXRoleTreeItem, kTreeItemRole); -STATIC_ASSERT_ENUM(kWebAXRoleTree, kTreeRole); -STATIC_ASSERT_ENUM(kWebAXRoleUnknown, kUnknownRole); -STATIC_ASSERT_ENUM(kWebAXRoleUserInterfaceTooltip, kUserInterfaceTooltipRole); -STATIC_ASSERT_ENUM(kWebAXRoleVideo, kVideoRole); -STATIC_ASSERT_ENUM(kWebAXRoleWebArea, kWebAreaRole); -STATIC_ASSERT_ENUM(kWebAXRoleWindow, kWindowRole); +using namespace HTMLNames; -STATIC_ASSERT_ENUM(kWebAXStateBusy, kAXBusyState); -STATIC_ASSERT_ENUM(kWebAXStateEnabled, kAXEnabledState); -STATIC_ASSERT_ENUM(kWebAXStateExpanded, kAXExpandedState); -STATIC_ASSERT_ENUM(kWebAXStateFocusable, kAXFocusableState); -STATIC_ASSERT_ENUM(kWebAXStateFocused, kAXFocusedState); -STATIC_ASSERT_ENUM(kWebAXStateHaspopup, kAXHaspopupState); -STATIC_ASSERT_ENUM(kWebAXStateHovered, kAXHoveredState); -STATIC_ASSERT_ENUM(kWebAXStateInvisible, kAXInvisibleState); -STATIC_ASSERT_ENUM(kWebAXStateLinked, kAXLinkedState); -STATIC_ASSERT_ENUM(kWebAXStateMultiline, kAXMultilineState); -STATIC_ASSERT_ENUM(kWebAXStateMultiselectable, kAXMultiselectableState); -STATIC_ASSERT_ENUM(kWebAXStateOffscreen, kAXOffscreenState); -STATIC_ASSERT_ENUM(kWebAXStateProtected, kAXProtectedState); -STATIC_ASSERT_ENUM(kWebAXStateReadonly, kAXReadonlyState); -STATIC_ASSERT_ENUM(kWebAXStateRequired, kAXRequiredState); -STATIC_ASSERT_ENUM(kWebAXStateSelectable, kAXSelectableState); -STATIC_ASSERT_ENUM(kWebAXStateSelected, kAXSelectedState); -STATIC_ASSERT_ENUM(kWebAXStateVertical, kAXVerticalState); -STATIC_ASSERT_ENUM(kWebAXStateVisited, kAXVisitedState); +namespace { -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kNone, AXDefaultActionVerb::kNone); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kActivate, - AXDefaultActionVerb::kActivate); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kCheck, AXDefaultActionVerb::kCheck); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kClick, AXDefaultActionVerb::kClick); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kJump, AXDefaultActionVerb::kJump); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kOpen, AXDefaultActionVerb::kOpen); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kPress, AXDefaultActionVerb::kPress); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kSelect, - AXDefaultActionVerb::kSelect); -STATIC_ASSERT_ENUM(WebAXDefaultActionVerb::kUncheck, - AXDefaultActionVerb::kUncheck); +struct AccessibilityRoleHashTraits : HashTraits<AccessibilityRole> { + static const bool kEmptyValueIsZero = true; + static AccessibilityRole EmptyValue() { + return AccessibilityRole::kUnknownRole; + } +}; -STATIC_ASSERT_ENUM(kWebAXTextDirectionLR, kAccessibilityTextDirectionLTR); -STATIC_ASSERT_ENUM(kWebAXTextDirectionRL, kAccessibilityTextDirectionRTL); -STATIC_ASSERT_ENUM(kWebAXTextDirectionTB, kAccessibilityTextDirectionTTB); -STATIC_ASSERT_ENUM(kWebAXTextDirectionBT, kAccessibilityTextDirectionBTT); +using ARIARoleMap = HashMap<String, + AccessibilityRole, + CaseFoldingHash, + HashTraits<String>, + AccessibilityRoleHashTraits>; -STATIC_ASSERT_ENUM(kWebAXSortDirectionUndefined, kSortDirectionUndefined); -STATIC_ASSERT_ENUM(kWebAXSortDirectionNone, kSortDirectionNone); -STATIC_ASSERT_ENUM(kWebAXSortDirectionAscending, kSortDirectionAscending); -STATIC_ASSERT_ENUM(kWebAXSortDirectionDescending, kSortDirectionDescending); -STATIC_ASSERT_ENUM(kWebAXSortDirectionOther, kSortDirectionOther); +struct RoleEntry { + const char* aria_role; + AccessibilityRole webcore_role; +}; -STATIC_ASSERT_ENUM(kWebAXExpandedUndefined, kExpandedUndefined); -STATIC_ASSERT_ENUM(kWebAXExpandedCollapsed, kExpandedCollapsed); -STATIC_ASSERT_ENUM(kWebAXExpandedExpanded, kExpandedExpanded); +const RoleEntry kRoles[] = {{"alert", kAlertRole}, + {"alertdialog", kAlertDialogRole}, + {"application", kApplicationRole}, + {"article", kArticleRole}, + {"banner", kBannerRole}, + {"button", kButtonRole}, + {"cell", kCellRole}, + {"checkbox", kCheckBoxRole}, + {"columnheader", kColumnHeaderRole}, + {"combobox", kComboBoxRole}, + {"complementary", kComplementaryRole}, + {"contentinfo", kContentInfoRole}, + {"definition", kDefinitionRole}, + {"dialog", kDialogRole}, + {"directory", kDirectoryRole}, + {"document", kDocumentRole}, + {"feed", kFeedRole}, + {"figure", kFigureRole}, + {"form", kFormRole}, + {"grid", kGridRole}, + {"gridcell", kCellRole}, + {"group", kGroupRole}, + {"heading", kHeadingRole}, + {"img", kImageRole}, + {"link", kLinkRole}, + {"list", kListRole}, + {"listbox", kListBoxRole}, + {"listitem", kListItemRole}, + {"log", kLogRole}, + {"main", kMainRole}, + {"marquee", kMarqueeRole}, + {"math", kMathRole}, + {"menu", kMenuRole}, + {"menubar", kMenuBarRole}, + {"menuitem", kMenuItemRole}, + {"menuitemcheckbox", kMenuItemCheckBoxRole}, + {"menuitemradio", kMenuItemRadioRole}, + {"navigation", kNavigationRole}, + {"none", kNoneRole}, + {"note", kNoteRole}, + {"option", kListBoxOptionRole}, + {"presentation", kPresentationalRole}, + {"progressbar", kProgressIndicatorRole}, + {"radio", kRadioButtonRole}, + {"radiogroup", kRadioGroupRole}, + {"region", kRegionRole}, + {"row", kRowRole}, + {"rowheader", kRowHeaderRole}, + {"scrollbar", kScrollBarRole}, + {"search", kSearchRole}, + {"searchbox", kSearchBoxRole}, + {"separator", kSplitterRole}, + {"slider", kSliderRole}, + {"spinbutton", kSpinButtonRole}, + {"status", kStatusRole}, + {"switch", kSwitchRole}, + {"tab", kTabRole}, + {"table", kTableRole}, + {"tablist", kTabListRole}, + {"tabpanel", kTabPanelRole}, + {"term", kTermRole}, + {"text", kStaticTextRole}, + {"textbox", kTextFieldRole}, + {"timer", kTimerRole}, + {"toolbar", kToolbarRole}, + {"tooltip", kUserInterfaceTooltipRole}, + {"tree", kTreeRole}, + {"treegrid", kTreeGridRole}, + {"treeitem", kTreeItemRole}}; -STATIC_ASSERT_ENUM(kWebAXOrientationUndefined, - kAccessibilityOrientationUndefined); -STATIC_ASSERT_ENUM(kWebAXOrientationVertical, - kAccessibilityOrientationVertical); -STATIC_ASSERT_ENUM(kWebAXOrientationHorizontal, - kAccessibilityOrientationHorizontal); +struct InternalRoleEntry { + AccessibilityRole webcore_role; + const char* internal_role_name; +}; -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateUndefined, kAriaCurrentStateUndefined); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateFalse, kAriaCurrentStateFalse); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateTrue, kAriaCurrentStateTrue); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStatePage, kAriaCurrentStatePage); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateStep, kAriaCurrentStateStep); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateLocation, kAriaCurrentStateLocation); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateDate, kAriaCurrentStateDate); -STATIC_ASSERT_ENUM(kWebAXAriaCurrentStateTime, kAriaCurrentStateTime); +const InternalRoleEntry kInternalRoles[] = { + {kUnknownRole, "Unknown"}, + {kAbbrRole, "Abbr"}, + {kAlertDialogRole, "AlertDialog"}, + {kAlertRole, "Alert"}, + {kAnchorRole, "Anchor"}, + {kAnnotationRole, "Annotation"}, + {kApplicationRole, "Application"}, + {kArticleRole, "Article"}, + {kAudioRole, "Audio"}, + {kBannerRole, "Banner"}, + {kBlockquoteRole, "Blockquote"}, + // TODO(nektar): Delete busy_indicator role. It's used nowhere. + {kBusyIndicatorRole, "BusyIndicator"}, + {kButtonRole, "Button"}, + {kCanvasRole, "Canvas"}, + {kCaptionRole, "Caption"}, + {kCellRole, "Cell"}, + {kCheckBoxRole, "CheckBox"}, + {kColorWellRole, "ColorWell"}, + {kColumnHeaderRole, "ColumnHeader"}, + {kColumnRole, "Column"}, + {kComboBoxRole, "ComboBox"}, + {kComplementaryRole, "Complementary"}, + {kContentInfoRole, "ContentInfo"}, + {kDateRole, "Date"}, + {kDateTimeRole, "DateTime"}, + {kDefinitionRole, "Definition"}, + {kDescriptionListDetailRole, "DescriptionListDetail"}, + {kDescriptionListRole, "DescriptionList"}, + {kDescriptionListTermRole, "DescriptionListTerm"}, + {kDetailsRole, "Details"}, + {kDialogRole, "Dialog"}, + {kDirectoryRole, "Directory"}, + {kDisclosureTriangleRole, "DisclosureTriangle"}, + {kDocumentRole, "Document"}, + {kEmbeddedObjectRole, "EmbeddedObject"}, + {kFeedRole, "feed"}, + {kFigcaptionRole, "Figcaption"}, + {kFigureRole, "Figure"}, + {kFooterRole, "Footer"}, + {kFormRole, "Form"}, + {kGenericContainerRole, "GenericContainer"}, + {kGridRole, "Grid"}, + {kGroupRole, "Group"}, + {kHeadingRole, "Heading"}, + {kIframePresentationalRole, "IframePresentational"}, + {kIframeRole, "Iframe"}, + {kIgnoredRole, "Ignored"}, + {kImageMapLinkRole, "ImageMapLink"}, + {kImageMapRole, "ImageMap"}, + {kImageRole, "Image"}, + {kInlineTextBoxRole, "InlineTextBox"}, + {kInputTimeRole, "InputTime"}, + {kLabelRole, "Label"}, + {kLegendRole, "Legend"}, + {kLinkRole, "Link"}, + {kLineBreakRole, "LineBreak"}, + {kListBoxOptionRole, "ListBoxOption"}, + {kListBoxRole, "ListBox"}, + {kListItemRole, "ListItem"}, + {kListMarkerRole, "ListMarker"}, + {kListRole, "List"}, + {kLogRole, "Log"}, + {kMainRole, "Main"}, + {kMarkRole, "Mark"}, + {kMarqueeRole, "Marquee"}, + {kMathRole, "Math"}, + {kMenuBarRole, "MenuBar"}, + {kMenuButtonRole, "MenuButton"}, + {kMenuItemRole, "MenuItem"}, + {kMenuItemCheckBoxRole, "MenuItemCheckBox"}, + {kMenuItemRadioRole, "MenuItemRadio"}, + {kMenuListOptionRole, "MenuListOption"}, + {kMenuListPopupRole, "MenuListPopup"}, + {kMenuRole, "Menu"}, + {kMeterRole, "Meter"}, + {kNavigationRole, "Navigation"}, + {kNoneRole, "None"}, + {kNoteRole, "Note"}, + {kOutlineRole, "Outline"}, + {kParagraphRole, "Paragraph"}, + {kPopUpButtonRole, "PopUpButton"}, + {kPreRole, "Pre"}, + {kPresentationalRole, "Presentational"}, + {kProgressIndicatorRole, "ProgressIndicator"}, + {kRadioButtonRole, "RadioButton"}, + {kRadioGroupRole, "RadioGroup"}, + {kRegionRole, "Region"}, + {kRootWebAreaRole, "RootWebArea"}, + {kRowHeaderRole, "RowHeader"}, + {kRowRole, "Row"}, + {kRubyRole, "Ruby"}, + {kRulerRole, "Ruler"}, + {kSVGRootRole, "SVGRoot"}, + {kScrollAreaRole, "ScrollArea"}, + {kScrollBarRole, "ScrollBar"}, + {kSeamlessWebAreaRole, "SeamlessWebArea"}, + {kSearchRole, "Search"}, + {kSearchBoxRole, "SearchBox"}, + {kSliderRole, "Slider"}, + {kSliderThumbRole, "SliderThumb"}, + {kSpinButtonPartRole, "SpinButtonPart"}, + {kSpinButtonRole, "SpinButton"}, + {kSplitterRole, "Splitter"}, + {kStaticTextRole, "StaticText"}, + {kStatusRole, "Status"}, + {kSwitchRole, "Switch"}, + {kTabGroupRole, "TabGroup"}, + {kTabListRole, "TabList"}, + {kTabPanelRole, "TabPanel"}, + {kTabRole, "Tab"}, + {kTableHeaderContainerRole, "TableHeaderContainer"}, + {kTableRole, "Table"}, + {kTermRole, "Term"}, + {kTextFieldRole, "TextField"}, + {kTimeRole, "Time"}, + {kTimerRole, "Timer"}, + {kToggleButtonRole, "ToggleButton"}, + {kToolbarRole, "Toolbar"}, + {kTreeGridRole, "TreeGrid"}, + {kTreeItemRole, "TreeItem"}, + {kTreeRole, "Tree"}, + {kUserInterfaceTooltipRole, "UserInterfaceTooltip"}, + {kVideoRole, "Video"}, + {kWebAreaRole, "WebArea"}, + {kWindowRole, "Window"}}; -STATIC_ASSERT_ENUM(kWebAXInvalidStateUndefined, kInvalidStateUndefined); -STATIC_ASSERT_ENUM(kWebAXInvalidStateFalse, kInvalidStateFalse); -STATIC_ASSERT_ENUM(kWebAXInvalidStateTrue, kInvalidStateTrue); -STATIC_ASSERT_ENUM(kWebAXInvalidStateSpelling, kInvalidStateSpelling); -STATIC_ASSERT_ENUM(kWebAXInvalidStateGrammar, kInvalidStateGrammar); -STATIC_ASSERT_ENUM(kWebAXInvalidStateOther, kInvalidStateOther); +static_assert(WTF_ARRAY_LENGTH(kInternalRoles) == kNumRoles, + "Not all internal roles have an entry in internalRoles array"); -STATIC_ASSERT_ENUM(kWebAXTextStyleNone, kTextStyleNone); -STATIC_ASSERT_ENUM(kWebAXTextStyleBold, kTextStyleBold); -STATIC_ASSERT_ENUM(kWebAXTextStyleItalic, kTextStyleItalic); -STATIC_ASSERT_ENUM(kWebAXTextStyleUnderline, kTextStyleUnderline); -STATIC_ASSERT_ENUM(kWebAXTextStyleLineThrough, kTextStyleLineThrough); +// Roles which we need to map in the other direction +const RoleEntry kReverseRoles[] = { + {"button", kToggleButtonRole}, {"combobox", kPopUpButtonRole}, + {"contentinfo", kFooterRole}, {"menuitem", kMenuButtonRole}, + {"menuitem", kMenuListOptionRole}, {"progressbar", kMeterRole}, + {"textbox", kTextFieldRole}}; -STATIC_ASSERT_ENUM(kWebAXNameFromUninitialized, kAXNameFromUninitialized); -STATIC_ASSERT_ENUM(kWebAXNameFromAttribute, kAXNameFromAttribute); -STATIC_ASSERT_ENUM(kWebAXNameFromAttributeExplicitlyEmpty, - kAXNameFromAttributeExplicitlyEmpty); -STATIC_ASSERT_ENUM(kWebAXNameFromCaption, kAXNameFromCaption); -STATIC_ASSERT_ENUM(kWebAXNameFromContents, kAXNameFromContents); -STATIC_ASSERT_ENUM(kWebAXNameFromPlaceholder, kAXNameFromPlaceholder); -STATIC_ASSERT_ENUM(kWebAXNameFromRelatedElement, kAXNameFromRelatedElement); -STATIC_ASSERT_ENUM(kWebAXNameFromValue, kAXNameFromValue); -STATIC_ASSERT_ENUM(kWebAXNameFromTitle, kAXNameFromTitle); +static ARIARoleMap* CreateARIARoleMap() { + ARIARoleMap* role_map = new ARIARoleMap; -STATIC_ASSERT_ENUM(kWebAXDescriptionFromUninitialized, - kAXDescriptionFromUninitialized); -STATIC_ASSERT_ENUM(kWebAXDescriptionFromAttribute, kAXDescriptionFromAttribute); -STATIC_ASSERT_ENUM(kWebAXDescriptionFromContents, kAXDescriptionFromContents); -STATIC_ASSERT_ENUM(kWebAXDescriptionFromRelatedElement, - kAXDescriptionFromRelatedElement); + for (size_t i = 0; i < WTF_ARRAY_LENGTH(kRoles); ++i) + role_map->Set(String(kRoles[i].aria_role), kRoles[i].webcore_role); -STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaKeyShortcuts, - AXStringAttribute::kAriaKeyShortcuts); -STATIC_ASSERT_ENUM(WebAXStringAttribute::kAriaRoleDescription, - AXStringAttribute::kAriaRoleDescription); -STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaActiveDescendant, - AXObjectAttribute::kAriaActiveDescendant); -STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaErrorMessage, - AXObjectAttribute::kAriaErrorMessage); -STATIC_ASSERT_ENUM(WebAXObjectVectorAttribute::kAriaControls, - AXObjectVectorAttribute::kAriaControls); -STATIC_ASSERT_ENUM(WebAXObjectAttribute::kAriaDetails, - AXObjectAttribute::kAriaDetails); -STATIC_ASSERT_ENUM(WebAXObjectVectorAttribute::kAriaFlowTo, - AXObjectVectorAttribute::kAriaFlowTo); -#undef STATIC_ASSERT_ENUM + // Grids "ignore" their non-row children during computation of children. + role_map->Set("rowgroup", kIgnoredRole); + + return role_map; +} + +static Vector<AtomicString>* CreateRoleNameVector() { + Vector<AtomicString>* role_name_vector = new Vector<AtomicString>(kNumRoles); + for (int i = 0; i < kNumRoles; i++) + (*role_name_vector)[i] = g_null_atom; + + for (size_t i = 0; i < WTF_ARRAY_LENGTH(kRoles); ++i) { + (*role_name_vector)[kRoles[i].webcore_role] = + AtomicString(kRoles[i].aria_role); + } + + for (size_t i = 0; i < WTF_ARRAY_LENGTH(kReverseRoles); ++i) { + (*role_name_vector)[kReverseRoles[i].webcore_role] = + AtomicString(kReverseRoles[i].aria_role); + } + + return role_name_vector; +} + +static Vector<AtomicString>* CreateInternalRoleNameVector() { + Vector<AtomicString>* internal_role_name_vector = + new Vector<AtomicString>(kNumRoles); + for (size_t i = 0; i < WTF_ARRAY_LENGTH(kInternalRoles); i++) { + (*internal_role_name_vector)[kInternalRoles[i].webcore_role] = + AtomicString(kInternalRoles[i].internal_role_name); + } + + return internal_role_name_vector; +} + +HTMLDialogElement* GetActiveDialogElement(Node* node) { + return node->GetDocument().ActiveModalDialog(); +} + +} // namespace + +unsigned AXObject::number_of_live_ax_objects_ = 0; + +AXObject::AXObject(AXObjectCacheImpl& ax_object_cache) + : id_(0), + have_children_(false), + role_(kUnknownRole), + last_known_is_ignored_value_(kDefaultBehavior), + explicit_container_id_(0), + parent_(nullptr), + last_modification_count_(-1), + cached_is_ignored_(false), + cached_is_inert_or_aria_hidden_(false), + cached_is_descendant_of_leaf_node_(false), + cached_is_descendant_of_disabled_node_(false), + cached_has_inherited_presentational_role_(false), + cached_is_presentational_child_(false), + cached_ancestor_exposes_active_descendant_(false), + cached_live_region_root_(nullptr), + ax_object_cache_(&ax_object_cache) { + ++number_of_live_ax_objects_; +} + +AXObject::~AXObject() { + DCHECK(IsDetached()); + --number_of_live_ax_objects_; +} + +void AXObject::Detach() { + // Clear any children and call detachFromParent on them so that + // no children are left with dangling pointers to their parent. + ClearChildren(); + + ax_object_cache_ = nullptr; +} + +bool AXObject::IsDetached() const { + return !ax_object_cache_; +} + +const AtomicString& AXObject::GetAOMPropertyOrARIAAttribute( + AOMStringProperty property) const { + if (Element* element = this->GetElement()) + return AccessibleNode::GetPropertyOrARIAAttribute(element, property); + return g_null_atom; +} + +bool AXObject::HasAOMPropertyOrARIAAttribute(AOMBooleanProperty property, + bool& result) const { + Element* element = this->GetElement(); + if (!element) + return false; + + bool is_null = true; + result = + AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); + return !is_null; +} + +bool AXObject::AOMPropertyOrARIAAttributeIsTrue( + AOMBooleanProperty property) const { + bool result; + if (HasAOMPropertyOrARIAAttribute(property, result)) + return result; + return false; +} + +bool AXObject::AOMPropertyOrARIAAttributeIsFalse( + AOMBooleanProperty property) const { + bool result; + if (HasAOMPropertyOrARIAAttribute(property, result)) + return !result; + return false; +} + +bool AXObject::HasAOMPropertyOrARIAAttribute(AOMUIntProperty property, + uint32_t& result) const { + Element* element = this->GetElement(); + if (!element) + return false; + + bool is_null = true; + result = + AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); + return !is_null; +} + +bool AXObject::HasAOMPropertyOrARIAAttribute(AOMIntProperty property, + int32_t& result) const { + Element* element = this->GetElement(); + if (!element) + return false; + + bool is_null = true; + result = + AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); + return !is_null; +} + +bool AXObject::HasAOMPropertyOrARIAAttribute(AOMFloatProperty property, + float& result) const { + Element* element = this->GetElement(); + if (!element) + return false; + + bool is_null = true; + result = + AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); + return !is_null; +} + +bool AXObject::IsARIATextControl() const { + return AriaRoleAttribute() == kTextFieldRole || + AriaRoleAttribute() == kSearchBoxRole || + AriaRoleAttribute() == kComboBoxRole; +} + +bool AXObject::IsButton() const { + AccessibilityRole role = RoleValue(); + + return role == kButtonRole || role == kPopUpButtonRole || + role == kToggleButtonRole; +} + +bool AXObject::IsCheckable() const { + switch (RoleValue()) { + case kCheckBoxRole: + case kMenuItemCheckBoxRole: + case kMenuItemRadioRole: + case kRadioButtonRole: + case kSwitchRole: + case kToggleButtonRole: + return true; + case kTreeItemRole: + case kListBoxOptionRole: + case kMenuListOptionRole: + return AriaCheckedIsPresent(); + default: + return false; + } +} + +// Why this is here instead of AXNodeObject: +// Because an AXMenuListOption (<option>) can +// have an ARIA role of menuitemcheckbox/menuitemradio +// yet does not inherit from AXNodeObject +AccessibilityCheckedState AXObject::CheckedState() const { + if (!IsCheckable()) + return kCheckedStateUndefined; + + // Try ARIA checked/pressed state + const AccessibilityRole role = RoleValue(); + const auto prop = role == kToggleButtonRole ? AOMStringProperty::kPressed + : AOMStringProperty::kChecked; + const AtomicString& checked_attribute = GetAOMPropertyOrARIAAttribute(prop); + if (checked_attribute) { + if (EqualIgnoringASCIICase(checked_attribute, "true")) + return kCheckedStateTrue; + + if (EqualIgnoringASCIICase(checked_attribute, "mixed")) { + // Only checkable role that doesn't support mixed is the switch. + if (role != kSwitchRole) + return kCheckedStateMixed; + } + + if (EqualIgnoringASCIICase(checked_attribute, "false")) + return kCheckedStateFalse; + } + + // Native checked state + if (role != kToggleButtonRole) { + const Node* node = this->GetNode(); + if (!node) + return kCheckedStateUndefined; + + if (IsNativeInputInMixedState(node)) + return kCheckedStateMixed; + + if (isHTMLInputElement(*node) && + toHTMLInputElement(*node).ShouldAppearChecked()) { + return kCheckedStateTrue; + } + } + + return kCheckedStateFalse; +} + +bool AXObject::IsNativeInputInMixedState(const Node* node) { + if (!isHTMLInputElement(node)) + return false; + + const HTMLInputElement* input = toHTMLInputElement(node); + const auto inputType = input->type(); + if (inputType != InputTypeNames::checkbox && + inputType != InputTypeNames::radio) + return false; + return input->ShouldAppearIndeterminate(); +} + +bool AXObject::IsLandmarkRelated() const { + switch (RoleValue()) { + case kApplicationRole: + case kArticleRole: + case kBannerRole: + case kComplementaryRole: + case kContentInfoRole: + case kFooterRole: + case kFormRole: + case kMainRole: + case kNavigationRole: + case kRegionRole: + case kSearchRole: + return true; + default: + return false; + } +} + +bool AXObject::IsMenuRelated() const { + switch (RoleValue()) { + case kMenuRole: + case kMenuBarRole: + case kMenuButtonRole: + case kMenuItemRole: + case kMenuItemCheckBoxRole: + case kMenuItemRadioRole: + return true; + default: + return false; + } +} + +bool AXObject::IsPasswordFieldAndShouldHideValue() const { + Settings* settings = GetDocument()->GetSettings(); + if (!settings || settings->GetAccessibilityPasswordValuesEnabled()) + return false; + + return IsPasswordField(); +} + +bool AXObject::IsClickable() const { + switch (RoleValue()) { + case kButtonRole: + case kCheckBoxRole: + case kColorWellRole: + case kComboBoxRole: + case kImageMapLinkRole: + case kLinkRole: + case kListBoxOptionRole: + case kMenuButtonRole: + case kPopUpButtonRole: + case kRadioButtonRole: + case kSpinButtonRole: + case kTabRole: + case kTextFieldRole: + case kToggleButtonRole: + return true; + default: + return false; + } +} + +bool AXObject::AccessibilityIsIgnored() { + Node* node = GetNode(); + if (!node) { + AXObject* parent = this->ParentObject(); + while (!node && parent) { + node = parent->GetNode(); + parent = parent->ParentObject(); + } + } + + if (node) + node->UpdateDistribution(); + + // TODO(aboxhall): Instead of this, propagate inert down through frames + Document* document = GetDocument(); + while (document && document->LocalOwner()) { + document->LocalOwner()->UpdateDistribution(); + document = document->LocalOwner()->ownerDocument(); + } + + UpdateCachedAttributeValuesIfNeeded(); + return cached_is_ignored_; +} + +void AXObject::UpdateCachedAttributeValuesIfNeeded() const { + if (IsDetached()) + return; + + AXObjectCacheImpl& cache = AxObjectCache(); + + if (cache.ModificationCount() == last_modification_count_) + return; + + last_modification_count_ = cache.ModificationCount(); + cached_background_color_ = ComputeBackgroundColor(); + cached_is_inert_or_aria_hidden_ = ComputeIsInertOrAriaHidden(); + cached_is_descendant_of_leaf_node_ = (LeafNodeAncestor() != 0); + cached_is_descendant_of_disabled_node_ = (DisabledAncestor() != 0); + cached_has_inherited_presentational_role_ = + (InheritsPresentationalRoleFrom() != 0); + cached_is_presentational_child_ = + (AncestorForWhichThisIsAPresentationalChild() != 0); + cached_is_ignored_ = ComputeAccessibilityIsIgnored(); + cached_live_region_root_ = + IsLiveRegion() + ? const_cast<AXObject*>(this) + : (ParentObjectIfExists() ? ParentObjectIfExists()->LiveRegionRoot() + : 0); + cached_ancestor_exposes_active_descendant_ = + ComputeAncestorExposesActiveDescendant(); +} + +bool AXObject::AccessibilityIsIgnoredByDefault( + IgnoredReasons* ignored_reasons) const { + return DefaultObjectInclusion(ignored_reasons) == kIgnoreObject; +} + +AXObjectInclusion AXObject::AccessibilityPlatformIncludesObject() const { + if (IsMenuListPopup() || IsMenuListOption()) + return kIncludeObject; + + return kDefaultBehavior; +} + +AXObjectInclusion AXObject::DefaultObjectInclusion( + IgnoredReasons* ignored_reasons) const { + if (IsInertOrAriaHidden()) { + if (ignored_reasons) + ComputeIsInertOrAriaHidden(ignored_reasons); + return kIgnoreObject; + } + + if (IsPresentationalChild()) { + if (ignored_reasons) { + AXObject* ancestor = AncestorForWhichThisIsAPresentationalChild(); + ignored_reasons->push_back( + IgnoredReason(kAXAncestorDisallowsChild, ancestor)); + } + return kIgnoreObject; + } + + return AccessibilityPlatformIncludesObject(); +} + +bool AXObject::IsInertOrAriaHidden() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_is_inert_or_aria_hidden_; +} + +bool AXObject::ComputeIsInertOrAriaHidden( + IgnoredReasons* ignored_reasons) const { + if (GetNode()) { + if (GetNode()->IsInert()) { + if (ignored_reasons) { + HTMLDialogElement* dialog = GetActiveDialogElement(GetNode()); + if (dialog) { + AXObject* dialog_object = AxObjectCache().GetOrCreate(dialog); + if (dialog_object) { + ignored_reasons->push_back( + IgnoredReason(kAXActiveModalDialog, dialog_object)); + } else { + ignored_reasons->push_back(IgnoredReason(kAXInertElement)); + } + } else { + const AXObject* inert_root_el = InertRoot(); + if (inert_root_el == this) { + ignored_reasons->push_back(IgnoredReason(kAXInertElement)); + } else { + ignored_reasons->push_back( + IgnoredReason(kAXInertSubtree, inert_root_el)); + } + } + } + return true; + } + } else { + AXObject* parent = ParentObject(); + if (parent && parent->IsInertOrAriaHidden()) { + if (ignored_reasons) + parent->ComputeIsInertOrAriaHidden(ignored_reasons); + return true; + } + } + + const AXObject* hidden_root = AriaHiddenRoot(); + if (hidden_root) { + if (ignored_reasons) { + if (hidden_root == this) { + ignored_reasons->push_back(IgnoredReason(kAXAriaHiddenElement)); + } else { + ignored_reasons->push_back( + IgnoredReason(kAXAriaHiddenSubtree, hidden_root)); + } + } + return true; + } + + return false; +} + +bool AXObject::IsDescendantOfLeafNode() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_is_descendant_of_leaf_node_; +} + +AXObject* AXObject::LeafNodeAncestor() const { + if (AXObject* parent = ParentObject()) { + if (!parent->CanHaveChildren()) + return parent; + + return parent->LeafNodeAncestor(); + } + + return 0; +} + +const AXObject* AXObject::AriaHiddenRoot() const { + for (const AXObject* object = this; object; object = object->ParentObject()) { + if (object->AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kHidden)) + return object; + } + + return 0; +} + +const AXObject* AXObject::InertRoot() const { + const AXObject* object = this; + if (!RuntimeEnabledFeatures::InertAttributeEnabled()) + return 0; + + while (object && !object->IsAXNodeObject()) + object = object->ParentObject(); + Node* node = object->GetNode(); + Element* element = node->IsElementNode() + ? ToElement(node) + : FlatTreeTraversal::ParentElement(*node); + while (element) { + if (element->hasAttribute(inertAttr)) + return AxObjectCache().GetOrCreate(element); + element = FlatTreeTraversal::ParentElement(*element); + } + + return 0; +} + +bool AXObject::IsDescendantOfDisabledNode() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_is_descendant_of_disabled_node_; +} + +const AXObject* AXObject::DisabledAncestor() const { + bool disabled = false; + if (HasAOMPropertyOrARIAAttribute(AOMBooleanProperty::kDisabled, disabled)) { + if (disabled) + return this; + return nullptr; + } + + if (AXObject* parent = ParentObject()) + return parent->DisabledAncestor(); + + return nullptr; +} + +bool AXObject::LastKnownIsIgnoredValue() { + if (last_known_is_ignored_value_ == kDefaultBehavior) { + last_known_is_ignored_value_ = + AccessibilityIsIgnored() ? kIgnoreObject : kIncludeObject; + } + + return last_known_is_ignored_value_ == kIgnoreObject; +} + +void AXObject::SetLastKnownIsIgnoredValue(bool is_ignored) { + last_known_is_ignored_value_ = is_ignored ? kIgnoreObject : kIncludeObject; +} + +bool AXObject::HasInheritedPresentationalRole() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_has_inherited_presentational_role_; +} + +bool AXObject::IsPresentationalChild() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_is_presentational_child_; +} + +bool AXObject::CanReceiveAccessibilityFocus() const { + const Element* elem = GetElement(); + if (!elem) + return false; + + // Focusable, and not forwarding the focus somewhere else + if (elem->IsFocusable() && !elem->FastHasAttribute(aria_activedescendantAttr)) + return true; + + // aria-activedescendant focus + return elem->FastHasAttribute(idAttr) && AncestorExposesActiveDescendant(); +} + +bool AXObject::AncestorExposesActiveDescendant() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_ancestor_exposes_active_descendant_; +} + +bool AXObject::ComputeAncestorExposesActiveDescendant() const { + const AXObject* parent = ParentObjectUnignored(); + if (!parent) + return false; + + if (parent->SupportsActiveDescendant() && + parent->HasAttribute(aria_activedescendantAttr)) { + return true; + } + + return parent->AncestorExposesActiveDescendant(); +} + +// Simplify whitespace, but preserve a single leading and trailing whitespace +// character if it's present. +// static +String AXObject::CollapseWhitespace(const String& str) { + StringBuilder result; + if (!str.IsEmpty() && IsHTMLSpace<UChar>(str[0])) + result.Append(' '); + result.Append(str.SimplifyWhiteSpace(IsHTMLSpace<UChar>)); + if (!str.IsEmpty() && IsHTMLSpace<UChar>(str[str.length() - 1])) + result.Append(' '); + return result.ToString(); +} + +String AXObject::ComputedName() const { + AXNameFrom name_from; + AXObject::AXObjectVector name_objects; + return GetName(name_from, &name_objects); +} + +String AXObject::GetName(AXNameFrom& name_from, + AXObject::AXObjectVector* name_objects) const { + HeapHashSet<Member<const AXObject>> visited; + AXRelatedObjectVector related_objects; + String text = TextAlternative(false, false, visited, name_from, + &related_objects, nullptr); + + AccessibilityRole role = RoleValue(); + if (!GetNode() || (!isHTMLBRElement(GetNode()) && role != kStaticTextRole && + role != kInlineTextBoxRole)) + text = CollapseWhitespace(text); + + if (name_objects) { + name_objects->clear(); + for (size_t i = 0; i < related_objects.size(); i++) + name_objects->push_back(related_objects[i]->object); + } + + return text; +} + +String AXObject::GetName(NameSources* name_sources) const { + AXObjectSet visited; + AXNameFrom tmp_name_from; + AXRelatedObjectVector tmp_related_objects; + String text = TextAlternative(false, false, visited, tmp_name_from, + &tmp_related_objects, name_sources); + text = text.SimplifyWhiteSpace(IsHTMLSpace<UChar>); + return text; +} + +String AXObject::RecursiveTextAlternative(const AXObject& ax_obj, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited) { + if (visited.Contains(&ax_obj) && !in_aria_labelled_by_traversal) + return String(); + + AXNameFrom tmp_name_from; + return ax_obj.TextAlternative(true, in_aria_labelled_by_traversal, visited, + tmp_name_from, nullptr, nullptr); +} + +bool AXObject::IsHiddenForTextAlternativeCalculation() const { + if (AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty::kHidden)) + return false; + + if (GetLayoutObject()) + return GetLayoutObject()->Style()->Visibility() != EVisibility::kVisible; + + // This is an obscure corner case: if a node has no LayoutObject, that means + // it's not rendered, but we still may be exploring it as part of a text + // alternative calculation, for example if it was explicitly referenced by + // aria-labelledby. So we need to explicitly call the style resolver to check + // whether it's invisible or display:none, rather than relying on the style + // cached in the LayoutObject. + Document* document = GetDocument(); + if (!document || !document->GetFrame()) + return false; + if (Node* node = GetNode()) { + if (node->isConnected() && node->IsElementNode()) { + RefPtr<ComputedStyle> style = + document->EnsureStyleResolver().StyleForElement(ToElement(node)); + return style->Display() == EDisplay::kNone || + style->Visibility() != EVisibility::kVisible; + } + } + return false; +} + +String AXObject::AriaTextAlternative(bool recursive, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + AXNameFrom& name_from, + AXRelatedObjectVector* related_objects, + NameSources* name_sources, + bool* found_text_alternative) const { + String text_alternative; + bool already_visited = visited.Contains(this); + visited.insert(this); + + // Step 2A from: http://www.w3.org/TR/accname-aam-1.1 + // If you change this logic, update AXNodeObject::nameFromLabelElement, too. + if (!in_aria_labelled_by_traversal && + IsHiddenForTextAlternativeCalculation()) { + *found_text_alternative = true; + return String(); + } + + // Step 2B from: http://www.w3.org/TR/accname-aam-1.1 + // If you change this logic, update AXNodeObject::nameFromLabelElement, too. + if (!in_aria_labelled_by_traversal && !already_visited) { + const QualifiedName& attr = + HasAttribute(aria_labeledbyAttr) && !HasAttribute(aria_labelledbyAttr) + ? aria_labeledbyAttr + : aria_labelledbyAttr; + name_from = kAXNameFromRelatedElement; + if (name_sources) { + name_sources->push_back(NameSource(*found_text_alternative, attr)); + name_sources->back().type = name_from; + } + + const AtomicString& aria_labelledby = GetAttribute(attr); + if (!aria_labelledby.IsNull()) { + if (name_sources) + name_sources->back().attribute_value = aria_labelledby; + + // Operate on a copy of |visited| so that if |nameSources| is not null, + // the set of visited objects is preserved unmodified for future + // calculations. + AXObjectSet visited_copy = visited; + text_alternative = TextFromAriaLabelledby(visited_copy, related_objects); + if (!text_alternative.IsNull()) { + if (name_sources) { + NameSource& source = name_sources->back(); + source.type = name_from; + source.related_objects = *related_objects; + source.text = text_alternative; + *found_text_alternative = true; + } else { + *found_text_alternative = true; + return text_alternative; + } + } else if (name_sources) { + name_sources->back().invalid = true; + } + } + } + + // Step 2C from: http://www.w3.org/TR/accname-aam-1.1 + // If you change this logic, update AXNodeObject::nameFromLabelElement, too. + name_from = kAXNameFromAttribute; + if (name_sources) { + name_sources->push_back( + NameSource(*found_text_alternative, aria_labelAttr)); + name_sources->back().type = name_from; + } + const AtomicString& aria_label = + GetAOMPropertyOrARIAAttribute(AOMStringProperty::kLabel); + if (!aria_label.IsEmpty()) { + text_alternative = aria_label; + + if (name_sources) { + NameSource& source = name_sources->back(); + source.text = text_alternative; + source.attribute_value = aria_label; + *found_text_alternative = true; + } else { + *found_text_alternative = true; + return text_alternative; + } + } + + return text_alternative; +} + +String AXObject::TextFromElements( + bool in_aria_labelledby_traversal, + AXObjectSet& visited, + HeapVector<Member<Element>>& elements, + AXRelatedObjectVector* related_objects) const { + StringBuilder accumulated_text; + bool found_valid_element = false; + AXRelatedObjectVector local_related_objects; + + for (const auto& element : elements) { + AXObject* ax_element = AxObjectCache().GetOrCreate(element); + if (ax_element) { + found_valid_element = true; + + String result = RecursiveTextAlternative( + *ax_element, in_aria_labelledby_traversal, visited); + local_related_objects.push_back( + new NameSourceRelatedObject(ax_element, result)); + if (!result.IsEmpty()) { + if (!accumulated_text.IsEmpty()) + accumulated_text.Append(' '); + accumulated_text.Append(result); + } + } + } + if (!found_valid_element) + return String(); + if (related_objects) + *related_objects = local_related_objects; + return accumulated_text.ToString(); +} + +void AXObject::TokenVectorFromAttribute(Vector<String>& tokens, + const QualifiedName& attribute) const { + Node* node = this->GetNode(); + if (!node || !node->IsElementNode()) + return; + + String attribute_value = GetAttribute(attribute).GetString(); + if (attribute_value.IsEmpty()) + return; + + attribute_value.SimplifyWhiteSpace(); + attribute_value.Split(' ', tokens); +} + +void AXObject::ElementsFromAttribute(HeapVector<Member<Element>>& elements, + const QualifiedName& attribute) const { + Vector<String> ids; + TokenVectorFromAttribute(ids, attribute); + if (ids.IsEmpty()) + return; + + TreeScope& scope = GetNode()->GetTreeScope(); + for (const auto& id : ids) { + if (Element* id_element = scope.getElementById(AtomicString(id))) + elements.push_back(id_element); + } +} + +void AXObject::AriaLabelledbyElementVector( + HeapVector<Member<Element>>& elements) const { + // Try both spellings, but prefer aria-labelledby, which is the official spec. + ElementsFromAttribute(elements, aria_labelledbyAttr); + if (!elements.size()) + ElementsFromAttribute(elements, aria_labeledbyAttr); +} + +String AXObject::TextFromAriaLabelledby( + AXObjectSet& visited, + AXRelatedObjectVector* related_objects) const { + HeapVector<Member<Element>> elements; + AriaLabelledbyElementVector(elements); + return TextFromElements(true, visited, elements, related_objects); +} + +String AXObject::TextFromAriaDescribedby( + AXRelatedObjectVector* related_objects) const { + AXObjectSet visited; + HeapVector<Member<Element>> elements; + ElementsFromAttribute(elements, aria_describedbyAttr); + return TextFromElements(true, visited, elements, related_objects); +} + +RGBA32 AXObject::BackgroundColor() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_background_color_; +} + +AccessibilityOrientation AXObject::Orientation() const { + // In ARIA 1.1, the default value for aria-orientation changed from + // horizontal to undefined. + return kAccessibilityOrientationUndefined; +} + +AXDefaultActionVerb AXObject::Action() const { + if (!ActionElement()) + return AXDefaultActionVerb::kNone; + + switch (RoleValue()) { + case kButtonRole: + case kToggleButtonRole: + return AXDefaultActionVerb::kPress; + case kTextFieldRole: + return AXDefaultActionVerb::kActivate; + case kMenuItemRadioRole: + case kRadioButtonRole: + return AXDefaultActionVerb::kSelect; + case kLinkRole: + return AXDefaultActionVerb::kJump; + case kPopUpButtonRole: + return AXDefaultActionVerb::kOpen; + default: + if (IsCheckable()) { + return CheckedState() != kCheckedStateTrue + ? AXDefaultActionVerb::kCheck + : AXDefaultActionVerb::kUncheck; + } + return AXDefaultActionVerb::kClick; + } +} + +bool AXObject::IsMultiline() const { + Node* node = this->GetNode(); + if (!node) + return false; + + if (isHTMLTextAreaElement(*node)) + return true; + + if (HasEditableStyle(*node)) + return true; + + if (!IsNativeTextControl() && !IsNonNativeTextControl()) + return false; + + return AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kMultiline); +} + +bool AXObject::AriaPressedIsPresent() const { + return !GetAttribute(aria_pressedAttr).IsEmpty(); +} + +bool AXObject::AriaCheckedIsPresent() const { + return !GetAttribute(aria_checkedAttr).IsEmpty(); +} + +bool AXObject::SupportsActiveDescendant() const { + // According to the ARIA Spec, all ARIA composite widgets, ARIA text boxes + // and ARIA groups should be able to expose an active descendant. + // Implicitly, <input> and <textarea> elements should also have this ability. + switch (AriaRoleAttribute()) { + case kComboBoxRole: + case kGridRole: + case kGroupRole: + case kListBoxRole: + case kMenuRole: + case kMenuBarRole: + case kRadioGroupRole: + case kRowRole: + case kSearchBoxRole: + case kTabListRole: + case kTextFieldRole: + case kToolbarRole: + case kTreeRole: + case kTreeGridRole: + return true; + default: + return false; + } +} + +bool AXObject::SupportsARIAAttributes() const { + return IsLiveRegion() || SupportsARIADragging() || SupportsARIADropping() || + SupportsARIAFlowTo() || SupportsARIAOwns() || + HasAttribute(aria_labelAttr) || HasAttribute(aria_currentAttr); +} + +bool AXObject::SupportsRangeValue() const { + return IsProgressIndicator() || IsMeter() || IsSlider() || IsScrollbar() || + IsSpinButton() || IsMoveableSplitter(); +} + +bool AXObject::SupportsSetSizeAndPosInSet() const { + AXObject* parent = ParentObjectUnignored(); + if (!parent) + return false; + + int role = RoleValue(); + int parent_role = parent->RoleValue(); + + if ((role == kListBoxOptionRole && parent_role == kListBoxRole) || + (role == kListItemRole && parent_role == kListRole) || + (role == kMenuItemRole && parent_role == kMenuRole) || + (role == kRadioButtonRole) || + (role == kTabRole && parent_role == kTabListRole) || + (role == kTreeItemRole && parent_role == kTreeRole) || + (role == kTreeItemRole && parent_role == kTreeItemRole)) { + return true; + } + + return false; +} + +int AXObject::IndexInParent() const { + if (!ParentObject()) + return 0; + + const auto& siblings = ParentObject()->Children(); + int child_count = siblings.size(); + + for (int index = 0; index < child_count; ++index) { + if (siblings[index].Get() == this) { + return index; + } + } + return 0; +} + +bool AXObject::IsLiveRegion() const { + const AtomicString& live_region = LiveRegionStatus(); + return EqualIgnoringASCIICase(live_region, "polite") || + EqualIgnoringASCIICase(live_region, "assertive"); +} + +AXObject* AXObject::LiveRegionRoot() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_live_region_root_; +} + +const AtomicString& AXObject::ContainerLiveRegionStatus() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_live_region_root_ ? cached_live_region_root_->LiveRegionStatus() + : g_null_atom; +} + +const AtomicString& AXObject::ContainerLiveRegionRelevant() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_live_region_root_ + ? cached_live_region_root_->LiveRegionRelevant() + : g_null_atom; +} + +bool AXObject::ContainerLiveRegionAtomic() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_live_region_root_ && + cached_live_region_root_->LiveRegionAtomic(); +} + +bool AXObject::ContainerLiveRegionBusy() const { + UpdateCachedAttributeValuesIfNeeded(); + return cached_live_region_root_ && cached_live_region_root_->LiveRegionBusy(); +} + +AXObject* AXObject::ElementAccessibilityHitTest(const IntPoint& point) const { + // Check if there are any mock elements that need to be handled. + for (const auto& child : children_) { + if (child->IsMockObject() && + child->GetBoundsInFrameCoordinates().Contains(point)) + return child->ElementAccessibilityHitTest(point); + } + + return const_cast<AXObject*>(this); +} + +const AXObject::AXObjectVector& AXObject::Children() { + UpdateChildrenIfNecessary(); + + return children_; +} + +AXObject* AXObject::ParentObject() const { + if (IsDetached()) + return 0; + + if (parent_) + return parent_; + + if (AxObjectCache().IsAriaOwned(this)) + return AxObjectCache().GetAriaOwnedParent(this); + + return ComputeParent(); +} + +AXObject* AXObject::ParentObjectIfExists() const { + if (IsDetached()) + return 0; + + if (parent_) + return parent_; + + return ComputeParentIfExists(); +} + +AXObject* AXObject::ParentObjectUnignored() const { + AXObject* parent; + for (parent = ParentObject(); parent && parent->AccessibilityIsIgnored(); + parent = parent->ParentObject()) { + } + + return parent; +} + +// Container widgets are those that a user tabs into and arrows around +// sub-widgets +bool AXObject::IsContainerWidget() const { + switch (RoleValue()) { + case kComboBoxRole: + case kGridRole: + case kListBoxRole: + case kMenuBarRole: + case kMenuRole: + case kRadioGroupRole: + case kSpinButtonRole: + case kTabListRole: + case kToolbarRole: + case kTreeGridRole: + case kTreeRole: + return true; + default: + return false; + } +} + +AXObject* AXObject::ContainerWidget() const { + AXObject* ancestor = ParentObjectUnignored(); + while (ancestor && !ancestor->IsContainerWidget()) + ancestor = ancestor->ParentObjectUnignored(); + + return ancestor; +} + +void AXObject::UpdateChildrenIfNecessary() { + if (!HasChildren()) + AddChildren(); +} + +void AXObject::ClearChildren() { + // Detach all weak pointers from objects to their parents. + for (const auto& child : children_) + child->DetachFromParent(); + + children_.clear(); + have_children_ = false; +} + +Element* AXObject::GetElement() const { + Node* node = GetNode(); + return node && node->IsElementNode() ? ToElement(node) : nullptr; +} + +Document* AXObject::GetDocument() const { + LocalFrameView* frame_view = DocumentFrameView(); + if (!frame_view) + return 0; + + return frame_view->GetFrame().GetDocument(); +} + +LocalFrameView* AXObject::DocumentFrameView() const { + const AXObject* object = this; + while (object && !object->IsAXLayoutObject()) + object = object->ParentObject(); + + if (!object) + return 0; + + return object->DocumentFrameView(); +} + +String AXObject::Language() const { + const AtomicString& lang = GetAttribute(langAttr); + if (!lang.IsEmpty()) + return lang; + + AXObject* parent = ParentObject(); + + // As a last resort, fall back to the content language specified in the meta + // tag. + if (!parent) { + Document* doc = GetDocument(); + if (doc) + return doc->ContentLanguage(); + return g_null_atom; + } + + return parent->Language(); +} + +bool AXObject::HasAttribute(const QualifiedName& attribute) const { + if (Element* element = GetElement()) + return element->FastHasAttribute(attribute); + return false; +} + +const AtomicString& AXObject::GetAttribute( + const QualifiedName& attribute) const { + if (Element* element = GetElement()) + return element->FastGetAttribute(attribute); + return g_null_atom; +} + +// +// Scrollable containers. +// + +bool AXObject::IsScrollableContainer() const { + return !!GetScrollableAreaIfScrollable(); +} + +IntPoint AXObject::GetScrollOffset() const { + ScrollableArea* area = GetScrollableAreaIfScrollable(); + if (!area) + return IntPoint(); + + return IntPoint(area->ScrollOffsetInt().Width(), + area->ScrollOffsetInt().Height()); +} + +IntPoint AXObject::MinimumScrollOffset() const { + ScrollableArea* area = GetScrollableAreaIfScrollable(); + if (!area) + return IntPoint(); + + return IntPoint(area->MinimumScrollOffsetInt().Width(), + area->MinimumScrollOffsetInt().Height()); +} + +IntPoint AXObject::MaximumScrollOffset() const { + ScrollableArea* area = GetScrollableAreaIfScrollable(); + if (!area) + return IntPoint(); + + return IntPoint(area->MaximumScrollOffsetInt().Width(), + area->MaximumScrollOffsetInt().Height()); +} + +void AXObject::SetScrollOffset(const IntPoint& offset) const { + ScrollableArea* area = GetScrollableAreaIfScrollable(); + if (!area) + return; + + // TODO(bokan): This should potentially be a UserScroll. + area->SetScrollOffset(ScrollOffset(offset.X(), offset.Y()), + kProgrammaticScroll); +} + +void AXObject::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform) const { + *out_container = nullptr; + out_bounds_in_container = FloatRect(); + out_container_transform.setIdentity(); + + // First check if it has explicit bounds, for example if this element is tied + // to a canvas path. When explicit coordinates are provided, the ID of the + // explicit container element that the coordinates are relative to must be + // provided too. + if (!explicit_element_rect_.IsEmpty()) { + *out_container = AxObjectCache().ObjectFromAXID(explicit_container_id_); + if (*out_container) { + out_bounds_in_container = FloatRect(explicit_element_rect_); + return; + } + } + + LayoutObject* layout_object = LayoutObjectForRelativeBounds(); + if (!layout_object) + return; + + if (IsWebArea()) { + if (layout_object->GetFrame()->View()) { + out_bounds_in_container.SetSize( + FloatSize(layout_object->GetFrame()->View()->ContentsSize())); + } + return; + } + + // First compute the container. The container must be an ancestor in the + // accessibility tree, and its LayoutObject must be an ancestor in the layout + // tree. Get the first such ancestor that's either scrollable or has a paint + // layer. + AXObject* container = ParentObjectUnignored(); + LayoutObject* container_layout_object = nullptr; + while (container) { + container_layout_object = container->GetLayoutObject(); + if (container_layout_object && + container_layout_object->IsBoxModelObject() && + layout_object->IsDescendantOf(container_layout_object)) { + if (container->IsScrollableContainer() || + container_layout_object->HasLayer()) + break; + } + + container = container->ParentObjectUnignored(); + } + + if (!container) + return; + *out_container = container; + out_bounds_in_container = + layout_object->LocalBoundingBoxRectForAccessibility(); + + // If the container has a scroll offset, subtract that out because we want our + // bounds to be relative to the *unscrolled* position of the container object. + ScrollableArea* scrollable_area = container->GetScrollableAreaIfScrollable(); + if (scrollable_area && !container->IsWebArea()) { + ScrollOffset scroll_offset = scrollable_area->GetScrollOffset(); + out_bounds_in_container.Move(scroll_offset); + } + + // Compute the transform between the container's coordinate space and this + // object. If the transform is just a simple translation, apply that to the + // bounding box, but if it's a non-trivial transformation like a rotation, + // scaling, etc. then return the full matrix instead. + TransformationMatrix transform = layout_object->LocalToAncestorTransform( + ToLayoutBoxModelObject(container_layout_object)); + if (transform.IsIdentityOr2DTranslation()) { + out_bounds_in_container.Move(transform.To2DTranslation()); + } else { + out_container_transform = TransformationMatrix::ToSkMatrix44(transform); + } +} + +LayoutRect AXObject::GetBoundsInFrameCoordinates() const { + AXObject* container = nullptr; + FloatRect bounds; + SkMatrix44 transform; + GetRelativeBounds(&container, bounds, transform); + FloatRect computed_bounds(0, 0, bounds.Width(), bounds.Height()); + while (container && container != this) { + computed_bounds.Move(bounds.X(), bounds.Y()); + if (!container->IsWebArea()) { + computed_bounds.Move(-container->GetScrollOffset().X(), + -container->GetScrollOffset().Y()); + } + if (!transform.isIdentity()) { + TransformationMatrix transformation_matrix(transform); + transformation_matrix.MapRect(computed_bounds); + } + container->GetRelativeBounds(&container, bounds, transform); + } + return LayoutRect(computed_bounds); +} + +// +// Modify or take an action on an object. +// + +bool AXObject::Press() { + Document* document = GetDocument(); + if (!document) + return false; + + UserGestureIndicator gesture_indicator( + UserGestureToken::Create(document, UserGestureToken::kNewGesture)); + Element* action_elem = ActionElement(); + if (action_elem) { + action_elem->AccessKeyAction(true); + return true; + } + + if (CanSetFocusAttribute()) { + SetFocused(true); + return true; + } + + return false; +} + +void AXObject::ScrollToMakeVisible() const { + IntRect object_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); + object_rect.SetLocation(IntPoint()); + ScrollToMakeVisibleWithSubFocus(object_rect); +} + +// This is a 1-dimensional scroll offset helper function that's applied +// separately in the horizontal and vertical directions, because the +// logic is the same. The goal is to compute the best scroll offset +// in order to make an object visible within a viewport. +// +// If the object is already fully visible, returns the same scroll +// offset. +// +// In case the whole object cannot fit, you can specify a +// subfocus - a smaller region within the object that should +// be prioritized. If the whole object can fit, the subfocus is +// ignored. +// +// If possible, the object and subfocus are centered within the +// viewport. +// +// Example 1: the object is already visible, so nothing happens. +// +----------Viewport---------+ +// +---Object---+ +// +--SubFocus--+ +// +// Example 2: the object is not fully visible, so it's centered +// within the viewport. +// Before: +// +----------Viewport---------+ +// +---Object---+ +// +--SubFocus--+ +// +// After: +// +----------Viewport---------+ +// +---Object---+ +// +--SubFocus--+ +// +// Example 3: the object is larger than the viewport, so the +// viewport moves to show as much of the object as possible, +// while also trying to center the subfocus. +// Before: +// +----------Viewport---------+ +// +---------------Object--------------+ +// +-SubFocus-+ +// +// After: +// +----------Viewport---------+ +// +---------------Object--------------+ +// +-SubFocus-+ +// +// When constraints cannot be fully satisfied, the min +// (left/top) position takes precedence over the max (right/bottom). +// +// Note that the return value represents the ideal new scroll offset. +// This may be out of range - the calling function should clip this +// to the available range. +static int ComputeBestScrollOffset(int current_scroll_offset, + int subfocus_min, + int subfocus_max, + int object_min, + int object_max, + int viewport_min, + int viewport_max) { + int viewport_size = viewport_max - viewport_min; + + // If the object size is larger than the viewport size, consider + // only a portion that's as large as the viewport, centering on + // the subfocus as much as possible. + if (object_max - object_min > viewport_size) { + // Since it's impossible to fit the whole object in the + // viewport, exit now if the subfocus is already within the viewport. + if (subfocus_min - current_scroll_offset >= viewport_min && + subfocus_max - current_scroll_offset <= viewport_max) + return current_scroll_offset; + + // Subfocus must be within focus. + subfocus_min = std::max(subfocus_min, object_min); + subfocus_max = std::min(subfocus_max, object_max); + + // Subfocus must be no larger than the viewport size; favor top/left. + if (subfocus_max - subfocus_min > viewport_size) + subfocus_max = subfocus_min + viewport_size; + + // Compute the size of an object centered on the subfocus, the size of the + // viewport. + int centered_object_min = (subfocus_min + subfocus_max - viewport_size) / 2; + int centered_object_max = centered_object_min + viewport_size; + + object_min = std::max(object_min, centered_object_min); + object_max = std::min(object_max, centered_object_max); + } + + // Exit now if the focus is already within the viewport. + if (object_min - current_scroll_offset >= viewport_min && + object_max - current_scroll_offset <= viewport_max) + return current_scroll_offset; + + // Center the object in the viewport. + return (object_min + object_max - viewport_min - viewport_max) / 2; +} + +void AXObject::ScrollToMakeVisibleWithSubFocus(const IntRect& subfocus) const { + // Search up the parent chain until we find the first one that's scrollable. + const AXObject* scroll_parent = ParentObject() ? ParentObject() : this; + ScrollableArea* scrollable_area = 0; + while (scroll_parent) { + scrollable_area = scroll_parent->GetScrollableAreaIfScrollable(); + if (scrollable_area) + break; + scroll_parent = scroll_parent->ParentObject(); + } + if (!scroll_parent || !scrollable_area) + return; + + IntRect object_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); + IntSize scroll_offset = scrollable_area->ScrollOffsetInt(); + IntRect scroll_visible_rect = scrollable_area->VisibleContentRect(); + + // Convert the object rect into local coordinates. + if (!scroll_parent->IsWebArea()) { + object_rect.MoveBy(IntPoint(scroll_offset)); + object_rect.MoveBy( + -PixelSnappedIntRect(scroll_parent->GetBoundsInFrameCoordinates()) + .Location()); + } + + int desired_x = ComputeBestScrollOffset( + scroll_offset.Width(), object_rect.X() + subfocus.X(), + object_rect.X() + subfocus.MaxX(), object_rect.X(), object_rect.MaxX(), 0, + scroll_visible_rect.Width()); + int desired_y = ComputeBestScrollOffset( + scroll_offset.Height(), object_rect.Y() + subfocus.Y(), + object_rect.Y() + subfocus.MaxY(), object_rect.Y(), object_rect.MaxY(), 0, + scroll_visible_rect.Height()); + + scroll_parent->SetScrollOffset(IntPoint(desired_x, desired_y)); + + // Convert the subfocus into the coordinates of the scroll parent. + IntRect new_subfocus = subfocus; + IntRect new_element_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); + IntRect scroll_parent_rect = + PixelSnappedIntRect(scroll_parent->GetBoundsInFrameCoordinates()); + new_subfocus.Move(new_element_rect.X(), new_element_rect.Y()); + new_subfocus.Move(-scroll_parent_rect.X(), -scroll_parent_rect.Y()); + + if (scroll_parent->ParentObject()) { + // Recursively make sure the scroll parent itself is visible. + scroll_parent->ScrollToMakeVisibleWithSubFocus(new_subfocus); + } else { + // To minimize the number of notifications, only fire one on the topmost + // object that has been scrolled. + AxObjectCache().PostNotification(const_cast<AXObject*>(this), + AXObjectCacheImpl::kAXLocationChanged); + } +} + +void AXObject::ScrollToGlobalPoint(const IntPoint& global_point) const { + // Search up the parent chain and create a vector of all scrollable parent + // objects and ending with this object itself. + HeapVector<Member<const AXObject>> objects; + AXObject* parent_object; + for (parent_object = this->ParentObject(); parent_object; + parent_object = parent_object->ParentObject()) { + if (parent_object->GetScrollableAreaIfScrollable()) + objects.push_front(parent_object); + } + objects.push_back(this); + + // Start with the outermost scrollable (the main window) and try to scroll the + // next innermost object to the given point. + int offset_x = 0, offset_y = 0; + IntPoint point = global_point; + size_t levels = objects.size() - 1; + for (size_t i = 0; i < levels; i++) { + const AXObject* outer = objects[i]; + const AXObject* inner = objects[i + 1]; + ScrollableArea* scrollable_area = outer->GetScrollableAreaIfScrollable(); + + IntRect inner_rect = + inner->IsWebArea() + ? PixelSnappedIntRect( + inner->ParentObject()->GetBoundsInFrameCoordinates()) + : PixelSnappedIntRect(inner->GetBoundsInFrameCoordinates()); + IntRect object_rect = inner_rect; + IntSize scroll_offset = scrollable_area->ScrollOffsetInt(); + + // Convert the object rect into local coordinates. + object_rect.Move(offset_x, offset_y); + if (!outer->IsWebArea()) + object_rect.Move(scroll_offset.Width(), scroll_offset.Height()); + + int desired_x = ComputeBestScrollOffset( + 0, object_rect.X(), object_rect.MaxX(), object_rect.X(), + object_rect.MaxX(), point.X(), point.X()); + int desired_y = ComputeBestScrollOffset( + 0, object_rect.Y(), object_rect.MaxY(), object_rect.Y(), + object_rect.MaxY(), point.Y(), point.Y()); + outer->SetScrollOffset(IntPoint(desired_x, desired_y)); + + if (outer->IsWebArea() && !inner->IsWebArea()) { + // If outer object we just scrolled is a web area (frame) but the inner + // object is not, keep track of the coordinate transformation to apply to + // future nested calculations. + scroll_offset = scrollable_area->ScrollOffsetInt(); + offset_x -= (scroll_offset.Width() + point.X()); + offset_y -= (scroll_offset.Height() + point.Y()); + point.Move(scroll_offset.Width() - inner_rect.Width(), + scroll_offset.Height() - inner_rect.Y()); + } else if (inner->IsWebArea()) { + // Otherwise, if the inner object is a web area, reset the coordinate + // transformation. + offset_x = 0; + offset_y = 0; + } + } + + // To minimize the number of notifications, only fire one on the topmost + // object that has been scrolled. + DCHECK(objects[0]); + // TODO(nektar): Switch to postNotification(objects[0] and remove |getNode|. + AxObjectCache().PostNotification(objects[0]->GetNode(), + AXObjectCacheImpl::kAXLocationChanged); +} + +void AXObject::SetSequentialFocusNavigationStartingPoint() { + // Call it on the nearest ancestor that overrides this with a specific + // implementation. + if (ParentObject()) + ParentObject()->SetSequentialFocusNavigationStartingPoint(); +} + +void AXObject::NotifyIfIgnoredValueChanged() { + bool is_ignored = AccessibilityIsIgnored(); + if (LastKnownIsIgnoredValue() != is_ignored) { + AxObjectCache().ChildrenChanged(ParentObject()); + SetLastKnownIsIgnoredValue(is_ignored); + } +} + +void AXObject::SelectionChanged() { + if (AXObject* parent = ParentObjectIfExists()) + parent->SelectionChanged(); +} + +int AXObject::LineForPosition(const VisiblePosition& position) const { + if (position.IsNull() || !GetNode()) + return -1; + + // If the position is not in the same editable region as this AX object, + // return -1. + Node* container_node = position.DeepEquivalent().ComputeContainerNode(); + if (!container_node->IsShadowIncludingInclusiveAncestorOf(GetNode()) && + !GetNode()->IsShadowIncludingInclusiveAncestorOf(container_node)) + return -1; + + int line_count = -1; + VisiblePosition current_position = position; + VisiblePosition previous_position; + + // Move up until we get to the top. + // FIXME: This only takes us to the top of the rootEditableElement, not the + // top of the top document. + do { + previous_position = current_position; + current_position = PreviousLinePosition(current_position, LayoutUnit(), + kHasEditableAXRole); + ++line_count; + } while (current_position.IsNotNull() && + !InSameLine(current_position, previous_position)); + + return line_count; +} + +bool AXObject::IsARIAControl(AccessibilityRole aria_role) { + return IsARIAInput(aria_role) || aria_role == kButtonRole || + aria_role == kComboBoxRole || aria_role == kSliderRole; +} + +bool AXObject::IsARIAInput(AccessibilityRole aria_role) { + return aria_role == kRadioButtonRole || aria_role == kCheckBoxRole || + aria_role == kTextFieldRole || aria_role == kSwitchRole || + aria_role == kSearchBoxRole; +} + +AccessibilityRole AXObject::AriaRoleToWebCoreRole(const String& value) { + DCHECK(!value.IsEmpty()); + + static const ARIARoleMap* role_map = CreateARIARoleMap(); + + Vector<String> role_vector; + value.Split(' ', role_vector); + AccessibilityRole role = kUnknownRole; + for (const auto& child : role_vector) { + role = role_map->at(child); + if (role) + return role; + } + + return role; +} + +bool AXObject::NameFromContents(bool recursive) const { + // ARIA 1.1, section 5.2.7.5. + bool result = false; + + switch (RoleValue()) { + // ----- NameFrom: contents ------------------------- + // Get their own name from contents, or contribute to ancestors + case kAnchorRole: + case kButtonRole: + case kCellRole: + case kCheckBoxRole: + case kColumnHeaderRole: + case kDisclosureTriangleRole: + case kHeadingRole: + case kLineBreakRole: + case kLinkRole: + case kListBoxOptionRole: + case kMenuButtonRole: + case kMenuItemRole: + case kMenuItemCheckBoxRole: + case kMenuItemRadioRole: + case kMenuListOptionRole: + case kPopUpButtonRole: + case kRadioButtonRole: + case kRowHeaderRole: + case kStaticTextRole: + case kSwitchRole: + case kTabRole: + case kToggleButtonRole: + case kTreeItemRole: + case kUserInterfaceTooltipRole: + result = true; + break; + + // ----- No name from contents ------------------------- + // These never have or contribute a name from contents, as they are + // containers for many subobjects. Superset of nameFrom:author ARIA roles. + case kAlertRole: + case kAlertDialogRole: + case kApplicationRole: + case kAudioRole: + case kArticleRole: + case kBannerRole: + case kBlockquoteRole: + case kColorWellRole: + case kColumnRole: + case kComboBoxRole: + case kComplementaryRole: + case kContentInfoRole: + case kDateRole: + case kDateTimeRole: + case kDefinitionRole: + case kDialogRole: + case kDirectoryRole: + case kDocumentRole: + case kEmbeddedObjectRole: + case kFeedRole: + case kFigureRole: + case kFormRole: + case kGridRole: + case kGroupRole: + case kIframePresentationalRole: + case kIframeRole: + case kImageRole: + case kInputTimeRole: + case kListBoxRole: + case kLogRole: + case kMainRole: + case kMarqueeRole: + case kMathRole: + case kMenuListPopupRole: + case kMenuRole: + case kMenuBarRole: + case kMeterRole: + case kNavigationRole: + case kNoteRole: + case kOutlineRole: + case kProgressIndicatorRole: + case kRadioGroupRole: + case kRegionRole: + case kRootWebAreaRole: + case kScrollBarRole: + case kSearchRole: + case kSearchBoxRole: + case kSplitterRole: + case kSliderRole: + case kSpinButtonRole: + case kStatusRole: + case kScrollAreaRole: + case kSeamlessWebAreaRole: + case kSliderThumbRole: + case kSpinButtonPartRole: + case kSVGRootRole: + case kTableRole: + case kTableHeaderContainerRole: + case kTabGroupRole: + case kTabListRole: + case kTabPanelRole: + case kTermRole: + case kTextFieldRole: + case kTimeRole: + case kTimerRole: + case kToolbarRole: + case kTreeRole: + case kTreeGridRole: + case kVideoRole: + case kWebAreaRole: + case kWindowRole: + result = false; + break; + + // ----- Conditional: contribute to ancestor only, unless focusable ------- + // Some objects can contribute their contents to ancestor names, but + // only have their own name if they are focusable + case kAbbrRole: + case kAnnotationRole: + case kBusyIndicatorRole: + case kCanvasRole: + case kCaptionRole: + case kDescriptionListDetailRole: + case kDescriptionListRole: + case kDescriptionListTermRole: + case kDetailsRole: + case kFigcaptionRole: + case kFooterRole: + case kGenericContainerRole: + case kIgnoredRole: + case kImageMapLinkRole: + case kImageMapRole: + case kInlineTextBoxRole: + case kLabelRole: + case kLegendRole: + case kListRole: + case kListItemRole: + case kListMarkerRole: + case kMarkRole: + case kNoneRole: + case kParagraphRole: + case kPreRole: + case kPresentationalRole: + // Spec says we should always expose the name on rows, + // but for performance reasons we only do it + // if the row might receive focus + case kRowRole: + case kRubyRole: + case kRulerRole: + result = recursive || (CanReceiveAccessibilityFocus() && !IsEditable()); + break; + + case kUnknownRole: + case kNumRoles: + LOG(ERROR) << "kUnknownRole for " << GetNode(); + NOTREACHED(); + break; + } + + return result; +} + +AccessibilityRole AXObject::ButtonRoleType() const { + // If aria-pressed is present, then it should be exposed as a toggle button. + // http://www.w3.org/TR/wai-aria/states_and_properties#aria-pressed + if (AriaPressedIsPresent()) + return kToggleButtonRole; + if (AriaHasPopup()) + return kPopUpButtonRole; + // We don't contemplate RadioButtonRole, as it depends on the input + // type. + + return kButtonRole; +} + +const AtomicString& AXObject::RoleName(AccessibilityRole role) { + static const Vector<AtomicString>* role_name_vector = CreateRoleNameVector(); + + return role_name_vector->at(role); +} + +const AtomicString& AXObject::InternalRoleName(AccessibilityRole role) { + static const Vector<AtomicString>* internal_role_name_vector = + CreateInternalRoleNameVector(); + + return internal_role_name_vector->at(role); +} + +DEFINE_TRACE(AXObject) { + visitor->Trace(children_); + visitor->Trace(parent_); + visitor->Trace(cached_live_region_root_); + visitor->Trace(ax_object_cache_); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.h b/third_party/WebKit/Source/modules/accessibility/AXObject.h index f8cd011e..f62c261 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.h
@@ -1,288 +1,894 @@ -// 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. + +/* + * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2008 Nuanti Ltd. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ #ifndef AXObject_h #define AXObject_h -#include "core/CoreExport.h" +#include "core/editing/VisiblePosition.h" +#include "core/editing/markers/DocumentMarker.h" +#include "core/inspector/protocol/Accessibility.h" +#include "modules/ModulesExport.h" +#include "modules/accessibility/AXEnums.h" +#include "platform/geometry/FloatQuad.h" +#include "platform/geometry/LayoutRect.h" +#include "platform/graphics/Color.h" +#include "platform/wtf/Forward.h" +#include "platform/wtf/Vector.h" + +class SkMatrix44; namespace blink { -enum AccessibilityRole { - kUnknownRole = 0, // Not mapped in platform APIs, generally indicates a bug - kAbbrRole, // No mapping to ARIA role. - kAlertDialogRole, - kAlertRole, - kAnchorRole, // No mapping to ARIA role. - kAnnotationRole, // No mapping to ARIA role. - kApplicationRole, - kArticleRole, - kAudioRole, // No mapping to ARIA role. - kBannerRole, - kBlockquoteRole, // No mapping to ARIA role. - kBusyIndicatorRole, // No mapping to ARIA role. - kButtonRole, - kCanvasRole, // No mapping to ARIA role. - kCaptionRole, // No mapping to ARIA role. - kCellRole, - kCheckBoxRole, - kColorWellRole, // No mapping to ARIA role. - kColumnHeaderRole, - kColumnRole, // No mapping to ARIA role. - kComboBoxRole, - kComplementaryRole, - kContentInfoRole, - kDateRole, // No mapping to ARIA role. - kDateTimeRole, // No mapping to ARIA role. - kDefinitionRole, - kDescriptionListDetailRole, // No mapping to ARIA role. - kDescriptionListRole, // No mapping to ARIA role. - kDescriptionListTermRole, // No mapping to ARIA role. - kDetailsRole, // No mapping to ARIA role. - kDialogRole, - kDirectoryRole, - kDisclosureTriangleRole, // No mapping to ARIA role. - kDocumentRole, - kEmbeddedObjectRole, // No mapping to ARIA role. - kFeedRole, - kFigcaptionRole, // No mapping to ARIA role. - kFigureRole, - kFooterRole, - kFormRole, - kGenericContainerRole, // No role was defined for this container - kGridRole, - kGroupRole, - kHeadingRole, - kIframePresentationalRole, // No mapping to ARIA role. - kIframeRole, // No mapping to ARIA role. - kIgnoredRole, // No mapping to ARIA role. - kImageMapLinkRole, // No mapping to ARIA role. - kImageMapRole, // No mapping to ARIA role. - kImageRole, - kInlineTextBoxRole, // No mapping to ARIA role. - kInputTimeRole, // No mapping to ARIA role. - kLabelRole, - kLegendRole, // No mapping to ARIA role. - kLineBreakRole, // No mapping to ARIA role. - kLinkRole, - kListBoxOptionRole, - kListBoxRole, - kListItemRole, - kListMarkerRole, // No mapping to ARIA role. - kListRole, - kLogRole, - kMainRole, - kMarkRole, // No mapping to ARIA role. - kMarqueeRole, - kMathRole, - kMenuBarRole, - kMenuButtonRole, - kMenuItemRole, - kMenuItemCheckBoxRole, - kMenuItemRadioRole, - kMenuListOptionRole, - kMenuListPopupRole, - kMenuRole, - kMeterRole, - kNavigationRole, - kNoneRole, // ARIA role of "none" - kNoteRole, - kOutlineRole, // No mapping to ARIA role. - kParagraphRole, // No mapping to ARIA role. - kPopUpButtonRole, - kPreRole, // No mapping to ARIA role. - kPresentationalRole, - kProgressIndicatorRole, - kRadioButtonRole, - kRadioGroupRole, - kRegionRole, - kRootWebAreaRole, // No mapping to ARIA role. - kRowHeaderRole, - kRowRole, - kRubyRole, // No mapping to ARIA role. - kRulerRole, // No mapping to ARIA role. - kSVGRootRole, // No mapping to ARIA role. - kScrollAreaRole, // No mapping to ARIA role. - kScrollBarRole, - kSeamlessWebAreaRole, // No mapping to ARIA role. - kSearchRole, - kSearchBoxRole, - kSliderRole, - kSliderThumbRole, // No mapping to ARIA role. - kSpinButtonPartRole, // No mapping to ARIA role. - kSpinButtonRole, - kSplitterRole, - kStaticTextRole, // No mapping to ARIA role. - kStatusRole, - kSwitchRole, - kTabGroupRole, // No mapping to ARIA role. - kTabListRole, - kTabPanelRole, - kTabRole, - kTableHeaderContainerRole, // No mapping to ARIA role. - kTableRole, - kTermRole, - kTextFieldRole, - kTimeRole, // No mapping to ARIA role. - kTimerRole, - kToggleButtonRole, - kToolbarRole, - kTreeGridRole, - kTreeItemRole, - kTreeRole, - kUserInterfaceTooltipRole, - kVideoRole, // No mapping to ARIA role. - kWebAreaRole, // No mapping to ARIA role. - kWindowRole, // No mapping to ARIA role. - kNumRoles +class AXObject; +class AXObjectCacheImpl; +class Element; +class IntPoint; +class LayoutObject; +class LocalFrameView; +class Node; +class ScrollableArea; + +enum class AOMBooleanProperty; +enum class AOMStringProperty; +enum class AOMUIntProperty; +enum class AOMIntProperty; +enum class AOMFloatProperty; + +typedef unsigned AXID; + +enum AccessibilityTextSource { + kAlternativeText, + kChildrenText, + kSummaryText, + kHelpText, + kVisibleText, + kTitleTagText, + kPlaceholderText, + kLabelByElementText, }; -enum AccessibilityState { - kAXBusyState, - kAXEnabledState, - kAXExpandedState, - kAXFocusableState, - kAXFocusedState, - kAXHaspopupState, - kAXHoveredState, - kAXInvisibleState, - kAXLinkedState, - kAXMultilineState, - kAXMultiselectableState, - kAXOffscreenState, - kAXProtectedState, - kAXReadonlyState, - kAXRequiredState, - kAXSelectableState, - kAXSelectedState, - kAXVerticalState, - kAXVisitedState +class AccessibilityText final + : public GarbageCollectedFinalized<AccessibilityText> { + WTF_MAKE_NONCOPYABLE(AccessibilityText); + + public: + DEFINE_INLINE_TRACE() { visitor->Trace(text_element_); } + + private: + AccessibilityText(const String& text, + const AccessibilityTextSource& source, + AXObject* element) + : text_(text), text_element_(element) {} + + String text_; + Member<AXObject> text_element_; }; -enum AccessibilityOrientation { - kAccessibilityOrientationUndefined = 0, - kAccessibilityOrientationVertical, - kAccessibilityOrientationHorizontal, +enum AXObjectInclusion { + kIncludeObject, + kIgnoreObject, + kDefaultBehavior, }; -enum class AXDefaultActionVerb { - kNone = 0, - kActivate, - kCheck, - kClick, - kJump, - kOpen, - kPress, - kSelect, - kUncheck +enum AccessibilityCheckedState { + kCheckedStateUndefined = 0, + kCheckedStateFalse, + kCheckedStateTrue, + kCheckedStateMixed }; -enum class AXSupportedAction { - kNone = 0, - kActivate, - kCheck, - kClick, - kJump, - kOpen, - kPress, - kSelect, - kUncheck +enum AccessibilityOptionalBool { + kOptionalBoolUndefined = 0, + kOptionalBoolTrue, + kOptionalBoolFalse }; -enum AccessibilityTextDirection { - kAccessibilityTextDirectionLTR, - kAccessibilityTextDirectionRTL, - kAccessibilityTextDirectionTTB, - kAccessibilityTextDirectionBTT +enum TextUnderElementMode { + kTextUnderElementAll, + kTextUnderElementAny // If the text is unimportant, just whether or not it's + // present }; -enum SortDirection { - kSortDirectionUndefined = 0, - kSortDirectionNone, - kSortDirectionAscending, - kSortDirectionDescending, - kSortDirectionOther +enum class AXBoolAttribute {}; + +class AXSparseAttributeClient { + public: + virtual void AddBoolAttribute(AXBoolAttribute, bool) = 0; + virtual void AddStringAttribute(AXStringAttribute, const String&) = 0; + virtual void AddObjectAttribute(AXObjectAttribute, AXObject&) = 0; + virtual void AddObjectVectorAttribute(AXObjectVectorAttribute, + HeapVector<Member<AXObject>>&) = 0; }; -enum AccessibilityExpanded { - kExpandedUndefined = 0, - kExpandedCollapsed, - kExpandedExpanded, +// The potential native HTML-based text (name, description or placeholder) +// sources for an element. See +// http://rawgit.com/w3c/aria/master/html-aam/html-aam.html#accessible-name-and-description-calculation +enum AXTextFromNativeHTML { + kAXTextFromNativeHTMLUninitialized = -1, + kAXTextFromNativeHTMLFigcaption, + kAXTextFromNativeHTMLLabel, + kAXTextFromNativeHTMLLabelFor, + kAXTextFromNativeHTMLLabelWrapped, + kAXTextFromNativeHTMLLegend, + kAXTextFromNativeHTMLTableCaption, + kAXTextFromNativeHTMLTitleElement, }; -enum AriaCurrentState { - kAriaCurrentStateUndefined = 0, - kAriaCurrentStateFalse, - kAriaCurrentStateTrue, - kAriaCurrentStatePage, - kAriaCurrentStateStep, - kAriaCurrentStateLocation, - kAriaCurrentStateDate, - kAriaCurrentStateTime +enum AXIgnoredReason { + kAXActiveModalDialog, + kAXAncestorDisallowsChild, + kAXAncestorIsLeafNode, + kAXAriaHiddenElement, + kAXAriaHiddenSubtree, + kAXEmptyAlt, + kAXEmptyText, + kAXInertElement, + kAXInertSubtree, + kAXInheritsPresentation, + kAXLabelContainer, + kAXLabelFor, + kAXNotRendered, + kAXNotVisible, + kAXPresentationalRole, + kAXProbablyPresentational, + kAXStaticTextUsedAsNameFor, + kAXUninteresting }; -enum InvalidState { - kInvalidStateUndefined = 0, - kInvalidStateFalse, - kInvalidStateTrue, - kInvalidStateSpelling, - kInvalidStateGrammar, - kInvalidStateOther +class IgnoredReason { + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); + + public: + AXIgnoredReason reason; + Member<const AXObject> related_object; + + explicit IgnoredReason(AXIgnoredReason reason) + : reason(reason), related_object(nullptr) {} + + IgnoredReason(AXIgnoredReason r, const AXObject* obj) + : reason(r), related_object(obj) {} + + DEFINE_INLINE_TRACE() { visitor->Trace(related_object); } }; -enum TextStyle { - kTextStyleNone = 0, - kTextStyleBold = 1 << 0, - kTextStyleItalic = 1 << 1, - kTextStyleUnderline = 1 << 2, - kTextStyleLineThrough = 1 << 3 +class NameSourceRelatedObject + : public GarbageCollectedFinalized<NameSourceRelatedObject> { + WTF_MAKE_NONCOPYABLE(NameSourceRelatedObject); + + public: + WeakMember<AXObject> object; + String text; + + NameSourceRelatedObject(AXObject* object, String text) + : object(object), text(text) {} + + DEFINE_INLINE_TRACE() { visitor->Trace(object); } }; -enum class AXStringAttribute { - kAriaKeyShortcuts, - kAriaRoleDescription, +typedef HeapVector<Member<NameSourceRelatedObject>> AXRelatedObjectVector; +class NameSource { + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); + + public: + String text; + bool superseded = false; + bool invalid = false; + AXNameFrom type = kAXNameFromUninitialized; + const QualifiedName& attribute; + AtomicString attribute_value; + AXTextFromNativeHTML native_source = kAXTextFromNativeHTMLUninitialized; + AXRelatedObjectVector related_objects; + + NameSource(bool superseded, const QualifiedName& attr) + : superseded(superseded), attribute(attr) {} + + explicit NameSource(bool superseded) + : superseded(superseded), attribute(QualifiedName::Null()) {} + + DEFINE_INLINE_TRACE() { visitor->Trace(related_objects); } }; -enum class AXObjectAttribute { - kAriaActiveDescendant, - kAriaDetails, - kAriaErrorMessage, +class DescriptionSource { + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); + + public: + String text; + bool superseded = false; + bool invalid = false; + AXDescriptionFrom type = kAXDescriptionFromUninitialized; + const QualifiedName& attribute; + AtomicString attribute_value; + AXTextFromNativeHTML native_source = kAXTextFromNativeHTMLUninitialized; + AXRelatedObjectVector related_objects; + + DescriptionSource(bool superseded, const QualifiedName& attr) + : superseded(superseded), attribute(attr) {} + + explicit DescriptionSource(bool superseded) + : superseded(superseded), attribute(QualifiedName::Null()) {} + + DEFINE_INLINE_TRACE() { visitor->Trace(related_objects); } }; -enum class AXObjectVectorAttribute { - kAriaControls, - kAriaFlowTo, +} // namespace blink + +WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::IgnoredReason); +WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::NameSource); +WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::DescriptionSource); + +namespace blink { + +class MODULES_EXPORT AXObject : public GarbageCollectedFinalized<AXObject> { + WTF_MAKE_NONCOPYABLE(AXObject); + + public: + typedef HeapVector<Member<AXObject>> AXObjectVector; + + struct AXRange { + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); + // The deepest descendant in which the range starts. + // (nullptr means the current object.) + Persistent<AXObject> anchor_object; + // The number of characters and child objects in the anchor object + // before the range starts. + int anchor_offset; + // When the same character offset could correspond to two possible + // cursor positions, upstream means it's on the previous line rather + // than the next line. + TextAffinity anchor_affinity; + + // The deepest descendant in which the range ends. + // (nullptr means the current object.) + Persistent<AXObject> focus_object; + // The number of characters and child objects in the focus object + // before the range ends. + int focus_offset; + // When the same character offset could correspond to two possible + // cursor positions, upstream means it's on the previous line rather + // than the next line. + TextAffinity focus_affinity; + + AXRange() + : anchor_object(nullptr), + anchor_offset(-1), + anchor_affinity(TextAffinity::kUpstream), + focus_object(nullptr), + focus_offset(-1), + focus_affinity(TextAffinity::kDownstream) {} + + AXRange(int start_offset, int end_offset) + : anchor_object(nullptr), + anchor_offset(start_offset), + anchor_affinity(TextAffinity::kUpstream), + focus_object(nullptr), + focus_offset(end_offset), + focus_affinity(TextAffinity::kDownstream) {} + + AXRange(AXObject* anchor_object, + int anchor_offset, + TextAffinity anchor_affinity, + AXObject* focus_object, + int focus_offset, + TextAffinity focus_affinity) + : anchor_object(anchor_object), + anchor_offset(anchor_offset), + anchor_affinity(anchor_affinity), + focus_object(focus_object), + focus_offset(focus_offset), + focus_affinity(focus_affinity) {} + + bool IsValid() const { + return ((anchor_object && focus_object) || + (!anchor_object && !focus_object)) && + anchor_offset >= 0 && focus_offset >= 0; + } + + // Determines if the range only refers to text offsets under the current + // object. + bool IsSimple() const { + return anchor_object == focus_object || !anchor_object || !focus_object; + } + }; + + protected: + AXObject(AXObjectCacheImpl&); + + public: + virtual ~AXObject(); + DECLARE_VIRTUAL_TRACE(); + + static unsigned NumberOfLiveAXObjects() { return number_of_live_ax_objects_; } + + // After constructing an AXObject, it must be given a + // unique ID, then added to AXObjectCacheImpl, and finally init() must + // be called last. + void SetAXObjectID(AXID ax_object_id) { id_ = ax_object_id; } + virtual void Init() {} + + // When the corresponding WebCore object that this AXObject + // wraps is deleted, it must be detached. + virtual void Detach(); + virtual bool IsDetached() const; + + // If the parent of this object is known, this can be faster than using + // computeParent(). + virtual void SetParent(AXObject* parent) { parent_ = parent; } + + // The AXObjectCacheImpl that owns this object, and its unique ID within this + // cache. + AXObjectCacheImpl& AxObjectCache() const { + DCHECK(ax_object_cache_); + return *ax_object_cache_; + } + + AXID AxObjectID() const { return id_; } + + // Wrappers that retrieve either an Accessibility Object Model property, + // or the equivalent ARIA attribute, in that order. + const AtomicString& GetAOMPropertyOrARIAAttribute(AOMStringProperty) const; + bool HasAOMPropertyOrARIAAttribute(AOMBooleanProperty, bool& result) const; + bool AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty) const; + bool AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty) const; + bool HasAOMPropertyOrARIAAttribute(AOMUIntProperty, uint32_t& result) const; + bool HasAOMPropertyOrARIAAttribute(AOMIntProperty, int32_t& result) const; + bool HasAOMPropertyOrARIAAttribute(AOMFloatProperty, float& result) const; + + virtual void GetSparseAXAttributes(AXSparseAttributeClient&) const {} + + // Determine subclass type. + virtual bool IsAXNodeObject() const { return false; } + virtual bool IsAXLayoutObject() const { return false; } + virtual bool IsAXInlineTextBox() const { return false; } + virtual bool IsAXListBox() const { return false; } + virtual bool IsAXListBoxOption() const { return false; } + virtual bool IsAXRadioInput() const { return false; } + virtual bool IsAXSVGRoot() const { return false; } + + // Check object role or purpose. + virtual AccessibilityRole RoleValue() const { return role_; } + bool IsARIATextControl() const; + virtual bool IsARIATreeGridRow() const { return false; } + virtual bool IsAXTable() const { return false; } + virtual bool IsAnchor() const { return false; } + bool IsButton() const; + bool IsCanvas() const { return RoleValue() == kCanvasRole; } + bool IsCheckbox() const { return RoleValue() == kCheckBoxRole; } + bool IsCheckboxOrRadio() const { return IsCheckbox() || IsRadioButton(); } + bool IsColorWell() const { return RoleValue() == kColorWellRole; } + bool IsComboBox() const { return RoleValue() == kComboBoxRole; } + virtual bool IsControl() const { return false; } + virtual bool IsDataTable() const { return false; } + virtual bool IsEmbeddedObject() const { return false; } + virtual bool IsFieldset() const { return false; } + virtual bool IsHeading() const { return false; } + virtual bool IsImage() const { return false; } + virtual bool IsImageMapLink() const { return false; } + virtual bool IsInputImage() const { return false; } + bool IsLandmarkRelated() const; + virtual bool IsLink() const { return false; } + virtual bool IsInPageLinkTarget() const { return false; } + virtual bool IsList() const { return false; } + virtual bool IsMenu() const { return false; } + virtual bool IsMenuButton() const { return false; } + virtual bool IsMenuList() const { return false; } + virtual bool IsMenuListOption() const { return false; } + virtual bool IsMenuListPopup() const { return false; } + bool IsMenuRelated() const; + virtual bool IsMeter() const { return false; } + virtual bool IsMockObject() const { return false; } + virtual bool IsNativeSpinButton() const { return false; } + virtual bool IsNativeTextControl() const { + return false; + } // input or textarea + virtual bool IsNonNativeTextControl() const { + return false; + } // contenteditable or role=textbox + virtual bool IsPasswordField() const { return false; } + virtual bool IsPasswordFieldAndShouldHideValue() const; + bool IsPresentational() const { + return RoleValue() == kNoneRole || RoleValue() == kPresentationalRole; + } + virtual bool IsProgressIndicator() const { return false; } + bool IsRadioButton() const { return RoleValue() == kRadioButtonRole; } + bool IsRange() const { + return RoleValue() == kProgressIndicatorRole || + RoleValue() == kScrollBarRole || RoleValue() == kSliderRole || + RoleValue() == kSpinButtonRole || IsMoveableSplitter(); + } + bool IsScrollbar() const { return RoleValue() == kScrollBarRole; } + virtual bool IsSlider() const { return false; } + virtual bool IsNativeSlider() const { return false; } + virtual bool IsMoveableSplitter() const { return false; } + virtual bool IsSpinButton() const { return RoleValue() == kSpinButtonRole; } + virtual bool IsSpinButtonPart() const { return false; } + bool IsTabItem() const { return RoleValue() == kTabRole; } + virtual bool IsTableCell() const { return false; } + virtual bool IsTableRow() const { return false; } + virtual bool IsTextControl() const { return false; } + virtual bool IsTableCol() const { return false; } + bool IsTree() const { return RoleValue() == kTreeRole; } + bool IsWebArea() const { return RoleValue() == kWebAreaRole; } + + // Check object state. + virtual bool IsClickable() const; + virtual bool IsCollapsed() const { return false; } + virtual bool IsEnabled() const { return false; } + virtual AccessibilityExpanded IsExpanded() const { + return kExpandedUndefined; + } + virtual bool IsFocused() const { return false; } + virtual bool IsHovered() const { return false; } + virtual bool IsLinked() const { return false; } + virtual bool IsLoaded() const { return false; } + virtual bool IsModal() const { return false; } + virtual bool IsMultiSelectable() const { return false; } + virtual bool IsOffScreen() const { return false; } + virtual bool IsReadOnly() const { return false; } + virtual bool IsRequired() const { return false; } + virtual bool IsSelected() const { return false; } + virtual bool IsSelectedOptionActive() const { return false; } + virtual bool IsVisible() const { return true; } + virtual bool IsVisited() const { return false; } + + // Check whether certain properties can be modified. + virtual bool CanSetFocusAttribute() const { return false; } + virtual bool CanSetValueAttribute() const { return false; } + virtual bool CanSetSelectedAttribute() const { return false; } + + // Whether objects are ignored, i.e. not included in the tree. + bool AccessibilityIsIgnored(); + typedef HeapVector<IgnoredReason> IgnoredReasons; + virtual bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const { + return true; + } + bool AccessibilityIsIgnoredByDefault(IgnoredReasons* = nullptr) const; + AXObjectInclusion AccessibilityPlatformIncludesObject() const; + virtual AXObjectInclusion DefaultObjectInclusion( + IgnoredReasons* = nullptr) const; + bool IsInertOrAriaHidden() const; + const AXObject* AriaHiddenRoot() const; + bool ComputeIsInertOrAriaHidden(IgnoredReasons* = nullptr) const; + bool IsDescendantOfLeafNode() const; + AXObject* LeafNodeAncestor() const; + bool IsDescendantOfDisabledNode() const; + const AXObject* DisabledAncestor() const; + bool LastKnownIsIgnoredValue(); + void SetLastKnownIsIgnoredValue(bool); + bool HasInheritedPresentationalRole() const; + bool IsPresentationalChild() const; + bool AncestorExposesActiveDescendant() const; + bool ComputeAncestorExposesActiveDescendant() const; + + // + // Accessible name calculation + // + + // Retrieves the accessible name of the object, an enum indicating where the + // name was derived from, and a list of objects that were used to derive the + // name, if any. + virtual String GetName(AXNameFrom&, AXObjectVector* name_objects) const; + + typedef HeapVector<NameSource> NameSources; + // Retrieves the accessible name of the object and a list of all potential + // sources for the name, indicating which were used. + virtual String GetName(NameSources*) const; + + typedef HeapVector<DescriptionSource> DescriptionSources; + // Takes the result of nameFrom from calling |name|, above, and retrieves the + // accessible description of the object, which is secondary to |name|, an enum + // indicating where the description was derived from, and a list of objects + // that were used to derive the description, if any. + virtual String Description(AXNameFrom, + AXDescriptionFrom&, + AXObjectVector* description_objects) const { + return String(); + } + + // Same as above, but returns a list of all potential sources for the + // description, indicating which were used. + virtual String Description(AXNameFrom, + AXDescriptionFrom&, + DescriptionSources*, + AXRelatedObjectVector*) const { + return String(); + } + + // Takes the result of nameFrom and descriptionFrom from calling |name| and + // |description|, above, and retrieves the placeholder of the object, if + // present and if it wasn't already exposed by one of the two functions above. + virtual String Placeholder(AXNameFrom) const { return String(); } + + // Internal functions used by name and description, above. + typedef HeapHashSet<Member<const AXObject>> AXObjectSet; + virtual String TextAlternative(bool recursive, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + AXNameFrom& name_from, + AXRelatedObjectVector* related_objects, + NameSources* name_sources) const { + return String(); + } + virtual String TextFromDescendants(AXObjectSet& visited, + bool recursive) const { + return String(); + } + + // Returns result of Accessible Name Calculation algorithm. + // This is a simpler high-level interface to |name| used by Inspector. + String ComputedName() const; + + // Internal function used to determine whether the result of calling |name| on + // this object would return text that came from the an HTML label element or + // not. This is intended to be faster than calling |name| or + // |textAlternative|, and without side effects (it won't call + // axObjectCache->getOrCreate). + virtual bool NameFromLabelElement() const { return false; } + + // + // Properties of static elements. + // + + virtual const AtomicString& AccessKey() const { return g_null_atom; } + RGBA32 BackgroundColor() const; + virtual RGBA32 ComputeBackgroundColor() const { return Color::kTransparent; } + virtual RGBA32 GetColor() const { return Color::kBlack; } + // Used by objects of role ColorWellRole. + virtual RGBA32 ColorValue() const { return Color::kTransparent; } + virtual bool CanvasHasFallbackContent() const { return false; } + virtual String FontFamily() const { return g_null_atom; } + // Font size is in pixels. + virtual float FontSize() const { return 0.0f; } + // Value should be 1-based. 0 means not supported. + virtual int HeadingLevel() const { return 0; } + // Value should be 1-based. 0 means not supported. + virtual unsigned HierarchicalLevel() const { return 0; } + // Return the content of an image or canvas as an image data url in + // PNG format. If |maxSize| is not empty and if the image is larger than + // those dimensions, the image will be resized proportionally first to fit. + virtual String ImageDataUrl(const IntSize& max_size) const { + return g_null_atom; + } + virtual AXObject* InPageLinkTarget() const { return nullptr; } + virtual AccessibilityOrientation Orientation() const; + virtual String GetText() const { return String(); } + virtual AccessibilityTextDirection GetTextDirection() const { + return kAccessibilityTextDirectionLTR; + } + virtual int TextLength() const { return 0; } + virtual TextStyle GetTextStyle() const { return kTextStyleNone; } + virtual AXObjectVector RadioButtonsInGroup() const { + return AXObjectVector(); + } + virtual KURL Url() const { return KURL(); } + + // Load inline text boxes for just this node, even if + // settings->inlineTextBoxAccessibilityEnabled() is false. + virtual void LoadInlineTextBoxes() {} + + // Walk the AXObjects on the same line. This is supported on any + // object type but primarily intended to be used for inline text boxes. + virtual AXObject* NextOnLine() const { return nullptr; } + virtual AXObject* PreviousOnLine() const { return nullptr; } + + // For all node objects. The start and end character offset of each + // marker, such as spelling or grammar error. + virtual void Markers(Vector<DocumentMarker::MarkerType>&, + Vector<AXRange>&) const {} + // For an inline text box. + // The integer horizontal pixel offset of each character in the string; + // negative values for RTL. + virtual void TextCharacterOffsets(Vector<int>&) const {} + // The start and end character offset of each word in the object's text. + virtual void GetWordBoundaries(Vector<AXRange>&) const {} + + // Properties of interactive elements. + AXDefaultActionVerb Action() const; + AccessibilityCheckedState CheckedState() const; + virtual AriaCurrentState GetAriaCurrentState() const { + return kAriaCurrentStateUndefined; + } + virtual InvalidState GetInvalidState() const { + return kInvalidStateUndefined; + } + // Only used when invalidState() returns InvalidStateOther. + virtual String AriaInvalidValue() const { return String(); } + virtual String ValueDescription() const { return String(); } + virtual float ValueForRange() const { return 0.0f; } + virtual float MaxValueForRange() const { return 0.0f; } + virtual float MinValueForRange() const { return 0.0f; } + virtual String StringValue() const { return String(); } + + // ARIA attributes. + virtual AXObject* ActiveDescendant() { return nullptr; } + virtual String AriaAutoComplete() const { return String(); } + virtual void AriaOwnsElements(AXObjectVector& owns) const {} + virtual void AriaDescribedbyElements(AXObjectVector&) const {} + virtual void AriaLabelledbyElements(AXObjectVector&) const {} + virtual bool AriaHasPopup() const { return false; } + virtual bool IsEditable() const { return false; } + bool IsMultiline() const; + virtual bool IsRichlyEditable() const { return false; } + bool AriaCheckedIsPresent() const; + bool AriaPressedIsPresent() const; + virtual AccessibilityRole AriaRoleAttribute() const { return kUnknownRole; } + virtual bool AriaRoleHasPresentationalChildren() const { return false; } + virtual AXObject* AncestorForWhichThisIsAPresentationalChild() const { + return 0; + } + bool SupportsActiveDescendant() const; + bool SupportsARIAAttributes() const; + virtual bool SupportsARIADragging() const { return false; } + virtual bool SupportsARIADropping() const { return false; } + virtual bool SupportsARIAFlowTo() const { return false; } + virtual bool SupportsARIAOwns() const { return false; } + bool SupportsRangeValue() const; + virtual SortDirection GetSortDirection() const { + return kSortDirectionUndefined; + } + + // Returns 0-based index. + int IndexInParent() const; + + // Value should be 1-based. 0 means not supported. + virtual int PosInSet() const { return 0; } + virtual int SetSize() const { return 0; } + bool SupportsSetSizeAndPosInSet() const; + + // ARIA live-region features. + bool IsLiveRegion() const; + AXObject* LiveRegionRoot() const; + virtual const AtomicString& LiveRegionStatus() const { return g_null_atom; } + virtual const AtomicString& LiveRegionRelevant() const { return g_null_atom; } + virtual bool LiveRegionAtomic() const { return false; } + virtual bool LiveRegionBusy() const { return false; } + + const AtomicString& ContainerLiveRegionStatus() const; + const AtomicString& ContainerLiveRegionRelevant() const; + bool ContainerLiveRegionAtomic() const; + bool ContainerLiveRegionBusy() const; + + // Every object's bounding box is returned relative to a + // container object (which is guaranteed to be an ancestor) and + // optionally a transformation matrix that needs to be applied too. + // To compute the absolute bounding box of an element, start with its + // boundsInContainer and apply the transform. Then as long as its container is + // not null, walk up to its container and offset by the container's offset + // from origin, the container's scroll position if any, and apply the + // container's transform. Do this until you reach the root of the tree. + virtual void GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform) const; + + // Get the bounds in frame-relative coordinates as a LayoutRect. + LayoutRect GetBoundsInFrameCoordinates() const; + + // Explicitly set an object's bounding rect and offset container. + void SetElementRect(LayoutRect r, AXObject* container) { + explicit_element_rect_ = r; + explicit_container_id_ = container->AxObjectID(); + } + + // Hit testing. + // Called on the root AX object to return the deepest available element. + virtual AXObject* AccessibilityHitTest(const IntPoint&) const { return 0; } + // Called on the AX object after the layout tree determines which is the right + // AXLayoutObject. + virtual AXObject* ElementAccessibilityHitTest(const IntPoint&) const; + + // High-level accessibility tree access. Other modules should only use these + // functions. + const AXObjectVector& Children(); + AXObject* ParentObject() const; + AXObject* ParentObjectIfExists() const; + virtual AXObject* ComputeParent() const = 0; + virtual AXObject* ComputeParentIfExists() const { return 0; } + AXObject* CachedParentObject() const { return parent_; } + AXObject* ParentObjectUnignored() const; + AXObject* ContainerWidget() const; + bool IsContainerWidget() const; + + // Low-level accessibility tree exploration, only for use within the + // accessibility module. + virtual AXObject* RawFirstChild() const { return 0; } + virtual AXObject* RawNextSibling() const { return 0; } + virtual void AddChildren() {} + virtual bool CanHaveChildren() const { return true; } + bool HasChildren() const { return have_children_; } + virtual void UpdateChildrenIfNecessary(); + virtual bool NeedsToUpdateChildren() const { return false; } + virtual void SetNeedsToUpdateChildren() {} + virtual void ClearChildren(); + virtual void DetachFromParent() { parent_ = 0; } + virtual AXObject* ScrollBar(AccessibilityOrientation) { return 0; } + + // Properties of the object's owning document or page. + virtual double EstimatedLoadingProgress() const { return 0; } + + // DOM and layout tree access. + virtual Node* GetNode() const { return nullptr; } + virtual Element* GetElement() const; // Same as GetNode, if it's an Element. + virtual LayoutObject* GetLayoutObject() const { return nullptr; } + virtual Document* GetDocument() const; + virtual LocalFrameView* DocumentFrameView() const; + virtual Element* AnchorElement() const { return nullptr; } + virtual Element* ActionElement() const { return nullptr; } + String Language() const; + bool HasAttribute(const QualifiedName&) const; + const AtomicString& GetAttribute(const QualifiedName&) const; + + // Methods that retrieve or manipulate the current selection. + + // Get the current selection from anywhere in the accessibility tree. + virtual AXRange Selection() const { return AXRange(); } + // Gets only the start and end offsets of the selection computed using the + // current object as the starting point. Returns a null selection if there is + // no selection in the subtree rooted at this object. + virtual AXRange SelectionUnderObject() const { return AXRange(); } + virtual void SetSelection(const AXRange&) {} + + // Scrollable containers. + bool IsScrollableContainer() const; + IntPoint GetScrollOffset() const; + IntPoint MinimumScrollOffset() const; + IntPoint MaximumScrollOffset() const; + void SetScrollOffset(const IntPoint&) const; + + // If this object itself scrolls, return its ScrollableArea. + virtual ScrollableArea* GetScrollableAreaIfScrollable() const { return 0; } + + // Modify or take an action on an object. + virtual void Increment() {} + virtual void Decrement() {} + bool PerformDefaultAction() { return Press(); } + virtual bool Press(); + // Make this object visible by scrolling as many nested scrollable views as + // needed. + void ScrollToMakeVisible() const; + // Same, but if the whole object can't be made visible, try for this subrect, + // in local coordinates. + void ScrollToMakeVisibleWithSubFocus(const IntRect&) const; + // Scroll this object to a given point in global coordinates of the top-level + // window. + void ScrollToGlobalPoint(const IntPoint&) const; + virtual void SetFocused(bool) {} + virtual void SetSelected(bool) {} + virtual void SetSequentialFocusNavigationStartingPoint(); + virtual void SetValue(const String&) {} + virtual void SetValue(float) {} + + // Notifications that this object may have changed. + virtual void ChildrenChanged() {} + virtual void HandleActiveDescendantChanged() {} + virtual void HandleAriaExpandedChanged() {} + void NotifyIfIgnoredValueChanged(); + virtual void SelectionChanged(); + virtual void TextChanged() {} + virtual void UpdateAccessibilityRole() {} + + // Text metrics. Most of these should be deprecated, needs major cleanup. + virtual VisiblePosition VisiblePositionForIndex(int) const { + return VisiblePosition(); + } + int LineForPosition(const VisiblePosition&) const; + virtual int Index(const VisiblePosition&) const { return -1; } + virtual void LineBreaks(Vector<int>&) const {} + + // Static helper functions. + static bool IsARIAControl(AccessibilityRole); + static bool IsARIAInput(AccessibilityRole); + static AccessibilityRole AriaRoleToWebCoreRole(const String&); + static const AtomicString& RoleName(AccessibilityRole); + static const AtomicString& InternalRoleName(AccessibilityRole); + + protected: + AXID id_; + AXObjectVector children_; + mutable bool have_children_; + AccessibilityRole role_; + AXObjectInclusion last_known_is_ignored_value_; + LayoutRect explicit_element_rect_; + AXID explicit_container_id_; + + // Used only inside textAlternative(): + static String CollapseWhitespace(const String&); + static String RecursiveTextAlternative(const AXObject&, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited); + bool IsHiddenForTextAlternativeCalculation() const; + String AriaTextAlternative(bool recursive, + bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + AXNameFrom&, + AXRelatedObjectVector*, + NameSources*, + bool* found_text_alternative) const; + String TextFromElements(bool in_aria_labelled_by_traversal, + AXObjectSet& visited, + HeapVector<Member<Element>>& elements, + AXRelatedObjectVector* related_objects) const; + void TokenVectorFromAttribute(Vector<String>&, const QualifiedName&) const; + void ElementsFromAttribute(HeapVector<Member<Element>>& elements, + const QualifiedName&) const; + void AriaLabelledbyElementVector(HeapVector<Member<Element>>& elements) const; + String TextFromAriaLabelledby(AXObjectSet& visited, + AXRelatedObjectVector* related_objects) const; + String TextFromAriaDescribedby(AXRelatedObjectVector* related_objects) const; + + virtual const AXObject* InheritsPresentationalRoleFrom() const { return 0; } + + bool CanReceiveAccessibilityFocus() const; + bool NameFromContents(bool recursive) const; + + AccessibilityRole ButtonRoleType() const; + + virtual LayoutObject* LayoutObjectForRelativeBounds() const { + return nullptr; + } + + const AXObject* InertRoot() const; + + mutable Member<AXObject> parent_; + + // The following cached attribute values (the ones starting with m_cached*) + // are only valid if m_lastModificationCount matches + // AXObjectCacheImpl::modificationCount(). + mutable int last_modification_count_; + mutable RGBA32 cached_background_color_; + mutable bool cached_is_ignored_ : 1; + mutable bool cached_is_inert_or_aria_hidden_ : 1; + mutable bool cached_is_descendant_of_leaf_node_ : 1; + mutable bool cached_is_descendant_of_disabled_node_ : 1; + mutable bool cached_has_inherited_presentational_role_ : 1; + mutable bool cached_is_presentational_child_ : 1; + mutable bool cached_ancestor_exposes_active_descendant_ : 1; + mutable Member<AXObject> cached_live_region_root_; + + Member<AXObjectCacheImpl> ax_object_cache_; + + // Updates the cached attribute values. This may be recursive, so to prevent + // deadlocks, + // functions called here may only search up the tree (ancestors), not down. + void UpdateCachedAttributeValuesIfNeeded() const; + + private: + bool IsCheckable() const; + static bool IsNativeInputInMixedState(const Node*); + static bool IncludesARIAWidgetRole(const String&); + static bool HasInteractiveARIAAttribute(const Element&); + + static unsigned number_of_live_ax_objects_; }; -// The source of the accessible name of an element. This is needed -// because on some platforms this determines how the accessible name -// is exposed. -enum AXNameFrom { - kAXNameFromUninitialized = -1, - kAXNameFromAttribute = 0, - kAXNameFromAttributeExplicitlyEmpty, - kAXNameFromCaption, - kAXNameFromContents, - kAXNameFromPlaceholder, - kAXNameFromRelatedElement, - kAXNameFromValue, - kAXNameFromTitle, -}; - -// The source of the accessible description of an element. This is needed -// because on some platforms this determines how the accessible description -// is exposed. -enum AXDescriptionFrom { - kAXDescriptionFromUninitialized = -1, - kAXDescriptionFromAttribute = 0, - kAXDescriptionFromContents, - kAXDescriptionFromRelatedElement, -}; - -// TODO(sashab): Add pure virtual methods to this class to remove dependencies -// on AXObjectImpl from outside of modules/. -class CORE_EXPORT AXObject {}; +#define DEFINE_AX_OBJECT_TYPE_CASTS(thisType, predicate) \ + DEFINE_TYPE_CASTS(thisType, AXObject, object, object->predicate, \ + object.predicate) } // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp index e0b1fde..269b6b51 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp
@@ -113,7 +113,7 @@ notification_post_timer_.Stop(); for (auto& entry : objects_) { - AXObjectImpl* obj = entry.value; + AXObject* obj = entry.value; obj->Detach(); RemoveAXID(obj); } @@ -123,11 +123,11 @@ #endif } -AXObjectImpl* AXObjectCacheImpl::Root() { +AXObject* AXObjectCacheImpl::Root() { return GetOrCreate(document_); } -AXObjectImpl* AXObjectCacheImpl::FocusedImageMapUIElement( +AXObject* AXObjectCacheImpl::FocusedImageMapUIElement( HTMLAreaElement* area_element) { // Find the corresponding accessibility object for the HTMLAreaElement. This // should be in the list of children for its corresponding image. @@ -138,15 +138,14 @@ if (!image_element) return 0; - AXObjectImpl* ax_layout_image = GetOrCreate(image_element); + AXObject* ax_layout_image = GetOrCreate(image_element); if (!ax_layout_image) return 0; - const AXObjectImpl::AXObjectVector& image_children = - ax_layout_image->Children(); + const AXObject::AXObjectVector& image_children = ax_layout_image->Children(); unsigned count = image_children.size(); for (unsigned k = 0; k < count; ++k) { - AXObjectImpl* child = image_children[k]; + AXObject* child = image_children[k]; if (!child->IsImageMapLink()) continue; @@ -157,7 +156,7 @@ return 0; } -AXObjectImpl* AXObjectCacheImpl::FocusedObject() { +AXObject* AXObjectCacheImpl::FocusedObject() { if (!AccessibilityEnabled()) return nullptr; @@ -175,12 +174,12 @@ if (AXObject* ax_popup = toHTMLInputElement(adjusted_focused_element)->PopupRootAXObject()) { if (Element* focused_element_in_popup = - ToAXObjectImpl(ax_popup)->GetDocument()->FocusedElement()) + ax_popup->GetDocument()->FocusedElement()) focused_node = focused_element_in_popup; } } - AXObjectImpl* obj = GetOrCreate(focused_node); + AXObject* obj = GetOrCreate(focused_node); if (!obj) return nullptr; @@ -192,7 +191,7 @@ return obj; } -AXObjectImpl* AXObjectCacheImpl::Get(LayoutObject* layout_object) { +AXObject* AXObjectCacheImpl::Get(LayoutObject* layout_object) { if (!layout_object) return 0; @@ -217,7 +216,7 @@ return layout_object && layout_object->IsMenuList(); } -AXObjectImpl* AXObjectCacheImpl::Get(const Node* node) { +AXObject* AXObjectCacheImpl::Get(const Node* node) { if (!node) return 0; @@ -250,7 +249,7 @@ return objects_.at(node_id); } -AXObjectImpl* AXObjectCacheImpl::Get(AbstractInlineTextBox* inline_text_box) { +AXObject* AXObjectCacheImpl::Get(AbstractInlineTextBox* inline_text_box) { if (!inline_text_box) return 0; @@ -271,8 +270,7 @@ return EqualIgnoringASCIICase(ToElement(node)->getAttribute(roleAttr), role); } -AXObjectImpl* AXObjectCacheImpl::CreateFromRenderer( - LayoutObject* layout_object) { +AXObject* AXObjectCacheImpl::CreateFromRenderer(LayoutObject* layout_object) { // FIXME: How could layoutObject->node() ever not be an Element? Node* node = layout_object->GetNode(); @@ -334,7 +332,7 @@ return AXLayoutObject::Create(layout_object, *this); } -AXObjectImpl* AXObjectCacheImpl::CreateFromNode(Node* node) { +AXObject* AXObjectCacheImpl::CreateFromNode(Node* node) { if (IsMenuListOption(node)) return AXMenuListOption::Create(toHTMLOptionElement(node), *this); @@ -344,23 +342,23 @@ return AXNodeObject::Create(node, *this); } -AXObjectImpl* AXObjectCacheImpl::CreateFromInlineTextBox( +AXObject* AXObjectCacheImpl::CreateFromInlineTextBox( AbstractInlineTextBox* inline_text_box) { return AXInlineTextBox::Create(inline_text_box, *this); } -AXObjectImpl* AXObjectCacheImpl::GetOrCreate(Node* node) { +AXObject* AXObjectCacheImpl::GetOrCreate(Node* node) { if (!node) return 0; if (!node->IsElementNode() && !node->IsTextNode() && !node->IsDocumentNode()) return 0; // Only documents, elements and text nodes get a11y objects - if (AXObjectImpl* obj = Get(node)) + if (AXObject* obj = Get(node)) return obj; // If the node has a layout object, prefer using that as the primary key for - // the AXObjectImpl, with the exception of an HTMLAreaElement, which is + // the AXObject, with the exception of an HTMLAreaElement, which is // created based on its node. if (node->GetLayoutObject() && !isHTMLAreaElement(node)) return GetOrCreate(node->GetLayoutObject()); @@ -371,7 +369,7 @@ if (isHTMLHeadElement(node)) return 0; - AXObjectImpl* new_obj = CreateFromNode(node); + AXObject* new_obj = CreateFromNode(node); // Will crash later if we have two objects for the same node. DCHECK(!Get(node)); @@ -388,14 +386,14 @@ return new_obj; } -AXObjectImpl* AXObjectCacheImpl::GetOrCreate(LayoutObject* layout_object) { +AXObject* AXObjectCacheImpl::GetOrCreate(LayoutObject* layout_object) { if (!layout_object) return 0; - if (AXObjectImpl* obj = Get(layout_object)) + if (AXObject* obj = Get(layout_object)) return obj; - AXObjectImpl* new_obj = CreateFromRenderer(layout_object); + AXObject* new_obj = CreateFromRenderer(layout_object); // Will crash later if we have two objects for the same layoutObject. DCHECK(!Get(layout_object)); @@ -409,15 +407,15 @@ return new_obj; } -AXObjectImpl* AXObjectCacheImpl::GetOrCreate( +AXObject* AXObjectCacheImpl::GetOrCreate( AbstractInlineTextBox* inline_text_box) { if (!inline_text_box) return 0; - if (AXObjectImpl* obj = Get(inline_text_box)) + if (AXObject* obj = Get(inline_text_box)) return obj; - AXObjectImpl* new_obj = CreateFromInlineTextBox(inline_text_box); + AXObject* new_obj = CreateFromInlineTextBox(inline_text_box); // Will crash later if we have two objects for the same inlineTextBox. DCHECK(!Get(inline_text_box)); @@ -431,8 +429,8 @@ return new_obj; } -AXObjectImpl* AXObjectCacheImpl::GetOrCreate(AccessibilityRole role) { - AXObjectImpl* obj = nullptr; +AXObject* AXObjectCacheImpl::GetOrCreate(AccessibilityRole role) { + AXObject* obj = nullptr; // will be filled in... switch (role) { @@ -472,7 +470,7 @@ return; // first fetch object to operate some cleanup functions on it - AXObjectImpl* obj = objects_.at(ax_id); + AXObject* obj = objects_.at(ax_id); if (!obj) return; @@ -534,7 +532,7 @@ return obj_id; } -AXID AXObjectCacheImpl::GetOrCreateAXID(AXObjectImpl* obj) { +AXID AXObjectCacheImpl::GetOrCreateAXID(AXObject* obj) { // check for already-assigned ID const AXID existing_axid = obj->AxObjectID(); if (existing_axid) { @@ -551,7 +549,7 @@ return new_axid; } -void AXObjectCacheImpl::RemoveAXID(AXObjectImpl* object) { +void AXObjectCacheImpl::RemoveAXID(AXObject* object) { if (!object) return; @@ -574,11 +572,11 @@ aria_owner_to_ids_mapping_.erase(obj_id); } -AXObjectImpl* AXObjectCacheImpl::NearestExistingAncestor(Node* node) { +AXObject* AXObjectCacheImpl::NearestExistingAncestor(Node* node) { // Find the nearest ancestor that already has an accessibility object, since // we might be in the middle of a layout. while (node) { - if (AXObjectImpl* obj = Get(node)) + if (AXObject* obj = Get(node)) return obj; node = node->parentNode(); } @@ -586,7 +584,7 @@ } void AXObjectCacheImpl::SelectionChanged(Node* node) { - AXObjectImpl* nearestAncestor = NearestExistingAncestor(node); + AXObject* nearestAncestor = NearestExistingAncestor(node); if (nearestAncestor) nearestAncestor->SelectionChanged(); } @@ -599,7 +597,7 @@ TextChanged(Get(layout_object)); } -void AXObjectCacheImpl::TextChanged(AXObjectImpl* obj) { +void AXObjectCacheImpl::TextChanged(AXObject* obj) { if (!obj) return; @@ -624,7 +622,7 @@ ChildrenChanged(Get(layout_object)); } -void AXObjectCacheImpl::ChildrenChanged(AXObjectImpl* obj) { +void AXObjectCacheImpl::ChildrenChanged(AXObject* obj) { if (!obj) return; @@ -636,7 +634,7 @@ unsigned i = 0, count = notifications_to_post_.size(); for (i = 0; i < count; ++i) { - AXObjectImpl* obj = notifications_to_post_[i].first; + AXObject* obj = notifications_to_post_[i].first; if (!obj->AxObjectID()) continue; @@ -680,7 +678,7 @@ PostNotification(Get(node), notification); } -void AXObjectCacheImpl::PostNotification(AXObjectImpl* object, +void AXObjectCacheImpl::PostNotification(AXObject* object, AXNotification notification) { if (!object) return; @@ -691,20 +689,19 @@ notification_post_timer_.StartOneShot(0, BLINK_FROM_HERE); } -bool AXObjectCacheImpl::IsAriaOwned(const AXObjectImpl* child) const { +bool AXObjectCacheImpl::IsAriaOwned(const AXObject* child) const { return aria_owned_child_to_owner_mapping_.Contains(child->AxObjectID()); } -AXObjectImpl* AXObjectCacheImpl::GetAriaOwnedParent( - const AXObjectImpl* child) const { +AXObject* AXObjectCacheImpl::GetAriaOwnedParent(const AXObject* child) const { return ObjectFromAXID( aria_owned_child_to_owner_mapping_.at(child->AxObjectID())); } void AXObjectCacheImpl::UpdateAriaOwns( - const AXObjectImpl* owner, + const AXObject* owner, const Vector<String>& id_vector, - HeapVector<Member<AXObjectImpl>>& owned_children) { + HeapVector<Member<AXObject>>& owned_children) { // // Update the map from the AXID of this element to the ids of the owned // children, and the reverse map from ids to possible AXID owners. @@ -754,7 +751,7 @@ if (!element) continue; - AXObjectImpl* child = GetOrCreate(element); + AXObject* child = GetOrCreate(element); if (!child) continue; @@ -772,7 +769,7 @@ // Walk up the parents of the owner object, make sure that this child // doesn't appear there, as that would create a cycle. bool found_cycle = false; - for (AXObjectImpl* parent = owner->ParentObject(); parent && !found_cycle; + for (AXObject* parent = owner->ParentObject(); parent && !found_cycle; parent = parent->ParentObject()) { if (parent == child) found_cycle = true; @@ -804,9 +801,9 @@ // to be safe and handle all cases we remove all of the current owned children // and add the new list of owned children. for (size_t i = 0; i < current_child_axi_ds.size(); ++i) { - // Find the AXObjectImpl for the child that this owner no longer owns. + // Find the AXObject for the child that this owner no longer owns. AXID removed_child_id = current_child_axi_ds[i]; - AXObjectImpl* removed_child = ObjectFromAXID(removed_child_id); + AXObject* removed_child = ObjectFromAXID(removed_child_id); // It's possible that this child has already been owned by some other owner, // in which case we don't need to do anything. @@ -824,7 +821,7 @@ removed_child->DetachFromParent(); AXID real_parent_id = aria_owned_child_to_real_parent_mapping_.at(removed_child_id); - AXObjectImpl* real_parent = ObjectFromAXID(real_parent_id); + AXObject* real_parent = ObjectFromAXID(real_parent_id); ChildrenChanged(real_parent); } @@ -834,10 +831,10 @@ } for (size_t i = 0; i < new_child_axi_ds.size(); ++i) { - // Find the AXObjectImpl for the child that will now be a child of this + // Find the AXObject for the child that will now be a child of this // owner. AXID added_child_id = new_child_axi_ds[i]; - AXObjectImpl* added_child = ObjectFromAXID(added_child_id); + AXObject* added_child = ObjectFromAXID(added_child_id); // Add this child to the mapping from child to owner. aria_owned_child_to_owner_mapping_.Set(added_child_id, owner->AxObjectID()); @@ -845,7 +842,7 @@ // Add its parent object to a mapping from child to real parent. If later // this owner doesn't own this child anymore, we need to return it to its // original parent. - AXObjectImpl* original_parent = added_child->ParentObject(); + AXObject* original_parent = added_child->ParentObject(); aria_owned_child_to_real_parent_mapping_.Set(added_child_id, original_parent->AxObjectID()); @@ -868,14 +865,14 @@ if (!owners) return; - AXObjectImpl* ax_element = GetOrCreate(element); + AXObject* ax_element = GetOrCreate(element); if (!ax_element) return; // If it's already owned, call childrenChanged on the owner to make sure it's // still an owner. if (IsAriaOwned(ax_element)) { - AXObjectImpl* owned_parent = GetAriaOwnedParent(ax_element); + AXObject* owned_parent = GetAriaOwnedParent(ax_element); DCHECK(owned_parent); ChildrenChanged(owned_parent); return; @@ -884,7 +881,7 @@ // If it's not already owned, check the possible owners based on our mapping // from ids to elements that have that id listed in their aria-owns attribute. for (const auto& ax_id : *owners) { - AXObjectImpl* owner = ObjectFromAXID(ax_id); + AXObject* owner = ObjectFromAXID(ax_id); if (owner) ChildrenChanged(owner); } @@ -904,7 +901,7 @@ } void AXObjectCacheImpl::ListboxActiveIndexChanged(HTMLSelectElement* select) { - AXObjectImpl* obj = Get(select); + AXObject* obj = Get(select); if (!obj || !obj->IsAXListBox()) return; @@ -913,7 +910,7 @@ void AXObjectCacheImpl::RadiobuttonRemovedFromGroup( HTMLInputElement* group_member) { - AXObjectImpl* obj = Get(group_member); + AXObject* obj = Get(group_member); if (!obj || !obj->IsAXRadioInput()) return; @@ -921,7 +918,7 @@ // node, as the removed node is already detached from tree. HTMLInputElement* first_radio = ToAXRadioInput(obj)->FindFirstRadioButtonInGroup(group_member); - AXObjectImpl* first_obj = Get(first_radio); + AXObject* first_obj = Get(first_radio); if (!first_obj || !first_obj->IsAXRadioInput()) return; @@ -936,31 +933,31 @@ modification_count_++; - // Create the AXObjectImpl if it didn't yet exist - that's always safe at the + // Create the AXObject if it didn't yet exist - that's always safe at the // end of a layout, and it allows an AX notification to be sent when a page // has its first layout, rather than when the document first loads. - if (AXObjectImpl* obj = GetOrCreate(layout_object)) + if (AXObject* obj = GetOrCreate(layout_object)) PostNotification(obj, kAXLayoutComplete); } void AXObjectCacheImpl::HandleClicked(Node* node) { - if (AXObjectImpl* obj = GetOrCreate(node)) + if (AXObject* obj = GetOrCreate(node)) PostNotification(obj, kAXClicked); } void AXObjectCacheImpl::HandleAriaExpandedChange(Node* node) { - if (AXObjectImpl* obj = GetOrCreate(node)) + if (AXObject* obj = GetOrCreate(node)) obj->HandleAriaExpandedChanged(); } void AXObjectCacheImpl::HandleAriaSelectedChanged(Node* node) { - AXObjectImpl* obj = Get(node); + AXObject* obj = Get(node); if (!obj) return; PostNotification(obj, kAXCheckedStateChanged); - AXObjectImpl* listbox = obj->ParentObjectUnignored(); + AXObject* listbox = obj->ParentObjectUnignored(); if (listbox && listbox->RoleValue() == kListBoxRole) PostNotification(listbox, kAXSelectedChildrenChanged); } @@ -971,12 +968,12 @@ // it can affect what's focusable or not. modification_count_++; - if (AXObjectImpl* obj = GetOrCreate(node)) + if (AXObject* obj = GetOrCreate(node)) obj->HandleActiveDescendantChanged(); } void AXObjectCacheImpl::HandleAriaRoleChanged(Node* node) { - if (AXObjectImpl* obj = GetOrCreate(node)) { + if (AXObject* obj = GetOrCreate(node)) { obj->UpdateAccessibilityRole(); modification_count_++; obj->NotifyIfIgnoredValueChanged(); @@ -1034,7 +1031,7 @@ // Only update if the accessibility object already exists and it's // not already marked as dirty. - if (AXObjectImpl* obj = Get(layout_object)) { + if (AXObject* obj = Get(layout_object)) { if (!obj->NeedsToUpdateChildren()) { obj->SetNeedsToUpdateChildren(); PostNotification(layout_object, kAXChildrenChanged); @@ -1073,12 +1070,11 @@ return result; } -AXObjectImpl* AXObjectCacheImpl::FirstAccessibleObjectFromNode( - const Node* node) { +AXObject* AXObjectCacheImpl::FirstAccessibleObjectFromNode(const Node* node) { if (!node) return 0; - AXObjectImpl* accessible_object = GetOrCreate(node->GetLayoutObject()); + AXObject* accessible_object = GetOrCreate(node->GetLayoutObject()); while (accessible_object && accessible_object->AccessibilityIsIgnored()) { node = NodeTraversal::Next(*node); @@ -1098,7 +1094,7 @@ if (!node) return false; - const AXObjectImpl* ax_object = GetOrCreate(const_cast<Node*>(node)); + const AXObject* ax_object = GetOrCreate(const_cast<Node*>(node)); return ax_object && ax_object->IsTextControl(); } @@ -1115,7 +1111,7 @@ return !is_null && !hidden; } -void AXObjectCacheImpl::PostPlatformNotification(AXObjectImpl* obj, +void AXObjectCacheImpl::PostPlatformNotification(AXObject* obj, AXNotification notification) { if (!obj || !obj->GetDocument() || !obj->DocumentFrameView() || !obj->DocumentFrameView()->GetFrame().GetPage()) @@ -1138,11 +1134,11 @@ if (!page) return; - AXObjectImpl* focused_object = this->FocusedObject(); + AXObject* focused_object = this->FocusedObject(); if (!focused_object) return; - AXObjectImpl* old_focused_object = Get(old_focused_node); + AXObject* old_focused_object = Get(old_focused_node); PostPlatformNotification(old_focused_object, kAXBlur); PostPlatformNotification(focused_object, kAXFocusedUIElementChanged); @@ -1153,7 +1149,7 @@ } void AXObjectCacheImpl::HandleEditableTextContentChanged(Node* node) { - AXObjectImpl* obj = Get(node); + AXObject* obj = Get(node); while (obj && !obj->IsNativeTextControl() && !obj->IsNonNativeTextControl()) obj = obj->ParentObject(); PostNotification(obj, AXObjectCache::kAXValueChanged); @@ -1164,8 +1160,8 @@ } void AXObjectCacheImpl::HandleTextMarkerDataAdded(Node* start, Node* end) { - AXObjectImpl* start_object = Get(start); - AXObjectImpl* end_object = Get(end); + AXObject* start_object = Get(start); + AXObject* end_object = Get(end); if (!start_object || !end_object) return; @@ -1182,7 +1178,7 @@ void AXObjectCacheImpl::HandleUpdateActiveMenuOption(LayoutMenuList* menu_list, int option_index) { - AXObjectImpl* obj = GetOrCreate(menu_list); + AXObject* obj = GetOrCreate(menu_list); if (!obj || !obj->IsMenuList()) return; @@ -1190,7 +1186,7 @@ } void AXObjectCacheImpl::DidShowMenuListPopup(LayoutMenuList* menu_list) { - AXObjectImpl* obj = Get(menu_list); + AXObject* obj = Get(menu_list); if (!obj || !obj->IsMenuList()) return; @@ -1198,7 +1194,7 @@ } void AXObjectCacheImpl::DidHideMenuListPopup(LayoutMenuList* menu_list) { - AXObjectImpl* obj = Get(menu_list); + AXObject* obj = Get(menu_list); if (!obj || !obj->IsMenuList()) return; @@ -1216,7 +1212,7 @@ void AXObjectCacheImpl::HandleScrolledToAnchor(const Node* anchor_node) { if (!anchor_node) return; - AXObjectImpl* obj = GetOrCreate(anchor_node->GetLayoutObject()); + AXObject* obj = GetOrCreate(anchor_node->GetLayoutObject()); if (!obj) return; if (obj->AccessibilityIsIgnored()) @@ -1226,7 +1222,7 @@ void AXObjectCacheImpl::HandleScrollPositionChanged( LocalFrameView* frame_view) { - AXObjectImpl* target_ax_object = + AXObject* target_ax_object = GetOrCreate(frame_view->GetFrame().GetDocument()); PostPlatformNotification(target_ax_object, kAXScrollPositionChanged); } @@ -1238,14 +1234,14 @@ } const AtomicString& AXObjectCacheImpl::ComputedRoleForNode(Node* node) { - AXObjectImpl* obj = GetOrCreate(node); + AXObject* obj = GetOrCreate(node); if (!obj) - return AXObjectImpl::RoleName(kUnknownRole); - return AXObjectImpl::RoleName(obj->RoleValue()); + return AXObject::RoleName(kUnknownRole); + return AXObject::RoleName(obj->RoleValue()); } String AXObjectCacheImpl::ComputedNameForNode(Node* node) { - AXObjectImpl* obj = GetOrCreate(node); + AXObject* obj = GetOrCreate(node); if (!obj) return ""; @@ -1253,7 +1249,7 @@ } void AXObjectCacheImpl::OnTouchAccessibilityHover(const IntPoint& location) { - AXObjectImpl* hit = Root()->AccessibilityHitTest(location); + AXObject* hit = Root()->AccessibilityHitTest(location); if (hit) { // Ignore events on a frame or plug-in, because the touch events // will be re-targeted there and we don't want to fire duplicate @@ -1269,11 +1265,11 @@ void AXObjectCacheImpl::SetCanvasObjectBounds(HTMLCanvasElement* canvas, Element* element, const LayoutRect& rect) { - AXObjectImpl* obj = GetOrCreate(element); + AXObject* obj = GetOrCreate(element); if (!obj) return; - AXObjectImpl* ax_canvas = GetOrCreate(canvas); + AXObject* ax_canvas = GetOrCreate(canvas); if (!ax_canvas) return;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h index 6238bfb..b8844f4 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h
@@ -32,7 +32,7 @@ #include <memory> #include "core/dom/AXObjectCacheBase.h" #include "modules/ModulesExport.h" -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" #include "platform/wtf/Forward.h" #include "platform/wtf/HashMap.h" #include "platform/wtf/HashSet.h" @@ -55,7 +55,7 @@ DECLARE_VIRTUAL_TRACE(); Document& GetDocument() { return *document_; } - AXObjectImpl* FocusedObject(); + AXObject* FocusedObject(); void Dispose() override; @@ -77,9 +77,9 @@ // Called by a node when text or a text equivalent (e.g. alt) attribute is // changed. void TextChanged(LayoutObject*) override; - void TextChanged(AXObjectImpl*); + void TextChanged(AXObject*); // Called when a node has just been attached, so we can make sure we have the - // right subclass of AXObjectImpl. + // right subclass of AXObject. void UpdateCacheAfterNodeIsAttached(Node*) override; void HandleAttributeChanged(const QualifiedName& attr_name, @@ -118,27 +118,27 @@ void OnTouchAccessibilityHover(const IntPoint&) override; // Returns the root object for the entire document. - AXObjectImpl* RootObject(); + AXObject* RootObject(); - AXObjectImpl* ObjectFromAXID(AXID id) const { return objects_.at(id); } - AXObjectImpl* Root(); + AXObject* ObjectFromAXID(AXID id) const { return objects_.at(id); } + AXObject* Root(); // used for objects without backing elements - AXObjectImpl* GetOrCreate(AccessibilityRole); - AXObjectImpl* GetOrCreate(LayoutObject*) override; - AXObjectImpl* GetOrCreate(Node*); - AXObjectImpl* GetOrCreate(AbstractInlineTextBox*); + AXObject* GetOrCreate(AccessibilityRole); + AXObject* GetOrCreate(LayoutObject*) override; + AXObject* GetOrCreate(Node*); + AXObject* GetOrCreate(AbstractInlineTextBox*); - // will only return the AXObjectImpl if it already exists - AXObjectImpl* Get(const Node*) override; - AXObjectImpl* Get(LayoutObject*); - AXObjectImpl* Get(AbstractInlineTextBox*); + // will only return the AXObject if it already exists + AXObject* Get(const Node*) override; + AXObject* Get(LayoutObject*); + AXObject* Get(AbstractInlineTextBox*); - AXObjectImpl* FirstAccessibleObjectFromNode(const Node*); + AXObject* FirstAccessibleObjectFromNode(const Node*); void Remove(AXID); - void ChildrenChanged(AXObjectImpl*); + void ChildrenChanged(AXObject*); void HandleActiveDescendantChanged(Node*); void HandleAriaRoleChanged(Node*); @@ -148,7 +148,7 @@ bool AccessibilityEnabled(); bool InlineTextBoxAccessibilityEnabled(); - void RemoveAXID(AXObjectImpl*); + void RemoveAXID(AXObject*); AXID GenerateAXID() const; @@ -158,7 +158,7 @@ void PostNotification(LayoutObject*, AXNotification); void PostNotification(Node*, AXNotification); - void PostNotification(AXObjectImpl*, AXNotification); + void PostNotification(AXObject*, AXNotification); // // Aria-owns support. @@ -166,10 +166,10 @@ // Returns true if the given object's position in the tree was due to // aria-owns. - bool IsAriaOwned(const AXObjectImpl*) const; + bool IsAriaOwned(const AXObject*) const; // Returns the parent of the given object due to aria-owns. - AXObjectImpl* GetAriaOwnedParent(const AXObjectImpl*) const; + AXObject* GetAriaOwnedParent(const AXObject*) const; // Given an object that has an aria-owns attributes, and a vector of ids from // the value of that attribute, updates the internal state to reflect the new @@ -180,9 +180,9 @@ // If one or more ids aren't found, they're added to a lookup table so that if // an element with that id appears later, it can be added when you call // updateTreeIfElementIdIsAriaOwned. - void UpdateAriaOwns(const AXObjectImpl* owner, + void UpdateAriaOwns(const AXObject* owner, const Vector<String>& id_vector, - HeapVector<Member<AXObjectImpl>>& owned_children); + HeapVector<Member<AXObject>>& owned_children); // Given an element in the DOM tree that was either just added or whose id // just changed, check to see if another object wants to be its parent due to @@ -191,16 +191,16 @@ void UpdateTreeIfElementIdIsAriaOwned(Element*); protected: - void PostPlatformNotification(AXObjectImpl*, AXNotification); + void PostPlatformNotification(AXObject*, AXNotification); void LabelChanged(Element*); - AXObjectImpl* CreateFromRenderer(LayoutObject*); - AXObjectImpl* CreateFromNode(Node*); - AXObjectImpl* CreateFromInlineTextBox(AbstractInlineTextBox*); + AXObject* CreateFromRenderer(LayoutObject*); + AXObject* CreateFromNode(Node*); + AXObject* CreateFromInlineTextBox(AbstractInlineTextBox*); private: Member<Document> document_; - HeapHashMap<AXID, Member<AXObjectImpl>> objects_; + HeapHashMap<AXID, Member<AXObject>> objects_; // LayoutObject and AbstractInlineTextBox are not on the Oilpan heap so we // do not use HeapHashMap for those mappings. HashMap<LayoutObject*, AXID> layout_object_mapping_; @@ -245,17 +245,17 @@ HashMap<String, std::unique_ptr<HashSet<AXID>>> id_to_aria_owners_mapping_; TaskRunnerTimer<AXObjectCacheImpl> notification_post_timer_; - HeapVector<std::pair<Member<AXObjectImpl>, AXNotification>> + HeapVector<std::pair<Member<AXObject>, AXNotification>> notifications_to_post_; void NotificationPostTimerFired(TimerBase*); - AXObjectImpl* FocusedImageMapUIElement(HTMLAreaElement*); + AXObject* FocusedImageMapUIElement(HTMLAreaElement*); - AXID GetOrCreateAXID(AXObjectImpl*); + AXID GetOrCreateAXID(AXObject*); void TextChanged(Node*); bool NodeIsTextControl(const Node*); - AXObjectImpl* NearestExistingAncestor(Node*); + AXObject* NearestExistingAncestor(Node*); Settings* GetSettings(); };
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.cpp deleted file mode 100644 index 0141a1d8..0000000 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.cpp +++ /dev/null
@@ -1,2102 +0,0 @@ -/* - * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "modules/accessibility/AXObjectImpl.h" - -#include "SkMatrix44.h" -#include "core/InputTypeNames.h" -#include "core/css/resolver/StyleResolver.h" -#include "core/dom/AccessibleNode.h" -#include "core/dom/UserGestureIndicator.h" -#include "core/editing/EditingUtilities.h" -#include "core/editing/VisibleUnits.h" -#include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameView.h" -#include "core/frame/Settings.h" -#include "core/html/HTMLDialogElement.h" -#include "core/html/HTMLFrameOwnerElement.h" -#include "core/html/HTMLInputElement.h" -#include "core/html/parser/HTMLParserIdioms.h" -#include "core/layout/LayoutBoxModelObject.h" -#include "modules/accessibility/AXObjectCacheImpl.h" -#include "platform/text/PlatformLocale.h" -#include "platform/wtf/HashSet.h" -#include "platform/wtf/StdLibExtras.h" -#include "platform/wtf/text/WTFString.h" - -using blink::WebLocalizedString; - -namespace blink { - -using namespace HTMLNames; - -namespace { - -struct AccessibilityRoleHashTraits : HashTraits<AccessibilityRole> { - static const bool kEmptyValueIsZero = true; - static AccessibilityRole EmptyValue() { - return AccessibilityRole::kUnknownRole; - } -}; - -using ARIARoleMap = HashMap<String, - AccessibilityRole, - CaseFoldingHash, - HashTraits<String>, - AccessibilityRoleHashTraits>; - -struct RoleEntry { - const char* aria_role; - AccessibilityRole webcore_role; -}; - -const RoleEntry kRoles[] = {{"alert", kAlertRole}, - {"alertdialog", kAlertDialogRole}, - {"application", kApplicationRole}, - {"article", kArticleRole}, - {"banner", kBannerRole}, - {"button", kButtonRole}, - {"cell", kCellRole}, - {"checkbox", kCheckBoxRole}, - {"columnheader", kColumnHeaderRole}, - {"combobox", kComboBoxRole}, - {"complementary", kComplementaryRole}, - {"contentinfo", kContentInfoRole}, - {"definition", kDefinitionRole}, - {"dialog", kDialogRole}, - {"directory", kDirectoryRole}, - {"document", kDocumentRole}, - {"feed", kFeedRole}, - {"figure", kFigureRole}, - {"form", kFormRole}, - {"grid", kGridRole}, - {"gridcell", kCellRole}, - {"group", kGroupRole}, - {"heading", kHeadingRole}, - {"img", kImageRole}, - {"link", kLinkRole}, - {"list", kListRole}, - {"listbox", kListBoxRole}, - {"listitem", kListItemRole}, - {"log", kLogRole}, - {"main", kMainRole}, - {"marquee", kMarqueeRole}, - {"math", kMathRole}, - {"menu", kMenuRole}, - {"menubar", kMenuBarRole}, - {"menuitem", kMenuItemRole}, - {"menuitemcheckbox", kMenuItemCheckBoxRole}, - {"menuitemradio", kMenuItemRadioRole}, - {"navigation", kNavigationRole}, - {"none", kNoneRole}, - {"note", kNoteRole}, - {"option", kListBoxOptionRole}, - {"presentation", kPresentationalRole}, - {"progressbar", kProgressIndicatorRole}, - {"radio", kRadioButtonRole}, - {"radiogroup", kRadioGroupRole}, - {"region", kRegionRole}, - {"row", kRowRole}, - {"rowheader", kRowHeaderRole}, - {"scrollbar", kScrollBarRole}, - {"search", kSearchRole}, - {"searchbox", kSearchBoxRole}, - {"separator", kSplitterRole}, - {"slider", kSliderRole}, - {"spinbutton", kSpinButtonRole}, - {"status", kStatusRole}, - {"switch", kSwitchRole}, - {"tab", kTabRole}, - {"table", kTableRole}, - {"tablist", kTabListRole}, - {"tabpanel", kTabPanelRole}, - {"term", kTermRole}, - {"text", kStaticTextRole}, - {"textbox", kTextFieldRole}, - {"timer", kTimerRole}, - {"toolbar", kToolbarRole}, - {"tooltip", kUserInterfaceTooltipRole}, - {"tree", kTreeRole}, - {"treegrid", kTreeGridRole}, - {"treeitem", kTreeItemRole}}; - -struct InternalRoleEntry { - AccessibilityRole webcore_role; - const char* internal_role_name; -}; - -const InternalRoleEntry kInternalRoles[] = { - {kUnknownRole, "Unknown"}, - {kAbbrRole, "Abbr"}, - {kAlertDialogRole, "AlertDialog"}, - {kAlertRole, "Alert"}, - {kAnchorRole, "Anchor"}, - {kAnnotationRole, "Annotation"}, - {kApplicationRole, "Application"}, - {kArticleRole, "Article"}, - {kAudioRole, "Audio"}, - {kBannerRole, "Banner"}, - {kBlockquoteRole, "Blockquote"}, - // TODO(nektar): Delete busy_indicator role. It's used nowhere. - {kBusyIndicatorRole, "BusyIndicator"}, - {kButtonRole, "Button"}, - {kCanvasRole, "Canvas"}, - {kCaptionRole, "Caption"}, - {kCellRole, "Cell"}, - {kCheckBoxRole, "CheckBox"}, - {kColorWellRole, "ColorWell"}, - {kColumnHeaderRole, "ColumnHeader"}, - {kColumnRole, "Column"}, - {kComboBoxRole, "ComboBox"}, - {kComplementaryRole, "Complementary"}, - {kContentInfoRole, "ContentInfo"}, - {kDateRole, "Date"}, - {kDateTimeRole, "DateTime"}, - {kDefinitionRole, "Definition"}, - {kDescriptionListDetailRole, "DescriptionListDetail"}, - {kDescriptionListRole, "DescriptionList"}, - {kDescriptionListTermRole, "DescriptionListTerm"}, - {kDetailsRole, "Details"}, - {kDialogRole, "Dialog"}, - {kDirectoryRole, "Directory"}, - {kDisclosureTriangleRole, "DisclosureTriangle"}, - {kDocumentRole, "Document"}, - {kEmbeddedObjectRole, "EmbeddedObject"}, - {kFeedRole, "feed"}, - {kFigcaptionRole, "Figcaption"}, - {kFigureRole, "Figure"}, - {kFooterRole, "Footer"}, - {kFormRole, "Form"}, - {kGenericContainerRole, "GenericContainer"}, - {kGridRole, "Grid"}, - {kGroupRole, "Group"}, - {kHeadingRole, "Heading"}, - {kIframePresentationalRole, "IframePresentational"}, - {kIframeRole, "Iframe"}, - {kIgnoredRole, "Ignored"}, - {kImageMapLinkRole, "ImageMapLink"}, - {kImageMapRole, "ImageMap"}, - {kImageRole, "Image"}, - {kInlineTextBoxRole, "InlineTextBox"}, - {kInputTimeRole, "InputTime"}, - {kLabelRole, "Label"}, - {kLegendRole, "Legend"}, - {kLinkRole, "Link"}, - {kLineBreakRole, "LineBreak"}, - {kListBoxOptionRole, "ListBoxOption"}, - {kListBoxRole, "ListBox"}, - {kListItemRole, "ListItem"}, - {kListMarkerRole, "ListMarker"}, - {kListRole, "List"}, - {kLogRole, "Log"}, - {kMainRole, "Main"}, - {kMarkRole, "Mark"}, - {kMarqueeRole, "Marquee"}, - {kMathRole, "Math"}, - {kMenuBarRole, "MenuBar"}, - {kMenuButtonRole, "MenuButton"}, - {kMenuItemRole, "MenuItem"}, - {kMenuItemCheckBoxRole, "MenuItemCheckBox"}, - {kMenuItemRadioRole, "MenuItemRadio"}, - {kMenuListOptionRole, "MenuListOption"}, - {kMenuListPopupRole, "MenuListPopup"}, - {kMenuRole, "Menu"}, - {kMeterRole, "Meter"}, - {kNavigationRole, "Navigation"}, - {kNoneRole, "None"}, - {kNoteRole, "Note"}, - {kOutlineRole, "Outline"}, - {kParagraphRole, "Paragraph"}, - {kPopUpButtonRole, "PopUpButton"}, - {kPreRole, "Pre"}, - {kPresentationalRole, "Presentational"}, - {kProgressIndicatorRole, "ProgressIndicator"}, - {kRadioButtonRole, "RadioButton"}, - {kRadioGroupRole, "RadioGroup"}, - {kRegionRole, "Region"}, - {kRootWebAreaRole, "RootWebArea"}, - {kRowHeaderRole, "RowHeader"}, - {kRowRole, "Row"}, - {kRubyRole, "Ruby"}, - {kRulerRole, "Ruler"}, - {kSVGRootRole, "SVGRoot"}, - {kScrollAreaRole, "ScrollArea"}, - {kScrollBarRole, "ScrollBar"}, - {kSeamlessWebAreaRole, "SeamlessWebArea"}, - {kSearchRole, "Search"}, - {kSearchBoxRole, "SearchBox"}, - {kSliderRole, "Slider"}, - {kSliderThumbRole, "SliderThumb"}, - {kSpinButtonPartRole, "SpinButtonPart"}, - {kSpinButtonRole, "SpinButton"}, - {kSplitterRole, "Splitter"}, - {kStaticTextRole, "StaticText"}, - {kStatusRole, "Status"}, - {kSwitchRole, "Switch"}, - {kTabGroupRole, "TabGroup"}, - {kTabListRole, "TabList"}, - {kTabPanelRole, "TabPanel"}, - {kTabRole, "Tab"}, - {kTableHeaderContainerRole, "TableHeaderContainer"}, - {kTableRole, "Table"}, - {kTermRole, "Term"}, - {kTextFieldRole, "TextField"}, - {kTimeRole, "Time"}, - {kTimerRole, "Timer"}, - {kToggleButtonRole, "ToggleButton"}, - {kToolbarRole, "Toolbar"}, - {kTreeGridRole, "TreeGrid"}, - {kTreeItemRole, "TreeItem"}, - {kTreeRole, "Tree"}, - {kUserInterfaceTooltipRole, "UserInterfaceTooltip"}, - {kVideoRole, "Video"}, - {kWebAreaRole, "WebArea"}, - {kWindowRole, "Window"}}; - -static_assert(WTF_ARRAY_LENGTH(kInternalRoles) == kNumRoles, - "Not all internal roles have an entry in internalRoles array"); - -// Roles which we need to map in the other direction -const RoleEntry kReverseRoles[] = { - {"button", kToggleButtonRole}, {"combobox", kPopUpButtonRole}, - {"contentinfo", kFooterRole}, {"menuitem", kMenuButtonRole}, - {"menuitem", kMenuListOptionRole}, {"progressbar", kMeterRole}, - {"textbox", kTextFieldRole}}; - -static ARIARoleMap* CreateARIARoleMap() { - ARIARoleMap* role_map = new ARIARoleMap; - - for (size_t i = 0; i < WTF_ARRAY_LENGTH(kRoles); ++i) - role_map->Set(String(kRoles[i].aria_role), kRoles[i].webcore_role); - - // Grids "ignore" their non-row children during computation of children. - role_map->Set("rowgroup", kIgnoredRole); - - return role_map; -} - -static Vector<AtomicString>* CreateRoleNameVector() { - Vector<AtomicString>* role_name_vector = new Vector<AtomicString>(kNumRoles); - for (int i = 0; i < kNumRoles; i++) - (*role_name_vector)[i] = g_null_atom; - - for (size_t i = 0; i < WTF_ARRAY_LENGTH(kRoles); ++i) { - (*role_name_vector)[kRoles[i].webcore_role] = - AtomicString(kRoles[i].aria_role); - } - - for (size_t i = 0; i < WTF_ARRAY_LENGTH(kReverseRoles); ++i) { - (*role_name_vector)[kReverseRoles[i].webcore_role] = - AtomicString(kReverseRoles[i].aria_role); - } - - return role_name_vector; -} - -static Vector<AtomicString>* CreateInternalRoleNameVector() { - Vector<AtomicString>* internal_role_name_vector = - new Vector<AtomicString>(kNumRoles); - for (size_t i = 0; i < WTF_ARRAY_LENGTH(kInternalRoles); i++) { - (*internal_role_name_vector)[kInternalRoles[i].webcore_role] = - AtomicString(kInternalRoles[i].internal_role_name); - } - - return internal_role_name_vector; -} - -HTMLDialogElement* GetActiveDialogElement(Node* node) { - return node->GetDocument().ActiveModalDialog(); -} - -} // namespace - -unsigned AXObjectImpl::number_of_live_ax_objects_ = 0; - -AXObjectImpl::AXObjectImpl(AXObjectCacheImpl& ax_object_cache) - : id_(0), - have_children_(false), - role_(kUnknownRole), - last_known_is_ignored_value_(kDefaultBehavior), - explicit_container_id_(0), - parent_(nullptr), - last_modification_count_(-1), - cached_is_ignored_(false), - cached_is_inert_or_aria_hidden_(false), - cached_is_descendant_of_leaf_node_(false), - cached_is_descendant_of_disabled_node_(false), - cached_has_inherited_presentational_role_(false), - cached_is_presentational_child_(false), - cached_ancestor_exposes_active_descendant_(false), - cached_live_region_root_(nullptr), - ax_object_cache_(&ax_object_cache) { - ++number_of_live_ax_objects_; -} - -AXObjectImpl::~AXObjectImpl() { - DCHECK(IsDetached()); - --number_of_live_ax_objects_; -} - -void AXObjectImpl::Detach() { - // Clear any children and call detachFromParent on them so that - // no children are left with dangling pointers to their parent. - ClearChildren(); - - ax_object_cache_ = nullptr; -} - -bool AXObjectImpl::IsDetached() const { - return !ax_object_cache_; -} - -const AtomicString& AXObjectImpl::GetAOMPropertyOrARIAAttribute( - AOMStringProperty property) const { - if (Element* element = this->GetElement()) - return AccessibleNode::GetPropertyOrARIAAttribute(element, property); - return g_null_atom; -} - -bool AXObjectImpl::HasAOMPropertyOrARIAAttribute(AOMBooleanProperty property, - bool& result) const { - Element* element = this->GetElement(); - if (!element) - return false; - - bool is_null = true; - result = - AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); - return !is_null; -} - -bool AXObjectImpl::AOMPropertyOrARIAAttributeIsTrue( - AOMBooleanProperty property) const { - bool result; - if (HasAOMPropertyOrARIAAttribute(property, result)) - return result; - return false; -} - -bool AXObjectImpl::AOMPropertyOrARIAAttributeIsFalse( - AOMBooleanProperty property) const { - bool result; - if (HasAOMPropertyOrARIAAttribute(property, result)) - return !result; - return false; -} - -bool AXObjectImpl::HasAOMPropertyOrARIAAttribute(AOMUIntProperty property, - uint32_t& result) const { - Element* element = this->GetElement(); - if (!element) - return false; - - bool is_null = true; - result = - AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); - return !is_null; -} - -bool AXObjectImpl::HasAOMPropertyOrARIAAttribute(AOMIntProperty property, - int32_t& result) const { - Element* element = this->GetElement(); - if (!element) - return false; - - bool is_null = true; - result = - AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); - return !is_null; -} - -bool AXObjectImpl::HasAOMPropertyOrARIAAttribute(AOMFloatProperty property, - float& result) const { - Element* element = this->GetElement(); - if (!element) - return false; - - bool is_null = true; - result = - AccessibleNode::GetPropertyOrARIAAttribute(element, property, is_null); - return !is_null; -} - -bool AXObjectImpl::IsARIATextControl() const { - return AriaRoleAttribute() == kTextFieldRole || - AriaRoleAttribute() == kSearchBoxRole || - AriaRoleAttribute() == kComboBoxRole; -} - -bool AXObjectImpl::IsButton() const { - AccessibilityRole role = RoleValue(); - - return role == kButtonRole || role == kPopUpButtonRole || - role == kToggleButtonRole; -} - -bool AXObjectImpl::IsCheckable() const { - switch (RoleValue()) { - case kCheckBoxRole: - case kMenuItemCheckBoxRole: - case kMenuItemRadioRole: - case kRadioButtonRole: - case kSwitchRole: - case kToggleButtonRole: - return true; - case kTreeItemRole: - case kListBoxOptionRole: - case kMenuListOptionRole: - return AriaCheckedIsPresent(); - default: - return false; - } -} - -// Why this is here instead of AXNodeObject: -// Because an AXMenuListOption (<option>) can -// have an ARIA role of menuitemcheckbox/menuitemradio -// yet does not inherit from AXNodeObject -AccessibilityCheckedState AXObjectImpl::CheckedState() const { - if (!IsCheckable()) - return kCheckedStateUndefined; - - // Try ARIA checked/pressed state - const AccessibilityRole role = RoleValue(); - const auto prop = role == kToggleButtonRole ? AOMStringProperty::kPressed - : AOMStringProperty::kChecked; - const AtomicString& checked_attribute = GetAOMPropertyOrARIAAttribute(prop); - if (checked_attribute) { - if (EqualIgnoringASCIICase(checked_attribute, "true")) - return kCheckedStateTrue; - - if (EqualIgnoringASCIICase(checked_attribute, "mixed")) { - // Only checkable role that doesn't support mixed is the switch. - if (role != kSwitchRole) - return kCheckedStateMixed; - } - - if (EqualIgnoringASCIICase(checked_attribute, "false")) - return kCheckedStateFalse; - } - - // Native checked state - if (role != kToggleButtonRole) { - const Node* node = this->GetNode(); - if (!node) - return kCheckedStateUndefined; - - if (IsNativeInputInMixedState(node)) - return kCheckedStateMixed; - - if (isHTMLInputElement(*node) && - toHTMLInputElement(*node).ShouldAppearChecked()) { - return kCheckedStateTrue; - } - } - - return kCheckedStateFalse; -} - -bool AXObjectImpl::IsNativeInputInMixedState(const Node* node) { - if (!isHTMLInputElement(node)) - return false; - - const HTMLInputElement* input = toHTMLInputElement(node); - const auto inputType = input->type(); - if (inputType != InputTypeNames::checkbox && - inputType != InputTypeNames::radio) - return false; - return input->ShouldAppearIndeterminate(); -} - -bool AXObjectImpl::IsLandmarkRelated() const { - switch (RoleValue()) { - case kApplicationRole: - case kArticleRole: - case kBannerRole: - case kComplementaryRole: - case kContentInfoRole: - case kFooterRole: - case kFormRole: - case kMainRole: - case kNavigationRole: - case kRegionRole: - case kSearchRole: - return true; - default: - return false; - } -} - -bool AXObjectImpl::IsMenuRelated() const { - switch (RoleValue()) { - case kMenuRole: - case kMenuBarRole: - case kMenuButtonRole: - case kMenuItemRole: - case kMenuItemCheckBoxRole: - case kMenuItemRadioRole: - return true; - default: - return false; - } -} - -bool AXObjectImpl::IsPasswordFieldAndShouldHideValue() const { - Settings* settings = GetDocument()->GetSettings(); - if (!settings || settings->GetAccessibilityPasswordValuesEnabled()) - return false; - - return IsPasswordField(); -} - -bool AXObjectImpl::IsClickable() const { - switch (RoleValue()) { - case kButtonRole: - case kCheckBoxRole: - case kColorWellRole: - case kComboBoxRole: - case kImageMapLinkRole: - case kLinkRole: - case kListBoxOptionRole: - case kMenuButtonRole: - case kPopUpButtonRole: - case kRadioButtonRole: - case kSpinButtonRole: - case kTabRole: - case kTextFieldRole: - case kToggleButtonRole: - return true; - default: - return false; - } -} - -bool AXObjectImpl::AccessibilityIsIgnored() { - Node* node = GetNode(); - if (!node) { - AXObjectImpl* parent = this->ParentObject(); - while (!node && parent) { - node = parent->GetNode(); - parent = parent->ParentObject(); - } - } - - if (node) - node->UpdateDistribution(); - - // TODO(aboxhall): Instead of this, propagate inert down through frames - Document* document = GetDocument(); - while (document && document->LocalOwner()) { - document->LocalOwner()->UpdateDistribution(); - document = document->LocalOwner()->ownerDocument(); - } - - UpdateCachedAttributeValuesIfNeeded(); - return cached_is_ignored_; -} - -void AXObjectImpl::UpdateCachedAttributeValuesIfNeeded() const { - if (IsDetached()) - return; - - AXObjectCacheImpl& cache = AxObjectCache(); - - if (cache.ModificationCount() == last_modification_count_) - return; - - last_modification_count_ = cache.ModificationCount(); - cached_background_color_ = ComputeBackgroundColor(); - cached_is_inert_or_aria_hidden_ = ComputeIsInertOrAriaHidden(); - cached_is_descendant_of_leaf_node_ = (LeafNodeAncestor() != 0); - cached_is_descendant_of_disabled_node_ = (DisabledAncestor() != 0); - cached_has_inherited_presentational_role_ = - (InheritsPresentationalRoleFrom() != 0); - cached_is_presentational_child_ = - (AncestorForWhichThisIsAPresentationalChild() != 0); - cached_is_ignored_ = ComputeAccessibilityIsIgnored(); - cached_live_region_root_ = - IsLiveRegion() - ? const_cast<AXObjectImpl*>(this) - : (ParentObjectIfExists() ? ParentObjectIfExists()->LiveRegionRoot() - : 0); - cached_ancestor_exposes_active_descendant_ = - ComputeAncestorExposesActiveDescendant(); -} - -bool AXObjectImpl::AccessibilityIsIgnoredByDefault( - IgnoredReasons* ignored_reasons) const { - return DefaultObjectInclusion(ignored_reasons) == kIgnoreObject; -} - -AXObjectInclusion AXObjectImpl::AccessibilityPlatformIncludesObject() const { - if (IsMenuListPopup() || IsMenuListOption()) - return kIncludeObject; - - return kDefaultBehavior; -} - -AXObjectInclusion AXObjectImpl::DefaultObjectInclusion( - IgnoredReasons* ignored_reasons) const { - if (IsInertOrAriaHidden()) { - if (ignored_reasons) - ComputeIsInertOrAriaHidden(ignored_reasons); - return kIgnoreObject; - } - - if (IsPresentationalChild()) { - if (ignored_reasons) { - AXObjectImpl* ancestor = AncestorForWhichThisIsAPresentationalChild(); - ignored_reasons->push_back( - IgnoredReason(kAXAncestorDisallowsChild, ancestor)); - } - return kIgnoreObject; - } - - return AccessibilityPlatformIncludesObject(); -} - -bool AXObjectImpl::IsInertOrAriaHidden() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_is_inert_or_aria_hidden_; -} - -bool AXObjectImpl::ComputeIsInertOrAriaHidden( - IgnoredReasons* ignored_reasons) const { - if (GetNode()) { - if (GetNode()->IsInert()) { - if (ignored_reasons) { - HTMLDialogElement* dialog = GetActiveDialogElement(GetNode()); - if (dialog) { - AXObjectImpl* dialog_object = AxObjectCache().GetOrCreate(dialog); - if (dialog_object) { - ignored_reasons->push_back( - IgnoredReason(kAXActiveModalDialog, dialog_object)); - } else { - ignored_reasons->push_back(IgnoredReason(kAXInertElement)); - } - } else { - const AXObjectImpl* inert_root_el = InertRoot(); - if (inert_root_el == this) { - ignored_reasons->push_back(IgnoredReason(kAXInertElement)); - } else { - ignored_reasons->push_back( - IgnoredReason(kAXInertSubtree, inert_root_el)); - } - } - } - return true; - } - } else { - AXObjectImpl* parent = ParentObject(); - if (parent && parent->IsInertOrAriaHidden()) { - if (ignored_reasons) - parent->ComputeIsInertOrAriaHidden(ignored_reasons); - return true; - } - } - - const AXObjectImpl* hidden_root = AriaHiddenRoot(); - if (hidden_root) { - if (ignored_reasons) { - if (hidden_root == this) { - ignored_reasons->push_back(IgnoredReason(kAXAriaHiddenElement)); - } else { - ignored_reasons->push_back( - IgnoredReason(kAXAriaHiddenSubtree, hidden_root)); - } - } - return true; - } - - return false; -} - -bool AXObjectImpl::IsDescendantOfLeafNode() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_is_descendant_of_leaf_node_; -} - -AXObjectImpl* AXObjectImpl::LeafNodeAncestor() const { - if (AXObjectImpl* parent = ParentObject()) { - if (!parent->CanHaveChildren()) - return parent; - - return parent->LeafNodeAncestor(); - } - - return 0; -} - -const AXObjectImpl* AXObjectImpl::AriaHiddenRoot() const { - for (const AXObjectImpl* object = this; object; - object = object->ParentObject()) { - if (object->AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kHidden)) - return object; - } - - return 0; -} - -const AXObjectImpl* AXObjectImpl::InertRoot() const { - const AXObjectImpl* object = this; - if (!RuntimeEnabledFeatures::InertAttributeEnabled()) - return 0; - - while (object && !object->IsAXNodeObject()) - object = object->ParentObject(); - Node* node = object->GetNode(); - Element* element = node->IsElementNode() - ? ToElement(node) - : FlatTreeTraversal::ParentElement(*node); - while (element) { - if (element->hasAttribute(inertAttr)) - return AxObjectCache().GetOrCreate(element); - element = FlatTreeTraversal::ParentElement(*element); - } - - return 0; -} - -bool AXObjectImpl::IsDescendantOfDisabledNode() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_is_descendant_of_disabled_node_; -} - -const AXObjectImpl* AXObjectImpl::DisabledAncestor() const { - bool disabled = false; - if (HasAOMPropertyOrARIAAttribute(AOMBooleanProperty::kDisabled, disabled)) { - if (disabled) - return this; - return nullptr; - } - - if (AXObjectImpl* parent = ParentObject()) - return parent->DisabledAncestor(); - - return nullptr; -} - -bool AXObjectImpl::LastKnownIsIgnoredValue() { - if (last_known_is_ignored_value_ == kDefaultBehavior) { - last_known_is_ignored_value_ = - AccessibilityIsIgnored() ? kIgnoreObject : kIncludeObject; - } - - return last_known_is_ignored_value_ == kIgnoreObject; -} - -void AXObjectImpl::SetLastKnownIsIgnoredValue(bool is_ignored) { - last_known_is_ignored_value_ = is_ignored ? kIgnoreObject : kIncludeObject; -} - -bool AXObjectImpl::HasInheritedPresentationalRole() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_has_inherited_presentational_role_; -} - -bool AXObjectImpl::IsPresentationalChild() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_is_presentational_child_; -} - -bool AXObjectImpl::CanReceiveAccessibilityFocus() const { - const Element* elem = GetElement(); - if (!elem) - return false; - - // Focusable, and not forwarding the focus somewhere else - if (elem->IsFocusable() && !elem->FastHasAttribute(aria_activedescendantAttr)) - return true; - - // aria-activedescendant focus - return elem->FastHasAttribute(idAttr) && AncestorExposesActiveDescendant(); -} - -bool AXObjectImpl::AncestorExposesActiveDescendant() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_ancestor_exposes_active_descendant_; -} - -bool AXObjectImpl::ComputeAncestorExposesActiveDescendant() const { - const AXObjectImpl* parent = ParentObjectUnignored(); - if (!parent) - return false; - - if (parent->SupportsActiveDescendant() && - parent->HasAttribute(aria_activedescendantAttr)) { - return true; - } - - return parent->AncestorExposesActiveDescendant(); -} - -// Simplify whitespace, but preserve a single leading and trailing whitespace -// character if it's present. -// static -String AXObjectImpl::CollapseWhitespace(const String& str) { - StringBuilder result; - if (!str.IsEmpty() && IsHTMLSpace<UChar>(str[0])) - result.Append(' '); - result.Append(str.SimplifyWhiteSpace(IsHTMLSpace<UChar>)); - if (!str.IsEmpty() && IsHTMLSpace<UChar>(str[str.length() - 1])) - result.Append(' '); - return result.ToString(); -} - -String AXObjectImpl::ComputedName() const { - AXNameFrom name_from; - AXObjectImpl::AXObjectVector name_objects; - return GetName(name_from, &name_objects); -} - -String AXObjectImpl::GetName(AXNameFrom& name_from, - AXObjectImpl::AXObjectVector* name_objects) const { - HeapHashSet<Member<const AXObjectImpl>> visited; - AXRelatedObjectVector related_objects; - String text = TextAlternative(false, false, visited, name_from, - &related_objects, nullptr); - - AccessibilityRole role = RoleValue(); - if (!GetNode() || (!isHTMLBRElement(GetNode()) && role != kStaticTextRole && - role != kInlineTextBoxRole)) - text = CollapseWhitespace(text); - - if (name_objects) { - name_objects->clear(); - for (size_t i = 0; i < related_objects.size(); i++) - name_objects->push_back(related_objects[i]->object); - } - - return text; -} - -String AXObjectImpl::GetName(NameSources* name_sources) const { - AXObjectSet visited; - AXNameFrom tmp_name_from; - AXRelatedObjectVector tmp_related_objects; - String text = TextAlternative(false, false, visited, tmp_name_from, - &tmp_related_objects, name_sources); - text = text.SimplifyWhiteSpace(IsHTMLSpace<UChar>); - return text; -} - -String AXObjectImpl::RecursiveTextAlternative( - const AXObjectImpl& ax_obj, - bool in_aria_labelled_by_traversal, - AXObjectSet& visited) { - if (visited.Contains(&ax_obj) && !in_aria_labelled_by_traversal) - return String(); - - AXNameFrom tmp_name_from; - return ax_obj.TextAlternative(true, in_aria_labelled_by_traversal, visited, - tmp_name_from, nullptr, nullptr); -} - -bool AXObjectImpl::IsHiddenForTextAlternativeCalculation() const { - if (AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty::kHidden)) - return false; - - if (GetLayoutObject()) - return GetLayoutObject()->Style()->Visibility() != EVisibility::kVisible; - - // This is an obscure corner case: if a node has no LayoutObject, that means - // it's not rendered, but we still may be exploring it as part of a text - // alternative calculation, for example if it was explicitly referenced by - // aria-labelledby. So we need to explicitly call the style resolver to check - // whether it's invisible or display:none, rather than relying on the style - // cached in the LayoutObject. - Document* document = GetDocument(); - if (!document || !document->GetFrame()) - return false; - if (Node* node = GetNode()) { - if (node->isConnected() && node->IsElementNode()) { - RefPtr<ComputedStyle> style = - document->EnsureStyleResolver().StyleForElement(ToElement(node)); - return style->Display() == EDisplay::kNone || - style->Visibility() != EVisibility::kVisible; - } - } - return false; -} - -String AXObjectImpl::AriaTextAlternative(bool recursive, - bool in_aria_labelled_by_traversal, - AXObjectSet& visited, - AXNameFrom& name_from, - AXRelatedObjectVector* related_objects, - NameSources* name_sources, - bool* found_text_alternative) const { - String text_alternative; - bool already_visited = visited.Contains(this); - visited.insert(this); - - // Step 2A from: http://www.w3.org/TR/accname-aam-1.1 - // If you change this logic, update AXNodeObject::nameFromLabelElement, too. - if (!in_aria_labelled_by_traversal && - IsHiddenForTextAlternativeCalculation()) { - *found_text_alternative = true; - return String(); - } - - // Step 2B from: http://www.w3.org/TR/accname-aam-1.1 - // If you change this logic, update AXNodeObject::nameFromLabelElement, too. - if (!in_aria_labelled_by_traversal && !already_visited) { - const QualifiedName& attr = - HasAttribute(aria_labeledbyAttr) && !HasAttribute(aria_labelledbyAttr) - ? aria_labeledbyAttr - : aria_labelledbyAttr; - name_from = kAXNameFromRelatedElement; - if (name_sources) { - name_sources->push_back(NameSource(*found_text_alternative, attr)); - name_sources->back().type = name_from; - } - - const AtomicString& aria_labelledby = GetAttribute(attr); - if (!aria_labelledby.IsNull()) { - if (name_sources) - name_sources->back().attribute_value = aria_labelledby; - - // Operate on a copy of |visited| so that if |nameSources| is not null, - // the set of visited objects is preserved unmodified for future - // calculations. - AXObjectSet visited_copy = visited; - text_alternative = TextFromAriaLabelledby(visited_copy, related_objects); - if (!text_alternative.IsNull()) { - if (name_sources) { - NameSource& source = name_sources->back(); - source.type = name_from; - source.related_objects = *related_objects; - source.text = text_alternative; - *found_text_alternative = true; - } else { - *found_text_alternative = true; - return text_alternative; - } - } else if (name_sources) { - name_sources->back().invalid = true; - } - } - } - - // Step 2C from: http://www.w3.org/TR/accname-aam-1.1 - // If you change this logic, update AXNodeObject::nameFromLabelElement, too. - name_from = kAXNameFromAttribute; - if (name_sources) { - name_sources->push_back( - NameSource(*found_text_alternative, aria_labelAttr)); - name_sources->back().type = name_from; - } - const AtomicString& aria_label = - GetAOMPropertyOrARIAAttribute(AOMStringProperty::kLabel); - if (!aria_label.IsEmpty()) { - text_alternative = aria_label; - - if (name_sources) { - NameSource& source = name_sources->back(); - source.text = text_alternative; - source.attribute_value = aria_label; - *found_text_alternative = true; - } else { - *found_text_alternative = true; - return text_alternative; - } - } - - return text_alternative; -} - -String AXObjectImpl::TextFromElements( - bool in_aria_labelledby_traversal, - AXObjectSet& visited, - HeapVector<Member<Element>>& elements, - AXRelatedObjectVector* related_objects) const { - StringBuilder accumulated_text; - bool found_valid_element = false; - AXRelatedObjectVector local_related_objects; - - for (const auto& element : elements) { - AXObjectImpl* ax_element = AxObjectCache().GetOrCreate(element); - if (ax_element) { - found_valid_element = true; - - String result = RecursiveTextAlternative( - *ax_element, in_aria_labelledby_traversal, visited); - local_related_objects.push_back( - new NameSourceRelatedObject(ax_element, result)); - if (!result.IsEmpty()) { - if (!accumulated_text.IsEmpty()) - accumulated_text.Append(' '); - accumulated_text.Append(result); - } - } - } - if (!found_valid_element) - return String(); - if (related_objects) - *related_objects = local_related_objects; - return accumulated_text.ToString(); -} - -void AXObjectImpl::TokenVectorFromAttribute( - Vector<String>& tokens, - const QualifiedName& attribute) const { - Node* node = this->GetNode(); - if (!node || !node->IsElementNode()) - return; - - String attribute_value = GetAttribute(attribute).GetString(); - if (attribute_value.IsEmpty()) - return; - - attribute_value.SimplifyWhiteSpace(); - attribute_value.Split(' ', tokens); -} - -void AXObjectImpl::ElementsFromAttribute(HeapVector<Member<Element>>& elements, - const QualifiedName& attribute) const { - Vector<String> ids; - TokenVectorFromAttribute(ids, attribute); - if (ids.IsEmpty()) - return; - - TreeScope& scope = GetNode()->GetTreeScope(); - for (const auto& id : ids) { - if (Element* id_element = scope.getElementById(AtomicString(id))) - elements.push_back(id_element); - } -} - -void AXObjectImpl::AriaLabelledbyElementVector( - HeapVector<Member<Element>>& elements) const { - // Try both spellings, but prefer aria-labelledby, which is the official spec. - ElementsFromAttribute(elements, aria_labelledbyAttr); - if (!elements.size()) - ElementsFromAttribute(elements, aria_labeledbyAttr); -} - -String AXObjectImpl::TextFromAriaLabelledby( - AXObjectSet& visited, - AXRelatedObjectVector* related_objects) const { - HeapVector<Member<Element>> elements; - AriaLabelledbyElementVector(elements); - return TextFromElements(true, visited, elements, related_objects); -} - -String AXObjectImpl::TextFromAriaDescribedby( - AXRelatedObjectVector* related_objects) const { - AXObjectSet visited; - HeapVector<Member<Element>> elements; - ElementsFromAttribute(elements, aria_describedbyAttr); - return TextFromElements(true, visited, elements, related_objects); -} - -RGBA32 AXObjectImpl::BackgroundColor() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_background_color_; -} - -AccessibilityOrientation AXObjectImpl::Orientation() const { - // In ARIA 1.1, the default value for aria-orientation changed from - // horizontal to undefined. - return kAccessibilityOrientationUndefined; -} - -AXDefaultActionVerb AXObjectImpl::Action() const { - if (!ActionElement()) - return AXDefaultActionVerb::kNone; - - switch (RoleValue()) { - case kButtonRole: - case kToggleButtonRole: - return AXDefaultActionVerb::kPress; - case kTextFieldRole: - return AXDefaultActionVerb::kActivate; - case kMenuItemRadioRole: - case kRadioButtonRole: - return AXDefaultActionVerb::kSelect; - case kLinkRole: - return AXDefaultActionVerb::kJump; - case kPopUpButtonRole: - return AXDefaultActionVerb::kOpen; - default: - if (IsCheckable()) { - return CheckedState() != kCheckedStateTrue - ? AXDefaultActionVerb::kCheck - : AXDefaultActionVerb::kUncheck; - } - return AXDefaultActionVerb::kClick; - } -} - -bool AXObjectImpl::IsMultiline() const { - Node* node = this->GetNode(); - if (!node) - return false; - - if (isHTMLTextAreaElement(*node)) - return true; - - if (HasEditableStyle(*node)) - return true; - - if (!IsNativeTextControl() && !IsNonNativeTextControl()) - return false; - - return AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty::kMultiline); -} - -bool AXObjectImpl::AriaPressedIsPresent() const { - return !GetAttribute(aria_pressedAttr).IsEmpty(); -} - -bool AXObjectImpl::AriaCheckedIsPresent() const { - return !GetAttribute(aria_checkedAttr).IsEmpty(); -} - -bool AXObjectImpl::SupportsActiveDescendant() const { - // According to the ARIA Spec, all ARIA composite widgets, ARIA text boxes - // and ARIA groups should be able to expose an active descendant. - // Implicitly, <input> and <textarea> elements should also have this ability. - switch (AriaRoleAttribute()) { - case kComboBoxRole: - case kGridRole: - case kGroupRole: - case kListBoxRole: - case kMenuRole: - case kMenuBarRole: - case kRadioGroupRole: - case kRowRole: - case kSearchBoxRole: - case kTabListRole: - case kTextFieldRole: - case kToolbarRole: - case kTreeRole: - case kTreeGridRole: - return true; - default: - return false; - } -} - -bool AXObjectImpl::SupportsARIAAttributes() const { - return IsLiveRegion() || SupportsARIADragging() || SupportsARIADropping() || - SupportsARIAFlowTo() || SupportsARIAOwns() || - HasAttribute(aria_labelAttr) || HasAttribute(aria_currentAttr); -} - -bool AXObjectImpl::SupportsRangeValue() const { - return IsProgressIndicator() || IsMeter() || IsSlider() || IsScrollbar() || - IsSpinButton() || IsMoveableSplitter(); -} - -bool AXObjectImpl::SupportsSetSizeAndPosInSet() const { - AXObjectImpl* parent = ParentObjectUnignored(); - if (!parent) - return false; - - int role = RoleValue(); - int parent_role = parent->RoleValue(); - - if ((role == kListBoxOptionRole && parent_role == kListBoxRole) || - (role == kListItemRole && parent_role == kListRole) || - (role == kMenuItemRole && parent_role == kMenuRole) || - (role == kRadioButtonRole) || - (role == kTabRole && parent_role == kTabListRole) || - (role == kTreeItemRole && parent_role == kTreeRole) || - (role == kTreeItemRole && parent_role == kTreeItemRole)) { - return true; - } - - return false; -} - -int AXObjectImpl::IndexInParent() const { - if (!ParentObject()) - return 0; - - const auto& siblings = ParentObject()->Children(); - int child_count = siblings.size(); - - for (int index = 0; index < child_count; ++index) { - if (siblings[index].Get() == this) { - return index; - } - } - return 0; -} - -bool AXObjectImpl::IsLiveRegion() const { - const AtomicString& live_region = LiveRegionStatus(); - return EqualIgnoringASCIICase(live_region, "polite") || - EqualIgnoringASCIICase(live_region, "assertive"); -} - -AXObjectImpl* AXObjectImpl::LiveRegionRoot() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_live_region_root_; -} - -const AtomicString& AXObjectImpl::ContainerLiveRegionStatus() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_live_region_root_ ? cached_live_region_root_->LiveRegionStatus() - : g_null_atom; -} - -const AtomicString& AXObjectImpl::ContainerLiveRegionRelevant() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_live_region_root_ - ? cached_live_region_root_->LiveRegionRelevant() - : g_null_atom; -} - -bool AXObjectImpl::ContainerLiveRegionAtomic() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_live_region_root_ && - cached_live_region_root_->LiveRegionAtomic(); -} - -bool AXObjectImpl::ContainerLiveRegionBusy() const { - UpdateCachedAttributeValuesIfNeeded(); - return cached_live_region_root_ && cached_live_region_root_->LiveRegionBusy(); -} - -AXObjectImpl* AXObjectImpl::ElementAccessibilityHitTest( - const IntPoint& point) const { - // Check if there are any mock elements that need to be handled. - for (const auto& child : children_) { - if (child->IsMockObject() && - child->GetBoundsInFrameCoordinates().Contains(point)) - return child->ElementAccessibilityHitTest(point); - } - - return const_cast<AXObjectImpl*>(this); -} - -const AXObjectImpl::AXObjectVector& AXObjectImpl::Children() { - UpdateChildrenIfNecessary(); - - return children_; -} - -AXObjectImpl* AXObjectImpl::ParentObject() const { - if (IsDetached()) - return 0; - - if (parent_) - return parent_; - - if (AxObjectCache().IsAriaOwned(this)) - return AxObjectCache().GetAriaOwnedParent(this); - - return ComputeParent(); -} - -AXObjectImpl* AXObjectImpl::ParentObjectIfExists() const { - if (IsDetached()) - return 0; - - if (parent_) - return parent_; - - return ComputeParentIfExists(); -} - -AXObjectImpl* AXObjectImpl::ParentObjectUnignored() const { - AXObjectImpl* parent; - for (parent = ParentObject(); parent && parent->AccessibilityIsIgnored(); - parent = parent->ParentObject()) { - } - - return parent; -} - -// Container widgets are those that a user tabs into and arrows around -// sub-widgets -bool AXObjectImpl::IsContainerWidget() const { - switch (RoleValue()) { - case kComboBoxRole: - case kGridRole: - case kListBoxRole: - case kMenuBarRole: - case kMenuRole: - case kRadioGroupRole: - case kSpinButtonRole: - case kTabListRole: - case kToolbarRole: - case kTreeGridRole: - case kTreeRole: - return true; - default: - return false; - } -} - -AXObjectImpl* AXObjectImpl::ContainerWidget() const { - AXObjectImpl* ancestor = ParentObjectUnignored(); - while (ancestor && !ancestor->IsContainerWidget()) - ancestor = ancestor->ParentObjectUnignored(); - - return ancestor; -} - -void AXObjectImpl::UpdateChildrenIfNecessary() { - if (!HasChildren()) - AddChildren(); -} - -void AXObjectImpl::ClearChildren() { - // Detach all weak pointers from objects to their parents. - for (const auto& child : children_) - child->DetachFromParent(); - - children_.clear(); - have_children_ = false; -} - -Element* AXObjectImpl::GetElement() const { - Node* node = GetNode(); - return node && node->IsElementNode() ? ToElement(node) : nullptr; -} - -Document* AXObjectImpl::GetDocument() const { - LocalFrameView* frame_view = DocumentFrameView(); - if (!frame_view) - return 0; - - return frame_view->GetFrame().GetDocument(); -} - -LocalFrameView* AXObjectImpl::DocumentFrameView() const { - const AXObjectImpl* object = this; - while (object && !object->IsAXLayoutObject()) - object = object->ParentObject(); - - if (!object) - return 0; - - return object->DocumentFrameView(); -} - -String AXObjectImpl::Language() const { - const AtomicString& lang = GetAttribute(langAttr); - if (!lang.IsEmpty()) - return lang; - - AXObjectImpl* parent = ParentObject(); - - // As a last resort, fall back to the content language specified in the meta - // tag. - if (!parent) { - Document* doc = GetDocument(); - if (doc) - return doc->ContentLanguage(); - return g_null_atom; - } - - return parent->Language(); -} - -bool AXObjectImpl::HasAttribute(const QualifiedName& attribute) const { - if (Element* element = GetElement()) - return element->FastHasAttribute(attribute); - return false; -} - -const AtomicString& AXObjectImpl::GetAttribute( - const QualifiedName& attribute) const { - if (Element* element = GetElement()) - return element->FastGetAttribute(attribute); - return g_null_atom; -} - -// -// Scrollable containers. -// - -bool AXObjectImpl::IsScrollableContainer() const { - return !!GetScrollableAreaIfScrollable(); -} - -IntPoint AXObjectImpl::GetScrollOffset() const { - ScrollableArea* area = GetScrollableAreaIfScrollable(); - if (!area) - return IntPoint(); - - return IntPoint(area->ScrollOffsetInt().Width(), - area->ScrollOffsetInt().Height()); -} - -IntPoint AXObjectImpl::MinimumScrollOffset() const { - ScrollableArea* area = GetScrollableAreaIfScrollable(); - if (!area) - return IntPoint(); - - return IntPoint(area->MinimumScrollOffsetInt().Width(), - area->MinimumScrollOffsetInt().Height()); -} - -IntPoint AXObjectImpl::MaximumScrollOffset() const { - ScrollableArea* area = GetScrollableAreaIfScrollable(); - if (!area) - return IntPoint(); - - return IntPoint(area->MaximumScrollOffsetInt().Width(), - area->MaximumScrollOffsetInt().Height()); -} - -void AXObjectImpl::SetScrollOffset(const IntPoint& offset) const { - ScrollableArea* area = GetScrollableAreaIfScrollable(); - if (!area) - return; - - // TODO(bokan): This should potentially be a UserScroll. - area->SetScrollOffset(ScrollOffset(offset.X(), offset.Y()), - kProgrammaticScroll); -} - -void AXObjectImpl::GetRelativeBounds( - AXObjectImpl** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { - *out_container = nullptr; - out_bounds_in_container = FloatRect(); - out_container_transform.setIdentity(); - - // First check if it has explicit bounds, for example if this element is tied - // to a canvas path. When explicit coordinates are provided, the ID of the - // explicit container element that the coordinates are relative to must be - // provided too. - if (!explicit_element_rect_.IsEmpty()) { - *out_container = AxObjectCache().ObjectFromAXID(explicit_container_id_); - if (*out_container) { - out_bounds_in_container = FloatRect(explicit_element_rect_); - return; - } - } - - LayoutObject* layout_object = LayoutObjectForRelativeBounds(); - if (!layout_object) - return; - - if (IsWebArea()) { - if (layout_object->GetFrame()->View()) { - out_bounds_in_container.SetSize( - FloatSize(layout_object->GetFrame()->View()->ContentsSize())); - } - return; - } - - // First compute the container. The container must be an ancestor in the - // accessibility tree, and its LayoutObject must be an ancestor in the layout - // tree. Get the first such ancestor that's either scrollable or has a paint - // layer. - AXObjectImpl* container = ParentObjectUnignored(); - LayoutObject* container_layout_object = nullptr; - while (container) { - container_layout_object = container->GetLayoutObject(); - if (container_layout_object && - container_layout_object->IsBoxModelObject() && - layout_object->IsDescendantOf(container_layout_object)) { - if (container->IsScrollableContainer() || - container_layout_object->HasLayer()) - break; - } - - container = container->ParentObjectUnignored(); - } - - if (!container) - return; - *out_container = container; - out_bounds_in_container = - layout_object->LocalBoundingBoxRectForAccessibility(); - - // If the container has a scroll offset, subtract that out because we want our - // bounds to be relative to the *unscrolled* position of the container object. - ScrollableArea* scrollable_area = container->GetScrollableAreaIfScrollable(); - if (scrollable_area && !container->IsWebArea()) { - ScrollOffset scroll_offset = scrollable_area->GetScrollOffset(); - out_bounds_in_container.Move(scroll_offset); - } - - // Compute the transform between the container's coordinate space and this - // object. If the transform is just a simple translation, apply that to the - // bounding box, but if it's a non-trivial transformation like a rotation, - // scaling, etc. then return the full matrix instead. - TransformationMatrix transform = layout_object->LocalToAncestorTransform( - ToLayoutBoxModelObject(container_layout_object)); - if (transform.IsIdentityOr2DTranslation()) { - out_bounds_in_container.Move(transform.To2DTranslation()); - } else { - out_container_transform = TransformationMatrix::ToSkMatrix44(transform); - } -} - -LayoutRect AXObjectImpl::GetBoundsInFrameCoordinates() const { - AXObjectImpl* container = nullptr; - FloatRect bounds; - SkMatrix44 transform; - GetRelativeBounds(&container, bounds, transform); - FloatRect computed_bounds(0, 0, bounds.Width(), bounds.Height()); - while (container && container != this) { - computed_bounds.Move(bounds.X(), bounds.Y()); - if (!container->IsWebArea()) { - computed_bounds.Move(-container->GetScrollOffset().X(), - -container->GetScrollOffset().Y()); - } - if (!transform.isIdentity()) { - TransformationMatrix transformation_matrix(transform); - transformation_matrix.MapRect(computed_bounds); - } - container->GetRelativeBounds(&container, bounds, transform); - } - return LayoutRect(computed_bounds); -} - -// -// Modify or take an action on an object. -// - -bool AXObjectImpl::Press() { - Document* document = GetDocument(); - if (!document) - return false; - - UserGestureIndicator gesture_indicator( - UserGestureToken::Create(document, UserGestureToken::kNewGesture)); - Element* action_elem = ActionElement(); - if (action_elem) { - action_elem->AccessKeyAction(true); - return true; - } - - if (CanSetFocusAttribute()) { - SetFocused(true); - return true; - } - - return false; -} - -void AXObjectImpl::ScrollToMakeVisible() const { - IntRect object_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); - object_rect.SetLocation(IntPoint()); - ScrollToMakeVisibleWithSubFocus(object_rect); -} - -// This is a 1-dimensional scroll offset helper function that's applied -// separately in the horizontal and vertical directions, because the -// logic is the same. The goal is to compute the best scroll offset -// in order to make an object visible within a viewport. -// -// If the object is already fully visible, returns the same scroll -// offset. -// -// In case the whole object cannot fit, you can specify a -// subfocus - a smaller region within the object that should -// be prioritized. If the whole object can fit, the subfocus is -// ignored. -// -// If possible, the object and subfocus are centered within the -// viewport. -// -// Example 1: the object is already visible, so nothing happens. -// +----------Viewport---------+ -// +---Object---+ -// +--SubFocus--+ -// -// Example 2: the object is not fully visible, so it's centered -// within the viewport. -// Before: -// +----------Viewport---------+ -// +---Object---+ -// +--SubFocus--+ -// -// After: -// +----------Viewport---------+ -// +---Object---+ -// +--SubFocus--+ -// -// Example 3: the object is larger than the viewport, so the -// viewport moves to show as much of the object as possible, -// while also trying to center the subfocus. -// Before: -// +----------Viewport---------+ -// +---------------Object--------------+ -// +-SubFocus-+ -// -// After: -// +----------Viewport---------+ -// +---------------Object--------------+ -// +-SubFocus-+ -// -// When constraints cannot be fully satisfied, the min -// (left/top) position takes precedence over the max (right/bottom). -// -// Note that the return value represents the ideal new scroll offset. -// This may be out of range - the calling function should clip this -// to the available range. -static int ComputeBestScrollOffset(int current_scroll_offset, - int subfocus_min, - int subfocus_max, - int object_min, - int object_max, - int viewport_min, - int viewport_max) { - int viewport_size = viewport_max - viewport_min; - - // If the object size is larger than the viewport size, consider - // only a portion that's as large as the viewport, centering on - // the subfocus as much as possible. - if (object_max - object_min > viewport_size) { - // Since it's impossible to fit the whole object in the - // viewport, exit now if the subfocus is already within the viewport. - if (subfocus_min - current_scroll_offset >= viewport_min && - subfocus_max - current_scroll_offset <= viewport_max) - return current_scroll_offset; - - // Subfocus must be within focus. - subfocus_min = std::max(subfocus_min, object_min); - subfocus_max = std::min(subfocus_max, object_max); - - // Subfocus must be no larger than the viewport size; favor top/left. - if (subfocus_max - subfocus_min > viewport_size) - subfocus_max = subfocus_min + viewport_size; - - // Compute the size of an object centered on the subfocus, the size of the - // viewport. - int centered_object_min = (subfocus_min + subfocus_max - viewport_size) / 2; - int centered_object_max = centered_object_min + viewport_size; - - object_min = std::max(object_min, centered_object_min); - object_max = std::min(object_max, centered_object_max); - } - - // Exit now if the focus is already within the viewport. - if (object_min - current_scroll_offset >= viewport_min && - object_max - current_scroll_offset <= viewport_max) - return current_scroll_offset; - - // Center the object in the viewport. - return (object_min + object_max - viewport_min - viewport_max) / 2; -} - -void AXObjectImpl::ScrollToMakeVisibleWithSubFocus( - const IntRect& subfocus) const { - // Search up the parent chain until we find the first one that's scrollable. - const AXObjectImpl* scroll_parent = ParentObject() ? ParentObject() : this; - ScrollableArea* scrollable_area = 0; - while (scroll_parent) { - scrollable_area = scroll_parent->GetScrollableAreaIfScrollable(); - if (scrollable_area) - break; - scroll_parent = scroll_parent->ParentObject(); - } - if (!scroll_parent || !scrollable_area) - return; - - IntRect object_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); - IntSize scroll_offset = scrollable_area->ScrollOffsetInt(); - IntRect scroll_visible_rect = scrollable_area->VisibleContentRect(); - - // Convert the object rect into local coordinates. - if (!scroll_parent->IsWebArea()) { - object_rect.MoveBy(IntPoint(scroll_offset)); - object_rect.MoveBy( - -PixelSnappedIntRect(scroll_parent->GetBoundsInFrameCoordinates()) - .Location()); - } - - int desired_x = ComputeBestScrollOffset( - scroll_offset.Width(), object_rect.X() + subfocus.X(), - object_rect.X() + subfocus.MaxX(), object_rect.X(), object_rect.MaxX(), 0, - scroll_visible_rect.Width()); - int desired_y = ComputeBestScrollOffset( - scroll_offset.Height(), object_rect.Y() + subfocus.Y(), - object_rect.Y() + subfocus.MaxY(), object_rect.Y(), object_rect.MaxY(), 0, - scroll_visible_rect.Height()); - - scroll_parent->SetScrollOffset(IntPoint(desired_x, desired_y)); - - // Convert the subfocus into the coordinates of the scroll parent. - IntRect new_subfocus = subfocus; - IntRect new_element_rect = PixelSnappedIntRect(GetBoundsInFrameCoordinates()); - IntRect scroll_parent_rect = - PixelSnappedIntRect(scroll_parent->GetBoundsInFrameCoordinates()); - new_subfocus.Move(new_element_rect.X(), new_element_rect.Y()); - new_subfocus.Move(-scroll_parent_rect.X(), -scroll_parent_rect.Y()); - - if (scroll_parent->ParentObject()) { - // Recursively make sure the scroll parent itself is visible. - scroll_parent->ScrollToMakeVisibleWithSubFocus(new_subfocus); - } else { - // To minimize the number of notifications, only fire one on the topmost - // object that has been scrolled. - AxObjectCache().PostNotification(const_cast<AXObjectImpl*>(this), - AXObjectCacheImpl::kAXLocationChanged); - } -} - -void AXObjectImpl::ScrollToGlobalPoint(const IntPoint& global_point) const { - // Search up the parent chain and create a vector of all scrollable parent - // objects and ending with this object itself. - HeapVector<Member<const AXObjectImpl>> objects; - AXObjectImpl* parent_object; - for (parent_object = this->ParentObject(); parent_object; - parent_object = parent_object->ParentObject()) { - if (parent_object->GetScrollableAreaIfScrollable()) - objects.push_front(parent_object); - } - objects.push_back(this); - - // Start with the outermost scrollable (the main window) and try to scroll the - // next innermost object to the given point. - int offset_x = 0, offset_y = 0; - IntPoint point = global_point; - size_t levels = objects.size() - 1; - for (size_t i = 0; i < levels; i++) { - const AXObjectImpl* outer = objects[i]; - const AXObjectImpl* inner = objects[i + 1]; - ScrollableArea* scrollable_area = outer->GetScrollableAreaIfScrollable(); - - IntRect inner_rect = - inner->IsWebArea() - ? PixelSnappedIntRect( - inner->ParentObject()->GetBoundsInFrameCoordinates()) - : PixelSnappedIntRect(inner->GetBoundsInFrameCoordinates()); - IntRect object_rect = inner_rect; - IntSize scroll_offset = scrollable_area->ScrollOffsetInt(); - - // Convert the object rect into local coordinates. - object_rect.Move(offset_x, offset_y); - if (!outer->IsWebArea()) - object_rect.Move(scroll_offset.Width(), scroll_offset.Height()); - - int desired_x = ComputeBestScrollOffset( - 0, object_rect.X(), object_rect.MaxX(), object_rect.X(), - object_rect.MaxX(), point.X(), point.X()); - int desired_y = ComputeBestScrollOffset( - 0, object_rect.Y(), object_rect.MaxY(), object_rect.Y(), - object_rect.MaxY(), point.Y(), point.Y()); - outer->SetScrollOffset(IntPoint(desired_x, desired_y)); - - if (outer->IsWebArea() && !inner->IsWebArea()) { - // If outer object we just scrolled is a web area (frame) but the inner - // object is not, keep track of the coordinate transformation to apply to - // future nested calculations. - scroll_offset = scrollable_area->ScrollOffsetInt(); - offset_x -= (scroll_offset.Width() + point.X()); - offset_y -= (scroll_offset.Height() + point.Y()); - point.Move(scroll_offset.Width() - inner_rect.Width(), - scroll_offset.Height() - inner_rect.Y()); - } else if (inner->IsWebArea()) { - // Otherwise, if the inner object is a web area, reset the coordinate - // transformation. - offset_x = 0; - offset_y = 0; - } - } - - // To minimize the number of notifications, only fire one on the topmost - // object that has been scrolled. - DCHECK(objects[0]); - // TODO(nektar): Switch to postNotification(objects[0] and remove |getNode|. - AxObjectCache().PostNotification(objects[0]->GetNode(), - AXObjectCacheImpl::kAXLocationChanged); -} - -void AXObjectImpl::SetSequentialFocusNavigationStartingPoint() { - // Call it on the nearest ancestor that overrides this with a specific - // implementation. - if (ParentObject()) - ParentObject()->SetSequentialFocusNavigationStartingPoint(); -} - -void AXObjectImpl::NotifyIfIgnoredValueChanged() { - bool is_ignored = AccessibilityIsIgnored(); - if (LastKnownIsIgnoredValue() != is_ignored) { - AxObjectCache().ChildrenChanged(ParentObject()); - SetLastKnownIsIgnoredValue(is_ignored); - } -} - -void AXObjectImpl::SelectionChanged() { - if (AXObjectImpl* parent = ParentObjectIfExists()) - parent->SelectionChanged(); -} - -int AXObjectImpl::LineForPosition(const VisiblePosition& position) const { - if (position.IsNull() || !GetNode()) - return -1; - - // If the position is not in the same editable region as this AX object, - // return -1. - Node* container_node = position.DeepEquivalent().ComputeContainerNode(); - if (!container_node->IsShadowIncludingInclusiveAncestorOf(GetNode()) && - !GetNode()->IsShadowIncludingInclusiveAncestorOf(container_node)) - return -1; - - int line_count = -1; - VisiblePosition current_position = position; - VisiblePosition previous_position; - - // Move up until we get to the top. - // FIXME: This only takes us to the top of the rootEditableElement, not the - // top of the top document. - do { - previous_position = current_position; - current_position = PreviousLinePosition(current_position, LayoutUnit(), - kHasEditableAXRole); - ++line_count; - } while (current_position.IsNotNull() && - !InSameLine(current_position, previous_position)); - - return line_count; -} - -bool AXObjectImpl::IsARIAControl(AccessibilityRole aria_role) { - return IsARIAInput(aria_role) || aria_role == kButtonRole || - aria_role == kComboBoxRole || aria_role == kSliderRole; -} - -bool AXObjectImpl::IsARIAInput(AccessibilityRole aria_role) { - return aria_role == kRadioButtonRole || aria_role == kCheckBoxRole || - aria_role == kTextFieldRole || aria_role == kSwitchRole || - aria_role == kSearchBoxRole; -} - -AccessibilityRole AXObjectImpl::AriaRoleToWebCoreRole(const String& value) { - DCHECK(!value.IsEmpty()); - - static const ARIARoleMap* role_map = CreateARIARoleMap(); - - Vector<String> role_vector; - value.Split(' ', role_vector); - AccessibilityRole role = kUnknownRole; - for (const auto& child : role_vector) { - role = role_map->at(child); - if (role) - return role; - } - - return role; -} - -bool AXObjectImpl::NameFromContents(bool recursive) const { - // ARIA 1.1, section 5.2.7.5. - bool result = false; - - switch (RoleValue()) { - // ----- NameFrom: contents ------------------------- - // Get their own name from contents, or contribute to ancestors - case kAnchorRole: - case kButtonRole: - case kCellRole: - case kCheckBoxRole: - case kColumnHeaderRole: - case kDisclosureTriangleRole: - case kHeadingRole: - case kLineBreakRole: - case kLinkRole: - case kListBoxOptionRole: - case kMenuButtonRole: - case kMenuItemRole: - case kMenuItemCheckBoxRole: - case kMenuItemRadioRole: - case kMenuListOptionRole: - case kPopUpButtonRole: - case kRadioButtonRole: - case kRowHeaderRole: - case kStaticTextRole: - case kSwitchRole: - case kTabRole: - case kToggleButtonRole: - case kTreeItemRole: - case kUserInterfaceTooltipRole: - result = true; - break; - - // ----- No name from contents ------------------------- - // These never have or contribute a name from contents, as they are - // containers for many subobjects. Superset of nameFrom:author ARIA roles. - case kAlertRole: - case kAlertDialogRole: - case kApplicationRole: - case kAudioRole: - case kArticleRole: - case kBannerRole: - case kBlockquoteRole: - case kColorWellRole: - case kColumnRole: - case kComboBoxRole: - case kComplementaryRole: - case kContentInfoRole: - case kDateRole: - case kDateTimeRole: - case kDefinitionRole: - case kDialogRole: - case kDirectoryRole: - case kDocumentRole: - case kEmbeddedObjectRole: - case kFeedRole: - case kFigureRole: - case kFormRole: - case kGridRole: - case kGroupRole: - case kIframePresentationalRole: - case kIframeRole: - case kImageRole: - case kInputTimeRole: - case kListBoxRole: - case kLogRole: - case kMainRole: - case kMarqueeRole: - case kMathRole: - case kMenuListPopupRole: - case kMenuRole: - case kMenuBarRole: - case kMeterRole: - case kNavigationRole: - case kNoteRole: - case kOutlineRole: - case kProgressIndicatorRole: - case kRadioGroupRole: - case kRegionRole: - case kRootWebAreaRole: - case kScrollBarRole: - case kSearchRole: - case kSearchBoxRole: - case kSplitterRole: - case kSliderRole: - case kSpinButtonRole: - case kStatusRole: - case kScrollAreaRole: - case kSeamlessWebAreaRole: - case kSliderThumbRole: - case kSpinButtonPartRole: - case kSVGRootRole: - case kTableRole: - case kTableHeaderContainerRole: - case kTabGroupRole: - case kTabListRole: - case kTabPanelRole: - case kTermRole: - case kTextFieldRole: - case kTimeRole: - case kTimerRole: - case kToolbarRole: - case kTreeRole: - case kTreeGridRole: - case kVideoRole: - case kWebAreaRole: - case kWindowRole: - result = false; - break; - - // ----- Conditional: contribute to ancestor only, unless focusable ------- - // Some objects can contribute their contents to ancestor names, but - // only have their own name if they are focusable - case kAbbrRole: - case kAnnotationRole: - case kBusyIndicatorRole: - case kCanvasRole: - case kCaptionRole: - case kDescriptionListDetailRole: - case kDescriptionListRole: - case kDescriptionListTermRole: - case kDetailsRole: - case kFigcaptionRole: - case kFooterRole: - case kGenericContainerRole: - case kIgnoredRole: - case kImageMapLinkRole: - case kImageMapRole: - case kInlineTextBoxRole: - case kLabelRole: - case kLegendRole: - case kListRole: - case kListItemRole: - case kListMarkerRole: - case kMarkRole: - case kNoneRole: - case kParagraphRole: - case kPreRole: - case kPresentationalRole: - // Spec says we should always expose the name on rows, - // but for performance reasons we only do it - // if the row might receive focus - case kRowRole: - case kRubyRole: - case kRulerRole: - result = recursive || (CanReceiveAccessibilityFocus() && !IsEditable()); - break; - - case kUnknownRole: - case kNumRoles: - LOG(ERROR) << "kUnknownRole for " << GetNode(); - NOTREACHED(); - break; - } - - return result; -} - -AccessibilityRole AXObjectImpl::ButtonRoleType() const { - // If aria-pressed is present, then it should be exposed as a toggle button. - // http://www.w3.org/TR/wai-aria/states_and_properties#aria-pressed - if (AriaPressedIsPresent()) - return kToggleButtonRole; - if (AriaHasPopup()) - return kPopUpButtonRole; - // We don't contemplate RadioButtonRole, as it depends on the input - // type. - - return kButtonRole; -} - -const AtomicString& AXObjectImpl::RoleName(AccessibilityRole role) { - static const Vector<AtomicString>* role_name_vector = CreateRoleNameVector(); - - return role_name_vector->at(role); -} - -const AtomicString& AXObjectImpl::InternalRoleName(AccessibilityRole role) { - static const Vector<AtomicString>* internal_role_name_vector = - CreateInternalRoleNameVector(); - - return internal_role_name_vector->at(role); -} - -DEFINE_TRACE(AXObjectImpl) { - visitor->Trace(children_); - visitor->Trace(parent_); - visitor->Trace(cached_live_region_root_); - visitor->Trace(ax_object_cache_); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.h b/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.h deleted file mode 100644 index c2487266..0000000 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectImpl.h +++ /dev/null
@@ -1,903 +0,0 @@ - -/* - * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved. - * Copyright (C) 2008 Nuanti Ltd. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef AXObjectImpl_h -#define AXObjectImpl_h - -#include "core/editing/VisiblePosition.h" -#include "core/editing/markers/DocumentMarker.h" -#include "core/inspector/protocol/Accessibility.h" -#include "modules/ModulesExport.h" -#include "modules/accessibility/AXObject.h" -#include "platform/geometry/FloatQuad.h" -#include "platform/geometry/LayoutRect.h" -#include "platform/graphics/Color.h" -#include "platform/wtf/Forward.h" -#include "platform/wtf/Vector.h" - -class SkMatrix44; - -namespace blink { - -class AXObjectImpl; -class AXObjectCacheImpl; -class Element; -class IntPoint; -class LayoutObject; -class LocalFrameView; -class Node; -class ScrollableArea; - -enum class AOMBooleanProperty; -enum class AOMStringProperty; -enum class AOMUIntProperty; -enum class AOMIntProperty; -enum class AOMFloatProperty; - -typedef unsigned AXID; - -enum AccessibilityTextSource { - kAlternativeText, - kChildrenText, - kSummaryText, - kHelpText, - kVisibleText, - kTitleTagText, - kPlaceholderText, - kLabelByElementText, -}; - -class AccessibilityText final - : public GarbageCollectedFinalized<AccessibilityText> { - WTF_MAKE_NONCOPYABLE(AccessibilityText); - - public: - DEFINE_INLINE_TRACE() { visitor->Trace(text_element_); } - - private: - AccessibilityText(const String& text, - const AccessibilityTextSource& source, - AXObjectImpl* element) - : text_(text), text_element_(element) {} - - String text_; - Member<AXObjectImpl> text_element_; -}; - -enum AXObjectInclusion { - kIncludeObject, - kIgnoreObject, - kDefaultBehavior, -}; - -enum AccessibilityCheckedState { - kCheckedStateUndefined = 0, - kCheckedStateFalse, - kCheckedStateTrue, - kCheckedStateMixed -}; - -enum AccessibilityOptionalBool { - kOptionalBoolUndefined = 0, - kOptionalBoolTrue, - kOptionalBoolFalse -}; - -enum TextUnderElementMode { - kTextUnderElementAll, - kTextUnderElementAny // If the text is unimportant, just whether or not it's - // present -}; - -enum class AXBoolAttribute {}; - -class AXSparseAttributeClient { - public: - virtual void AddBoolAttribute(AXBoolAttribute, bool) = 0; - virtual void AddStringAttribute(AXStringAttribute, const String&) = 0; - virtual void AddObjectAttribute(AXObjectAttribute, AXObjectImpl&) = 0; - virtual void AddObjectVectorAttribute(AXObjectVectorAttribute, - HeapVector<Member<AXObjectImpl>>&) = 0; -}; - -// The potential native HTML-based text (name, description or placeholder) -// sources for an element. See -// http://rawgit.com/w3c/aria/master/html-aam/html-aam.html#accessible-name-and-description-calculation -enum AXTextFromNativeHTML { - kAXTextFromNativeHTMLUninitialized = -1, - kAXTextFromNativeHTMLFigcaption, - kAXTextFromNativeHTMLLabel, - kAXTextFromNativeHTMLLabelFor, - kAXTextFromNativeHTMLLabelWrapped, - kAXTextFromNativeHTMLLegend, - kAXTextFromNativeHTMLTableCaption, - kAXTextFromNativeHTMLTitleElement, -}; - -enum AXIgnoredReason { - kAXActiveModalDialog, - kAXAncestorDisallowsChild, - kAXAncestorIsLeafNode, - kAXAriaHiddenElement, - kAXAriaHiddenSubtree, - kAXEmptyAlt, - kAXEmptyText, - kAXInertElement, - kAXInertSubtree, - kAXInheritsPresentation, - kAXLabelContainer, - kAXLabelFor, - kAXNotRendered, - kAXNotVisible, - kAXPresentationalRole, - kAXProbablyPresentational, - kAXStaticTextUsedAsNameFor, - kAXUninteresting -}; - -class IgnoredReason { - DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); - - public: - AXIgnoredReason reason; - Member<const AXObjectImpl> related_object; - - explicit IgnoredReason(AXIgnoredReason reason) - : reason(reason), related_object(nullptr) {} - - IgnoredReason(AXIgnoredReason r, const AXObjectImpl* obj) - : reason(r), related_object(obj) {} - - DEFINE_INLINE_TRACE() { visitor->Trace(related_object); } -}; - -class NameSourceRelatedObject - : public GarbageCollectedFinalized<NameSourceRelatedObject> { - WTF_MAKE_NONCOPYABLE(NameSourceRelatedObject); - - public: - WeakMember<AXObjectImpl> object; - String text; - - NameSourceRelatedObject(AXObjectImpl* object, String text) - : object(object), text(text) {} - - DEFINE_INLINE_TRACE() { visitor->Trace(object); } -}; - -typedef HeapVector<Member<NameSourceRelatedObject>> AXRelatedObjectVector; -class NameSource { - DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); - - public: - String text; - bool superseded = false; - bool invalid = false; - AXNameFrom type = kAXNameFromUninitialized; - const QualifiedName& attribute; - AtomicString attribute_value; - AXTextFromNativeHTML native_source = kAXTextFromNativeHTMLUninitialized; - AXRelatedObjectVector related_objects; - - NameSource(bool superseded, const QualifiedName& attr) - : superseded(superseded), attribute(attr) {} - - explicit NameSource(bool superseded) - : superseded(superseded), attribute(QualifiedName::Null()) {} - - DEFINE_INLINE_TRACE() { visitor->Trace(related_objects); } -}; - -class DescriptionSource { - DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); - - public: - String text; - bool superseded = false; - bool invalid = false; - AXDescriptionFrom type = kAXDescriptionFromUninitialized; - const QualifiedName& attribute; - AtomicString attribute_value; - AXTextFromNativeHTML native_source = kAXTextFromNativeHTMLUninitialized; - AXRelatedObjectVector related_objects; - - DescriptionSource(bool superseded, const QualifiedName& attr) - : superseded(superseded), attribute(attr) {} - - explicit DescriptionSource(bool superseded) - : superseded(superseded), attribute(QualifiedName::Null()) {} - - DEFINE_INLINE_TRACE() { visitor->Trace(related_objects); } -}; - -} // namespace blink - -WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::IgnoredReason); -WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::NameSource); -WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::DescriptionSource); - -namespace blink { - -class MODULES_EXPORT AXObjectImpl - : public GarbageCollectedFinalized<AXObjectImpl>, - public AXObject { - WTF_MAKE_NONCOPYABLE(AXObjectImpl); - - public: - typedef HeapVector<Member<AXObjectImpl>> AXObjectVector; - - struct AXRange { - DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); - // The deepest descendant in which the range starts. - // (nullptr means the current object.) - Persistent<AXObjectImpl> anchor_object; - // The number of characters and child objects in the anchor object - // before the range starts. - int anchor_offset; - // When the same character offset could correspond to two possible - // cursor positions, upstream means it's on the previous line rather - // than the next line. - TextAffinity anchor_affinity; - - // The deepest descendant in which the range ends. - // (nullptr means the current object.) - Persistent<AXObjectImpl> focus_object; - // The number of characters and child objects in the focus object - // before the range ends. - int focus_offset; - // When the same character offset could correspond to two possible - // cursor positions, upstream means it's on the previous line rather - // than the next line. - TextAffinity focus_affinity; - - AXRange() - : anchor_object(nullptr), - anchor_offset(-1), - anchor_affinity(TextAffinity::kUpstream), - focus_object(nullptr), - focus_offset(-1), - focus_affinity(TextAffinity::kDownstream) {} - - AXRange(int start_offset, int end_offset) - : anchor_object(nullptr), - anchor_offset(start_offset), - anchor_affinity(TextAffinity::kUpstream), - focus_object(nullptr), - focus_offset(end_offset), - focus_affinity(TextAffinity::kDownstream) {} - - AXRange(AXObjectImpl* anchor_object, - int anchor_offset, - TextAffinity anchor_affinity, - AXObjectImpl* focus_object, - int focus_offset, - TextAffinity focus_affinity) - : anchor_object(anchor_object), - anchor_offset(anchor_offset), - anchor_affinity(anchor_affinity), - focus_object(focus_object), - focus_offset(focus_offset), - focus_affinity(focus_affinity) {} - - bool IsValid() const { - return ((anchor_object && focus_object) || - (!anchor_object && !focus_object)) && - anchor_offset >= 0 && focus_offset >= 0; - } - - // Determines if the range only refers to text offsets under the current - // object. - bool IsSimple() const { - return anchor_object == focus_object || !anchor_object || !focus_object; - } - }; - - protected: - AXObjectImpl(AXObjectCacheImpl&); - - public: - virtual ~AXObjectImpl(); - DECLARE_VIRTUAL_TRACE(); - - static unsigned NumberOfLiveAXObjects() { return number_of_live_ax_objects_; } - - // After constructing an AXObjectImpl, it must be given a - // unique ID, then added to AXObjectCacheImpl, and finally init() must - // be called last. - void SetAXObjectID(AXID ax_object_id) { id_ = ax_object_id; } - virtual void Init() {} - - // When the corresponding WebCore object that this AXObjectImpl - // wraps is deleted, it must be detached. - virtual void Detach(); - virtual bool IsDetached() const; - - // If the parent of this object is known, this can be faster than using - // computeParent(). - virtual void SetParent(AXObjectImpl* parent) { parent_ = parent; } - - // The AXObjectCacheImpl that owns this object, and its unique ID within this - // cache. - AXObjectCacheImpl& AxObjectCache() const { - DCHECK(ax_object_cache_); - return *ax_object_cache_; - } - - AXID AxObjectID() const { return id_; } - - // Wrappers that retrieve either an Accessibility Object Model property, - // or the equivalent ARIA attribute, in that order. - const AtomicString& GetAOMPropertyOrARIAAttribute(AOMStringProperty) const; - bool HasAOMPropertyOrARIAAttribute(AOMBooleanProperty, bool& result) const; - bool AOMPropertyOrARIAAttributeIsTrue(AOMBooleanProperty) const; - bool AOMPropertyOrARIAAttributeIsFalse(AOMBooleanProperty) const; - bool HasAOMPropertyOrARIAAttribute(AOMUIntProperty, uint32_t& result) const; - bool HasAOMPropertyOrARIAAttribute(AOMIntProperty, int32_t& result) const; - bool HasAOMPropertyOrARIAAttribute(AOMFloatProperty, float& result) const; - - virtual void GetSparseAXAttributes(AXSparseAttributeClient&) const {} - - // Determine subclass type. - virtual bool IsAXNodeObject() const { return false; } - virtual bool IsAXLayoutObject() const { return false; } - virtual bool IsAXInlineTextBox() const { return false; } - virtual bool IsAXListBox() const { return false; } - virtual bool IsAXListBoxOption() const { return false; } - virtual bool IsAXRadioInput() const { return false; } - virtual bool IsAXSVGRoot() const { return false; } - - // Check object role or purpose. - virtual AccessibilityRole RoleValue() const { return role_; } - bool IsARIATextControl() const; - virtual bool IsARIATreeGridRow() const { return false; } - virtual bool IsAXTable() const { return false; } - virtual bool IsAnchor() const { return false; } - bool IsButton() const; - bool IsCanvas() const { return RoleValue() == kCanvasRole; } - bool IsCheckbox() const { return RoleValue() == kCheckBoxRole; } - bool IsCheckboxOrRadio() const { return IsCheckbox() || IsRadioButton(); } - bool IsColorWell() const { return RoleValue() == kColorWellRole; } - bool IsComboBox() const { return RoleValue() == kComboBoxRole; } - virtual bool IsControl() const { return false; } - virtual bool IsDataTable() const { return false; } - virtual bool IsEmbeddedObject() const { return false; } - virtual bool IsFieldset() const { return false; } - virtual bool IsHeading() const { return false; } - virtual bool IsImage() const { return false; } - virtual bool IsImageMapLink() const { return false; } - virtual bool IsInputImage() const { return false; } - bool IsLandmarkRelated() const; - virtual bool IsLink() const { return false; } - virtual bool IsInPageLinkTarget() const { return false; } - virtual bool IsList() const { return false; } - virtual bool IsMenu() const { return false; } - virtual bool IsMenuButton() const { return false; } - virtual bool IsMenuList() const { return false; } - virtual bool IsMenuListOption() const { return false; } - virtual bool IsMenuListPopup() const { return false; } - bool IsMenuRelated() const; - virtual bool IsMeter() const { return false; } - virtual bool IsMockObject() const { return false; } - virtual bool IsNativeSpinButton() const { return false; } - virtual bool IsNativeTextControl() const { - return false; - } // input or textarea - virtual bool IsNonNativeTextControl() const { - return false; - } // contenteditable or role=textbox - virtual bool IsPasswordField() const { return false; } - virtual bool IsPasswordFieldAndShouldHideValue() const; - bool IsPresentational() const { - return RoleValue() == kNoneRole || RoleValue() == kPresentationalRole; - } - virtual bool IsProgressIndicator() const { return false; } - bool IsRadioButton() const { return RoleValue() == kRadioButtonRole; } - bool IsRange() const { - return RoleValue() == kProgressIndicatorRole || - RoleValue() == kScrollBarRole || RoleValue() == kSliderRole || - RoleValue() == kSpinButtonRole || IsMoveableSplitter(); - } - bool IsScrollbar() const { return RoleValue() == kScrollBarRole; } - virtual bool IsSlider() const { return false; } - virtual bool IsNativeSlider() const { return false; } - virtual bool IsMoveableSplitter() const { return false; } - virtual bool IsSpinButton() const { return RoleValue() == kSpinButtonRole; } - virtual bool IsSpinButtonPart() const { return false; } - bool IsTabItem() const { return RoleValue() == kTabRole; } - virtual bool IsTableCell() const { return false; } - virtual bool IsTableRow() const { return false; } - virtual bool IsTextControl() const { return false; } - virtual bool IsTableCol() const { return false; } - bool IsTree() const { return RoleValue() == kTreeRole; } - bool IsWebArea() const { return RoleValue() == kWebAreaRole; } - - // Check object state. - virtual bool IsClickable() const; - virtual bool IsCollapsed() const { return false; } - virtual bool IsEnabled() const { return false; } - virtual AccessibilityExpanded IsExpanded() const { - return kExpandedUndefined; - } - virtual bool IsFocused() const { return false; } - virtual bool IsHovered() const { return false; } - virtual bool IsLinked() const { return false; } - virtual bool IsLoaded() const { return false; } - virtual bool IsModal() const { return false; } - virtual bool IsMultiSelectable() const { return false; } - virtual bool IsOffScreen() const { return false; } - virtual bool IsReadOnly() const { return false; } - virtual bool IsRequired() const { return false; } - virtual bool IsSelected() const { return false; } - virtual bool IsSelectedOptionActive() const { return false; } - virtual bool IsVisible() const { return true; } - virtual bool IsVisited() const { return false; } - - // Check whether certain properties can be modified. - virtual bool CanSetFocusAttribute() const { return false; } - virtual bool CanSetValueAttribute() const { return false; } - virtual bool CanSetSelectedAttribute() const { return false; } - - // Whether objects are ignored, i.e. not included in the tree. - bool AccessibilityIsIgnored(); - typedef HeapVector<IgnoredReason> IgnoredReasons; - virtual bool ComputeAccessibilityIsIgnored(IgnoredReasons* = nullptr) const { - return true; - } - bool AccessibilityIsIgnoredByDefault(IgnoredReasons* = nullptr) const; - AXObjectInclusion AccessibilityPlatformIncludesObject() const; - virtual AXObjectInclusion DefaultObjectInclusion( - IgnoredReasons* = nullptr) const; - bool IsInertOrAriaHidden() const; - const AXObjectImpl* AriaHiddenRoot() const; - bool ComputeIsInertOrAriaHidden(IgnoredReasons* = nullptr) const; - bool IsDescendantOfLeafNode() const; - AXObjectImpl* LeafNodeAncestor() const; - bool IsDescendantOfDisabledNode() const; - const AXObjectImpl* DisabledAncestor() const; - bool LastKnownIsIgnoredValue(); - void SetLastKnownIsIgnoredValue(bool); - bool HasInheritedPresentationalRole() const; - bool IsPresentationalChild() const; - bool AncestorExposesActiveDescendant() const; - bool ComputeAncestorExposesActiveDescendant() const; - - // - // Accessible name calculation - // - - // Retrieves the accessible name of the object, an enum indicating where the - // name was derived from, and a list of objects that were used to derive the - // name, if any. - virtual String GetName(AXNameFrom&, AXObjectVector* name_objects) const; - - typedef HeapVector<NameSource> NameSources; - // Retrieves the accessible name of the object and a list of all potential - // sources for the name, indicating which were used. - virtual String GetName(NameSources*) const; - - typedef HeapVector<DescriptionSource> DescriptionSources; - // Takes the result of nameFrom from calling |name|, above, and retrieves the - // accessible description of the object, which is secondary to |name|, an enum - // indicating where the description was derived from, and a list of objects - // that were used to derive the description, if any. - virtual String Description(AXNameFrom, - AXDescriptionFrom&, - AXObjectVector* description_objects) const { - return String(); - } - - // Same as above, but returns a list of all potential sources for the - // description, indicating which were used. - virtual String Description(AXNameFrom, - AXDescriptionFrom&, - DescriptionSources*, - AXRelatedObjectVector*) const { - return String(); - } - - // Takes the result of nameFrom and descriptionFrom from calling |name| and - // |description|, above, and retrieves the placeholder of the object, if - // present and if it wasn't already exposed by one of the two functions above. - virtual String Placeholder(AXNameFrom) const { return String(); } - - // Internal functions used by name and description, above. - typedef HeapHashSet<Member<const AXObjectImpl>> AXObjectSet; - virtual String TextAlternative(bool recursive, - bool in_aria_labelled_by_traversal, - AXObjectSet& visited, - AXNameFrom& name_from, - AXRelatedObjectVector* related_objects, - NameSources* name_sources) const { - return String(); - } - virtual String TextFromDescendants(AXObjectSet& visited, - bool recursive) const { - return String(); - } - - // Returns result of Accessible Name Calculation algorithm. - // This is a simpler high-level interface to |name| used by Inspector. - String ComputedName() const; - - // Internal function used to determine whether the result of calling |name| on - // this object would return text that came from the an HTML label element or - // not. This is intended to be faster than calling |name| or - // |textAlternative|, and without side effects (it won't call - // axObjectCache->getOrCreate). - virtual bool NameFromLabelElement() const { return false; } - - // - // Properties of static elements. - // - - virtual const AtomicString& AccessKey() const { return g_null_atom; } - RGBA32 BackgroundColor() const; - virtual RGBA32 ComputeBackgroundColor() const { return Color::kTransparent; } - virtual RGBA32 GetColor() const { return Color::kBlack; } - // Used by objects of role ColorWellRole. - virtual RGBA32 ColorValue() const { return Color::kTransparent; } - virtual bool CanvasHasFallbackContent() const { return false; } - virtual String FontFamily() const { return g_null_atom; } - // Font size is in pixels. - virtual float FontSize() const { return 0.0f; } - // Value should be 1-based. 0 means not supported. - virtual int HeadingLevel() const { return 0; } - // Value should be 1-based. 0 means not supported. - virtual unsigned HierarchicalLevel() const { return 0; } - // Return the content of an image or canvas as an image data url in - // PNG format. If |maxSize| is not empty and if the image is larger than - // those dimensions, the image will be resized proportionally first to fit. - virtual String ImageDataUrl(const IntSize& max_size) const { - return g_null_atom; - } - virtual AXObjectImpl* InPageLinkTarget() const { return nullptr; } - virtual AccessibilityOrientation Orientation() const; - virtual String GetText() const { return String(); } - virtual AccessibilityTextDirection GetTextDirection() const { - return kAccessibilityTextDirectionLTR; - } - virtual int TextLength() const { return 0; } - virtual TextStyle GetTextStyle() const { return kTextStyleNone; } - virtual AXObjectVector RadioButtonsInGroup() const { - return AXObjectVector(); - } - virtual KURL Url() const { return KURL(); } - - // Load inline text boxes for just this node, even if - // settings->inlineTextBoxAccessibilityEnabled() is false. - virtual void LoadInlineTextBoxes() {} - - // Walk the AXObjects on the same line. This is supported on any - // object type but primarily intended to be used for inline text boxes. - virtual AXObjectImpl* NextOnLine() const { return nullptr; } - virtual AXObjectImpl* PreviousOnLine() const { return nullptr; } - - // For all node objects. The start and end character offset of each - // marker, such as spelling or grammar error. - virtual void Markers(Vector<DocumentMarker::MarkerType>&, - Vector<AXRange>&) const {} - // For an inline text box. - // The integer horizontal pixel offset of each character in the string; - // negative values for RTL. - virtual void TextCharacterOffsets(Vector<int>&) const {} - // The start and end character offset of each word in the object's text. - virtual void GetWordBoundaries(Vector<AXRange>&) const {} - - // Properties of interactive elements. - AXDefaultActionVerb Action() const; - AccessibilityCheckedState CheckedState() const; - virtual AriaCurrentState GetAriaCurrentState() const { - return kAriaCurrentStateUndefined; - } - virtual InvalidState GetInvalidState() const { - return kInvalidStateUndefined; - } - // Only used when invalidState() returns InvalidStateOther. - virtual String AriaInvalidValue() const { return String(); } - virtual String ValueDescription() const { return String(); } - virtual float ValueForRange() const { return 0.0f; } - virtual float MaxValueForRange() const { return 0.0f; } - virtual float MinValueForRange() const { return 0.0f; } - virtual String StringValue() const { return String(); } - - // ARIA attributes. - virtual AXObjectImpl* ActiveDescendant() { return nullptr; } - virtual String AriaAutoComplete() const { return String(); } - virtual void AriaOwnsElements(AXObjectVector& owns) const {} - virtual void AriaDescribedbyElements(AXObjectVector&) const {} - virtual void AriaLabelledbyElements(AXObjectVector&) const {} - virtual bool AriaHasPopup() const { return false; } - virtual bool IsEditable() const { return false; } - bool IsMultiline() const; - virtual bool IsRichlyEditable() const { return false; } - bool AriaCheckedIsPresent() const; - bool AriaPressedIsPresent() const; - virtual AccessibilityRole AriaRoleAttribute() const { return kUnknownRole; } - virtual bool AriaRoleHasPresentationalChildren() const { return false; } - virtual AXObjectImpl* AncestorForWhichThisIsAPresentationalChild() const { - return 0; - } - bool SupportsActiveDescendant() const; - bool SupportsARIAAttributes() const; - virtual bool SupportsARIADragging() const { return false; } - virtual bool SupportsARIADropping() const { return false; } - virtual bool SupportsARIAFlowTo() const { return false; } - virtual bool SupportsARIAOwns() const { return false; } - bool SupportsRangeValue() const; - virtual SortDirection GetSortDirection() const { - return kSortDirectionUndefined; - } - - // Returns 0-based index. - int IndexInParent() const; - - // Value should be 1-based. 0 means not supported. - virtual int PosInSet() const { return 0; } - virtual int SetSize() const { return 0; } - bool SupportsSetSizeAndPosInSet() const; - - // ARIA live-region features. - bool IsLiveRegion() const; - AXObjectImpl* LiveRegionRoot() const; - virtual const AtomicString& LiveRegionStatus() const { return g_null_atom; } - virtual const AtomicString& LiveRegionRelevant() const { return g_null_atom; } - virtual bool LiveRegionAtomic() const { return false; } - virtual bool LiveRegionBusy() const { return false; } - - const AtomicString& ContainerLiveRegionStatus() const; - const AtomicString& ContainerLiveRegionRelevant() const; - bool ContainerLiveRegionAtomic() const; - bool ContainerLiveRegionBusy() const; - - // Every object's bounding box is returned relative to a - // container object (which is guaranteed to be an ancestor) and - // optionally a transformation matrix that needs to be applied too. - // To compute the absolute bounding box of an element, start with its - // boundsInContainer and apply the transform. Then as long as its container is - // not null, walk up to its container and offset by the container's offset - // from origin, the container's scroll position if any, and apply the - // container's transform. Do this until you reach the root of the tree. - virtual void GetRelativeBounds(AXObjectImpl** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const; - - // Get the bounds in frame-relative coordinates as a LayoutRect. - LayoutRect GetBoundsInFrameCoordinates() const; - - // Explicitly set an object's bounding rect and offset container. - void SetElementRect(LayoutRect r, AXObjectImpl* container) { - explicit_element_rect_ = r; - explicit_container_id_ = container->AxObjectID(); - } - - // Hit testing. - // Called on the root AX object to return the deepest available element. - virtual AXObjectImpl* AccessibilityHitTest(const IntPoint&) const { - return 0; - } - // Called on the AX object after the layout tree determines which is the right - // AXLayoutObject. - virtual AXObjectImpl* ElementAccessibilityHitTest(const IntPoint&) const; - - // High-level accessibility tree access. Other modules should only use these - // functions. - const AXObjectVector& Children(); - AXObjectImpl* ParentObject() const; - AXObjectImpl* ParentObjectIfExists() const; - virtual AXObjectImpl* ComputeParent() const = 0; - virtual AXObjectImpl* ComputeParentIfExists() const { return 0; } - AXObjectImpl* CachedParentObject() const { return parent_; } - AXObjectImpl* ParentObjectUnignored() const; - AXObjectImpl* ContainerWidget() const; - bool IsContainerWidget() const; - - // Low-level accessibility tree exploration, only for use within the - // accessibility module. - virtual AXObjectImpl* RawFirstChild() const { return 0; } - virtual AXObjectImpl* RawNextSibling() const { return 0; } - virtual void AddChildren() {} - virtual bool CanHaveChildren() const { return true; } - bool HasChildren() const { return have_children_; } - virtual void UpdateChildrenIfNecessary(); - virtual bool NeedsToUpdateChildren() const { return false; } - virtual void SetNeedsToUpdateChildren() {} - virtual void ClearChildren(); - virtual void DetachFromParent() { parent_ = 0; } - virtual AXObjectImpl* ScrollBar(AccessibilityOrientation) { return 0; } - - // Properties of the object's owning document or page. - virtual double EstimatedLoadingProgress() const { return 0; } - - // DOM and layout tree access. - virtual Node* GetNode() const { return nullptr; } - virtual Element* GetElement() const; // Same as GetNode, if it's an Element. - virtual LayoutObject* GetLayoutObject() const { return nullptr; } - virtual Document* GetDocument() const; - virtual LocalFrameView* DocumentFrameView() const; - virtual Element* AnchorElement() const { return nullptr; } - virtual Element* ActionElement() const { return nullptr; } - String Language() const; - bool HasAttribute(const QualifiedName&) const; - const AtomicString& GetAttribute(const QualifiedName&) const; - - // Methods that retrieve or manipulate the current selection. - - // Get the current selection from anywhere in the accessibility tree. - virtual AXRange Selection() const { return AXRange(); } - // Gets only the start and end offsets of the selection computed using the - // current object as the starting point. Returns a null selection if there is - // no selection in the subtree rooted at this object. - virtual AXRange SelectionUnderObject() const { return AXRange(); } - virtual void SetSelection(const AXRange&) {} - - // Scrollable containers. - bool IsScrollableContainer() const; - IntPoint GetScrollOffset() const; - IntPoint MinimumScrollOffset() const; - IntPoint MaximumScrollOffset() const; - void SetScrollOffset(const IntPoint&) const; - - // If this object itself scrolls, return its ScrollableArea. - virtual ScrollableArea* GetScrollableAreaIfScrollable() const { return 0; } - - // Modify or take an action on an object. - virtual void Increment() {} - virtual void Decrement() {} - bool PerformDefaultAction() { return Press(); } - virtual bool Press(); - // Make this object visible by scrolling as many nested scrollable views as - // needed. - void ScrollToMakeVisible() const; - // Same, but if the whole object can't be made visible, try for this subrect, - // in local coordinates. - void ScrollToMakeVisibleWithSubFocus(const IntRect&) const; - // Scroll this object to a given point in global coordinates of the top-level - // window. - void ScrollToGlobalPoint(const IntPoint&) const; - virtual void SetFocused(bool) {} - virtual void SetSelected(bool) {} - virtual void SetSequentialFocusNavigationStartingPoint(); - virtual void SetValue(const String&) {} - virtual void SetValue(float) {} - - // Notifications that this object may have changed. - virtual void ChildrenChanged() {} - virtual void HandleActiveDescendantChanged() {} - virtual void HandleAriaExpandedChanged() {} - void NotifyIfIgnoredValueChanged(); - virtual void SelectionChanged(); - virtual void TextChanged() {} - virtual void UpdateAccessibilityRole() {} - - // Text metrics. Most of these should be deprecated, needs major cleanup. - virtual VisiblePosition VisiblePositionForIndex(int) const { - return VisiblePosition(); - } - int LineForPosition(const VisiblePosition&) const; - virtual int Index(const VisiblePosition&) const { return -1; } - virtual void LineBreaks(Vector<int>&) const {} - - // Static helper functions. - static bool IsARIAControl(AccessibilityRole); - static bool IsARIAInput(AccessibilityRole); - static AccessibilityRole AriaRoleToWebCoreRole(const String&); - static const AtomicString& RoleName(AccessibilityRole); - static const AtomicString& InternalRoleName(AccessibilityRole); - - protected: - AXID id_; - AXObjectVector children_; - mutable bool have_children_; - AccessibilityRole role_; - AXObjectInclusion last_known_is_ignored_value_; - LayoutRect explicit_element_rect_; - AXID explicit_container_id_; - - // Used only inside textAlternative(): - static String CollapseWhitespace(const String&); - static String RecursiveTextAlternative(const AXObjectImpl&, - bool in_aria_labelled_by_traversal, - AXObjectSet& visited); - bool IsHiddenForTextAlternativeCalculation() const; - String AriaTextAlternative(bool recursive, - bool in_aria_labelled_by_traversal, - AXObjectSet& visited, - AXNameFrom&, - AXRelatedObjectVector*, - NameSources*, - bool* found_text_alternative) const; - String TextFromElements(bool in_aria_labelled_by_traversal, - AXObjectSet& visited, - HeapVector<Member<Element>>& elements, - AXRelatedObjectVector* related_objects) const; - void TokenVectorFromAttribute(Vector<String>&, const QualifiedName&) const; - void ElementsFromAttribute(HeapVector<Member<Element>>& elements, - const QualifiedName&) const; - void AriaLabelledbyElementVector(HeapVector<Member<Element>>& elements) const; - String TextFromAriaLabelledby(AXObjectSet& visited, - AXRelatedObjectVector* related_objects) const; - String TextFromAriaDescribedby(AXRelatedObjectVector* related_objects) const; - - virtual const AXObjectImpl* InheritsPresentationalRoleFrom() const { - return 0; - } - - bool CanReceiveAccessibilityFocus() const; - bool NameFromContents(bool recursive) const; - - AccessibilityRole ButtonRoleType() const; - - virtual LayoutObject* LayoutObjectForRelativeBounds() const { - return nullptr; - } - - const AXObjectImpl* InertRoot() const; - - mutable Member<AXObjectImpl> parent_; - - // The following cached attribute values (the ones starting with m_cached*) - // are only valid if m_lastModificationCount matches - // AXObjectCacheImpl::modificationCount(). - mutable int last_modification_count_; - mutable RGBA32 cached_background_color_; - mutable bool cached_is_ignored_ : 1; - mutable bool cached_is_inert_or_aria_hidden_ : 1; - mutable bool cached_is_descendant_of_leaf_node_ : 1; - mutable bool cached_is_descendant_of_disabled_node_ : 1; - mutable bool cached_has_inherited_presentational_role_ : 1; - mutable bool cached_is_presentational_child_ : 1; - mutable bool cached_ancestor_exposes_active_descendant_ : 1; - mutable Member<AXObjectImpl> cached_live_region_root_; - - Member<AXObjectCacheImpl> ax_object_cache_; - - // Updates the cached attribute values. This may be recursive, so to prevent - // deadlocks, - // functions called here may only search up the tree (ancestors), not down. - void UpdateCachedAttributeValuesIfNeeded() const; - - private: - bool IsCheckable() const; - static bool IsNativeInputInMixedState(const Node*); - static bool IncludesARIAWidgetRole(const String&); - static bool HasInteractiveARIAAttribute(const Element&); - - static unsigned number_of_live_ax_objects_; -}; - -DEFINE_TYPE_CASTS(AXObjectImpl, AXObject, obj, true, true); - -#define DEFINE_AX_OBJECT_TYPE_CASTS(thisType, predicate) \ - DEFINE_TYPE_CASTS(thisType, AXObjectImpl, object, object->predicate, \ - object.predicate) - -} // namespace blink - -#endif // AXObjectImpl_h
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectTest.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectTest.cpp index b0e27de..a1ca9b9c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectTest.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectTest.cpp
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" #include "core/dom/Document.h" #include "core/dom/Element.h"
diff --git a/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp index 75f9c2b8..ff9247e4 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp
@@ -40,7 +40,7 @@ void AXRadioInput::RequestUpdateToNextNode(bool forward) { HTMLInputElement* next_element = RadioInputType::NextRadioButtonInGroup(GetInputElement(), forward); - AXObjectImpl* next_axobject = AxObjectCache().Get(next_element); + AXObject* next_axobject = AxObjectCache().Get(next_element); if (!next_axobject || !next_axobject->IsAXRadioInput()) return; @@ -88,10 +88,10 @@ HTMLInputElement* prev_element = RadioInputType::NextRadioButtonInGroup(GetInputElement(), false); if (prev_element) { - AXObjectImpl* object = AxObjectCache().Get(prev_element); - // If the previous element doesn't have AXObjectImpl yet, caculate position + AXObject* object = AxObjectCache().Get(prev_element); + // If the previous element doesn't have AXObject yet, caculate position // from the first element. Otherwise, get position from the previous - // AXObjectImpl. + // AXObject. if (!object || !object->IsAXRadioInput()) { position = CountFromFirstElement(); } else {
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.cpp b/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.cpp index 08c33dcd..eb04cff 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.cpp
@@ -43,7 +43,7 @@ return new AXSVGRoot(layout_object, ax_object_cache); } -void AXSVGRoot::SetParent(AXObjectImpl* parent) { +void AXSVGRoot::SetParent(AXObject* parent) { // Only update the parent to another objcet if it wasn't already set to // something. Multiple elements in an HTML document can reference // the same remote SVG document, and in that case the parent should just @@ -52,7 +52,7 @@ parent_ = parent; } -AXObjectImpl* AXSVGRoot::ComputeParent() const { +AXObject* AXSVGRoot::ComputeParent() const { DCHECK(!IsDetached()); // If a parent was set because this is a remote SVG resource, use that // but otherwise, we should rely on the standard layout tree for the parent.
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.h b/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.h index 7901267..e35efa4d 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.h +++ b/third_party/WebKit/Source/modules/accessibility/AXSVGRoot.h
@@ -45,13 +45,13 @@ static AXSVGRoot* Create(LayoutObject*, AXObjectCacheImpl&); ~AXSVGRoot() override; - void SetParent(AXObjectImpl*) override; + void SetParent(AXObject*) override; AccessibilityRole DetermineAccessibilityRole() override; bool ComputeAccessibilityIsIgnored(IgnoredReasons*) const override; private: - AXObjectImpl* ComputeParent() const override; + AXObject* ComputeParent() const override; bool IsAXSVGRoot() const override { return true; } };
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSlider.cpp b/third_party/WebKit/Source/modules/accessibility/AXSlider.cpp index 3ceb2181..140a364 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSlider.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXSlider.cpp
@@ -100,8 +100,7 @@ children_.push_back(thumb); } -AXObjectImpl* AXSlider::ElementAccessibilityHitTest( - const IntPoint& point) const { +AXObject* AXSlider::ElementAccessibilityHitTest(const IntPoint& point) const { if (children_.size()) { DCHECK(children_.size() == 1); if (children_[0]->GetBoundsInFrameCoordinates().Contains(point))
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSlider.h b/third_party/WebKit/Source/modules/accessibility/AXSlider.h index bcccbad..d89316c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSlider.h +++ b/third_party/WebKit/Source/modules/accessibility/AXSlider.h
@@ -49,7 +49,7 @@ private: HTMLInputElement* GetInputElement() const; - AXObjectImpl* ElementAccessibilityHitTest(const IntPoint&) const final; + AXObject* ElementAccessibilityHitTest(const IntPoint&) const final; AccessibilityRole DetermineAccessibilityRole() final; bool IsSlider() const final { return true; }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp index a4a11d6..1e8e30c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp
@@ -54,12 +54,12 @@ } void AXSpinButton::Detach() { - AXObjectImpl::Detach(); + AXObject::Detach(); spin_button_element_ = nullptr; } void AXSpinButton::DetachFromParent() { - AXObjectImpl::DetachFromParent(); + AXObject::DetachFromParent(); spin_button_element_ = nullptr; } @@ -102,7 +102,7 @@ } void AXSpinButtonPart::GetRelativeBounds( - AXObjectImpl** out_container, + AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const { *out_container = nullptr;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h index 679f6038..85fcad8 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h +++ b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h
@@ -73,7 +73,7 @@ bool Press() override; AccessibilityRole RoleValue() const override { return kButtonRole; } bool IsSpinButtonPart() const override { return true; } - void GetRelativeBounds(AXObjectImpl** out_container, + void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, SkMatrix44& out_container_transform) const override; };
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp index 5f48cfb..fc5828c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp
@@ -388,7 +388,7 @@ // Add caption if (HTMLTableCaptionElement* caption = toHTMLTableElement(table_node)->caption()) { - AXObjectImpl* caption_object = ax_cache.GetOrCreate(caption); + AXObject* caption_object = ax_cache.GetOrCreate(caption); if (caption_object && !caption_object->AccessibilityIsIgnored()) children_.push_back(caption_object); } @@ -402,14 +402,14 @@ LayoutTableSection* initial_table_section = table_section; while (table_section) { - HeapHashSet<Member<AXObjectImpl>> appended_rows; + HeapHashSet<Member<AXObject>> appended_rows; unsigned num_rows = table_section->NumRows(); for (unsigned row_index = 0; row_index < num_rows; ++row_index) { LayoutTableRow* layout_row = table_section->RowLayoutObjectAt(row_index); if (!layout_row) continue; - AXObjectImpl* row_object = ax_cache.GetOrCreate(layout_row); + AXObject* row_object = ax_cache.GetOrCreate(layout_row); if (!row_object || !row_object->IsTableRow()) continue; @@ -440,13 +440,13 @@ children_.push_back(column); } - AXObjectImpl* header_container_object = HeaderContainer(); + AXObject* header_container_object = HeaderContainer(); if (header_container_object && !header_container_object->AccessibilityIsIgnored()) children_.push_back(header_container_object); } -AXObjectImpl* AXTable::HeaderContainer() { +AXObject* AXTable::HeaderContainer() { if (header_container_) return header_container_.Get(); @@ -458,13 +458,13 @@ return header_container_.Get(); } -const AXObjectImpl::AXObjectVector& AXTable::Columns() { +const AXObject::AXObjectVector& AXTable::Columns() { UpdateChildrenIfNecessary(); return columns_; } -const AXObjectImpl::AXObjectVector& AXTable::Rows() { +const AXObject::AXObjectVector& AXTable::Rows() { UpdateChildrenIfNecessary(); return rows_; @@ -477,7 +477,7 @@ UpdateChildrenIfNecessary(); unsigned column_count = columns_.size(); for (unsigned c = 0; c < column_count; c++) { - AXObjectImpl* column = columns_[c].Get(); + AXObject* column = columns_[c].Get(); if (column->IsTableCol()) ToAXTableColumn(column)->HeaderObjectsForColumn(headers); } @@ -490,7 +490,7 @@ UpdateChildrenIfNecessary(); unsigned row_count = rows_.size(); for (unsigned r = 0; r < row_count; r++) { - AXObjectImpl* row = rows_[r].Get(); + AXObject* row = rows_[r].Get(); if (row->IsTableRow()) ToAXTableRow(rows_[r].Get())->HeaderObjectsForRow(headers); } @@ -562,7 +562,7 @@ std::min(static_cast<unsigned>(children.size()), column + 1); col_index_counter > 0; --col_index_counter) { unsigned col_index = col_index_counter - 1; - AXObjectImpl* child = children[col_index].Get(); + AXObject* child = children[col_index].Get(); if (!child->IsTableCell()) continue;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTable.h b/third_party/WebKit/Source/modules/accessibility/AXTable.h index cd22e7d8..f9c9024 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTable.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTable.h
@@ -77,13 +77,13 @@ void RowHeaders(AXObjectVector&); // an object that contains, as children, all the objects that act as headers - AXObjectImpl* HeaderContainer(); + AXObject* HeaderContainer(); protected: AXObjectVector rows_; AXObjectVector columns_; - Member<AXObjectImpl> header_container_; + Member<AXObject> header_container_; bool is_ax_table_; bool HasARIARole() const;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp index 73424e3..bbe7147 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableCell.cpp
@@ -78,7 +78,7 @@ return false; } -AXObjectImpl* AXTableCell::ParentTable() const { +AXObject* AXTableCell::ParentTable() const { if (!layout_object_ || !layout_object_->IsTableCell()) return 0; @@ -96,7 +96,7 @@ } bool AXTableCell::IsTableCell() const { - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (!parent || !parent->IsTableRow()) return false; @@ -110,7 +110,7 @@ return col_index; } - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (!parent || !parent->IsTableRow()) return 0; @@ -124,7 +124,7 @@ return row_index; } - AXObjectImpl* parent = ParentObjectUnignored(); + AXObject* parent = ParentObjectUnignored(); if (!parent || !parent->IsTableRow()) return 0;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableCell.h b/third_party/WebKit/Source/modules/accessibility/AXTableCell.h index ca0f14e..1c9f0af 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableCell.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTableCell.h
@@ -60,7 +60,7 @@ void SetARIAColIndexFromRow(int index) { aria_col_index_from_row_ = index; } protected: - virtual AXObjectImpl* ParentTable() const; + virtual AXObject* ParentTable() const; AccessibilityRole DetermineAccessibilityRole() final; private:
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp index 5f8563a..bccd5fc 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.cpp
@@ -45,7 +45,7 @@ return new AXTableColumn(ax_object_cache); } -void AXTableColumn::SetParent(AXObjectImpl* parent) { +void AXTableColumn::SetParent(AXObject* parent) { AXMockObject::SetParent(parent); ClearChildren(); @@ -87,7 +87,7 @@ if (!layout_cell) continue; - AXObjectImpl* cell = AxObjectCache().GetOrCreate(layout_cell->GetNode()); + AXObject* cell = AxObjectCache().GetOrCreate(layout_cell->GetNode()); if (!cell || !cell->IsTableCell() || headers.Contains(cell)) continue; @@ -97,7 +97,7 @@ } } -AXObjectImpl* AXTableColumn::HeaderObject() { +AXObject* AXTableColumn::HeaderObject() { AXObjectVector headers; HeaderObjectsForColumn(headers); if (!headers.size())
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h index fbcfd3c4..c800bf4 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTableColumn.h
@@ -48,7 +48,7 @@ ~AXTableColumn() override; // retrieves the topmost "column" header (th) - AXObjectImpl* HeaderObject(); + AXObject* HeaderObject(); // retrieves the "column" headers (th, scope) from top to bottom void HeaderObjectsForColumn(AXObjectVector&); @@ -58,7 +58,7 @@ int ColumnIndex() const { return column_index_; } void AddChildren() override; - void SetParent(AXObjectImpl*) override; + void SetParent(AXObject*) override; private: unsigned column_index_;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp b/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp index f84006b..cc5c2aa 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTableRow.cpp
@@ -76,7 +76,7 @@ } bool AXTableRow::IsTableRow() const { - AXObjectImpl* table = ParentTable(); + AXObject* table = ParentTable(); if (!table || !table->IsAXTable()) return false; @@ -97,15 +97,15 @@ return false; } -AXObjectImpl* AXTableRow::ParentTable() const { - AXObjectImpl* parent = ParentObjectUnignored(); +AXObject* AXTableRow::ParentTable() const { + AXObject* parent = ParentObjectUnignored(); if (!parent || !parent->IsAXTable()) return 0; return parent; } -AXObjectImpl* AXTableRow::HeaderObject() { +AXObject* AXTableRow::HeaderObject() { AXObjectVector headers; HeaderObjectsForRow(headers); if (!headers.size())
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTableRow.h b/third_party/WebKit/Source/modules/accessibility/AXTableRow.h index 6caef64f..279572db 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTableRow.h +++ b/third_party/WebKit/Source/modules/accessibility/AXTableRow.h
@@ -49,11 +49,11 @@ bool IsTableRow() const final; // retrieves the "row" header (a th tag in the rightmost column) - virtual AXObjectImpl* HeaderObject(); + virtual AXObject* HeaderObject(); // Retrieves the "row" headers (th, scope) from left to right for the each // row. virtual void HeaderObjectsForRow(AXObjectVector&); - AXObjectImpl* ParentTable() const; + AXObject* ParentTable() const; void SetRowIndex(int row_index) { row_index_ = row_index; } int RowIndex() const { return row_index_; }
diff --git a/third_party/WebKit/Source/modules/accessibility/BUILD.gn b/third_party/WebKit/Source/modules/accessibility/BUILD.gn index 80d1b04..f6eff8b 100644 --- a/third_party/WebKit/Source/modules/accessibility/BUILD.gn +++ b/third_party/WebKit/Source/modules/accessibility/BUILD.gn
@@ -12,6 +12,8 @@ "AXARIAGridCell.h", "AXARIAGridRow.cpp", "AXARIAGridRow.h", + "AXEnums.cpp", + "AXEnums.h", "AXImageMapLink.cpp", "AXImageMapLink.h", "AXInlineTextBox.cpp", @@ -40,8 +42,6 @@ "AXObject.h", "AXObjectCacheImpl.cpp", "AXObjectCacheImpl.h", - "AXObjectImpl.cpp", - "AXObjectImpl.h", "AXProgressIndicator.cpp", "AXProgressIndicator.h", "AXRadioInput.cpp",
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp index 616a7bc..d5ebdba 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp
@@ -16,8 +16,8 @@ #include "core/inspector/InspectorDOMAgent.h" #include "core/inspector/InspectorStyleSheet.h" #include "core/page/Page.h" +#include "modules/accessibility/AXObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" #include "modules/accessibility/InspectorTypeBuilderHelper.h" namespace blink { @@ -43,7 +43,7 @@ static const AXID kIDForInspectedNodeWithNoAXNode = 0; -void FillLiveRegionProperties(AXObjectImpl& ax_object, +void FillLiveRegionProperties(AXObject& ax_object, protocol::Array<AXProperty>& properties) { if (!ax_object.LiveRegionRoot()) return; @@ -70,13 +70,13 @@ } } -void FillGlobalStates(AXObjectImpl& ax_object, +void FillGlobalStates(AXObject& ax_object, protocol::Array<AXProperty>& properties) { if (!ax_object.IsEnabled()) properties.addItem( CreateProperty(AXGlobalStatesEnum::Disabled, CreateBooleanValue(true))); - if (const AXObjectImpl* hidden_root = ax_object.AriaHiddenRoot()) { + if (const AXObject* hidden_root = ax_object.AriaHiddenRoot()) { properties.addItem( CreateProperty(AXGlobalStatesEnum::Hidden, CreateBooleanValue(true))); properties.addItem( @@ -156,7 +156,7 @@ role == kRowHeaderRole || role == kTreeItemRole; } -void FillWidgetProperties(AXObjectImpl& ax_object, +void FillWidgetProperties(AXObject& ax_object, protocol::Array<AXProperty>& properties) { AccessibilityRole role = ax_object.RoleValue(); String autocomplete = ax_object.AriaAutoComplete(); @@ -242,7 +242,7 @@ } } -void FillWidgetStates(AXObjectImpl& ax_object, +void FillWidgetStates(AXObject& ax_object, protocol::Array<AXProperty>& properties) { AccessibilityRole role = ax_object.RoleValue(); const char* checked_prop_val = 0; @@ -306,9 +306,9 @@ std::unique_ptr<AXProperty> CreateRelatedNodeListProperty( const String& key, - AXObjectImpl::AXObjectVector& nodes, + AXObject::AXObjectVector& nodes, const QualifiedName& attr, - AXObjectImpl& ax_object) { + AXObject& ax_object) { std::unique_ptr<AXValue> node_list_value = CreateRelatedNodeListValue(nodes); const AtomicString& attr_value = ax_object.GetAttribute(attr); node_list_value->setValue(protocol::StringValue::create(attr_value)); @@ -319,14 +319,14 @@ : public GarbageCollected<SparseAttributeAXPropertyAdapter>, public AXSparseAttributeClient { public: - SparseAttributeAXPropertyAdapter(AXObjectImpl& ax_object, + SparseAttributeAXPropertyAdapter(AXObject& ax_object, protocol::Array<AXProperty>& properties) : ax_object_(&ax_object), properties_(properties) {} DEFINE_INLINE_TRACE() { visitor->Trace(ax_object_); } private: - Member<AXObjectImpl> ax_object_; + Member<AXObject> ax_object_; protocol::Array<AXProperty>& properties_; void AddBoolAttribute(AXBoolAttribute attribute, bool value) { @@ -348,7 +348,7 @@ } } - void AddObjectAttribute(AXObjectAttribute attribute, AXObjectImpl& object) { + void AddObjectAttribute(AXObjectAttribute attribute, AXObject& object) { switch (attribute) { case AXObjectAttribute::kAriaActiveDescendant: properties_.addItem( @@ -369,7 +369,7 @@ } void AddObjectVectorAttribute(AXObjectVectorAttribute attribute, - HeapVector<Member<AXObjectImpl>>& objects) { + HeapVector<Member<AXObject>>& objects) { switch (attribute) { case AXObjectVectorAttribute::kAriaControls: properties_.addItem(CreateRelatedNodeListProperty( @@ -385,9 +385,9 @@ } }; -void FillRelationships(AXObjectImpl& ax_object, +void FillRelationships(AXObject& ax_object, protocol::Array<AXProperty>& properties) { - AXObjectImpl::AXObjectVector results; + AXObject::AXObjectVector results; ax_object.AriaDescribedbyElements(results); if (!results.IsEmpty()) properties.addItem(CreateRelatedNodeListProperty( @@ -403,12 +403,12 @@ } std::unique_ptr<AXValue> CreateRoleNameValue(AccessibilityRole role) { - AtomicString role_name = AXObjectImpl::RoleName(role); + AtomicString role_name = AXObject::RoleName(role); std::unique_ptr<AXValue> role_name_value; if (!role_name.IsNull()) { role_name_value = CreateValue(role_name, AXValueTypeEnum::Role); } else { - role_name_value = CreateValue(AXObjectImpl::InternalRoleName(role), + role_name_value = CreateValue(AXObject::InternalRoleName(role), AXValueTypeEnum::InternalRole); } return role_name_value; @@ -443,7 +443,7 @@ ScopedAXObjectCache::Create(document); AXObjectCacheImpl* cache = ToAXObjectCacheImpl(scoped_cache->Get()); - AXObjectImpl* inspected_ax_object = cache->GetOrCreate(dom_node); + AXObject* inspected_ax_object = cache->GetOrCreate(dom_node); *nodes = protocol::Array<protocol::Accessibility::AXNode>::create(); if (!inspected_ax_object || inspected_ax_object->AccessibilityIsIgnored()) { (*nodes)->addItem(BuildObjectForIgnoredNode(dom_node, inspected_ax_object, @@ -451,15 +451,15 @@ *nodes, *cache)); return Response::OK(); } else { - (*nodes)->addItem(BuildProtocolAXObjectImpl( - *inspected_ax_object, inspected_ax_object, - fetch_relatives.fromMaybe(true), *nodes, *cache)); + (*nodes)->addItem( + BuildProtocolAXObject(*inspected_ax_object, inspected_ax_object, + fetch_relatives.fromMaybe(true), *nodes, *cache)); } if (!inspected_ax_object) return Response::OK(); - AXObjectImpl* parent = inspected_ax_object->ParentObjectUnignored(); + AXObject* parent = inspected_ax_object->ParentObjectUnignored(); if (!parent) return Response::OK(); @@ -470,25 +470,25 @@ } void InspectorAccessibilityAgent::AddAncestors( - AXObjectImpl& first_ancestor, - AXObjectImpl* inspected_ax_object, + AXObject& first_ancestor, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { - AXObjectImpl* ancestor = &first_ancestor; + AXObject* ancestor = &first_ancestor; while (ancestor) { - nodes->addItem(BuildProtocolAXObjectImpl(*ancestor, inspected_ax_object, - true, nodes, cache)); + nodes->addItem(BuildProtocolAXObject(*ancestor, inspected_ax_object, true, + nodes, cache)); ancestor = ancestor->ParentObjectUnignored(); } } std::unique_ptr<AXNode> InspectorAccessibilityAgent::BuildObjectForIgnoredNode( Node* dom_node, - AXObjectImpl* ax_object, + AXObject* ax_object, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { - AXObjectImpl::IgnoredReasons ignored_reasons; + AXObject::IgnoredReasons ignored_reasons; AXID ax_id = kIDForInspectedNodeWithNoAXNode; if (ax_object && ax_object->IsAXLayoutObject()) ax_id = ax_object->AxObjectID(); @@ -503,7 +503,7 @@ if (ax_object && ax_object->IsAXLayoutObject()) { ax_object->ComputeAccessibilityIsIgnored(&ignored_reasons); - AXObjectImpl* parent_object = ax_object->ParentObjectUnignored(); + AXObject* parent_object = ax_object->ParentObjectUnignored(); if (parent_object && fetch_relatives) AddAncestors(*parent_object, ax_object, nodes, cache); } else if (dom_node && !dom_node->GetLayoutObject()) { @@ -531,11 +531,11 @@ AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { - // Walk up parents until an AXObjectImpl can be found. + // Walk up parents until an AXObject can be found. Node* parent_node = inspected_dom_node.IsShadowRoot() ? &ToShadowRoot(inspected_dom_node).host() : FlatTreeTraversal::Parent(inspected_dom_node); - AXObjectImpl* parent_ax_object = cache.GetOrCreate(parent_node); + AXObject* parent_ax_object = cache.GetOrCreate(parent_node); while (parent_node && !parent_ax_object) { parent_node = parent_node->IsShadowRoot() ? &ToShadowRoot(parent_node)->host() @@ -553,22 +553,21 @@ // Populate parent and ancestors. std::unique_ptr<AXNode> parent_node_object = - BuildProtocolAXObjectImpl(*parent_ax_object, nullptr, true, nodes, cache); + BuildProtocolAXObject(*parent_ax_object, nullptr, true, nodes, cache); std::unique_ptr<protocol::Array<AXNodeId>> child_ids = protocol::Array<AXNodeId>::create(); child_ids->addItem(String::Number(kIDForInspectedNodeWithNoAXNode)); parent_node_object->setChildIds(std::move(child_ids)); nodes->addItem(std::move(parent_node_object)); - AXObjectImpl* grandparent_ax_object = - parent_ax_object->ParentObjectUnignored(); + AXObject* grandparent_ax_object = parent_ax_object->ParentObjectUnignored(); if (grandparent_ax_object) AddAncestors(*grandparent_ax_object, nullptr, nodes, cache); } -std::unique_ptr<AXNode> InspectorAccessibilityAgent::BuildProtocolAXObjectImpl( - AXObjectImpl& ax_object, - AXObjectImpl* inspected_ax_object, +std::unique_ptr<AXNode> InspectorAccessibilityAgent::BuildProtocolAXObject( + AXObject& ax_object, + AXObject* inspected_ax_object, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { @@ -591,7 +590,7 @@ SparseAttributeAXPropertyAdapter adapter(ax_object, *properties); ax_object.GetSparseAXAttributes(adapter); - AXObjectImpl::NameSources name_sources; + AXObject::NameSources name_sources; String computed_name = ax_object.GetName(&name_sources); if (!name_sources.IsEmpty()) { std::unique_ptr<AXValue> name = @@ -624,18 +623,18 @@ } void InspectorAccessibilityAgent::FillCoreProperties( - AXObjectImpl& ax_object, - AXObjectImpl* inspected_ax_object, + AXObject& ax_object, + AXObject* inspected_ax_object, bool fetch_relatives, AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { AXNameFrom name_from; - AXObjectImpl::AXObjectVector name_objects; + AXObject::AXObjectVector name_objects; ax_object.GetName(name_from, &name_objects); AXDescriptionFrom description_from; - AXObjectImpl::AXObjectVector description_objects; + AXObject::AXObjectVector description_objects; String description = ax_object.Description(name_from, description_from, &description_objects); if (!description.IsEmpty()) { @@ -661,12 +660,12 @@ } void InspectorAccessibilityAgent::PopulateRelatives( - AXObjectImpl& ax_object, - AXObjectImpl* inspected_ax_object, + AXObject& ax_object, + AXObject* inspected_ax_object, AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { - AXObjectImpl* parent_object = ax_object.ParentObject(); + AXObject* parent_object = ax_object.ParentObject(); if (parent_object && parent_object != inspected_ax_object) { // Use unignored parent unless parent is inspected ignored object. parent_object = ax_object.ParentObjectUnignored(); @@ -683,8 +682,8 @@ } void InspectorAccessibilityAgent::AddChildren( - AXObjectImpl& ax_object, - AXObjectImpl* inspected_ax_object, + AXObject& ax_object, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNodeId>>& child_ids, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { @@ -694,9 +693,9 @@ return; } - const AXObjectImpl::AXObjectVector& children = ax_object.Children(); + const AXObject::AXObjectVector& children = ax_object.Children(); for (unsigned i = 0; i < children.size(); i++) { - AXObjectImpl& child_ax_object = *children[i].Get(); + AXObject& child_ax_object = *children[i].Get(); child_ids->addItem(String::Number(child_ax_object.AxObjectID())); if (&child_ax_object == inspected_ax_object) continue; @@ -709,7 +708,7 @@ // Only add children of inspected node (or un-inspectable children of // inspected node) to returned nodes. - std::unique_ptr<AXNode> child_node = BuildProtocolAXObjectImpl( + std::unique_ptr<AXNode> child_node = BuildProtocolAXObject( child_ax_object, inspected_ax_object, true, nodes, cache); nodes->addItem(std::move(child_node)); }
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.h b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.h index c93ef9d..5eac7ee9 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.h +++ b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.h
@@ -11,7 +11,7 @@ namespace blink { -class AXObjectImpl; +class AXObject; class AXObjectCacheImpl; class InspectorDOMAgent; class Page; @@ -39,7 +39,7 @@ private: std::unique_ptr<AXNode> BuildObjectForIgnoredNode( Node* dom_node, - AXObjectImpl*, + AXObject*, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; @@ -47,40 +47,40 @@ AXNode&, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; - std::unique_ptr<AXNode> BuildProtocolAXObjectImpl( - AXObjectImpl&, - AXObjectImpl* inspected_ax_object, + std::unique_ptr<AXNode> BuildProtocolAXObject( + AXObject&, + AXObject* inspected_ax_object, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; - void FillCoreProperties(AXObjectImpl&, - AXObjectImpl* inspected_ax_object, + void FillCoreProperties(AXObject&, + AXObject* inspected_ax_object, bool fetch_relatives, AXNode&, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; - void AddAncestors(AXObjectImpl& first_ancestor, - AXObjectImpl* inspected_ax_object, + void AddAncestors(AXObject& first_ancestor, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; - void PopulateRelatives(AXObjectImpl&, - AXObjectImpl* inspected_ax_object, + void PopulateRelatives(AXObject&, + AXObject* inspected_ax_object, AXNode&, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; void AddSiblingsOfIgnored( std::unique_ptr<protocol::Array<AXNodeId>>& child_ids, - AXObjectImpl& parent_ax_object, - AXObjectImpl* inspected_ax_object, + AXObject& parent_ax_object, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; void addChild(std::unique_ptr<protocol::Array<AXNodeId>>& child_ids, - AXObjectImpl& child_ax_object, - AXObjectImpl* inspected_ax_object, + AXObject& child_ax_object, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const; - void AddChildren(AXObjectImpl&, - AXObjectImpl* inspected_ax_object, + void AddChildren(AXObject&, + AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNodeId>>& child_ids, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl&) const;
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp index 897aa82..57293b0 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp
@@ -5,8 +5,8 @@ #include "modules/accessibility/InspectorTypeBuilderHelper.h" #include "core/dom/DOMNodeIds.h" +#include "modules/accessibility/AXObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" namespace blink { @@ -99,9 +99,8 @@ .build(); } -std::unique_ptr<AXRelatedNode> RelatedNodeForAXObjectImpl( - const AXObjectImpl& ax_object, - String* name = nullptr) { +std::unique_ptr<AXRelatedNode> RelatedNodeForAXObject(const AXObject& ax_object, + String* name = nullptr) { Node* node = ax_object.GetNode(); if (!node) return nullptr; @@ -123,13 +122,12 @@ return related_node; } -std::unique_ptr<AXValue> CreateRelatedNodeListValue( - const AXObjectImpl& ax_object, - String* name, - const String& value_type) { +std::unique_ptr<AXValue> CreateRelatedNodeListValue(const AXObject& ax_object, + String* name, + const String& value_type) { std::unique_ptr<protocol::Array<AXRelatedNode>> related_nodes = protocol::Array<AXRelatedNode>::create(); - related_nodes->addItem(RelatedNodeForAXObjectImpl(ax_object, name)); + related_nodes->addItem(RelatedNodeForAXObject(ax_object, name)); return AXValue::create() .setType(value_type) .setRelatedNodes(std::move(related_nodes)) @@ -143,8 +141,8 @@ protocol::Array<AXRelatedNode>::create(); for (unsigned i = 0; i < related_objects.size(); i++) { std::unique_ptr<AXRelatedNode> frontend_related_node = - RelatedNodeForAXObjectImpl(*(related_objects[i]->object), - &(related_objects[i]->text)); + RelatedNodeForAXObject(*(related_objects[i]->object), + &(related_objects[i]->text)); if (frontend_related_node) frontend_related_nodes->addItem(std::move(frontend_related_node)); } @@ -155,13 +153,13 @@ } std::unique_ptr<AXValue> CreateRelatedNodeListValue( - AXObjectImpl::AXObjectVector& ax_objects, + AXObject::AXObjectVector& ax_objects, const String& value_type) { std::unique_ptr<protocol::Array<AXRelatedNode>> related_nodes = protocol::Array<AXRelatedNode>::create(); for (unsigned i = 0; i < ax_objects.size(); i++) { std::unique_ptr<AXRelatedNode> related_node = - RelatedNodeForAXObjectImpl(*(ax_objects[i].Get())); + RelatedNodeForAXObject(*(ax_objects[i].Get())); if (related_node) related_nodes->addItem(std::move(related_node)); }
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.h b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.h index ca41d046..70aff11 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.h +++ b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.h
@@ -7,8 +7,8 @@ #include "core/inspector/protocol/Accessibility.h" #include "modules/ModulesExport.h" +#include "modules/accessibility/AXObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" namespace blink { @@ -31,13 +31,13 @@ bool value, const String& value_type = AXValueTypeEnum::Boolean); std::unique_ptr<AXValue> CreateRelatedNodeListValue( - const AXObjectImpl&, + const AXObject&, String* name = nullptr, const String& value_type = AXValueTypeEnum::Idref); std::unique_ptr<AXValue> CreateRelatedNodeListValue(AXRelatedObjectVector&, const String& value_type); std::unique_ptr<AXValue> CreateRelatedNodeListValue( - AXObjectImpl::AXObjectVector& ax_objects, + AXObject::AXObjectVector& ax_objects, const String& value_type = AXValueTypeEnum::IdrefList); std::unique_ptr<AXValueSource> CreateValueSource(NameSource&);
diff --git a/third_party/WebKit/Source/modules/accessibility/testing/InternalsAccessibility.cpp b/third_party/WebKit/Source/modules/accessibility/testing/InternalsAccessibility.cpp index c1ba20ec..fe5a0d2 100644 --- a/third_party/WebKit/Source/modules/accessibility/testing/InternalsAccessibility.cpp +++ b/third_party/WebKit/Source/modules/accessibility/testing/InternalsAccessibility.cpp
@@ -5,12 +5,12 @@ #include "InternalsAccessibility.h" #include "core/testing/Internals.h" -#include "modules/accessibility/AXObjectImpl.h" +#include "modules/accessibility/AXObject.h" namespace blink { unsigned InternalsAccessibility::numberOfLiveAXObjects(Internals&) { - return AXObjectImpl::NumberOfLiveAXObjects(); + return AXObject::NumberOfLiveAXObjects(); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DAPITest.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DAPITest.cpp index f79796e4..6b62ebfe 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DAPITest.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DAPITest.cpp
@@ -12,8 +12,8 @@ #include "core/html/ImageData.h" #include "core/loader/EmptyClients.h" #include "core/testing/DummyPageHolder.h" +#include "modules/accessibility/AXObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" #include "modules/canvas2d/CanvasGradient.h" #include "modules/canvas2d/CanvasPattern.h" #include "modules/canvas2d/HitRegionOptions.h" @@ -331,7 +331,7 @@ AXObjectCacheImpl* ax_object_cache = ToAXObjectCacheImpl(GetDocument().ExistingAXObjectCache()); - AXObjectImpl* ax_object = ax_object_cache->GetOrCreate(button_element); + AXObject* ax_object = ax_object_cache->GetOrCreate(button_element); LayoutRect ax_bounds = ax_object->GetBoundsInFrameCoordinates(); EXPECT_EQ(25, ax_bounds.X().ToInt()); @@ -358,7 +358,7 @@ AXObjectCacheImpl* ax_object_cache = ToAXObjectCacheImpl(GetDocument().ExistingAXObjectCache()); - AXObjectImpl* ax_object = ax_object_cache->GetOrCreate(button_element); + AXObject* ax_object = ax_object_cache->GetOrCreate(button_element); LayoutRect ax_bounds = ax_object->GetBoundsInFrameCoordinates(); EXPECT_EQ(25, ax_bounds.X().ToInt());
diff --git a/third_party/WebKit/Source/modules/eventsource/EventSource.cpp b/third_party/WebKit/Source/modules/eventsource/EventSource.cpp index e1a76073..266eff9 100644 --- a/third_party/WebKit/Source/modules/eventsource/EventSource.cpp +++ b/third_party/WebKit/Source/modules/eventsource/EventSource.cpp
@@ -133,6 +133,9 @@ request.SetHTTPHeaderField(HTTPNames::Accept, "text/event-stream"); request.SetHTTPHeaderField(HTTPNames::Cache_Control, "no-cache"); request.SetRequestContext(WebURLRequest::kRequestContextEventSource); + request.SetFetchCredentialsMode( + with_credentials_ ? WebURLRequest::kFetchCredentialsModeInclude + : WebURLRequest::kFetchCredentialsModeSameOrigin); request.SetExternalRequestStateFromRequestorAddressSpace( execution_context.GetSecurityContext().AddressSpace()); if (parser_ && !parser_->LastEventId().IsEmpty()) { @@ -157,15 +160,7 @@ ? kDoNotEnforceContentSecurityPolicy : kEnforceContentSecurityPolicy; - StoredCredentials allow_credentials = - (origin->CanRequestNoSuborigin(current_url_) || with_credentials_) - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; - CredentialRequest credentials_requested = - with_credentials_ ? kClientRequestedCredentials - : kClientDidNotRequestCredentials; - ResourceLoaderOptions resource_loader_options(allow_credentials, - credentials_requested); + ResourceLoaderOptions resource_loader_options; resource_loader_options.data_buffering_policy = kDoNotBufferData; resource_loader_options.security_origin = origin;
diff --git a/third_party/WebKit/Source/modules/exported/README.md b/third_party/WebKit/Source/modules/exported/README.md new file mode 100644 index 0000000..eb00790 --- /dev/null +++ b/third_party/WebKit/Source/modules/exported/README.md
@@ -0,0 +1,2 @@ +Files that are implementations of abstract classes defined in public/web/ that +have dependencies on modules/.
diff --git a/third_party/WebKit/Source/modules/exported/WebAXObject.cpp b/third_party/WebKit/Source/modules/exported/WebAXObject.cpp index 088e3a3a..4263073 100644 --- a/third_party/WebKit/Source/modules/exported/WebAXObject.cpp +++ b/third_party/WebKit/Source/modules/exported/WebAXObject.cpp
@@ -46,8 +46,8 @@ #include "core/layout/api/LayoutViewItem.h" #include "core/page/Page.h" #include "core/style/ComputedStyle.h" +#include "modules/accessibility/AXObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" -#include "modules/accessibility/AXObjectImpl.h" #include "modules/accessibility/AXTable.h" #include "modules/accessibility/AXTableCell.h" #include "modules/accessibility/AXTableColumn.h" @@ -86,14 +86,13 @@ } void AddObjectAttribute(AXObjectAttribute attribute, - AXObjectImpl& value) override { + AXObject& value) override { attribute_map_.AddObjectAttribute( static_cast<WebAXObjectAttribute>(attribute), WebAXObject(&value)); } - void AddObjectVectorAttribute( - AXObjectVectorAttribute attribute, - HeapVector<Member<AXObjectImpl>>& value) override { + void AddObjectVectorAttribute(AXObjectVectorAttribute attribute, + HeapVector<Member<AXObject>>& value) override { WebVector<WebAXObject> result(value.size()); for (size_t i = 0; i < value.size(); i++) result[i] = WebAXObject(value[i]); @@ -555,7 +554,7 @@ if (IsDetached()) return WebAXObject(); - AXObjectImpl* live_region_root = private_->LiveRegionRoot(); + AXObject* live_region_root = private_->LiveRegionRoot(); if (live_region_root) return WebAXObject(live_region_root); return WebAXObject(); @@ -674,7 +673,7 @@ IntPoint contents_point = private_->DocumentFrameView()->SoonToBeRemovedUnscaledViewportToContents( point); - AXObjectImpl* hit = private_->AccessibilityHitTest(contents_point); + AXObject* hit = private_->AccessibilityHitTest(contents_point); if (hit) return WebAXObject(hit); @@ -753,7 +752,7 @@ WebAXObject WebAXObject::InPageLinkTarget() const { if (IsDetached()) return WebAXObject(); - AXObjectImpl* target = private_->InPageLinkTarget(); + AXObject* target = private_->InPageLinkTarget(); if (!target) return WebAXObject(); return WebAXObject(target); @@ -777,7 +776,7 @@ if (IsDetached()) return WebVector<WebAXObject>(); - AXObjectImpl::AXObjectVector radio_buttons = private_->RadioButtonsInGroup(); + AXObject::AXObjectVector radio_buttons = private_->RadioButtonsInGroup(); WebVector<WebAXObject> web_radio_buttons(radio_buttons.size()); for (size_t i = 0; i < radio_buttons.size(); ++i) web_radio_buttons[i] = WebAXObject(radio_buttons[i]); @@ -807,7 +806,7 @@ return; } - AXObjectImpl::AXRange ax_selection = private_->Selection(); + AXObject::AXRange ax_selection = private_->Selection(); anchor_object = WebAXObject(ax_selection.anchor_object); anchor_offset = ax_selection.anchor_offset; anchor_affinity = @@ -825,9 +824,9 @@ if (IsDetached()) return; - AXObjectImpl::AXRange ax_selection(anchor_object, anchor_offset, - TextAffinity::kUpstream, focus_object, - focus_offset, TextAffinity::kDownstream); + AXObject::AXRange ax_selection(anchor_object, anchor_offset, + TextAffinity::kUpstream, focus_object, + focus_offset, TextAffinity::kDownstream); private_->SetSelection(ax_selection); return; } @@ -836,7 +835,7 @@ if (IsDetached()) return 0; - AXObjectImpl::AXRange ax_selection = private_->SelectionUnderObject(); + AXObject::AXRange ax_selection = private_->SelectionUnderObject(); if (ax_selection.focus_offset < 0) return 0; @@ -847,7 +846,7 @@ if (IsDetached()) return 0; - AXObjectImpl::AXRange ax_selection = private_->SelectionUnderObject(); + AXObject::AXRange ax_selection = private_->SelectionUnderObject(); if (ax_selection.anchor_offset < 0) return 0; @@ -889,7 +888,7 @@ if (IsDetached()) return; - private_->SetSelection(AXObjectImpl::AXRange(selection_start, selection_end)); + private_->SetSelection(AXObject::AXRange(selection_start, selection_end)); } void WebAXObject::SetSequentialFocusNavigationStartingPoint() const { @@ -976,7 +975,7 @@ return WebString(); AXNameFrom name_from = kAXNameFromUninitialized; - HeapVector<Member<AXObjectImpl>> name_objects; + HeapVector<Member<AXObject>> name_objects; WebString result = private_->GetName(name_from, &name_objects); out_name_from = static_cast<WebAXNameFrom>(name_from); @@ -993,7 +992,7 @@ return WebString(); AXNameFrom name_from; - HeapVector<Member<AXObjectImpl>> name_objects; + HeapVector<Member<AXObject>> name_objects; return private_->GetName(name_from, &name_objects); } @@ -1005,7 +1004,7 @@ return WebString(); AXDescriptionFrom description_from = kAXDescriptionFromUninitialized; - HeapVector<Member<AXObjectImpl>> description_objects; + HeapVector<Member<AXObject>> description_objects; String result = private_->Description(static_cast<AXNameFrom>(name_from), description_from, &description_objects); out_description_from = static_cast<WebAXDescriptionFrom>(description_from); @@ -1213,7 +1212,7 @@ AXTableCell* cell = ToAXTable(private_.Get())->CellForColumnAndRow(column, row); - return WebAXObject(static_cast<AXObjectImpl*>(cell)); + return WebAXObject(static_cast<AXObject*>(cell)); } WebAXObject WebAXObject::HeaderContainerObject() const { @@ -1233,7 +1232,7 @@ if (!private_->IsAXTable()) return WebAXObject(); - const AXObjectImpl::AXObjectVector& rows = ToAXTable(private_.Get())->Rows(); + const AXObject::AXObjectVector& rows = ToAXTable(private_.Get())->Rows(); if (row_index < rows.size()) return WebAXObject(rows[row_index]); @@ -1247,7 +1246,7 @@ if (!private_->IsAXTable()) return WebAXObject(); - const AXObjectImpl::AXObjectVector& columns = + const AXObject::AXObjectVector& columns = ToAXTable(private_.Get())->Columns(); if (column_index < columns.size()) return WebAXObject(columns[column_index]); @@ -1283,7 +1282,7 @@ if (!private_->IsAXTable()) return; - AXObjectImpl::AXObjectVector headers; + AXObject::AXObjectVector headers; ToAXTable(private_.Get())->RowHeaders(headers); size_t header_count = headers.size(); @@ -1323,7 +1322,7 @@ if (!private_->IsAXTable()) return; - AXObjectImpl::AXObjectVector headers; + AXObject::AXObjectVector headers; ToAXTable(private_.Get())->ColumnHeaders(headers); size_t header_count = headers.size(); @@ -1418,7 +1417,7 @@ return; Vector<DocumentMarker::MarkerType> marker_types; - Vector<AXObjectImpl::AXRange> marker_ranges; + Vector<AXObject::AXRange> marker_ranges; private_->Markers(marker_types, marker_ranges); DCHECK_EQ(marker_types.size(), marker_ranges.size()); @@ -1456,7 +1455,7 @@ if (IsDetached()) return; - Vector<AXObjectImpl::AXRange> word_boundaries; + Vector<AXObject::AXRange> word_boundaries; private_->GetWordBoundaries(word_boundaries); WebVector<int> word_start_offsets(word_boundaries.size()); @@ -1516,7 +1515,7 @@ DCHECK(IsLayoutClean(private_->GetDocument())); #endif - AXObjectImpl* container = nullptr; + AXObject* container = nullptr; FloatRect bounds; private_->GetRelativeBounds(&container, bounds, container_transform); offset_container = WebAXObject(container); @@ -1539,14 +1538,14 @@ private_->ScrollToGlobalPoint(point); } -WebAXObject::WebAXObject(AXObjectImpl* object) : private_(object) {} +WebAXObject::WebAXObject(AXObject* object) : private_(object) {} -WebAXObject& WebAXObject::operator=(AXObjectImpl* object) { +WebAXObject& WebAXObject::operator=(AXObject* object) { private_ = object; return *this; } -WebAXObject::operator AXObjectImpl*() const { +WebAXObject::operator AXObject*() const { return private_.Get(); }
diff --git a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp index 114d28f..f7b78ee 100644 --- a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp
@@ -336,6 +336,7 @@ main_script_loader_->LoadAsynchronously( *main_frame_->GetFrame()->GetDocument(), worker_start_data_.script_url, WebURLRequest::kFetchRequestModeSameOrigin, + WebURLRequest::kFetchCredentialsModeSameOrigin, worker_start_data_.address_space, nullptr, Bind(&WebEmbeddedWorkerImpl::OnScriptLoaderFinished, WTF::Unretained(this)));
diff --git a/third_party/WebKit/Source/modules/fetch/BlobBytesConsumer.cpp b/third_party/WebKit/Source/modules/fetch/BlobBytesConsumer.cpp index ad7768b..cb3e6b530 100644 --- a/third_party/WebKit/Source/modules/fetch/BlobBytesConsumer.cpp +++ b/third_party/WebKit/Source/modules/fetch/BlobBytesConsumer.cpp
@@ -76,6 +76,7 @@ ResourceRequest request(blob_url_); request.SetRequestContext(WebURLRequest::kRequestContextInternal); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); request.SetUseStreamOnResponse(true); // We intentionally skip // 'setExternalRequestStateFromRequestorAddressSpace', as 'blob:' @@ -284,8 +285,7 @@ options.content_security_policy_enforcement = kDoNotEnforceContentSecurityPolicy; - ResourceLoaderOptions resource_loader_options( - kDoNotAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; resource_loader_options.data_buffering_policy = kDoNotBufferData; resource_loader_options.initiator_info.name = FetchInitiatorTypeNames::internal;
diff --git a/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp b/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp index 0c8bf34..d602c49f4 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchDataLoader.cpp
@@ -12,6 +12,7 @@ #include "modules/fetch/MultipartParser.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "platform/HTTPNames.h" +#include "platform/loader/fetch/TextResourceDecoderOptions.h" #include "platform/network/ParsedContentDisposition.h" #include "platform/wtf/Functional.h" #include "platform/wtf/PtrUtil.h" @@ -344,8 +345,10 @@ blob_data_->SetContentType(content_type.IsNull() ? "text/plain" : content_type); } else { - if (!string_decoder_) - string_decoder_ = TextResourceDecoder::CreateAlwaysUseUTF8ForText(); + if (!string_decoder_) { + string_decoder_ = TextResourceDecoder::Create( + TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText()); + } string_builder_.reset(new StringBuilder); } return true; @@ -409,7 +412,8 @@ DCHECK(!decoder_); DCHECK(!consumer_); client_ = client; - decoder_ = TextResourceDecoder::CreateAlwaysUseUTF8ForText(); + decoder_ = TextResourceDecoder::Create( + TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText()); consumer_ = consumer; consumer_->SetClient(this); OnStateChange();
diff --git a/third_party/WebKit/Source/modules/fetch/FetchManager.cpp b/third_party/WebKit/Source/modules/fetch/FetchManager.cpp index 9ba20f58..f438b19 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchManager.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchManager.cpp
@@ -768,32 +768,7 @@ // mode is |include|, or |HTTPRequest|'s credentials mode is |same-origin| // and the |CORS flag| is unset, and unset otherwise." - // TODO(tyoshino): It's wrong to use |cors_flag| here, now. The credentials - // mode must work even with the no-cors. See the following issues: - // - https://github.com/whatwg/fetch/issues/130 - // - https://github.com/whatwg/fetch/issues/169 - // - // https://w3c.github.io/webappsec-suborigins/#security-model-opt-outs: - // "request's credentials mode is "same-origin" and request's environment - // settings object has the suborigin unsafe credentials flag set and the - // request’s current url is same-physical-origin with request origin." - StoredCredentials allow_credentials = kDoNotAllowStoredCredentials; - if ((request_->Credentials() == - WebURLRequest::kFetchCredentialsModeSameOrigin && - (!cors_flag || - request_->Origin()->HasSuboriginAndShouldAllowCredentialsFor( - request_->Url()))) || - request_->Credentials() == WebURLRequest::kFetchCredentialsModeInclude || - request_->Credentials() == WebURLRequest::kFetchCredentialsModePassword) { - allow_credentials = kAllowStoredCredentials; - } - CredentialRequest credentials_requested = kClientDidNotRequestCredentials; - if (request_->Credentials() == WebURLRequest::kFetchCredentialsModeInclude || - request_->Credentials() == WebURLRequest::kFetchCredentialsModePassword) { - credentials_requested = kClientRequestedCredentials; - } - ResourceLoaderOptions resource_loader_options(allow_credentials, - credentials_requested); + ResourceLoaderOptions resource_loader_options; resource_loader_options.data_buffering_policy = kDoNotBufferData; resource_loader_options.security_origin = request_->Origin().Get(); @@ -845,12 +820,12 @@ request.SetRequestContext(request_->Context()); request.SetUseStreamOnResponse(true); request.SetHTTPMethod(request_->Method()); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); request.SetFetchRedirectMode(WebURLRequest::kFetchRedirectModeError); // We intentionally skip 'setExternalRequestStateFromRequestorAddressSpace', // as 'data:' can never be external. - ResourceLoaderOptions resource_loader_options( - kDoNotAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; resource_loader_options.data_buffering_policy = kDoNotBufferData; resource_loader_options.security_origin = request_->Origin().Get();
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBKey.h b/third_party/WebKit/Source/modules/indexeddb/IDBKey.h index 294fc24..f1cf4c9 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBKey.h +++ b/third_party/WebKit/Source/modules/indexeddb/IDBKey.h
@@ -45,7 +45,7 @@ return new IDBKey(kNumberType, number); } - static IDBKey* CreateBinary(PassRefPtr<SharedBuffer> binary) { + static IDBKey* CreateBinary(RefPtr<SharedBuffer> binary) { return new IDBKey(std::move(binary)); } @@ -83,7 +83,7 @@ return array_; } - PassRefPtr<SharedBuffer> Binary() const { + RefPtr<SharedBuffer> Binary() const { DCHECK_EQ(type_, kBinaryType); return binary_; }
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp index d0d1669..66ae7a81 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBValue.cpp
@@ -26,7 +26,7 @@ isolate_->AdjustAmountOfExternalAllocatedMemory(external_allocated_size_); } -IDBValue::IDBValue(PassRefPtr<SharedBuffer> data, +IDBValue::IDBValue(RefPtr<SharedBuffer> data, const WebVector<WebBlobInfo>& web_blob_info, IDBKey* primary_key, const IDBKeyPath& key_path) @@ -60,7 +60,7 @@ } } -IDBValue::IDBValue(PassRefPtr<SharedBuffer> unwrapped_data, +IDBValue::IDBValue(RefPtr<SharedBuffer> unwrapped_data, std::unique_ptr<Vector<RefPtr<BlobDataHandle>>> blob_data, std::unique_ptr<Vector<WebBlobInfo>> blob_info) : data_(std::move(unwrapped_data)),
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBValue.h b/third_party/WebKit/Source/modules/indexeddb/IDBValue.h index ef6ae3c..fb7f4a65 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBValue.h +++ b/third_party/WebKit/Source/modules/indexeddb/IDBValue.h
@@ -48,12 +48,12 @@ IDBValue(); IDBValue(const WebIDBValue&, v8::Isolate*); - IDBValue(PassRefPtr<SharedBuffer>, + IDBValue(RefPtr<SharedBuffer>, const WebVector<WebBlobInfo>&, IDBKey*, const IDBKeyPath&); IDBValue(const IDBValue*, IDBKey*, const IDBKeyPath&); - IDBValue(PassRefPtr<SharedBuffer> unwrapped_data, + IDBValue(RefPtr<SharedBuffer> unwrapped_data, std::unique_ptr<Vector<RefPtr<BlobDataHandle>>>, std::unique_ptr<Vector<WebBlobInfo>>);
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp b/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp index 4eb7074..40a76b1 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp +++ b/third_party/WebKit/Source/modules/notifications/NotificationImageLoader.cpp
@@ -111,12 +111,13 @@ // TODO(mvanouwerkerk): Add an entry for notifications to // FetchInitiatorTypeNames and use it. - ResourceLoaderOptions resource_loader_options( - kAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; if (execution_context->IsWorkerGlobalScope()) resource_loader_options.request_initiator_context = kWorkerContext; ResourceRequest resource_request(url); + resource_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeInclude); resource_request.SetRequestContext(WebURLRequest::kRequestContextImage); resource_request.SetPriority(kResourceLoadPriorityMedium); resource_request.SetRequestorOrigin(execution_context->GetSecurityOrigin());
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.cpp index 36385f3..207b979 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.cpp
@@ -52,12 +52,12 @@ ->ClearCachedMetadata(script_url_); } -PassRefPtr<CachedMetadata> +RefPtr<CachedMetadata> ServiceWorkerScriptCachedMetadataHandler::GetCachedMetadata( uint32_t data_type_id) const { if (!cached_metadata_ || cached_metadata_->DataTypeID() != data_type_id) return nullptr; - return cached_metadata_.Get(); + return cached_metadata_; } String ServiceWorkerScriptCachedMetadataHandler::Encoding() const {
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.h index a442a8a5..1bf9cce 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.h +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerScriptCachedMetadataHandler.h
@@ -32,7 +32,7 @@ size_t, CacheType) override; void ClearCachedMetadata(CacheType) override; - PassRefPtr<CachedMetadata> GetCachedMetadata( + RefPtr<CachedMetadata> GetCachedMetadata( uint32_t data_type_id) const override; String Encoding() const override;
diff --git a/third_party/WebKit/Source/platform/Cursor.cpp b/third_party/WebKit/Source/platform/Cursor.cpp index ab35a537..a21f9ec0 100644 --- a/third_party/WebKit/Source/platform/Cursor.cpp +++ b/third_party/WebKit/Source/platform/Cursor.cpp
@@ -24,6 +24,8 @@ */ #include "platform/Cursor.h" +#include "platform/wtf/Assertions.h" +#include "public/platform/WebCursorInfo.h" namespace blink { @@ -306,4 +308,59 @@ return c; } +STATIC_ASSERT_ENUM(WebCursorInfo::kTypePointer, Cursor::kPointer); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCross, Cursor::kCross); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeHand, Cursor::kHand); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeIBeam, Cursor::kIBeam); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWait, Cursor::kWait); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeHelp, Cursor::kHelp); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastResize, Cursor::kEastResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthResize, Cursor::kNorthResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastResize, + Cursor::kNorthEastResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestResize, + Cursor::kNorthWestResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthResize, Cursor::kSouthResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthEastResize, + Cursor::kSouthEastResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthWestResize, + Cursor::kSouthWestResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWestResize, Cursor::kWestResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthSouthResize, + Cursor::kNorthSouthResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastWestResize, Cursor::kEastWestResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastSouthWestResize, + Cursor::kNorthEastSouthWestResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestSouthEastResize, + Cursor::kNorthWestSouthEastResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeColumnResize, Cursor::kColumnResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeRowResize, Cursor::kRowResize); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeMiddlePanning, Cursor::kMiddlePanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastPanning, Cursor::kEastPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthPanning, Cursor::kNorthPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastPanning, + Cursor::kNorthEastPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestPanning, + Cursor::kNorthWestPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthPanning, Cursor::kSouthPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthEastPanning, + Cursor::kSouthEastPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthWestPanning, + Cursor::kSouthWestPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWestPanning, Cursor::kWestPanning); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeMove, Cursor::kMove); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeVerticalText, Cursor::kVerticalText); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCell, Cursor::kCell); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeContextMenu, Cursor::kContextMenu); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeAlias, Cursor::kAlias); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeProgress, Cursor::kProgress); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNoDrop, Cursor::kNoDrop); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCopy, Cursor::kCopy); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNone, Cursor::kNone); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNotAllowed, Cursor::kNotAllowed); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeZoomIn, Cursor::kZoomIn); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeZoomOut, Cursor::kZoomOut); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeGrab, Cursor::kGrab); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeGrabbing, Cursor::kGrabbing); +STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCustom, Cursor::kCustom); } // namespace blink
diff --git a/third_party/WebKit/Source/platform/SharedBuffer.cpp b/third_party/WebKit/Source/platform/SharedBuffer.cpp index 80eb82d..548af9c 100644 --- a/third_party/WebKit/Source/platform/SharedBuffer.cpp +++ b/third_party/WebKit/Source/platform/SharedBuffer.cpp
@@ -81,10 +81,10 @@ return buffer_.data(); } -void SharedBuffer::Append(PassRefPtr<SharedBuffer> data) { +void SharedBuffer::Append(const SharedBuffer& data) { const char* segment; size_t position = 0; - while (size_t length = data->GetSomeDataInternal(segment, position)) { + while (size_t length = data.GetSomeDataInternal(segment, position)) { Append(segment, length); position += length; }
diff --git a/third_party/WebKit/Source/platform/SharedBuffer.h b/third_party/WebKit/Source/platform/SharedBuffer.h index 10ad094..f6b40b8 100644 --- a/third_party/WebKit/Source/platform/SharedBuffer.h +++ b/third_party/WebKit/Source/platform/SharedBuffer.h
@@ -81,7 +81,7 @@ bool IsEmpty() const { return !size(); } - void Append(PassRefPtr<SharedBuffer>); + void Append(const SharedBuffer&); HAS_STRICTLY_TYPED_ARG void Append(const char* data, STRICTLY_TYPED_ARG(size)) {
diff --git a/third_party/WebKit/Source/platform/exported/WebData.cpp b/third_party/WebKit/Source/platform/exported/WebData.cpp index 9f9dca2..8ddff9fa 100644 --- a/third_party/WebKit/Source/platform/exported/WebData.cpp +++ b/third_party/WebKit/Source/platform/exported/WebData.cpp
@@ -58,16 +58,19 @@ return private_->Data(); } -WebData::WebData(PassRefPtr<SharedBuffer> buffer) - : private_(std::move(buffer)) {} +WebData::WebData(RefPtr<SharedBuffer> buffer) : private_(std::move(buffer)) {} -WebData& WebData::operator=(PassRefPtr<SharedBuffer> buffer) { +WebData& WebData::operator=(RefPtr<SharedBuffer> buffer) { private_ = std::move(buffer); return *this; } -WebData::operator PassRefPtr<SharedBuffer>() const { - return PassRefPtr<SharedBuffer>(private_.Get()); +WebData::operator RefPtr<SharedBuffer>() const { + return RefPtr<SharedBuffer>(private_.Get()); +} + +WebData::operator const SharedBuffer&() const { + return *private_; } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp b/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp index dffadfb1..1472b010 100644 --- a/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp +++ b/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp
@@ -157,15 +157,15 @@ private_->SetContainsPasswordData(contains_password_data); } -WebHTTPBody::WebHTTPBody(PassRefPtr<EncodedFormData> data) +WebHTTPBody::WebHTTPBody(RefPtr<EncodedFormData> data) : private_(static_cast<WebHTTPBodyPrivate*>(data.LeakRef())) {} -WebHTTPBody& WebHTTPBody::operator=(PassRefPtr<EncodedFormData> data) { +WebHTTPBody& WebHTTPBody::operator=(RefPtr<EncodedFormData> data) { DCHECK(static_cast<WebHTTPBodyPrivate*>(data.LeakRef())); return *this; } -WebHTTPBody::operator PassRefPtr<EncodedFormData>() const { +WebHTTPBody::operator RefPtr<EncodedFormData>() const { return private_; }
diff --git a/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp b/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp index 69dcaa98..fbc4477 100644 --- a/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp +++ b/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp
@@ -48,10 +48,10 @@ private_ = r.private_; } -WebHTTPLoadInfo::WebHTTPLoadInfo(WTF::PassRefPtr<ResourceLoadInfo> value) +WebHTTPLoadInfo::WebHTTPLoadInfo(WTF::RefPtr<ResourceLoadInfo> value) : private_(std::move(value)) {} -WebHTTPLoadInfo::operator WTF::PassRefPtr<ResourceLoadInfo>() const { +WebHTTPLoadInfo::operator WTF::RefPtr<ResourceLoadInfo>() const { return private_.Get(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebImage.cpp b/third_party/WebKit/Source/platform/exported/WebImage.cpp index 3a9131d9..fbb0f0d 100644 --- a/third_party/WebKit/Source/platform/exported/WebImage.cpp +++ b/third_party/WebKit/Source/platform/exported/WebImage.cpp
@@ -44,10 +44,8 @@ namespace blink { WebImage WebImage::FromData(const WebData& data, const WebSize& desired_size) { - RefPtr<SharedBuffer> buffer = PassRefPtr<SharedBuffer>(data); - std::unique_ptr<ImageDecoder> decoder( - ImageDecoder::Create(buffer, true, ImageDecoder::kAlphaPremultiplied, - ColorBehavior::Ignore())); + std::unique_ptr<ImageDecoder> decoder(ImageDecoder::Create( + data, true, ImageDecoder::kAlphaPremultiplied, ColorBehavior::Ignore())); if (!decoder || !decoder->IsSizeAvailable()) return WebImage(); @@ -83,10 +81,8 @@ // never hit in practice. const size_t kMaxFrameCount = 8; - RefPtr<SharedBuffer> buffer = PassRefPtr<SharedBuffer>(data); - std::unique_ptr<ImageDecoder> decoder( - ImageDecoder::Create(buffer, true, ImageDecoder::kAlphaPremultiplied, - ColorBehavior::Ignore())); + std::unique_ptr<ImageDecoder> decoder(ImageDecoder::Create( + data, true, ImageDecoder::kAlphaPremultiplied, ColorBehavior::Ignore())); if (!decoder || !decoder->IsSizeAvailable()) return WebVector<WebImage>();
diff --git a/third_party/WebKit/Source/platform/exported/WebInputEvent.cpp b/third_party/WebKit/Source/platform/exported/WebInputEvent.cpp index 41791554..9333f3d 100644 --- a/third_party/WebKit/Source/platform/exported/WebInputEvent.cpp +++ b/third_party/WebKit/Source/platform/exported/WebInputEvent.cpp
@@ -59,7 +59,7 @@ }; struct SameSizeAsWebGestureEvent : public SameSizeAsWebInputEvent { - int gesture_data[14]; + int gesture_data[15]; }; struct SameSizeAsWebTouchEvent : public SameSizeAsWebInputEvent {
diff --git a/third_party/WebKit/Source/platform/fonts/FontDescription.cpp b/third_party/WebKit/Source/platform/fonts/FontDescription.cpp index 060ef8e2..3dba0000 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDescription.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontDescription.cpp
@@ -31,9 +31,11 @@ #include "platform/Language.h" #include "platform/RuntimeEnabledFeatures.h" +#include "platform/wtf/Assertions.h" #include "platform/wtf/StringHasher.h" #include "platform/wtf/text/AtomicStringHash.h" #include "platform/wtf/text/StringHash.h" +#include "public/platform/WebFontDescription.h" namespace blink { @@ -355,16 +357,45 @@ break; } return SkFontStyle(NumericFontWeight(Weight()), width, slant); - static_assert( - static_cast<int>(kFontStretchUltraCondensed) == - static_cast<int>(SkFontStyle::kUltraCondensed_Width), - "FontStretchUltraCondensed should map to kUltraCondensed_Width"); - static_assert(static_cast<int>(kFontStretchNormal) == - static_cast<int>(SkFontStyle::kNormal_Width), - "FontStretchNormal should map to kNormal_Width"); - static_assert(static_cast<int>(kFontStretchUltraExpanded) == - static_cast<int>(SkFontStyle::kUltraExpanded_Width), - "FontStretchUltraExpanded should map to kUltraExpanded_Width"); } +STATIC_ASSERT_ENUM(kFontStretchUltraCondensed, + SkFontStyle::kUltraCondensed_Width); +STATIC_ASSERT_ENUM(kFontStretchNormal, SkFontStyle::kNormal_Width); +STATIC_ASSERT_ENUM(kFontStretchUltraExpanded, + SkFontStyle::kUltraExpanded_Width); + +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyNone, + FontDescription::kNoFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyStandard, + FontDescription::kStandardFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilySerif, + FontDescription::kSerifFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilySansSerif, + FontDescription::kSansSerifFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyMonospace, + FontDescription::kMonospaceFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyCursive, + FontDescription::kCursiveFamily); +STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyFantasy, + FontDescription::kFantasyFamily); + +STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingAuto, kAutoSmoothing); +STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingNone, kNoSmoothing); +STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingGrayscale, kAntialiased); +STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingSubpixel, + kSubpixelAntialiased); + +STATIC_ASSERT_ENUM(WebFontDescription::kWeight100, kFontWeight100); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight200, kFontWeight200); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight300, kFontWeight300); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight400, kFontWeight400); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight500, kFontWeight500); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight600, kFontWeight600); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight700, kFontWeight700); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight800, kFontWeight800); +STATIC_ASSERT_ENUM(WebFontDescription::kWeight900, kFontWeight900); +STATIC_ASSERT_ENUM(WebFontDescription::kWeightNormal, kFontWeightNormal); +STATIC_ASSERT_ENUM(WebFontDescription::kWeightBold, kFontWeightBold); + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp b/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp index 7d69328..ced5240 100644 --- a/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp +++ b/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp
@@ -187,9 +187,9 @@ return source_.GetHotSpot(hot_spot); } -Image::SizeAvailability BitmapImage::SetData(PassRefPtr<SharedBuffer> data, +Image::SizeAvailability BitmapImage::SetData(RefPtr<SharedBuffer> data, bool all_data_received) { - if (!data.Get()) + if (!data) return kSizeAvailable; int length = data->size();
diff --git a/third_party/WebKit/Source/platform/graphics/BitmapImage.h b/third_party/WebKit/Source/platform/graphics/BitmapImage.h index e93ed07..6328194 100644 --- a/third_party/WebKit/Source/platform/graphics/BitmapImage.h +++ b/third_party/WebKit/Source/platform/graphics/BitmapImage.h
@@ -66,7 +66,7 @@ bool GetHotSpot(IntPoint&) const override; String FilenameExtension() const override; - SizeAvailability SetData(PassRefPtr<SharedBuffer> data, + SizeAvailability SetData(RefPtr<SharedBuffer> data, bool all_data_received) override; SizeAvailability DataChanged(bool all_data_received) override;
diff --git a/third_party/WebKit/Source/platform/graphics/Image.cpp b/third_party/WebKit/Source/platform/graphics/Image.cpp index d930750..88683c7 100644 --- a/third_party/WebKit/Source/platform/graphics/Image.cpp +++ b/third_party/WebKit/Source/platform/graphics/Image.cpp
@@ -78,7 +78,7 @@ return MIMETypeRegistry::IsSupportedImageResourceMIMEType(type); } -Image::SizeAvailability Image::SetData(PassRefPtr<SharedBuffer> data, +Image::SizeAvailability Image::SetData(RefPtr<SharedBuffer> data, bool all_data_received) { encoded_image_data_ = std::move(data); if (!encoded_image_data_.Get())
diff --git a/third_party/WebKit/Source/platform/graphics/Image.h b/third_party/WebKit/Source/platform/graphics/Image.h index b4315a4..e187234 100644 --- a/third_party/WebKit/Source/platform/graphics/Image.h +++ b/third_party/WebKit/Source/platform/graphics/Image.h
@@ -116,7 +116,7 @@ // Otherwise: // Image loading is completed synchronously. // ImageResourceObserver::AsyncLoadCompleted() is not called. - virtual SizeAvailability SetData(PassRefPtr<SharedBuffer> data, + virtual SizeAvailability SetData(RefPtr<SharedBuffer> data, bool all_data_received); virtual SizeAvailability DataChanged(bool /*all_data_received*/) { return kSizeUnavailable;
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h index ff36b94..96e6159 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h
@@ -96,7 +96,7 @@ AlphaOption, const ColorBehavior&); static std::unique_ptr<ImageDecoder> Create( - PassRefPtr<SharedBuffer> data, + RefPtr<SharedBuffer> data, bool data_complete, AlphaOption alpha_option, const ColorBehavior& color_behavior) { @@ -121,7 +121,7 @@ OnSetData(data_.Get()); } - void SetData(PassRefPtr<SharedBuffer> data, bool all_data_received) { + void SetData(RefPtr<SharedBuffer> data, bool all_data_received) { SetData(SegmentReader::CreateFromSharedBuffer(std::move(data)), all_data_received); }
diff --git a/third_party/WebKit/Source/platform/loader/BUILD.gn b/third_party/WebKit/Source/platform/loader/BUILD.gn index 60842f9c..3ac6a5f 100644 --- a/third_party/WebKit/Source/platform/loader/BUILD.gn +++ b/third_party/WebKit/Source/platform/loader/BUILD.gn
@@ -69,6 +69,8 @@ "fetch/ResourceTimingInfo.cpp", "fetch/ResourceTimingInfo.h", "fetch/SubstituteData.h", + "fetch/TextResourceDecoderOptions.cpp", + "fetch/TextResourceDecoderOptions.h", "fetch/UniqueIdentifier.cpp", "fetch/UniqueIdentifier.h", ]
diff --git a/third_party/WebKit/Source/platform/loader/fetch/CachedMetadata.h b/third_party/WebKit/Source/platform/loader/fetch/CachedMetadata.h index 45cff94..ef3feb9 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/CachedMetadata.h +++ b/third_party/WebKit/Source/platform/loader/fetch/CachedMetadata.h
@@ -34,7 +34,6 @@ #include <stdint.h> #include "platform/PlatformExport.h" #include "platform/wtf/Assertions.h" -#include "platform/wtf/PassRefPtr.h" #include "platform/wtf/RefCounted.h" #include "platform/wtf/RefPtr.h" #include "platform/wtf/Vector.h" @@ -47,14 +46,14 @@ // data type ID will reject data generated with a different byte-order. class PLATFORM_EXPORT CachedMetadata : public RefCounted<CachedMetadata> { public: - static PassRefPtr<CachedMetadata> Create(uint32_t data_type_id, - const char* data, - size_t size) { + static RefPtr<CachedMetadata> Create(uint32_t data_type_id, + const char* data, + size_t size) { return AdoptRef(new CachedMetadata(data_type_id, data, size)); } - static PassRefPtr<CachedMetadata> CreateFromSerializedData(const char* data, - size_t size) { + static RefPtr<CachedMetadata> CreateFromSerializedData(const char* data, + size_t size) { return AdoptRef(new CachedMetadata(data, size)); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/CachedMetadataHandler.h b/third_party/WebKit/Source/platform/loader/fetch/CachedMetadataHandler.h index 7a65f93d..66db6f76 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/CachedMetadataHandler.h +++ b/third_party/WebKit/Source/platform/loader/fetch/CachedMetadataHandler.h
@@ -34,7 +34,7 @@ virtual void ClearCachedMetadata(CacheType = kCacheLocally) = 0; // Returns cached metadata of the given type associated with this resource. // This cached metadata can be pruned at any time. - virtual PassRefPtr<CachedMetadata> GetCachedMetadata( + virtual RefPtr<CachedMetadata> GetCachedMetadata( uint32_t data_type_id) const = 0; // Returns the encoding to which the cache is specific. virtual String Encoding() const = 0;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.cpp b/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.cpp index 7be30e3..1d93cb8 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.cpp
@@ -95,12 +95,13 @@ DCHECK(request_url.Pass().IsEmpty()); ResourceRequest preflight_request(request_url); - preflight_request.SetAllowStoredCredentials(false); preflight_request.SetHTTPMethod(HTTPNames::OPTIONS); preflight_request.SetHTTPHeaderField(HTTPNames::Access_Control_Request_Method, AtomicString(request.HttpMethod())); preflight_request.SetPriority(request.Priority()); preflight_request.SetRequestContext(request.GetRequestContext()); + preflight_request.SetFetchCredentialsMode( + WebURLRequest::kFetchCredentialsModeOmit); preflight_request.SetServiceWorkerMode( WebURLRequest::ServiceWorkerMode::kNone); @@ -125,7 +126,7 @@ CrossOriginAccessControl::AccessStatus CrossOriginAccessControl::CheckAccess( const ResourceResponse& response, - StoredCredentials include_credentials, + WebURLRequest::FetchCredentialsMode credentials_mode, const SecurityOrigin* security_origin) { static const char allow_origin_header_name[] = "access-control-allow-origin"; static const char allow_credentials_header_name[] = @@ -156,7 +157,7 @@ if (allow_origin_header_value == "*") { // A wildcard Access-Control-Allow-Origin can not be used if credentials are // to be sent, even with Access-Control-Allow-Credentials set to true. - if (include_credentials == kDoNotAllowStoredCredentials) + if (!FetchUtils::ShouldTreatCredentialsModeAsInclude(credentials_mode)) return kAccessAllowed; if (response.IsHTTP()) { return kWildcardOriginNotAllowed; @@ -175,7 +176,7 @@ return kAllowOriginMismatch; } - if (include_credentials == kAllowStoredCredentials) { + if (FetchUtils::ShouldTreatCredentialsModeAsInclude(credentials_mode)) { const AtomicString& allow_credentials_header_value = response.HttpHeaderField(allow_credentials_header_name); if (allow_credentials_header_value != "true") { @@ -540,7 +541,7 @@ RefPtr<SecurityOrigin> current_security_origin, ResourceRequest& new_request, const ResourceResponse& redirect_response, - StoredCredentials with_credentials, + WebURLRequest::FetchCredentialsMode credentials_mode, ResourceLoaderOptions& options, String& error_message) { // http://www.w3.org/TR/cors/#redirect-steps terminology: @@ -569,7 +570,7 @@ // Step 5: perform resource sharing access check. CrossOriginAccessControl::AccessStatus cors_status = CrossOriginAccessControl::CheckAccess( - redirect_response, with_credentials, current_security_origin.Get()); + redirect_response, credentials_mode, current_security_origin.Get()); if (cors_status != kAccessAllowed) { StringBuilder builder; builder.Append("Redirect from '"); @@ -595,13 +596,7 @@ new_request.ClearHTTPOrigin(); new_request.SetHTTPOrigin(new_security_origin.Get()); - // Unset credentials flag if request's credentials mode is "same-origin" as - // request's response tainting becomes "cors". - // - // This is equivalent to the step 2 in - // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch - if (options.credentials_requested == kClientDidNotRequestCredentials) - options.allow_credentials = kDoNotAllowStoredCredentials; + options.cors_flag = true; } return true; }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.h b/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.h index c97eb867..197eaa2 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.h +++ b/third_party/WebKit/Source/platform/loader/fetch/CrossOriginAccessControl.h
@@ -33,7 +33,6 @@ #include "platform/wtf/Allocator.h" #include "platform/wtf/Forward.h" #include "platform/wtf/HashSet.h" -#include "platform/wtf/PassRefPtr.h" namespace blink { @@ -95,7 +94,7 @@ // access is allowed. Use |accessControlErrorString()| to construct a // user-friendly error message for any of the other (error) conditions. static AccessStatus CheckAccess(const ResourceResponse&, - StoredCredentials, + WebURLRequest::FetchCredentialsMode, const SecurityOrigin*); // Perform the required CORS checks on the response to a preflight request. @@ -122,7 +121,7 @@ static bool HandleRedirect(RefPtr<SecurityOrigin>, ResourceRequest&, const ResourceResponse&, - StoredCredentials, + WebURLRequest::FetchCredentialsMode, ResourceLoaderOptions&, String&);
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.cpp b/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.cpp index f5aee5c..4c9e1f77 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.cpp
@@ -34,7 +34,6 @@ FetchParameters::FetchParameters(const ResourceRequest& resource_request) : resource_request_(resource_request), - options_(kAllowStoredCredentials, kClientRequestedCredentials), speculative_preload_type_(SpeculativePreloadType::kNotSpeculative), preload_discovery_time_(0.0), defer_(kNoDefer), @@ -56,39 +55,30 @@ void FetchParameters::SetCrossOriginAccessControl( SecurityOrigin* origin, CrossOriginAttributeValue cross_origin) { - DCHECK_NE(cross_origin, kCrossOriginAttributeNotSet); - - // Per https://w3c.github.io/webappsec-suborigins/#security-model-opt-outs, - // credentials are forced when credentials mode is "same-origin", the - // 'unsafe-credentials' option is set, and the request's physical origin is - // the same as the URL's. - - const bool is_same_origin_request = - origin && (origin->CanRequestNoSuborigin(resource_request_.Url()) || - origin->HasSuboriginAndShouldAllowCredentialsFor(Url())); - - // Currently FetchParametersMode and FetchCredentialsMode are only used when - // the request goes to Service Worker. - resource_request_.SetFetchRequestMode(WebURLRequest::kFetchRequestModeCORS); - resource_request_.SetFetchCredentialsMode( - cross_origin == kCrossOriginAttributeUseCredentials - ? WebURLRequest::kFetchCredentialsModeInclude - : WebURLRequest::kFetchCredentialsModeSameOrigin); - - if (is_same_origin_request || - cross_origin == kCrossOriginAttributeUseCredentials) { - options_.allow_credentials = kAllowStoredCredentials; - resource_request_.SetAllowStoredCredentials(true); - } else { - options_.allow_credentials = kDoNotAllowStoredCredentials; - resource_request_.SetAllowStoredCredentials(false); + switch (cross_origin) { + case kCrossOriginAttributeNotSet: + NOTREACHED(); + break; + case kCrossOriginAttributeAnonymous: + SetCrossOriginAccessControl( + origin, WebURLRequest::kFetchCredentialsModeSameOrigin); + break; + case kCrossOriginAttributeUseCredentials: + SetCrossOriginAccessControl(origin, + WebURLRequest::kFetchCredentialsModeInclude); + break; } - options_.cors_enabled = kIsCORSEnabled; +} + +void FetchParameters::SetCrossOriginAccessControl( + SecurityOrigin* origin, + WebURLRequest::FetchCredentialsMode credentials_mode) { + // Currently FetchParametersMode is only used when the request goes to + // Service Worker. + resource_request_.SetFetchRequestMode(WebURLRequest::kFetchRequestModeCORS); + resource_request_.SetFetchCredentialsMode(credentials_mode); + options_.security_origin = origin; - options_.credentials_requested = - cross_origin == kCrossOriginAttributeUseCredentials - ? kClientRequestedCredentials - : kClientDidNotRequestCredentials; // TODO: Credentials should be removed only when the request is cross origin. resource_request_.RemoveUserAndPassFromURL();
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.h b/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.h index da1de53..525ee59 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.h +++ b/third_party/WebKit/Source/platform/loader/fetch/FetchParameters.h
@@ -34,6 +34,7 @@ #include "platform/loader/fetch/ResourceRequest.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/text/TextEncoding.h" +#include "public/platform/WebURLRequest.h" namespace blink { class SecurityOrigin; @@ -90,6 +91,7 @@ String Charset() const { return String(charset_.GetName()); } void SetCharset(const WTF::TextEncoding& charset) { charset_ = charset; } + ResourceLoaderOptions& MutableOptions() { return options_; } const ResourceLoaderOptions& Options() const { return options_; } DeferOption Defer() const { return defer_; } @@ -122,7 +124,13 @@ ContentSecurityPolicyDisposition content_security_policy_option) { options_.content_security_policy_option = content_security_policy_option; } + // Configures the request to use the "cors" mode and the credentials mode + // specified by the crossOrigin attribute. void SetCrossOriginAccessControl(SecurityOrigin*, CrossOriginAttributeValue); + // Configures the request to use the "cors" mode and the specified + // credentials mode. + void SetCrossOriginAccessControl(SecurityOrigin*, + WebURLRequest::FetchCredentialsMode); OriginRestriction GetOriginRestriction() const { return origin_restriction_; } void SetOriginRestriction(OriginRestriction restriction) { origin_restriction_ = restriction;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchUtils.h b/third_party/WebKit/Source/platform/loader/fetch/FetchUtils.h index 11a22a0..789352a 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/FetchUtils.h +++ b/third_party/WebKit/Source/platform/loader/fetch/FetchUtils.h
@@ -8,6 +8,7 @@ #include "platform/PlatformExport.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/Forward.h" +#include "public/platform/WebURLRequest.h" namespace blink { @@ -34,6 +35,14 @@ // code, https://tools.ietf.org/html/rfc7231#section-6.3 . We opt to use // the Fetch term in naming the predicate. static bool IsOkStatus(int status) { return status >= 200 && status < 300; } + + // Used by e.g. the CORS check algorithm to check if the FetchCredentialsMode + // should be treated as equivalent to "include" in the Fetch spec. + static bool ShouldTreatCredentialsModeAsInclude( + WebURLRequest::FetchCredentialsMode credentials_mode) { + return credentials_mode == WebURLRequest::kFetchCredentialsModeInclude || + credentials_mode == WebURLRequest::kFetchCredentialsModePassword; + } }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheCorrectnessTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheCorrectnessTest.cpp index 7eebf0be..1dfab66 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheCorrectnessTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheCorrectnessTest.cpp
@@ -61,6 +61,7 @@ if (response.Url().IsNull()) response.SetURL(KURL(kParsedURLString, kResourceURL)); ResourceRequest request(response.Url()); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* resource = MockResource::Create(request); resource->SetResponse(response); resource->Finish(); @@ -71,6 +72,7 @@ MockResource* ResourceFromResourceRequest(ResourceRequest request) { if (request.Url().IsNull()) request.SetURL(KURL(kParsedURLString, kResourceURL)); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* resource = MockResource::Create(request); resource->SetResponse(ResourceResponse(KURL(kParsedURLString, kResourceURL), "text/html", 0, g_null_atom)); @@ -352,6 +354,7 @@ KURL redirect_target_url(kParsedURLString, kRedirectTargetUrlString); ResourceRequest request(redirect_url); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* first_resource = MockResource::Create(request); ResourceResponse fresh301_response; @@ -392,6 +395,7 @@ KURL redirect_target_url(kParsedURLString, kRedirectTargetUrlString); ResourceRequest request(redirect_url); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* first_resource = MockResource::Create(request); ResourceResponse stale301_response; @@ -488,6 +492,7 @@ KURL redirect_target_url(kParsedURLString, kRedirectTargetUrlString); ResourceRequest request(redirect_url); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* first_resource = MockResource::Create(request); ResourceResponse fresh302_response; @@ -528,6 +533,7 @@ KURL redirect_target_url(kParsedURLString, kRedirectTargetUrlString); ResourceRequest request(redirect_url); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); MockResource* first_resource = MockResource::Create(request); ResourceResponse fresh302_response;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheTest.cpp index a263e1a..60ab2c8 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/MemoryCacheTest.cpp
@@ -48,8 +48,8 @@ public: static FakeDecodedResource* Create(const String& url, Type type) { ResourceRequest request(url); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; return new FakeDecodedResource(request, type, options); } @@ -74,8 +74,10 @@ } static FakeResource* Create(const KURL& url, Type type) { ResourceRequest request(url); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + + ResourceLoaderOptions options; + return new FakeResource(request, type, options); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/RawResource.h b/third_party/WebKit/Source/platform/loader/fetch/RawResource.h index 0ad25d5..6594f6f6 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/RawResource.h +++ b/third_party/WebKit/Source/platform/loader/fetch/RawResource.h
@@ -52,9 +52,9 @@ static RawResource* FetchManifest(FetchParameters&, ResourceFetcher*); // Exposed for testing - static RawResource* Create(const ResourceRequest& request, Type type) { - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + static RawResource* Create(ResourceRequest request, Type type) { + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; return new RawResource(request, type, options); } static RawResource* CreateForTest(const KURL& url, Type type) { @@ -77,13 +77,13 @@ const ResourceResponse&) override; private: - class RawResourceFactory : public ResourceFactory { + class RawResourceFactory : public NonTextResourceFactory { public: - explicit RawResourceFactory(Resource::Type type) : ResourceFactory(type) {} + explicit RawResourceFactory(Resource::Type type) + : NonTextResourceFactory(type) {} Resource* Create(const ResourceRequest& request, - const ResourceLoaderOptions& options, - const String& charset) const override { + const ResourceLoaderOptions& options) const override { return new RawResource(request, type_, options); } };
diff --git a/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp b/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp index 0984dc5..d515bef71 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp
@@ -121,7 +121,7 @@ DECLARE_VIRTUAL_TRACE(); void SetCachedMetadata(uint32_t, const char*, size_t, CacheType) override; void ClearCachedMetadata(CacheType) override; - PassRefPtr<CachedMetadata> GetCachedMetadata(uint32_t) const override; + RefPtr<CachedMetadata> GetCachedMetadata(uint32_t) const override; String Encoding() const override; // Sets the serialized metadata retrieved from the platform's cache. void SetSerializedCachedMetadata(const char*, size_t); @@ -169,12 +169,11 @@ SendToPlatform(); } -PassRefPtr<CachedMetadata> -Resource::CachedMetadataHandlerImpl::GetCachedMetadata( +RefPtr<CachedMetadata> Resource::CachedMetadataHandlerImpl::GetCachedMetadata( uint32_t data_type_id) const { if (!cached_metadata_ || cached_metadata_->DataTypeID() != data_type_id) return nullptr; - return cached_metadata_.Get(); + return cached_metadata_; } String Resource::CachedMetadataHandlerImpl::Encoding() const { @@ -357,7 +356,7 @@ SetEncodedSize(data_->size()); } -void Resource::SetResourceBuffer(PassRefPtr<SharedBuffer> resource_buffer) { +void Resource::SetResourceBuffer(RefPtr<SharedBuffer> resource_buffer) { DCHECK(!is_revalidating_); DCHECK(!ErrorOccurred()); DCHECK_EQ(options_.data_buffering_policy, kBufferData); @@ -426,13 +425,10 @@ bool Resource::PassesAccessControlCheck( const SecurityOrigin* security_origin) const { - StoredCredentials stored_credentials = - LastResourceRequest().AllowStoredCredentials() - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; CrossOriginAccessControl::AccessStatus status = - CrossOriginAccessControl::CheckAccess(GetResponse(), stored_credentials, - security_origin); + CrossOriginAccessControl::CheckAccess( + GetResponse(), LastResourceRequest().GetFetchCredentialsMode(), + security_origin); return status == CrossOriginAccessControl::kAccessAllowed; }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/Resource.h b/third_party/WebKit/Source/platform/loader/fetch/Resource.h index e1c25fea..ad20a5a 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/Resource.h +++ b/third_party/WebKit/Source/platform/loader/fetch/Resource.h
@@ -214,10 +214,8 @@ bool PassesAccessControlCheck(const SecurityOrigin*) const; - virtual PassRefPtr<const SharedBuffer> ResourceBuffer() const { - return data_; - } - void SetResourceBuffer(PassRefPtr<SharedBuffer>); + virtual RefPtr<const SharedBuffer> ResourceBuffer() const { return data_; } + void SetResourceBuffer(RefPtr<SharedBuffer>); virtual bool WillFollowRedirect(const ResourceRequest&, const ResourceResponse&); @@ -513,6 +511,21 @@ Resource::Type type_; }; +class NonTextResourceFactory : public ResourceFactory { + protected: + explicit NonTextResourceFactory(Resource::Type type) + : ResourceFactory(type) {} + + virtual Resource* Create(const ResourceRequest&, + const ResourceLoaderOptions&) const = 0; + + Resource* Create(const ResourceRequest& request, + const ResourceLoaderOptions& options, + const String&) const final { + return Create(request, options); + } +}; + #define DEFINE_RESOURCE_TYPE_CASTS(typeName) \ DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, \ resource->GetType() == Resource::k##typeName, \
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp index a43e4f9..94e4bd3 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp
@@ -582,8 +582,37 @@ if (!params.Url().IsValid()) return kAbort; - resource_request.SetAllowStoredCredentials( - params.Options().allow_credentials == kAllowStoredCredentials); + RefPtr<SecurityOrigin> origin = params.Options().security_origin; + params.MutableOptions().cors_flag = + !origin || !origin->CanRequestNoSuborigin(params.Url()); + + if (params.Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher) { + if (resource_request.GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS) { + bool allow_stored_credentials = false; + switch (resource_request.GetFetchCredentialsMode()) { + case WebURLRequest::kFetchCredentialsModeOmit: + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + allow_stored_credentials = + !params.Options().cors_flag || + (origin && + origin->HasSuboriginAndShouldAllowCredentialsFor(params.Url())); + break; + case WebURLRequest::kFetchCredentialsModeInclude: + case WebURLRequest::kFetchCredentialsModePassword: + allow_stored_credentials = true; + break; + } + resource_request.SetAllowStoredCredentials(allow_stored_credentials); + } else { + resource_request.SetAllowStoredCredentials( + resource_request.GetFetchCredentialsMode() != + WebURLRequest::kFetchCredentialsModeOmit); + } + } + return kContinue; } @@ -975,12 +1004,44 @@ return false; } - if (!is_static_data && - !params.Options().CanReuseRequest(existing_resource->Options())) { - return false; - } + if (is_static_data) + return true; - return true; + // Answers the question "can a separate request with different options be + // re-used" (e.g. preload request). The safe (but possibly slow) answer is + // always false. + // + // Data buffering policy differences are believed to be safe for re-use. + // + // TODO: Check content_security_policy_option. + // + // initiator_info is purely informational and should be benign for re-use. + // + // request_initiator_context is benign (indicates document vs. worker). + + if (params.Options().synchronous_policy != + existing_resource->Options().synchronous_policy) + return false; + + // securityOrigin has more complicated checks which callers are responsible + // for. + + // TODO(yhirano): Clean up this condition. This is generated to keep the old + // behavior across refactoring. + // + // TODO(tyoshino): Consider returning false when the credentials mode + // differs. + if ((params.Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + params.GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS) == + (existing_resource->Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + existing_resource->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS)) + return true; + + return false; } ResourceFetcher::RevalidationPolicy
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp index 1c48f07..2bcce1a9 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcherTest.cpp
@@ -322,8 +322,8 @@ ResourceFetcher::Create(Context(), Context()->GetTaskRunner()); ResourceRequest request(KURL(kParsedURLString, "data:text/html,foo")); request.SetRequestContext(WebURLRequest::kRequestContextVideo); - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); + ResourceLoaderOptions options; options.data_buffering_policy = kDoNotBufferData; options.initiator_info.name = FetchInitiatorTypeNames::internal; FetchParameters fetch_params(request, options);
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.cpp index 2a23959..9632797 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.cpp
@@ -26,11 +26,11 @@ push_start_(0), push_end_(0) {} -PassRefPtr<ResourceLoadTiming> ResourceLoadTiming::Create() { +RefPtr<ResourceLoadTiming> ResourceLoadTiming::Create() { return AdoptRef(new ResourceLoadTiming); } -PassRefPtr<ResourceLoadTiming> ResourceLoadTiming::DeepCopy() { +RefPtr<ResourceLoadTiming> ResourceLoadTiming::DeepCopy() { RefPtr<ResourceLoadTiming> timing = Create(); timing->request_time_ = request_time_; timing->proxy_start_ = proxy_start_; @@ -48,7 +48,7 @@ timing->ssl_end_ = ssl_end_; timing->push_start_ = push_start_; timing->push_end_ = push_end_; - return timing.Release(); + return timing; } bool ResourceLoadTiming::operator==(const ResourceLoadTiming& other) const {
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.h index d48b9b9..b454e6e 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadTiming.h
@@ -27,7 +27,6 @@ #define ResourceLoadTiming_h #include "platform/PlatformExport.h" -#include "platform/wtf/PassRefPtr.h" #include "platform/wtf/RefCounted.h" #include "platform/wtf/RefPtr.h" @@ -36,9 +35,9 @@ class PLATFORM_EXPORT ResourceLoadTiming : public RefCounted<ResourceLoadTiming> { public: - static PassRefPtr<ResourceLoadTiming> Create(); + static RefPtr<ResourceLoadTiming> Create(); - PassRefPtr<ResourceLoadTiming> DeepCopy(); + RefPtr<ResourceLoadTiming> DeepCopy(); bool operator==(const ResourceLoadTiming&) const; bool operator!=(const ResourceLoadTiming&) const;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp index a6db5b32..b36cc90 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp
@@ -183,19 +183,19 @@ return false; } - if (resource_->Options().cors_enabled == kIsCORSEnabled) { + if (resource_->Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + resource_->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS) { RefPtr<SecurityOrigin> source_origin = resource_->Options().security_origin; if (!source_origin.Get()) source_origin = Context().GetSecurityOrigin(); String error_message; - StoredCredentials with_credentials = - resource_->LastResourceRequest().AllowStoredCredentials() - ? kAllowStoredCredentials - : kDoNotAllowStoredCredentials; if (!CrossOriginAccessControl::HandleRedirect( - source_origin, new_request, redirect_response, with_credentials, + source_origin, new_request, redirect_response, + resource_->GetResourceRequest().GetFetchCredentialsMode(), resource_->MutableOptions(), error_message)) { resource_->SetCORSFailed(); Context().AddConsoleMessage(error_message); @@ -217,8 +217,25 @@ fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, cross_origin); - new_request.SetAllowStoredCredentials( - resource_->Options().allow_credentials == kAllowStoredCredentials); + if (resource_->Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + resource_->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS) { + bool allow_stored_credentials = false; + switch (new_request.GetFetchCredentialsMode()) { + case WebURLRequest::kFetchCredentialsModeOmit: + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + allow_stored_credentials = !resource_->Options().cors_flag; + break; + case WebURLRequest::kFetchCredentialsModeInclude: + case WebURLRequest::kFetchCredentialsModePassword: + allow_stored_credentials = true; + break; + } + new_request.SetAllowStoredCredentials(allow_stored_credentials); + } + Context().PrepareRequest(new_request, FetchContext::RedirectType::kForRedirect); Context().DispatchWillSendRequest(resource_->Identifier(), new_request, @@ -290,7 +307,8 @@ CrossOriginAccessControl::AccessStatus cors_status = CrossOriginAccessControl::CheckAccess( - response_for_access_control, resource->Options().allow_credentials, + response_for_access_control, + resource->GetResourceRequest().GetFetchCredentialsMode(), source_origin); if (cors_status != CrossOriginAccessControl::kAccessAllowed) { resource->SetCORSFailed(); @@ -323,7 +341,10 @@ const ResourceResponse& response = web_url_response.ToResourceResponse(); if (response.WasFetchedViaServiceWorker()) { - if (resource_->Options().cors_enabled == kIsCORSEnabled && + if (resource_->Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + resource_->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS && response.WasFallbackRequiredByServiceWorker()) { ResourceRequest request = resource_->LastResourceRequest(); DCHECK_EQ(request.GetServiceWorkerMode(), @@ -360,7 +381,10 @@ return; } } - } else if (resource_->Options().cors_enabled == kIsCORSEnabled) { + } else if (resource_->Options().cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + resource_->GetResourceRequest().GetFetchRequestMode() == + WebURLRequest::kFetchRequestModeCORS) { ResourceRequestBlockedReason blocked_reason = CanAccessResponse(resource_, response); if (blocked_reason != ResourceRequestBlockedReason::kNone) {
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptions.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptions.h index 42d95fea..d361291 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptions.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptions.h
@@ -51,27 +51,17 @@ kWorkerContext, }; -enum StoredCredentials : uint8_t { - kAllowStoredCredentials, - kDoNotAllowStoredCredentials -}; - -// APIs like XMLHttpRequest and EventSource let the user decide whether to send -// credentials, but they're always sent for same-origin requests. Additional -// information is needed to handle cross-origin redirects correctly. -enum CredentialRequest : uint8_t { - kClientRequestedCredentials, - kClientDidNotRequestCredentials -}; - enum SynchronousPolicy : uint8_t { kRequestSynchronously, kRequestAsynchronously }; -// A resource fetch can be marked as being CORS enabled. The loader must perform -// an access check upon seeing the response. -enum CORSEnabled : uint8_t { kNotCORSEnabled, kIsCORSEnabled }; +// Used by the DocumentThreadableLoader to turn off part of the CORS handling +// logic in the ResourceFetcher to use its own CORS handling logic. +enum CORSHandlingByResourceFetcher { + kDisableCORSHandlingByResourceFetcher, + kEnableCORSHandlingByResourceFetcher, +}; // Was the request generated from a "parser-inserted" element? // https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted @@ -86,53 +76,33 @@ USING_FAST_MALLOC(ResourceLoaderOptions); public: - ResourceLoaderOptions(StoredCredentials allow_credentials, - CredentialRequest credentials_requested) + ResourceLoaderOptions() : data_buffering_policy(kBufferData), - allow_credentials(allow_credentials), - credentials_requested(credentials_requested), content_security_policy_option(kCheckContentSecurityPolicy), request_initiator_context(kDocumentContext), synchronous_policy(kRequestAsynchronously), - cors_enabled(kNotCORSEnabled), + cors_handling_by_resource_fetcher(kEnableCORSHandlingByResourceFetcher), + cors_flag(false), parser_disposition(kParserInserted), cache_aware_loading_enabled(kNotCacheAwareLoadingEnabled) {} - // Answers the question "can a separate request with these different options - // be re-used" (e.g. preload request) The safe (but possibly slow) answer is - // always false. - bool CanReuseRequest(const ResourceLoaderOptions& other) const { - // dataBufferingPolicy differences are believed to be safe for re-use. - // FIXME: check allowCredentials. - // FIXME: check credentialsRequested. - // FIXME: check contentSecurityPolicyOption. - // initiatorInfo is purely informational and should be benign for re-use. - // requestInitiatorContext is benign (indicates document vs. worker) - if (synchronous_policy != other.synchronous_policy) - return false; - return cors_enabled == other.cors_enabled; - // securityOrigin has more complicated checks which callers are responsible - // for. - } - FetchInitiatorInfo initiator_info; // When adding members, CrossThreadResourceLoaderOptionsData should be // updated. DataBufferingPolicy data_buffering_policy; - // Whether HTTP credentials and cookies are sent with the request. - StoredCredentials allow_credentials; - - // Whether the client (e.g. XHR) wanted credentials in the first place. - CredentialRequest credentials_requested; - ContentSecurityPolicyDisposition content_security_policy_option; RequestInitiatorContext request_initiator_context; SynchronousPolicy synchronous_policy; - // If the resource is loaded out-of-origin, whether or not to use CORS. - CORSEnabled cors_enabled; + // When set to true, the ResourceFetcher suppresses part of its CORS handling + // logic. Used by DocumentThreadableLoader which does CORS handling by + // itself. + CORSHandlingByResourceFetcher cors_handling_by_resource_fetcher; + + // Corresponds to the CORS flag in the Fetch spec. + bool cors_flag; RefPtr<SecurityOrigin> security_origin; String content_security_policy_nonce; @@ -147,13 +117,13 @@ explicit CrossThreadResourceLoaderOptionsData( const ResourceLoaderOptions& options) : data_buffering_policy(options.data_buffering_policy), - allow_credentials(options.allow_credentials), - credentials_requested(options.credentials_requested), content_security_policy_option(options.content_security_policy_option), initiator_info(options.initiator_info), request_initiator_context(options.request_initiator_context), synchronous_policy(options.synchronous_policy), - cors_enabled(options.cors_enabled), + cors_handling_by_resource_fetcher( + options.cors_handling_by_resource_fetcher), + cors_flag(options.cors_flag), security_origin(options.security_origin ? options.security_origin->IsolatedCopy() : nullptr), @@ -163,13 +133,15 @@ cache_aware_loading_enabled(options.cache_aware_loading_enabled) {} operator ResourceLoaderOptions() const { - ResourceLoaderOptions options(allow_credentials, credentials_requested); + ResourceLoaderOptions options; options.data_buffering_policy = data_buffering_policy; options.content_security_policy_option = content_security_policy_option; options.initiator_info = initiator_info; options.request_initiator_context = request_initiator_context; options.synchronous_policy = synchronous_policy; - options.cors_enabled = cors_enabled; + options.cors_handling_by_resource_fetcher = + cors_handling_by_resource_fetcher; + options.cors_flag = cors_flag; options.security_origin = security_origin; options.content_security_policy_nonce = content_security_policy_nonce; options.integrity_metadata = integrity_metadata; @@ -179,14 +151,15 @@ } DataBufferingPolicy data_buffering_policy; - StoredCredentials allow_credentials; - CredentialRequest credentials_requested; ContentSecurityPolicyDisposition content_security_policy_option; CrossThreadFetchInitiatorInfoData initiator_info; RequestInitiatorContext request_initiator_context; SynchronousPolicy synchronous_policy; - CORSEnabled cors_enabled; + + CORSHandlingByResourceFetcher cors_handling_by_resource_fetcher; + bool cors_flag; RefPtr<SecurityOrigin> security_origin; + String content_security_policy_nonce; IntegrityMetadataSet integrity_metadata; ParserDisposition parser_disposition;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptionsTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptionsTest.cpp index 99dec5c..fbb6586 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptionsTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoaderOptionsTest.cpp
@@ -16,21 +16,16 @@ // initiatorInfo and securityOrigin. static_assert(std::is_enum<DataBufferingPolicy>::value, "DataBufferingPolicy should be an enum"); - static_assert(std::is_enum<StoredCredentials>::value, - "StoredCredentials should be an enum"); - static_assert(std::is_enum<CredentialRequest>::value, - "CredentialRequest should be an enum"); static_assert(std::is_enum<ContentSecurityPolicyDisposition>::value, "ContentSecurityPolicyDisposition should be an enum"); static_assert(std::is_enum<RequestInitiatorContext>::value, "RequestInitiatorContext should be an enum"); static_assert(std::is_enum<SynchronousPolicy>::value, "SynchronousPolicy should be an enum"); - static_assert(std::is_enum<CORSEnabled>::value, - "CORSEnabled should be an enum"); + static_assert(std::is_enum<CORSHandlingByResourceFetcher>::value, + "CORSHandlingByResourceFetcher should be an enum"); - ResourceLoaderOptions original(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + ResourceLoaderOptions original; RefPtr<SecurityOrigin> security_origin = SecurityOrigin::CreateFromString("http://www.google.com"); original.security_origin = security_origin; @@ -42,8 +37,6 @@ // Check that contents are correctly copied to |copyData| EXPECT_EQ(original.data_buffering_policy, copy_data.data_buffering_policy); - EXPECT_EQ(original.allow_credentials, copy_data.allow_credentials); - EXPECT_EQ(original.credentials_requested, copy_data.credentials_requested); EXPECT_EQ(original.content_security_policy_option, copy_data.content_security_policy_option); EXPECT_EQ(original.initiator_info.name, copy_data.initiator_info.name); @@ -54,7 +47,8 @@ EXPECT_EQ(original.request_initiator_context, copy_data.request_initiator_context); EXPECT_EQ(original.synchronous_policy, copy_data.synchronous_policy); - EXPECT_EQ(original.cors_enabled, copy_data.cors_enabled); + EXPECT_EQ(original.cors_handling_by_resource_fetcher, + copy_data.cors_handling_by_resource_fetcher); EXPECT_EQ(original.security_origin->Protocol(), copy_data.security_origin->Protocol()); EXPECT_EQ(original.security_origin->Host(), @@ -75,8 +69,6 @@ // Check that contents are correctly copied to |copy| EXPECT_EQ(original.data_buffering_policy, copy.data_buffering_policy); - EXPECT_EQ(original.allow_credentials, copy.allow_credentials); - EXPECT_EQ(original.credentials_requested, copy.credentials_requested); EXPECT_EQ(original.content_security_policy_option, copy.content_security_policy_option); EXPECT_EQ(original.initiator_info.name, copy.initiator_info.name); @@ -84,7 +76,8 @@ EXPECT_EQ(original.initiator_info.start_time, copy.initiator_info.start_time); EXPECT_EQ(original.request_initiator_context, copy.request_initiator_context); EXPECT_EQ(original.synchronous_policy, copy.synchronous_policy); - EXPECT_EQ(original.cors_enabled, copy.cors_enabled); + EXPECT_EQ(original.cors_handling_by_resource_fetcher, + copy.cors_handling_by_resource_fetcher); EXPECT_EQ(original.security_origin->Protocol(), copy.security_origin->Protocol()); EXPECT_EQ(original.security_origin->Host(), copy.security_origin->Host());
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp index 4c6b5c3..826b860 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp
@@ -301,7 +301,7 @@ return http_body_.Get(); } -void ResourceRequest::SetHTTPBody(PassRefPtr<EncodedFormData> http_body) { +void ResourceRequest::SetHTTPBody(RefPtr<EncodedFormData> http_body) { http_body_ = std::move(http_body); } @@ -310,7 +310,7 @@ } void ResourceRequest::SetAttachedCredential( - PassRefPtr<EncodedFormData> attached_credential) { + RefPtr<EncodedFormData> attached_credential) { attached_credential_ = std::move(attached_credential); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h index dbbbb28..49a7bc7 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h
@@ -155,10 +155,10 @@ } EncodedFormData* HttpBody() const; - void SetHTTPBody(PassRefPtr<EncodedFormData>); + void SetHTTPBody(RefPtr<EncodedFormData>); EncodedFormData* AttachedCredential() const; - void SetAttachedCredential(PassRefPtr<EncodedFormData>); + void SetAttachedCredential(RefPtr<EncodedFormData>); bool AllowStoredCredentials() const; void SetAllowStoredCredentials(bool allow_credentials); @@ -238,7 +238,7 @@ // Extra data associated with this request. ExtraData* GetExtraData() const { return extra_data_.Get(); } - void SetExtraData(PassRefPtr<ExtraData> extra_data) { + void SetExtraData(RefPtr<ExtraData> extra_data) { extra_data_ = std::move(extra_data); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp index a6c9b065..ff945347 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp
@@ -554,16 +554,15 @@ } void ResourceResponse::SetResourceLoadTiming( - PassRefPtr<ResourceLoadTiming> resource_load_timing) { + RefPtr<ResourceLoadTiming> resource_load_timing) { resource_load_timing_ = std::move(resource_load_timing); } -PassRefPtr<ResourceLoadInfo> ResourceResponse::GetResourceLoadInfo() const { +RefPtr<ResourceLoadInfo> ResourceResponse::GetResourceLoadInfo() const { return resource_load_info_.Get(); } -void ResourceResponse::SetResourceLoadInfo( - PassRefPtr<ResourceLoadInfo> load_info) { +void ResourceResponse::SetResourceLoadInfo(RefPtr<ResourceLoadInfo> load_info) { resource_load_info_ = std::move(load_info); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h index 9f3d82e..811fcef 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h
@@ -212,10 +212,10 @@ void SetWasCached(bool); ResourceLoadTiming* GetResourceLoadTiming() const; - void SetResourceLoadTiming(PassRefPtr<ResourceLoadTiming>); + void SetResourceLoadTiming(RefPtr<ResourceLoadTiming>); - PassRefPtr<ResourceLoadInfo> GetResourceLoadInfo() const; - void SetResourceLoadInfo(PassRefPtr<ResourceLoadInfo>); + RefPtr<ResourceLoadInfo> GetResourceLoadInfo() const; + void SetResourceLoadInfo(RefPtr<ResourceLoadInfo>); HTTPVersion HttpVersion() const { return http_version_; } void SetHTTPVersion(HTTPVersion version) { http_version_ = version; } @@ -355,7 +355,7 @@ // Extra data associated with this response. ExtraData* GetExtraData() const { return extra_data_.Get(); } - void SetExtraData(PassRefPtr<ExtraData> extra_data) { + void SetExtraData(RefPtr<ExtraData> extra_data) { extra_data_ = std::move(extra_data); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.cpp index dc578c9..a1c52c5 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.cpp
@@ -10,7 +10,7 @@ namespace blink { -PassRefPtr<ResourceTimingInfo> ResourceTimingInfo::Adopt( +RefPtr<ResourceTimingInfo> ResourceTimingInfo::Adopt( std::unique_ptr<CrossThreadResourceTimingInfoData> data) { RefPtr<ResourceTimingInfo> info = ResourceTimingInfo::Create( AtomicString(data->type_), data->initial_time_, data->is_main_resource_); @@ -23,7 +23,7 @@ info->redirect_chain_.push_back(ResourceResponse(response_data.get())); info->transfer_size_ = data->transfer_size_; info->negative_allowed_ = data->negative_allowed_; - return info.Release(); + return info; } std::unique_ptr<CrossThreadResourceTimingInfoData>
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.h index 4a89430..3958820 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceTimingInfo.h
@@ -51,12 +51,12 @@ WTF_MAKE_NONCOPYABLE(ResourceTimingInfo); public: - static PassRefPtr<ResourceTimingInfo> Create(const AtomicString& type, - const double time, - bool is_main_resource) { + static RefPtr<ResourceTimingInfo> Create(const AtomicString& type, + const double time, + bool is_main_resource) { return AdoptRef(new ResourceTimingInfo(type, time, is_main_resource)); } - static PassRefPtr<ResourceTimingInfo> Adopt( + static RefPtr<ResourceTimingInfo> Adopt( std::unique_ptr<CrossThreadResourceTimingInfoData>); // Gets a copy of the data suitable for passing to another thread.
diff --git a/third_party/WebKit/Source/platform/loader/fetch/SubstituteData.h b/third_party/WebKit/Source/platform/loader/fetch/SubstituteData.h index cc0b163..af424d28 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/SubstituteData.h +++ b/third_party/WebKit/Source/platform/loader/fetch/SubstituteData.h
@@ -29,7 +29,6 @@ #include "platform/SharedBuffer.h" #include "platform/weborigin/KURL.h" #include "platform/wtf/Allocator.h" -#include "platform/wtf/PassRefPtr.h" #include "platform/wtf/RefPtr.h" namespace blink { @@ -43,7 +42,7 @@ SubstituteData() : substitute_data_load_policy_(kLoadNormally) {} SubstituteData( - PassRefPtr<SharedBuffer> content, + RefPtr<SharedBuffer> content, const AtomicString& mime_type, const AtomicString& text_encoding, const KURL& failing_url,
diff --git a/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.cpp b/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.cpp new file mode 100644 index 0000000..8e0de55f --- /dev/null +++ b/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.cpp
@@ -0,0 +1,65 @@ +// 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 "platform/loader/fetch/TextResourceDecoderOptions.h" +#include "platform/Language.h" + +namespace blink { + +TextResourceDecoderOptions::TextResourceDecoderOptions( + ContentType content_type, + const WTF::TextEncoding& default_encoding) + : TextResourceDecoderOptions(kUseContentAndBOMBasedDetection, + content_type, + default_encoding, + nullptr, + KURL()) {} + +TextResourceDecoderOptions +TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText() { + return TextResourceDecoderOptions(kAlwaysUseUTF8ForText, kPlainTextContent, + UTF8Encoding(), nullptr, KURL()); +} + +TextResourceDecoderOptions TextResourceDecoderOptions::CreateWithAutoDetection( + ContentType content_type, + const WTF::TextEncoding& default_encoding, + const WTF::TextEncoding& hint_encoding, + const KURL& hint_url) { + return TextResourceDecoderOptions(kUseAllAutoDetection, content_type, + default_encoding, hint_encoding.GetName(), + hint_url); +} + +TextResourceDecoderOptions::TextResourceDecoderOptions( + EncodingDetectionOption encoding_detection_option, + ContentType content_type, + const WTF::TextEncoding& default_encoding, + const char* hint_encoding, + const KURL& hint_url) + : encoding_detection_option_(encoding_detection_option), + content_type_(content_type), + default_encoding_(default_encoding), + use_lenient_xml_decoding_(false), + hint_encoding_(hint_encoding), + hint_url_(hint_url) { + hint_language_[0] = 0; + if (encoding_detection_option_ == kUseAllAutoDetection) { + // Checking empty URL helps unit testing. Providing DefaultLanguage() is + // sometimes difficult in tests. + if (!hint_url_.IsEmpty()) { + // This object is created in the main thread, but used in another thread. + // We should not share an AtomicString. + AtomicString locale = DefaultLanguage(); + if (locale.length() >= 2) { + // DefaultLanguage() is always an ASCII string. + hint_language_[0] = static_cast<char>(locale[0]); + hint_language_[1] = static_cast<char>(locale[1]); + hint_language_[2] = 0; + } + } + } +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.h b/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.h new file mode 100644 index 0000000..07505d9d --- /dev/null +++ b/third_party/WebKit/Source/platform/loader/fetch/TextResourceDecoderOptions.h
@@ -0,0 +1,94 @@ +// 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 TextResourceDecoderOptions_h +#define TextResourceDecoderOptions_h + +#include "platform/PlatformExport.h" +#include "platform/weborigin/KURL.h" +#include "platform/wtf/text/TextEncoding.h" + +namespace blink { + +class PLATFORM_EXPORT TextResourceDecoderOptions final { + public: + enum ContentType { + kPlainTextContent, + kHTMLContent, + kXMLContent, + kCSSContent, + kMaxContentType = kCSSContent + }; // PlainText only checks for BOM. + + explicit TextResourceDecoderOptions( + ContentType, + const WTF::TextEncoding& default_encoding = WTF::TextEncoding()); + + // Corresponds to utf-8 decode in Encoding spec: + // https://encoding.spec.whatwg.org/#utf-8-decode. + static TextResourceDecoderOptions CreateAlwaysUseUTF8ForText(); + + static TextResourceDecoderOptions CreateWithAutoDetection( + ContentType, + const WTF::TextEncoding& default_encoding, + const WTF::TextEncoding& hint_encoding, + const KURL& hint_url); + + void SetUseLenientXMLDecoding() { use_lenient_xml_decoding_ = true; } + + static ContentType DetermineContentType(const String& mime_type); + + // TextResourceDecoder does three kind of encoding detection: + // 1. By BOM, + // 2. By Content if |content_type_| is not |kPlainTextContext| + // (e.g. <meta> tag for HTML), and + // 3. By DetectTextEncoding(). + enum EncodingDetectionOption { + // Use 1. + 2. + 3. + kUseAllAutoDetection, + + // Use 1. + 2. + kUseContentAndBOMBasedDetection, + + // Use None of them. + // |content_type_| must be |kPlainTextContent| and + // |default_encoding_| must be UTF8Encoding. + // This doesn't change encoding based on BOMs, but still processes + // utf-8 BOMs so that utf-8 BOMs don't appear in the decoded result. + kAlwaysUseUTF8ForText + }; + + EncodingDetectionOption GetEncodingDetectionOption() const { + return encoding_detection_option_; + } + ContentType GetContentType() const { return content_type_; } + const WTF::TextEncoding& DefaultEncoding() const { return default_encoding_; } + bool GetUseLenientXMLDecoding() const { return use_lenient_xml_decoding_; } + + const char* HintEncoding() const { return hint_encoding_; } + const KURL& HintURL() const { return hint_url_; } + const char* HintLanguage() const { return hint_language_; } + + private: + TextResourceDecoderOptions(EncodingDetectionOption, + ContentType, + const WTF::TextEncoding& default_encoding, + const char* hint_encoding, + const KURL& hint_url); + + const EncodingDetectionOption encoding_detection_option_; + const ContentType content_type_; + const WTF::TextEncoding default_encoding_; + bool use_lenient_xml_decoding_; // Don't stop on XML decoding errors. + + // Hints for DetectTextEncoding(). + // Only used when |encoding_detection_option_| == |kUseAllAutoDetection|. + const char* const hint_encoding_; + const KURL hint_url_; + char hint_language_[3]; +}; + +} // namespace blink + +#endif
diff --git a/third_party/WebKit/Source/platform/loader/testing/MockResource.cpp b/third_party/WebKit/Source/platform/loader/testing/MockResource.cpp index 4289b332..30fd1a39 100644 --- a/third_party/WebKit/Source/platform/loader/testing/MockResource.cpp +++ b/third_party/WebKit/Source/platform/loader/testing/MockResource.cpp
@@ -12,13 +12,12 @@ namespace { -class MockResourceFactory final : public ResourceFactory { +class MockResourceFactory final : public NonTextResourceFactory { public: - MockResourceFactory() : ResourceFactory(Resource::kMock) {} + MockResourceFactory() : NonTextResourceFactory(Resource::kMock) {} Resource* Create(const ResourceRequest& request, - const ResourceLoaderOptions& options, - const String&) const override { + const ResourceLoaderOptions& options) const override { return new MockResource(request, options); } }; @@ -35,8 +34,7 @@ // static MockResource* MockResource::Create(const ResourceRequest& request) { - ResourceLoaderOptions options(kDoNotAllowStoredCredentials, - kClientDidNotRequestCredentials); + ResourceLoaderOptions options; return new MockResource(request, options); }
diff --git a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp index 197cf5f..e1aa336 100644 --- a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp +++ b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
@@ -51,7 +51,6 @@ #include "core/layout/compositing/CompositedSelectionBound.h" #include "core/loader/FrameLoaderTypes.h" #include "core/loader/NavigationPolicy.h" -#include "core/loader/appcache/ApplicationCacheHost.h" #include "core/page/PageVisibilityState.h" #include "core/style/ComputedStyleConstants.h" #include "modules/indexeddb/IDBKey.h" @@ -61,7 +60,6 @@ #include "modules/navigatorcontentutils/NavigatorContentUtilsClient.h" #include "modules/quota/DeprecatedStorageQuota.h" #include "modules/speech/SpeechRecognitionError.h" -#include "platform/Cursor.h" #include "platform/FileMetadata.h" #include "platform/FileSystemType.h" #include "platform/fonts/FontDescription.h" @@ -77,15 +75,12 @@ #include "platform/weborigin/SchemeRegistry.h" #include "platform/wtf/Assertions.h" #include "platform/wtf/text/StringImpl.h" -#include "public/platform/WebApplicationCacheHost.h" #include "public/platform/WebClipboard.h" #include "public/platform/WebContentSecurityPolicy.h" #include "public/platform/WebContentSecurityPolicyStruct.h" -#include "public/platform/WebCursorInfo.h" #include "public/platform/WebFileError.h" #include "public/platform/WebFileInfo.h" #include "public/platform/WebFileSystem.h" -#include "public/platform/WebFontDescription.h" #include "public/platform/WebHistoryScrollRestorationType.h" #include "public/platform/WebInputEvent.h" #include "public/platform/WebMediaPlayer.h" @@ -133,127 +128,14 @@ namespace blink { -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUncached, - ApplicationCacheHost::kUncached); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kIdle, ApplicationCacheHost::kIdle); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kChecking, - ApplicationCacheHost::kChecking); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kDownloading, - ApplicationCacheHost::kDownloading); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUpdateReady, - ApplicationCacheHost::kUpdateready); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kObsolete, - ApplicationCacheHost::kObsolete); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kCheckingEvent, - ApplicationCacheHost::kCheckingEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kErrorEvent, - ApplicationCacheHost::kErrorEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kNoUpdateEvent, - ApplicationCacheHost::kNoupdateEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kDownloadingEvent, - ApplicationCacheHost::kDownloadingEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kProgressEvent, - ApplicationCacheHost::kProgressEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kUpdateReadyEvent, - ApplicationCacheHost::kUpdatereadyEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kCachedEvent, - ApplicationCacheHost::kCachedEvent); -STATIC_ASSERT_ENUM(WebApplicationCacheHost::kObsoleteEvent, - ApplicationCacheHost::kObsoleteEvent); STATIC_ASSERT_ENUM(WebClientRedirectPolicy::kNotClientRedirect, ClientRedirectPolicy::kNotClientRedirect); STATIC_ASSERT_ENUM(WebClientRedirectPolicy::kClientRedirect, ClientRedirectPolicy::kClientRedirect); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypePointer, Cursor::kPointer); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCross, Cursor::kCross); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeHand, Cursor::kHand); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeIBeam, Cursor::kIBeam); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWait, Cursor::kWait); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeHelp, Cursor::kHelp); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastResize, Cursor::kEastResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthResize, Cursor::kNorthResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastResize, - Cursor::kNorthEastResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestResize, - Cursor::kNorthWestResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthResize, Cursor::kSouthResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthEastResize, - Cursor::kSouthEastResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthWestResize, - Cursor::kSouthWestResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWestResize, Cursor::kWestResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthSouthResize, - Cursor::kNorthSouthResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastWestResize, Cursor::kEastWestResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastSouthWestResize, - Cursor::kNorthEastSouthWestResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestSouthEastResize, - Cursor::kNorthWestSouthEastResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeColumnResize, Cursor::kColumnResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeRowResize, Cursor::kRowResize); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeMiddlePanning, Cursor::kMiddlePanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeEastPanning, Cursor::kEastPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthPanning, Cursor::kNorthPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthEastPanning, - Cursor::kNorthEastPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNorthWestPanning, - Cursor::kNorthWestPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthPanning, Cursor::kSouthPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthEastPanning, - Cursor::kSouthEastPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeSouthWestPanning, - Cursor::kSouthWestPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeWestPanning, Cursor::kWestPanning); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeMove, Cursor::kMove); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeVerticalText, Cursor::kVerticalText); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCell, Cursor::kCell); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeContextMenu, Cursor::kContextMenu); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeAlias, Cursor::kAlias); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeProgress, Cursor::kProgress); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNoDrop, Cursor::kNoDrop); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCopy, Cursor::kCopy); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNone, Cursor::kNone); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeNotAllowed, Cursor::kNotAllowed); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeZoomIn, Cursor::kZoomIn); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeZoomOut, Cursor::kZoomOut); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeGrab, Cursor::kGrab); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeGrabbing, Cursor::kGrabbing); -STATIC_ASSERT_ENUM(WebCursorInfo::kTypeCustom, Cursor::kCustom); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyNone, - FontDescription::kNoFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyStandard, - FontDescription::kStandardFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilySerif, - FontDescription::kSerifFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilySansSerif, - FontDescription::kSansSerifFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyMonospace, - FontDescription::kMonospaceFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyCursive, - FontDescription::kCursiveFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kGenericFamilyFantasy, - FontDescription::kFantasyFamily); -STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingAuto, kAutoSmoothing); -STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingNone, kNoSmoothing); -STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingGrayscale, kAntialiased); -STATIC_ASSERT_ENUM(WebFontDescription::kSmoothingSubpixel, - kSubpixelAntialiased); - -STATIC_ASSERT_ENUM(WebFontDescription::kWeight100, kFontWeight100); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight200, kFontWeight200); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight300, kFontWeight300); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight400, kFontWeight400); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight500, kFontWeight500); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight600, kFontWeight600); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight700, kFontWeight700); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight800, kFontWeight800); -STATIC_ASSERT_ENUM(WebFontDescription::kWeight900, kFontWeight900); -STATIC_ASSERT_ENUM(WebFontDescription::kWeightNormal, kFontWeightNormal); -STATIC_ASSERT_ENUM(WebFontDescription::kWeightBold, kFontWeightBold); STATIC_ASSERT_ENUM(WebFrameOwnerProperties::ScrollingMode::kAuto, kScrollbarAuto);
diff --git a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp index 0fbd7ce..8eaa0b6 100644 --- a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp +++ b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp
@@ -539,6 +539,7 @@ NavigationPolicy policy, bool replaces_current_history_item, bool is_client_redirect, + WebTriggeringEventInfo triggering_event_info, HTMLFormElement* form, ContentSecurityPolicyDisposition should_check_main_world_content_security_policy) { @@ -560,6 +561,7 @@ navigation_info.extra_data = ds ? ds->GetExtraData() : nullptr; navigation_info.replaces_current_history_item = replaces_current_history_item; navigation_info.is_client_redirect = is_client_redirect; + navigation_info.triggering_event_info = triggering_event_info; navigation_info.should_check_main_world_content_security_policy = should_check_main_world_content_security_policy == kCheckContentSecurityPolicy
diff --git a/third_party/WebKit/Source/web/LocalFrameClientImpl.h b/third_party/WebKit/Source/web/LocalFrameClientImpl.h index e1729b13..5ef26bd 100644 --- a/third_party/WebKit/Source/web/LocalFrameClientImpl.h +++ b/third_party/WebKit/Source/web/LocalFrameClientImpl.h
@@ -114,6 +114,7 @@ NavigationPolicy, bool should_replace_current_entry, bool is_client_redirect, + WebTriggeringEventInfo, HTMLFormElement*, ContentSecurityPolicyDisposition should_bypass_main_world_csp) override; void DispatchWillSendSubmitEvent(HTMLFormElement*) override;
diff --git a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp index 97de102..aae3b54f 100644 --- a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp +++ b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp
@@ -90,7 +90,6 @@ #include "public/platform/WebString.h" #include "public/web/WebDevToolsAgentClient.h" #include "public/web/WebSettings.h" -#include "web/WebFrameWidgetImpl.h" namespace blink { @@ -237,8 +236,7 @@ WebDevToolsAgentImpl* agent = new WebDevToolsAgentImpl(frame, client, false); if (frame->FrameWidget()) - agent->LayerTreeViewChanged( - ToWebFrameWidgetImpl(frame->FrameWidget())->LayerTreeView()); + agent->LayerTreeViewChanged(frame->FrameWidget()->GetLayerTreeView()); return agent; }
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h index f542cd51..e79fe7f01 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h +++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h
@@ -148,7 +148,6 @@ // Event related methods: void MouseContextMenu(const WebMouseEvent&); - WebLayerTreeView* LayerTreeView() const { return layer_tree_view_; } GraphicsLayer* RootGraphicsLayer() const override { return root_graphics_layer_; };
diff --git a/third_party/WebKit/Source/web/tests/AccessibilityObjectModelTest.cpp b/third_party/WebKit/Source/web/tests/AccessibilityObjectModelTest.cpp index 69a9154..684063bb 100644 --- a/third_party/WebKit/Source/web/tests/AccessibilityObjectModelTest.cpp +++ b/third_party/WebKit/Source/web/tests/AccessibilityObjectModelTest.cpp
@@ -79,7 +79,7 @@ auto* axTextBox = cache->GetOrCreate(textbox); EXPECT_EQ(kComboBoxRole, axTextBox->RoleValue()); AXNameFrom name_from; - AXObjectImpl::AXObjectVector name_objects; + AXObject::AXObjectVector name_objects; EXPECT_EQ("Combo", axTextBox->GetName(name_from, &name_objects)); EXPECT_FALSE(axTextBox->IsEnabled()); @@ -109,7 +109,7 @@ auto* axButton = cache->GetOrCreate(button); EXPECT_EQ(kCheckBoxRole, axButton->RoleValue()); AXNameFrom name_from; - AXObjectImpl::AXObjectVector name_objects; + AXObject::AXObjectVector name_objects; EXPECT_EQ("Check", axButton->GetName(name_from, &name_objects)); EXPECT_FALSE(axButton->IsEnabled());
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index 2e16c16..aba3857 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -9555,6 +9555,7 @@ KURL resource_url(kParsedURLString, "chrome://test.pdf"); ResourceRequest request(resource_url); request.SetRequestContext(WebURLRequest::kRequestContextObject); + request.SetFetchCredentialsMode(WebURLRequest::kFetchCredentialsModeOmit); RegisterMockedChromeURLLoad("test.pdf"); LocalFrame* frame( @@ -9565,8 +9566,7 @@ // First try to load the request with regular access. Should fail. options.fetch_request_mode = WebURLRequest::kFetchRequestModeCORS; - ResourceLoaderOptions resource_loader_options( - kDoNotAllowStoredCredentials, kClientDidNotRequestCredentials); + ResourceLoaderOptions resource_loader_options; DocumentThreadableLoader::LoadResourceSynchronously( *frame->GetDocument(), request, client, options, resource_loader_options); EXPECT_TRUE(client.Failed());
diff --git a/third_party/WebKit/public/BUILD.gn b/third_party/WebKit/public/BUILD.gn index cd29bd6..f688547 100644 --- a/third_party/WebKit/public/BUILD.gn +++ b/third_party/WebKit/public/BUILD.gn
@@ -600,6 +600,7 @@ "web/WebTextDirection.h", "web/WebTextInputType.h", "web/WebTreeScopeType.h", + "web/WebTriggeringEventInfo.h", "web/WebUserGestureIndicator.h", "web/WebUserGestureToken.h", "web/WebUserMediaClient.h",
diff --git a/third_party/WebKit/public/platform/WebData.h b/third_party/WebKit/public/platform/WebData.h index fcd3c686..acfa468 100644 --- a/third_party/WebKit/public/platform/WebData.h +++ b/third_party/WebKit/public/platform/WebData.h
@@ -35,7 +35,7 @@ #include "WebPrivatePtr.h" #if INSIDE_BLINK -#include "platform/wtf/PassRefPtr.h" +#include "platform/wtf/RefPtr.h" #endif namespace blink { @@ -77,9 +77,10 @@ bool IsNull() const { return private_.IsNull(); } #if INSIDE_BLINK - WebData(PassRefPtr<SharedBuffer>); - WebData& operator=(PassRefPtr<SharedBuffer>); - operator PassRefPtr<SharedBuffer>() const; + WebData(RefPtr<SharedBuffer>); + WebData& operator=(RefPtr<SharedBuffer>); + operator RefPtr<SharedBuffer>() const; + operator const SharedBuffer&() const; #else template <class C> WebData(const C& c) {
diff --git a/third_party/WebKit/public/platform/WebGestureEvent.h b/third_party/WebKit/public/platform/WebGestureEvent.h index 4cefc341..94d5657 100644 --- a/third_party/WebKit/public/platform/WebGestureEvent.h +++ b/third_party/WebKit/public/platform/WebGestureEvent.h
@@ -37,6 +37,7 @@ int global_x; int global_y; WebGestureDevice source_device; + bool is_source_touch_event_set_non_blocking; // If the WebGestureEvent has sourceDevice=WebGestureDeviceTouchscreen, this // field contains the unique identifier for the touch event that released
diff --git a/third_party/WebKit/public/platform/WebHTTPBody.h b/third_party/WebKit/public/platform/WebHTTPBody.h index 6cec78f..e128d189 100644 --- a/third_party/WebKit/public/platform/WebHTTPBody.h +++ b/third_party/WebKit/public/platform/WebHTTPBody.h
@@ -38,7 +38,7 @@ #include "WebURL.h" #if INSIDE_BLINK -#include "platform/wtf/PassRefPtr.h" +#include "platform/wtf/RefPtr.h" #endif namespace blink { @@ -106,10 +106,9 @@ BLINK_PLATFORM_EXPORT void SetContainsPasswordData(bool); #if INSIDE_BLINK - BLINK_PLATFORM_EXPORT WebHTTPBody(WTF::PassRefPtr<EncodedFormData>); - BLINK_PLATFORM_EXPORT WebHTTPBody& operator=( - WTF::PassRefPtr<EncodedFormData>); - BLINK_PLATFORM_EXPORT operator WTF::PassRefPtr<EncodedFormData>() const; + BLINK_PLATFORM_EXPORT WebHTTPBody(WTF::RefPtr<EncodedFormData>); + BLINK_PLATFORM_EXPORT WebHTTPBody& operator=(WTF::RefPtr<EncodedFormData>); + BLINK_PLATFORM_EXPORT operator WTF::RefPtr<EncodedFormData>() const; #endif private:
diff --git a/third_party/WebKit/public/platform/WebHTTPLoadInfo.h b/third_party/WebKit/public/platform/WebHTTPLoadInfo.h index cf2ca61..770dffca 100644 --- a/third_party/WebKit/public/platform/WebHTTPLoadInfo.h +++ b/third_party/WebKit/public/platform/WebHTTPLoadInfo.h
@@ -74,8 +74,8 @@ BLINK_PLATFORM_EXPORT void SetNPNNegotiatedProtocol(const WebString&); #if INSIDE_BLINK - BLINK_PLATFORM_EXPORT WebHTTPLoadInfo(WTF::PassRefPtr<ResourceLoadInfo>); - BLINK_PLATFORM_EXPORT operator WTF::PassRefPtr<ResourceLoadInfo>() const; + BLINK_PLATFORM_EXPORT WebHTTPLoadInfo(WTF::RefPtr<ResourceLoadInfo>); + BLINK_PLATFORM_EXPORT operator WTF::RefPtr<ResourceLoadInfo>() const; #endif private:
diff --git a/third_party/WebKit/public/web/WebAXObject.h b/third_party/WebKit/public/web/WebAXObject.h index 4581f0c3..9e2af54 100644 --- a/third_party/WebKit/public/web/WebAXObject.h +++ b/third_party/WebKit/public/web/WebAXObject.h
@@ -43,7 +43,7 @@ namespace blink { -class AXObjectImpl; +class AXObject; class ScopedAXObjectCache; class WebAXObject; class WebNode; @@ -82,7 +82,7 @@ std::unique_ptr<ScopedAXObjectCache> private_; }; -// A container for passing around a reference to AXObjectImpl. +// A container for passing around a reference to AXObject. class WebAXObject { public: ~WebAXObject() { Reset(); } @@ -359,13 +359,13 @@ BLINK_EXPORT void ScrollToGlobalPoint(const WebPoint&) const; #if BLINK_IMPLEMENTATION - BLINK_EXPORT WebAXObject(AXObjectImpl*); - WebAXObject& operator=(AXObjectImpl*); - operator AXObjectImpl*() const; + BLINK_EXPORT WebAXObject(AXObject*); + WebAXObject& operator=(AXObject*); + operator AXObject*() const; #endif private: - WebPrivatePtr<AXObjectImpl> private_; + WebPrivatePtr<AXObject> private_; }; } // namespace blink
diff --git a/third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h b/third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h index bccff23..b5b9e84 100644 --- a/third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h +++ b/third_party/WebKit/public/web/WebAssociatedURLLoaderOptions.h
@@ -43,21 +43,26 @@ WebAssociatedURLLoaderOptions() : untrusted_http(false), - allow_credentials(false), + fetch_request_mode(WebURLRequest::kFetchRequestModeSameOrigin), + fetch_credentials_mode(WebURLRequest::kFetchCredentialsModeOmit), expose_all_response_headers(false), - preflight_policy(kConsiderPreflight), - fetch_request_mode(WebURLRequest::kFetchRequestModeSameOrigin) {} + preflight_policy(kConsiderPreflight) {} // Whether to validate the method and headers as if this was an // XMLHttpRequest. bool untrusted_http; - // Whether to send HTTP credentials and cookies with the request. - bool allow_credentials; + + // The mode to use. See https://fetch.spec.whatwg.org/#concept-request-mode. + WebURLRequest::FetchRequestMode fetch_request_mode; + // The credentials mode to use. + // See https://fetch.spec.whatwg.org/#concept-request-credentials-mode + WebURLRequest::FetchCredentialsMode fetch_credentials_mode; + // If policy is to use access control, whether to expose non-whitelisted // response headers to the client. bool expose_all_response_headers; + PreflightPolicy preflight_policy; - WebURLRequest::FetchRequestMode fetch_request_mode; }; } // namespace blink
diff --git a/third_party/WebKit/public/web/WebFrameClient.h b/third_party/WebKit/public/web/WebFrameClient.h index a288fed..172cac3 100644 --- a/third_party/WebKit/public/web/WebFrameClient.h +++ b/third_party/WebKit/public/web/WebFrameClient.h
@@ -48,6 +48,7 @@ #include "WebNavigatorContentUtilsClient.h" #include "WebSandboxFlags.h" #include "WebTextDirection.h" +#include "WebTriggeringEventInfo.h" #include "public/platform/BlameContext.h" #include "public/platform/WebApplicationCacheHost.h" #include "public/platform/WebColor.h" @@ -327,6 +328,7 @@ bool replaces_current_history_item; bool is_history_navigation_in_new_child_frame; bool is_client_redirect; + WebTriggeringEventInfo triggering_event_info; WebFormElement form; bool is_cache_disabled; WebSourceLocation source_location; @@ -346,6 +348,7 @@ replaces_current_history_item(false), is_history_navigation_in_new_child_frame(false), is_client_redirect(false), + triggering_event_info(WebTriggeringEventInfo::kUnknown), is_cache_disabled(false), should_check_main_world_content_security_policy( kWebContentSecurityPolicyDispositionCheck),
diff --git a/third_party/WebKit/public/web/WebTriggeringEventInfo.h b/third_party/WebKit/public/web/WebTriggeringEventInfo.h new file mode 100644 index 0000000..206b7a3 --- /dev/null +++ b/third_party/WebKit/public/web/WebTriggeringEventInfo.h
@@ -0,0 +1,29 @@ +// 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 WebTriggeringEventInfo_h +#define WebTriggeringEventInfo_h + +namespace blink { + +// Extra info sometimes associated with a navigation. Mirrors +// theWebTriggeringEventInfoEnum. +enum class WebTriggeringEventInfo { + kUnknown, + + // The navigation was not triggered via a JS Event. + kNotFromEvent, + + // The navigation was triggered via a JS event with isTrusted() == true. + kFromTrustedEvent, + + // The navigation was triggered via a JS event with isTrusted() == false. + kFromUntrustedEvent, + + kLast, +}; + +} // namespace blink + +#endif // WebTriggeringEventInfo_h
diff --git a/third_party/mach_override/README.chromium b/third_party/mach_override/README.chromium index 8a7c3fd..8d1d95ae 100644 --- a/third_party/mach_override/README.chromium +++ b/third_party/mach_override/README.chromium
@@ -1,6 +1,6 @@ Name: mach_override Short Name: mach_override -Version: Newer than 1.2. HEAD from branch semver-1.x. +Version: unknown URL: https://github.com/rentzsch/mach_override Date: 2014-05-11 Revision: 919148f94db54fc04d287eb6a42c0c36b166bbfa @@ -16,4 +16,5 @@ http://udis86.sourceforge.net/ and https://github.com/vmt/udis86 . -Local Modifications: None. +Local Modifications: Sped up allocation of branch island memory via usage of + vm_region to skip already allocated pages.
diff --git a/third_party/mach_override/chromium.patch b/third_party/mach_override/chromium.patch new file mode 100644 index 0000000..dba82cd --- /dev/null +++ b/third_party/mach_override/chromium.patch
@@ -0,0 +1,123 @@ +diff --git a/third_party/mach_override/README.chromium b/third_party/mach_override/README.chromium +index 8a7c3fd79e0b..8d1d95ae0037 100644 +--- a/third_party/mach_override/README.chromium ++++ b/third_party/mach_override/README.chromium +@@ -1,6 +1,6 @@ + Name: mach_override + Short Name: mach_override +-Version: Newer than 1.2. HEAD from branch semver-1.x. ++Version: unknown + URL: https://github.com/rentzsch/mach_override + Date: 2014-05-11 + Revision: 919148f94db54fc04d287eb6a42c0c36b166bbfa +@@ -16,4 +16,5 @@ mach_override includes a copy of libudis86 1.7.1, available separately from + http://udis86.sourceforge.net/ and https://github.com/vmt/udis86 . + + +-Local Modifications: None. ++Local Modifications: Sped up allocation of branch island memory via usage of ++ vm_region to skip already allocated pages. +diff --git a/third_party/mach_override/chromium.patch b/third_party/mach_override/chromium.patch +new file mode 100644 +index 000000000000..e69de29bb2d1 +diff --git a/third_party/mach_override/mach_override.c b/third_party/mach_override/mach_override.c +index 85a75e5c2067..d822520fa00c 100644 +--- a/third_party/mach_override/mach_override.c ++++ b/third_party/mach_override/mach_override.c +@@ -41,7 +41,7 @@ long kIslandTemplate[] = { + #define kInstructionHi 10 + #define kInstructionLo 11 + +-#elif defined(__i386__) ++#elif defined(__i386__) + + #define kOriginalInstructionsSize 16 + +@@ -61,6 +61,7 @@ char kIslandTemplate[] = { + #define kOriginalInstructionsSize 32 + + #define kJumpAddress kOriginalInstructionsSize + 6 ++#define kMaxJumpOffset (0x7fffffffUL) + + char kIslandTemplate[] = { + // kOriginalInstructionsSize nop instructions so that we +@@ -267,7 +268,13 @@ mach_override_ptr( + + #if defined(__i386__) || defined(__x86_64__) + if (!err) { +- uint32_t addressOffset = ((char*)escapeIsland - (char*)originalFunctionPtr - 5); ++ // TODO: On 64-bit, move to opcode FF/4 (jmp 64-bit absolute indirect) ++ // instead of E9 (jmp 32-bit relative to RIP). Then we should update ++ // allocateBranchIsland to simply allocate any page in the address space. ++ // See the 64-bit version of kIslandTemplate array. ++ int64_t addressOffset64 = ((char*)escapeIsland - (char*)originalFunctionPtr - 5); ++ int32_t addressOffset = addressOffset64; ++ assert(addressOffset64 == addressOffset); + addressOffset = OSSwapInt32(addressOffset); + + jumpRelativeInstruction |= 0xE900000000000000LL; +@@ -385,7 +392,7 @@ allocateBranchIsland( + void *originalFunctionAddress) + { + assert( island ); +- ++ + mach_error_t err = err_none; + + if( allocateHigh ) { +@@ -401,23 +408,41 @@ allocateBranchIsland( + vm_address_t first = 0xfeffffff; + vm_address_t last = 0xfe000000 + PAGE_SIZE; + #elif defined(__x86_64__) +- // 64-bit ASLR is in bits 13-28 +- vm_address_t first = ((uint64_t)originalFunctionAddress & ~( (0xFUL << 28) | (PAGE_SIZE - 1) ) ) | (0x1UL << 31); +- vm_address_t last = (uint64_t)originalFunctionAddress & ~((0x1UL << 32) - 1); ++ // This logic is more complex due to the 32-bit limit of the jump out ++ // of the original function. Once that limitation is removed, we can ++ // use vm_allocate with VM_FLAGS_ANYWHERE as in the i386 code above. ++ const uint64_t kPageMask = ~(PAGE_SIZE - 1); ++ vm_address_t first = (uint64_t)originalFunctionAddress - kMaxJumpOffset; ++ first = (first & kPageMask) + PAGE_SIZE; // Align up to the next page start ++ if (first > (uint64_t)originalFunctionAddress) first = 0; ++ vm_address_t last = (uint64_t)originalFunctionAddress + kMaxJumpOffset; ++ if (last < (uint64_t)originalFunctionAddress) last = ULONG_MAX; + #endif + + page = first; + int allocated = 0; + vm_map_t task_self = mach_task_self(); + +- while( !err && !allocated && page != last ) { ++ while( !err && !allocated && page < last ) { + + err = vm_allocate( task_self, &page, PAGE_SIZE, 0 ); + if( err == err_none ) + allocated = 1; + else if( err == KERN_NO_SPACE ) { + #if defined(__x86_64__) +- page -= PAGE_SIZE; ++ // This memory region is not suitable, skip it: ++ vm_size_t region_size; ++ mach_msg_type_number_t int_count = VM_REGION_BASIC_INFO_COUNT_64; ++ vm_region_basic_info_data_64_t vm_region_info; ++ mach_port_t object_name; ++ // The call will move 'page' to the beginning of the region: ++ err = vm_region_64(task_self, &page, ®ion_size, ++ VM_REGION_BASIC_INFO_64, (vm_region_info_t)&vm_region_info, ++ &int_count, &object_name); ++ if (err == KERN_SUCCESS) ++ page += region_size; ++ else ++ break; + #else + page += PAGE_SIZE; + #endif +@@ -438,7 +463,7 @@ allocateBranchIsland( + } + if( !err ) + (**island).allocatedHigh = allocateHigh; +- ++ + return err; + } +
diff --git a/third_party/mach_override/mach_override.c b/third_party/mach_override/mach_override.c index 85a75e5c..d822520 100644 --- a/third_party/mach_override/mach_override.c +++ b/third_party/mach_override/mach_override.c
@@ -41,7 +41,7 @@ #define kInstructionHi 10 #define kInstructionLo 11 -#elif defined(__i386__) +#elif defined(__i386__) #define kOriginalInstructionsSize 16 @@ -61,6 +61,7 @@ #define kOriginalInstructionsSize 32 #define kJumpAddress kOriginalInstructionsSize + 6 +#define kMaxJumpOffset (0x7fffffffUL) char kIslandTemplate[] = { // kOriginalInstructionsSize nop instructions so that we @@ -267,7 +268,13 @@ #if defined(__i386__) || defined(__x86_64__) if (!err) { - uint32_t addressOffset = ((char*)escapeIsland - (char*)originalFunctionPtr - 5); + // TODO: On 64-bit, move to opcode FF/4 (jmp 64-bit absolute indirect) + // instead of E9 (jmp 32-bit relative to RIP). Then we should update + // allocateBranchIsland to simply allocate any page in the address space. + // See the 64-bit version of kIslandTemplate array. + int64_t addressOffset64 = ((char*)escapeIsland - (char*)originalFunctionPtr - 5); + int32_t addressOffset = addressOffset64; + assert(addressOffset64 == addressOffset); addressOffset = OSSwapInt32(addressOffset); jumpRelativeInstruction |= 0xE900000000000000LL; @@ -385,7 +392,7 @@ void *originalFunctionAddress) { assert( island ); - + mach_error_t err = err_none; if( allocateHigh ) { @@ -401,23 +408,41 @@ vm_address_t first = 0xfeffffff; vm_address_t last = 0xfe000000 + PAGE_SIZE; #elif defined(__x86_64__) - // 64-bit ASLR is in bits 13-28 - vm_address_t first = ((uint64_t)originalFunctionAddress & ~( (0xFUL << 28) | (PAGE_SIZE - 1) ) ) | (0x1UL << 31); - vm_address_t last = (uint64_t)originalFunctionAddress & ~((0x1UL << 32) - 1); + // This logic is more complex due to the 32-bit limit of the jump out + // of the original function. Once that limitation is removed, we can + // use vm_allocate with VM_FLAGS_ANYWHERE as in the i386 code above. + const uint64_t kPageMask = ~(PAGE_SIZE - 1); + vm_address_t first = (uint64_t)originalFunctionAddress - kMaxJumpOffset; + first = (first & kPageMask) + PAGE_SIZE; // Align up to the next page start + if (first > (uint64_t)originalFunctionAddress) first = 0; + vm_address_t last = (uint64_t)originalFunctionAddress + kMaxJumpOffset; + if (last < (uint64_t)originalFunctionAddress) last = ULONG_MAX; #endif page = first; int allocated = 0; vm_map_t task_self = mach_task_self(); - while( !err && !allocated && page != last ) { + while( !err && !allocated && page < last ) { err = vm_allocate( task_self, &page, PAGE_SIZE, 0 ); if( err == err_none ) allocated = 1; else if( err == KERN_NO_SPACE ) { #if defined(__x86_64__) - page -= PAGE_SIZE; + // This memory region is not suitable, skip it: + vm_size_t region_size; + mach_msg_type_number_t int_count = VM_REGION_BASIC_INFO_COUNT_64; + vm_region_basic_info_data_64_t vm_region_info; + mach_port_t object_name; + // The call will move 'page' to the beginning of the region: + err = vm_region_64(task_self, &page, ®ion_size, + VM_REGION_BASIC_INFO_64, (vm_region_info_t)&vm_region_info, + &int_count, &object_name); + if (err == KERN_SUCCESS) + page += region_size; + else + break; #else page += PAGE_SIZE; #endif @@ -438,7 +463,7 @@ } if( !err ) (**island).allocatedHigh = allocateHigh; - + return err; }
diff --git a/third_party/usrsctp/README.chromium b/third_party/usrsctp/README.chromium index fa30f26..598a214 100644 --- a/third_party/usrsctp/README.chromium +++ b/third_party/usrsctp/README.chromium
@@ -1,8 +1,8 @@ Name: usrsctp URL: http://github.com/sctplab/usrsctp Version: 0 -Date: 4 Nov 2015 -Revision: ef6e3302205dbadf0584b712f53e48159be2dffb +Date: Jul 25, 2016 +Revision: 9a3e5465e9d96d8a7f78f1e996412d6235d7a359 License: New BSD License File: LICENSE Security Critical: yes
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 75faca3d..545c1e581 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -340,7 +340,7 @@ 'Android arm64 Builder': 'official_goma_minimal_symbols_android_arm64', 'Android Compile': 'official_goma_minimal_symbols_android', 'Android arm64 Compile': 'official_goma_minimal_symbols_android_arm64', - 'Linux Builder': 'official_goma', + 'Linux Builder': 'official_goma_perf', 'Mac Builder': 'official_goma', 'Win Builder': 'official_goma_x86', 'Win x64 Builder': 'official_goma', @@ -1362,6 +1362,10 @@ 'official', 'goma', ], + 'official_goma_perf': [ + 'official', 'goma', 'no_gnome_keyring', + ], + 'official_goma_chromeos': [ 'official', 'goma', 'chromeos', 'x11_cros', ], @@ -1834,6 +1838,10 @@ 'gn_args': 'android_ndk_version="r13b" android_ndk_major_version=13', }, + 'no_gnome_keyring': { + 'gn_args': 'use_gnome_keyring=false', + }, + 'no_pch': { 'gn_args': 'enable_precompiled_headers=false', },
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 4658371..196c83b 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -5737,6 +5737,16 @@ <int value="37" label="Share link"/> </enum> +<enum name="ContextMenuSaveImage"> + <summary>Context menu type related to the save image option.</summary> + <int value="0" label="Loaded"/> + <int value="1" label="Image was fatched LoFi"/> + <int value="2" label="Not downloadable scheme"/> + <int value="3" label="No save image option and param is not image"/> + <int value="4" label="No save image option and param is image"/> + <int value="5" label="Save image option shown"/> +</enum> + <enum name="ContextMenuSaveLinkType"> <summary> The content type when user chooses save link context menu option @@ -24861,6 +24871,13 @@ <int value="8" label="Cancelled by native for other reasons"/> </enum> +<enum name="MobileDownloadDuplicateInfobar"> + <int value="0" label="Infobar shown"/> + <int value="1" label="Download canceled"/> + <int value="2" label="No download dir"/> + <int value="3" label="Create new file"/> +</enum> + <enum name="MobileDownloadInterceptFailureReason"> <int value="0" label="No failure"/> <int value="1" label="Empty url"/> @@ -24879,6 +24896,14 @@ <int value="4" label="Resumption auto started"/> </enum> +<enum name="MobileDownloadStoragePermission"> + <int value="0" label="Storage permission is requested"/> + <int value="1" label="Already has storage permission"/> + <int value="2" label="Storage permission is granted"/> + <int value="3" label="Storage permission is denied"/> + <int value="4" label="Storage permission failed due to missing WebContents"/> +</enum> + <enum name="MobileFreProgress"> <int value="0" label="FRE started"/> <int value="1" label="Welcome shown"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index f81d3e5..99d8a56 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -32242,6 +32242,15 @@ <summary>Android: Records the reason that a download is canceled.</summary> </histogram> +<histogram name="MobileDownload.ContextMenu.SaveImage" + enum="ContextMenuSaveImage"> + <owner>qinmin@chromium.org</owner> + <summary> + Android: Records various counts related to the save image context menu + option. + </summary> +</histogram> + <histogram name="MobileDownload.DownloadResumption" enum="MobileDownloadResumption"> <owner>qinmin@chromium.org</owner> @@ -32257,6 +32266,14 @@ </summary> </histogram> +<histogram name="MobileDownload.DuplicateInfobar" + enum="MobileDownloadDuplicateInfobar"> + <owner>qinmin@chromium.org</owner> + <summary> + Android: Records various counts related to the duplicate download infobar. + </summary> +</histogram> + <histogram name="MobileDownload.InterceptFailureReason" enum="MobileDownloadInterceptFailureReason"> <obsolete> @@ -32301,6 +32318,14 @@ </summary> </histogram> +<histogram name="MobileDownload.StoragePermission" + enum="MobileDownloadStoragePermission"> + <owner>qinmin@chromium.org</owner> + <summary> + Android: Records various counts when requesting the storage permission. + </summary> +</histogram> + <histogram name="MobileFre.Progress" enum="MobileFreProgress"> <owner>gogerald@chromium.org</owner> <summary> @@ -75670,14 +75695,6 @@ </summary> </histogram> -<histogram name="Sync.ModelTypeMemoryKB" units="KB"> - <owner>pavely@chromium.org</owner> - <summary> - Estimated memory usage by sync datatype in kilobytes. Recorded after sync - configuration. - </summary> -</histogram> - <histogram name="Sync.ModelTypeStoreInitResult" enum="SyncModelTypeStoreInitResult"> <owner>pavely@chromium.org</owner> @@ -95734,7 +95751,6 @@ <suffix name="USER_EVENT" label="USER_EVENT"/> <suffix name="WIFI_CREDENTIAL" label="WIFI_CREDENTIAL"/> <affected-histogram name="Sync.ModelTypeCount"/> - <affected-histogram name="Sync.ModelTypeMemoryKB"/> </histogram_suffixes> <histogram_suffixes name="SyzygyStartupTime" separator="_">
diff --git a/tools/traffic_annotation/auditor/BUILD.gn b/tools/traffic_annotation/auditor/BUILD.gn index bd3606fb..6e6c720 100644 --- a/tools/traffic_annotation/auditor/BUILD.gn +++ b/tools/traffic_annotation/auditor/BUILD.gn
@@ -41,9 +41,20 @@ use_protobuf_full = true } -group("traffic_annotation_auditor") { +executable("traffic_annotation_auditor") { + sources = [ + "../../../net/traffic_annotation/network_traffic_annotation.h", + "../../../net/traffic_annotation/network_traffic_annotation_test_helper.h", + "traffic_annotation_auditor.cc", + "traffic_annotation_auditor.h", + "traffic_annotation_auditor_ui.cc", + "traffic_annotation_file_filter.cc", + "traffic_annotation_file_filter.h", + ] + deps = [ ":traffic_annotation", + "//base", "//third_party/protobuf:protobuf_full", ] }
diff --git a/tools/traffic_annotation/auditor/README.md b/tools/traffic_annotation/auditor/README.md index 41aafc0..a6a8326 100644 --- a/tools/traffic_annotation/auditor/README.md +++ b/tools/traffic_annotation/auditor/README.md
@@ -1,27 +1,24 @@ # Network Traffic Annotation Auditor -This script runs the clang tool for extraction of Network Traffic Annotations -from chromium source code and collects and summarizes its outputs. - -## Running -1. `ninja -C [build directory] traffic_annotation_auditor` -2. Copy * from `[build_directory]/pyproto/tools/traffic_annotation` to - `tools/traffic_annotation/auditor` +This executable runs the clang tool for extraction of Network Traffic +Annotations from chromium source code and collects and summarizes its outputs. ## Usage -`traffic_annotation_auditor.py [OPTION]... [path_filter]...` +`traffic_annotation_auditor [OPTION]... [path_filter]...` Extracts network traffic annotations from source files. If path filter(s) are specified, only those directories of the source will be analyzed. -Run `traffic_annotation_auditor.py --help` for options. +Run `traffic_annotation_auditor --help` for options. Example: - `traffic_annotation_auditor.py --build-dir=out/Debug --summary-file= + `traffic_annotation_auditor --build-dir=out/Debug --summary-file= report.txt` +## Running on Linux +Before running the script as above, you should build the COMPLETE chromium. ## Running on Windows -Before running the script as above, you should build COMPLETE chromium with +Before running the script as above, you should build the COMPLETE chromium with clang with keeprsp switch as follows: 1. `gn args [build_dir, e.g. out\Debug]` 2. add `is_clang=true` to the opened text file and save and close it. -3. `ninja -C [build_dir] -d keeprsp -k 1000` +3. `ninja -C [build_dir] -d keeprsp`
diff --git a/tools/traffic_annotation/auditor/prepare_protobuf.py b/tools/traffic_annotation/auditor/prepare_protobuf.py deleted file mode 100644 index 6d986aa6..0000000 --- a/tools/traffic_annotation/auditor/prepare_protobuf.py +++ /dev/null
@@ -1,36 +0,0 @@ -# Copyright (c) 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. - -""" This code is imported with modifications from -'//infra/recipes-py/recipe_engine/env.py' to import protobuf from third_party -directory instead of the one installed with current python libraries.""" - -import contextlib -import pkg_resources -import os -import sys - - -def PrepareProtobuf(): - CHROME_SRC = os.path.abspath( - os.path.join(os.path.dirname(os.path.realpath(__file__)), - "..", "..", "..")) - THIRD_PARTY = os.path.join(CHROME_SRC, 'third_party') - sys.path.insert(0, os.path.join(THIRD_PARTY, 'protobuf', 'python')) - sys.path.insert( - 1, os.path.join(THIRD_PARTY, 'protobuf', 'third_party', 'six')) - - @contextlib.contextmanager - def temp_sys_path(): - orig_path = sys.path[:] - try: - yield - finally: - sys.path = orig_path - - with temp_sys_path(): - sys.path = [THIRD_PARTY] - sys.modules.pop('google', None) - pkg_resources.declare_namespace('google') - pkg_resources.fixup_namespace_packages(THIRD_PARTY)
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc new file mode 100644 index 0000000..cc452512 --- /dev/null +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc
@@ -0,0 +1,280 @@ +// 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 "tools/traffic_annotation/auditor/traffic_annotation_auditor.h" + +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/process/launch.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "third_party/protobuf/src/google/protobuf/text_format.h" +#include "tools/traffic_annotation/auditor/traffic_annotation_file_filter.h" + +namespace { + +// Recursively compute the hash code of the given string as in: +// "net/traffic_annotation/network_traffic_annotation.h" +uint32_t recursive_hash(const char* str, int N) { + if (N == 1) + return static_cast<uint32_t>(str[0]); + else + return (recursive_hash(str, N - 1) * 31 + str[N - 1]) % 138003713; +} + +} // namespace + +namespace traffic_annotation_auditor { + +AnnotationInstance::AnnotationInstance() + : annotation_type(AnnotationType::ANNOTATION_COMPLETE) {} + +AnnotationInstance::AnnotationInstance(const AnnotationInstance& other) + : proto(other.proto), + annotation_type(other.annotation_type), + extra_id(other.extra_id), + unique_id_hash_code(other.unique_id_hash_code), + extra_id_hash_code(other.extra_id_hash_code){}; + +bool AnnotationInstance::Deserialize( + const std::vector<std::string>& serialized_lines, + int start_line, + int end_line, + std::string* error_text) { + if (end_line - start_line < 7) { + LOG(ERROR) << "Not enough lines to deserialize annotation."; + *error_text = "FATAL"; + return false; + } + + // Extract header lines. + const std::string& file_path = serialized_lines[start_line++]; + const std::string& function_context = serialized_lines[start_line++]; + int line_number; + base::StringToInt(serialized_lines[start_line++], &line_number); + std::string function_type = serialized_lines[start_line++]; + const std::string& unique_id = serialized_lines[start_line++]; + extra_id = serialized_lines[start_line++]; + + // Decode function type. + if (function_type == "Definition") { + annotation_type = AnnotationType::ANNOTATION_COMPLETE; + } else if (function_type == "Partial") { + annotation_type = AnnotationType::ANNOTATION_PARTIAL; + } else if (function_type == "Completing") { + annotation_type = AnnotationType::ANNOTATION_COMPLETENG; + } else if (function_type == "BranchedCompleting") { + annotation_type = AnnotationType::ANNOTATION_BRANCHED_COMPLETING; + } else { + LOG(ERROR) << "Unexpected function type: " << function_type; + *error_text = "FATAL"; + return false; + } + + // Process test tags. + unique_id_hash_code = ComputeHashValue(unique_id); + if (unique_id_hash_code == TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code || + unique_id_hash_code == + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code) { + return false; + } + + // Process undefined tags. + if (unique_id_hash_code == NO_TRAFFIC_ANNOTATION_YET.unique_id_hash_code || + unique_id_hash_code == + NO_PARTIAL_TRAFFIC_ANNOTATION_YET.unique_id_hash_code) { + *error_text = base::StringPrintf( + "Annotation is defined with temporary tag for file '%s', line %i.", + file_path.c_str(), line_number); + return false; + } + + // Process missing tag. + if (unique_id_hash_code == MISSING_TRAFFIC_ANNOTATION.unique_id_hash_code) { + *error_text = + base::StringPrintf("Missing annotation in file '%s', line %i.", + file_path.c_str(), line_number); + return false; + } + + // Decode serialized proto. + std::string annotation_text = ""; + while (start_line < end_line) { + annotation_text += serialized_lines[start_line++] + "\n"; + } + if (!google::protobuf::TextFormat::ParseFromString( + annotation_text, (google::protobuf::Message*)&proto)) { + // TODO(rhalavati@): Find exact error message using: + // google::protobuf::io::ErrorCollector error_collector; + // google::protobuf::TextFormat::Parser::RecordErrorsTo(&error_collector); + *error_text = + base::StringPrintf("Could not parse protobuf for file '%s', line %i.", + file_path.c_str(), line_number); + return false; + } + + // Add other fields. + traffic_annotation::NetworkTrafficAnnotation_TrafficSource* src = + proto.mutable_source(); + src->set_file(file_path); + src->set_function(function_context); + src->set_line(line_number); + proto.set_unique_id(unique_id); + extra_id_hash_code = ComputeHashValue(extra_id); + + return true; +} + +CallInstance::CallInstance() : line_number(0), is_annotated(false) {} + +CallInstance::CallInstance(const CallInstance& other) + : file_path(other.file_path), + line_number(other.line_number), + function_context(other.function_context), + function_name(other.function_name), + is_annotated(other.is_annotated){}; + +bool CallInstance::Deserialize(const std::vector<std::string>& serialized_lines, + int start_line, + int end_line, + std::string* error_text) { + if (end_line - start_line != 5) { + LOG(ERROR) << "Incorrect number of lines to deserialize call."; + *error_text = "FATAL"; + return false; + } + + file_path = serialized_lines[start_line++]; + function_context = serialized_lines[start_line++]; + int line_number_int; + base::StringToInt(serialized_lines[start_line++], &line_number_int); + line_number = static_cast<uint32_t>(line_number_int); + function_name = serialized_lines[start_line++]; + int is_annotated_int; + base::StringToInt(serialized_lines[start_line++], &is_annotated_int); + is_annotated = is_annotated_int != 0; + return true; +} + +int ComputeHashValue(const std::string& unique_id) { + return unique_id.length() ? static_cast<int>(recursive_hash( + unique_id.c_str(), unique_id.length())) + : -1; +} + +std::string RunClangTool(const base::FilePath& source_path, + const base::FilePath& build_path, + const base::CommandLine::StringVector& path_filters, + const bool full_run) { + base::CommandLine cmdline(source_path.Append(FILE_PATH_LITERAL("tools")) + .Append(FILE_PATH_LITERAL("clang")) + .Append(FILE_PATH_LITERAL("scripts")) + .Append(FILE_PATH_LITERAL("run_tool.py"))); + cmdline.AppendSwitch("generate-compdb"); + cmdline.AppendSwitch("tool=traffic_annotation_extractor"); + cmdline.AppendArg( + base::StringPrintf("-p=%s", build_path.MaybeAsASCII().c_str())); + + if (full_run) { + for (const auto& path : path_filters) + cmdline.AppendArgNative(path); + } else { + TrafficAnnotationFileFilter filter; + std::vector<std::string> file_paths; + + if (path_filters.size()) { + for (const auto& path_filter : path_filters) { + filter.GetRelevantFiles(source_path, +#if defined(OS_WIN) + base::UTF16ToASCII(path_filter), +#else + path_filter, +#endif + &file_paths); + } + } else { + filter.GetRelevantFiles(source_path, "", &file_paths); + } + + if (!file_paths.size()) + return ""; + for (const auto& file_path : file_paths) + cmdline.AppendArg(file_path); + } + +#if defined(OS_WIN) + cmdline.PrependWrapper(L"python"); +#endif + + std::string results; + return base::GetAppOutput(cmdline, &results) ? results : ""; +} + +bool ParseClangToolRawOutput(const std::string& clang_output, + std::vector<AnnotationInstance>* annotations, + std::vector<CallInstance>* calls, + std::vector<std::string>* errors) { + // Remove possible carriage return characters before splitting lines. + std::string trimmed_input; + base::RemoveChars(clang_output, "\r", &trimmed_input); + std::vector<std::string> lines = base::SplitString( + trimmed_input, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + + for (unsigned int current = 0; current < lines.size(); current++) { + bool annotation_block; + if (lines[current] == "==== NEW ANNOTATION ====") + annotation_block = true; + else if (lines[current] == "==== NEW CALL ====") { + annotation_block = false; + } else if (lines[current].empty()) { + continue; + } else { + LOG(ERROR) << "Unexpected token at line: " << current; + return false; + } + + // Get the block. + current++; + unsigned int end_line = current; + std::string end_marker = + annotation_block ? "==== ANNOTATION ENDS ====" : "==== CALL ENDS ===="; + while (end_line < lines.size() && lines[end_line] != end_marker) + end_line++; + if (end_line == lines.size()) { + LOG(ERROR) << "Block starting at line " << current + << " is not ended by the appropriate tag."; + return false; + } + + // Deserialize and handle errors. + std::string error_text; + if (annotation_block) { + AnnotationInstance new_annotation; + if (new_annotation.Deserialize(lines, current, end_line, &error_text)) + annotations->push_back(new_annotation); + } else { + CallInstance new_call; + if (new_call.Deserialize(lines, current, end_line, &error_text)) + calls->push_back(new_call); + } + if (!error_text.empty()) { + if (error_text == "FATAL") { + LOG(ERROR) << "Aborting after line " << current << "."; + return false; + } + errors->push_back(error_text); + } + + current = end_line; + } // for + + return true; +} + +} // namespace traffic_annotation_auditor \ No newline at end of file
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.h b/tools/traffic_annotation/auditor/traffic_annotation_auditor.h new file mode 100644 index 0000000..2a1b9055 --- /dev/null +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor.h
@@ -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. + +#ifndef TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ +#define TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "tools/traffic_annotation/traffic_annotation.pb.h" + +namespace traffic_annotation_auditor { + +// Holds an instance of network traffic annotation. +// TODO(rhalavati): Check if this class can also be reused in clang tool. +class AnnotationInstance { + public: + // Annotation Type + enum class AnnotationType { + ANNOTATION_COMPLETE, + ANNOTATION_PARTIAL, + ANNOTATION_COMPLETENG, + ANNOTATION_BRANCHED_COMPLETING + }; + + AnnotationInstance(); + AnnotationInstance(const AnnotationInstance& other); + + // Deserializes an instance from serialized lines of the text provided by the + // clang tool. + // |serialized_lines| are read from |start_line| to |end_line| and should + // contain the following lines: + // 1- File path. + // 2- Name of the function including this annotation. + // 3- Line number. + // 4- Annotation function Type. + // 5- Unique id of annotation. + // 6- Completing id or group id, when applicable, empty otherwise. + // 7- Serialization of annotation text (several lines). + // If the annotation is correctly read and should be stored (is not test, + // not available, or missing), returns true, otherwise false. + // If any error happens, |error_text| will be set. If it would be set to + // FATAL, furthur processing of the text should be stopped. + bool Deserialize(const std::vector<std::string>& serialized_lines, + int start_line, + int end_line, + std::string* error_text); + + // Protobuf of the annotation. + traffic_annotation::NetworkTrafficAnnotation proto; + + // Type of the annotation. + AnnotationType annotation_type; + + // Extra id of the annotation (if available). + std::string extra_id; + + // Hash codes of unique id and extra id (if available). + int unique_id_hash_code; + int extra_id_hash_code; +}; + +// Holds an instance of calling a function that might have a network traffic +// annotation argument. +// TODO(rhalavati): Check if this class can also be reused in clang tool. +class CallInstance { + public: + CallInstance(); + CallInstance(const CallInstance& other); + + // Deserializes an instance from serialized lines of text provided by the + // clang tool. + // |serialized_lines| are read from |start_line| to |end_line| and should + // contain the following lines: + // 1- File path. + // 2- Name of the function in which the call is made. + // 3- Name of the called function. + // 4- Does the call have an annotation? + // If the call instance is correctly read returns true, otherwise false. + // If any error happens, |error_text| will be set. If it would be set to + // FATAL, further processing of the text should be stopped. + bool Deserialize(const std::vector<std::string>& serialized_lines, + int start_line, + int end_line, + std::string* error_text); + + std::string file_path; + uint32_t line_number; + + // Name of the function in which annotation is defined. + std::string function_context; + + // Name of the function that may need annotation. + std::string function_name; + + // Is function |function_name| annotated? + bool is_annotated; +}; + +// Runs traffic_annotation_extractor clang tool and returns its output. +std::string RunClangTool(const base::FilePath& source_path, + const base::FilePath& build_path, + const base::CommandLine::StringVector& path_filters, + bool full_run); + +// Parses the output of clang tool and populates instances, calls, and errors. +// Errors include not finding the file, incorrect content, or missing or not +// provided annotations. +bool ParseClangToolRawOutput(const std::string& clang_output, + std::vector<AnnotationInstance>* annotations, + std::vector<CallInstance>* calls, + std::vector<std::string>* errors); + +// Computes the hash value of a traffic annotation unique id. +int ComputeHashValue(const std::string& unique_id); + +} // namespace traffic_annotation_auditor + +#endif // TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ \ No newline at end of file
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.py b/tools/traffic_annotation/auditor/traffic_annotation_auditor.py deleted file mode 100755 index 54a83c3..0000000 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor.py +++ /dev/null
@@ -1,307 +0,0 @@ -#!/usr/bin/env python -# 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. - -"""This script is used to extract network traffic annotations from Chrome. -Please refer to README.md for running steps.""" - -import argparse -import datetime -import os -import subprocess -import sys -import tempfile - -from traffic_annotation_file_filter import TrafficAnnotationFileFilter - - -# These two lines are required to import protobuf from third_party directory -# instead of the one installed with python. -from prepare_protobuf import PrepareProtobuf -PrepareProtobuf() - -from google.protobuf import text_format -import traffic_annotation_pb2 - - -def _RecursiveHash(string): - if len(string) == 1: - return ord(string[0]) - last_character = ord(string[-1]) - string = string[:-1] - return (_RecursiveHash(string) * 31 + last_character) % 138003713 - - -def _ComputeStringHash(unique_id): - """Computes the hash value of a string, as in - 'net/traffic_annotation/network_traffic_annotation.h'. - args: - unique_id: str The string to be converted to hash code. - - Returns: - unsigned int Hash code of the input string - """ - return _RecursiveHash(unique_id) if len(unique_id) else -1 - - -def _RunClangTool(src_dir, build_dir, path_filters, prefilter_files): - """Executes the clang tool to extract annotations. - Args: - src_dir: str Path to the src directory of Chrome. - build_dir: str Path to the build directory. - path_filters: list of str List of paths to source directories for - extraction. - prefilter_files: bool Flag stating if source files should be first filtered - using annotation related keywords and then given to clang tool. - - Returns: - str Output of clang tool (extracted content and metadata of annotations). - """ - args = [ - src_dir + "/tools/clang/scripts/run_tool.py", - "--generate-compdb", - "--tool=traffic_annotation_extractor", - "-p=" + build_dir] - if sys.platform == "win32": - args.insert(0, "python") - - if prefilter_files: - file_filter = TrafficAnnotationFileFilter(False) - for path in path_filters: - args += file_filter.GetFilteredFilesList(path) - else: - args += path_filters - - command = subprocess.Popen(args, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - stdout_text, stderr_text = command.communicate() - if stderr_text: - print stderr_text - return stdout_text - - -def _ParsRawAnnotations(raw_annotations): - """Parses raw annotations texts which are received from the clang tool. - Args: - raw_annotations: str Serialization of annotations and metadata. Each - annotation should have either of the following lines: - 1- "==== NEW ANNOTATION ====" - 2- File path. - 3- Name of the function including this position. - 4- Line number. - 5- Function Type. - 6- Unique id of annotation. - 7- Completing id or group id, when applicable, empty otherwise. - 8- Serialization of annotation text (several lines) - n- "==== ANNOTATION ENDS ====" - or: - 1: "==== NEW CALL ====" - 2: File path. - 3: Name of the function in which the call is made. - 4: Name of the called function. - 5: Does the call have an annotation? - 6: "==== CALL ENDS ====" - - Returns: - annotations: ExtractedNetworkTrafficAnnotation A protobuf including all - extracted annotations. - metadata: list of dict List of metadata for each annotation. Each item - includes the following fields: - function_type: str Type of the function that defines the annotation. - extra_id: str Possible prefix for annotation completion. - errors: list of str List of errors. - """ - annotations = traffic_annotation_pb2.ExtractedNetworkTrafficAnnotation() - errors = [] - metadata = [] - - lines = [line.strip("\r\n") for line in raw_annotations.split("\n")] - current = 0 - - try: - while current < len(lines) - 1: - if lines[current] == "==== NEW ANNOTATION ====": - if current + 6 >= len(lines): - raise Exception( - "Not enough header lines at line %i." % current) - - # Extract header lines. - source = traffic_annotation_pb2.NetworkTrafficAnnotation.TrafficSource() - source.file = lines[current + 1] - source.function = lines[current + 2] - source.line = int(lines[current + 3]) - unique_id = lines[current + 5] - - new_metadata = {"function_type": lines[current + 4], - "extra_id": lines[current + 6], - "unique_id_hash": _ComputeStringHash(unique_id)} - # Extract serialized proto. - current += 7 - annotation_text = "" - - while current < len(lines): - if lines[current] == "==== ANNOTATION ENDS ====": - break - else: - annotation_text += lines[current] - current += 1 - else: - raise Exception( - "Error at line %i, expected annotation end tag." % current) - current += 1 - - # Process unittests and undefined tags. - if unique_id in ("test", "test_partial"): - continue - if unique_id in ("undefined", "missing"): - errors.append("Annotation is not defined for file '%s', line %i." % - (source.file, source.line)) - continue - - # Decode serialized proto. - annotation_proto = traffic_annotation_pb2.NetworkTrafficAnnotation() - try: - text_format.Parse(annotation_text, annotation_proto) - except Exception as error: - errors.append("Annotation in file '%s', line %i, has an error: %s" % - (source.file, source.line, error)) - - # Add new proto. - annotation_proto.unique_id = unique_id - annotation_proto.source.CopyFrom(source) - annotations.network_traffic_annotation.add().CopyFrom(annotation_proto) - metadata.append(new_metadata) - elif lines[current] == "==== NEW CALL ====": - # Ignore calls for now. - while current < len(lines): - if lines[current] == "==== CALL ENDS ====": - break - current += 1 - else: - raise Exception( - "Error at line %i, expected call end tag." % current) - current += 1 - else: # The line is neither new annotation nor new call. - raise Exception( - "Error at line %i, expected starting new annotation or call." % - current) - - except Exception as error: - errors.append(str(error)) - - print "Extracted %i annotations with %i errors." % \ - (len(annotations.network_traffic_annotation), len(errors)) - return annotations, metadata, errors - - -def _WriteSummaryFile(annotations, metadata, errors, file_path): - """Writes extracted annotations and errors into a simple text file. - args: - annotations: ExtractedNetworkTrafficAnnotation A protobuf including all - extracted annotations. - metadata: list of dict Metadata for annotations, as specified in the outputs - of _ParsRawAnnotations function. - errors: list of str List of all extraction errors. - file_path: str File path to the brief summary file. - """ - with open(file_path, "w") as summary_file: - if errors: - summary_file.write("Errors:\n%s\n\n" % "\n".join(errors)) - if len(annotations.network_traffic_annotation): - summary_file.write("Annotations:\n") - for annotation, meta in zip(annotations.network_traffic_annotation, - metadata): - summary_file.write( - "%s\n+MetaData:%s\n---\n" % (str(annotation), str(meta))) - - -def _WriteHashCodesFile(annotations, metadata, file_path): - """Writes unique ids and hash codes of annotations into a simple text file. - args: - annotations: ExtractedNetworkTrafficAnnotation A protobuf including all - extracted annotations. - metadata: list of dict Metadata for annotations, as specified in the outputs - of _ParsRawAnnotations function. - file_path: str File path to the brief summary file. - """ - hash_list = [] - for annotation, meta in zip(annotations.network_traffic_annotation, metadata): - hash_list += ["%s,%s" % (annotation.unique_id, meta["unique_id_hash"])] - for keyword in ("test", "test_partial", "undefined", "missing"): - hash_list += ["%s,%s" % (keyword, _ComputeStringHash(keyword))] - open(file_path, "w").write("\n".join(sorted(hash_list))) - - -def main(): - parser = argparse.ArgumentParser(description="Traffic Annotation Auditor.") - parser.add_argument("--build-dir", - help="Path to the build directory.") - parser.add_argument("--extractor-output", - help="Optional path to the temporary file that extracted " - "annotations will be stored into.") - parser.add_argument("--extractor-input", - help="Optional path to the file that temporary extracted " - "annotations are already stored in. If this is " - "provided, clang tool is not run and this is used " - "as input.") - parser.add_argument("--summary-file", - help="Path to the output file with all annotations.") - parser.add_argument("--hash-codes-file", - help="Path to the output file with the list of unique " - "ids and their hash codes.") - parser.add_argument("path_filters", - nargs="*", - help="Optional paths to filter what files the tool is " - "run on.", - default=[""]) - parser.add_argument("--prefilter-files", action="store_true", - help="Checks source files for patterns of annotations " - "and network functions that may require annotation " - "and limits running clang tool only on them.") - args = parser.parse_args() - - if not args.summary_file and not args.hash_codes_file: - print "Warning: Output file not specified." - - # If a pre-extracted input file is provided, load it. - if args.extractor_input: - with open(args.extractor_input, "r") as raw_file: - raw_annotations = raw_file.read() - else: - # Either extacted input file or build directory should be provided. - if not args.build_dir: - print "You must either specify the build directory to run the clang " \ - "tool and extract annotations, or specify the input directory " \ - "where extracted annotation files already exist.\n" - return 1 - - # Get Chrome source directory with relative path from this file. - chrome_source = os.path.abspath(os.path.join(os.path.dirname( - os.path.realpath(__file__)), "..", "..", "..")) - raw_annotations = _RunClangTool(chrome_source, args.build_dir, - args.path_filters, args.prefilter_files) - - if args.extractor_output: - with open(args.extractor_output, "w") as raw_file: - raw_file.write(raw_annotations) - - annotations, metadata, errors = _ParsRawAnnotations(raw_annotations) - - if not annotations: - print "Could not extract any annotation." - if errors: - print "Errors:\n%s" % "\n".join(errors) - return 1 - - if args.summary_file: - _WriteSummaryFile(annotations, metadata, errors, args.summary_file) - - if args.hash_codes_file: - _WriteHashCodesFile(annotations, metadata, args.hash_codes_file) - - return 0 - - -if __name__ == "__main__": - sys.exit(main())
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc new file mode 100644 index 0000000..d7f0bd5 --- /dev/null +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc
@@ -0,0 +1,192 @@ +// 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 "base/files/file_util.h" +#include "base/strings/stringprintf.h" +#include "net/traffic_annotation/network_traffic_annotation.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "third_party/protobuf/src/google/protobuf/text_format.h" +#include "tools/traffic_annotation/auditor/traffic_annotation_auditor.h" + +const char* HELP_TEXT = R"( +Traffic Annotation Auditor +Extracts network traffic annotaions from the repository, audits them for errors +and coverage, and produces reports. + +Usage: traffic_annotation_auditor [OPTION]... [path_filters] + +Extracts network traffic annotations from source files. If path filter(s) are +specified, only those directories of the source will be analyzed. + +Options: + -h, --help Shows help. + --build-path Path to the build directory. + --source-path Optional path to the src directory. If not provided and + build-path is available, assumed to be 'build-path/../..', + otherwise current directory. + --extractor-output Optional path to the temporary file that extracted + annotations will be stored into. + --extracted-input Optional path to the file that temporary extracted + annotations are already stored in. If this is provided, + clang tool is not run and this is used as input. + --full-run Optional flag asking the tool to run on the whole + repository without text filtering files. Using this flag + may increase processing time x40. + --summary-file Optional path to the output file with all annotations. + --ids-file Optional path to the output file with the list of unique + ids and their hash codes. + path_filters Optional paths to filter what files the tool is run on. + +Example: + traffic_annotation_auditor --build-dir=out/Debug summary-file=report.txt +)"; + +#if defined(OS_WIN) +int wmain(int argc, wchar_t* argv[]) { +#else +int main(int argc, char* argv[]) { +#endif + // Parse switches. + base::CommandLine command_line = base::CommandLine(argc, argv); + if (command_line.HasSwitch("help") || command_line.HasSwitch("h")) { + printf("%s", HELP_TEXT); + return 1; + } + + base::FilePath build_path = command_line.GetSwitchValuePath("build-path"); + base::FilePath source_path = command_line.GetSwitchValuePath("source-path"); + base::FilePath extractor_output = + command_line.GetSwitchValuePath("extractor-output"); + base::FilePath extractor_input = + command_line.GetSwitchValuePath("extractor-input"); + bool full_run = command_line.HasSwitch("full-run"); + base::FilePath summary_file = command_line.GetSwitchValuePath("summary-file"); + base::FilePath ids_file = command_line.GetSwitchValuePath("ids-file"); + base::CommandLine::StringVector path_filters = command_line.GetArgs(); + + // If source path is not provided, guess it using build path or current + // directory. + if (source_path.empty()) { + if (build_path.empty()) + base::GetCurrentDirectory(&source_path); + else + source_path = build_path.Append(base::FilePath::kParentDirectory) + .Append(base::FilePath::kParentDirectory); + } + + // Extract annotations. + std::string raw_output; + if (extractor_input.empty()) { + // Get build directory, if it is empty issue an error. + if (build_path.empty()) { + LOG(ERROR) + << "You must either specify the build directory to run the clang " + "tool and extract annotations, or specify the input file where " + "extracted annotations already exist.\n"; + return 1; + } + + raw_output = traffic_annotation_auditor::RunClangTool( + source_path, build_path, path_filters, full_run); + } else { + if (!base::ReadFileToString(extractor_input, &raw_output)) { + LOG(ERROR) << "Could not read input file: " + << extractor_input.value().c_str(); + return 1; + } + } + + // Write extractor output if requested. + if (!extractor_output.empty() && extractor_input.empty()) { + base::WriteFile(extractor_output, raw_output.c_str(), raw_output.length()); + } + + // Process extractor output. + std::vector<traffic_annotation_auditor::AnnotationInstance> + annotation_instances; + std::vector<traffic_annotation_auditor::CallInstance> call_instances; + std::vector<std::string> errors; + + if (!traffic_annotation_auditor::ParseClangToolRawOutput( + raw_output, &annotation_instances, &call_instances, &errors)) { + return 1; + } + + // Write the summary file. + if (!summary_file.empty()) { + std::string report; + std::vector<std::string> items; + + report = "[Errors]\n"; + std::sort(errors.begin(), errors.end()); + for (const std::string& error : errors) + report += error + "\n"; + + report += "\n[Annotations]\n"; + for (const auto& instance : annotation_instances) { + std::string serialized; + google::protobuf::TextFormat::PrintToString(instance.proto, &serialized); + items.push_back(serialized + + "\n----------------------------------------\n"); + } + std::sort(items.begin(), items.end()); + for (const std::string& item : items) + report += item; + + report += "\n[Calls]\n"; + items.clear(); + for (const auto& instance : call_instances) { + items.push_back(base::StringPrintf( + "File:%s:%i\nFunction:%s\nAnnotated: %i\n", + instance.file_path.c_str(), instance.line_number, + instance.function_name.c_str(), instance.is_annotated)); + } + std::sort(items.begin(), items.end()); + for (const std::string& item : items) + report += item; + + if (base::WriteFile(summary_file, report.c_str(), report.length()) == -1) { + LOG(ERROR) << "Could not write summary file."; + return 1; + } + } + + // Write ids file. + if (!ids_file.empty()) { + std::string report; + std::vector<std::pair<int, std::string>> items; + for (auto& instance : annotation_instances) { + items.push_back(make_pair(traffic_annotation_auditor::ComputeHashValue( + instance.proto.unique_id()), + instance.proto.unique_id())); + } + items.push_back(std::make_pair( + TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code, "test")); + items.push_back( + std::make_pair(PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code, + "test_partial")); + items.push_back(std::make_pair( + NO_TRAFFIC_ANNOTATION_YET.unique_id_hash_code, "undefined")); + DCHECK_EQ(NO_PARTIAL_TRAFFIC_ANNOTATION_YET.unique_id_hash_code, + NO_TRAFFIC_ANNOTATION_YET.unique_id_hash_code); + items.push_back(std::make_pair( + MISSING_TRAFFIC_ANNOTATION.unique_id_hash_code, "missing")); + + std::sort(items.begin(), items.end()); + for (const auto& item : items) + report += base::StringPrintf("<int value=\"%i\" label=\"%s\" />\n", + item.first, item.second.c_str()); + + if (base::WriteFile(ids_file, report.c_str(), report.length()) == -1) { + LOG(ERROR) << "Could not write ids file."; + return 1; + } + } + + LOG(INFO) << "Extracted " << annotation_instances.size() << " annotations & " + << call_instances.size() << " calls, with " << errors.size() + << " errors."; + + return 0; +}
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc new file mode 100644 index 0000000..598b8bb --- /dev/null +++ b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc
@@ -0,0 +1,133 @@ +// 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 "tools/traffic_annotation/auditor/traffic_annotation_file_filter.h" + +#include <fstream> + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/process/launch.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" + +namespace { + +// List of keywords that indicate a file may be related to network traffic +// annotations. This list includes all keywords related to defining annotations +// and all functions that need one. +const char* kRelevantKeywords[] = { + "network_traffic_annotation", + "network_traffic_annotation_test_helper", + "NetworkTrafficAnnotationTag", + "PartialNetworkTrafficAnnotationTag", + "DefineNetworkTrafficAnnotation", + "DefinePartialNetworkTrafficAnnotation", + "CompleteNetworkTrafficAnnotation", + "BranchedCompleteNetworkTrafficAnnotation", + "NO_TRAFFIC_ANNOTATION_YET", + "NO_PARTIAL_TRAFFIC_ANNOTATION_YET", + "MISSING_TRAFFIC_ANNOTATION", + "TRAFFIC_ANNOTATION_FOR_TESTS", + "PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS", + "SSLClientSocket", // SSLClientSocket:: + "TCPClientSocket", // TCPClientSocket:: + "UDPClientSocket", // UDPClientSocket:: + "URLFetcher::Create", // This one is used with class as it's too generic. + "CreateDatagramClientSocket", // ClientSocketFactory:: + "CreateSSLClientSocket", // ClientSocketFactory:: + "CreateTransportClientSocket", // ClientSocketFactory:: + "CreateRequest", // URLRequestContext:: + nullptr // End Marker +}; + +} // namespace + +TrafficAnnotationFileFilter::TrafficAnnotationFileFilter() {} + +TrafficAnnotationFileFilter::~TrafficAnnotationFileFilter() {} + +void TrafficAnnotationFileFilter::GetFilesFromGit( + const base::FilePath& source_path) { + const base::CommandLine::CharType* args[] = +#if defined(OS_WIN) + {FILE_PATH_LITERAL("git.bat"), FILE_PATH_LITERAL("ls-files")}; +#else + {"git", "ls-files"}; +#endif + base::CommandLine cmdline(2, args); + + // Change directory to source path to access git. + base::FilePath original_path; + base::GetCurrentDirectory(&original_path); + base::SetCurrentDirectory(source_path); + + // Get list of files from git. + std::string results; + if (!base::GetAppOutput(cmdline, &results)) { + LOG(ERROR) << "Could not get files from git."; + } else { + for (const std::string file_path : base::SplitString( + results, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL)) { + if (IsFileRelevant(file_path)) + git_files_.push_back(file_path); + } + } + + base::SetCurrentDirectory(original_path); +} + +bool TrafficAnnotationFileFilter::IsFileRelevant(const std::string& file_path) { + // Check file extension. + int pos = file_path.length() - 3; + + if (pos < 0 || (strcmp(".mm", file_path.c_str() + pos) && + strcmp(".cc", file_path.c_str() + pos))) { + return false; + } + + base::FilePath converted_file_path = +#if defined(OS_WIN) + base::FilePath( + base::FilePath::StringPieceType(base::UTF8ToWide(file_path))); +#else + base::FilePath(base::FilePath::StringPieceType(file_path)); +#endif + + // Check file content. + std::string file_content; + if (!base::ReadFileToString(converted_file_path, &file_content)) { + LOG(ERROR) << "Could not open file: " << file_path; + return false; + } + + for (int i = 0; kRelevantKeywords[i]; i++) { + if (file_content.find(kRelevantKeywords[i]) != std::string::npos) + return true; + } + + return false; +} + +void TrafficAnnotationFileFilter::GetRelevantFiles( + const base::FilePath& source_path, + std::string directory_name, + std::vector<std::string>* file_paths) { + if (!git_files_.size()) + GetFilesFromGit(source_path); + +#if defined(FILE_PATH_USES_WIN_SEPARATORS) + std::replace(directory_name.begin(), directory_name.end(), L'\\', L'/'); +#endif + + size_t name_length = directory_name.length(); + for (const std::string& file_path : git_files_) { + if (!strncmp(file_path.c_str(), directory_name.c_str(), name_length)) + file_paths->push_back(file_path); + } +}
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h new file mode 100644 index 0000000..2e94919 --- /dev/null +++ b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h
@@ -0,0 +1,43 @@ +// 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 TRAFFIC_ANNOTATION_FILE_FILTER_H_ +#define TRAFFIC_ANNOTATION_FILE_FILTER_H_ + +#include <string> +#include <vector> + +namespace base { +class FilePath; +} + +// Provides the list of files that might be relevent to network traffic +// annotation by matching filename and searching for keywords in the file +// content. +// The file should end with either .cc or .mm and the content should include a +// keyword specifying definition of network traffic annotations or the name of +// a function that needs annotation. +class TrafficAnnotationFileFilter { + public: + TrafficAnnotationFileFilter(); + ~TrafficAnnotationFileFilter(); + + // Returns the list of relevant files in the given |directory_name| into the + // |file_paths|. If |directory_name| is empty, all files are returned. + // |source_path| should be the repository source directory, e.g. C:/src. + void GetRelevantFiles(const base::FilePath& source_path, + std::string directory_name, + std::vector<std::string>* file_paths); + + // Checks the name and content of a file and returns true if it is relevant. + bool IsFileRelevant(const std::string& file_path); + + private: + // Gets the list of all files in the repository. + void GetFilesFromGit(const base::FilePath& source_path); + + std::vector<std::string> git_files_; +}; + +#endif // TRAFFIC_ANNOTATION_FILE_FILTER_H_ \ No newline at end of file
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.py b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.py deleted file mode 100755 index f00daf1..0000000 --- a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.py +++ /dev/null
@@ -1,84 +0,0 @@ -#!/usr/bin/env python -# 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. - -import os.path -import re -import subprocess -import sys - - -def _GetFilesFromGit(): - """Gets the list of files in the git repository.""" - args = [] - if sys.platform == 'win32': - args.append('git.bat') - else: - args.append('git') - args.append('ls-files') - command = subprocess.Popen(args, stdout=subprocess.PIPE) - output, _ = command.communicate() - return [os.path.realpath(p) for p in output.splitlines()] - - -class TrafficAnnotationFileFilter(): - KEYWORDS = [ - 'network_traffic_annotation', - 'network_traffic_annotation_test_helper', - 'NetworkTrafficAnnotationTag', - 'PartialNetworkTrafficAnnotationTag', - 'DefineNetworkTrafficAnnotation', - 'DefinePartialNetworkTrafficAnnotation', - 'CompleteNetworkTrafficAnnotation', - 'BranchedCompleteNetworkTrafficAnnotation', - 'NO_TRAFFIC_ANNOTATION_YET', - 'NO_PARTIAL_TRAFFIC_ANNOTATION_YET', - 'MISSING_TRAFFIC_ANNOTATION', - 'TRAFFIC_ANNOTATION_FOR_TESTS', - 'PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS', - 'SSLClientSocket', # SSLClientSocket:: - 'TCPClientSocket', # TCPClientSocket:: - 'UDPClientSocket', # UDPClientSocket:: - 'URLFetcher::Create', # This one is used with class as it's too generic. - 'CreateDatagramClientSocket', # ClientSocketFactory:: - 'CreateSSLClientSocket', # ClientSocketFactory:: - 'CreateTransportClientSocket', # ClientSocketFactory:: - 'CreateRequest', # URLRequestContext:: - ] - - def __init__(self, - skip_tests=True): - """Creates a new TrafficAnnotationFileFilter. - - Args: - skip_tests: bool Flag stating if test files should be returned or not. - """ - assert(all(re.match('^[A-Za-z:_]+$', keyword) for keyword in self.KEYWORDS)) - self.content_matcher = re.compile('.*(' + '|'.join(self.KEYWORDS) + ').*') - self.file_name_matcher = re.compile( - '^(?!.*?test)^.*(\.cc|\.mm)$' if skip_tests else - '^.*(\.cc|\.mm)$') - self.git_files = filter(lambda x: self.FileIsRelevantContent(x), - _GetFilesFromGit()) - - def FileIsRelevantContent(self, filename): - if self.file_name_matcher.match(filename): - with open(filename, 'r') as in_file: - for line in in_file: - if self.content_matcher.match(line): - return True - return False - - - def GetFilteredFilesList(self, dir_name='/'): - """Returns the list of relevant files in given directory. - Args: - dir_name: str The directory to search for relevant files, e.g. - 'chrome/browser'. All child directories would also be searched. - - Returns: - list of str List of relevant files - """ - matcher = re.compile(os.path.abspath(dir_name) + '/.*') - return filter(matcher.match, self.git_files)
diff --git a/ui/arc/notification/arc_notification_content_view.cc b/ui/arc/notification/arc_notification_content_view.cc index c55e22f..33a68a9 100644 --- a/ui/arc/notification/arc_notification_content_view.cc +++ b/ui/arc/notification/arc_notification_content_view.cc
@@ -640,6 +640,10 @@ void ArcNotificationContentView::GetAccessibleNodeData( ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_BUTTON; + node_data->AddStringAttribute( + ui::AX_ATTR_ROLE_DESCRIPTION, + l10n_util::GetStringUTF8( + IDS_MESSAGE_NOTIFICATION_SETTINGS_BUTTON_ACCESSIBLE_NAME)); node_data->SetName(accessible_name_); }
diff --git a/ui/aura/gestures/gesture_recognizer_unittest.cc b/ui/aura/gestures/gesture_recognizer_unittest.cc index 0aff210..8c6d262 100644 --- a/ui/aura/gestures/gesture_recognizer_unittest.cc +++ b/ui/aura/gestures/gesture_recognizer_unittest.cc
@@ -352,7 +352,7 @@ synchronous_ack_for_next_event_ == AckState::CONSUMED ? ui::ER_CONSUMED : ui::ER_UNHANDLED, - window_); + false /* is_source_touch_event_set_non_blocking */, window_); synchronous_ack_for_next_event_ = AckState::PENDING; } else { sent_events_ids_.push_back(event->unique_event_id()); @@ -389,7 +389,8 @@ sent_events_ids_.pop_front(); dispatcher_->ProcessedTouchEvent( sent_event_id, window_, - prevent_defaulted ? ui::ER_HANDLED : ui::ER_UNHANDLED); + prevent_defaulted ? ui::ER_HANDLED : ui::ER_UNHANDLED, + false /* is_source_touch_event_set_non_blocking */); } Window* window_;
diff --git a/ui/aura/window_event_dispatcher.cc b/ui/aura/window_event_dispatcher.cc index dc286d0..ea3e2fdc 100644 --- a/ui/aura/window_event_dispatcher.cc +++ b/ui/aura/window_event_dispatcher.cc
@@ -180,12 +180,15 @@ return DispatchMouseEnterOrExit(window, event, ui::ET_MOUSE_EXITED); } -void WindowEventDispatcher::ProcessedTouchEvent(uint32_t unique_event_id, - Window* window, - ui::EventResult result) { +void WindowEventDispatcher::ProcessedTouchEvent( + uint32_t unique_event_id, + Window* window, + ui::EventResult result, + bool is_source_touch_event_set_non_blocking) { ui::GestureRecognizer::Gestures gestures = - ui::GestureRecognizer::Get()->AckTouchEvent(unique_event_id, result, - window); + ui::GestureRecognizer::Get()->AckTouchEvent( + unique_event_id, result, is_source_touch_event_set_non_blocking, + window); DispatchDetails details = ProcessGestures(window, std::move(gestures)); if (details.dispatcher_destroyed) return; @@ -555,7 +558,8 @@ Window* window = static_cast<Window*>(target); ui::GestureRecognizer::Gestures gestures = ui::GestureRecognizer::Get()->AckTouchEvent( - touchevent.unique_event_id(), event.result(), window); + touchevent.unique_event_id(), event.result(), + false /* is_source_touch_event_set_non_blocking */, window); return ProcessGestures(window, std::move(gestures)); }
diff --git a/ui/aura/window_event_dispatcher.h b/ui/aura/window_event_dispatcher.h index fad430e..fd998c3 100644 --- a/ui/aura/window_event_dispatcher.h +++ b/ui/aura/window_event_dispatcher.h
@@ -92,7 +92,8 @@ // space, in DIPs. virtual void ProcessedTouchEvent(uint32_t unique_event_id, Window* window, - ui::EventResult result); + ui::EventResult result, + bool is_source_touch_event_set_non_blocking); // These methods are used to defer the processing of mouse/touch events // related to resize. A client (typically a RenderWidgetHostViewAura) can call
diff --git a/ui/aura/window_event_dispatcher_unittest.cc b/ui/aura/window_event_dispatcher_unittest.cc index c14ab34..58efc20b 100644 --- a/ui/aura/window_event_dispatcher_unittest.cc +++ b/ui/aura/window_event_dispatcher_unittest.cc
@@ -941,7 +941,9 @@ std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - host()->dispatcher()->ProcessedTouchEvent(0, window.get(), ui::ER_UNHANDLED); + host()->dispatcher()->ProcessedTouchEvent( + 0, window.get(), ui::ER_UNHANDLED, + false /* is_source_touch_event_set_non_blocking */); } // This event handler requests the dispatcher to start holding pointer-move @@ -2604,8 +2606,9 @@ // Convert touch event back to root window coordinates. event->ConvertLocationToTarget(window_, window_->GetRootWindow()); event->DisableSynchronousHandling(); - dispatcher_->ProcessedTouchEvent(event->unique_event_id(), window_, - ui::ER_UNHANDLED); + dispatcher_->ProcessedTouchEvent( + event->unique_event_id(), window_, ui::ER_UNHANDLED, + false /* is_source_touch_event_set_non_blocking */); event->StopPropagation(); }
diff --git a/ui/chromeos/touch_exploration_controller.cc b/ui/chromeos/touch_exploration_controller.cc index c756b0a0..bd0473c 100644 --- a/ui/chromeos/touch_exploration_controller.cc +++ b/ui/chromeos/touch_exploration_controller.cc
@@ -197,8 +197,9 @@ if (gesture_provider_.get()) { ui::TouchEvent mutable_touch_event = touch_event; if (gesture_provider_->OnTouchEvent(&mutable_touch_event)) { - gesture_provider_->OnTouchEventAck(mutable_touch_event.unique_event_id(), - false); + gesture_provider_->OnTouchEventAck( + mutable_touch_event.unique_event_id(), false /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } ProcessGestureEvents(); }
diff --git a/ui/events/blink/blink_event_util.cc b/ui/events/blink/blink_event_util.cc index 7dfbe29..ad6e31ae7 100644 --- a/ui/events/blink/blink_event_util.cc +++ b/ui/events/blink/blink_event_util.cc
@@ -627,6 +627,9 @@ break; } + gesture.is_source_touch_event_set_non_blocking = + details.is_source_touch_event_set_non_blocking(); + gesture.unique_touch_event_id = unique_touch_event_id; switch (details.type()) {
diff --git a/ui/events/blink/input_handler_proxy.cc b/ui/events/blink/input_handler_proxy.cc index c797a685..0f26dd9 100644 --- a/ui/events/blink/input_handler_proxy.cc +++ b/ui/events/blink/input_handler_proxy.cc
@@ -324,6 +324,17 @@ } if (has_ongoing_compositor_scroll_fling_pinch_) { + const auto& gesture_event = ToWebGestureEvent(event_with_callback->event()); + if (gesture_event.source_device == blink::kWebGestureDeviceTouchscreen && + gesture_event.is_source_touch_event_set_non_blocking) { + // Dispatch immediately to avoid regression in + // |smoothness.tough_scrolling_cases:first_gesture_scroll_update_latency|. + compositor_event_queue_->Queue(std::move(event_with_callback), + tick_clock_->NowTicks()); + DispatchQueuedInputEvents(); + return; + } + bool needs_animate_input = compositor_event_queue_->empty(); compositor_event_queue_->Queue(std::move(event_with_callback), tick_clock_->NowTicks());
diff --git a/ui/events/gesture_detection/filtered_gesture_provider.cc b/ui/events/gesture_detection/filtered_gesture_provider.cc index d82d5db..10b93b2 100644 --- a/ui/events/gesture_detection/filtered_gesture_provider.cc +++ b/ui/events/gesture_detection/filtered_gesture_provider.cc
@@ -50,9 +50,12 @@ return result; } -void FilteredGestureProvider::OnTouchEventAck(uint32_t unique_event_id, - bool event_consumed) { - gesture_filter_.OnTouchEventAck(unique_event_id, event_consumed); +void FilteredGestureProvider::OnTouchEventAck( + uint32_t unique_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking) { + gesture_filter_.OnTouchEventAck(unique_event_id, event_consumed, + is_source_touch_event_set_non_blocking); } void FilteredGestureProvider::ResetDetection() {
diff --git a/ui/events/gesture_detection/filtered_gesture_provider.h b/ui/events/gesture_detection/filtered_gesture_provider.h index c0af13b..b0f5c7b 100644 --- a/ui/events/gesture_detection/filtered_gesture_provider.h +++ b/ui/events/gesture_detection/filtered_gesture_provider.h
@@ -41,7 +41,9 @@ // To be called upon asynchronous and synchronous ack of an event that was // forwarded after a successful call to |OnTouchEvent()|. - void OnTouchEventAck(uint32_t unique_event_id, bool event_consumed); + void OnTouchEventAck(uint32_t unique_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking); // Methods delegated to |gesture_provider_|. void ResetDetection();
diff --git a/ui/events/gesture_detection/gesture_event_data_packet.cc b/ui/events/gesture_detection/gesture_event_data_packet.cc index fd63932d..5edd34a 100644 --- a/ui/events/gesture_detection/gesture_event_data_packet.cc +++ b/ui/events/gesture_detection/gesture_event_data_packet.cc
@@ -111,9 +111,14 @@ return packet; } -void GestureEventDataPacket::Ack(bool event_consumed) { +void GestureEventDataPacket::Ack(bool event_consumed, + bool is_source_touch_event_set_non_blocking) { DCHECK_EQ(static_cast<int>(ack_state_), static_cast<int>(AckState::PENDING)); ack_state_ = event_consumed ? AckState::CONSUMED : AckState::UNCONSUMED; + for (auto& gesture : gestures_.container()) { + gesture.details.set_is_source_touch_event_set_non_blocking( + is_source_touch_event_set_non_blocking); + } } } // namespace ui
diff --git a/ui/events/gesture_detection/gesture_event_data_packet.h b/ui/events/gesture_detection/gesture_event_data_packet.h index 264f1fd..d408ba1f 100644 --- a/ui/events/gesture_detection/gesture_event_data_packet.h +++ b/ui/events/gesture_detection/gesture_event_data_packet.h
@@ -61,7 +61,7 @@ // We store the ack with the packet until the packet reaches the // head of the queue, and then we handle the ack. - void Ack(bool event_consumed); + void Ack(bool event_consumed, bool is_source_touch_event_set_non_blocking); AckState ack_state() { return ack_state_; } uint32_t unique_touch_event_id() const { return unique_touch_event_id_; }
diff --git a/ui/events/gesture_detection/touch_disposition_gesture_filter.cc b/ui/events/gesture_detection/touch_disposition_gesture_filter.cc index 6668f0d7..a23bc35 100644 --- a/ui/events/gesture_detection/touch_disposition_gesture_filter.cc +++ b/ui/events/gesture_detection/touch_disposition_gesture_filter.cc
@@ -191,7 +191,9 @@ } void TouchDispositionGestureFilter::OnTouchEventAck( - uint32_t unique_touch_event_id, bool event_consumed) { + uint32_t unique_touch_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking) { // Spurious asynchronous acks should not trigger a crash. if (IsEmpty() || (Head().empty() && sequences_.size() == 1)) return; @@ -201,13 +203,13 @@ if (!Tail().empty() && Tail().back().unique_touch_event_id() == unique_touch_event_id) { - Tail().back().Ack(event_consumed); + Tail().back().Ack(event_consumed, is_source_touch_event_set_non_blocking); if (sequences_.size() == 1 && Tail().size() == 1) SendAckedEvents(); } else { DCHECK(!Head().empty()); DCHECK_EQ(Head().front().unique_touch_event_id(), unique_touch_event_id); - Head().front().Ack(event_consumed); + Head().front().Ack(event_consumed, is_source_touch_event_set_non_blocking); SendAckedEvents(); } }
diff --git a/ui/events/gesture_detection/touch_disposition_gesture_filter.h b/ui/events/gesture_detection/touch_disposition_gesture_filter.h index 59bc7d87..1a09bf8 100644 --- a/ui/events/gesture_detection/touch_disposition_gesture_filter.h +++ b/ui/events/gesture_detection/touch_disposition_gesture_filter.h
@@ -46,7 +46,9 @@ PacketResult OnGesturePacket(const GestureEventDataPacket& packet); // OnTouchEventAck must be called upon receipt of every touch event ack. - void OnTouchEventAck(uint32_t unique_touch_event_id, bool event_consumed); + void OnTouchEventAck(uint32_t unique_touch_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking); // Whether there are any active gesture sequences still queued in the filter. bool IsEmpty() const;
diff --git a/ui/events/gesture_detection/touch_disposition_gesture_filter_unittest.cc b/ui/events/gesture_detection/touch_disposition_gesture_filter_unittest.cc index e84049c..613cc75 100644 --- a/ui/events/gesture_detection/touch_disposition_gesture_filter_unittest.cc +++ b/ui/events/gesture_detection/touch_disposition_gesture_filter_unittest.cc
@@ -140,24 +140,31 @@ return queue_->OnGesturePacket(packet); } - void SendTouchEventAck(uint32_t touch_event_id, bool event_consumed) { - queue_->OnTouchEventAck(touch_event_id, event_consumed); + void SendTouchEventAck(uint32_t touch_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking) { + queue_->OnTouchEventAck(touch_event_id, event_consumed, + is_source_touch_event_set_non_blocking); } void SendTouchConsumedAck(uint32_t touch_event_id) { - SendTouchEventAck(touch_event_id, true); + SendTouchEventAck(touch_event_id, true /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } void SendTouchNotConsumedAck(uint32_t touch_event_id) { - SendTouchEventAck(touch_event_id, false); + SendTouchEventAck(touch_event_id, false /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } void SendTouchConsumedAckForLastTouch() { - SendTouchEventAck(last_sent_touch_event_id_, true); + SendTouchEventAck(last_sent_touch_event_id_, true /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } void SendTouchNotConsumedAckForLastTouch() { - SendTouchEventAck(last_sent_touch_event_id_, false); + SendTouchEventAck(last_sent_touch_event_id_, false /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } void PushGesture(EventType type) {
diff --git a/ui/events/gesture_event_details.h b/ui/events/gesture_event_details.h index 2b066d5..907a940e 100644 --- a/ui/events/gesture_event_details.h +++ b/ui/events/gesture_event_details.h
@@ -45,6 +45,15 @@ device_type_ = device_type; } + bool is_source_touch_event_set_non_blocking() const { + return is_source_touch_event_set_non_blocking_; + } + void set_is_source_touch_event_set_non_blocking( + bool is_source_touch_event_set_non_blocking) { + is_source_touch_event_set_non_blocking_ = + is_source_touch_event_set_non_blocking; + } + int touch_points() const { return touch_points_; } void set_touch_points(int touch_points) { DCHECK_GT(touch_points, 0); @@ -225,6 +234,8 @@ GestureDeviceType device_type_; + bool is_source_touch_event_set_non_blocking_ = false; + int touch_points_; // Number of active touch points in the gesture. // Bounding box is an axis-aligned rectangle that contains all the
diff --git a/ui/events/gestures/gesture_provider_aura.cc b/ui/events/gestures/gesture_provider_aura.cc index b8e83b2..260ada94 100644 --- a/ui/events/gestures/gesture_provider_aura.cc +++ b/ui/events/gestures/gesture_provider_aura.cc
@@ -42,13 +42,16 @@ return true; } -void GestureProviderAura::OnTouchEventAck(uint32_t unique_touch_event_id, - bool event_consumed) { +void GestureProviderAura::OnTouchEventAck( + uint32_t unique_touch_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking) { DCHECK(pending_gestures_.empty()); DCHECK(!handling_event_); base::AutoReset<bool> handling_event(&handling_event_, true); - filtered_gesture_provider_.OnTouchEventAck(unique_touch_event_id, - event_consumed); + filtered_gesture_provider_.OnTouchEventAck( + unique_touch_event_id, event_consumed, + is_source_touch_event_set_non_blocking); } void GestureProviderAura::OnGestureEvent(const GestureEventData& gesture) { @@ -82,7 +85,8 @@ touch_event->set_root_location_f(point); OnTouchEvent(touch_event.get()); - OnTouchEventAck(touch_event->unique_event_id(), true); + OnTouchEventAck(touch_event->unique_event_id(), true /* event_consumed */, + false /* is_source_touch_event_set_non_blocking */); } } // namespace content
diff --git a/ui/events/gestures/gesture_provider_aura.h b/ui/events/gestures/gesture_provider_aura.h index 4fa90ac..fc7bdab 100644 --- a/ui/events/gestures/gesture_provider_aura.h +++ b/ui/events/gestures/gesture_provider_aura.h
@@ -42,7 +42,9 @@ } bool OnTouchEvent(TouchEvent* event); - void OnTouchEventAck(uint32_t unique_touch_event_id, bool event_consumed); + void OnTouchEventAck(uint32_t unique_touch_event_id, + bool event_consumed, + bool is_source_touch_event_set_non_blocking); const MotionEventAura& pointer_state() { return pointer_state_; } std::vector<std::unique_ptr<GestureEvent>> GetAndResetPendingGestures(); void OnTouchEnter(int pointer_id, float x, float y);
diff --git a/ui/events/gestures/gesture_recognizer.h b/ui/events/gestures/gesture_recognizer.h index 4f3daf4..8e24e6d7 100644 --- a/ui/events/gestures/gesture_recognizer.h +++ b/ui/events/gestures/gesture_recognizer.h
@@ -37,6 +37,7 @@ // the queue which matches with unique_event_id. virtual Gestures AckTouchEvent(uint32_t unique_event_id, ui::EventResult result, + bool is_source_touch_event_set_non_blocking, GestureConsumer* consumer) = 0; // This is called when the consumer is destroyed. So this should cleanup any
diff --git a/ui/events/gestures/gesture_recognizer_impl.cc b/ui/events/gestures/gesture_recognizer_impl.cc index 5f7e70cd..a4c7c82 100644 --- a/ui/events/gestures/gesture_recognizer_impl.cc +++ b/ui/events/gestures/gesture_recognizer_impl.cc
@@ -282,6 +282,7 @@ GestureRecognizer::Gestures GestureRecognizerImpl::AckTouchEvent( uint32_t unique_event_id, ui::EventResult result, + bool is_source_touch_event_set_non_blocking, GestureConsumer* consumer) { GestureProviderAura* gesture_provider = nullptr; @@ -295,7 +296,8 @@ } else { gesture_provider = GetGestureProviderForConsumer(consumer); } - gesture_provider->OnTouchEventAck(unique_event_id, result != ER_UNHANDLED); + gesture_provider->OnTouchEventAck(unique_event_id, result != ER_UNHANDLED, + is_source_touch_event_set_non_blocking); return gesture_provider->GetAndResetPendingGestures(); }
diff --git a/ui/events/gestures/gesture_recognizer_impl.h b/ui/events/gestures/gesture_recognizer_impl.h index 036a1a6f..f06cf6d 100644 --- a/ui/events/gestures/gesture_recognizer_impl.h +++ b/ui/events/gestures/gesture_recognizer_impl.h
@@ -72,6 +72,7 @@ Gestures AckTouchEvent(uint32_t unique_event_id, ui::EventResult result, + bool is_source_touch_event_set_non_blocking, GestureConsumer* consumer) override; bool CleanupStateForConsumer(GestureConsumer* consumer) override;
diff --git a/ui/events/gestures/gesture_recognizer_impl_mac.cc b/ui/events/gestures/gesture_recognizer_impl_mac.cc index d3036c7..359b909b 100644 --- a/ui/events/gestures/gesture_recognizer_impl_mac.cc +++ b/ui/events/gestures/gesture_recognizer_impl_mac.cc
@@ -27,6 +27,7 @@ Gestures AckTouchEvent(uint32_t unique_event_id, ui::EventResult result, + bool is_source_touch_event_set_non_blocking, GestureConsumer* consumer) override { return {}; }
diff --git a/ui/gfx/buffer_format_util.cc b/ui/gfx/buffer_format_util.cc index 35003e1..72667e6 100644 --- a/ui/gfx/buffer_format_util.cc +++ b/ui/gfx/buffer_format_util.cc
@@ -11,16 +11,24 @@ namespace gfx { namespace { -const BufferFormat kBufferFormats[] = { - BufferFormat::ATC, BufferFormat::ATCIA, - BufferFormat::DXT1, BufferFormat::DXT5, - BufferFormat::ETC1, BufferFormat::R_8, - BufferFormat::RG_88, BufferFormat::BGR_565, - BufferFormat::RGBA_4444, BufferFormat::RGBX_8888, - BufferFormat::RGBA_8888, BufferFormat::BGRX_8888, - BufferFormat::BGRA_8888, BufferFormat::RGBA_F16, - BufferFormat::UYVY_422, BufferFormat::YUV_420_BIPLANAR, - BufferFormat::YVU_420}; +const BufferFormat kBufferFormats[] = {BufferFormat::ATC, + BufferFormat::ATCIA, + BufferFormat::DXT1, + BufferFormat::DXT5, + BufferFormat::ETC1, + BufferFormat::R_8, + BufferFormat::R_16, + BufferFormat::RG_88, + BufferFormat::BGR_565, + BufferFormat::RGBA_4444, + BufferFormat::RGBX_8888, + BufferFormat::RGBA_8888, + BufferFormat::BGRX_8888, + BufferFormat::BGRA_8888, + BufferFormat::RGBA_F16, + BufferFormat::UYVY_422, + BufferFormat::YUV_420_BIPLANAR, + BufferFormat::YVU_420}; static_assert(arraysize(kBufferFormats) == (static_cast<int>(BufferFormat::LAST) + 1), @@ -49,6 +57,7 @@ return false; *size_in_bytes = (checked_size & ~0x3).ValueOrDie(); return true; + case BufferFormat::R_16: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: @@ -102,6 +111,7 @@ case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: + case BufferFormat::R_16: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: @@ -129,6 +139,7 @@ case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: + case BufferFormat::R_16: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444: @@ -201,6 +212,7 @@ case BufferFormat::DXT5: case BufferFormat::ETC1: case BufferFormat::R_8: + case BufferFormat::R_16: case BufferFormat::RG_88: case BufferFormat::BGR_565: case BufferFormat::RGBA_4444:
diff --git a/ui/gfx/buffer_types.h b/ui/gfx/buffer_types.h index 179ee19..9cb5b7b6 100644 --- a/ui/gfx/buffer_types.h +++ b/ui/gfx/buffer_types.h
@@ -16,6 +16,7 @@ DXT5, ETC1, R_8, + R_16, RG_88, BGR_565, RGBA_4444,
diff --git a/ui/gfx/mac/io_surface.cc b/ui/gfx/mac/io_surface.cc index ee10bf3..606c345a 100644 --- a/ui/gfx/mac/io_surface.cc +++ b/ui/gfx/mac/io_surface.cc
@@ -46,6 +46,7 @@ static int32_t bytes_per_element[] = {1, 2}; DCHECK_LT(static_cast<size_t>(plane), arraysize(bytes_per_element)); return bytes_per_element[plane]; + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::UYVY_422: DCHECK_EQ(plane, 0); @@ -81,6 +82,7 @@ return '420v'; case gfx::BufferFormat::UYVY_422: return '2vuy'; + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::ATC: case gfx::BufferFormat::ATCIA:
diff --git a/ui/gfx/mojo/buffer_types.mojom b/ui/gfx/mojo/buffer_types.mojom index 0578311..29c50d54 100644 --- a/ui/gfx/mojo/buffer_types.mojom +++ b/ui/gfx/mojo/buffer_types.mojom
@@ -12,6 +12,7 @@ DXT5, ETC1, R_8, + R_16, RG_88, BGR_565, RGBA_4444,
diff --git a/ui/gfx/mojo/buffer_types_struct_traits.h b/ui/gfx/mojo/buffer_types_struct_traits.h index ad25a17..ce05fe9 100644 --- a/ui/gfx/mojo/buffer_types_struct_traits.h +++ b/ui/gfx/mojo/buffer_types_struct_traits.h
@@ -26,6 +26,8 @@ return gfx::mojom::BufferFormat::ETC1; case gfx::BufferFormat::R_8: return gfx::mojom::BufferFormat::R_8; + case gfx::BufferFormat::R_16: + return gfx::mojom::BufferFormat::R_16; case gfx::BufferFormat::RG_88: return gfx::mojom::BufferFormat::RG_88; case gfx::BufferFormat::BGR_565: @@ -74,6 +76,9 @@ case gfx::mojom::BufferFormat::R_8: *out = gfx::BufferFormat::R_8; return true; + case gfx::mojom::BufferFormat::R_16: + *out = gfx::BufferFormat::R_16; + return true; case gfx::mojom::BufferFormat::RG_88: *out = gfx::BufferFormat::RG_88; return true;
diff --git a/ui/gl/gl_image_io_surface.mm b/ui/gl/gl_image_io_surface.mm index fc4df49..c9fabee 100644 --- a/ui/gl/gl_image_io_surface.mm +++ b/ui/gl/gl_image_io_surface.mm
@@ -32,6 +32,7 @@ bool ValidInternalFormat(unsigned internalformat) { switch (internalformat) { case GL_RED: + case GL_R16_EXT: case GL_RG: case GL_BGRA_EXT: case GL_RGB: @@ -54,6 +55,7 @@ case gfx::BufferFormat::UYVY_422: case gfx::BufferFormat::YUV_420_BIPLANAR: return true; + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::ATC: case gfx::BufferFormat::ATCIA: @@ -75,6 +77,8 @@ switch (format) { case gfx::BufferFormat::R_8: return GL_RED; + case gfx::BufferFormat::R_16: + return GL_R16_EXT; case gfx::BufferFormat::RG_88: return GL_RG; case gfx::BufferFormat::BGRA_8888: @@ -107,6 +111,8 @@ switch (format) { case gfx::BufferFormat::R_8: return GL_RED; + case gfx::BufferFormat::R_16: + return GL_R16_EXT; case gfx::BufferFormat::RG_88: return GL_RG; case gfx::BufferFormat::BGRA_8888: @@ -140,6 +146,8 @@ case gfx::BufferFormat::R_8: case gfx::BufferFormat::RG_88: return GL_UNSIGNED_BYTE; + case gfx::BufferFormat::R_16: + return GL_UNSIGNED_SHORT; case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::BGRX_8888: case gfx::BufferFormat::RGBA_8888:
diff --git a/ui/gl/gl_image_memory.cc b/ui/gl/gl_image_memory.cc index 20e694f..170e3c69 100644 --- a/ui/gl/gl_image_memory.cc +++ b/ui/gl/gl_image_memory.cc
@@ -45,6 +45,7 @@ case gfx::BufferFormat::DXT5: case gfx::BufferFormat::ETC1: case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444: @@ -73,6 +74,7 @@ case gfx::BufferFormat::ETC1: return true; case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444: @@ -107,6 +109,8 @@ return GL_ETC1_RGB8_OES; case gfx::BufferFormat::R_8: return GL_RED; + case gfx::BufferFormat::R_16: + return GL_R16_EXT; case gfx::BufferFormat::RG_88: return GL_RG; case gfx::BufferFormat::RGBA_4444: @@ -142,6 +146,7 @@ case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::RGBA_F16: case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::ATC: case gfx::BufferFormat::ATCIA: @@ -173,6 +178,8 @@ case gfx::BufferFormat::R_8: case gfx::BufferFormat::RG_88: return GL_UNSIGNED_BYTE; + case gfx::BufferFormat::R_16: + return GL_UNSIGNED_SHORT; case gfx::BufferFormat::RGBA_F16: return GL_HALF_FLOAT_OES; case gfx::BufferFormat::ATC: @@ -194,6 +201,7 @@ GLint DataRowLength(size_t stride, gfx::BufferFormat format) { switch (format) { case gfx::BufferFormat::RG_88: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_4444: return base::checked_cast<GLint>(stride) / 2; @@ -319,6 +327,7 @@ case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::RGBA_F16: case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: { size_t gles2_data_stride = RowSizeForBufferFormat(size.width(), format, 0);
diff --git a/ui/gl/gl_image_native_pixmap.cc b/ui/gl/gl_image_native_pixmap.cc index d29de1ca..e2c0c4c 100644 --- a/ui/gl/gl_image_native_pixmap.cc +++ b/ui/gl/gl_image_native_pixmap.cc
@@ -14,6 +14,7 @@ (static_cast<uint32_t>(c) << 16) | (static_cast<uint32_t>(d) << 24)) #define DRM_FORMAT_R8 FOURCC('R', '8', ' ', ' ') +#define DRM_FORMAT_R16 FOURCC('R', '1', '6', ' ') #define DRM_FORMAT_GR88 FOURCC('G', 'R', '8', '8') #define DRM_FORMAT_RGB565 FOURCC('R', 'G', '1', '6') #define DRM_FORMAT_ARGB8888 FOURCC('A', 'R', '2', '4') @@ -42,6 +43,8 @@ return format == gfx::BufferFormat::BGRA_8888; case GL_RED_EXT: return format == gfx::BufferFormat::R_8; + case GL_R16_EXT: + return format == gfx::BufferFormat::R_16; case GL_RG_EXT: return format == gfx::BufferFormat::RG_88; default: @@ -52,6 +55,7 @@ bool ValidFormat(gfx::BufferFormat format) { switch (format) { case gfx::BufferFormat::R_8: + case gfx::BufferFormat::R_16: case gfx::BufferFormat::RG_88: case gfx::BufferFormat::BGR_565: case gfx::BufferFormat::RGBA_8888: @@ -80,6 +84,8 @@ switch (format) { case gfx::BufferFormat::R_8: return DRM_FORMAT_R8; + case gfx::BufferFormat::R_16: + return DRM_FORMAT_R16; case gfx::BufferFormat::RG_88: return DRM_FORMAT_GR88; case gfx::BufferFormat::BGR_565: @@ -250,6 +256,8 @@ switch (format) { case gfx::BufferFormat::R_8: return GL_RED_EXT; + case gfx::BufferFormat::R_16: + return GL_R16_EXT; case gfx::BufferFormat::RG_88: return GL_RG_EXT; case gfx::BufferFormat::BGR_565:
diff --git a/ui/gl/test/gl_image_test_support.cc b/ui/gl/test/gl_image_test_support.cc index b77b2fd9..abd8aa2f 100644 --- a/ui/gl/test/gl_image_test_support.cc +++ b/ui/gl/test/gl_image_test_support.cc
@@ -60,6 +60,15 @@ memset(&data[y * stride], color[0], width); } return; + case gfx::BufferFormat::R_16: + DCHECK_EQ(0, plane); + for (int y = 0; y < height; ++y) { + uint16_t* row = reinterpret_cast<uint16_t*>(data + y * stride); + for (int x = 0; x < width; ++x) { + row[x] = static_cast<uint16_t>(color[0] << 8); + } + } + return; case gfx::BufferFormat::BGR_565: DCHECK_EQ(0, plane); for (int y = 0; y < height; ++y) {
diff --git a/ui/message_center/views/message_view.cc b/ui/message_center/views/message_view.cc index ac2dc30..ed06b3f 100644 --- a/ui/message_center/views/message_view.cc +++ b/ui/message_center/views/message_view.cc
@@ -16,6 +16,7 @@ #include "ui/message_center/message_center.h" #include "ui/message_center/message_center_style.h" #include "ui/message_center/views/message_center_controller.h" +#include "ui/strings/grit/ui_strings.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/button/image_button.h" @@ -114,6 +115,10 @@ void MessageView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_BUTTON; + node_data->AddStringAttribute( + ui::AX_ATTR_ROLE_DESCRIPTION, + l10n_util::GetStringUTF8( + IDS_MESSAGE_NOTIFICATION_SETTINGS_BUTTON_ACCESSIBLE_NAME)); node_data->SetName(accessible_name_); }
diff --git a/ui/ozone/platform/drm/common/drm_util.cc b/ui/ozone/platform/drm/common/drm_util.cc index c70f4d8..9713037 100644 --- a/ui/ozone/platform/drm/common/drm_util.cc +++ b/ui/ozone/platform/drm/common/drm_util.cc
@@ -20,6 +20,11 @@ #include "ui/display/util/edid_parser.h" #include "ui/ozone/common/display_snapshot_proxy.h" +#if !defined(DRM_FORMAT_R16) +// TODO(riju): crbug.com/733703 +#define DRM_FORMAT_R16 fourcc_code('R', '1', '6', ' ') +#endif + namespace ui { namespace { @@ -434,6 +439,8 @@ switch (format) { case gfx::BufferFormat::R_8: return DRM_FORMAT_R8; + case gfx::BufferFormat::R_16: + return DRM_FORMAT_R16; case gfx::BufferFormat::RG_88: return DRM_FORMAT_GR88; case gfx::BufferFormat::RGBA_8888:
diff --git a/ui/strings/ui_strings.grd b/ui/strings/ui_strings.grd index 344a686..78f9fe7 100644 --- a/ui/strings/ui_strings.grd +++ b/ui/strings/ui_strings.grd
@@ -604,6 +604,9 @@ <message name="IDS_MESSAGE_CENTER_ACCESSIBLE_NAME" desc="The accessible name for the Notification Center window."> Notification Center </message> + <message name="IDS_MESSAGE_CENTER_NOTIFICATION_ACCESSIBLE_NAME" desc="The accessible name for a single notification."> + Notification + </message> <message name="IDS_MESSAGE_CENTER_NOTIFIER_DISABLE" desc="The menu entry for disabling a notifier from a notification."> Disable notifications from <ph name="notifier_name">$1<ex>Notification Galore!</ex></ph> </message>
diff --git a/ui/views/controls/combobox/combobox.cc b/ui/views/controls/combobox/combobox.cc index c948d755..615318fe 100644 --- a/ui/views/controls/combobox/combobox.cc +++ b/ui/views/controls/combobox/combobox.cc
@@ -751,7 +751,11 @@ } void Combobox::GetAccessibleNodeData(ui::AXNodeData* node_data) { - node_data->role = ui::AX_ROLE_COMBO_BOX; + // AX_ROLE_COMBO_BOX is for UI elements with a dropdown and an editable text + // field, which views::Combobox does not have. Use AX_ROLE_POP_UP_BUTTON to + // match an HTML <select> element. + node_data->role = ui::AX_ROLE_POP_UP_BUTTON; + node_data->SetName(accessible_name_); node_data->SetValue(model_->GetItemAt(selected_index_)); if (enabled()) {